
    rh                     :   d dl mZ d dlmZmZmZ ddlmZ ddlm	Z	m
Z
 ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ 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$ ddl%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z-  e(       r
d dl.Z.d dl.m/Z/  ed       G d de/j`                               Z1 G d de/j`                        Z2 G d de/j`                        Z3 G d d e/j`                        Z4 G d! d"e/j`                        Z5d# Z6 G d$ d%e/j`                        Z7 G d& d'e/j`                        Z8 G d( d)e/j`                        Z9d* Z:dUd+Z;d,e.jx                  d-e=d.e.jx                  fd/Z>	 dVd0e/j`                  d1e.jx                  d2e.jx                  d3e.jx                  d4ee.jx                     d5e?d6e?d7e e"   fd8Z@ G d9 d:e/j`                        ZA G d; d<e      ZBe# G d= d>e             ZCe# G d? d@e             ZD G dA dBe/j`                        ZEe# G dC dDeC             ZFe# G dE dFeCe             ZGe e#dGH       G dI dJe                    ZHe e#dKH       G dL dMe                    ZI e#dNH       G dO dPeD             ZJ e#dQH       G dR dSeDe             ZKg dTZLy)W    )	dataclass)CallableOptionalUnion   )ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hub)create_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPastModelOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuple)check_model_inputs)is_torch_available   )	AutoModel   )
AriaConfigAriaTextConfigN)nnRMSNormc                   ,     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      y/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/models/aria/modeling_aria.pyr(   zAriaTextRMSNorm.__init__1   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tor*   float32powmeanrsqrtr-   r,   )r.   hidden_statesinput_dtypevariances       r2   forwardzAriaTextRMSNorm.forward9   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r3   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler,   shaper-   r.   s    r2   
extra_reprzAriaTextRMSNorm.extra_repr@   s*    ))*+6$2G2G1HIIr3   )gư>)__name__
__module____qualname__r(   r@   rE   __classcell__r1   s   @r2   r%   r%   /   s    $;Jr3   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'   r(   r"   Linear	linear_in
linear_outr   act)r.   in_featureshidden_features
output_dimr1   s       r2   r(   zAriaProjectorMLP.__init__Q   sB    ;eL))OZeL*%r3   c                 h    | j                  | j                  |            }| j                  |      }|S N)rT   rR   rS   )r.   r=   s     r2   r@   zAriaProjectorMLP.forwardW   s-    !>?6r3   rF   rG   rH   __doc__r(   r@   rI   rJ   s   @r2   rL   rL   D   s    
&r3   rL   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 )NFrN   T)batch_first)r'   r(   vision_configr/   num_attention_heads	num_headsr"   rQ   q_projk_projv_projMultiheadAttentionmultihead_attnlinearDropoutdropout	LayerNorm
layer_normlayer_norm_kv)r.   r^   r_   r/   rd   r1   s        r2   r(   zAriaCrossAttention.__init__f   s    **66((<<	"ii[uEii[uEii[uE !33KX\]ii[9zz,/,,{3\\+6r3   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)re   rn   ro   rf   rg   ri   rl   rj   )	r.   key_value_statesr=   rr   querykeyvalueattn_output_s	            r2   r@   zAriaCrossAttention.forwardw   s      DOOM:;--.>?kk*+,-,,UC),TQll4;;{#;<r3   )r   rY   )	rF   rG   rH   r[   r    floatr(   r@   rI   rJ   s   @r2   r]   r]   ]   s     7z 7 7"r3   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 rY   )r'   r(   projector_patch_to_query_dictpatch_to_query_dictrb   r/   rU   rc   rd   kv_dimtext_configrV   rW   r"   r)   r*   zeros'max_value_projector_patch_to_query_dictrt   r]   
cross_attnrm   rn   rL   feed_forwardr.   r^   r1   s     r2   r(   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r3   rs   rr   c                 4   |j                   d   |j                   d   }}|| j                  vr*t        d| d| j                  j                          d      | j                  |   }| j                  d| j                  d      j                  |dd      }|M|j                  | j                  d      }|j                  d      j                  d|j                  d      d      }| j                  |||      }| j                  | j                  |            }|S )	a  
        Forward pass of the Projector module.

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

        Returns:
            `torch.Tensor`: Output tensor of shape (batch_size, query_number, output_dim).
        r   r   zNumber of patches z: not found in patch_to_query_dict amongst possible values .Nr5   rq   )rC   r~   KeyErrorkeysrt   	unsqueezerepeatrepeat_interleaverd   expandsizer   r   rn   )	r.   rs   rr   
