
    qiL                       d dl mZ d dlZd dlZd dlmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZ dd	lmZmZmZmZ dd
lmZmZmZmZmZ ddlmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z<m=Z= ddl>m?Z? ddl@mAZAmBZBmCZCmDZDmEZEmFZFmGZG ddlHmIZImJZJmKZKmLZL ddlMmNZN  e9j                  eP      ZQd ZR G d de?      ZS G d de      ZT G d deG      ZU G d d ej                        ZW G d! d"ej                        ZX G d# d$ej                        ZY G d% d&e      ZZ G d' d(e,d)*      Z[ G d+ d,e.d)*      Z\e7 G d- d.e/             Z] G d/ d0eD      Z^ G d1 d2ej                        Z_ G d3 d4ej                        Z` G d5 d6ej                        Za G d7 d8eA      Zb G d9 d:eB      Zce7 G d; d<e*             Zd G d= d>eF      Ze G d? d@eE      Zf G dA dBedeC      Zg G dC dDeI      Zh G dE dFeL      Zi G dG dHeK      Zj e7dIJ       G dK dLeJ             Zkg dMZly)N    )IterableN)nn   )initialization)ACT2FN)Cache)PreTrainedConfig)BaseImageProcessorBatchFeatureget_patch_output_sizeselect_best_resolution)PaddingModeconvert_to_rgbpadresizeto_channel_dimension_format)
ChannelDimension
ImageInputPILImageResamplingget_image_sizeinfer_channel_dimension_formatis_scaled_imagemake_flat_list_of_imagesto_numpy_arrayvalid_imagesvalidate_preprocess_arguments)FlashAttentionKwargs)BaseModelOutputWithPooling)PreTrainedModel)ImagesKwargsMultiModalDataProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput)
TensorTypeTransformersKwargsauto_docstringcan_return_tuplelogging   )CONFIG_MAPPING
AutoConfigAutoTokenizer)LlamaConfig)LlamaAttentionLlamaDecoderLayerLlamaForCausalLMLlamaMLP
LlamaModelLlamaPreTrainedModelLlamaRMSNorm)LlavaCausalLMOutputWithPastLlavaForConditionalGeneration
LlavaModelLlavaModelOutputWithPast)divide_to_patchesc                    | j                   d   }|j                   d   }t        j                  ||| j                  | j                        }t        j
                  |d      }t        j                  dt        j                  |j                        }t        j                  ||f      }t        |j                   d         D ]2  }||   }	||dz      }
| |	|
 }t        j                  |||         }|||	|
 4 |S )a*  
    Compute the matrix multiplication (GEMM) for each expert sequentially. This approach is computationally inefficient, especially when dealing with a large number of experts.

    Args:
        token_states (torch.Tensor): Input tensor of shape (num_tokens, in_features).
        expert_weights (torch.Tensor): Weight tensor of shape (num_experts, in_features, out_features).
        tokens_per_expert (torch.Tensor): Number of tokens assigned to each expert.

    Returns:
        torch.Tensor: Output tensor of shape (num_tokens, out_features).
    r   dtypedevicedim   )
shapetorchzerosr@   rA   cumsumlongcatrangematmul)token_statesexpert_weightstokens_per_expert
num_tokensout_featuresoutputcumsum_num_tokenszero_tensor
expert_numstartendtokensouts                W/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/aria/modular_aria.pysequential_experts_gemmr[   C   s     ##A&J!''+L[[\9K9KT`TgTghF%6A>++auzz:K:R:RSK		;0A"BCN0034  
!*-
Q/eC(ll6>*#=>uS  M    c            	       \     e Zd ZdZdZdZddddddddZ	 	 	 	 	 ddeded	ed
ef fdZ xZ	S )AriaTextConfigau  
    This class handles the configuration for the text component of the Aria model.
    Instantiating a configuration with the defaults will yield a similar configuration to that of the model of the Aria
    [rhymes-ai/Aria](https://huggingface.co/rhymes-ai/Aria) architecture.
    This class extends the LlamaConfig to include additional parameters specific to the Mixture of Experts (MoE) architecture.

    Args:
        vocab_size (`int`, *optional*, defaults to 32000):
            Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`LlamaModel`]
        hidden_size (`int`, *optional*, defaults to 4096):
            Dimension of the hidden representations.
        intermediate_size (`int`, *optional*, defaults to 4096):
            The size of the MLP representations.
        num_hidden_layers (`int`, *optional*, defaults to 32):
            Number of hidden layers in the Transformer decoder.
        num_attention_heads (`int`, *optional*, defaults to 32):
            Number of attention heads for each attention layer in the Transformer decoder.
        num_key_value_heads (`int`, *optional*):
            This is the number of key_value heads that should be used to implement Grouped Query Attention. If
            `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
            `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
            converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
            by meanpooling all the original heads within that group. For more details, check out [this
            paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
            `num_attention_heads`.
        hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
            The non-linear activation function (function or string) in the decoder.
        max_position_embeddings (`int`, *optional*, defaults to 2048):
            The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
            Llama 2 up to 4096, CodeLlama up to 16384.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        rms_norm_eps (`float`, *optional*, defaults to 1e-06):
            The epsilon used by the rms normalization layers.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models). Only
            relevant if `config.is_decoder=True`.
        pad_token_id (`int`, *optional*, defaults to 2):
            Padding token id.
        bos_token_id (`int`, *optional*, defaults to 1):
            Beginning of stream token id.
        eos_token_id (`int`, *optional*, defaults to 2):
            End of stream token id.
        pretraining_tp (`int`, *optional*, defaults to 1):
            Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
            document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
            understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
            results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
        tie_word_embeddings (`bool`, *optional*, defaults to `False`):
            Whether to tie weight embeddings
        rope_parameters (`RopeParameters`, *optional*):
            Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
            a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
            with longer `max_position_embeddings`.
        attention_bias (`bool`, *optional*, defaults to `False`):
            Whether to use a bias in the query, key, value and output projection layers during self-attention.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        mlp_bias (`bool`, *optional*, defaults to `False`):
            Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
        head_dim (`int`, *optional*):
            The attention head dimension. If None, it will default to hidden_size // num_heads
        moe_num_experts (`int`, *optional*, defaults to 8):
            The number of experts in the MoE layer.
        moe_topk (`int`, *optional*, defaults to 2):
            The number of top experts to route to for each token.
        moe_num_shared_experts (`int`, *optional*, defaults to 2):
            The number of shared experts.
    	aria_texttext_configcolwiserowwise)zlayers.*.self_attn.q_projzlayers.*.self_attn.k_projzlayers.*.self_attn.v_projzlayers.*.self_attn.o_projz%layers.*.mlp.shared_experts.gate_projz#layers.*.mlp.shared_experts.up_projz%layers.*.mlp.shared_experts.down_projintermediate_sizemoe_num_expertsmoe_topkmoe_num_shared_expertsc                 `    || _         || _        || _        || _        t	        |   dd|i| y )Npad_token_id )rc   rd   re   rf   super__init__)selfrc   rd   re   rf   rh   super_kwargs	__class__s          rZ   rk   zAriaTextConfig.__init__   s9     "3. &<#ClClCr\   )i      r,   r,   r,   )
