
    %	&h>                    B   d dl mZ d dlmZ d dlmZmZmZmZm	Z	 ddl
mZ ddl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 ddlmZmZ ddlmZmZ ddl m!Z! ddl"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/m0Z0 ddl1m2Z2m3Z3  e-       r
d dl4Z4d dl4m5Z5  e'       rd dl6m7Z7 ddl8m9Z9  e(jt                  e;      Z<dZ= G d de5j|                        Z? G d de5j|                        Z@ G d de5j|                        ZA G d  d!e5j|                        ZB G d" d#e5j|                        ZCd$ ZD G d% d&e5j|                        ZE G d' d(e5j|                        ZF G d) d*e5j|                        ZGd+ ZHdUd,ZId-e4j                  d.eKd/e4j                  fd0ZL	 dVd1e5j|                  d2e4j                  d3e4j                  d4e4j                  d5ee4j                     d6eMd7eMfd8ZN G d9 d:e5j|                        ZO G d; d<e5j|                        ZP G d= d>e      ZQd?ZR e$d@eR       G dA dBe             ZS G dC dDe5j|                        ZTdEZU e$dFeR       G dG dHeQ             ZV G dI dJee#      ZW G dK dLeQe      ZXe G dM dNe             ZYdOZZdPZ[ e$dQe[       G dR dSeSe             Z\g dTZ]y)W    )	dataclass)partial)CallableListOptionalTupleUnion   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs)BaseModelOutputWithPastCausalLMOutputWithPastModelOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)
LossKwargsadd_start_docstrings%add_start_docstrings_to_model_forwardcan_return_tupleis_torch_flex_attn_availableloggingreplace_return_docstrings)deprecate_kwarg)is_torch_available   )	AutoModelAutoModelForCausalLM   )
AriaConfigAriaTextConfigN)nn)	BlockMask)make_flex_block_causal_maskr(   c                   ,     e Zd Zd fd	Zd Zd Z xZS )AriaTextRMSNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z>
        AriaTextRMSNorm is equivalent to T5LayerNorm
        N)super__init__r)   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      |/var/www/pru.catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/aria/modeling_aria.pyr0   zAriaTextRMSNorm.__init__A   s1     	ll5::k#:; #    c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )Nr#   T)keepdim)	dtypetor2   float32powmeanrsqrtr5   r4   )r6   hidden_statesinput_dtypevariances       r:   forwardzAriaTextRMSNorm.forwardI   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r;   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler4   shaper5   r6   s    r:   
extra_reprzAriaTextRMSNorm.extra_reprP   s*    ))*+6$2G2G1HIIr;   )gư>)__name__
__module____qualname__r0   rH   rM   __classcell__r9   s   @r:   r-   r-   @   s    $;J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)r/   r0   r)   Linear	linear_in
linear_outr   act)r6   in_featureshidden_features
output_dimr9   s       r:   r0   zAriaProjectorMLP.__init__a   sB    ;eL))OZeL*%r;   c                 h    | j                  | j                  |            }| j                  |      }|S N)r\   rZ   r[   )r6   rE   s     r:   rH   zAriaProjectorMLP.forwardg   s-    !>?6r;   rN   rO   rP   __doc__r0   rH   rQ   rR   s   @r:   rT   rT   T   s    
&r;   rT   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 )NFrV   T)batch_first)r/   r0   vision_configr7   num_attention_heads	num_headsr)   rY   q_projk_projv_projMultiheadAttentionmultihead_attnlinearDropoutdropout	LayerNorm
layer_normlayer_norm_kv)r6   rf   rg   r7   rl   r9   s        r:   r0   zAriaCrossAttention.__init__v   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)rm   rv   rw   rn   ro   rq   rt   rr   )	r6   key_value_statesrE   rz   querykeyvalueattn_output_s	            r:   rH   zAriaCrossAttention.forward   s      DOOM:;--.>?kk*+,-,,UC),TQll4;;{#;<r;   )r   ra   )	rN   rO   rP   rc   r'   floatr0   rH   rQ   rR   s   @r:   re   re   m   s     7z 7 7"r;   re   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.
    rf   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 ra   )r/   r0   projector_patch_to_query_dictpatch_to_query_dictrj   r7   r]   rk   rl   kv_dimtext_configr^   r_   r)   r1   r2   zeros'max_value_projector_patch_to_query_dictr|   re   
