
    %	&h}                    :   d dl Z d dlmZmZmZmZmZm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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# dd
l$m%Z% ddl&m'Z' ddl(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z>m?Z? ddl@mAZA ddlBmCZCmDZDmEZEmFZFmGZGmHZH ddlImJZJ ddlKmLZL  e4j                  eN      ZO e9       r
d dlPZPd dlPmQZQ d ZR G d deA      ZS G d de      ZT G d deH      ZU G d d eQj                        ZW G d! d"eQj                        ZX G d# d$eQj                        ZYd% ZZ G d& d'e      Z[ G d( d)e)d*+      Z\ G d, d-e*      Z] G d. d/eE      Z^ G d0 d1eQj                        Z_ G d2 d3eQj                        Z` G d4 d5eQj                        Za G d6 d7eC      Zb G d8 d9e'      Zc G d: d;eG      Zd G d< d=eF      Ze G d> d?eceD      Zf G d@ dAeJ      ZgdBZhdCZi e1dDei       G dE dFede             Zjg dGZky)H    N)DictIterableListOptionalTupleUnion   )ACT2FN)PretrainedConfig)GenerationMixin)BaseImageProcessorBatchFeatureselect_best_resolution)PaddingModeconvert_to_rgbpadresizeto_channel_dimension_format)	ChannelDimension
ImageInputPILImageResamplingget_image_sizeinfer_channel_dimension_formatmake_flat_list_of_imagesto_numpy_arrayvalid_imagesvalidate_preprocess_arguments)CausalLMOutputWithPast)PreTrainedModel)ProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput)
TensorTypeadd_start_docstrings%add_start_docstrings_to_model_forwardcan_return_tupleloggingreplace_return_docstrings)deprecate_kwarg)is_torch_available   )CONFIG_MAPPING
AutoConfig	AutoModelAutoModelForCausalLMAutoTokenizer)LlamaConfig)LlamaDecoderLayerLlamaForCausalLMLlamaMLP
LlamaModelLlamaPreTrainedModelLlamaRMSNorm)LlavaCausalLMOutputWithPast)divide_to_patches)nnc                    | 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                {/var/www/pru.catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/aria/modular_aria.pysequential_experts_gemmr[   J   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            	       H     e Zd ZdZdZdZ	 	 	 	 	 d	dedededef fdZ xZS )
AriaTextConfiga>  
    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 checkout [this
            paper](https://arxiv.org/pdf/2305.13245.pdf). 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_theta (`float`, *optional*, defaults to 10000.0):
            The base period of the RoPE embeddings.
        rope_scaling (`Dict`, *optional*):
            Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
            and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
            accordingly.
            Expected contents:
                `rope_type` (`str`):
                    The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
                    'llama3'], with 'default' being the original RoPE implementation.
                `factor` (`float`, *optional*):
                    Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
                    most scaling types, a `factor` of x will enable the model to handle sequences of length x *
                    original maximum pre-trained length.
                `original_max_position_embeddings` (`int`, *optional*):
                    Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
                    pretraining.
                `attention_factor` (`float`, *optional*):
                    Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
                    computation. If unspecified, it defaults to value recommended by the implementation, using the
                    `factor` field to infer the suggested value.
                `beta_fast` (`float`, *optional*):
                    Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
                    ramp function. If unspecified, it defaults to 32.
                `beta_slow` (`float`, *optional*):
                    Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
                    ramp function. If unspecified, it defaults to 1.
                `short_factor` (`List[float]`, *optional*):
                    Only used with 'longrope'. The scaling factor to be applied to short contexts (<
                    `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
                    size divided by the number of attention heads divided by 2
                `long_factor` (`List[float]`, *optional*):
                    Only used with 'longrope'. The scaling factor to be applied to long contexts (<
                    `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
                    size divided by the number of attention heads divided by 2
                `low_freq_factor` (`float`, *optional*):
                    Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
                `high_freq_factor` (`float`, *optional*):
                    Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
        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intermediate_sizemoe_num_expertsmoe_topkmoe_num_shared_expertsc                 `    t        |   dd|i| || _        || _        || _        || _        y )Npad_token_id )super__init__ra   rb   rc   rd   )selfra   rb   rc   rd   rf   super_kwargs	__class__s          rZ   ri   zAriaTextConfig.__init__   s9     	ClClC!2. &<#r\   )i      r-   r-   r-   )	__name__
__module____qualname____doc__
model_typebase_config_keyintri   __classcell__rl   s   @rZ   r^   r^   i   sW    hT J#O "& &'== = 	=
 !$= =r\   r^   c                   T     e Zd ZdZdZeedZ	 	 	 	 	 	 d
dedede	dede
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.

    Attributes:
        model_type (`str`):
            Type of the model, set to `"aria"`.
        image_token_index (`int`):
            Index used to represent image tokens.
        projector_patch_to_query_dict (`dict`):
            Mapping of patch sizes to query dimensions.
        vision_config (`AriaVisionConfig`):
            Configuration for the vision component.
        text_config (`AriaTextConfig`):
            Configuration for the text component.
    aria)r`   vision_configvision_feature_layerr`   projector_patch_to_query_dictimage_token_indexinitializer_rangec                    || _         |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i | y c c}	}w )N      )i  i$  idefics3_visionrr   rg   )r}   itemsrt   r|   maxvalues'max_value_projector_patch_to_query_dictr{   
isinstancedictr.   rz   r~   r^   r`   rh   ri   )rj   rz   r{   r`   r|   r}   r~   kwargskvrl   s             rZ   ri   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"' .ps   D)Nr>   NN	   g{Gz?)rn   ro   rp   rq   rr   r^   r/   sub_configsrt   r   floatri   ru   rv   s   @rZ   rx   rx      sj    "H J"0:NK $&&*.2!"#'&# "&# $	&#
 (,&# &# !&# &#r\   rx   c                       e Zd Zy)AriaTextRMSNormNrn   ro   rp   rg   r\   rZ   r   r   8      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)rh   ri   r<   Linear	linear_in
linear_outr
   act)rj   in_featureshidden_features
output_dimrl   s       rZ   ri   zAriaProjectorMLP.__init__I  sB    ;eL))OZeL*%r\   c                 h    | j                  | j                  |            }| j                  |      }|S N)r   r   r   )rj   hidden_statess     rZ   forwardzAriaProjectorMLP.forwardO  s-    !>?6r\   rn   ro   rp   rq   ri   r   ru   rv   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)rh   ri   rz   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)rj   r   r   r   r   rl   s        rZ   ri   zAriaCrossAttention.__init__^  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   )	rj   key_value_statesr   r   querykeyvalueattn_output_s	            rZ   r   zAriaCrossAttention.forwardo  s      DOOM:;--.>?kk*+,-,,UC),TQll4;;{#;<r\   )r   r   )	rn   ro   rp   rq   rx   r   ri   r   ru   rv   s   @rZ   r   r   U  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ej                     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   )rh   ri   r|   patch_to_query_dictrz   r   r   r   r   kv_dimr`   r   r   r<   	ParameterrF   rG   r   r   r   
cross_attnr   r   r   feed_forwardrj   r   rl   s     rZ   ri   zAriaProjector.__init__  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\   r   r   c                 P   |j                   d   |j                   d   }}|| j                  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   keysKeyErrorr   	unsqueezerepeatrepeat_interleaver   expandsizer   r   r   )	rj   r   r   
batch_sizenum_patches	query_numqueriesattention_outrY   s	            rZ   r   zAriaProjector.forward  s?    #3"8"8";=M=S=STU=VK
d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   )rn   ro   rp   rq   rx   ri   rF   Tensorr   r   ru   rv   s   @rZ   r   r     s7    ff( %,,AW r\   r   c                     t        | |      \  }}|\  }}||z  }||z  }||k  r(|}	t        t        j                  ||z        |      }
|
|	fS |}
t        t        j                  ||z        |      }	|
|	fS )Nchannel_dim)r   minmathceil)imagetarget_resolutioninput_data_formatoriginal_heightoriginal_widthtarget_heighttarget_widthscale_wscale_h	new_width
new_heights              rZ   _get_patch_output_sizer     s    &4UHY&Z#O^"3M<^+Go-G 	?W#<=}M

 y   #
		.7":;\J	y  r\   c                   2    e Zd ZdZg dZddddddddej                  f	dee   d	ee   d