__name__
__module____qualname____doc__
model_typebase_config_keybase_model_tp_planintrk   __classcell__rn   s   @rZ   r^   r^   b   sz    EN J#O%.%.%.%.1:/81: "& &'DD D 	D
 !$D Dr\   r^   c                   z     e Zd ZdZdZddiZeedZ	 	 	 	 	 	 	 dde	ded	e
dz  de	dz  d
edz  dedz  f fdZ xZS )
AriaConfiga  
    This class handles the configuration for both vision and text components of the Aria model,
    as well as additional parameters for image token handling and projector mapping.
    Instantiating a configuration with the defaults will yield a similar configuration to that of the model of the Aria
    [rhymes-ai/Aria](https://huggingface.co/rhymes-ai/Aria) architecture.

    Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PreTrainedConfig`] for more information.

    Args:
        vision_config (`AriaVisionConfig` or `dict`, *optional*):
            Configuration for the vision component.
        vision_feature_layer (`int`, *optional*, defaults to -1):
            The index of the layer to select the vision feature.
        text_config (`AriaTextConfig` or `dict`, *optional*):
            Configuration for the text component.
        projector_patch_to_query_dict (`dict`, *optional*):
            Mapping of patch sizes to query dimensions.
        image_token_index (`int`, *optional*, defaults to 9):
            Index used to represent image tokens.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated normal initializer for initializing all weight matrices.
        tie_word_embeddings (`bool`, *optional*, defaults to `False`):
            Whether to tie weight embeddings
    ariaimage_token_idimage_token_index)r`   vision_configNvision_feature_layerr`   projector_patch_to_query_dictinitializer_rangetie_word_embeddingsc                    || _         |ddd}|j                         D 	
ci c]  \  }	}
t        |	      t        |
       c}
}	| _        t	        | j                  j                               | _        || _        t        |t              rd|d<   t        |d      di |}n|t        d          }|| _        || _        t        |t              rd|v rt        di |}n|
t               }|| _        || _        t!        | D  di | y c c}
}	w )N      )i  i$  idefics3_visionrt   ri   )r~   itemsrw   r   maxvalues'max_value_projector_patch_to_query_dictr   
isinstancedictr-   r   r   r^   r`   r   rj   rk   )rl   r   r   r`   r   r~   r   r   kwargskvrn   s              rZ   rk   zAriaConfig.__init__   s    "3 )0-) JgIlIlIn-oAc!fc!fn-o*7:4;];];d;d;f7g4$8!mT**;M,'*=+FGX-XM"*+<=?M*!2k4(\[-H(7;7K (*K&#6 "6") .ps   D)Nr>   NN	   g{Gz?F)rp   rq   rr   rs   rt   attribute_mapr^   r.   sub_configsrw   r   floatboolrk   rx   ry   s   @rZ   r{   r{      s    4 J-M #1:NK $&&*59()*.+0(# "(# $	(#
 (,d{(# :(# !4<(# "D[(# (#r\   r{   c                       e Zd Zy)AriaTextRMSNormNrp   rq   rr   ri   r\   rZ   r   r         r\   r   c                   (     e Zd ZdZ fdZd Z xZS )AriaProjectorMLPa!  
    Feed-Forward Network module for the Aria Projector.

    Args:
        in_features (`int`):
            Input embedding dimension.
        hidden_features (`int`):
            Hidden dimension of the feed-forward network.
        output_dim (`int`):
            Output dimension.
    c                     t         |           t        j                  ||d      | _        t        j                  ||d      | _        t        d   | _        y )NFbiasgelu_new)rj   rk   r   Linear	linear_in
linear_outr   act)rl   in_featureshidden_features
output_dimrn   s       rZ   rk   zAriaProjectorMLP.__init__#  sB    ;eL))OZeL*%r\   c                 h    | j                  | j                  |            }| j                  |      }|S N)r   r   r   )rl   hidden_statess     rZ   forwardzAriaProjectorMLP.forward)  s-    !>?6r\   rp   rq   rr   rs   rk   r   rx   ry   s   @rZ   r   r     s    
&r\   r   c                   6     e Zd ZdZddedef fdZddZ xZS )AriaCrossAttentionzv
    Aria Cross-Attention module.

    Args:
        config (`AriaConfig`):
            The configuration to use.
    configdropout_ratec                 B   t         |           |j                  j                  }|j                  j                  }|| _        t        j                  ||d      | _        t        j                  ||d      | _	        t        j                  ||d      | _
        t        j                  ||d      | _        t        j                  ||      | _        t        j                  |      | _        t        j                   |      | _        t        j                   |      | _        y )NFr   T)batch_first)rj   rk   r   hidden_sizenum_attention_heads	num_headsr   r   q_projk_projv_projMultiheadAttentionmultihead_attnlinearDropoutdropout	LayerNorm
layer_normlayer_norm_kv)rl   r   r   r   r   rn   s        rZ   rk   zAriaCrossAttention.__init__8  s    **66((<<	"ii[uEii[uEii[uE !33KX\]ii[9zz,/,,{3\\+6r\   c                    | j                  | j                  |            }| j                  |      }| j                  |      }| j	                  |      }| j                  ||||      \  }}| j                  | j                  |            }|S )a  
        Forward pass of the AriaCrossAttention module.

        Args:
            key_value_states (`torch.Tensor`):
                Input tensor for key and value.
            hidden_states (`torch.Tensor`):
                Input tensor for query.
            attn_mask (`torch.Tensor`, *optional*, defaults to None):
                Attention mask.

        Returns:
            torch.Tensor:
                Output tensor after cross-attention.
        	attn_mask)r   r   r   r   r   r   r   r   )	rl   key_value_statesr   r   querykeyvalueattn_output_s	            rZ   r   zAriaCrossAttention.forwardI  s      DOOM:;--.>?kk*+,-,,UC),TQll4;;{#;<r\   )r   r   )	rp   rq   rr   rs   r{   r   rk   r   rx   ry   s   @rZ   r   r   /  s     7z 7 7"r\   r   c                   h     e Zd ZdZdef fdZddej                  dej                  dz  fdZ xZ	S )	AriaProjectora  
    Aria Projector module.

    This module projects vision features into the language model's embedding space, enabling interaction between vision and language components.

    Args:
        config (`AriaConfig`):
            Configuration object for the model.
    r   c                    t         |           |j                  | _        |j                  j
                  | _        |j                  j                  | _        |j                  j
                  | _	        |j                  j
                  | _        |j                  j
                  | _        t        j                  t        j                   |j"                  | j                              | _        t'        |      | _        t        j*                  | j                        | _        t/        | j                  | j                  | j                        | _        y r   )rj   rk   r   patch_to_query_dictr   r   r   r   r   kv_dimr`   r   r   r   	ParameterrF   rG   r   r   r   