cross_attnru   rv   rT   feed_forwardr6   rf   r9   s     r:   r0   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{   rz   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   r&   zNumber of patches z: not found in patch_to_query_dict amongst possible values .Nr=   ry   )rK   r   keysKeyErrorr|   	unsqueezerepeatrepeat_interleaverl   expandsizer   r   rv   )	r6   r{   rz   
batch_sizenum_patches	query_numqueriesattention_outouts	            r:   rH   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;   ra   )rN   rO   rP   rc   r'   r0   r2   Tensorr   rH   rQ   rR   s   @r:   r   r      s7    ff( %,,AW r;   r   c                   .     e Zd ZdZdef fdZ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.
    rf   c                     t         |           || _        |j                  | _        |j                  |j
                  z  | _        t        j                  | j                  | j                  |j                        | _	        t        j                  | j                  | j                  |j                        | _
        t        j                  | j                  | j                  |j                        | _        t        |j                     | _        y )NrV   )r/   r0   rf   r7   intermediate_sizemoe_num_shared_expertsr)   rY   mlp_bias	gate_projup_proj	down_projr   
hidden_actact_fnr   s     r:   r0   zAriaSharedExpertsMLP.__init__   s    !--!'!9!9F<Y<Y!Y4#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r;   c                     | j                  | j                  | j                  |            | j                  |      z        }|S ra   )r   r   r   r   )r6   xr   s      r:   rH   zAriaSharedExpertsMLP.forward   s6    NN4;;t~~a/@#ADLLQRO#ST	r;   rN   rO   rP   rc   r(   r0   rH   rQ   rR   s   @r:   r   r      s    0~ 0r;   r   c                    | 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   r=   r?   devicedimr&   )
rK   r2   r   r?   r   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tokensr   s                r:   sequential_experts_gemmr      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  Mr;   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 ra   )
r/   r0   r]   r   groupsr)   r1   r2   emptyr4   )r6   r]   r   r   r9   s       r:   r0   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   r4   cpu)r6   inputr   s      r:   rH   zAriaGroupedExpertsGemm.forward6  s'     'KK!!#
 	
r;   rb   rR   s   @r:   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.
    rf   returnNc                     t         |           || _        t        |j                  |j
                  dz  |j                        | _        t        |j
                  |j                  |j                        | _        y )Nr#   )	r/   r0   rf   r   r7   r   moe_num_expertsfc1fc2r   s     r:   r0   zAriaGroupedExpertsMLP.__init__S  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=   r   )r   r2   chunkr)   
functionalsilur   )r6   permuted_tokensr   
fc1_output
projectiongate
fc2_outputs          r:   rH   zAriaGroupedExpertsMLP.forwardY  s\     XXo/@A
 ;;z1"=
D]]''
3d:
XXj*;<
r;   r   rR   s   @r:   r   r   J  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.
    rf   c                     t         |           t        j                  |j                  |j
                  d      | _        t        |      | _        t        |      | _
        || _        y NFrV   )r/   r0   r)   rY   r7   r   routerr   expertsr   shared_expertsrf   r   s     r:   r0   zAriaTextMoELayer.__init__w  sO    ii 2 2F4J4JQVW,V426:r;   rE   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=   r&   )kr   r   r   )binsminmaxr   )rK   viewr   r   r2   topkrf   moe_topkr)   r   softmaxr?   histcflattenr@   rA   r   argsortindex_selectr   r   r   index_copy_r   sumr   )r6   rE   original_shapelogits