batch_sizenum_patches	query_numqueriesattention_outouts	            r2   r@   zAriaProjector.forward   s6    #3"8"8";=M=S=STU=VK
d666$[M1klp  mE  mE  mJ  mJ  mL  lM  MN  O  ,,[9	**Zi(2215<<ZAN !33DNNAFI!++A.55b',,q/2NI(8'YW >?
r3   rY   )rF   rG   rH   r[   r    r(   r*   Tensorr   r@   rI   rJ   s   @r2   r{   r{      s7    ff( %,,AW r3   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.
    r^   c                     t         |           || _        |j                  | _        |j                  |j
                  z  | _        t        j                  | j                  | j                  |j                        | _	        t        j                  | j                  | j                  |j                        | _
        t        j                  | j                  | j                  |j                        | _        t        |j                     | _        y )NrN   )r'   r(   r^   r/   intermediate_sizemoe_num_shared_expertsr"   rQ   mlp_bias	gate_projup_proj	down_projr   
hidden_actact_fnr   s     r2   r(   zAriaSharedExpertsMLP.__init__   s    !--!'!9!9F<Y<Y!Y4#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r3   c                     | j                  | j                  | j                  |            | j                  |      z        }|S rY   )r   r   r   r   )r.   xr   s      r2   r@   zAriaSharedExpertsMLP.forward   s6    NN4;;t~~a/@#ADLLQRO#ST	r3   rF   rG   rH   r[   r!   r(   r@   rI   rJ   s   @r2   r   r      s    0~ 0r3   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   r5   r7   devicedimr   )
rC   r*   r   r7   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                r2   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  Mr3   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 rY   )
r'   r(   rU   r   groupsr"   r)   r*   emptyr,   )r.   rU   r   r   r1   s       r2   r(   zAriaGroupedExpertsGemm.__init__  sB    &(ll5;;v{L#QRr3   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)r.   inputr   s      r2   r@   zAriaGroupedExpertsGemm.forward&  s'     'KK!!#
 	
r3   rZ   rJ   s   @r2   r   r     s     S
r3   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^   returnNc                     t         |           || _        t        |j                  |j
                  dz  |j                        | _        t        |j
                  |j                  |j                        | _        y )Nr   )	r'   r(   r^   r   r/   r   moe_num_expertsfc1fc2r   s     r2   r(   zAriaGroupedExpertsMLP.__init__C  sa    )&*<*<f>V>VYZ>Z\b\r\rs)&*B*BFDVDVX^XnXnor3   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   r5   r   )r   r*   chunkr"   
functionalsilur   )r.   permuted_tokensr   
fc1_output
projectiongate
fc2_outputs          r2   r@   zAriaGroupedExpertsMLP.forwardI  s\     XXo/@A
 ;;z1"=
D]]''
3d:
XXj*;<
r3   r   rJ   s   @r2   r   r   :  s#    p~ p$ pr3   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 NFrN   )r'   r(   r"   rQ   r/   r   routerr   expertsr   shared_expertsr^   r   s     r2   r(   zAriaTextMoELayer.__init__g  sO    ii 2 2F4J4JQVW,V426:r3   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.
        r5   r   )kr   r   r   )binsminmaxr   )rC   viewr   r   r*   topkr^   moe_topkr"   r   softmaxr7   histcflattenr8   r9   r   argsortindex_selectr   r   r   index_copy_r   sumr   )r.   r=   original_shapelogits
top_logitstop_indicesscoresoriginal_dtyper   indicesflatten_indicessorted_indicesr   expert_outputunpermuted_tokensr   shared_expert_outputs                    r2   r@   zAriaTextMoELayer.forwardo  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,,,r3   )
rF   rG   rH   r[   r!   r(   r*   r   r@   rI   rJ   s   @r2   r   r   \  s/    ~ 9-U\\ 9-ell 9-r3   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..Nr5   r   r   )rC   r*   r   )r   x1x2s      r2   rotate_halfr     sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r3   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           r2   apply_rotary_pos_embr    sY    ( --
&C
--
&C3w;q>C/0G3w;q>C/0GGr3   r=   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)rC   r   reshape)r=   r  batchnum_key_value_headsslenhead_dims         r2   	repeat_kvr	    so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr3   modulert   ru   rv   attention_maskscalingrl   kwargsc                 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   r5   )r   r7   )ptrainingr   )r	  num_key_value_groupsr*   r   	transposerC   r"   r   r   r9   r8   r7   rl   r  
contiguous)r
  rt   ru   rv   r  r  rl   r  