cross_attnr   r   r   feed_forwardrl   r   rn   s     rZ   rk   zAriaProjector.__init__q  s     	#)#G#G !//;;--AA**66%11== ,,88\\%++f.\.\^b^n^n"op
,V4,,t'7'78,T-=-=t?S?SUYUdUder\   Nr   r   c                 4   |j                   d   |j                   d   }}|| j                  vr*t        d| d| j                  j                          d      | j                  |   }| j                  d| j                  d      j                  |dd      }|M|j                  | j                  d      }|j                  d      j                  d|j                  d      d      }| j                  |||      }| j                  | j                  |            }|S )	a  
        Forward pass of the Projector module.

        Args:
            key_value_states (`torch.Tensor`):
                Input tensor of shape (batch_size, num_patches, kv_dim).
            attn_mask (`torch.Tensor`, *optional*, default is None):
                Attention mask.

        Returns:
            `torch.Tensor`: Output tensor of shape (batch_size, query_number, output_dim).
        r   rD   zNumber of patches z: not found in patch_to_query_dict amongst possible values .Nr>   r   )rE   r   KeyErrorkeysr   	unsqueezerepeatrepeat_interleaver   expandsizer   r   r   )	rl   r   r   
batch_sizenum_patches	query_numqueriesattention_outrY   s	            rZ   r   zAriaProjector.forward  s6    #3"8"8";=M=S=STU=VK
d666$[M1klp  mE  mE  mJ  mJ  mL  lM  MN  O  ,,[9	**Zi(2215<<ZAN !33DNNAFI!++A.55b',,q/2NI(8'YW >?
r\   r   )
rp   rq   rr   rs   r{   rk   rF   Tensorr   rx   ry   s   @rZ   r   r   f  s8    ff( PTAT r\   r   c                   p    e Zd ZdZg dZddddddddddej                  fd	ee   dz  d
ee   dz  de	de	dee
e	e	f      dz  dedz  dedz  dede	ez  dedz  def fdZdddddddddddej                  dfdeee   z  d	eee   z  dz  d
eee   z  dz  de	dz  de	dz  dedz  dedz  dedz  dedz  dedz  dedz  deez  dz  dedz  deez  dz  fdZdej(                  de
dedej(                  fdZde
de
fd Zdej(                  de
dedej(                  fd!Zej2                  d"ddfdej(                  d#e	e
e	e	f   z  ee
e	e	f      z  d$ed%eee   z  deez  dz  deez  dz  dej(                  fd&Zdej(                  d'ee
e	e	f      d(e	dedededeej(                     fd)Zd-d*e	d+e	fd,Z xZS ).AriaImageProcessoraG  
    A vision processor for the Aria model that handles image preprocessing.
    Initialize the AriaImageProcessor.

    Args:
        image_mean (`list`, *optional*, defaults to [0.5, 0.5, 0.5]):
            Mean values for normalization.
        image_std (`list`, *optional*, defaults to [0.5, 0.5, 0.5]):
            Standard deviation values for normalization.
        max_image_size (`int`, *optional*, defaults to 980):
            Maximum image size.
        min_image_size (`int`, *optional*, defaults to 336):
            Minimum image size.
        split_resolutions (`list`, *optional*, defaults to a list of optimal,resolutions as tuples):
            The optimal resolutions for splitting the image.
        split_image (`bool`, *optional*, defaults to `False`):
            Whether to split the image.
        do_convert_rgb (`bool`, *optional*, defaults to `True`):
            Whether to convert the image to RGB.
        do_rescale (`bool`, *optional*, defaults to `True`):
            Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
            the `preprocess` method.
        rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
            Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
            method.
        do_normalize (`bool`, *optional*, defaults to `True`):
            Whether to normalize the image.
        resample (PILImageResampling, *optional*, defaults to `BICUBIC`):
            The resampling filter to use if resizing the image.
    pixel_values
pixel_mask	num_cropsN  iP  FTgp?
image_mean	image_stdmax_image_sizemin_image_sizesplit_resolutionssplit_imagedo_convert_rgb
do_rescalerescale_factordo_normalizeresamplec                 &   t        |   di | |g d}|g d}|| _        || _        || _        || _        || _        |!g d}|D cg c]  }|d   dz  |d   dz  f }}|| _        || _        || _	        |	| _
        |
| _        || _        y c c}w )N)      ?r   r   ))rD   r,   )rD   r   )rD      )rD      )rD      )rD      )rD   ro   )r,   r   )r,   r   )r,   r,   )r,   rD   )r   rD   )r   r,   )r   rD   )r   r,   )r   rD   )r   rD   )r   rD   )ro   rD   r     rD   ri   )rj   rk   r   r   r   r   r   r   r   r   r   r   r   )rl   r   r   r   r   r   r   r   r   r   r   r   r   elrn   s                 rZ   rk   zAriaImageProcessor.__init__  s     	"6"(J'I,,$"&$ !yFW X"Q%#+r!us{!; X X!2,$,(  !Ys   
Bptimagesreturn_tensorsdata_formatinput_data_formatc           	      P   ||n| j                   }||n| j                  }||n| j                  }||n| j                  }||n| j                  }||n| j
                  }||n| j                  }|	|	n| j                  }	|
|
n| j                  }
||n| j                  }|dvrt        d      | j                  |      }t        |      }t        |      st        d      t        |
|||||	       |r|D cg c]  }t        |       }}|D cg c]  }t!        |       }}|r#t#        |d         rt$        j'                  d       |t)        |d         }g }g }d}|D ]}  }|r"| j+                  || j,                  ||||      }n|g}|t/        |      |kD  rt/        |      }|D ]2  }t1        |      \  }}|t3        ||      z  }||k\  rt3        t5        ||z        |      |f}n|t3        t5        ||z        |      f}t7        |||||	      }||d   z
  ||d
   z
  }}t9        |d|fd|ff||      }t;        j<                  ||ft>              }d
|d|d   d|d
   f<   |jA                  |       |r| jC                  ||	|      }|