top_logitstop_indicesscoresoriginal_dtyper   indicesflatten_indicessorted_indicesr   expert_outputunpermuted_tokensr   shared_expert_outputs                    r:   rH   zAriaTextMoELayer.forward  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   rc   r(   r0   r2   r   rH   rQ   rR   s   @r:   r   r   l  s/    ~ 9-U\\ 9-ell 9-r;   r   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..Nr=   r#   r   )rK   r2   r   )r   x1x2s      r:   rotate_halfr     sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r;   c                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )r   r   )qr   cossinposition_idsunsqueeze_dimq_embedk_embeds           r:   apply_rotary_pos_embr	    sY    ( --
&C
--
&C3w;q>C/0G3w;q>C/0GGr;   rE   n_repr   c                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r&   N)rK   r   reshape)rE   r
  batchnum_key_value_headsslenhead_dims         r:   	repeat_kvr    so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr;   moduler|   r}   r~   attention_maskscalingrt   c                 T   t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
|#|d d d d d d d |j
                  d   f   }|
|z   }
t        j                  j                  |
dt        j                        j                  |j                        }
t        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr#   r
   r=   )r   r?   )ptrainingr&   )r  num_key_value_groupsr2   r   	transposerK   r)   r   r   rA   r@   r?   rt   r  
contiguous)r  r|   r}   r~   r  r  rt   kwargs
key_statesvalue_statesattn_weightscausal_maskr   s                r:   eager_attention_forwardr!    s    3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#k1==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r;   c                   6    e Zd ZdZdedef fdZ	 	 ddej                  de	ej                  ej                  f   de
ej                     de
e   d	e
ej                     d
ee   de	ej                  e
ej                     e
e	ej                        f   fdZ xZS )AriaTextAttentionz=Multi-headed attention from 'Attention Is All You Need' paperrf   	layer_idxc                 d   t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  |j                  z  | _	        | j                  dz  | _
        |j                  | _        d| _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j                  | j                  z  |j
                  |j                        | _        y )Nr  g      TrV   )r/   r0   rf   r$  getattrr7   rk   r  r  r  r  attention_dropout	is_causalr)   rY   attention_biasrm   rn   ro   o_projr6   rf   r$  r9   s      r:   r0   zAriaTextAttention.__init__  sM   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
r;   rE   position_embeddingsr  past_key_valuecache_positionr  r   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }|\  }}t        |	|
||      \  }	}
|'|||d}|j                  |
|| j                  |      \  }
}t        }| j                  j                  dk7  r^| j                  j                  dk(  r(|j                  dd      rt        j                  d	       nt         | j                  j                     } || |	|
||f| j"                  sd
n| j$                  | j&                  d|\  }} |j(                  g |d j+                         }| j-                  |      }||fS )Nr=   r&   r#   )r  r  r.  eagersdpaoutput_attentionsFz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.        )rt   r  )rK   r  rm   r   r  rn   ro   r	  updater$  r!  rf   _attn_implementationgetloggerwarning_oncer   r  r'  r  r  r  r*  )r6   rE   r,  r  r-  r.  r  input_shapehidden_shapequery_statesr  r  r  r  cache_kwargsattention_interfacer   r  s                     r:   rH   zAriaTextAttention.forward  s    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&S#7jRUWZ#[ j%#&snUL'5'<'<ZW[WeWegs't$J(?;;++w6{{//69fjjI\^c>d##L
 '>dkk>^>^&_#$7	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r;   )NN)rN   rO   rP   rc   r(   intr0   r2   r   r   r   r   
LongTensorr   r   rH   rQ   rR   s   @r:   r#  r#    s    G
~ 
# 
8 +/59/)||/) #5<<#=>/) !.	/)
 !/) !!1!12/) -./) 
u||Xell3XeELL>Q5RR	S/)r;   r#  c                   t    e Zd ZdZdedef fdZ	 	 	 	 	 	 	 ddej                  de	ej                     de	ej                     de	e   d	e	e   d
e	e   de	ej                     de	eej                  ej                  f      dee   deej                   e	eej                   ej                   f      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.
    rf   r$  c                     t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y )N)rf   r$  r8   )r/   r0   r7   r#  	self_attnr   mlpr-   rms_norm_epsinput_layernormpost_attention_layernormr+  s      r:   r0   zAriaTextDecoderLayer.__init__\  sm    !--*&IN#F+.v/A/AvGZGZ[(78J8JPVPcPc(d%r;   rE   r  r  r-  r2  	use_cacher.  r,  r  r   c	                     |}
