
    fThd^                    >   S r SSKrSSKJrJrJrJrJr  SSKrSSK	J
s  Jr  SSKrSSKJ
r
  SSKJr  SSKJrJr  SSKJr  SS	KJr  SS
KJr  SSKJrJrJr  SSKJrJr  SSK J!r!J"r"  SSK#J$r$  SSK%J&r&J'r'J(r(J)r)J*r*  SSK+J,r,J-r-J.r.  \)" 5       (       a  SSK/J0r0  SSK1J2r2  \*Rf                  " \45      r5S\Rl                  S\7S\8S\\Rl                  \Rl                  4   4S jr9S\Rl                  S\7S\7S\Rt                  S\Rl                  4
S jr; " S S\
Rx                  5      r= " S S \
Rx                  5      r> " S! S"\
Rx                  5      r?S#\Rl                  S$\7S\Rl                  4S% jr@ SYS&\
Rx                  S'\Rl                  S(\Rl                  S)\Rl                  S*\\Rl                     S+\AS,\A4S- jjrB " S. S/\
Rx                  5      rC " S0 S1\
Rx                  5      rD " S2 S3\
Rx                  5      rE " S4 S5\
Rx                  5      rF " S6 S7\
Rx                  5      rGS8 rHSZS9 jrI " S: S;\
Rx                  5      rJ " S< S=\
Rx                  5      rK " S> S?\
Rx                  5      rL " S@ SA\R                  Rx                  5      rM " SB SC\
Rx                  5      rN\' " SD SE\"5      5       rO\'" SFSG9 " SH SI\O5      5       rP\'" SJSG9 " SK SL\O5      5       rQ " SM SN\\&5      rR\'" SOSG9 " SP SQ\O\5      5       rS\'" SRSG9 " SS ST\O5      5       rT\'" SUSG9 " SV SW\O\5      5       rU/ SXQrVg)[zPyTorch Mllama model.    N)CallableListOptionalTupleUnion)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs)BaseModelOutputBaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)
LossKwargsauto_docstringcan_return_tupleis_torch_flex_attn_availablelogging   )MllamaConfigMllamaTextConfigMllamaVisionConfig)	BlockMask)make_flex_block_causal_maskcross_attention_masknum_vision_tokensdtypereturnc                    U R                   tp4nU R                  USS9n U R                  X4S5      n U R                  S5      n SU -
  R	                  U5      nUR                  UR	                  [        R                  5      [        R                  " U5      R                  5      n [        R                  " U5      R                  nX:g  R                  SS9R                  U 5      S   nX-  n X4$ )Nr	   dimr         ?).N)shaperepeat_interleaveview	unsqueezetomasked_filltorchboolfinfominanytype_as)	r#   r$   r%   