r;| jE                  || j                   | j                  ||      }|tG        |||      n|}|jA                  |       5  tI        t;        jJ                  |d      t;        jJ                  |d      |d|      S c c}w c c}w )aI  
        Process a list of images.

        Args:
            images (ImageInput or list of ImageInput):
                The input image or a list of images.
            image_mean (`list`, *optional*, defaults to [0.5, 0.5, 0.5]):
                Mean values for normalization.
            image_std (`list`, *optional*, defaults to [0.5, 0.5, 0.5]):
                Standard deviation values for normalization.
            max_image_size (`int`, *optional*, defaults to `self.max_image_size` (980)):
                Maximum image size.
            min_image_size (`int`, *optional*, defaults to `self.min_image_size` (336)):
                Minimum image size.
            split_image (`bool`, *optional*, defaults to `self.split_image` (False)):
                Whether to split the image.
            do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb` (True)):
                Whether to convert the image to RGB.
            do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
                Whether to rescale the image.
            rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
                Rescale factor to rescale the image by if `do_rescale` is set to `True`.
            do_normalize (`bool`, *optional*, defaults to `self.do_normalize` (True)):
                Whether to normalize the image.
            resample (PILImageResampling, *optional*, defaults to `self.resample` (BICUBIC)):
                The resampling filter to use if resizing the image.
            return_tensors (`str` or `TensorType`, *optional*, defaults to "pt"):
                The type of tensor to return.
            data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format for the output image. Can be one of:
                    - `"channels_first"` or `ChannelDimension.FIRST`:
                        image in (num_channels, height, width) format.
                    - `"channels_last"` or `ChannelDimension.LAST`:
                        image in (height, width, num_channels) format.
                If unset, will use same as the input image.
            input_data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format for the input image. Can be one of:
                    - `"channels_first"` or `ChannelDimension.FIRST`:
                        image in (num_channels, height, width) format.
                    - `"channels_last"` or `ChannelDimension.LAST`:
                        image in (height, width, num_channels) format.
                If unset, will use the inferred format of the input image.

        Returns:
            BatchFeature:
                A BatchFeature object containing:
                - 'pixel_values':
                    Tensor of processed image pixel values.
                - 'pixel_mask':
                    Boolean pixel mask. This mask is a 2D tensor of shape (max_image_size, max_image_size) where:
                    - True (1) values indicate pixels that belong to the original resized image.
                    - False (0) values indicate pixels that are part of the padding.
                  The mask helps distinguish between actual image content and padded areas in subsequent processing steps.
                - 'num_crops':
                    The maximum number of crops across all images.
        Nr   r   z(max_image_size must be either 490 or 980zSInvalid image type. Must be of type PIL.Image.Image, numpy.ndarray, or torch.Tensor)r   r   r   r   r   r   r   zIt looks like you are trying to rescale already rescaled images. If the input images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.)r   r   )r   r   r   rD   )r@   )imagescaler   )axisr   datatensor_type)&r   r   r   r   r   r   r   r   r   r   
ValueErrorfetch_imagesr   r   r   r   r   r   loggerwarning_oncer   get_image_patchesr   lenr   r   rw   r   r   nprG   r   appendrescale	normalizer   r   stack)rl   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   pixel_masksr   crop_images
crop_imagehwr  new_sizecrop_image_resizedpadding_bottompadding_rightcrop_image_paddedr   s                                 rZ   
preprocesszAriaImageProcessor.preprocess  s   R $.#9Zt
!*!6IDNN	+9+E4K^K^+9+E4K^K^%0%<k$BRBR+9+E4K^K^#-#9Zt
+9+E4K^K^'3'?|TEVEV'38+GHH""6*)&1F#rss%%!!)	
 9?@nU+@F@ 6<<E.'<</&)4s
 $ >vay I	 @	7E"44**" 1&7 5   %g C$4y$@,	) 17
%j11&Q26 #CE	NN C^TH .CE	NN0STH%+% 1&7&" 1?!0Ln_ghi_jNj$'&(1m*<= 1&7	%!  XX~~&FdS
;<
=Xa[=-HQK-78"":.(,/~Yj )5 )%  (,)$5*; )7 )% '2 44E{Tef. & ##$56c17@	7B  "A > hh{;&
 '
 	
i A =s   9LL#r  target_resolutionreturnc                 H    t        |||      \  }}t        |||f||      }|S )aG  
        Resizes an image to a target resolution while maintaining aspect ratio.

        Args:
            image (np.ndarray):
                The input image.
            target_resolution (tuple):
                The target resolution (height, width) of the image.
            resample (`PILImageResampling`):
                Resampling filter to use if resizing the image.
            input_data_format (`ChannelDimension` or `str`):
                The channel dimension format of the input image.

        Returns:
            np.ndarray: The resized and padded image.
        r   r   )r   r   )rl   r  r  r   r   
new_height	new_widthresized_images           rZ   _resize_for_patchingz'AriaImageProcessor._resize_for_patching  s7    & !6e=NPa b
I uz9&=duvr\   original_resolutionc                 z    |\  }}|\  }}t        ||z
  d      \  }}t        ||z
  d      \  }	}
|	|	|
z   f|||z   ffS Nr,   )divmod)rl   r&  r  original_heightoriginal_widthtarget_heighttarget_widthpaste_xr_xpaste_yr_ys              rZ   _get_padding_sizez$AriaImageProcessor._get_padding_size  s]    *='&7#|l^;Q?mo=qA3''7S=)AAAr\   c                 j    t        |||      }| j                  ||      }| j                  ||      }|S )zU
        Pad an image to a target resolution while maintaining aspect ratio.
        )padding)r   r2  r   )rl   r  r  r   new_resolutionr4  padded_images          rZ   _pad_for_patchingz$AriaImageProcessor._pad_for_patching  s?     /u6GIZ[((9JKxxwx7r\           r4  modeconstant_valuesc                 ^   t        |t              st        |      dk7  rt        ||||||      S |t	        |      }t
        j                  dt
        j                  dt
        j                  dt
        j                  di}t        j                  ||||   |      }|t        |||      }|S |}|S )a	  
        Pads the `image` with the specified `padding` and `mode`. Padding can be in the (`height`, `width`)
        dimension of in the (`num_patches`) dimension. In the second case an iterable if tuples is expected
        as input.

        Args:
            image (`np.ndarray`):
                The image to pad.
            padding (`int` or `tuple[int, int]` or `Iterable[tuple[int, int]]`):
                Padding to apply to the edges of the height, width axes. Can be one of three formats:
                - `((before_height, after_height), (before_width, after_width))` unique pad widths for each axis.
                - `((before, after),)` yields same before and after pad for height and width.
                - `(pad,)` or int is a shortcut for before = after = pad width for all axes.
            mode (`PaddingMode`):
                The padding mode to use. Can be one of:
                    - `"constant"`: pads with a constant value.
                    - `"reflect"`: pads with the reflection of the vector mirrored on the first and last values of the
                    vector along each axis.
                    - `"replicate"`: pads with the replication of the last value on the edge of the array along each axis.
                    - `"symmetric"`: pads with the reflection of the vector mirrored along the edge of the array.
            constant_values (`float` or `Iterable[float]`, *optional*):
                The value to use for the padding if `mode` is `"constant"`.
            data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format for the output image. Can be one of:
                    - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                    - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                If unset, will use same as the input image.
            input_data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format for the input image. Can be one of:
                    - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                    - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                If unset, will use the inferred format of the input image.

        Returns:
            `np.ndarray`: The padded image.

        r   constantreflectedge	symmetric)r9  r:  )r   rw   r  r   r   r   CONSTANTREFLECT	REPLICATE	SYMMETRICr  r   )rl   r  r4  r9  r:  r   r   padding_mode_mappings           rZ   r   zAriaImageProcessor.pad  s    ` gs#s7|q'8ugt_kK\]]$ >u E   *!!6!!;	 
 ug,@,FXghR]Ri'{<MN 	  pu 	 r\   grid_pinpoints