key_statesvalue_statesattn_weightscausal_maskrw   s                r2   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$$r3   c                       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j                  f   fdZ xZS )AriaTextAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr^   	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      TrN   )r'   r(   r^   r  getattrr/   rc   r  r  r  r  attention_dropout	is_causalr"   rQ   attention_biasre   rf   rg   o_projr.   r^   r  r1   s      r2   r(   zAriaTextAttention.__init__  sM   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
r3   r=   position_embeddingsr  past_key_valuecache_positionr  r   c                 4   |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t        | j                  j                     } || |	|
||f| j                  sdn| j                  | j                   d|\  }} |j"                  g |d j%                         }| j'                  |      }||fS )Nr5   r   r   )r   r   r&  eager        )rl   r  )rC   r  re   r   r  rf   rg   r  updater  r  r^   _attn_implementationr   r  r  r  r  r  r"  )r.   r=   r$  r  r%  r&  r  input_shapehidden_shapequery_statesr  r  r   r   cache_kwargsattention_interfacerw   r  s                     r2   r@   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"9$++:Z:Z"[$7	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r3   )NN)rF   rG   rH   r[   r!   intr(   r*   r   rB   r   r	   
LongTensorr   r   r@   rI   rJ   s   @r2   r  r    s    G
~ 
# 
8 +/59))||)) #5<<#=>)) !.	))
 !)) !!1!12)) +,)) 
u||U\\)	*))r3   r  c                   ,    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j                     de	eej                  ej                  f      dee   deej                     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^   r  c                     t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y )N)r^   r  r0   )r'   r(   r/   r  	self_attnr   mlpr%   rms_norm_epsinput_layernormpost_attention_layernormr#  s      r2   r(   zAriaTextDecoderLayer.__init__F  sm    !--*&IN#F+.v/A/AvGZGZ[(78J8JPVPcPc(d%r3   r=   r  r   r%  	use_cacher&  r$  r  r   c                     |}	| j                  |      } | j                  d|||||||d|\  }}
|	|z   }|}	| j                  |      }| j                  |      }|	|z   }|S )N)r=   r  r   r%  r<  r&  r$   )r:  r7  r;  r8  )r.   r=   r  r   r%  r<  r&  r$  r  residualrx   s              r2   r@   zAriaTextDecoderLayer.forwardO  s     !,,];)4>> 	
')%)) 3	
 	
q !=0 !55mD/ =0r3   )NNNFNN)rF   rG   rH   r[   r!   r1  r(   r*   r   r   r2  r	   boolrB   r   r   r@   rI   rJ   s   @r2   r4  r4  9  s    
e~ e# e 2637*.$)59KO|| !. u//0	
 ! D> !!1!12 &eELL%,,,F&GH +, 
u||	r3   r4  c                   T     e Zd ZU eed<   dZddgZdZdZdZ	dZ
dZeedZ fd	Z xZS )
AriaTextPreTrainedModelr^   modelr4  r   Tpast_key_valuesFr=   
attentionsc                     t         |   |       t        |t              r<|j                  j
                  j                  d| j                  j                         y y )Nr)  )r;   std)	r'   _init_weights
isinstancer   r,   datanormal_r^   initializer_ranger.   r
  r1   s     r2   rI  z%AriaTextPreTrainedModel._init_weights  sG    f%f45MM&&CT[[5R5R&S 6r3   )rF   rG   rH   r!   __annotations__base_model_prefix_no_split_modulessupports_gradient_checkpointing_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_attention_backendr4  r  _can_record_outputsrI  rI   rJ   s   @r2   rB  rB  q  sR    /1IJ&*#"3 N"&-'
T Tr3   rB  c                   \     e Zd ZU eed<   dZdZdgZdgZdZ	dZ
dZdZdZeedZ fdZ xZS )	AriaPreTrainedModelr^    TAriaDecoderLayerrD  FrE  c                     t         |   |       t        |t              r@t        j
                  j                  |j                  | j                  j                         y y )N)rH  )