e	de	de
eee	e	f         de
e   de
e   de
e   def fdZdddddddddej                  dfdeeee   f   de
eeee   f      d	e
eeee   f      d
e
e	   de
e	   de
e   de
e   de
e   dede
eeef      de
e   de
eeef      fdZdej,                  dededej,                  fdZdej,                  dededej,                  fdZej6                  dddfdej8                  dee	ee	e	f   eee	e	f      f   ded eeee   f   de
eeef      de
eeef      dej8                  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 xZ S )%AriaImageProcessora  
    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_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  FT
image_mean	image_stdmax_image_sizemin_image_sizesplit_resolutionssplit_imagedo_convert_rgb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   rm   )r-   r   )r-   r	   )r-   r-   )r-   rD   )r	   rD   )r	   r-   )r   rD   )r   r-   )r   rD   )r   rD   )r  rD   )rm   rD   r     rD   rg   )rh   ri   r   r   r   r   r   r   r   r   r   )rj   r   r   r   r   r   r   r   r   r   r   elrl   s               rZ   ri   zAriaImageProcessor.__init__  s     	"6"(J'I,,$"&$ !yFW X"Q%#+r!us{!; X X!2,( 	 !Ys   
B ptimagesreturn_tensorsdata_formatr   c           	      z   ||n| j                   }||n| j                  }||n| j                  }||n| j                  }||n| j                  }||n| j
                  }||n| j                  }|	|	n| j                  }	|dvrt        d      t        |      }t        |      st        d      t        ||||	       |r|D cg c]  }t        |       }}|D cg c]  }t        |       }}|t        |d         }g }g }d}|D ]j  }|r"| j                  || j                   ||	||      }n|g}|t#        |      |kD  rt#        |      }|D ]  }t%        |      \  }}|t'        ||      z  }||k\  rt'        t)        ||z        |      |f}n|t'        t)        ||z        |      f}t+        |||	||      }||d   z
  ||d	   z
  }}t-        |d|fd|ff||      }t/        j0                  ||ft2        
      }d	|d|d   d|d	   f<   |j5                  |       |r>| j7                  |dz  | j                   | j                  ||      }|t9        |||      n|}|j5                  |       " m t;        t/        j<                  |d      t/        j<                  |d      |d|
      S c c}w c c}w )a!  
        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_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 980zkInvalid image type. Must be of type PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or jax.ndarray.)r   r   r   r   r   )r  r   )r   r  r   rD   )r@   g     o@)axisr   )datatensor_type)r   r   r   r   r   r   r   r   