patch_sizec                     t        |t              st        d      |}t        ||      }t	        ||      }	| j                  ||	||      }
| j                  |
|	|      }t        |||      }|D cg c]  }t        |||       }}|S c c}w )a]  
        Process an image with variable resolutions by dividing it into patches.

        Args:
            image (`np.ndarray`):
                The input image to be processed.
            grid_pinpoints (list[tuple[int, int]]):
                A list of possible resolutions as tuples.
            patch_size (`int`):
                Size of the patches to divide the image into.
            resample (`PILImageResampling`):
                Resampling filter to use if resizing the image.
            data_format (`ChannelDimension` or `str`):
                The channel dimension format for the output image.
            input_data_format (`ChannelDimension` or `str`):
                The channel dimension format of the input image.

        Returns:
            `list[np.ndarray]`: A list of NumPy arrays containing the processed image patches.
        z6grid_pinpoints must be a list of possible resolutions.)channel_dimr!  )r   )rF  r   )rH  input_channel_dim)	r   list	TypeErrorr   r   r%  r7  r<   r   )rl   r  rE  rF  r   r   r   possible_resolutions
image_sizebest_resolutionr$  r6  patchespatchs                 rZ   r  z$AriaImageProcessor.get_image_patches!  s    : .$/TUU-#E7HI
0=QR11?XIZ 2 
 --m_`q-r#LZ[lm
 !
 (;Zkl
 
 	
s   2Bheightwidthc                     |j                  d| j                        }|j                  d| j                        }t        ||f| j                        \  }}|sd}|S ||z  |z  |z  }|S )a  
        A utility that returns number of image patches for a given image size.

        Args:
            height (`int`):
                Height of the input image.
            width (`int`):
                Width of the input image.
            images_kwargs (`dict`, *optional*)
                Any kwargs to override defaults of the image processor.
        Returns:
            `int`: Number of patches per image.
        r   r   rD   )getr   r   r   r   )	rl   rQ  rR  images_kwargsr   r   resized_heightresized_widthr   s	            rZ   get_number_of_image_patchesz.AriaImageProcessor.get_number_of_image_patchesS  s|     $''t7G7GH&**+;T=P=PQ(>PTPfPf(g%*a 1?.0PS`0`dr0rr\   r   )rp   rq   rr   rs   model_input_namesr   BICUBICrJ  r   rw   tupler   rk   r   FIRSTr   strr'   r  r  ndarrayr%  r2  r7  r   r@  r   r   r  rX  rx   ry   s   @rZ   r   r     s   > D *.(,!!:>#(&*&-$('9'A'A"!K$&"! ;%"! 	"!
 "!  c3h047"! D["! t"! "! e"! Tk"! %"!N 2604%)%)#'&*"&'+$(.226/?/E/E;?B
T*--B
 DK'$.B
 4;&-	B

 d
B
 d
B
 D[B
 tB
 4KB
 B
 TkB
 %t+B
 j(4/B
 &,B
 !11D8B
HZZ49Xh	4BU Bu BZZ49N^	" (003659;?@zz@ uS#X&%S/)BB@ 	@
 %0@ ++d2@ !11D8@ 
@D0zz0 U38_-0 	0
 %0 &0 ,0 
bjj	0d# c r\   r   c                   0    e Zd ZU dZeed<   eed<   eed<   y)AriaImagesKwargsa  
    split_image (`bool`, *optional*, defaults to `False`):
        Whether to split large images into multiple crops. When enabled, images exceeding the maximum size are
        divided into overlapping crops that are processed separately and then combined. This allows processing
        of very high-resolution images that exceed the model's input size limits.
    max_image_size (`int`, *optional*, defaults to `980`):
        Maximum image size (in pixels) for a single image crop. Images larger than this will be split into
        multiple crops when `split_image=True`, or resized if splitting is disabled. This parameter controls
        the maximum resolution of individual image patches processed by the model.
    min_image_size (`int`, *optional*):
        Minimum image size (in pixels) for a single image crop. Images smaller than this will be upscaled to
        meet the minimum requirement. If not specified, images are processed at their original size (subject
        to the maximum size constraint).
    r   r   r   N)rp   rq   rr   rs   r   __annotations__rw   ri   r\   rZ   r`  r`  i  s     r\   r`  F)totalc                   D    e Zd ZU eed<   ddddddej                  dZy)AriaProcessorKwargsrU  F)r4  return_mm_token_type_idsr   )r   r   )text_kwargsrU  r   N)rp   rq   rr   r`  ra  r'   PYTORCH	_defaultsri   r\   rZ   rd  rd  ~  s4    ## (-

 " 
 %,,
Ir\   rd  c            
            e Zd Z	 	 	 	 ddeez  dedz  deeez  ef   dz  f fdZe		 dde
ez  ee
   z  ee   z  dedz  dee   d	efd
       ZddZed        Z xZS )AriaProcessorN	tokenizerchat_templatesize_conversionc                 *   |ddd}|j                         D ci c]  \  }}t        |      | c}}| _        |j                  | _        |j                  | _        ||j
                  |j                  |_        t        | !  |||       yc c}}w )zx
        size_conversion (`Dict`, *optional*):
            A dictionary indicating size conversions for images.
        Nr   r   r  )rl  )	r   rw   rm  image_tokenr}   	pad_token	unk_tokenrj   rk   )rl   image_processorrk  rl  rm  r   r   rn   s          rZ   rk   zAriaProcessor.__init__  s     "$'c2O6E6K6K6MNdaA	N$00'66 Y%8%8%@"+"5"5I)=Q  Os   Btextr   r   r  c                     | j                   t        fd| j                  j                  i|}t	        |t
              r|g}n.t	        |t              st	        |d   t
              st        d      | | j                  |fi |d   }| j                  |j                  j                  d      }g }|j                  d      |z  }|D ]P  }	|	j                  | j                  j                  | j                  j                  |z        }	|j                  |	       R ni }|}|d   j                  d	d      }
|d   j                  d
d      } | j                  |fi |d   d	di}| j!                  ||dg       |rUt#        j$                  |d         }t#        j&                  |d         }d||| j(                  k(  <   |j+                         |d<   t-        i |||
      S )a  
        Returns:
            [`BatchFeature`]: A [`BatchFeature`] with the following fields:
            - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
            - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
            `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
            `None`).
            - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
            - **pixel_mask** -- Pixel mask to be fed to a model. Returned when `images` is not `None`.
        tokenizer_init_kwargsr   zAInvalid input text. Please provide a string, or a list of stringsNrU  r,   r   rf  r   re  Fr  )
modalities	input_idsrD   mm_token_type_idsr  )_merge_kwargsrd  rk  init_kwargsr   r]  rJ  rK  rr  rm  r   rE   popreplacero  r  _check_special_mm_tokensr  array
zeros_liker}   tolistr   )rl   rs  r   r   output_kwargsimage_inputstokens_per_imageprompt_stringsr   sampler   re  text_inputs	array_idsrx  s                  rZ   __call__zAriaProcessor.__call__  s   " +**
"&.."<"<
 
 dC 6DD$'