r'   rI  rJ  r{   r"   inittrunc_normal_rt   r^   rM  rN  s     r2   rI  z!AriaPreTrainedModel._init_weights  sD    f%fm,GG!!&,,DKK4Q4Q!R -r3   )rF   rG   rH   r    rO  rP  rR  rQ  rS  rT  rU  _supports_flex_attn_can_compile_fullgraphrV  r4  r  rW  rI  rI   rJ   s   @r2   rY  rY    s^    &*#+,#4"5N""&-'
S Sr3   rY  c                   ^     e Zd Zddef fdZ ej                         ed               Z xZ	S )AriaTextRotaryEmbeddingr^   c                    t         |           t        |d      rUt        |j                  t
              r;|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'   r(   hasattrrJ  rd  dictgetre  max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr^   r   rope_init_fnattention_scalingregister_bufferrh  original_inv_freq)r.   r^   r   rh  r1   s       r2   r(   z AriaTextRotaryEmbedding.__init__  s    6>*z&:M:Mt/T#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%r3   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   r5   r   mpsr   F)device_typeenabledr   r   )r7   )rh  ry   r   rC   r8   r   rJ  rf  strr*   autocastr  r   r   rq  r   r7   )
r.   r   r   inv_freq_expandedposition_ids_expandedrv  freqsembr   r   s
             r2   r@   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.rY   )
rF   rG   rH   r!   r(   r*   no_gradr   r@   rI   rJ   s   @r2   rb  rb    s3    /~ /" U]]_<  <r3   rb  c                       e Zd Zdef fdZ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j                     d	ee   d
ee   defd              Z xZS )AriaTextModelr^   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 )Nr6  )r^   F)r'   r(   pad_token_idpadding_idx
vocab_sizer"   	Embeddingr/   embed_tokens
ModuleListr   num_hidden_layersr4  layersr%   r9  normrb  
rotary_embgradient_checkpointing	post_initr#  s      r2   r(   zAriaTextModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammFKFLdLdFef!&)4f
 $F$6$6F<O<OP	1@&+# 	 gs   D	input_idsr  r   rD  inputs_embedsr&  r<  r  r   c           
      *   |d u |d uz  rt        d      || j                  |      }|r|
t               }|F||j                         nd}	t	        j
                  |	|	|j                  d   z   |j                        }||j                  d      }t        | j                  |||||      }
|}| j                  ||      }| j                  d | j                  j                   D ]  } ||f|
||||d|} | j                  |      }t        ||      S )Nz:You must specify exactly one of input_ids or inputs_embedsr   r   )r   )r^   input_embedsr  r&  rD  r   )r  r   r%  r&  r$  )last_hidden_staterD  )
ValueErrorr  r
   get_seq_lengthr*   arangerC   r   r   r   r^   r  r  r  r  r   )r.   r  r  r   rD  r  r&  r<  r  past_seen_tokensr  r=   r$  decoder_layers                 r2   r@   zAriaTextModel.forward  sT    -t";<YZZ *.*;*;I*FM0*nO!CRC^==?de+0<< "2]5H5H5K"KTaThTh,N )33A6L(;;&))+%
 &"oom\J![[)H4;;+H+HI 		M)*).-$7 M		 		-0&++
 	
r3   NNNNNNN)rF   rG   rH   r!   r(   r   r   r   r*   r2  r   r	   FloatTensorr@  r   r   r   r@   rI   rJ   s   @r2   r  r    s    ~    151537+/5959$(8
E,,-8
 !.8
 u//0	8

 "%8
   1 128
 !!1!128
 D>8
 +,8
 
!8
  8
r3   r  c                   l    e Zd ZdgZddiZddgdgfiZdef fdZd Zd	 Z	e
	 	 	 	 	 	 	 	 	 dd
eej                     deej                     deej                     dee   deej                      deej                     dee   deej                     deeej                  f   dee   defd       Z xZS )AriaTextForCausalLMlm_head.weightlm_headcolwise_repr=   r   r^   c                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y r   )
r'   r(   r  rC  r  r"   rQ   r/   r  r  r   s     r2   r(   zAriaTextForCausalLM.__init__  sU     "6*
 ++yy!3!3V5F5FUS 	r3   c                     || _         y rY   rC  r.   decoders     r2   set_decoderzAriaTextForCausalLM.set_decoder  s	    