ValueErrorr   r   r   r   r   r   get_image_patchesr   lenr   r   rt   r   r   nprG   boolappend	normalizer   r   stack)rj   r  r   r   r   r   r   r   r   r   r  r  r   r   r   pixel_masksr   crop_images
crop_imagehwscalenew_sizecrop_image_resizedpadding_bottompadding_rightcrop_image_paddedr   s                               rZ   
preprocesszAriaImageProcessor.preprocess  sP   F $.#9Zt
!*!6IDNN	+9+E4K^K^+9+E4K^K^%0%<k$BRBR+9+E4K^K^'3'?|TEVEV'38+GHH)&1F#: 
 	&%!		
 9?@nU+@F@ 6<<E.'<<$ >vay I	 ;	7E"44**" 1&7 5   %g C$4y$@,	) ,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"":.(,)E1$5*; )7 )% '2 44E{Tef. & ##$56Y,7;	7x  "A > hh{;&
 '
 	
S A =s   J3J8r   r   returnc                 H    t        |||      \  }}t        |||f||      }|S )aC  
        Resizes an image to a target resolution while maintaining aspect ratio.

        Args:
            image (np.array):
                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.array: The resized and padded image.
        r   r   )r   r   )rj   r   r   r   r   r   r   resized_images           rZ   _resize_for_patchingz'AriaImageProcessor._resize_for_patching  s7    & !7u>OQb c
I uz9&=duvr\   c                     |\  }}t        |||      \  }}||z
  dz  }||z
  dz  }	| j                  ||	|	f||ff      }
|
S )zU
        Pad an image to a target resolution while maintaining aspect ratio.
        r-   )padding)r   r   )rj   r   r   r   r   r   r   r   paste_xpaste_ypadded_images              rZ   _pad_for_patchingz$AriaImageProcessor._pad_for_patching  sh     '8#| 6u>OQb c