| j                  |      } | j                  d||||||||d|	\  }}|
|z   }|}
| j                  |      }| j                  |      }|
|z   }|f}|r||fz  }|S )N)rE   r  r  r-  r2  rI  r.  r,   )rG  rD  rH  rE  )r6   rE   r  r  r-  r2  rI  r.  r,  r  residualself_attn_weightsoutputss                r:   rH   zAriaTextDecoderLayer.forwarde  s     !,,]; ,:4>> 
,
')%)/) 3
,
 
,
(( !=0 !55mD/ =0 ")++Gr;   )NNNFFNN)rN   rO   rP   rc   r(   r>  r0   r2   r   r   r?  r   boolr   r   r   FloatTensorrH   rQ   rR   s   @r:   rA  rA  O  s   
e~ e# e 2637*.,1$)59KO(||( !.( u//0	(
 !( $D>( D>( !!1!12( &eELL%,,,F&GH( -.( 
u  (51B1BEDUDU1U+V"WW	X(r;   rA  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.
    modelrA  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 )Nr3  rC   stdrW   )rf   initializer_range
isinstancer)   rY   r4   datanormal_rW   zero_	Embeddingpadding_idxr   Conv2dhasattrr6   r  rW  s      r:   _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   rc   r'   config_classbase_model_prefix_no_split_modulessupports_gradient_checkpointing_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_classrb  rK  r;   r:   rR  rR    sB     L/1IJ&*#"3"N )r;   rR  aM  
    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 ([`AriaTextConfig`]):
            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.
zRThe bare Aria Model outputting raw hidden-states without any specific head on top.c                   F    e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZdZdZd Zy)AriaPreTrainedModelrS  TAriaDecoderLayerrT  Fc                    | 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 )Nr3  rV  )rW  )rf   rX  rY  r)   rY   r4   rZ  r[  rW   r\  r]  r^  r   inittrunc_normal_r|   ra  s      r:   rb  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   r(   rc  rd  rf  re  rg  rh  ri  _supports_flex_attnrj  _supports_quantized_cache_supports_static_cache_supports_attention_backendrb  rK  r;   r:   rl  rl    sU    
 "L&*#+,#4"5!N  $""'9r;   rl  c                   ^     e Zd Zddef fdZ ej                         ed               Z xZ	S )AriaTextRotaryEmbeddingrf   c                    t         |           t        |d      rG|j                  ;|j                  j	                  d|j                  j	                  d            | _        nd| _        |j                  | _        |j                  | _        || _	        t        | j
                     | _        | j                  | j                  |      \  }| _        | j                  d|d       | j                  | _        y )Nrope_scaling	rope_typetypedefaultinv_freqF)