r3   c                     | j                   S rY   r  rD   s    r2   get_decoderzAriaTextForCausalLM.get_decoder!  s    zzr3   r  r  r   rD  r  labelsr<  r&  logits_to_keepr  r   c
                 z    | 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  
        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."
        ```)r  r  r   rD  r  r<  r&  Nr   r  r  lossr   rD  r=   rF  r>  )rC  r  rJ  r1  slicer  loss_functionr^   r  r   rD  r=   rF  )r.   r  r  r   rD  r  r  r<  r&  r  r  outputsr=   slice_indicesr   r  s                   r2   r@   zAriaTextForCausalLM.forward$  s    > ,64:: 	,
)%+')	,
 	,
  118B>SV8W~ot4]kmA}a,?@A%4%%pVFt{{OeOepiopD%#33!//))
 	
r3   )	NNNNNNNNr   )rF   rG   rH   _tied_weights_keys_tp_plan_pp_planr!   r(   r  r  r   r   r*   r2  r   r	   r  r@  r   r1  r   r   r   r@   rI   rJ   s   @r2   r  r    s9   *+=)H_-z:;H~   151537+/59-1$(59348
E,,-8
 !.8
 u//0	8

 "%8
   1 128
 ))*8
 D>8
 !!1!128
 c5<</08
 +,8
 
 8
 8
r3   r  zP
    Base class for Aria causal language model (or autoregressive) outputs.
    )custom_introc                      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]  
    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 (`Cache`, *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.
    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   rD  r=   rF  image_hidden_states)rF   rG   rH   r[   r  r   r*   r  rO  r   rD  listr=   rB   rF  r  r>  r3   r2   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;r3   r  zI
    Base class for Aria outputs, with hidden states and attentions.
    c                   :    e Zd ZU dZdZeej                     ed<   y)AriaModelOutputWithPasta  
    past_key_values (`Cache`, *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.
    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  )	rF   rG   rH   r[   r  r   r*   r  rO  r>  r3   r2   r  r    s    
 8<%"3"34;r3   r  zt
    The Aria model which consists of a vision backbone and a language model, without a language modeling head.
    c                       e Zd ZddiZdef fdZd Zd Zd Zd Z		 	 dd	e
j                  d
ee
j                     defdZde
j                  de
j                  de
j                  fdZee	 	 	 	 	 	 	 	 	 dde
j                  d	e
j                  d
e
j                  dee
j&                     dee
j                     dee   dee
j                     dee   dee
j                     dee   deeef   fd              Zd Z xZS )	AriaModelzlanguage_model.modellanguage_modelr^   c                     t         |   |       t        j                  |j                        | _        t        |      | _        t        j                  |j                        | _	        | j                          y rY   )r'   r(   r   from_configrb   vision_towerr{   multi_modal_projectorr   r  r  r   s     r2   r(   zAriaModel.__init__  sY     %11&2F2FG%26%:"'33F4F4FGr3   c                 6    | j                   j                         S rY   )r  get_input_embeddingsrD   s    r2   r  zAriaModel.get_input_embeddings  s    ""7799r3   c                 :    | j                   j                  |       y rY   )r  set_input_embeddingsr.   rv   s     r2   r  zAriaModel.set_input_embeddings  s    007r3   c                     || _         y rY   r  r  s     r2   r  zAriaModel.set_decoder  s
    %r3   c                     | j                   S rY   r  rD   s    r2   r  zAriaModel.get_decoder  s    """r3   pixel_values
pixel_maskvision_feature_layerc                    ||n| j                   j                  }| j                  |      }| j                  ||d      }d}|&|j	                  d      }t        j                  |      }|j                  |   }| j                  ||      }	|	S )aM  
        Obtains image last hidden states from the vision tower and apply multimodal projection.

        Args:
            pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`):
               The tensors corresponding to the input images.
            pixel_mask (`torch.FloatTensor]`, *optional*):
                The tensors corresponding to the input image mask.
            vision_feature_layer (`Union[int, list[int]]`, *optional*):
                The index of the layer to select the vision feature. If multiple indices are provided,
                the vision feature of the corresponding indices will be concatenated to form the
                vision features.
        Returns:
            image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
        NT)patch_attention_maskoutput_hidden_statesr   rq   )	r^   r  _create_patch_attention_maskr  r   r*   logical_notr=   r  )