I)+1 :-!3xx'0BWgDV/WxXr\           r'  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)r-  r.  )r   rt   r  r   r   r   CONSTANTREFLECT	REPLICATE	SYMMETRICr  r   )rj   r   r'  r-  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 )aY  
        Process an image with variable resolutions by dividing it into patches.

        Args:
            image (`np.array`):
                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.array]`: A list of NumPy arrays containing the processed image patches.
        z6grid_pinpoints must be a list of possible resolutions.r   r#  )r   )r:  r   )r   input_channel_dim)	r   list	TypeErrorr   r   r%  r+  r;   r   )rj   r   r9  r:  r   r  r   possible_resolutions
image_sizebest_resolutionr$  r*  patchespatchs                 rZ   r  z$AriaImageProcessor.get_image_patches7  s    : .$/TUU-#E7HI
0=QR11?XIZ 2 
 --m_`q-r#LZ[lm
 !
 (;Zkl
 
 	
s   2B)!rn   ro   rp   rq   model_input_namesr   BICUBICr   r   rt   r   r   r  ri   r   FIRSTr   r   strr%   r   r  arraytupler%  r+  r   r4  ndarrayr   r   r  ru   rv   s   @rZ   r   r     sP   2 D #'!%!!=A&+)-'+'9'A'A!K! ;! 	!
 ! $DsCx$9:! d^! !! tn! %!F ;?9=(,(,&*)-'+'+;?2B2H2HDHo
j$z"223o
 U5$u+#567o
 E%e"456	o

 !o
 !o
 d^o
 !o
 tno
 %o
 !sJ!78o
 ./o
 $E#/?*?$@Ao
bXX27Vf	4XX27L\	( (009<>BDH@zz@ sE#s(OXeCHo-FFG@ 	@
 uhuo56@ eC)9$9:;@ $E#/?*?$@A@ 
@D0xx0 U38_-0 	0
 %0 &0 ,0 
bhh0r\   r   c                   6    e Zd Zddidddej                  dZy)AriaProcessorKwargsr'  Fr   )r   r   )text_kwargsimages_kwargsr  N)rn   ro   rp   r%   PYTORCH	_defaultsrg   r\   rZ   rL  rL  j  s-     u
 " 
 %,,	Ir\   rL  F)totalc                        e Zd ZdZddgZddgZdZdZ	 	 	 	 ddee	e
f   dee
   deeeeef   ef      f fdZ	 	 	 dd	eeeee   ee   f   d
ee   dee   defdZd Zd Zed        Z xZS )AriaProcessora  
    AriaProcessor is a processor for the Aria model which wraps the Aria image preprocessor and the LLama slow tokenizer.

    Args:
        image_processor (`AriaImageProcessor`, *optional*):
            The AriaImageProcessor to use for image preprocessing.
        tokenizer (`PreTrainedTokenizerBase`, *optional*):
            An instance of [`PreTrainedTokenizerBase`]. This should correspond with the model's text model. The tokenizer is a required input.
        chat_template (`str`, *optional*):
            A Jinja template which will be used to convert lists of messages in a chat into a tokenizable string.
        size_conversion (`Dict`, *optional*):
            A dictionary indicating size conversions for images.
    image_processor	tokenizerchat_templatesize_conversionr   r2   c                     |ddd}|j                         D ci c]  \  }}t        |      | c}}| _        ||j                  |j                  |_        t
        |   |||       y c c}}w )Nr   r   r	  )rV  )r   rt   rW  	pad_token	unk_tokenrh   ri   )rj   rT  rU  rV  rW  r   r   rl   s          rZ   ri   zAriaProcessor.__init__  sv     "$'c2O6E6K6K6MNdaA	N Y%8%8%@"+"5"5I)=Q  Os   A-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 }|}	 | j                  |	fi |d   }t!        i ||      S )	a  
        Main method to prepare for the model one or several sequences(s) and image(s).

        Args:
            text (`TextInput`, `PreTokenizedInput`, `List[TextInput]`, `List[PreTokenizedInput]`):
                The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
                (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
                `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
            images (`ImageInput`):
                The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
                tensor. Both channels-first and channels-last formats are supported.


        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 stringsrN  r-   r   rM  )r  )_merge_kwargsrL  rU  init_kwargsr   rG  r=  r  rT  rW  r   rE   popreplaceimage_tokenr  r   )rj   r[  r  audiovideosr   output_kwargsimage_inputstokens_per_imageprompt_stringsr   sampletext_inputss                rZ   __call__zAriaProcessor.__call__  s^   < +**
"&.."<"<
 

 dC 6DD$'
47C0H`aa/4//0L
  $33L4M4M4S4STU4VWN$((58HHI .(B(BDNND^D^ajDjk%%f-.
 L!N$dnn
M*

 !@K!@<!@AAr\   c                 :     | j                   j                  |i |S )z
        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        )rU  batch_decoderj   argsr   s      rZ   rm  zAriaProcessor.batch_decode  s     
 +t~~**D;F;;r\   c                 :     | j                   j                  |i |S )z
        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )rU  decodern  s      rZ   rq  zAriaProcessor.decode  s     
 %t~~$$d5f55r\   c                     | j                   j                  }| j                  j                  }|D cg c]
  }|dk7  s	| }}t        t        j                  ||z               S c c}w )Nr   )rU  rD  rT  r=  r   fromkeys)rj   tokenizer_input_namesimage_processor_input_namesnames       rZ   rD  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#)NNNN)NNN)rn   ro   rp   rq   