persistent)r/   r0   r`  rx  r6  ry  max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrf   r   rope_init_fnattention_scalingregister_bufferr|  original_inv_freq)r6   rf   r   r|  r9   s       r:   r0   z AriaTextRotaryEmbedding.__init__  s    6>*v/B/B/N#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%r;   c                 b   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        j                  |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   r=   r&   mpsr   F)device_typeenabledr#   r   )r?   )r|  r   r   rK   r@   r   rY  rz  strr2   autocastr  r   r  r  r  r?   )
r6   r   r  inv_freq_expandedposition_ids_expandedr  freqsembr  r  s
             r:   rH   zAriaTextRotaryEmbedding.forward  sV    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfk^^UC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s    BF%%F.ra   )
rN   rO   rP   r(   r0   r2   no_gradr   rH   rQ   rR   s   @r:   rv  rv    s3    /~ /" U]]_<  <r;   rv  a$  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        past_key_values (`Cache`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
zVThe bare AriaText Model outputting raw hidden-states without any specific head on top.c                       e Zd ZdZdef fdZd Zd Ze e	e
      	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     d	ee   d
eej                      dee   dee   dee   deej                     dee   defd              Z	 ddej                  dej                  dej                  d	edef
dZedej                  dededej2                  dej4                  dej                  defd       Z xZS )AriaTextModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`AriaTextDecoderLayer`]

    Args:
        config: AriaTextConfig
    rf   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )NrC  )rf   F)r/   r0   pad_token_idr^  
vocab_sizer)   r]  r7   embed_tokens
ModuleListr   num_hidden_layersrA  layersr-   rF  normrv  
rotary_embgradient_checkpointing	post_initr+  s      r:   r0   zAriaTextModel.__init__R  s     !.. ++LL):):F<N<NPTP`P`ammFKFLdLdFef!&)4f
 $F$6$6F<O<OP	1@&+# 	 gs   Dc                     | j                   S ra   r  rL   s    r:   get_input_embeddingsz"AriaTextModel.get_input_embeddingsb  s       r;   c                     || _         y ra   r  r6   r~   s     r:   set_input_embeddingsz"AriaTextModel.set_input_embeddingse  s
    !r;   	input_idsr  r  rT  inputs_embedsrI  r2  output_hidden_statesr.  flash_attn_kwargsr   c
                 ^   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|d u |d uz  rt	        d      | j
                  r%| j                  r|rt        j                  d       d}t        |t        d       t        f      st	        d      || j                  |      }|r|
t               }|	F||j                         nd}t        j                   |||j"                  d   z   |j$                        }	||	j'                  d      }| j)                  |||	||      }|}| j+                  ||      }|rdnd }|rdnd }| j,                  d | j                   j.                   D ]r  }|r||fz  }| j
                  r:| j                  r.| j1                  t3        |j4                  fi |
|||||||	|	      }n ||f||||||	|d	|
}|d   }|sj||d   fz  }t | j7                  |      }|r||fz  }t9        ||r|nd ||
      S )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FzBThe `past_key_values` should be either a `Cache` object or `None`.r   r&   r   rK  )r  r  r-  r2  rI  r.  r,  )last_hidden_staterT  rE   
attentions)rf   r2  r  rI  
ValueErrorr  r  r7  r8  rY  rz  r   r  r   get_seq_lengthr2   arangerK   r   r   _update_causal_maskr  r  r  _gradient_checkpointing_funcr   __call__r  r   )r6   r  r  r  rT  r  rI  r2  r  r.  r  past_seen_tokensr   rE   r,  all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                      r:   rH   zAriaTextModel.forwardh  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<YZZ&&4==Yj I /DJ+>?abb  --i8M0*nO!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L..M>?L]
 & #oom\J #7BD0d![[)H4;;+H+HI  	6M#!m%55!**t}} $ A AM22H6GH! #%"'
! !.!
!#.!-#2&7'#1(;
! (
! *!,M =#3"55A 	6D 		-0  -!11&+/8Od+%	
 	
r;   input_tensorc           
         | j                   j                  dk(  r||dk(  j                         r|S y | j                   j                  dk(  r7t        |t        j
                        rt        |      }t        |t              r|S ||j                         nd}t        |t              }| j                   j                  dk(  r(|s&|s$t        j                  |||| j                        ry |j                  |j                  }	}|j                  d   }
|r|j!                         }n1t        |t        j
                        r|j                  d   n||
z   dz   }| j#                  ||
|||	||j                  d   	      }| j                   j                  dk(  rQ|O|j                  j$                  d
v r7|s5t	        j&                  |      j(                  }t        j*                  ||      }|S )Nflash_attention_2r3  flex_attentionr   r1  )r  past_key_values_lengthis_trainingr&   r=   )sequence_lengthtarget_lengthr?   r   r.  r   )cudaxpu)rf   r5  anyrY  r2   r   r+   r*   r  r   r   _ignore_causal_mask_sdpar  r?   r   rK   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionrz  finfor   _unmask_unattended)r6   r  r  r.  rT  r2  r  using_static_cacher?   r   r  r  r   	min_dtypes                 r:   r  z!AriaTextModel._update_causal_mask  s    ;;++/BB)~/D.I.I.K%%;;++/??.%,,7!<^!L.)4%%
 @O?Z?99;`a'E ;;++v5>PYj%>>*'7 MM	 $**L,?,?v&,,Q/+??AM nell; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**o=%
 E*..I0CCKQZ[Kr;   r  r  r?   r   r   c                    | | j                         dk(  r| }|S t        j                  |      j                  }	t        j                  ||f|	||      }|dk7  rt        j
                  |d      }|t        j                  ||      |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }
|ddddddd|
f   | ddddddf   j                  |j                        z   }|dk(  }|ddddddd|
f   j                  ||	      |ddddddd|
f<   |S )	a  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to place the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuer?   r   r&   )diagonalr  r=   r   )r   r2   r  r   fulltriur  r  r   clonerK   r@   r   masked_fill)r  r  r  r?   r   r.  r   r  r   r  mask_lengthpadding_masks               r:   r  zCAriaTextModel._prepare_4d_causal_attention_mask_with_cache_position  sy   B %.*<*<*>!*C(K* ' E*..I** -0Ye\bK !##jjqA5<<fEH^H^_acdHeeeK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c )6Aq!\k\12 r;   )	NNNNNNNNN)F)rN   rO   rP   rc   r(   r0   r  r  r   r   ARIA_TEXT_INPUTS_DOCSTRINGr   r2   r?  r   r   rP  rO  r   r   r   rH   r  staticmethodr>  r?   r   r  rQ   rR   s   @r:   r  r  F  s   
~  !" *+EF 151537+/59$(,0/359i
E,,-i
 !.i
 u//0	i

 "%i
   1 12i
 D>i
 $D>i
 'tni
 !!1!12i
 $$89i
 
!i
 G i
b #(DD llD 	D
 D  DL 777 7 {{	7
 7 7 7 7r;   r  c                       e Zd Zy)KwargsForCausalLMN)rN   rO   rP   rK  r;   r:   r  r  V  s    r;   r  c                       e Zd ZdZdgZddiZddgdgfiZeZdef fdZ	d	 Z
d
 Zd Zd Zd Zd Ze eddd       ee       eee      	 	 	 	 	 	 	 	 	 	 	 d!deej2                     deej4                     deej2                     dee   deej8                     deej2                     dee   dee   dee   deej2                     deeej4                  f   de e!   de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.weightlm_headcolwise_reprE   r   rf   c                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y r   )