batch_sizetext_total_length_inverted_cross_attn_masknegative_inf_valuefull_text_row_masked_out_masks	            b/var/www/auris/envauris/lib/python3.13/site-packages/transformers/models/mllama/modeling_mllama.py_prepare_cross_attention_maskr?   /   s     )=(B(B%JA/AABSYZA[/44ZTVW/99!< !$&: :>>uE3?? ##EJJ/U1C1G1G U+//		388R8@HHI]^_hi " 9>>    aspect_ratio_masknum_patchestarget_lengthc                 t   U R                   u  pEU R                  XESS5      R                  U5      nUR                  SSUS5      nX!-
  nSUS S 2S S 2U* S 24'   SU-
  nUR	                  XEU-  S5      nXfR                  SS5      -  [        R                  " U5      R                  -  nUR                  S5      nU$ )Nr   r   r*   )
r,   r.   r0   repeatreshape	transposer2   r4   r5   r/   )rA   rB   rC   r%   r8   max_num_tilesattention_maskpad_patchess           r>   $_prepare_aspect_ratio_attention_maskrL   K   s     !2 7 7J&++Jq!LOOPUVN#**1aBN  -K*+N1a+&' 'N $++J8UWXYN#&>&>r2&FFUZI[I_I__N#--a0Nr@   c                      ^  \ rS rSrS
S\S\4U 4S jjjrS\R                  S\R                  S\R                  4S jr	S	r
U =r$ )%MllamaPrecomputedAspectRatioEmbeddingf   configis_gatedc                   > [         TU ]  5         UR                  U l        UR                  U l        UR                  U l        X l        [        R                  " U R                  S-   U R                  U R                  -  5      U l        U(       a0  [        R                  " [        R                  " S5      5      U l        g g Nr   )super__init__rI   hidden_sizemax_aspect_ratio_idrQ   r   	Embedding	embedding	Parameterr2   zerosgateselfrP   rQ   	__class__s      r>   rU   .MllamaPrecomputedAspectRatioEmbedding.__init__g   s    #11!--#)#=#=  d&>&>&BDDVDVY]YiYiDijU[[^4DI r@   hidden_stateaspect_ratio_idsr&   c                     U R                  U5      nUR                  SU R                  SU R                  5      nU R                  (       a  X0R
                  R                  5       -  nX-   nU$ )Nr*   r   )rY   rG   rI   rV   rQ   r\   tanh)r^   ra   rb   
embeddingss       r>   forward-MllamaPrecomputedAspectRatioEmbedding.forwardr   s[    ^^$45
''D,>,>4CSCST
==#iinn&66J#0r@   )rY   r\   rV   rQ   rW   rI   )T)__name__
__module____qualname____firstlineno__r    r3   rU   r2   Tensorrf   __static_attributes____classcell__r_   s   @r>   rN   rN   f   sJ    	51 	5T 	5 	5ELL ELL UZUaUa  r@   rN   c                      ^  \ rS rSrS\4U 4S jjrS\R                  S\R                  S\R                  4S jrSr	U =r
$ )	"MllamaPrecomputedPositionEmbedding}   rP   c                   > [         TU ]  5         UR                  U l        UR                  U l        UR                  UR
                  -  S-  S-   U l        UR                  U l        UR                  S-  U l        [        R                  " [        R                  " S5      5      U l        [        R                  " U R                  U R                  5      n[        R                  " U R                  U-  5      U l        [        R                   " U R                  S-   U R                  U R                  -  U R                  -  5      U l        g )N   r         )rT   rU   rI   rW   
image_size
patch_sizerB   rV   scaler   rZ   r2   r[   r\   randnrY   rX   tile_embedding)r^   rP   position_embeddingr_   s      r>   rU   +MllamaPrecomputedPositionEmbedding.__init__~   s    #11#)#=#= "--1B1BBqH1L!--''-
LLQ0	 #[[)9)94;K;KLdjj3E&EF !ll$$q($*<*<t?O?O*ORVRbRb*b
r@   ra   rb   r&   c                    SU R                   R                  5       -
  U R                  -  nXR                  SSU R                  U R
                  5      -   nU R                  U5      nUR                  S   nUR                  XPR                  U R                  U R
                  5      nU R                   R                  5       U-  nX-   nU$ )Nr   r   )
r\   rd   rY   r.   rB   rV   rz   r,   rG   rI   )r^   ra   rb   gated_position_embeddingtile_position_embeddingr8   gated_tile_position_embeddings          r>   rf   *MllamaPrecomputedPositionEmbedding.forward   s    $%		(8$8DNN#J #&C&CAq$JZJZ\`\l\l&mm #'"5"56F"G!''*
"9"A"A**D,<,<d>N>N#
 )-		(8;R(R%#Cr@   )rY   r\   rV   rW   rI   rB   rx   rz   )rh   ri   rj   rk   r    rU   r2   rl   rf   rm   rn   ro   s   @r>   rq   rq   }   s>    
1 
&ELL ELL UZUaUa  r@   rq   c                   b   ^  \ rS rSrU 4S jrS\R                  S\R                  4S jrSrU =r	$ )MllamaVisionMLP   c                   > [         TU ]  5         Xl        [        UR                     U l        [        R                  " UR                  UR                  5      U l
        [        R                  " UR                  UR                  5      U l        g N)rT   rU   rP   r
   
hidden_actactivation_fnr   LinearrV   intermediate_sizefc1fc2r^   rP   r_   s     r>   rU   MllamaVisionMLP.__init__   sb    #F$5$5699V//1I1IJ99V55v7I7IJr@   hidden_statesr&   c                 l    U R                  U5      nU R                  U5      nU R                  U5      nU$ r   )r   r   r   )r^   r   s     r>   rf   MllamaVisionMLP.forward   s4    /**=9/r@   )r   rP   r   r   )
rh   ri   rj   rk   rU   r2   rl   rf   rm   rn   ro   s   @r>   r   r      s)    KU\\ ell  r@   r   r   n_repc                     U R                   u  p#pEUS:X  a  U $ U SS2SS2SSS2SS24   R                  X#XU5      n U R                  X#U-  XE5      $ )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)r,   expandrG   )r   r   batchnum_key_value_headsslenhead_dims         r>   	repeat_kvr      s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr@   modulequerykeyvaluerJ   scalingdropoutc                 @   [        X R                  5      n[        X0R                  5      n	[        R                  " XR	                  SS5      5      U-  n
Ub"  US S 2S S 2S S 2S UR
                  S   24   nX-   n
[        R                  R                  U
S[        R                  S9R                  UR                  5      n
[        R                  R                  XU R                  S9n
[        R                  " X5      nUR	                  SS5      R                  5       nX4$ )Nrt   r	   rE   r*   )r)   r%   )ptrainingr   )r   num_key_value_groupsr2   matmulrH   r,   r   
functionalsoftmaxfloat32r0   r%   r   r   
contiguous)r   r   r   r   rJ   r   r   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputs                r>   eager_attention_forwardr      s     3 ; ;<JU$?$?@L<<';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#1==((2U]](SVVW\WbWbcL==((6??([L,,|:K''1-88:K$$r@   c                      ^  \ rS rSrS\4U 4S jjr  S
S\R                  S\\R                     S\\	   S\
\R                  \\R                     4   4S jjrS	rU =r$ )MllamaVisionAttention   rP   c                   > [         TU ]  5         Xl        UR                  U l        UR
                  U l        UR                  UR
                  -  U l        U R                  S-  U l        SU l	        [        R                  " U R                  U R                  U R                  -  SS9U l        [        R                  " U R                  U R                  U R                  -  SS9U l        [        R                  " U R                  U R                  U R                  -  SS9U l        [        R                  " U R                  U R                  -  U R                  SS9U l        g )Nru   r   Fbias)rT   rU   rP   rV   	embed_dimattention_heads	num_headsr   r   r   r   r   q_projk_projv_projo_projr   s     r>   rU   MllamaVisionAttention.__init__   s    ++//**f.D.DD}}d*$%!ii0NUZ[ii0NUZ[ii0NUZ[ii >UZ[r@   ra   rJ   output_attentionsr&   c                    U R                  U5      nU R                  U5      nU R                  U5      nUR                  u  pn
UR                  u  pn
UR	                  XU R
                  U R                  5      R                  SS5      nUR	                  XU R
                  U R                  5      R                  SS5      nUR	                  XU R
                  U R                  5      R                  SS5      n[        nU R                  R                  S:w  aT  U R                  R                  S:X  a  U(       a  [        R                  S5        O[        U R                  R                     nU" U UUUU4SU R                  S.UD6u  pUR                  XS5      R!                  5       nU R#                  U5      nU(       d  S nX4$ )	Nr   rt   eagersdpa`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.        r   r   r*   )r   r   r   r,   r.   r   r   rH   r   rP   _attn_implementationloggerwarning_oncer   r   rG   r   r   )r^   ra   rJ   r   r   r   r   r   r8   	q_seq_lenr:   
kv_seq_lenattention_interfacer   r   s                  r>   rf   MllamaVisionAttention.forward   s    L)kk,'L)#(;; 
q99q

:$..$--PZZ[\^_`hhzt~~t}}MWWXY[\]

:4>>4==Q[[\]_`a(?;;++w6{{//69>O##L
 '>dkk>^>^&_#$7	%
 LL	%
 	%
! "))*DOOQkk+. L((r@   )
rP   r   r   r   r   r   r   r   r   r   NN)rh   ri   rj   rk   r    rU   r2   rl   r   r3   r   rf   rm   rn   ro   s   @r>   r   r      sr    \1 \$ 26,0	.)ll.) !..) $D>	.) 
u||Xell33	4.) .)r@   r   c                      ^  \ rS rSrS
S\S\4U 4S jjjr  SS\R                  S\	\R                     S\	\   4S jjr
S	rU =r$ )MllamaVisionEncoderLayeri  rP   rQ   c                   > [         TU ]  5         UR                  U l        UR                  U l        X l        UR                  U l        [        U5      U l        [        U5      U l
        [        R                  " U R                  UR                  S9U l        [        R                  " U R                  UR                  S9U l        U(       a  [        R                   " ["        R$                  " S5      [&        R(                  -  S-  5      U l        [        R                   " ["        R$                  " S5      [&        R(                  -  S-  5      U l        g g )Nepsr      )rT   rU   rV   r   num_attention_headsrQ   r   r   	self_attnr   mlpr   	LayerNormnorm_epsinput_layernormpost_attention_layernormrZ   r2   onesmathpi	gate_attngate_ffnr]   s      r>   rU   !MllamaVisionEncoderLayer.__init__  s    !--#)#9#9  !'!9!9.v6"6*!||D,<,<&//R(*T5E5E6??([%\\%**Q-$''*AA*EFDNLLA)@1)DEDM r@   ra   rJ   r   c                 |   UnU R                  U5      nU R                  XS9u  pU R                  (       a  U R                  R	                  5       U-  nXA-   nUnU R                  U5      nU R                  U5      nU R                  (       a  U R                  R	                  5       U-  nXA-   nU4nU(       a  Xe4-  nU$ )N)rJ   )r   r   rQ   r   rd   r   r   r   )r^   ra   rJ   r   residualr   outputss          r>   rf    MllamaVisionEncoderLayer.forward.  s      ++L9%)^^L^%`"==>>..0<?L.  44\Bxx-====--/,>L./&Gr@   )
r   r   rV   r   r   rQ   r   r   r   r   Fr   )rh   ri   rj   rk   r    r3   rU   r2   rl   r   rf   rm   rn   ro   s   @r>   r   r     s_    F1 FT F F* 26,0	ll !. $D>	 r@   r   c                      ^  \ rS rSrSrSS\4U 4S jjjr    SS\R                  S\	\R                     S\	\
   S\	\
   S	\	\
   S
\\\4   4S jjrSrU =r$ )MllamaVisionEncoderiL  z
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`MllamaEncoderLayer`].

Args:
    config: MllamaConfig
rP   c           	         > [         TU ]  5         Xl        [        R                  " [        U5       Vs/ s H  n[        X5      PM     sn5      U l        SU l        Xl        g s  snf )NF)	rT   rU   rP   r   
ModuleListranger   layersgradient_checkpointing)r^   rP   
num_layersrQ   r:   r_   s        r>   rU   MllamaVisionEncoder.__init__U  sU    mmY^_iYj$kYjTU%=f%OYj$kl&+# %ls   A"r   rJ   r   output_hidden_statesreturn_dictr&   c                 *   Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nU(       a  SOSnU(       a  SOSnU R                   Hl  nU(       a  Xa4-   nU R
                  (       a0  U R                  (       a  U R                  UR                  UUU5      n	OU" UUUS9n	U(       a  XyS   4-   nU	S   nMn     U(       a  Xa4-   nU(       d  [        S XU4 5       5      $ [        XUS9$ )a  
Args:
    inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
        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.
    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)
    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.
N )ra   rJ   r   r   r   c              3   .   #    U  H  oc  M  Uv   M     g 7fr   r   .0vs     r>   	<genexpr>.MllamaVisionEncoder.forward.<locals>.<genexpr>  s     e$Sq$S   	last_hidden_stater   
attentions)rP   r   r   use_return_dictr   r   r   _gradient_checkpointing_func__call__tupler   )
r^   r   rJ   r   r   r   encoder_statesall_attentionsencoder_layerlayer_outputss
             r>   rf   MllamaVisionEncoder.forward\  s!   < 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]30d![[M#!/2B!B**t}} $ A A!**!"%	! !.!.#1&7! !!/3C2E!E)!,M) ),  +.>>Ne]N$Seee+Vd
 	
r@   )rP   r   r   )    F)NNNN)rh   ri   rj   rk   __doc__r    rU   r2   rl   r   r3   r   r   r   rf   rm   rn   ro   s   @r>   r   r   L  s    1   26,0/3&*D
||D
 !.D
 $D>	D

 'tnD
 d^D
 
uo%	&D
 D
r@   r   c                   8   ^  \ rS rSrSU 4S jjrS rS rSrU =r$ )MllamaTextRMSNormi  c                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z0
MllamaTextRMSNorm is equivalent to T5LayerNorm
N)rT   rU   r   rZ   r2   r   weightvariance_epsilon)r^   rV   r   r_   s      r>   rU   MllamaTextRMSNorm.__init__  s/     	ll5::k#:; #r@   c                    UR                   nUR                  [        R                  5      nUR	                  S5      R                  SSS9nU[        R                  " X0R                  -   5      -  nU R                  UR                  U5      -  $ )Nrt   r*   T)keepdim)	r%   r0   r2   r   powmeanrsqrtr  r
  )r^   r   input_dtypevariances       r>   rf   MllamaTextRMSNorm.forward  sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::r@   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)r   r
  r,   r  r^   s    r>   
extra_reprMllamaTextRMSNorm.extra_repr  s*    ))*+6$2G2G1HIIr@   )r  r
  )gư>)	rh   ri   rj   rk   rU   rf   r  rm   rn   ro   s   @r>   r  r    s    $;J Jr@   r  c                   N  ^  \ rS rSrSr  SS\\   S\\   4U 4S jjjr      SS\	R                  S\\	R                     S\\   S	\\	R                     S