attributesvalid_kwargsimage_processor_classtokenizer_classr   r2   rG  r   r   r   rt   ri   r$   r#   r   r   r"   rL  r   rk  rm  rq  propertyrD  ru   rv   s   @rZ   rS  rS  w  s    $[1J#%67L0%O /3'+BFR +,R  }	R
 "$uUCZ'8#'=">?R& (,=BI0$y/4HYCZZ[=B $=B ,-=B 
=B~<6 X Xr\   rS  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   )rh   ri   ra   rd   r   s     rZ   ri   zAriaSharedExpertsMLP.__init__  s)    !'!9!9F<Y<Y!Yr\   )rn   ro   rp   rq   r^   ri   ru   rv   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   )
rh   ri   r   rQ   groupsr<   r   rF   emptyweight)rj   r   rQ   r  rl   s       rZ   ri   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)rj   inputrO   s      rZ   r   zAriaGroupedExpertsGemm.forward  s'     'KK!!#
 	
r\   r   rv   s   @rZ   r  r    s     S
r\   r  c                   2     e Zd ZdZdeddf fdZd Z xZS )AriaGroupedExpertsMLPz
    Grouped MLP module for Mixture of Experts.

    Args:
        config (`AriaTextConfig`):
            Configuration object for the model.
    r   r!  Nc                     t         |           || _        t        |j                  |j
                  dz  |j                        | _        t        |j
                  |j                  |j                        | _        y )Nr-   )	rh   ri   r   r  r   ra   rb   fc1fc2r   s     rZ   ri   zAriaGroupedExpertsMLP.__init__8  sa    )&*<*<f>V>VYZ>Z\b\r\rs)&*B*BFDVDVX^XnXnor\   c                     | j                  ||      }t        j                  |dd      \  }}t        j                  j                  |      |z  }| j                  ||      }|S )a5  
        Forward pass of the Grouped MLP.

        Args:
            permuted_tokens (torch.Tensor): Permuted input tokens.
            tokens_per_expert (torch.Tensor): Number of tokens assigned to each expert.

        Returns:
            torch.Tensor: Output tensor after passing through the MLP.
        r-   r>   rB   )r  rF   chunkr<   
functionalsilur  )rj   permuted_tokensrO   
fc1_output
projectiongate
fc2_outputs          rZ   r   zAriaGroupedExpertsMLP.forward>  s\     XXo/@A
 ;;z1"=
D]]''
3d:
XXj*;<
r\   )rn   ro   rp   rq   r^   ri   r   ru   rv   s   @rZ   r  r  /  s#    p~ p$ pr\   r  c                   `     e Zd ZdZdef fdZdej                  dej                  fdZ xZ	S )AriaTextMoELayerz
    Aria Text Mixture of Experts (MoE) Layer.

    This layer applies a gating mechanism to route input tokens to different experts.

    Args:
        config (`AriaTextConfig`):
            Configuration object for the text component of the model.
    r   c                     t         |           t        j                  |j                  |j
                  d      | _        t        |      | _        t        |      | _
        || _        y NFr   )rh   ri   r<   r   r   rb   routerr  expertsr}  shared_expertsr   r   s     rZ   ri   zAriaTextMoELayer.__init__\  sO    ii 2 2F4J4JQVW,V426:r\   r   r!  c                    |j                   }|j                  d|j                  d            }| j                  |      }t	        j
                  || j                  j                  d      \  }}t        j                  j                  |d      }|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(                  |j                   d   | j                  j                  z  |j                  d      f|j                  |j*                        }|j-                  d||       |j                  d| j                  j                  |j                  d            }||j/                  d      z  j1                  d      j                  |      }| j3                  |j                  |            }||z   S )a.  
        Forward pass of the MoE Layer.

        Args:
            hidden_states (`torch.Tensor`):
                Input tensor of shape (batch_size, sequence_length, hidden_size).

        Returns:
            torch.Tensor: Output tensor after passing through the MoE layer.

        Process:
        1. Route tokens to experts using the router.
        2. Permute tokens based on routing decisions.
        3. Process tokens through experts.
        4. Unpermute and combine expert outputs.
        5. Add shared expert output to the final result.
        r>   rD   )r   rC   rB   r   )binsr   r   r?   )rE   viewr   r  rF   topkr   rc   r<   r  softmaxr@   histcflattentofloat32rb   argsortindex_selectr  rG   rA   index_copy_r   sumr  )rj   r   original_shapelogits