r/   r0   r  rS  r  r)   rY   r7   r  r  r   s     r:   r0   zAriaTextForCausalLM.__init__j  sU     "6*
 ++yy!3!3V5F5FUS 	r;   c                 .    | j                   j                  S ra   rS  r  rL   s    r:   r  z(AriaTextForCausalLM.get_input_embeddingss  s    zz&&&r;   c                 &    || j                   _        y ra   r  r  s     r:   r  z(AriaTextForCausalLM.set_input_embeddingsv  s    "'

r;   c                     | j                   S ra   r  rL   s    r:   get_output_embeddingsz)AriaTextForCausalLM.get_output_embeddingsy  s    ||r;   c                     || _         y ra   r  r6   new_embeddingss     r:   set_output_embeddingsz)AriaTextForCausalLM.set_output_embeddings|  s	    %r;   c                     || _         y ra   rS  r6   decoders     r:   set_decoderzAriaTextForCausalLM.set_decoder  s	    
r;   c                     | j                   S ra   r  rL   s    r:   get_decoderzAriaTextForCausalLM.get_decoder  s    zzr;   num_logits_to_keep4.50logits_to_keepversionnew_nameoutput_typerc  r  r  r  rT  r  labelsrI  r2  r  r.  r  r   c                    ||n| j                   j                  }|	|	n| j                   j                  }	 | j                  d||||||||	|
d	|}|j                  }t        |t              rt        | d      n|}| j                  |dd|ddf         }d}|* | j                  d||| 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 -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

            logits_to_keep (`int` or `torch.Tensor`, *optional*):
                If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
                If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
                This is useful when using packed tensor format (single dimension for batch and sequence length).

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, AriaTextForCausalLM

        >>> model = AriaTextForCausalLM.from_pretrained("meta-aria_text/AriaText-2-7b-hf")
        >>> tokenizer = AutoTokenizer.from_pretrained("meta-aria_text/AriaText-2-7b-hf")

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
        ```N)	r  r  r  rT  r  rI  r2  r  r.  r   r  r  lossr   rT  rE   r  rK  )rf   r2  r  rS  r  rY  r>  slicer  loss_functionr  r   rT  rE   r  )r6   r  r  r  rT  r  r  rI  r2  r  r.  r  r  rN  rE   slice_indicesr   r  s                     r:   rH   zAriaTextForCausalLM.forward  s   d 2C1N-TXT_T_TqTq$8$D $++JjJj 	
 ,64:: ,
)%+'/!5),
 ,
  118B>SV8W~ot4]kmA}a,?@A%4%%pVFt{{OeOepiopD%#33!//))
 	
r;   )NNNNNNNNNNr   )$rN   rO   rP   rc   _tied_weights_keys_tp_plan_pp_planr(   rc  r0   r  r  r  r  r  r  r   r!   r   r  r    r   _CONFIG_FOR_DOCr   r2   r?  r   r   rP  rO  r	   r>  r   r  rH   rQ   rR   s   @r:   r  r  Y  s   	 ++=)H_-z:;H!L~ '(& )6DTU*+EF+AP_` 151537+/59-1$(,0/35934P
E,,-P
 !.P
 u//0	P

 "%P
   1 12P
 ))*P
 D>P
 $D>P
 'tnP
 !!1!12P
 c5<</0P
 *+P
 
 P
 a G V P