\S\\   S\\	R                     S\\	R                  \\	R                     \\\	R                        4   4S jjrSrU =r$ )MllamaTextCrossAttentioni  z=Multi-headed attention from 'Attention Is All You Need' paperrP   	layer_idxc                   > [         TU ]  5         Xl        U R                  R                  U l        U R                  R
                  U l        UR                  U l        UR                  U l        UR                  U R                  -  U l        X l	        U R                  U R
                  -  U l
        U R                  S-  U l        [        R                  " U R                  U R                  U R                  -  SS9U l        [        R                  " U R                  U R
                  U R                  -  SS9U l        [        R                  " U R                  U R
                  U R                  -  SS9U l        [        R                  " U R                  U R                  -  U R                  SS9U l        [%        U R                  UR&                  S9U l        [%        U R                  UR&                  S9U l        g )Nru   Fr   r   )rT   rU   rP   r   r   r   r   rV   r   r  r   r   r   r   r   r   r   r   r  rms_norm_epsq_normk_normr^   rP   r  r_   s      r>   rU   !MllamaTextCrossAttention.__init__  sg   
 	88#';;#B#B ~~!--**dnn<"$(NNd6N6N$N!}}d*ii 0 0$..4==2PW\]ii 0 0$2J2JT]]2Zafgii 0 0$2J2JT]]2Zafgii >@P@PW\]'6;N;NO'6;N;NOr@   r   cross_attention_statespast_key_valuerJ   r   	use_cachecache_positionr&   c                    UR                  5       u  pnU R                  U5      nUR                  XU R                  U R                  5      R                  SS5      nU R                  U5      nUb  U R                  U5      nU R                  U5      nUR                  U	SU R                  U R                  5      R                  SS5      nUR                  U	SU R                  U R                  5      R                  SS5      nU R                  U5      nUb!  UR                  XU R                  SU05      u  pOFUS   S:w  a2  UR                  U R                     UR                  U R                     pO[        S5      e[         nU R"                  R$                  S:w  aT  U R"                  R$                  S	:X  a  U(       a  [&        R)                  S
5        O[*        U R"                  R$                     nU" U UUUU4U R,                  (       d  SOU R.                  U R0                  S.UD6u  nnUR3                  XS5      R5                  5       nU R7                  U5      nU(       d  SnUUU4$ )z#Input shape: Batch x Time x Channelr   rt   Nr*   r%  r   z^Cross attention layer can't find neither `cross_attn_states` nor cached values for key/values!r   r   r   r   r   )sizer   r.   r   r   rH   r  r   r   r   r  updater  	key_cachevalue_cache
ValueErrorr   rP   r   r   r   r   r   r   r   rG   r   r   )r^   r   r"  r#  rJ   r   r$  r%  r   bszq_lenr:   query_statesr   r   r   r   r   s                     r>   rf    MllamaTextCrossAttention.forward  sF    &**,A{{=1#((T^^T]]S]]^_abc{{<0!-%;<J;;'=>L#b$2J2JDMMZddefhijJ',,S"d6N6NPTP]P]^hhijlmnLZ0J) ,:+@+@dnn?OQ_>`,(
 A!#((8**4>>: %
 p  )@;;++w6{{//69>O##L
 '>dkk>^>^&_#$7	%
  $}}C$,,LL	%
 	%
!\ "))#b9DDFkk+. LL.88r@   )rP   r   r   rV   r  r   r  r   r   r   r   r  r   r   r   r   )NNNFNN)rh   ri   rj   rk   r  r   r   intrU   r2   rl   r   r3   
LongTensorr   rf   rm   rn   ro   s   @r>   r  r    s    G .2#'P)*P C=P P6 :>*.15"'$(59D9||D9 !) 6D9 !	D9
 !.D9  D9 D>D9 !!1!12D9 
u||Xell3XeELL>Q5RR	SD9 D9r@   r  c                     U SSU R                   S   S-  24   nU SU R                   S   S-  S24   n[        R                  " U* U4SS9$ )z*Rotates half the hidden dims of the input..Nr*   rt   r(   )r,   r2   cat)xx1x2s      r>   rotate_halfr7    sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r@   c                     UR                  U5      nUR                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nXg4$ )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/   r7  )qkcossinposition_idsunsqueeze_dimq_embedk_embeds           r>   apply_rotary_pos_embrA  #  sS    ( --
&C
--
&Cw;q>C/0Gw;q>C/0Gr@   c                      ^  \ rS rSrS\S\4U 4S jjr    SS\R                  S\R                  S\R                  S\	S	\	4
S
 jjr
SrU =r$ )MllamaTextSelfAttentioni>  rP   r  c                 d  > [         TU ]  5         Xl        UR                  U l        UR
                  U l        UR                  U l        UR                  U l        UR                  U R                  -  U l        U R                  U R                  -  U l	        U R                  S-  U l
        UR                  U l        X l        [        R                  " U R                  U R                  U R                  -  SS9U l        [        R                  " U R                  U R                  U R                  -  SS9U l        [        R                  " U R                  U R                  U R                  -  SS9U l        [        R                  " U R                  U R                  -  U R                  SS9U l        g )Nru   Fr   )rT   rU   rP   r   r   r   rV   r   r   r   r   
rope_thetar  r   r   r   r   r   r   r   s      r>   rU    MllamaTextSelfAttention.__init__?  s:   33~~!--#)#=#= **dnn<$(NNd6N6N$N!}}d* ++"ii 0 0$..4==2PW\]ii 0 0$2J2JT]]2Zafgii 0 0$2J2JT]]2Zafgii >@P@PW\]r@   r   rJ   position_embeddingsr   r$  c                 (   UR                  5       u  pnU R                  U5      nU R                  U5      nU R                  U5      nUR	                  XU R
                  U R                  5      R                  SS5      nUR	                  XU R                  U R                  5      R                  SS5      nUR	                  XU R                  U R                  5      R                  SS5      nUu  nn[        XUU5      u  pUb$  UXS.nUR                  XU R                  U5      u  p[        nU R                  R                  S:w  aT  U R                  R                  S:X  a  U(       a  [        R!                  S5        O["        U R                  R                     nU" U UUUU4U R$                  (       d  SOU R&                  U R(                  S.UD6u  nnUR+                  XS	5      R-                  5       nU R/                  U5      nU(       d  S nUUU4$ )
Nr   rt   )r<  r;  r%  r   r   r   r   r   r*   )r'  r   r   r   r.   r   r   rH   r   rA  r(  r  r   rP   r   r   r   r   r   r   r   rG   r   r   )r^   r   rJ   rG  r   r$  r#  r%  r   r,  r-  r:   r.  r   r   r;  r<  cache_kwargsr   r   r   s                        r>   rf   MllamaTextSelfAttention.forwardQ  s    &**,A{{=1[[/
{{=1#((T^^T]]S]]^_abc__S1I1I4==Yccdeghi
#((T5M5Mt}}]gghiklm&S#7RUWZ#[ %#&sUL'5'<'<ZW[WeWegs't$J(?;;++w6{{//69>O##L
 '>dkk>^>^&_#$7	%
  $}}C$,,LL	%
 	%
!\ "))#b9DDFkk+. LL.88r@   )rP   r   r   rV   r   r  r   r   r   r   r   rE  r   r   )FFNN)rh   ri   rj   rk   r   r0  rU   r2   rl   r3   rf   rm   rn   ro   s   @r>   rC  rC  >  sn    ^/ ^C ^. #(99||99 99 #\\	99
  99 99 99r@   rC  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )MllamaTextMLPi  c                   > [         TU ]  5         Xl        UR                  U l        UR                  U l        [
        R                  " U R                  U R                  SS9U l        [
        R                  " U R                  U R                  SS9U l        [
        R                  " U R                  U R                  SS9U l	        [        UR                     U l        g NFr   )rT   rU   rP   rV   r   r   r   	gate_projup_proj	down_projr
   r   act_fnr   s     r>   rU   MllamaTextMLP.__init__  s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../r@   c                     U R                  U R                  U R                  U5      5      U R                  U5      -  5      nU$ r   )rQ  rR  rO  rP  )r^   r4  rQ  s      r>   rf   MllamaTextMLP.forward  s6    NN4;;t~~a/@#ADLLQRO#ST	r@   )rR  rP   rQ  rO  rV   r   rP  )rh   ri   rj   rk   rU   rf   rm   rn   ro   s   @r>   rL  rL    s    	0 r@   rL  c                      ^  \ rS rSrS\S\4U 4S jjr          SS\R                  S\	\R                     S\	\R                     S\	\R                     S	\	\
\R                  \R                  4      S
\	\R                     S\	\   S\	\   S\	\   S\	\R                     S\	\
\R                  \R                  4      S\\   S\
\R                   \	\
\R                   \R                   4      4   4S jjrSrU =r$ )MllamaSelfAttentionDecoderLayeri  rP   r  c                   > [         TU ]  5         UR                  U l        [        XS9U l        [        U5      U l        [        UR                  UR                  S9U l	        [        UR                  UR                  S9U l
        X l        g )N)rP   r  r   )rT   rU   rV   rC  r   rL  r   r  r  r   r   r  r   s      r>   rU   (MllamaSelfAttentionDecoderLayer.__init__  sp    !--0T (01C1CI\I\](9&:L:LRXReRe(f%"r@   r   r"  r#   rJ   r=   r=  r#  r   r$  r%  rG  r   r&   c                     UnU R                  U5      nU R                  " SUUUUUU	U
US.UD6u  pnX-   nUnU R                  U5      nU R                  U5      nX-   nU4nU(       a  UU4-  nU	(       a  UU4-  nU$ )a  
Args:
    hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
    attention_mask (`torch.FloatTensor`, *optional*):
        attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
        query_sequence_length, key_sequence_length)` if default attention is used.
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
    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`).
    past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
    cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
        Indices depicting the position of the input sequence tokens in the sequence
    position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
        Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
        with `head_dim` being the embedding dimension of each attention head.
    kwargs (`dict`, *optional*):
        Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
        into the model
)r   rJ   r=  r#  r   r$  r%  rG  r   )r   r   r   r   )r^   r   r"  r#   rJ   r=   r=  r#  r   r$  r%  rG  r   r   self_attn_weightspresent_key_valuer   s                    r>   rf   'MllamaSelfAttentionDecoderLayer.forward  s    J !,,]; ?Cnn 
?
')%)/) 3
?
 
?
;*; !0 !55mD/ 0 ")++G)++Gr@   )rV   r   r  r   r   r   )
NNNNNNFFNN)rh   ri   rj   rk   r   r0  rU   r2   rl   r   r   r1  r   r3   r   r   FloatTensorrf   rm   rn   ro   s   @r>   rW  rW    sp   
#/ 
#C 
# :>7;15UY37*.,1$)59KOE||E !) 6E 'u||4	E
 !.E (0ellELL6P0Q'RE u//0E !E $D>E D>E !!1!12E &eELL%,,,F&GHE -.E 
u  (51B1BEDUDU1U+V"WW	XE Er@   rW  c                     ^  \ rS rSrSrS\S\SS4U 4S jjr      SS\R                  S	\R                  S
\R                  S\R                  S\
\R                  \R                  4   S\\R                     S\\   S\\   S\\   S\\R                     S\\R                     S\\   S\
\R                     4S jjrSrU =r$ ) MllamaCrossAttentionDecoderLayeri  zLCross-attention transformer block with tanh-gated attention and feedforward.rP   r  r&   Nc                   > [         TU ]  5         X l        [        XS9U l        [        UR                  UR                  S9U l        [        R                  R                  [        R                  " S5      5      U l        [        U5      U l        [        UR                  UR                  S9U l        [        R                  R                  [        R                  " S5      5      U l        g )N)r  r   r   )rT   rU   r  r  
cross_attnr  rV   r  r   r2   r   rZ   r[   cross_attn_attn_gaterL  r   r   cross_attn_mlp_gater   s      r>   rU   )MllamaCrossAttentionDecoderLayer.__init__  s    "26O01C1CI\I\]$)HH$6$6u{{1~$F! ((9&:L:LRXReRe(f%#(88#5#5ekk!n#E r@   r   r"  r#   rJ   r=   r=  r#  r   r$  r%  rG  r   c           
      |   UnU R                  U5      nU R                  " SUUUUUU
S.UD6u  pnXR                  R                  5       U-  -   nUnU R	                  U5      nU R                  U5      nUb  US S 2S4   U-  nXR                  R                  5       U-  -   nU4nU(       a  X4-  nU	(       a  X4-  nU$ )N)r   rJ   r"  r#  r   r%  r   r   )r   rb  rc  rd   r   r   rd  )r^   r   r"  r#   rJ   r=   r=  r#  r   r$  r%  rG  r   r   r   r   s                   r>   rf   (MllamaCrossAttentionDecoderLayer.forward  s     !,,];6:oo 7
'/#9)/)7
 7
3^ !#<#<#A#A#Cm#SS 55mD/(49!Q$?-OM #;#;#@#@#B]#RR "&G((Gr@   )rb  rc  rd  r   r  r   r   )NNFFNN)rh   ri   rj   rk   r  r   r0  rU   r2   rl   r   r   r1  r   r3   r   r   rf   rm   rn   ro   s   @r>   r`  r`    s   V
F/ 
FC 
FD 
F& 48*.,1$)596:,||, !&, $ll	,
 , (-U\\5<<-G'H, u//0, !, $D>, D>, !!1!12, &ell3, -., 
u||	, ,r@   r`  c                   l   ^  \ rS rSrSS\4U 4S jjjr\R                  " 5       \S 5       5       r	Sr
U =r$ )MllamaRotaryEmbeddingi3  rP   c                 T  > [         TU ]  5         UR                  S   U l        UR                  U l        UR                  U l        Xl        [        U R                     U l	        U R                  U R                  U5      u  o0l
        U R                  SUSS9  U R                  U l        g )N	rope_typeinv_freqF)