top_logitstop_indicesscoresoriginal_dtyperO   indicesflatten_indicessorted_indicesr  expert_outputunpermuted_tokensrR   shared_expert_outputs                    rZ   r   zAriaTextMoELayer.forwardd  s   $ ',,%**2}/A/A"/EF ]+"'**Vt{{7K7KQR"S
K&&zr&:$**!KK!$$U]]3,,++a/	

 "^
 	  ",,r*7'44Q$++J^J^8^_ _6GH "KK\\!_t{{333]5G5G5JK%% ''

 	%%aG-222t{{7K7K]M_M_`aMbc#f&6&6r&::??A?FKKN[  $22=3E3En3UV,,,r\   )
rn   ro   rp   rq   r^   ri   rF   r   r   ru   rv   s   @rZ   r  r  Q  s/    ~ 9-U\\ 9-ell 9-r\   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                 D    t         |   |        t        |      | _        y r   )rh   ri   r  mlprj   r   r  rl   s      rZ   ri   zAriaTextDecoderLayer.__init__  s    #F+r\   )rn   ro   rp   rq   r^   rt   ri   ru   rv   s   @rZ   r  r    s     
,~ ,# , ,r\   r  c                   :    e Zd ZdZeZdZddgZdZdZ	dZ
dZdZd Zy	)
AriaTextPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
    modelr  r  Tpast_key_valuesFc                    | j                   j                  }t        |t        j                        rY|j
                  j                  j                  d|       |j                  %|j                  j                  j                          y y t        |t        j                        rf|j
                  j                  j                  d|       |j                  2|j
                  j                  |j                     j                          y y t        |t              r(|j
                  j                  j                  d|       y t        |t        j                        rf|j
                  j                  j                  d|       t        |d      r2|j                  %|j                  j                  j                          y y y y )Nr,  meanstdr   )r   r~   r   r<   r   r  r  normal_r   zero_	Embeddingpadding_idxr  Conv2dhasattrrj   moduler  s      rZ   _init_weightsz%AriaTextPreTrainedModel._init_weights  sH   kk++fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . 67MM&&CS&9		*MM&&CS&9vv&6;;+B  &&( ,C& +r\   N)rn   ro   rp   rq   rx   config_classbase_model_prefix_no_split_modulessupports_gradient_checkpointing_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_classr  rg   r\   rZ   r  r    sB     L/1IJ&*#"3"N )r\   r  c                       e Zd ZdZdZd Zy)AriaPreTrainedModelFc                    | j                   j                  }t        |t        j                        rY|j
                  j                  j                  d|       |j                  %|j                  j                  j                          y y t        |t        j                        rf|j
                  j                  j                  d|       |j                  2|j
                  j                  |j                     j                          y y t        |t              r,t        j                  j                  |j                  |       y y )Nr,  r  )r  )r   r~   r   r<   r   r  r  r  r   r  r  r  r   inittrunc_normal_r   r  s      rZ   r  z!AriaPreTrainedModel._init_weights  s    kk++fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> ..GG!!&,,C!8 /r\   N)rn   ro   rp   _supports_static_cache_supports_attention_backendr  rg   r\   rZ   r  r    s    ""'9r\   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)
rh   ri   r<   
ModuleListrK   num_hidden_layersr  layersgradient_checkpointing	post_initr  s      rZ   ri   zAriaTextModel.__init__  s[     mmFKFLdLdFef!&)4f
 ',# gs   A.)rn   ro   rp   r^   ri   ru   rv   s   @rZ   r  r    s    ~  r\   r  c                   2     e Zd ZdZdgZeZdef fdZ xZS )AriaTextForCausalLMa7  
    Aria model for causal language modeling tasks.

    This class extends `LlamaForCausalLM` to incorporate the Mixture of Experts (MoE) approach,
    allowing for more efficient and scalable language modeling.

    Args:
        config (`AriaTextConfig`):
            Configuration object for the model.
    zlm_head.weightr   c                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y r  )
rh   ri   r  r  
vocab_sizer<   r   r   lm_headr  r   s     rZ   ri   zAriaTextForCausalLM.__init__  sU     "6*
 ++yy!3!3V5F5FUS 	r\   )	rn   ro   rp   rq   _tied_weights_keysr^   r  ri   ru   rv   s   @rZ   r  r    s)    	 ++!L~  r\   r  c                       e Zd Zy)AriaCausalLMOutputWithPastNr   rg   r\   rZ   r  r    r   r\   r  a4  
    Args:
        input_ids (`torch.LongTensor`, *optional*):
            Input token IDs.
        pixel_values (`torch.FloatTensor`, *optional*):
            Pixel values of the images.
        pixel_mask (`torch.LongTensor`, *optional*):
            Mask for the pixel values.
        attention_mask (`torch.Tensor`, *optional*):
            Attention mask.
        position_ids (`torch.LongTensor`, *optional*):
            Position IDs.
        past_key_values (`List[torch.FloatTensor]`, *optional*):
            Past key values for efficient processing.
        inputs_embeds (`torch.FloatTensor`, *optional*):
            Input embeddings.
        labels (`torch.LongTensor`, *optional*):
            Labels for computing the language modeling loss.
        use_cache (`bool`, *optional*):
            Whether to use the model's cache mechanism.
        output_attentions (`bool`, *optional*):
            Whether to output attention weights.
        output_hidden_states (`bool`, *optional*):
            Whether to output hidden states.
        return_dict (`bool`, *optional*):
            Whether to return a `ModelOutput` object.
        logits_to_keep (`int` or `torch.Tensor`, *optional*, defaults to 0):
            If an `int`, calculate logits for the last `logits_to_keep` tokens, or all `input_ids` if `0`.
            Otherwise, slice according to the 1D tensor in the sequence length dimension
        cache_position (`torch.LongTensor`, *optional*):
            Cache positions.
        **loss_kwargs:
            Additional keyword arguments for loss calculation.
aG  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config (`AriaConfig`):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zAria 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.c            !           e Zd ZeZdZdZdZdgZdef fdZ	d Z
d Zd Zd Zd	 Zd
 Zd Z	 	 d"dej$                  deej$                     defdZe eddd       ee       eee      	 	 	 	 	 	 	 	 	 	 	 	 	 d#deej8                     deej$                     deej8                     deej:                     deej8                     deeej$                        deej$                     deej8                     dee   dee   dee   de eej:                  f   deej8                     defd                             Z!	 	 	 	 	 	 	 d$d!Z" xZ#S )%AriaForConditionalGenerationFzlanguage_model.lm_head.weightr   c                    t         |   |       t        j                  |j                        | _        t        |      | _        |j                  j                  | _	        t        j                  |j                        | _        | j                  j                  | j                  j                  nd| _        |j                  j                  dk(  | _        | j!                          y )Nr>   flash_attention_2)rh   ri   r0   from_configrz   vision_towerr   multi_modal_projectorr`   r  r1   language_modelr   rf   _attn_implementation_use_flash_attention_2r  r   s     rZ   ri   z%AriaForConditionalGeneration.__init__M  s     %11&2F2FG%26%:" ,,772>>v?Q?QR8<8P8P8\DKK44bd&,&8&8&M&MQd&d#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   )unfoldr  r   r:  r  r  )rj   r   patches_subgrids      rZ   _create_patch_attention_maskz9AriaForConditionalGeneration._create_patch_attention_maskX  s    $++""))44""))44 , 

 *00""))44""))44 1 

  ###1A5;;==r\   c                 6    | j                   j                         S r   )r  get_input_embeddingsrj   s    rZ   r  z1AriaForConditionalGeneration.get_input_embeddingsh  s    ""7799r\   c                 :    | j                   j                  |       y r   )r  set_input_embeddings)rj   r   s     rZ   r  z1AriaForConditionalGeneration.set_input_embeddingsk  s    007r\   c                 6    | j                   j                         S r   )r  get_output_embeddingsr  s    rZ   r  z2AriaForConditionalGeneration.get_output_embeddingsn  s    ""88::r\   c                 :    | j                   j                  |       y r   )r  set_output_embeddings)rj   new_embeddingss     rZ   r  z2AriaForConditionalGeneration.set_output_embeddingsq  s    11.Ar\   c                 :    | j                   j                  |       y r   )r  set_decoder)rj   decoders     rZ   r  z(AriaForConditionalGeneration.set_decodert  s    ''0r\   c                 6    | j                   j                         S r   )r  get_decoderr  s    rZ   r  z(AriaForConditionalGeneration.get_decoderw  s    ""..00r\   r   r   r{   c                     | j                  |      }| j                  ||d      }d }|&|j                  d      }t        j                  |      }|j
                  |   }| j                  ||      }	|	S )NT)patch_attention_maskoutput_hidden_statesrD   r   )r  r  r  rF   logical_notr   r  )