r.   r  r  r  r  image_outputsimage_attn_maskflattened_maskselected_image_featureimage_featuress
             r2   get_image_featureszAriaModel.get_image_features  s    , %9$D $++JjJj 	  $@@L))/CZ^ * 
 +199!<N#//?O!.!<!<=Q!R334JVe3fr3   r  r  r  c                 P   |m| | j                         t        j                  | j                  j                  t        j
                  |j                              k(  }|j                  d      }n|| j                  j                  k(  }|j                         }|j                  d      j                  |      j                  |j                        }|j                  d   |j                  d   z  }||   j                         |j                         k7  rt        d| d|       |S )z
        Obtains multimodal placeholdr mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
        equal to the length of multimodal features. If the lengths are different, an error is raised.
        r   r5   r   r   z6Image features and image tokens do not match: tokens: z, features )r  r*   tensorr^   image_token_idr   r   allr   r   	expand_asr8   rC   numelr  )r.   r  r  r  special_image_maskn_image_tokensn_image_featuress          r2   get_placeholder_maskzAriaModel.get_placeholder_mask  s    !.2M$2K2K2MT[[77uzzR_RfRfg3 " "4!7!7!;!*dkk.H.H!H+//1/99"=GGVYYZgZnZno)//2^5I5I!5LL+,2248L8L8NNHHXXcdtcuv  "!r3   r  r   rD  r<  r&  r  r   c
           
         | | j                         |      }||j                  d   dk7  rt| j                  ||| j                  j                        }|j                  |j                  |j                        }| j                  |||      }|j                  ||      } | j                  d||||||	d|
}t        |j                  |r|j                  nd |j                  |j                  |      S d       S )Nr   r  r  r  )r  r  )r  r   rD  r  r<  r&  )r  rD  r=   rF  r  r>  )r  rC   r  r^   r  r8   r   r7   r  masked_scatterr  r  r  rD  r=   rF  )r.   r  r  r  r  r   rD  r  r<  r&  r  r  r  r  s                 r2   r@   zAriaModel.forward  s6     7D557	BM #(;(;A(>!(C!44)%%)[[%E%E 5 N
 ,..}/C/C]EXEXYN!%!:!:~ "; " *889K^\M%$%% 
)%+')
 
 '%777@G33d!//))2>2J
 	

 QU
 	
r3   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   )r5   r  r   r   )unfoldr  r^   
patch_sizer   r@  )r.   r  patches_subgrids      r2   r  z&AriaModel._create_patch_attention_mask  s    $++""))44""))44 , 

 *00""))44""))44 1 

  ###1A5;;==r3   Nr5   )	NNNNNNNNN)rF   rG   rH   _checkpoint_conversion_mappingr    r(   r  r  r  r  r*   r  r   r1  r  r2  r  r   r   r   r	   r@  r   r   r   rB   r  r@   r  rI   rJ   s   @r2   r  r    s    '=>N%O"z :8&# 37$&	#''# U../# "	#J"))":?:K:K"]b]n]n"0  '+*.'+1537+/59$(59-
##-
 ''-
 $$	-

 !.-
 u//0-
 "%-
   1 12-
 D>-
 !!1!12-
 -.-
 
u--	.-
  -
^>r3   r  z
    Aria model for conditional generation tasks.

    This model combines a vision tower, a multi-modal projector, and a language model
    to perform tasks that involve both image and text inputs.
    c                   b    e Zd ZdddddZdgZdef fdZd	 Zd
 Zde	j                  fdZd Zd Z	 	 d"dej                  deej                     defdZed        Zed        Zed        Zee	 	 	 	 	 	 	 	 	 	 	 d#dej2                  dej                  dej2                  deej4                     deej2                     dee   deej                     deej2                     dee   deeej4                  f   deej2                     dee   dee e!f   fd               Z"	 	 	 	 	 	 	 d$ fd!	Z# xZ$S )%AriaForConditionalGenerationzmodel.language_modelzmodel.vision_towerzmodel.multi_modal_projectorr  )z^language_model.modelz^vision_towerz^multi_modal_projectorz^language_model.lm_headr  r^   c                     t         |   |       t        |      | _        t	        j
                  |j                  j                  |j                  j                  d      | _	        | j                          y r   )r'   r(   r  rC  r"   rQ   r   r/   r  r  r  r   s     r2   r(   z%AriaForConditionalGeneration.__init__@  sS     v&
yy!3!3!?!?ASASA^A^ejkr3   c                 6    | j                   j                         S rY   )rC  r  rD   s    r2   r  z1AriaForConditionalGeneration.get_input_embeddingsF  s    zz..00r3   c                 :    | j                   j                  |       y rY   )rC  r  r  s     r2   r  z1AriaForConditionalGeneration.set_input_embeddingsI  s    