r;   r  c                      e Zd ZU dZdZeej                     ed<   dZ	eej                     ed<   dZ
eeej                        ed<   dZeeej                        ed<   dZeeej                        ed<   dZeej                     ed<   y)	AriaCausalLMOutputWithPasta  
    Base class for Aria causal language model (or autoregressive) outputs.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

            Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        image_hidden_states (`torch.FloatTensor`, *optional*):
            A `torch.FloatTensor` of size (batch_size, num_images, sequence_length, hidden_size)`.
            image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
    Nr  r   rT  rE   r  image_hidden_states)rN   rO   rP   rc   r  r   r2   rP  __annotations__r   rT  r   rE   r   r  r  rK  r;   r:   r  r    s    < )-D(5$$
%,*.FHU&&'.9=OXd5#4#456=8<M8E%"3"345<59Ju001297;%"3"34;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.weightrf   c                    t         |   |       t        j                  |j                        | _        t        |      | _        |j                  j                  | _	        t        j                  |j                        | _        | j                  j                  | j                  j                  nd| _        |j                  j                  dk(  | _        | j!                          y )Nr=   r  )r/   r0   r$   from_configrj   vision_towerr   multi_modal_projectorr   r  r%   language_modelrf   r  r5  _use_flash_attention_2r  r   s     r:   r0   z%AriaForConditionalGeneration.__init__F  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 )Nr&   )	dimensionr   stepr#   )r=   r  r   r   )unfoldr  rf   
patch_sizer   rO  )r6   
pixel_maskpatches_subgrids      r:   _create_patch_attention_maskz9AriaForConditionalGeneration._create_patch_attention_maskQ  s    $++""))44""))44 , 

 *00""))44""))44 1 

  ###1A5;;==r;   c                 6    | j                   j                         S ra   )r
  r  rL   s    r:   r  z1AriaForConditionalGeneration.get_input_embeddingsa  s    ""7799r;   c                 :    | j                   j                  |       y ra   )r
  r  r  s     r:   r  z1AriaForConditionalGeneration.set_input_embeddingsd  s    007r;   c                 6    | j                   j                         S ra   )r
  r  rL   s    r:   r  z2AriaForConditionalGeneration.get_output_embeddingsg  s    ""88::r;   c                 :    | j                   j                  |       y ra   )r
  r  r  s     r:   r  z2AriaForConditionalGeneration.set_output_embeddingsj  s    11.Ar;   c                 :    | j                   j                  |       y ra   )r
  r  r  s     r:   r  z(AriaForConditionalGeneration.set_decoderm  s    ''0r;   c                 6    | j                   j                         S ra   )r
  r  rL   s    r:   r  z(AriaForConditionalGeneration.get_decoderp  s    ""..00r;   pixel_valuesr  vision_feature_layerc                     | j                  |      }| j                  ||d      }d }|&|j                  d      }t        j                  |      }|j
                  |   }| j                  ||      }	|	S )NT)patch_attention_maskr  r&   ry   )r  r  r   r2   logical_notrE   r	  )
r6   r  r  r  r  image_outputsimage_attn_maskflattened_maskselected_image_featureimage_featuress
             r:   get_image_featuresz/AriaForConditionalGeneration.get_image_featuress  s      $@@L))/CZ^ * 
 +199!<N#//?O!.!<!<=Q!R334JVe3fr;   r  r  r  r  r  r  r  r  rT  r  r  rI  r2  r  r.  r   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.
        ```Nr&   r   r   r   r=   )r  r  r  z6Image features and image tokens do not match: tokens: z, features )	r  r  rT  r  rI  r2  r  r  r.  r  r  rK  )rf   r2  r  r  rK   r2   tensorimage_token_indexr   r   r   r   	expand_asr@   r$  r  r  r?   masked_scatterr
  r   r  r   r  r  rT  rE   r  )r6   r  r  r  r  r  rT  r  r  rI  r2  r  r  r.  loss_kwargsspecial_image_maskn_image_tokensimage_embedsr#  n_imagesn_features_per_imagen_image_featuresrN  r   r  s                            r:   rH   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)rT  r  r  r.  r  r   r  r  )r
  prepare_inputs_for_generation)r6   r  rT  r  r  r  r  r.  r  r  model_inputss              r:   r2  z:AriaForConditionalGeneration.prepare_inputs_for_generation  si     It**HH
+')))
 
 !! ,8L()3L&r;   )Nr=   )NNNNNNNNNNNr   N)NNNNNNN)$rN   rO   rP   r'   rc  rh  rq  ri  r  r0   r  r  r  r  r  r  r  r2   rP  r   r>  r$  r   r!   r   ARIA_INPUTS_DOCSTRINGr    r  r?  r   r   rO  r	   rH   r2  rQ   rR   s   @r:   r  r  8  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  )r  rl  rR  r  r  )Nr&   )r3  )^dataclassesr   	functoolsr   typingr   r   r   r   r	   activationsr   cache_utilsr   r   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_outputsr   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   r   r    utils.deprecationr!   utils.import_utilsr"   autor$   r%   configuration_ariar'   r(   r2   r)   !torch.nn.attention.flex_attentionr*   integrations.flex_attentionr+   
get_loggerrN   r7  r  Moduler-   rT   re   r   r   r   r   r   r   r   r	  r   r>  r  r   r!  r#  rA  rR  ARIA_TEXT_START_DOCSTRINGrl  rv  r  r  r  r  r  r4  ARIA_START_DOCSTRINGr  __all__rK  r;   r:   <module>rM     s  * "  9 9 ! ; ; ) > B \ \ K F &   1 4 2 :   !;J 
		H	%"Jbii J(ryy 24 4n>BII >B299 4>)
RYY )
XBII DL-ryy L-^(6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % %4I)		 I)X>299 >B)o )@ " X9/ 9	98<bii <D@ F \I+ I	IX ?,j >@
1? @
F $< $< $<N! F " A s#6 sslr;   