rj   r   r   r{   r  image_outputsimage_attn_maskflattened_maskselected_image_featureimage_featuress
             rZ   get_image_featuresz/AriaForConditionalGeneration.get_image_featuresz  s      $@@L))/CZ^ * 
 +199!<N#//?O!.!<!<=Q!R334JVe3fr\   num_logits_to_keepz4.50logits_to_keep)versionnew_name)output_typer  	input_idsattention_maskposition_idsr  inputs_embedslabels	use_cacheoutput_attentionsr  cache_positionr!  c                    |
|
n| j                   j                  }
||n| j                   j                  }| | j                         |      }||j                  d   dk7  r|| | j                         t        j                  | j                   j                  t
        j                  |j                              k(  }|j                  d      j                  d      d   }nt|| j                   j                  k(  }|j                  d      j                  |      j                  |j                        }|j                  d      j                  d      }| j                  ||| j                   j                        }|j                  d   |j                  d   }}||z  }||k7  rt!        d| d	|       |j                  |j                  |j"                        }|j%                  ||      }| j'                  |||||	|
|||
	      }|j(                  }d}|4 | j*                  d||| j                   j,                  j.                  d|}t1        |||j2                  |j4                  |j6                        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 `Idefics3ForConditionalGeneration`).
                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]`.
        Returns:

        Example:

        ```python
        >>> import requests
        >>> 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", torch_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.
        ```NrD   r?   rB   r   r>   )r   r   r{   z6Image features and image tokens do not match: tokens: z, features )	r  r  r  r  r   r!  r  r  r"  )r  r  r  )lossr  r  r   
attentionsrg   )r   r!  r  r  rE   rF   tensorr}   rI   rA   r  r   	expand_asr  r  r{   r  r@   masked_scatterr  r  loss_functionr`   r  r  r  r   r%  )rj   r  r   r   r  r  r  r  r  r   r!  r  r  r"  loss_kwargsspecial_image_maskn_image_tokensimage_embedsr  n_imagesn_features_per_imagen_image_featuresoutputsr  r$  s                            rZ   r   z$AriaForConditionalGeneration.forward  s   d 2C1N-TXT_T_TqTq$8$D $++JjJj 	  7D557	BM #(;(;A(>!(C %26Qd6O6O6QLL!>!>ejjYfYmYmn7 &" #5!9!9a!9!@!D!D!D!KA!N(DKK,I,II%1%;%;B%?%I%I-%X%[%[\i\p\p%q"".!3!3!3!:!>!>1!>!E!44)%%)[[%E%E 5 N
 .<-A-A!-DnFZFZ[\F]*H'*>>!11 L^L\\ghxgyz  ,..}/C/C]EXEXYN)889K^\M*.*=*=)%+'/!5)) +> 