''.r3   r   c                     | j                   S rY   )r  rD   s    r2   get_output_embeddingsz2AriaForConditionalGeneration.get_output_embeddingsL  s    ||r3   c                 :    | j                   j                  |       y rY   )rC  r  r  s     r2   r  z(AriaForConditionalGeneration.set_decoderO  s    

w'r3   c                 6    | j                   j                         S rY   )rC  r  rD   s    r2   r  z(AriaForConditionalGeneration.get_decoderR  s    zz%%''r3   r  r  r  c                 >    | j                   j                  |||      S )Nr  )rC  r  )r.   r  r  r  s       r2   r  z/AriaForConditionalGeneration.get_image_featuresU  s)     zz,,%!!5 - 
 	
r3   c                 .    | j                   j                  S rY   )rC  r  rD   s    r2   r  z+AriaForConditionalGeneration.language_modelb  s    zz(((r3   c                 .    | j                   j                  S rY   )rC  r  rD   s    r2   r  z)AriaForConditionalGeneration.vision_towerf  s    zz&&&r3   c                 .    | j                   j                  S rY   )rC  r  rD   s    r2   r  z2AriaForConditionalGeneration.multi_modal_projectorj  s    zz///r3   r  r  r   rD  r  r  r<  r  r&  r  c                     | j                   d||||||||	|d	|}|d   }t        |
t              rt        |
 d      n|
}| j	                  |dd|ddf         }d}|4 | j
                  d||| j                  j                  j                  d|}t        |||j                  |j                  |j                        S )aa  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or `model.image_token_id` (where `model` is your instance of `AriaForConditionalGeneration`).
            Tokens with indices set to `model.image_token_id` are ignored (masked), the loss is only
            computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

        ```python
        >>> import 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.
        ```)	r  r  r  r  r   rD  r  r<  r&  r   Nr  r  r>  )rC  rJ  r1  r  r  r  r^   r   r  r  rD  r=   rF  )r.   r  r  r  r  r   rD  r  r  r<  r  r&  r  r  r=   r  r   r  s                     r2   r@   z$AriaForConditionalGeneration.forwardn  s    Z $** 
%!)%+')
 
  
8B>SV8W~ot4]kmA}a,?@A%4%% f9P9P9[9[_eD *#33!//))
 	
r3   c	           	      X    t        |   |f|||||d|	}
|d   dk(  r
||
d<   ||
d<   |
S )N)rD  r  r  r&  r  r   r  r  )r'   prepare_inputs_for_generation)r.   r  rD  r  r  r  r  r&  r  r  model_inputsr1   s              r2   r  z:AriaForConditionalGeneration.prepare_inputs_for_generation  s`     w<
+')))
 
 !! ,8L()3L&r3   r  )NNNNNNNNNr   Nr  )%rF   rG   rH   r  r  r    r(   r  r  r"   Moduler  r  r  r*   r  r   r1  r  propertyr  r  r  r   r   r2  r   r	   r@  r   r   r   rB   r  r@   r  rI   rJ   s   @r2   r  r  /  s(    "8-"?#,	&" ++z 1/ryy (( 37$&	

''

 U../

 "	

 ) ) ' ' 0 0  '+*.'+1537+/59-1$(3459i
##i
 ''i
 $$	i

 !.i
 u//0i
 "%i
   1 12i
 ))*i
 D>i
 c5<</0i
 !!1!12i
 +,i
 
u00	1i
  i
\  r3   r  )r  rY  rB  r  r  r  )Nr   )r)  )Mdataclassesr   typingr   r   r   activationsr   cache_utilsr	   r
   
generationr   integrationsr   masking_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   utils.genericr   utils.import_utilsr   autor   configuration_ariar    r!   r*   r"   r  r%   rL   r]   r{   r   r   r   r   r   r   r  r   r1  r	  ry   r  r  r4  rB  rY  rb  r  r  r  r  r  r  __all__r>  r3   r2   <module>r     s  * " , , ! . ) 7 / B 9 \ \ K F & I I / 4  :  Y'Jbii J (J(ryy 24 4n>BII >B299 4>)
RYY )
XBII DL-ryy L-^(6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % % '(%4C)		 C)L55 5p To T T* S/ S S,<bii <D K
+ K
 K
\ M
1? M
 M
` 
< < <2 
<5 < <  
R># R>
R>j @#6 @@Fr3   