47C0H_``/4//Y-:XYL#33L4M4M4S4STU4VWN$((58HHI .(B(BDNND^D^ajDjk%%f-.
 L!N&}599:JDQ#0#?#C#CD^`e#f $dnn^i}]7Sidhi%%nkwi%X#[!9:I "k+.F GBCi4+>+>>?/@/G/G/IK+,!@K!@<!@n]]r\   c                    i }|t         j                  j                  di       }|j                  |       |j                  dd      xs | j                  j
                  }|D cg c]   } | j                  j                  g || " }}|D cg c]  }| j                  |   |z   }	}|j                  |	|d       t        di |S c c}w c c}w )a  
        Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
        Args:
            image_sizes (`list[list[int]]`, *optional*):
                The input sizes formatted as (height, width) per each image.
        Returns:
            `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
            input modalities, along with other useful data.
        NrU  r   )num_image_tokensnum_image_patchesri   )	rd  rh  rT  updaterr  r   rX  rm  r!   )
rl   image_sizesr   vision_datarU  max_sizerM  r  r   r  s
             rZ   _get_num_multimodal_tokensz(AriaProcessor._get_num_multimodal_tokens  s     "/99==orRM  ($(()94@gDDXDXDgDgH #.! A$$@@\*\m\! ! arrQ\ 4 4X > Lrr4D[lmn,,,!  ss   $%C	Cc                     | j                   j                  }| j                  j                  }|D cg c]
  }|dk7  s	| }}t        t        j                  ||z               S c c}w )Nr   )rk  rY  rr  rJ  r   fromkeys)rl   tokenizer_input_namesimage_processor_input_namesnames       rZ   rY  zAriaProcessor.model_input_names  se     $ @ @&*&:&:&L&L# 9T&kW[_jWjt&k#&kDMM"7:U"UVWW 'ls
   
A#A#)NNNNr   )rp   rq   rr   r/   r]  r   r   rw   rk   r)   r&   r%   rJ  r   r$   rd  r   r  r  propertyrY  rx   ry   s   @rZ   rj  rj    s     )-$(9=R !3&R Tz	R
 eck3./$6R,  %)4^++d9o=EV@WW4^ T!4^ ,-	4^
 
4^ 4^l-4 X Xr\   rj  c                   (     e Zd ZdZdef fdZ xZS )AriaSharedExpertsMLPa/  
    Shared Expert MLP for shared experts.

    Unlike routed experts, shared experts process all tokens without routing.
    This class reconfigures the intermediate size in comparison to the LlamaMLP.

    Args:
        config (`AriaTextConfig`): Configuration object for the Aria language model.
    r   c                 `    t         |   |       |j                  |j                  z  | _        y r   )rj   rk   rc   rf   r   s     rZ   rk   zAriaSharedExpertsMLP.__init__  s)     !'!9!9F<Y<Y!Yr\   )rp   rq   rr   rs   r^   rk   rx   ry   s   @rZ   r  r    s    Z~ Z Zr\   r  c                   (     e Zd ZdZ fdZd Z xZS )AriaGroupedExpertsGemmaP  
    Grouped GEMM (General Matrix Multiplication) module for efficient expert computation.
    This module utilizes the grouped_gemm library (https://github.com/fanshiqing/grouped_gemm)
    for optimized performance. If the grouped_gemm library is not installed, it gracefully
    falls back to a sequential GEMM implementation, which may be slower but ensures
    functionality.

    Args:
        in_features (`int`):
            Number of input features.
        out_features (`int`):
            Number of output features.
        groups (`int`):
            Number of expert groups.
    c                     t         |           || _        || _        || _        t        j                  t        j                  |||            | _	        y r   )
rj   rk   r   rQ   groupsr   r   rF   emptyweight)rl   r   rQ   r  rn   s       rZ   rk   zAriaGroupedExpertsGemm.__init__#  sB    &(ll5;;v{L#QRr\   c                 L    t        || j                  |j                               S )au  
        Perform grouped matrix multiplication.

        Args:
            input (`torch.Tensor`):
                Input tensor of shape (num_tokens, in_features).
            tokens_per_expert (`torch.Tensor`):
                Number of tokens assigned to each expert.

        Returns:
            torch.Tensor: Output tensor of shape (num_tokens, out_features).
        )r[   r  cpu)rl   inputrO   s      rZ   r   zAriaGroupedExpertsGemm.forward*  s'     'KK!!#
 	
r\   r   ry   s   @rZ   r  r    s     S
r\   r  c                   N     e Zd Zdeddf fdZd Zdej                  fdZ xZ	S )AriaExpertsr   r  Nc                     t         |           || _        t        |j                  |j
                  dz  |j                        | _        t        |j
                  |j                  |j                        | _        y r(  )	rj   rk   r   r  r   rc   rd   fc1fc2r   s     rZ   rk   zAriaExperts.__init__?  sa    )&*<*<f>V>VYZ>Z\b\r\rs)&*B*BFDVDVX^XnXnor\   c                     t        j                  || j                  j                  d      \  }}t        j
                  j                  |d      }||fS )NrD   )r   rC   r>   rB   )rF   topkr   re   r   
functionalsoftmax)rl   router_logits
top_logitstop_indicesscoress        rZ   route_tokens_to_expertsz#AriaExperts.route_tokens_to_expertsE  sH    "'**]dkk>R>RXY"Z
K&&zr&:F""r\   c                 B   | j                  |      \  }}|j                  }t        j                  |j	                         j                  t        j                        | j                  j                  d| j                  j                  dz
        j                  |      }|}|j                  d      }t        j                  |      }	|j                  d|	| j                  j                  z        }
| j                  |
|      }t        j                  |dd      \  }}t        j                   j#                  |      |z  }| j%                  ||      }t        j&                  |j(                  d   | j                  j                  z  |j+                  d      f|j                  |j,                        }|j/                  d|	|       |j                  d| j                  j                  |j+                  d            }||j1                  d      z  j3                  d      }|S )Nr   rD   )binsminr   r>   r,   rB   r?   )r  r@   rF   histcflattentofloat32r   rd   viewargsortindex_selectre   r  chunkr   r  silur  rG   rE   r   rA   index_copy_r   sum)rl   r   r  top_k_indextop_k_weightsoriginal_dtyperO   indicesflatten_indicessorted_indicespermuted_tokens
fc1_output
projectiongateexpert_outputunpermuted_tokensrR   s                    rZ   r   zAriaExperts.forwardJ  s   %)%A%A-%P"]$**!KK!$$U]]3,,++a/	

 "^
 	 !,,r*7'44Q$++J^J^8^_XXo/@A
 ;;z1"=