+
 %4%% f9P9P9[9[_jD *#33!//))
 	
r\   c	           	      p     | j                   j                  |f|||||d|	}
|d   dk(  r
||
d<   ||
d<   |
S )N)r  r  r  r"  r  r   r   r   )r  prepare_inputs_for_generation)rj   r  r  r  r   r   r  r"  r  r   model_inputss              rZ   r3  z:AriaForConditionalGeneration.prepare_inputs_for_generation  si     It**HH
+')))
 
 !! ,8L()3L&r\   )Nr>   )NNNNNNNNNNNr   N)NNNNNNN)$rn   ro   rp   rx   r  r  _supports_flex_attnr  r  ri   r  r  r  r  r  r  r  rF   FloatTensorr   rt   r  r(   r+   r'   ARIA_INPUTS_DOCSTRINGr*   r  
LongTensorr   r   r  r   r   r3  ru   rv   s   @rZ   r  r  ?  s7    L"N9:	z 	> :8;B11 37$&	'' U../ "	& )6DTU*+@A+ET^_ 1548151537=A59-1$(,0/33459J
E,,-J
 u001J
 U--.	J

 !.J
 u//0J
 "$u'8'8"9:J
   1 12J
 ))*J
 D>J
 $D>J
 'tnJ
 c5<</0J
 !!1!12J
  
$!J
 ` B V J
^ r\   r  )	rx   r^   r   rS  r  r  r  r  r  )lr   typingr   r   r   r   r   r   numpyr  activationsr
   configuration_utilsr   
generationr   image_processing_utilsr   r   r   image_transformsr   r   r   r   r   image_utilsr   r   r   r   r   r   r   r   r   modeling_outputsr   modeling_utilsr   processing_utilsr    r!   r"   tokenization_utilsr#   r$   utilsr%   r&   r'   r(   r)   r*   utils.deprecationr+   utils.import_utilsr,   autor.   r/   r0   r1   r2   llama.configuration_llamar3   llama.modeling_llamar4   r5   r6   r7   r8   r9   llava.modeling_llavar:   &llava_next.image_processing_llava_nextr;   
get_loggerrn   loggerrF   r<   r[   r^   rx   r   Moduler   r   r   r   r   rL  rS  r}  r  r  r  r  r  r  r  r  r  r7  ARIA_START_DOCSTRINGr  __all__rg   r\   rZ   <module>rR     s    ? ?  ! 3 ) ^ ^ e e
 
 
 7 - H H  1 4 ] ] 3  ? F 
		H	%>{=[ {=|N#! N#b	l 	ryy 24 4n>BII >B!"I+ IX
*% 
yXN yXxZ8 Z )
RYY )
XBII DL-ryy L-^,, ,$)o )@9. 9$J 13C 2	!< 	! F " A s#6 ssl
r\   