persistent)rT   rU   rope_scalingrk  max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrP   r   rope_init_fnattention_scalingregister_bufferrl  original_inv_freq)r^   rP   devicerl  r_   s       r>   rU   MllamaRotaryEmbedding.__init__4  s    ,,[9"("@"@$*$B$B!/?+/+<+<T[[&+Q((ZeD!%r@   c                 0   U R                   S S S 2S 4   R                  5       R                  UR                  S   SS5      nUS S 2S S S 24   R                  5       n[	        UR
                  R                  [        5      (       a0  UR
                  R                  S:w  a  UR
                  R                  OSn[        R                  " USS9   UR                  5       UR                  5       -  R                  SS5      n[        R                  " Xf4SS	9nUR                  5       U R                  -  nUR                  5       U R                  -  n	S S S 5        WR                  UR                   S
9W	R                  UR                   S
94$ ! , (       d  f       N@= f)Nr   r*   r   mpscpuF)device_typeenabledrt   r(   )r%   )rl  floatr   r,   
isinstancerv  typestrr2   autocastrH   r3  r;  rs  r<  r0   r%   )
r^   r4  r=  inv_freq_expandedposition_ids_expandedr{  freqsembr;  r<  s
             r>   rf   MllamaRotaryEmbedding.forward@  s@    !MM$4-8>>@GGHZHZ[\H]_acde ,QaZ 8 > > @'1!((--'E'E!((--[`J`ahhmmfk^^UC&,,.1F1L1L1NNYYZ[]^_E))UN3C'')d444C'')d444C	 D vvAGGv$cff177f&;;; DCs   BF
F)rs  rP   rp  ru  rq  rr  rk  r   )rh   ri   rj   rk   r   rU   r2   no_gradr   rf   rm   rn   ro   s   @r>   ri  ri  3  s7    
// 
/ 
/ ]]_<  <r@   ri  c                      \ rS rSr\rSrSr/ SQrSr	Sr
SrSrSrSrS r SS\\R$                  S4   S	\R$                  S
\R$                  S\S\4
S jjr\S\R$                  S\S\S\R0                  S
\R$                  S\4S j5       rSrg)MllamaPreTrainedModeliP   T)r   r`  rW  Fc                    [        U R                  SU R                  R                  5       R                  5      n[	        U[
        R                  [
        R                  45      (       aW  UR                  R                  R                  SUS9  UR                  b%  UR                  R                  R                  5         g g [	        U[
        R                  5      (       ad  UR                  R                  R                  SUS9  UR                  b2  UR                  R                  UR                     R                  5         g g [	        U[
        R                  5      (       aJ  UR                  R                  R!                  S5        UR                  R                  R                  5         g [	        U["        5      (       a&  UR                  R                  R!                  S5        g [	        U[$        5      (       a3  [
        R&                  R                  UR(                  R                  US9  g [	        U[*        5      (       af  [
        R&                  R                  UR,                  R                  US9  [
        R&                  R/                  UR0                  R                  5        g [	        U[2        5      (       av  UR4                  (       ae  [
        R&                  R                  UR6                  R                  US9  [
        R&                  R                  UR8                  R                  US9  g [	        U[:        5      (       aI  UR<                  R                  R                  5         UR>                  R                  R                  5         g [	        U[@        5      (       a7  UR4                  (       a%  UR0                  R                  R                  5         g g g )Ninitializer_ranger   )r  stdr+   )r  )!getattrrP   get_text_configr  r~  r   r   Conv2dr
  datanormal_r   zero_rX   padding_idxr   fill_r  MllamaVisionModelinitclass_embeddingrq   rY   zeros_r\   r   rQ   r   r   r`  rc  rd  rN   )r^   r   r  s      r>   _init_weights#MllamaPreTrainedModel._init_weightsa  s   dkk#68S8S8U8g8ghfryy"))455MM&&CS&9{{&  &&( '--MM&&CS&9!!-""6#5#56<<> .--MM$$S)KK""$ 122MM$$S) 122GGOOF2277SOA BCCGGOOF,,11sO;GGNN6;;++, 899fooGGOOF,,11sO;GGOOFOO00cO: @AA'',,224&&++113 EFF  &&(  Gr@   rJ   r!   input_tensorr%  past_key_valuesr   c           	         U R                   R                  S:X  a  Ub  US:H  R                  5       (       a  U$ g U R                   R                  S:X  a,  [        U[        R
                  5      (       a  [        U5      nU$ Ub  UR                  5       OSnUb  UR                  OSnU R                   R                  S:X  a5  U(       d.  U(       d'  [        R                  " UUUU R                  S9(       a  g UR                  nUR                  S   n	U(       a  UR                  5       n
O5[        U[        R
                  5      (       a  UR                  S	   OXi-   S-   n
U R                  UU	U
UUUR                  S   S
9nU R                   R                  S:X  aZ  UbW  UR                   R"                  S;   a=  U(       d6  [        R$                  " U5      R&                  n[        R(                  " X5      nU$ )Nflash_attention_2r   flex_attentionr   Fr   )inputs_embedspast_key_values_lengthis_trainingr   r*   )sequence_lengthrC   r%   r%  r8   )cudaxpunpu)rP   r   r6   r~  r2   rl   r"   get_seq_lengthis_compileabler   _ignore_causal_mask_sdpar   r%   r,   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionrv  r  r4   r5   _unmask_unattended)r^   rJ   r  r%  r  r   past_seen_tokensusing_compilable_cacher%   r  rC   r   	min_dtypes                r>   _update_causal_mask)MllamaPreTrainedModel._update_causal_mask  s    ;;++/BB)~/D.I.I.K.K%%;;++/??.%,,77!<^!L!!
 @O?Z?99;`aCRC^!?!?di ;;++v5>T]n%>>*'7 MM	 ""&,,Q/!+??AM nell;; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCK[Kr@   r  rC   r%   r8   c                    U b  U R                  5       S:X  a  U nU$ [        R                  " U5      R                  n[        R                  " X4XUR
                  S9nUS:w  a  [        R                  " USS9nU[        R                  " X$R
                  S9UR                  SS5      :  -  nUSSSS2SS24   R                  USSS5      nU b  UR                  5       nU R                  S   n	USS2SS2SS2SU	24   U SS2SSSS24   R                  UR
                  5      -   n
U
S:H  n
USS2SS2SS2SU	24   R                  X5      USS2SS2SS2SU	24'   U$ )	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.
    cache_position (`torch.Tensor`):
        Indices depicting the position of the input sequence tokens in the sequence.
    batch_size (`torch.Tensor`):
        Batch size.
Nr   )
fill_valuer%   rv  r   )diagonalrv  r*   r   )r)   r2   r4   r5   fullrv  triuarangerG   r   cloner,   r0   r1   )rJ   r  rC   r%   r%  r8   r   r   r  mask_lengthpadding_masks              r>   r  KMllamaPreTrainedModel._prepare_4d_causal_attention_mask_with_cache_position  s}   > %.*<*<*>!*C(K* ' E*..I** 0Y\j\q\qK !##jjqA5<<>S>STWeWmWmnprsWtttK%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@   r   Nr   )rh   ri   rj   rk   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_cache_class_supports_static_cache_supports_sdpa_supports_flash_attn_2_supports_quantized_cache_supports_attention_backendr  r   r2   rl   r   r3   r  staticmethodr0  r%   r  rm   r   r@   r>   r  r  P  s    L&*#
 !"N! $"&)L #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4r@   r  zH
    The Mllama Vision Model which consists of two vision encoders.
    )custom_introc                   (  ^  \ rS rSr\rSrS\4U 4S jjrS rS\	R                  S\	R                  4S jr\   SS	\	R                  S
\	R                  S\	R                  S\\   S\\   S\\   S\\\\	R                  S4   4   4S jj5       rSrU =r$ )r  i  vision_modelrP   c           	        > [         TU ]  U5        UR                  U l        UR                  U l        UR                  U l        UR
                  U l        UR                  U l        UR                  U l        U R                  U R                  -  S-  S-   U l        UR
                  S-  U l	        [        R                  " UR                  U R
                  U R                  U R                  SSS9U l        [        R                  " U R                  [        R                  " U R
                  5      -  5      U l        [#        U5      U l        ['        USS9U l        ['        USS9U l        [        R,                  " U R
                  5      U l        [        R,                  " U R
                  5      U l        [3        XR4                  SS9U l        [3        XR8                  SS9U l        U R=                  5         g )	Nrt   r   ru   validF)in_channelsout_channelskernel_sizestridepaddingr   T)rQ   )rT   rU   rv   rw   rI   rV   num_channelsintermediate_layers_indicesrB   rx   r   r  patch_embeddingrZ   r2   ry   r  rq   gated_positional_embeddingrN   pre_tile_positional_embeddingpost_tile_positional_embeddingr   layernorm_prelayernorm_postr   num_hidden_layerstransformernum_global_layersglobal_transformer	post_initr   s     r>   rU   MllamaVisionModel.__init__  s     ++ ++#11!--"//+1+M+M( OOt>1DqH''-
!yy++))?? 
  "||DJJTEUEU9V,VW*LV*T'-RSYdh-i*.STZei.j+  \\$*:*:; ll4+;+;< /v7O7OZ_`"5f>V>Vae"fr@   c                     U R                   $ )zW
This function is used to fetch the first embedding layer to activate grads on inputs.
)r  r  s    r>   get_input_embeddings&MllamaVisionModel.get_input_embeddings,  s     ###r@   ra   r&   c                     UR                   u  p#nU R                  R                  USU5      n[        R                  " XQ/SS9nU$ )Nr   r(   )r,   r  r   r2   r3  )r^   ra   r8   r:   rV   r  s         r>   apply_class_embedding'MllamaVisionModel.apply_class_embedding2  sE    %1%7%7"
{..55j![Qyy/!@aHr@   pixel_valuesrb   rA   r   r   r   .c                 6   Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUR                  u  pxppUR                  Xx-  U	-  XU5      nUR                  Xx-  S5      nU R                  R                  R                  nU R                  R                  R                  nU R                  UR                  X5      5      nUR                  S5      R                  SS5      nUR                  u  nnnUR                  Xx-  U	SU5      nU R                  UU5      nUR                  Xx-  U	-  UU5      nU R                  U5      nUS-  nUR                  Xx-  U	UU5      nU R                  UU5      nU R!                  U5      nSUR                  S   S-  -
  S-  nSSSU4n["        R$                  " UUSSS	9nUS:  a  U* OSnUR                  Xx-  S5      n['        UU R(                  UR                  S   U R                  S
9nUR+                  Xx-  SU5      nU R-                  UUSUS9nUS   nU R/                  U5      nUR                  Xx-  U	UU-   U5      nU R1                  UU5      nUR                  Xx-  U	UU-   -  U5      nU R3                  UUUUS9nUS   nUR                  Xx-  U	UU-   U5      nUSS2SS2SU24   nUR                  XxU	UU5      nU R4                   Vs/ s H  nUS   U   PM     nn[6        R8                  " USS9nUR                  Xx-  U	UU-   S5      nUSS2SS2SU24   nUR                  XxU	US5      n[6        R:                  " UU/SS9nU(       a  [=        U5      [=        US   5      -   nOSnU(       a5  U(       a  [=        US   5      O[=        US   5      n[=        US   5      U-   nOSnU(       d  [=        S UUU4 5       5      $ [?        UUUS9$ s  snf )aM  
aspect_ratio_ids (`torch.Tensor` of shape `(batch_size, max_num_images)`, *optional*):
    Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image.
    These ids correspond to indices in the model's list of supported aspect ratios, offset by 1.

    For example, if the model supports aspect ratios [[1, 1], [1, 2], [2, 1]]:
    - An image with aspect ratio [1, 1] would have ID 1
    - An image with aspect ratio [1, 2] would have ID 2
    - An image with aspect ratio [2, 1] would have ID 3

    The id 0 is reserved for padding (i.e., no image).

    If an image has aspect ratio [1, 2], that means it was split into 2 tiles horizontally, and its `aspect_ratio_id` would be 2.
aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*):
    Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`:

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

Example:

```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, MllamaVisionModel

>>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
>>> model = MllamaVisionModel.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)

>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(images=image, return_tensors="pt")

>>> output = model(**inputs)

>>> print(output.last_hidden_state.shape)
torch.Size([1, 1, 4, 1025, 7680])
```
Nr*   rt   r      rE   r   constant)moder   )rA   rB   rC   r%   T)rJ   r   r   r(   c              3   .   #    U  H  oc  M  Uv   M     g 7fr   r   r   s     r>   r   ,MllamaVisionModel.forward.<locals>.<genexpr>  s     _$Mq$Mr   r   ) rP   r   r   r   r,   rG   r  r
  r%   rv  r0   flattenrH   r  r  r  r  FpadrL   rB   r.   r  r  r  r  r  r2   stackr3  r   r   ) r^   r  rb   rA   r   r   r   r8   num_concurrent_media	num_tilesr  heightwidthtarget_dtypetarget_devicepatch_embedsra   r:   rB   r)   num_padding_patchesr  slice_indexrJ   outputglobal_outputiall_intermediate_hidden_statesintermediate_hidden_statesr   global_attnr   s                                    r>   rf   MllamaVisionModel.forward8  s   d 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]S_SeSeP
)6#++J,MPY,Y[gqvw+33J4UWYZ ++2288,,33::++LOOM,XY#++A.88A> +00;#++J,MyZ\^ab99,HXY $++J,MPY,Y[fhkl11,?q $++J,MyZegjk66|EUV)),7  !L$6$6r$:Q$>?1Da/0uu\71M.AA.E**4 +22:3TVXY=,((&,,Q/**	
 $(()JBPST!!)!%/	 " 
 ay**<8 $++-y+H[:[]`
 ::<IYZ#++-yKJ]<]/^`c
 //)!5/	 0 
 %Q' $++-y+H[:[]`
 $Aq,;,$67#++JiYdfij AE@`@`)a@`1&)A,@`&)a%*[[1OUW%X" &@%G%G-y+H[:[]_&
" &@1l{l@R%S"%?%G%Gib&
"
 yy,0J!KQST!"@AE-XYJZD[[M M5I%a 01uUbcdUeOfKvay)K7JJ_\=*$M___*'!
 	
= *bs   P)r  r  r  rV   rv   r  r  r  rI   r  rB   r  rw   r  r  rx   r  )NNN)rh   ri   rj   rk   r    r  r  rU   r  r2   rl   r  r   r   r3   r   r   r   rf   rm   rn   ro   s   @r>   r  r    s     &L&#1 #J$%,, 5<<   -1/3&*i
lli
  ,,i
 !<<	i

 $D>i
 'tni
 d^i
 
ellC&7 88	9i
 i
r@   r  zc
    The Mllama Text Model which consists of transformer with self and cross attention layers.
    c            "         ^  \ rS rSr\rSrS\4U 4S jjrS rS r	\
             SS\\R                     S\\R                     S	\\R                     S
\\R                     S\\R                     S\\\R                  \R                  4      S\\\\\R                     4      S\\R                     S\\   S\\   S\\   S\\   S\\R                     S\\   S\\\4   4S jj5       rSrU =r$ )MllamaTextModeli  language_model.modelrP   c                   > [         TU ]  U5        UR                  U l        UR                  U l        [
        R                  " UR                  S-   UR                  U R                  5      U l        UR                  U l	        / n[        UR                  5       HH  nX0R                  ;   a  UR                  [        X5      5        M.  UR                  [        X5      5        MJ     [
        R                  " U5      U l        [#        UR                  UR$                  S9U l        [)        US9U l        SU l        U R/                  5         g )Nr  r   )rP   F)rT   rU   pad_token_idr  
vocab_sizer   rX   rV   embed_tokenscross_attention_layersr   r  appendr`  rW  r   r   r  r  normri  
rotary_embr   r  )r^   rP   r   r  r_   s       r>   rU   MllamaTextModel.__init__  s     !.. ++LL):):Q)>@R@RTXTdTde&,&C&C#v778I777>vQR=fPQ	 9 mmF+%f&8&8f>Q>QR	/v>&+#r@   c                     U R                   $ r   r  r  s    r>   r  $MllamaTextModel.get_input_embeddings  s       r@   c                     Xl         g r   r  r^   r   s     r>   set_input_embeddings$MllamaTextModel.set_input_embeddings  s    !r@   	input_idsrJ   r=  r"  r#   r=   r  r  r$  r   r   r   r%  r   r&   c                    U
b  U
OU R                   R                  n
Ub  UOU R                   R                  nU	b  U	OU R                   R                  n	Ub  UOU R                   R                  nUSL USL-  (       a  [        S5      eU R                  (       a/  U R                  (       a  U	(       a  [        R                  S5        Sn	Uc  U R                  U5      nUnU	(       a  Uc
  [        5       nUcE  Ub  UR                  5       OSn[        R                  " UUUR                  S   -   UR                   S9nUc  UR#                  S5      nU R%                  X(XU
5      nU R'                  X5      nU(       a  SOSnU
(       a  SOSnSn[)        U R*                  5       H  u  nnU(       a  UU4-  nUU R,                  ;   nUSL =(       d    USL=(       a    UR                  U5      S:H  nU(       a  Uc	  U(       a  M_  U R                  (       a8  U R                  (       a'  U R/                  UR0                  UUUUUUUU
U	UU5      nOU" U4UUUUUUU
U	UUS	.
UD6nUS   nU	(       a  UU
(       a  S
OS   nU
(       d  M  UUS   4-  nM     U R3                  U5      nU(       a  UU4-  nU	(       a  UOSnU(       d  [5        S UUUU4 5       5      $ [7        UUUUS9$ )aY  
cross_attention_states (`torch.FloatTensor`, *optional*):
    Output of the vision model, used for cross-attention. This tensor contains the processed image features that
    the language model will attend to.
cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
    Cross-attention mask to control the interaction between text tokens and image tiles.
    This 4D tensor defines which image tiles each text token should attend to.

    For each text token (in seq_length):
    - 1 indicates the token **should attend** to the corresponding image tile
    - 0 indicates the token **should not attend** to the corresponding image tile
full_text_row_masked_out_mask (`Tuple[torch.Tensor, torch.Tensor]`, *optional*):
    A tuple containing two tensors that mask out rows in the cross-attention mechanism:
    - The first tensor has shape `(batch_size, 1, seq_length, 1)` and contains values of 0 or 1.
      A value of 0 indicates that the corresponding text token's entire row in the cross-attention
      matrix should be masked out (all image tokens ignored).
    - The second tensor has the same shape and is used internally to apply the masking during
      the forward pass of cross-attention layers.
    This mask is derived from the cross_attention_mask and is used to handle cases where a text token
    should not attend to any image token.

Example:

```python
>>> from transformers import AutoProcessor, MllamaTextModel

>>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
>>> model = MllamaTextModel.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)

>>> text = "<|image|>If I had to write a haiku for this one"
>>> inputs = processor(text=text, return_tensors="pt")

>>> output = model(**inputs)

>>> print(output.last_hidden_state.shape)
torch.Size([1, 13, 4096])
```
N:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.Fr   r   r  r   )
r"  r#   rJ   r=   r=  r#  r   r$  r%  rG  rt   c              3   .   #    U  H  oc  M  Uv   M     g 7fr   r   r   s     r>   r   *MllamaTextModel.forward.<locals>.<genexpr>  s     t$bq$br   r   r  r   r   )rP   r   r   r$  r   r+  r   r   r   r   r  r   r  r2   r  r,   rv  r/   r  r  	enumerater   r	  r   r   r  r   r   )r^   r  rJ   r=  r"  r#   r=   r  r  r$  r   r   r   r%  r   r   r  r   rG  all_hidden_statesall_self_attnsnext_decoder_cacheidxdecoder_layeris_cross_attention_layeris_cross_attention_cache_emptyr  
next_caches                               r>   rf   MllamaTextModel.forward  s    r 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]-t";<YZZ&&4==Yj I  --i8M%0*nO!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L..>L]

 #oomJ #7BD0d!"+DKK"8C#!m%55!
 (+d.I.I'I$-<-D .t+X0N0Ns0SWX0X + (,B,JOm**t}} $ A A!**!*(1 #%"'! !.!!+A)=#.2O!-#2&7'#1(;! ! *!,M%28I1q%Q"  =#3"55i #9l 		-0  -!11+4'$
t]J@QSa$bttt&+&+%	
 	
r@   )r	  r  r   r   r  r  r  r  )NNNNNNNNNNNNN)rh   ri   rj   rk   r   r  r  rU   r  r  r   r   r2   r1  rl   r^  r   r   r   r   r3   r   r   r   rf   rm   rn   ro   s   @r>   r  r    s    $L./ (!"  151537>B7;UYKO59$(,0/3&*59i
E,,-i
 !.i
 u//0	i

 !)):): ;i
 'u||4i
 (0ellELL6P0Q'Ri
 "%tE4E4E/F(F"GHi
   1 12i
 D>i
 $D>i
 'tni
 d^i
 !!1!12i
 -.i
  
u--	.!i
 i
r@   r  c                       \ rS rSrSrg)KwargsForCausalLMi  r   N)rh   ri   rj   rk   rm   r   r@   r>   r&  r&    s    3r@   r&  zE
    The Mllama Text Model with a language modeling head on top.
    c            &       P  ^  \ rS rSr\rSrSrS/rU 4S jr	S r
S rS rS	 rS
 rS r\               SS\\R&                     S\\R(                     S\\R&                     S\\R&                     S\\R&                     S\\\R(                  \R(                  4      S\\\\\R2                     4      S\\R2                     S\\R&                     S\\   S\\   S\\   S\\   S\\R&                     S\\\R(                  4   S\\   S\\\4   4"S jj5       rSr U =r!$ ) MllamaForCausalLMi  Tlanguage_modellm_head.weightc                 z  > [         TU ]  UR                  5       5        UR                  5       U l        U R                  R                  U l        [
        R                  U R                  5      U l        [        R                  " U R                  R                  U R                  SS9U l        U R                  5         g rN  )rT   rU   r  text_configr  r  _from_configmodelr   r   rV   lm_headr  r   s     r>   rU   MllamaForCausalLM.__init__  s    //12!113**55$11$2B2BC
yy!1!1!=!=tUZ[r@   c                 .    U R                   R                  $ r   r.  r  r  s    r>   r  &MllamaForCausalLM.get_input_embeddings  s    zz&&&r@   c                 $    XR                   l        g r   r2  r  s     r>   r  &MllamaForCausalLM.set_input_embeddings  s    "'

r@   c                     U R                   $ r   r/  r  s    r>   get_output_embeddings'MllamaForCausalLM.get_output_embeddings      ||r@   c                     Xl         g r   r7  r^   new_embeddingss     r>   set_output_embeddings'MllamaForCausalLM.set_output_embeddings      %r@   c                     Xl         g r   r.  )r^   decoders     r>   set_decoderMllamaForCausalLM.set_decoder  s    
r@   c                     U R                   $ r   rB  r  s    r>   get_decoderMllamaForCausalLM.get_decoder  s    zzr@   r  rJ   r=  r"  r#   r=   r  r  labelsr$  r   r   r   r%  logits_to_keepr   r&   c                 Z   Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nU R                  " SUUUUUUUUU
UUUUS.UD6nUS   n[        U[        5      (       a  [        U* S5      OUnU R                  USS2USS24   5      R                  5       nSnU	b  U R                  " UXR                  40 UD6nU(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                  UR                  S9$ )a	  
cross_attention_states (`torch.FloatTensor`, *optional*):
    Output of the vision model, used for cross-attention. This tensor contains the processed image features that
    the language model will attend to.
cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
    Cross-attention mask to control the interaction between text tokens and image tiles.
    This 4D tensor defines which image tiles each text token should attend to.

    For each text token (in seq_length):
    - 1 indicates the token **should attend** to the corresponding image tile
    - 0 indicates the token **should not attend** to the corresponding image tile
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]`.
full_text_row_masked_out_mask (`Tuple[torch.Tensor, torch.Tensor]`, *optional*):
    A tuple containing two tensors that mask out rows in the cross-attention mechanism:
    - The first tensor has shape `(batch_size, 1, seq_length, 1)` and contains values of 0 or 1.
      A value of 0 indicates that the corresponding text token's entire row in the cross-attention
      matrix should be masked out (all image tokens ignored).
    - The second tensor has the same shape and is used internally to apply the masking during
      the forward pass of cross-attention layers.
    This mask is derived from the cross_attention_mask and is used to handle cases where a text token
    should not attend to any image token.

Example:

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

>>> model = MllamaForCausalLM.from_pretrained("Llama-3.2-11B-Vision")
>>> tokenizer = AutoTokenizer.from_pretrained("Llama-3.2-11B-Vision")

>>> prompt = "If I had to write a haiku, it would be:"
>>> inputs = tokenizer(prompt, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=40, do_sample=True, temperature=0.6)
>>> result = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
>>> print(result)
If I had to write a haiku, it would be: "Snowflakes gently fall" - simple, yet peaceful.
I love the idea of snowflakes gently falling, each one
```
N)r  r"  rJ   r=  r#   r=   r  r  r$  r   r   r   r%  r   r   losslogitsr  r   r   r   )rP   r   r   r   r.  r~  r0  slicer/  r}  loss_functionr  r   r  r   r   )r^   r  rJ   r=  r"  r#   r=   r  r  rI  r$  r   r   r   r%  rJ  r   r   r   slice_indicesrN  rM  r  s                          r>   rf   MllamaForCausalLM.forward  se   @ 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] ** 
#9)%!5*G+'/!5#)
 
"  
8B>SV8W8W~ot4]kmA}a,?@AGGI%%ffooPPDY,F'+'7D7V#CVC%#33!//))
 	
r@   )r/  r.  r,  r  )NNNNNNNNNNNNNNr   )"rh   ri   rj   rk   r   r  r  r  _tied_weights_keysrU   r  r  r8  r>  rD  rG  r   r   r2   r1  rl   r   r   r   r   r^  r3   r0  r   r&  r   rf   rm   rn   ro   s   @r>   r(  r(    s    $L!(*+'(&  151537=A;?UYKO59-1$(,0/3&*5934!i
E,,-i
 !.i
 u//0	i

 !))9)9 :i
 'u'7'78i
 (0ellELL6P0Q'Ri
 "%tE4E4E/F(F"GHi
   1 12i
 ))*i
 D>i
 $D>i
 'tni
 d^i
 !!1!12i
  c5<</0!i
" *+#i
$ 
u,,	-%i
 i
r@   r(  zr
    The Mllama model which consists of a vision encoder and a language model without language modeling head.
    c            '         ^  \ rS rSrSS0rSrS\4U 4S jjrS rS r	\
\               SS	\\R                     S
\\R                     S\\R                      S\\R                      S\\R                      S\\R                      S\\R                      S\\R                     S\\\R                        S\\R                     S\\   S\\   S\\   S\\   S\\R                     S\\   S\\\4   4"S jj5       5       rSrU =r$ )MllamaModeliK  r  r)  FrP   c                   > [         TU ]  U5        UR                  R                  U l        UR                  R                  U l        UR
                  R                  U l        UR
                  R                  U l        U R                  R                  b  U R                  R                  OSU l	        [        R                  UR
                  5      U l        [        R                  UR                  5      U l        [        R                   " UR
                  R                  UR                  R                  SS9U l        U R%                  5         g )Nr*   Tr   )rT   rU   r,  r  rV   vision_configrI   vision_output_dimrP   r  r  r-  r  r  r)  r   r   multi_modal_projectorr  r   s     r>   rU   MllamaModel.__init__T  s      ,,77!--99#11??!'!5!5!G!G8<8P8P8\DKK44bd-::6;O;OP-::6;M;MN%'YY  22**&
"
 	r@   c                 6    U R                   R                  5       $ r   )r)  r  r  s    r>   r   MllamaModel.get_input_embeddingse  s    ""7799r@   c                 :    U R                   R                  U5        g r   )r)  r  r  s     r>   r   MllamaModel.set_input_embeddingsh  s    007r@   r  r  rA   rb   rJ   r#   r"  r=  r  r  r$  r   r   r   r%  r   r&   c                 (   Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUSL U
SL-  (       a  [	        S5      eUb  U
b  [	        S5      eUb  Ub  [	        S5      eUb`  Uc  [	        S5      eU R                  UUUUUUS9nUS   nU R                  U5      R                  SUR                  S	   U R                  5      nUb-  [        UU R
                  R                  U R                  S
9u  nnOSnUb  Ub  USS2SS2U4   nUSS2SS2U4   nU R                  " SUUUUUUU	UU
UUSUS.UD6n[        UR                  UR                   UR"                  UR$                  S9$ )a  
aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*):
    Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`:

    - 1 for tiles that are **not masked**,
    - 0 for tiles that are **masked**.
aspect_ratio_ids (`torch.Tensor` of shape `(batch_size, max_num_images)`, *optional*):
    Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image.
    These ids correspond to indices in the model's list of supported aspect ratios, offset by 1.

    For example, if the model supports aspect ratios [[1, 1], [1, 2], [2, 1]]:
    - An image with aspect ratio [1, 1] would have ID 1
    - An image with aspect ratio [1, 2] would have ID 2
    - An image with aspect ratio [2, 1] would have ID 3

    The id 0 is reserved for padding (i.e., no image).

    If an image has aspect ratio [1, 2], that means it was split into 2 tiles horizontally, and its `aspect_ratio_id` would be 2.
cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
    Cross-attention mask to control the interaction between text tokens and image tiles.
    This 4D tensor defines which image tiles each text token should attend to.

    For each text token (in seq_length):
    - 1 indicates the token **should attend** to the corresponding image tile
    - 0 indicates the token **should not attend** to the corresponding image tile
cross_attention_states (`torch.FloatTensor`, *optional*):
    Output of the vision model, used for cross-attention. This tensor contains the processed image features that
    the language model will attend to.
Nr  zdYou cannot specify both pixel_values and inputs_embeds at the same time, and must specify either onezM`pixel_values` and `cross_attention_states` cannot be provided simultaneouslyzA`aspect_ratio_ids` must be provided if `pixel_values` is provided)r  rb   rA   r   r   r   r   r*   rE   )r$   r%   T)r  rJ   r=  r"  r#   r=   r  r$  r  r   r   r   r%  r  r   )rP   r   r   r   r+  r  rY  rG   r,   rV   r?   rB   r%   r)  r   r   r  r   r   )r^   r  r  rA   rb   rJ   r#   r"  r=  r  r  r$  r   r   r   r%  r   vision_outputsr=   r   s                       r>   rf   MllamaModel.forwardk  s   d 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]-t";<YZZ#(Av  #(>(Jlmm#' !dee!..)!1"3%9"3' / N &4A%6"%)%?%?@V%W%_%_*004d6F6F&"  +B_$"&"3"3"?"?jjC? "? -1)+0J#71n8L#M ,I!QP^J^,_)%% 
)%#9!5*G+'!5/)
 
" '%77#33!//))	
 	
r@   )rV   r)  rI   rY  r  r  rX  r  )NNNNNNNNNNNNNNN)rh   ri   rj   rk   _checkpoint_conversion_mappingr  r   rU   r  r  r   r   r   r2   r1  r^  rl   r   r3   r   r   r   r   r   rf   rm   rn   ro   s   @r>   rU  rU  K  s    '=>N%O" %| ":8  15484837157;9=37=A59$(,0/3&*59!u
E,,-u
 u001u
 $ELL1	u

 #5<<0u
 !.u
 'u||4u
 !) 6u
 u//0u
 "$u'8'8"9:u
   1 12u
 D>u
 $D>u
 'tnu
 d^u
  !!1!12!u
" -.#u
$ 
u,,	-%u
  u
r@   rU  zS
    The Mllama model which consists of a vision encoder and a language model.
    c            +         ^  \ rS rSrSSSSS.rSrS/rS	\4U 4S
 jjrS r	S r
S rS r\S 5       r\S 5       r\\                 S(S\\R(                     S\\R*                     S\\R,                     S\\R,                     S\\R,                     S\\R,                     S\\R,                     S\\R(                     S\\\\\R*                     4      S\\R*                     S\\R(                     S\\   S\\   S\\   S\\   S \\R(                     S!\\\R,                  4   S"\\   S#\\\4   4&S$ jj5       5       r             S)U 4S% jjr!U 4S& jr"S'r#U =r$$ )*MllamaForConditionalGenerationi  zmodel.language_modelzmodel.vision_modelzmodel.multi_modal_projectorr/  )z^language_model.modelz^vision_modelz^multi_modal_projectorz^language_model.lm_headFr*  rP   c                    > [         TU ]  U5        [        U5      U l        [        R
                  " UR                  R                  UR                  R                  SS9U l	        U R                  5         g rN  )rT   rU   rU  r.  r   r   r,  rV   r  r/  r  r   s     r>   rU   'MllamaForConditionalGeneration.__init__  sS      (
yy!3!3!?!?ASASA^A^ejkr@   c                 6    U R                   R                  5       $ r   )r.  r  r  s    r>   r  3MllamaForConditionalGeneration.get_input_embeddings  s    zz..00r@   c                 :    U R                   R                  U5        g r   )r.  r  r  s     r>   r  3MllamaForConditionalGeneration.set_input_embeddings  s    

''.r@   c                     U R                   $ r   r7  r  s    r>   r8  4MllamaForConditionalGeneration.get_output_embeddings   r:  r@   c                     Xl         g r   r7  r<  s     r>   r>  4MllamaForConditionalGeneration.set_output_embeddings  r@  r@   c                 .    U R                   R                  $ r   )r.  r)  r  s    r>   r)  -MllamaForConditionalGeneration.language_model  s    zz(((r@   c                 .    U R                   R                  $ r   )r.  r  r  s    r>   r  +MllamaForConditionalGeneration.vision_model  s    zz&&&r@   r  r  rA   rb   rJ   r#   r"  r=  r  r  rI  r$  r   r   r   r%  rJ  r   r&   c                 4   Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nU R                  " SUUUUUUUUU	U
UUUSUS.UD6nUS   n[        U[        5      (       a  [        U* S5      OUnU R                  USS2USS24   5      nSnUb2  U R                  " UXR                   R                  R                  40 UD6n[        UUUR                  UR                  UR                  S9$ )a  
aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*):
    Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`:

    - 1 for tiles that are **not masked**,
    - 0 for tiles that are **masked**.
aspect_ratio_ids (`torch.Tensor` of shape `(batch_size, max_num_images)`, *optional*):
    Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image.
    These ids correspond to indices in the model's list of supported aspect ratios, offset by 1.

    For example, if the model supports aspect ratios [[1, 1], [1, 2], [2, 1]]:
    - An image with aspect ratio [1, 1] would have ID 1
    - An image with aspect ratio [1, 2] would have ID 2
    - An image with aspect ratio [2, 1] would have ID 3

    The id 0 is reserved for padding (i.e., no image).

    If an image has aspect ratio [1, 2], that means it was split into 2 tiles horizontally, and its `aspect_ratio_id` would be 2.
cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
    Cross-attention mask to control the interaction between text tokens and image tiles.
    This 4D tensor defines which image tiles each text token should attend to.

    For each text token (in seq_length):
    - 1 indicates the token **should attend** to the corresponding image tile
    - 0 indicates the token **should not attend** to the corresponding image tile
cross_attention_states (`torch.FloatTensor`, *optional*):
    Output of the vision model, used for cross-attention. This tensor contains the processed image features that
    the language model will attend to.
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]`.

Example:

```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, MllamaForConditionalGeneration

>>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
>>> model = MllamaForConditionalGeneration.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)

>>> prompt = "<|image|>If I had to write a haiku for this one"
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> inputs = processor(text=prompt, images=image, return_tensors="pt")

>>> # Generate
>>> output = model.generate(**inputs, max_new_tokens=15)

>>> prompt_len = inputs.input_ids.shape[-1]
>>> generated_ids = output[:, prompt_len:]
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
>>> print(generated_text)
[', it would be:.\\nA stop sign in Chinatown.\\n']
```
NT)r  r  rA   rb   r#   r"  rJ   r=  r  r  r$  r   r   r   r%  r   rL  r   )rP   r   r   r   r.  r~  r0  rO  r/  rP  r,  r  r   r  r   r   )r^   r  r  rA   rb   rJ   r#   r"  r=  r  r  rI  r$  r   r   r   r%  rJ  r   r   r   rQ  rN  rM  s                           r>   rf   &MllamaForConditionalGeneration.forward  sA   f 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]** 
%/-!5#9)%+'/!5)
  !
&  
8B>SV8W8W~ot4]kmA}a,?@A%%ffkk6M6M6X6Xc\bcD%#33!//))
 	
r@   c                 r   > [         TU ]  " U4U	U
UUUUUUUUUS.UD6nUS   S:w  a  S US'   S US'   S US'   U$ )N)r  r$  r  r=  rJ   r  rb   rA   r#   r%  rJ  r   r  rb   rA   )rT   prepare_inputs_for_generation)r^   r  r  rJ   r=  r  rb   rA   r#   r  r$  r%  rJ  r   model_inputsr_   s                  r>   rv  <MllamaForConditionalGeneration.prepare_inputs_for_generation  s|    $ w<
+'%)%-/!5))
 
$ !!+/L(/3L+,04L,-r@   c                    > UR                  SS 5      n[        TU ]  " SUUUS.UD6nUb#  [        R                  " XUS S 2SS 2S4   /SS9US'   U$ )Nr#   )r   model_kwargsis_encoder_decoderr*   .r   r(   r   )getrT   #_update_model_kwargs_for_generationr2   r3  )r^   r   rz  r{  r   cross_attention_mask_prevr_   s         r>   r}  BMllamaForConditionalGeneration._update_model_kwargs_for_generation  sx    $0$4$45KT$R!wB 
%1
 	
 %03899*ack,RSYZ4L/0 r@   )r/  r.  )NNNNNNNNNNNNNNNNr   )NNNNNNNNNFNN)%rh   ri   rj   rk   rb  r  rS  r   rU   r  r  r8  r>  propertyr)  r  r   r   r   r2   r1  r^  rl   r   r   r   r3   r0  r   r&  r   r   rf   rv  r}  rm   rn   ro   s   @r>   rd  rd    s    "8-"?#,	&" !&*+| 1/& ) ) ' '  15484837157;9=37KO59-1$(,0/3&*5934%y
E,,-y
 u001y
 $ELL1	y

 #5<<0y
 !.y
 'u||4y
 !) 6y
 u//0y
 "%tE4E4E/F(F"GHy
   1 12y
 ))*y
 D>y
 $D>y
 'tny
  d^!y
" !!1!12#y
$ c5<</0%y
& *+'y
( 
u,,	-)y
  y
z !)V r@   rd  )rd  r(  r  r  r  rU  )r   rS   )Wr  r   typingr   r   r   r   r   r2   torch.nn.functionalr   r   r  torch.utils.checkpointactivationsr
   cache_utilsr   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   configuration_mllamar   r   r    !torch.nn.attention.flex_attentionr!   integrations.flex_attentionr"   
get_loggerrh   r   rl   r0  r  r?   r%   rL   ModulerN   rq   r   r   r}  r   r   r   r   r  r  r7  rA  rC  rL  rW  r`  ri  r  r  r  r&  r(  rU  rd  __all__r   r@   r>   <module>r     sq     9 9      ! . ) > B ` ` K F & h h T T  !!;J 
		H	%?,,?? ? 5<<%&	?8||  ;;	
 \\6BII ." "Lbii  	UU\\ 	U# 	U%,, 	U( %II%<<% 
% <<	%
 U\\*% % %4>)BII >)B.ryy .bT
")) T
pJ		 J(_9ryy _9F(6L9bii L9`BII $Rbii Rj;uxx ;|<BII <: jO j jZ 
_
- _

_
D 
H
+ H

H
V ?,j > 
K
- K

K
\ 
R
' R

R
j 
[%:O [
[|r@   