D]]''
3d:
->?!KK  #dkk&:&::M<N<Nq<QR%% ''

 	%%aG-222t{{7K7K]M_M_`aMbc#m&=&=b&AAFF1FMr\   )
rp   rq   rr   r^   rk   r  rF   r   r   rx   ry   s   @rZ   r  r  >  s.    p~ p$ p#
u|| r\   r  c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )AriaTextMoELayerr   c                     t         |           t        j                  |j                  |j
                  d      | _        t        |      | _        t        |      | _
        || _        y NFr   )rj   rk   r   r   r   rd   routerr  expertsr  shared_expertsr   r   s     rZ   rk   zAriaTextMoELayer.__init__k  sO    ii 2 2F4J4JQVW"6*26:r\   r   r  c                 
   |j                   }|j                  d|j                  d            }| j                  |      }| j	                  ||      j                  |      }| j                  |j                  |            }||z   S Nr>   )rE   r  r   r  r  r  )rl   r   original_shaper  r  shared_expert_outputs         rZ   r   zAriaTextMoELayer.forwardr  s{    &,,%**2}/A/A"/EFM2]MBGGW#22=3E3En3UV333r\   )	rp   rq   rr   r^   rk   rF   r   r   rx   ry   s   @rZ   r  r  j  s*    ~ 4U\\ 4ell 4r\   r  c                       e Zd ZdZy)AriaTextAttentionz=Multi-headed attention from 'Attention Is All You Need' paperN)rp   rq   rr   rs   ri   r\   rZ   r  r  {  s    Gr\   r  c                   ,     e Zd ZdZdedef fdZ xZS )AriaTextDecoderLayerag  
    Aria Text Decoder Layer.

    This class defines a single decoder layer in the language model, incorporating self-attention and Mixture of Experts (MoE) feed-forward network.

    Args:
        config (`AriaTextConfig`):
            Configuration object for the text component of the model.
        layer_idx (`int`):
            Index of the layer.
    r   	layer_idxc                 F    t         |   ||       t        |      | _        y r   )rj   rk   r  mlprl   r   r  rn   s      rZ   rk   zAriaTextDecoderLayer.__init__  s    +#F+r\   )rp   rq   rr   rs   r^   rw   rk   rx   ry   s   @rZ   r  r    s     
,~ ,# , ,r\   r  c                        e Zd ZU eed<   dZdZddgZdZdZ	dZ
dZdZeedZ ej"                          fd	       Z xZS )
AriaTextPreTrainedModelr   model)r  rs  r  r  Tpast_key_values)r   
attentionsc                     t         |   |       t        |t              r7t	        j
                  |j                  d| j                  j                         y y )Nr8  )meanstd)	rj   _init_weightsr   r  initnormal_r  r   r   )rl   modulern   s     rZ   r  z%AriaTextPreTrainedModel._init_weights  s>    f%f45LLSdkk6S6ST 6r\   )rp   rq   rr   r^   ra  base_model_prefixinput_modalities_no_split_modulessupports_gradient_checkpointing_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_attention_backendr  r  _can_record_outputsrF   no_gradr  rx   ry   s   @rZ   r  r    sj    (/1IJ&*#"3N"&-'
 U]]_U Ur\   r  c                   R    e Zd ZU eed<   dZdZdZ ej                         d        Z
y)AriaPreTrainedModelr   r  FTc                     t        j                  | |       t        |t              r6t	        j
                  |j                  | j                  j                         y y )N)r  )	r   r  r   r   r  trunc_normal_r   r   r   )rl   r  s     rZ   r  z!AriaPreTrainedModel._init_weights  s?    %%dF3fm,v||1N1NO -r\   N)rp   rq   rr   r{   ra  r  _can_compile_fullgraphr  rF   r  r  ri   r\   rZ   r  r    s6    ""&U]]_P Pr\   r  c                   $     e Zd Zdef fdZ xZS )AriaTextModelr   c           	          t         |   |       t        j                  t	        |j
                        D cg c]  }t        ||       c}      | _        d| _        | j                          y c c}w )NF)
rj   rk   r   
ModuleListrK   num_hidden_layersr  layersgradient_checkpointing	post_initr  s      rZ   rk   zAriaTextModel.__init__  s[     mmFKFLdLdFef!&)4f
 ',# gs   A.)rp   rq   rr   r^   rk   rx   ry   s   @rZ   r  r    s    ~  r\   r  c                   @     e Zd ZddiZdef fdZe fd       Z xZS )AriaTextForCausalLMlm_head.weightzmodel.embed_tokens.weightr   c                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y r  )
rj   rk   r  r  
vocab_sizer   r   r   lm_headr   r   s     rZ   rk   zAriaTextForCausalLM.__init__  sU     "6*
 ++yy!3!3V5F5FUS 	r\   c                 &    t        |   | fi | y r   )rj   r   )rl   rm   rn   s     rZ   r   zAriaTextForCausalLM.forward  s    --r\   )	rp   rq   rr   _tied_weights_keysr^   rk   r)   r   rx   ry   s   @rZ   r  r    s/    *,GH~  . .r\   r  c                       e Zd Zy)AriaCausalLMOutputWithPastNr   ri   r\   rZ   r
  r
    r   r\   r
  c                       e Zd Zy)AriaModelOutputWithPastNr   ri   r\   rZ   r  r    r   r\   r  c                       e Zd Zdef fdZd Z	 	 	 ddej                  dej                  dz  dede	dz  d	e
e   d
eez  fdZ	 	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                   dz  dej                  dz  dedz  dej                  dz  de	dz  dej                  dz  d	e
e   d
eez  fdZ xZS )	AriaModelr   c                 D    t         |   |       t        |      | _        y r   )rj   rk   r   multi_modal_projectorr   s     rZ   rk   zAriaModel.__init__  s     %26%:"r\   c                    |y |j                  d| j                  j                  j                  | j                  j                  j                        }|j                  d| j                  j                  j                  | j                  j                  j                        }|j	                  d      dkD  j                         S )NrD   )	dimensionr   stepr,   )r>   rB   r   )unfoldvision_towerr   rF  r  r   )rl   r   patches_subgrids      rZ   _create_patch_attention_maskz&AriaModel._create_patch_attention_mask  s    $++""))44""))44 , 

 *00""))44""))44 1 

  ###1A5;;==r\   Nr   r   r   output_hidden_statesr   r  c                     | j                  |      } | j                  |f|ddd|}d }|&|j                  d      }	t        j                  |	      }|j
                  |   }
| j                  |
|      |_        |S )NT)patch_attention_maskr  return_dictrD   r   )r  r  r  rF   logical_notr   r  pooler_output)rl   r   r   r   r  r   r  image_outputsimage_attn_maskflattened_maskselected_image_features              rZ   get_image_featureszAriaModel.get_image_features  s      $@@L)))
!5!%	

 
 +199!<N#//?O!.!<!<=Q!R&*&@&@AWcr&@&s#r\   rw  attention_maskposition_idsr  inputs_embeds	use_cachecache_positionc
           
         | | j                         |      }||j                  d   dk7  r| j                  ||| j                  j                  d      j
                  }|j                  |j                  |j                        }| j                  |||      }|j                  ||      } | j                  d||||||	d|
}t        |j                  |r|j                  nd |j                  |j                   |      S d       S )NrD   T)r   r   r   r  )r&  image_features)r$  r%  r  r&  r'  r(  )last_hidden_stater  r   r  image_hidden_statesri   )get_input_embeddingsrE   r#  r   r   r  r  rA   r@   get_placeholder_maskmasked_scatterlanguage_modelr  r+  r  r   r  )rl   rw  r   r   r$  r%  r  r&  r'  r(  r   r*  special_image_maskoutputss                 rZ   r   zAriaModel.forward  sC     7D557	BM #(;(;A(>!(C!44)%%)[[%E%E 	 5 
 m  ,..}/C/C]EXEXYN!%!:!:~ "; " *889K^\M%$%% 
)%+')
 
 '%777@G33d!//))2>2J
 	

 QU
 	
r\   )Nr>   N)	NNNNNNNNN)rp   rq   rr   r{   rk   r  rF   FloatTensorrw   r   r$   r(   r[  r   r#  
LongTensorr   r   r   r  r   rx   ry   s   @rZ   r  r    sl   ;z ;>& 04$&,0'' %%, "	
 #Tk +, 
+	+8 .215.2.204(,26!%26.
##d*.
 ''$..
 $$t+	.

 t+.
 &&-.
 .
 ((4/.
 $;.
 ((4/.
 -..
 
(	(.
r\   r  z
    Aria model for conditional generation tasks.

    This model combines a vision tower, a multi-modal projector, and a language model
    to perform tasks that involve both image and text inputs.
    )custom_introc                       e Zd ZddiZe	 	 ddej                  dej                  dz  dedee	   de
ez  f
d	       Zee	 	 	 	 	 	 	 	 	 	 	 dd
ej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dedz  dej                  dz  dej                  dz  dedz  deej                  z  dej                  dz  dee	   de
ez  fd              Z	 	 	 	 	 	 	 	 d fd	Z xZS )AriaForConditionalGenerationr  z(model.language_model.embed_tokens.weightNr   r   r   r   r  c                 B     | j                   j                  d|||d|S )N)r   r   r   ri   )r  r#  )rl   r   r   r   r   s        rZ   r#  z/AriaForConditionalGeneration.get_image_featuresD  s5     -tzz,, 
%!!5
 	
 	
r\   rw  r$  r%  r  r&  labelsr'  logits_to_keepr(  c                     | j                   d||||||||	|d	|}|d   }t        |
t              rt        |
 d      n|
}| j	                  |dd|ddf         }d}|4 | j
                  d||| j                  j                  j                  d|}t        |||j                  |j                  |j                        S )a{  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or `model.image_token_id` (where `model` is your instance of `AriaForConditionalGeneration`).
            Tokens with indices set to `model.image_token_id` are ignored (masked), the loss is only
            computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

        ```python
        >>> import httpx
        >>> from io import BytesIO
        >>> import torch
        >>> from PIL import Image
        >>> from io import BytesIO

        >>> from transformers import AutoProcessor, AutoModel
        >>> from transformers.image_utils import load_image

        >>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
        >>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
        >>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
        >>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")

        >>> processor = AutoProcessor.from_pretrained("Rhymes-AI/Aria")
        >>> model = AutoModel.from_pretrained("Rhymes-AI/Aria", dtype=torch.bfloat16, device_map="auto")

        >>> # Create inputs
        >>> messages = [
        ...     {
        ...         "role": "user",
        ...         "content": [
        ...             {"type": "image"},
        ...             {"type": "text", "text": "In this image, we can see the city of New York, and more specifically the Statue of Liberty."},
        ...             {"type": "image"},
        ...             {"type": "text", "text": "What can we see in this image?"},
        ...         ]
        ...     },
        ...     {
        ...         "role": "user",
        ...         "content": [
        ...             {"type": "image"},
        ...             {"type": "text", "text": "In which city is that bridge located?"},
        ...         ]
        ...     }
        ... ]

        >>> prompts = [processor.apply_chat_template([message], add_generation_prompt=True) for message in messages]
        >>> images = [[image1, image2], [image3]]
        >>> inputs = processor(text=prompts, images=images, padding=True, return_tensors="pt").to(model.device)

        >>> # Generate
        >>> generated_ids = model.generate(**inputs, max_new_tokens=256)
        >>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)

        >>> print(generated_texts[0])
        Assistant: There are buildings, trees, lights, and water visible in this image.

        >>> print(generated_texts[1])
        Assistant: The bridge is in San Francisco.
        ```)	rw  r   r   r$  r%  r  r&  r'  r(  r   N)logitsr9  r  )lossr<  r  r   r  ri   )r  r   rw   slicer  loss_functionr   r`   r  r
  r  r   r  )rl   rw  r   r   r$  r%  r  r&  r9  r'  r:  r(  r   r2  r   slice_indicesr<  r=  s                     rZ   r   z$AriaForConditionalGeneration.forwardS  s    \ $** 
%!)%+')
 
  
8B>SV8W~ot4]kmA}a,?@A%4%% f9P9P9[9[_eD *#33!//))
 	
r\   c
           
      r    t        |   |f||||||	d|
}|	s|
j                  dd      s
||d<   ||d<   |S )N)r  r&  r$  r(  r:  is_first_iterationr'  Tr   r   )rj   prepare_inputs_for_generationrT  )rl   rw  r  r&  r   r   r$  r(  r:  rB  r   model_inputsrn   s               rZ   rC  z:AriaForConditionalGeneration.prepare_inputs_for_generation  sf     w<	
+')))1	
 	
 VZZT%B
 ,8L()3L&r\   r  )NNNNNNNNNr   N)NNNNNNNF)rp   rq   rr   r  r)   rF   r3  rw   r$   r(   r[  r   r#  r*   r4  r   r   r   r
  r   rC  rx   ry   s   @rZ   r7  r7  9  s    +,VW 04$&	
''
 %%,
 "	

 +,
 
+	+
 
  .215.2.204(,26*.!%-.26j
##d*j
 ''$.j
 $$t+	j

 t+j
 &&-j
 j
 ((4/j
   4'j
 $;j
 ell*j
 ((4/j
 +,j
 
+	+j
  j
^     r\   r7  )
r{   r^   r   rj  r7  r  r  r  r  r  )mcollections.abcr   numpyr  rF   r    r   r  activationsr   cache_utilsr   configuration_utilsr	   image_processing_utilsr
   r   r   r   image_transformsr   r   r   r   r   image_utilsr   r   r   r   r   r   r   r   r   r   modeling_flash_attention_utilsr   modeling_outputsr   modeling_utilsr   processing_utilsr    r!   r"   r#   r$   tokenization_pythonr%   r&   utilsr'   r(   r)   r*   r+   autor-   r.   r/   llama.configuration_llamar0   llama.modeling_llamar1   r2   r3   r4   r5   r6   r7   llava.modeling_llavar8   r9   r:   r;   &llava_next.image_processing_llava_nextr<   
get_loggerrp   r
  r[   r^   r{   r   Moduler   r   r   r   r`  rd  rj  r  r  r  r  r  r  r  r  r  r  r
  r  r  r7  __all__ri   r\   rZ   <module>r\     sB   %    & !   3 u u e e   C : - f f ? ^ ^ < < 3    G 
		H	%>aD[ aDHI#! I#X	l 	ryy 24 4n>BII >B+ D|5 **%   pXN pX pXfZ8 Z )
RYY )
X)")) )X4ryy 4"H H,, ,$ Uo U U.
P. 
PJ .13C ."	!< 		6 	]

 ]
@ `#@ ``Fr\   