
    g             
       T   d Z ddlZddlmZmZmZmZ ddlZddlm	c m
Z ddlZddlm	Z	 ddlmZ ddlmZ ddlmZmZ dd	l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m Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z&  e!j'        e(          Z)dej*        de+de,deej*        ej*        f         fdZ-dej*        de+de+dej.        dej*        f
dZ/ G d de	j0                  Z1 G d de	j0                  Z2 G d de	j0                  Z3 G d d e	j0                  Z4 G d! d"e4          Z5e4e5d#Z6 G d$ d%e	j0                  Z7 G d& d'e	j0                  Z8 G d( d)e	j0                  Z9 G d* d+e	j0                  Z: G d, d-e:          Z;d. Z<dQd/Z=d0ej*        d1e+dej*        fd2Z> G d3 d4e	j0                  Z? G d5 d6e?          Z@e:e;d#ZAe?e@d#ZB G d7 d8e	j0                  ZC G d9 d:e	j0                  ZD G d; d<ej	        j0                  ZE G d= d>e	j0                  ZF G d? d@e          ZGdAZHdBZIdCZJdDZK edEeH           G dF dGeG                      ZL edHeH           G dI dJeG                      ZM edKeH           G dL dMeGe                      ZN edNeH           G dO dPeGe                      ZOdS )RzPyTorch Mllama model.    N)ListOptionalTupleUnion)nn   )PreTrainedModel)ACT2FN)CacheStaticCache)GenerationMixin)AttentionMaskConverter)BaseModelOutputBaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONS)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )MllamaConfigMllamaTextConfigMllamaVisionConfigcross_attention_masknum_vision_tokensdtypereturnc                 
   | j         ^}}}|                     |d          } |                     ||d          } |                     d          } d| z
                      |          }|                    |                    t          j                  t          j        |          j	                  } t          j        |          j	        }| |k    
                    d                              |           d         }| |z  } | |fS )Nr   dimr   g      ?).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	            f/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/mllama/modeling_mllama.py_prepare_cross_attention_maskr6   ,   s    )=(B%J!A/AABSYZA[[/44ZARTVWW/99!<< !$&: :>>uEE3?? ##EJ//U1C1C1G  U++/	!3	388R8@@HHI]^^_hi " 99!>>>    aspect_ratio_masknum_patchestarget_lengthc                    | j         \  }}|                     ||dd                              |          }|                    dd|d          }||z
  }d|d d d d | d f<   d|z
  }|                    |||z  d          }||                    dd          z  t          j        |          j        z  }|	                    d          }|S )Nr   r   r"   )
r#   r%   r'   repeatreshape	transposer)   r+   r,   r&   )r8   r9   r:   r   r/   max_num_tilesattention_maskpad_patchess           r5   $_prepare_aspect_ratio_attention_maskrC   H   s     !2 7J&++Jq!LLOOPUVVN#**1aBBN  +-K*+N111aaa+&' 'N $++J8UWXYYN#n&>&>r2&F&FFUZI[I[I__N#--a00Nr7   c                   \     e Zd Zd	dedef fdZdej        dej        dej        fdZ xZ	S )
%MllamaPrecomputedAspectRatioEmbeddingTconfigis_gatedc                 Z   t                                                       |j        | _        |j        | _        |j        | _        || _        t          j        | j        dz   | j        | j        z            | _        |r-t          j	        t          j        d                    | _        d S d S Nr   )super__init__r@   hidden_sizemax_aspect_ratio_idrG   r   	Embedding	embedding	Parameterr)   zerosgateselfrF   rG   	__class__s      r5   rK   z.MllamaPrecomputedAspectRatioEmbedding.__init__d   s    #1!-#)#=  d&>&BDDVY]YiDijj 	5U[^^44DIII	5 	5r7   hidden_stateaspect_ratio_idsr   c                     |                      |          }|                    d| j        d| j                  }| j        r|| j                                        z  }||z   }|S )Nr"   r   )rO   r>   r@   rL   rG   rR   tanh)rT   rV   rW   
embeddingss       r5   forwardz-MllamaPrecomputedAspectRatioEmbedding.forwardo   sc    ^^$455
''D,>4CSTT
= 	7#dinn&6&66J#j0r7   )T)
__name__
__module____qualname__r   r*   rK   r)   Tensorr[   __classcell__rU   s   @r5   rE   rE   c   s        	5 	51 	5T 	5 	5 	5 	5 	5 	5EL EL UZUa        r7   rE   c                   V     e Zd Zdef fdZdej        dej        dej        fdZ xZS )"MllamaPrecomputedPositionEmbeddingrF   c                 &   t                                                       |j        | _        |j        | _        |j        |j        z  dz  dz   | _        |j        | _        |j        dz  | _        t          j
        t          j        d                    | _        t          j        | j        | j                  }t          j
        | j        |z            | _        t          j        | j        dz   | j        | j        z  | j        z            | _        d S )N   r         )rJ   rK   r@   rM   
image_size
patch_sizer9   rL   scaler   rP   r)   rQ   rR   randnrO   rN   tile_embedding)rT   rF   position_embeddingrU   s      r5   rK   z+MllamaPrecomputedPositionEmbedding.__init__{   s    #1#)#= "-1BBqH1L!-'-
LQ00	 #[)94;KLLdj3E&EFF !l$q($*<t?O*ORVRb*b
 
r7   rV   rW   r   c                 l   d| j                                         z
  | j        z  }||                    dd| j        | j                  z   }|                     |          }|j        d         }|                    || j	        | j        | j                  }| j                                         |z  }||z   }|S )Nr   r   )
rR   rY   rO   r%   r9   rL   rk   r#   r>   r@   )rT   rV   rW   gated_position_embeddingtile_position_embeddingr/   gated_tile_position_embeddings          r5   r[   z*MllamaPrecomputedPositionEmbedding.forward   s    $%	(8(8$8DN#J #&>&C&CAq$JZ\`\l&m&mm #'"5"56F"G"G!'*
"9"A"A*D,<d>N#
 #
 )-	(8(8;R(R%#&CCr7   )	r\   r]   r^   r   rK   r)   r_   r[   r`   ra   s   @r5   rc   rc   z   sv        
1 
 
 
 
 
 
&EL EL UZUa        r7   rc   c                   B     e Zd Z fdZdej        dej        fdZ xZS )MllamaVisionMLPc                    t                                                       || _        t          |j                 | _        t          j        |j        |j	                  | _
        t          j        |j	        |j                  | _        d S N)rJ   rK   rF   r
   
hidden_actactivation_fnr   LinearrL   intermediate_sizefc1fc2rT   rF   rU   s     r5   rK   zMllamaVisionMLP.__init__   sf    #F$569V/1IJJ9V5v7IJJr7   hidden_statesr   c                     |                      |          }|                     |          }|                     |          }|S rt   )ry   rv   rz   )rT   r|   s     r5   r[   zMllamaVisionMLP.forward   s=    //**=99//r7   )r\   r]   r^   rK   r)   r_   r[   r`   ra   s   @r5   rr   rr      sc        K K K K KU\ el        r7   rr   c            	       l     e Zd Zdef fdZ	 	 d	dej        deej                 dedej        fdZ	 xZ
S )
MllamaVisionAttentionrF   c                    t                                                       |j        | _        |j        | _        |j        |j        z  | _        t          j        | j        | j        | j        z  d          | _	        t          j        | j        | j        | j        z  d          | _
        t          j        | j        | j        | j        z  d          | _        t          j        | j        | j        z  | j        d          | _        d S NFbias)rJ   rK   rL   	embed_dimattention_heads	num_headshead_dimr   rw   q_projk_projv_projo_projr{   s     r5   rK   zMllamaVisionAttention.__init__   s    +/*f.DDi0NUZ[[[i0NUZ[[[i0NUZ[[[i >UZ[[[r7   NrV   rA   output_attentionsr   c                 ,   |                      |          }|                     |          }|                     |          }|j        \  }}}	|j        \  }	}
}	|                    ||| j        | j                                      dd          }|                    ||
| j        | j                                      dd          }|                    ||
| j        | j                                      dd          }t          j	        ||                    dd                    t          j        | j                  z  }|$|d d d d d d d |j        d         f         }||z   }t          j                            |dt          j                                      |j                  }t          j	        ||          }|                    dd                                          }|                    ||d          }|                     |          }|sd }||fS )Nr   re   r   r<   r"   r!   r   )r   r   r   r#   r%   r   r   r?   r)   matmulmathsqrtr   
functionalsoftmaxfloat32r'   r   
contiguousr>   r   )rT   rV   rA   r   querykeyvaluer/   	q_seq_lenr1   
kv_seq_lenattn_weightscausal_maskattn_outputoutputs                  r5   r[   zMllamaVisionAttention.forward   s    L))kk,''L))#(; 
Iq9:q

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

:z4>4=QQ[[\]_`aa|E3==A+>+>??$)DMBZBZZ%(AAAqqq/CIbM/)ABK'+5L },,\r,WWZZ[`[fggl<77!++Aq11<<>>!))*iDD[))  	 L|##r7   NN)r\   r]   r^   r   rK   r)   r_   r   r*   r[   r`   ra   s   @r5   r   r      s        
\1 
\ 
\ 
\ 
\ 
\ 
\ 26"&	#$ #$l#$ !.#$  	#$
 
#$ #$ #$ #$ #$ #$ #$ #$r7   r   c            	       `     e Zd Z	 	 ddej        deej                 dedej        f fdZ xZS )MllamaVisionSdpaAttentionNrV   rA   r   r   c                 ^   |r>t                               d           t                                          |||          S |                     |          }|                     |          }|                     |          }|j        \  }}}	|j        \  }	}
}	|                    ||| j	        | j
                  }|                    ||
| j	        | j
                  }|                    ||
| j	        | j
                  }|                    dd          }|                    dd          }|                    dd          }t          j        ||||          }|                    dd                                          }|                    ||d          }|                     |          }|d fS )Na  MllamaModel is using MllamaVisionSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.rV   rA   r   r   re   )	attn_maskr"   )loggerwarning_oncerJ   r[   r   r   r   r#   r%   r   r   r?   Fscaled_dot_product_attentionr   r>   r   )rT   rV   rA   r   r   r   r   r/   r   r1   r   r   r   rU   s                r5   r[   z!MllamaVisionSdpaAttention.forward   s     		[   77??)-"3 #    L))kk,''L))#(; 
Iq9:q

:y$.$-PPhhz:t~t}MM

:z4>4=QQ1%%mmAq!!1%%4UCR`aaa!++Aq11<<>>!))*iDD[))t|r7   r   )	r\   r]   r^   r)   r_   r   r*   r[   r`   ra   s   @r5   r   r      s{        
 26"&	( (l( !.(  	(
 
( ( ( ( ( ( ( ( ( (r7   r   )eagersdpac                   d     e Zd Zd
dedef fdZ	 	 ddej        deej                 defd	Z	 xZ
S )MllamaVisionEncoderLayerFrF   rG   c                    t                                                       |j        | _        |j        | _        || _        |j        | _        t          |j                 |          | _	        t          |          | _        t          j        | j        |j                  | _        t          j        | j        |j                  | _        |rxt          j        t%          j        d          t(          j        z  dz            | _        t          j        t%          j        d          t(          j        z  dz            | _        d S d S )Nepsr      )rJ   rK   rL   r   num_attention_headsrG   rx   MLLAMA_VISION_ATTENTION_CLASSES_attn_implementation	self_attnrr   mlpr   	LayerNormnorm_epsinput_layernormpost_attention_layernormrP   r)   onesr   pi	gate_attngate_ffnrS   s      r5   rK   z!MllamaVisionEncoderLayer.__init__  s   !-#)#9  !'!989TUV\]]"6**!|D,<&/RRR(*T5E6?([([([% 	F\%*Q--$'*AA*EFFDNLA)@1)DEEDMMM	F 	Fr7   NrV   rA   r   c                 v   |}|                      |          }|                     ||          \  }}| j        r| j                                        |z  }||z   }|}|                     |          }|                     |          }| j        r| j                                        |z  }||z   }|f}|r||fz  }|S )N)rA   )r   r   rG   r   rY   r   r   r   )rT   rV   rA   r   residualr   outputss          r5   r[   z MllamaVisionEncoderLayer.forward%  s      ++L99%)^^LQ_^%`%`"l= 	@>..00<?L,.  44\BBxx--= 	?=--//,>L,./ 	'&Gr7   )Fr   )r\   r]   r^   r   r*   rK   r)   r_   r   r[   r`   ra   s   @r5   r   r     s        F F1 FT F F F F F F* 26"&	 l !.  	       r7   r   c                        e Zd ZdZddef fdZ	 	 	 	 ddej        deej                 d	ee	         d
ee	         dee	         de
eef         fdZ xZS )MllamaVisionEncoderz
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`MllamaEncoderLayer`].

    Args:
        config: MllamaConfig
        FrF   c                     t                                                       | _        t          j        fdt          |          D                       | _        d| _        | _        d S )Nc                 0    g | ]}t                    S  )r   ).0r1   rF   rG   s     r5   
<listcomp>z0MllamaVisionEncoder.__init__.<locals>.<listcomp>O  s%    $k$k$kTU%=fh%O%O$k$k$kr7   F)rJ   rK   rF   r   
ModuleListrangelayersgradient_checkpointing)rT   rF   
num_layersrG   rU   s    ` `r5   rK   zMllamaVisionEncoder.__init__L  sh    m$k$k$k$k$kY^_iYjYj$k$k$kll&+#r7   Nr|   rA   r   output_hidden_statesreturn_dictr   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|rdnd}|rdnd}| j        D ]Z}|r||fz   }| j        r%| j        r|                     |j        |||          }	n ||||          }	|r||	d         fz   }|	d         }[|r||fz   }|st          d |||fD                       S t          |||          S )ad  
        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.
        Nr   r   r   r   c              3      K   | ]}||V  	d S rt   r   r   vs     r5   	<genexpr>z.MllamaVisionEncoder.forward.<locals>.<genexpr>  s(      eeqWXWdWdWdWdWdeer7   last_hidden_stater|   
attentions)rF   r   r   use_return_dictr   r   training_gradient_checkpointing_func__call__tupler   )
rT   r|   rA   r   r   r   encoder_statesall_attentionsencoder_layerlayer_outputss
             r5   r[   zMllamaVisionEncoder.forwardS  sr   < 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]3=0:d![ 	- 	-M# C!/=2B!B* t}  $ A A!*!"%	! ! !.!.#1&7! ! ! ! F!/=3C2E!E)!,MM 	?+}.>>N 	fee]NN$Seeeeee+>Vd
 
 
 	
r7   )r   F)NNNN)r\   r]   r^   __doc__r   rK   r)   r_   r   r*   r   r   r   r[   r`   ra   s   @r5   r   r   C  s          1       26,0/3&*D
 D
|D
 !.D
 $D>	D

 'tnD
 d^D
 
uo%	&D
 D
 D
 D
 D
 D
 D
 D
r7   r   c                   ,     e Zd Zd fd	Zd Zd Z xZS )MllamaTextRMSNormư>c                     t                                                       t          j        t	          j        |                    | _        || _        dS )z@
        MllamaTextRMSNorm is equivalent to T5LayerNorm
        N)rJ   rK   r   rP   r)   r   weightvariance_epsilon)rT   rL   r   rU   s      r5   rK   zMllamaTextRMSNorm.__init__  sD     	l5:k#:#:;; #r7   c                    |j         }|                    t          j                  }|                    d                              dd          }|t          j        || j        z             z  }| j        |                    |          z  S )Nre   r"   T)keepdim)	r   r'   r)   r   powmeanrsqrtr   r   )rT   r|   input_dtypevariances       r5   r[   zMllamaTextRMSNorm.forward  s|    #)%((77 $$Q'',,R,>>%Ht?T4T(U(UU{]--k::::r7   c                 H    t          | j        j                   d| j         S )Nz, eps=)r   r   r#   r   rT   s    r5   
extra_reprzMllamaTextRMSNorm.extra_repr  s&    )**II$2GIIIr7   )r   )r\   r]   r^   rK   r[   r   r`   ra   s   @r5   r   r     sb        $ $ $ $ $ $; ; ;J J J J J J Jr7   r   c                   ,    e Zd ZdZ	 	 ddee         dee         f fdZ	 	 	 	 	 	 ddej	        deej	                 d	ee
         d
eej	                 dededeej                 deej	        eej	                 eeej	                          f         fdZ xZS )MllamaTextCrossAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNrF   	layer_idxc                    t                                                       || _        | j        j        | _        | j        j        | _        |j        | _        |j        | _        |j        | j        z  | _        || _	        | j        | j        z  | _
        t          j        | j        | j        | j        z  d          | _        t          j        | j        | j        | j        z  d          | _        t          j        | j        | j        | j        z  d          | _        t          j        | j        | j        z  | j        d          | _        t#          | j        |j                  | _        t#          | j        |j                  | _        d S )NFr   r   )rJ   rK   rF   r   r   num_key_value_headsdropoutrL   r   r   num_key_value_groupsr   rw   r   r   r   r   r   rms_norm_epsq_normk_normrT   rF   r   rU   s      r5   rK   z!MllamaTextCrossAttention.__init__  sE   
 	8#';#B ~!-*dn<"$(Nd6N$N!i 0$.4=2PW\]]]i 0$2JT]2Zafgggi 0$2JT]2Zafgggi >@PW\]]]'6;NOOO'6;NOOOr7   Fr|   cross_attention_statespast_key_valuerA   r   	use_cachecache_positionr   c                     |                                 \  }}	}
|                     |          }|                    ||	| j        | j                                      dd          }|                     |          }||                     |          }|                     |          }|                    |d| j	        | j                                      dd          }|                    |d| j	        | j                                      dd          }t          || j                  }t          || j                  }|                     |          }|"|                    ||| j        d|i          \  }}n@|d         dk    r%|j        | j                 |j        | j                 }}nt#          d          t%          j        ||                    dd                    t)          j        | j                  z  }|$|ddddddd|j        d	         f         }||z   }t.          j                            |dt$          j        
                              |j                  }t.          j                            || j        | j                  }t%          j        ||          }|                    dd                                          }|                     ||	d          }| !                    |          }|sd}|||fS )#Input shape: Batch x Time x Channelr   re   Nr"   r   r   ^Cross attention layer can't find neither `cross_attn_states` nor cached values for key/values!r   r<   r   pr   )"sizer   r%   r   r   r?   r   r   r   r   	repeat_kvr   r   updater   	key_cachevalue_cache
ValueErrorr)   r   r   r   r#   r   r   r   r   r'   r   r   r   r   r>   r   )rT   r|   r   r   rA   r   r   r   bszq_lenr1   query_states
key_statesvalue_statesr   r   r   s                    r5   r[   z MllamaTextCrossAttention.forward  s    &**,,UA{{=11#((eT^T]SS]]^_abcc{{<00!-%;<<J;;'=>>L#b$2JDMZZddefhijjJ',,S"d6NPTP]^^hhijlmnnL":t/HIIJ$\43LMMLZ00J) ,:+@+@dn?OQ_>`, ,(
L A!##(8*4>: %JJ
 p   |L*2F2Fq!2L2LMMPTPYZ^ZgPhPhh%(AAAqqq2HJ4DR4H2H)HIK'+5L},,\r,WWZZ[g[mnn},,\T\TXTa,bbl<>>!++Aq11<<>>!))#ub99kk+..  	 LL.88r7   r   NNNFNN)r\   r]   r^   r   r   r   intrK   r)   r_   r   r*   
LongTensorr   r[   r`   ra   s   @r5   r   r     s-       GG .2#'P P)*P C=P P P P P P4 :>*.15"'5999 99|99 !) 699 !	99
 !.99  99 99 !!1299 
u|Xel3XeEL>Q5RR	S99 99 99 99 99 99 99 99r7   r   c                        e Zd ZdZ	 	 	 	 	 	 ddej        deej                 dee         deej                 ded	ed
eej	                 de
ej        eej                 ee
ej                          f         f fdZ xZS )MllamaTextCrossSdpaAttentiona  
    Mllama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `MllamaTextCrossAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFr|   r   r   rA   r   r   r   r   c           	         |rBt                               d           t                                          |||||||          S |                                \  }}	}
|                     |          }|                    ||	| j        | j                  	                    dd          }| 
                    |          }||                     |          }|                     |          }|                    |d| j        | j                  	                    dd          }|                    |d| j        | j                  	                    dd          }|"|                    ||| j        d|i          \  }}n@|d         dk    r%|j        | j                 |j        | j                 }}nt%          d	          t'          || j                  }t'          || j                  }|                     |          }|j        j        d
k    r>|<|                                }|                                }|                                }||	dk    rdnd}t2          j        j                            ||||| j        r| j        nd|          }|	                    dd                                          }|                    ||	d          }|                      |          }|d|fS )r  a  MllamaModel is using MllamaTextCrossSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.)r|   r   rA   r   r   r   r   r   re   Nr"   r   r   r  cudaTF        r   	dropout_p	is_causal)!r   r   rJ   r[   r  r   r%   r   r   r?   r   r   r   r   r  r   r	  r
  r  r  r   r   devicetyper   r)   r   r   r   r   r   r>   r   )rT   r|   r   r   rA   r   r   r   r  r  r1   r  r  r  r  r   rU   s                   r5   r[   z$MllamaTextCrossSdpaAttention.forward  s     	[   77??+'=--"3#- #    &**,,UA{{=11#((eT^T]SS]]^_abcc{{<00!-%;<<J;;'=>>L#b$2JDMZZddefhijjJ',,S"d6NPTP]^^hhijlmnnL) ,:+@+@dn?OQ_>`, ,(
L A!##(8*4>: %JJ
 p   z4+DEE
 t/HII[[,,
 #v--.2L'2244L#..00J'2244L +2uqyyDDe	h)FF$&*m<dll G 
 
 "++Aq11<<>>!))#ub99kk+..D.00r7   r  )r\   r]   r^   r   r)   r_   r   r   r*   r  r   r[   r`   ra   s   @r5   r  r    s          :>*.15"'59S1 S1|S1 !) 6S1 !	S1
 !.S1  S1 S1 !!12S1 
u|Xel3XeEL>Q5RR	SS1 S1 S1 S1 S1 S1 S1 S1 S1 S1r7   r  c                     | dd| j         d         dz  f         }| d| j         d         dz  df         }t          j        | |fd          S )z*Rotates half the hidden dims of the input..Nr"   re   r    )r#   r)   cat)xx1x2s      r5   rotate_halfr#  d  s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r7   c                     |                     |          }|                     |          }| |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#  )qkcossinposition_idsunsqueeze_dimq_embedk_embeds           r5   apply_rotary_pos_embr-  l  sc    ( --
&
&C
--
&
&C3w;q>>C/0G3w;q>>C/0GGr7   r|   n_repc                     | j         \  }}}}|dk    r| S | dddddddddf                             |||||          } |                     |||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)r#   expandr>   )r|   r.  batchr   slenr   s         r5   r  r    s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr7   c                   l     e Zd Zdedef fdZ	 	 	 	 ddej        dej        dej        d	ed
ef
dZ	 xZ
S )MllamaTextSelfAttentionrF   r   c                    t                                                       || _        |j        | _        |j        | _        |j        | _        |j        | _        |j        | j        z  | _        | j        | j        z  | _	        |j
        | _
        || _        t          j        | j        | j        | j        z  d          | _        t          j        | j        | j        | j        z  d          | _        t          j        | j        | j        | j        z  d          | _        t          j        | j        | j        z  | j        d          | _        d S r   )rJ   rK   rF   r   r   r   rL   r   r   r   
rope_thetar   r   rw   r   r   r   r   r   s      r5   rK   z MllamaTextSelfAttention.__init__  s   3~!-#)#= *dn<$(Nd6N$N! +"i 0$.4=2PW\]]]i 0$2JT]2Zafgggi 0$2JT]2Zafgggi >@PW\]]]r7   FNr|   rA   position_embeddingsr   r   c                 b   |                                 \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|\  }}t          ||||          \  }}|&|||d}|
                    ||| j        |          \  }}t          || j                  }t          || j                  }t          j        ||                    dd                    t!          j        | j                  z  }|$|d d d d d d d |j        d         f         }||z   }t&          j                            |dt          j                                      |j                  }t&          j                            || j        | j                  }t          j        ||          }|                    dd                                          }|                    |	|
d          }|                     |          }|sd }|||fS )	Nr   re   r(  r'  r   r   r<   r"   r   r  )r  r   r   r   r%   r   r   r?   r   r-  r  r   r  r   r)   r   r   r   r#   r   r   r   r   r'   r   r   r   r   r   )rT   r|   rA   r7  r   r   r   r   kwargsr  r  r1   r  r  r  r'  r(  cache_kwargsr   r   r   s                        r5   r[   zMllamaTextSelfAttention.forward  s    &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm&S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII|L*2F2Fq!2L2LMMPTPYZ^ZgPhPhh%(AAAqqq2HJ4DR4H2H)HIK'+5L },,\r,WWZZ[g[mnn},,\T\TXTa,bbl<>>!++Aq11<<>>!&&sE266kk+..  	 LL.88r7   FFNN)r\   r]   r^   r   r  rK   r)   r_   r*   r[   r`   ra   s   @r5   r4  r4    s        ^/ ^C ^ ^ ^ ^ ^ ^, #(39 39|39 39 #\	39
  39 39 39 39 39 39 39 39 39r7   r4  c                   \     e Zd Z	 	 	 	 d	dej        dej        dej        dedef
 fdZ xZS )
MllamaTextSelfSdpaAttentionFNr|   rA   r7  r   r   c                 d   |r;t                               d            t                      j        d|||||||d|S |                                \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j	        | j
                                      dd          }|                    |	|
| j        | j
                                      dd          }|                    |	|
| j        | j
                                      dd          }|\  }}t          ||||          \  }}|&|||d}|                    ||| j        |          \  }}t!          || j                  }t!          || j                  }|}||d d d d d d d |j        d         f         }|j        j        dk    r>|<|                                }|                                }|                                }||
dk    rdnd	}t,          j        j                            ||||| j        r| j        nd
|          }|                    dd                                          }|                    |	|
d          }|                     |          }|d |fS )Na  MllamaModel is using MllamaTextSelfSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.)r|   rA   r7  r   r   r   r   r   re   r9  r<   r  TFr  r  r"   r   )r   r   rJ   r[   r  r   r   r   r%   r   r   r?   r   r-  r  r   r  r   r#   r  r  r   r)   r   r   r   r   r   r   )rT   r|   rA   r7  r   r   r   r   r:  r  r  r1   r  r  r  r'  r(  r;  r   r  r   rU   s                        r5   r[   z#MllamaTextSelfSdpaAttention.forward  s     	[   #577? 	+-$7-"3#-	 	 	 	 	 &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm&S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII$%%aaaAAA/E1A"1E/E&EFK #v--+2I'2244L#..00J'2244L (/EAIIDD5	h)FF!&*m<dll G 
 
 "++Aq11<<>>!&&sE266kk+..D.00r7   r<  )r\   r]   r^   r)   r_   r*   r[   r`   ra   s   @r5   r>  r>    s         #(M1 M1|M1 M1 #\	M1
  M1 M1 M1 M1 M1 M1 M1 M1 M1 M1 M1r7   r>  c                   $     e Zd Z fdZd Z xZS )MllamaTextMLPc                    t                                                       || _        |j        | _        |j        | _        t          j        | j        | j        d          | _        t          j        | j        | j        d          | _        t          j        | j        | j        d          | _	        t          |j                 | _        d S r   )rJ   rK   rF   rL   rx   r   rw   	gate_projup_proj	down_projr
   ru   act_fnr{   s     r5   rK   zMllamaTextMLP.__init__4  s    !-!'!94#3T5KRWXXXy!143IPUVVV4#94;KRWXXXV./r7   c                     |                      |                     |                     |                    |                     |          z            S rt   )rE  rF  rC  rD  )rT   r   s     r5   r[   zMllamaTextMLP.forward?  s;    ~~dkk$..*;*;<<t||ANOOOr7   )r\   r]   r^   rK   r[   r`   ra   s   @r5   rA  rA  3  sN        	0 	0 	0 	0 	0P P P P P P Pr7   rA  c                       e 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j                 d
ee	ej        ej        f                  deej
                 dee         dee         dee         deej
                 dee	ej        ej        f                  de	ej        ee	ej        ej        f                  f         fdZ xZS )MllamaSelfAttentionDecoderLayerrF   r   c                 X   t                                                       |j        | _        t          |j                 ||          | _        t          |          | _        t          |j        |j	                  | _
        t          |j        |j	                  | _        || _        d S )N)rF   r   r   )rJ   rK   rL   MLLAMA_TEXT_ATTENTION_CLASSESr   r   rA  r   r   r   r   r   r   r   s      r5   rK   z(MllamaSelfAttentionDecoderLayer.__init__E  s    !-6v7RS[amvwww ((01CI\]]](9&:LRXRe(f(f(f%"r7   NFr|   r   r   rA   r4   r)  r   r   r   r   r7  r   c           
         |}|                      |          }|                     ||||||	|
|          \  }}}||z   }|}|                     |          }|                     |          }||z   }|f}|r||fz  }|	r||fz  }|S )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|   rA   r)  r   r   r   r   r7  )r   r   r   r   )rT   r|   r   r   rA   r4   r)  r   r   r   r   r7  r   self_attn_weightspresent_key_valuer   s                   r5   r[   z'MllamaSelfAttentionDecoderLayer.forwardQ  s    H !,,];; ?Cnn')%)/) 3 ?M 	?
 	?
;(*; !=0 !55mDD// =0 " 	,)++G 	,)++Gr7   )
NNNNNNFFNN)r\   r]   r^   r   r  rK   r)   r_   r   r   r  r   r*   FloatTensorr[   r`   ra   s   @r5   rI  rI  D  s       
#/ 
#C 
# 
# 
# 
# 
# 
# :>7;15UY37*.,1$)59KOC C|C !) 6C 'u|4	C
 !.C (0elEL6P0Q'RC u/0C !C $D>C D>C !!12C &eEL%,,F&GHC 
u (51BEDU1U+V"WW	XC C C C C C C Cr7   rI  c                   >    e Zd ZdZdededdf fdZ	 	 	 	 	 	 ddej        d	ej        d
ej        dej        de	ej        ej        f         de
ej                 de
e         de
e         de
e         de
ej                 de
ej                 de	ej                 fdZ xZS ) MllamaCrossAttentionDecoderLayerzLCross-attention transformer block with tanh-gated attention and feedforward.rF   r   r   Nc                    t                                                       || _        t          |j                 ||          | _        t          |j        |j                  | _	        t          j                            t          j        d                    | _        t          |          | _        t          |j        |j                  | _        t          j                            t          j        d                    | _        d S )N)r   r   r   )rJ   rK   r   #MLLAMA_TEXT_CROSS_ATTENTION_CLASSESr   
cross_attnr   rL   r   r   r)   r   rP   rQ   cross_attn_attn_gaterA  r   r   cross_attn_mlp_gater   s      r5   rK   z)MllamaCrossAttentionDecoderLayer.__init__  s    "=f>YZ[amvwww01CI\]]]$)H$6$6u{1~~$F$F! (((9&:LRXRe(f(f(f%#(8#5#5ek!nn#E#E   r7   Fr|   r   r   rA   r4   r)  r   r   r   r   r7  c                    |}|                      |          }|                     ||||||
          \  }}}|| j                                        |z  z   }|}|                     |          }|                     |          }||d d df         |z  }|| j                                        |z  z   }|f}|r||fz  }|	r||fz  }|S )N)r|   rA   r   r   r   r   r   )r   rT  rU  rY   r   r   rV  )rT   r|   r   r   rA   r4   r)  r   r   r   r   r7  r   r   r   s                  r5   r[   z(MllamaCrossAttentionDecoderLayer.forward  s    !,,];;6:oo'/#9)/) 7F 7
 7
3|^ !4#<#A#A#C#Cm#SS 55mDD//(49!!!Q$?-OM 4#;#@#@#B#B]#RR " 	'&G 	)((Gr7   )NNFFNN)r\   r]   r^   r   r   r  rK   r)   r_   r   r   r  r   r*   r[   r`   ra   s   @r5   rQ  rQ    sE       VV
F/ 
FC 
FD 
F 
F 
F 
F 
F 
F& 48*.,1$)596:* *|* !&* $l	*
 * (-U\5<-G'H* u/0* !* $D>* D>* !!12* &el3* 
u|	* * * * * * * *r7   rQ  c                   \     e Zd Zddef fdZd Z ej                    d             Z xZ	S )MllamaRotaryEmbeddingNrF   c                 f   t                                                       |j        d         | _        |j        | _        |j        | _        || _        t          | j                 | _	        | 	                    | j        |          \  }| _
        |                     d|d           | j        | _        d S )N	rope_typeinv_freqF
persistent)rJ   rK   rope_scalingr[  max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrF   r   rope_init_fnattention_scalingregister_bufferr\  original_inv_freq)rT   rF   r  r\  rU   s       r5   rK   zMllamaRotaryEmbedding.__init__  s    ,[9"("@$*$B!/?+/+<+<T[&+Q+Q($(ZeDDD!%r7   c                 ^   t          j        |          dz   }|| j        k    rB | j        | j        |fd|i| j        \  }| _        |                     d|d           || _        || j        k     r;| j        | j        k    r-|                     d| j	        d           | j        | _        dS dS dS )a  
        dynamic RoPE layers should recompute `inv_freq` in the following situations:
        1 - growing beyond the cached sequence length (allow scaling)
        2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
        r   seq_lenr\  Fr]  N)
r)   maxra  rc  rF   rope_kwargsrd  re  rb  rf  )rT   r)  r  rh  r\  s        r5   _dynamic_frequency_updatez/MllamaRotaryEmbedding._dynamic_frequency_update  s     )L))A-T,,,/@t/@V0 0-408<8H0 0,Hd,   X% HHH&-D#T...43JTMf3f3f  T-CPU VVV&*&?D### /.3f3fr7   c                 V   d| j         v r|                     ||j                   | j        d d d d f                                                             |j        d         dd          }|d d d d d f                                         }|j        j        }t          |t                    r|dk    r|nd}t          j        |d	          5  |                                |                                z                      dd
          }t          j        ||fd          }|                                }|                                }	d d d            n# 1 swxY w Y   || j        z  }|	| j        z  }	|                    |j                  |	                    |j                  fS )Ndynamicr  r   r"   r   mpscpuF)device_typeenabledre   r    )r   )r[  rk  r  r\  floatr0  r#   r  
isinstancestrr)   autocastr?   r  r'  r(  rd  r'   r   )
rT   r   r)  inv_freq_expandedposition_ids_expandedrq  freqsembr'  r(  s
             r5   r[   zMllamaRotaryEmbedding.forward  s   &&**<*III !M$4-8>>@@GGHZ[\H]_acdee ,QQQaaaZ 8 > > @ @hm%/S%A%AekUZFZFZkk`e^UCCC 	 	&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C''))C''))C		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 D**D**vvAGv$$cff17f&;&;;;s   A>EEErt   )
r\   r]   r^   r   rK   rk  r)   no_gradr[   r`   ra   s   @r5   rY  rY    s        
/ 
// 
/ 
/ 
/ 
/ 
/ 
/@ @ @$ U]__< < _< < < < <r7   rY  c                   8    e Zd ZeZdZdZg dZdZdZ	dZ
dZd ZdS )MllamaPreTrainedModelmodelT)r   rQ  rI  Fc                 d   | j                                         j        }t          |t          j        t          j        f          rJ|j        j        	                    d|           |j
         |j
        j                                         d S d S t          |t          j                  rU|j        j        	                    d|           |j        +|j        j        |j                                                  d S d S t          |t          j                  r|j        	                    d|           d S t          |t                    r-t          j        	                    |j        j        |           d S t          |t$                    r-t          j        	                    |j        j        |           d S t          |t(                    r_|j        rZt          j        	                    |j        j        |           t          j        	                    |j        j        |           d S d S d S )Nr  )r   std)r  )rF   get_text_configinitializer_rangert  r   rw   Conv2dr   datanormal_r   zero_rN   padding_idxrP   MllamaVisionModelinitclass_embeddingrc   rO   r   rG   r   r   )rT   moduler  s      r5   _init_weightsz#MllamaPreTrainedModel._init_weights  s   k))++=fry")455 	;M&&CS&999{& &&((((( '&-- 	;M&&CS&999!-"6#56<<>>>>> .--- 	;KSc22222 122 	;GOOF27SOAAAAA BCC 	;GOOF,1sO;;;;; 899 	;fo 	;GOOF,1sO;;;GOOFO0cO:::::	; 	; 	; 	;r7   N)r\   r]   r^   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_cache_class_supports_static_cache_supports_sdpa_supports_quantized_cacher  r   r7   r5   r}  r}  
  s_        L&*#  
 !"N $; ; ; ; ;r7   r}  aK  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

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

    Parameters:
        config ([`MllamaConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, max_num_images, max_num_tiles, channels, image_size, image_size)):
            The tensors corresponding to the input images. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`MllamaImageProcessor.__call__`] for details ([]`MllamaProcessor`] uses
            [`MllamaImageProcessor`] for processing images).
        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.
        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.
a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

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

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

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

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

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

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

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

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

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

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance, see our
            [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
            - 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)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

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

            [What are input IDs?](../glossary#input-ids)
        pixel_values (`torch.FloatTensor` of shape `(batch_size, max_num_images, max_num_tiles, channels, image_size, image_size)):
            The tensors corresponding to the input images. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`MllamaImageProcessor.__call__`] for details ([]`MllamaProcessor`] uses
            [`MllamaImageProcessor`] for processing images).
        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.
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

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

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

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

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

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

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

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance, see our
            [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
            - 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)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
z>The Mllama Vision Model which consists of two vision encoders.c                   6    e Zd ZeZdZdef fdZd Zdej	        dej	        fdZ
 ee           eed	          	 	 	 ddej	        dej	        dej	        dee         dee         dee         deeeej	        df         f         fd                        Z xZS )r  vision_modelrF   c                    t                                          |           |j        | _        |j        | _        |j        | _        |j        | _        |j        | _        |j        | _        | j        | j        z  dz  dz   | _        |j        dz  | _	        t          j        |j        | j        | j        | j        dd          | _        t          j        | j	        t          j        | j                  z            | _        t#          |          | _        t'          |d          | _        t'          |d          | _        t          j        | j                  | _        t          j        | j                  | _        t3          ||j        d          | _        t3          ||j        d          | _        |                                  d S )	Nre   r   rf   validF)in_channelsout_channelskernel_sizestridepaddingr   T)rG   )rJ   rK   rg   rh   r@   rL   num_channelsintermediate_layers_indicesr9   ri   r   r  patch_embeddingrP   r)   rj   r  rc   gated_positional_embeddingrE   pre_tile_positional_embeddingpost_tile_positional_embeddingr   layernorm_prelayernorm_postr   num_hidden_layerstransformernum_global_layersglobal_transformer	post_initr{   s     r5   rK   zMllamaVisionModel.__init__'  s       + +#1!-"/+1+M( Ot>1DqH'-
!y+)? 
  
  
  "|DJTEU9V9V,VWW*LV*T*T'-RSYdh-i-i-i*.STZei.j.j.j+  \$*:;; l4+;<< /vv7OZ_```"5ff>Vae"f"f"fr7   c                     | j         S )zg
        This function is used to fetch the first embedding layer to activate grads on inputs.
        )r  r   s    r5   get_input_embeddingsz&MllamaVisionModel.get_input_embeddingsL  s     ##r7   rV   r   c                     |j         \  }}}| j                            |d|          }t          j        ||gd          }|S )Nr   r    )r#   r  r0  r)   r  )rT   rV   r/   r1   rL   r  s         r5   apply_class_embeddingz'MllamaVisionModel.apply_class_embeddingR  sJ    %1%7"
A{.55j![QQy/<!@aHHHr7   r   output_typer  Npixel_valuesrW   r8   r   r   r   .c                    ||n| j         j        }||n| j         j        }||n| j         j        }|j        \  }}}	}
}}|                    ||z  |	z  |
||          }|                    ||z  d          }|                     |                    | j                                      | j	                            }|
                    d                              dd          }|j        \  }}}|                    ||z  |	d|          }|                     ||          }|                    ||z  |	z  ||          }|                     |          }|dz  }|                    ||z  |	||          }|                     ||          }|                     |          }d|j        d         dz  z
  dz  }ddd|f}t!          j        ||dd	          }|dk    r| nd}|                    ||z  d          }t%          || j        |j        d         | j        
          }|                    ||z  d|          }|                     ||d|          }|d         }|                     |          }|                    ||z  |	||z   |          }|                     ||          }|                    ||z  |	||z   z  |          }|                     ||||          }|d         }|                    ||z  |	||z   |          }|ddddd|f         }|                    |||	||          }|d         }t3          j        |d          }|d| j        f         }|                    ||z  |	||z   d          }|ddddd|f         }|                    |||	|d          }t3          j        ||gd          }|r&t;          |          t;          |d                   z   }nd}|rE|rt;          |d                   nt;          |d                   }t;          |d                   |z   }nd}|st;          d |||fD                       S t=          |||          S )a  

        Returns:

        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"   re   r      r<   r   constant)moder   )r8   r9   r:   r   T)rA   r   r   r    .c              3      K   | ]}||V  	d S rt   r   r   s     r5   r   z,MllamaVisionModel.forward.<locals>.<genexpr>  s(      __qQRQ^Q^Q^Q^Q^__r7   r   )rF   r   r   r   r#   r>   r  r'   r   r  flattenr?   r  r  r  r  r   padrC   r9   r%   r  r  r  r  r)   stackr  r  r   r   )rT   r  rW   r8   r   r   r   r/   num_concurrent_media	num_tilesr  heightwidthpatch_embedsrV   r1   r9   r!   num_padding_patchesr  slice_indexrA   r   global_outputall_intermediate_hidden_statesintermediate_hidden_statesr|   global_attnr   s                                r5   r[   zMllamaVisionModel.forwardX  s   H 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]S_SeP
()\65#++J9M,MPY,Y[gioqvww+33JAU4UWYZZ ++LOODJ,G,G,J,J4;,W,WXX#++A..88A>> +0;#++J9M,MyZ\^abb99,HXYY $++J9M,MPY,Y[fhkll11,??q $++J9M,MyZegjkk66|EUVV)),77  !L$6r$:Q$>?1Da/0u\71MMM.AA.E.E***4 +22:@T3TVXYY=,(&,Q/*	
 
 
 $((6J)JBPSTT!!)!%/	 " 
 
 ay**<88 $++--y+H[:[]`
 
 ::<IYZZ#++--yKJ]<]/^`c
 
 //)!5/	 0 
 
 %Q' $++--y+H[:[]`
 
 $AAAqqq,;,$67#++J8LiYdfijj *0&%*[1OUW%X%X%X"%?TEe@e%f" &@%G%G--y+H[:[]_&
 &
" &@111l{l@R%S"%?%G%G,ib&
 &
"
 y,0J!KQSTTT 	!!"@AAE-XYJZD[D[[MM M 	5If%a 0111uUbcdUeOfOfKvay))K7JJJ 	`__\=*$M______*'!
 
 
 	
r7   )NNN)r\   r]   r^   r   r  r  rK   r  r)   r_   r  r   MLLAMA_VISION_INPUTS_DOCSTRINGr   r   r   r*   r   r   r[   r`   ra   s   @r5   r  r    s_       
 &L&#1 # # # # # #J$ $ $%, 5<     +*+IJJ?I]^^^ -1/3&*Y
 Y
lY
  ,Y
 !<	Y

 $D>Y
 'tnY
 d^Y
 
elC&7 88	9Y
 Y
 Y
 _^ KJY
 Y
 Y
 Y
 Y
r7   r  zYThe Mllama Text Model which consists of transformer with self and cross attention layers.c            !           e Zd ZeZdZdef fdZd Zd Z e	e
           eed          	 	 	 	 	 	 	 	 	 	 	 	 	 d d	eej                 d
eej                 deej                 deej                 deej                 deeej        ej        f                  deeeeej                 f                  deej                 dee         dee         dee         dee         deej                 deeef         fd                        Zd
ej        dej        dej        dedef
dZed
ej        dededej        dej        dej        defd            Z xZS )!MllamaTextModelzlanguage_model.modelrF   c                    t                                          |           |j        | _        |j        | _        t          j        |j        dz   |j        | j                  | _        |j	        | _	        g }t          |j                  D ]R}|| j	        v r$|                    t          ||                     /|                    t          ||                     St          j        |          | _        t#          |j        |j                  | _        t)          |          | _        d| _        |                                  d S )Nr  r   )rF   F)rJ   rK   pad_token_idr  
vocab_sizer   rN   rL   embed_tokenscross_attention_layersr   r  appendrQ  rI  r   r   r   r   normrY  
rotary_embr   r  )rT   rF   r   r   rU   s       r5   rK   zMllamaTextModel.__init__  s*      !. +L):Q)>@RTXTdee&,&C#v788 	R 	RID777>vyQQRRRR=fiPPQQQQmF++%f&8f>QRRR	/v>>>&+#r7   c                     | j         S rt   r  r   s    r5   r  z$MllamaTextModel.get_input_embeddings  s      r7   c                     || _         d S rt   r  rT   r   s     r5   set_input_embeddingsz$MllamaTextModel.set_input_embeddings  s    !r7   r   r  N	input_idsrA   r)  r   r   r4   past_key_valuesinputs_embedsr   r   r   r   r   r   c                    |
|
n| j         j        }
||n| j         j        }|	|	n| j         j        }	||n| j         j        }|du |duz  rt          d          | j        r%| j        r|	rt          	                    d           d}	|| 
                    |          }|}|B||                                nd}t          j        |||j        d         z   |j                  }||                    d          }|                     |||||
          }|                     ||          }|rdnd}|
rdnd}d}t'          | j                  D ]\  }}|r||fz  }|| j        v }|du p|duo|                    |          dk    }|r||r>| j        r-| j        r&|                     |j        ||||||||
|	||          }n |||||||||
|	||	          }|d         }|	r||
rd
nd         }|
r||d         fz  }|                     |          }|r||fz  }|	r|nd}|st3          d ||||fD                       S t5          ||||          S )aN  

        Returns:

        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   rn  r   )
r   r   rA   r4   r)  r   r   r   r   r7  re   c              3      K   | ]}||V  	d S rt   r   r   s     r5   r   z*MllamaTextModel.forward.<locals>.<genexpr>  s(      ttqfgfsfsfsfsfsttr7   )r   r  r|   r   )rF   r   r   r   r   r  r   r   r   r   r  get_seq_lengthr)   aranger#   r  r&   _update_causal_maskr  	enumerater   r  r   r   r  r   r   )rT   r  rA   r)  r   r   r4   r  r  r   r   r   r   r   r|   past_seen_tokensr   r7  all_hidden_statesall_self_attnsnext_decoder_cacheidxdecoder_layeris_cross_attention_layeris_cross_attention_cache_emptyr   
next_caches                              r5   r[   zMllamaTextModel.forward  s   P 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]-t";< 	[YZZZ& 	4= 	Y 	j   I  --i88M%!CRC^==???de"\ "2]5H5K"KTaTh  N )33A66L..M>?L]
 

 #oom\JJ #7@BBD0:d!"+DK"8"8 3	6 3	6C# 6!m%55!
 (+d.I'I$-<-D .t+X0N0Ns0S0SWX0X + ( ,B,JOm,J* t}  $ A A!*!*(1 #%"'! ! !.!+A)=#.2O!-#2&7'#1(;! ! ! *!,M R%28I3P11q%Q"  6=#3"55		-00   	2-!11+4>''$
 	utt]J@QSa$btttttt&+&+%	
 
 
 	
r7   input_tensorc           
         | j         j        dk    r
|d|v r|S d S ||                                nd}t          |t                    }| j         j        dk    r#|s!|st          j        |||| j                  rd S |j        |j	        }	}|j
        d         }
|r|                                }n/t          |t          j                  r|j
        d         n||
z   dz   }|                     ||
|||	||j
        d                   }| j         j        dk    rB|@|j	        j        d	k    r0|s.t          j        |          j        }t          j        ||          }|S )
Nflash_attention_2r  r   r   )r  past_key_values_lengthis_trainingr   r"   )sequence_lengthr:   r   r  r   r/   r  )rF   r   r  rt  r   r   _ignore_causal_mask_sdpar   r   r  r#   get_max_cache_shaper)   r_   5_prepare_4d_causal_attention_mask_with_cache_positionr  r+   r,   _unmask_unattended)rT   rA   r  r   r  r   r  using_static_cacher   r  r  r:   r   	min_dtypes                 r5   r  z#MllamaTextModel._update_causal_mask  s    ;+/BBB)c^.C.C%%4
 @O?Z?99;;;`a'EE ;+v55>P5Yj5%>*'7 M	    t$*L,?v&,Q/ 	+??AAMM nel;;<$R((%7!;  PP+')#)!, Q 
 
 K,66*%*f44% 5 E**.I0CKQZ[[Kr7   r  r:   r   r  r/   c                    | |                                  dk    r| }n+t          j        |          j        }	t          j        ||f|	||          }|dk    rt          j        |d          }|t          j        ||          |                    dd          k    z  }|ddddddf                             |ddd          }| |	                                }| j
        d         }
|ddddddd|
f         | ddddddf         z   }|dk    }|ddddddd|
f                             ||	          |ddddddd|
f<   |S )	a  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to plcae the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        Nr   )
fill_valuer   r  r   )diagonalrn  r"   r   )r!   r)   r+   r,   fulltriur  r>   r0  cloner#   r(   )rA   r  r:   r   r  r   r/   r:  r   r  mask_lengthpadding_masks               r5   r  zEMllamaTextModel._prepare_4d_causal_attention_mask_with_cache_position  s   D %.*<*<*>*>!*C*C(KKE**.I* -0Ye\b  K !###jqAAA5<fEEEH^H^_acdHeHeeeK%dD!!!QQQ&67>>z1bRTUUK))//11,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdd+q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 r7   )NNNNNNNNNNNNN)r\   r]   r^   r   r  r  rK   r  r  r   MLLAMA_TEXT_INPUTS_DOCSTRINGr   r   r   r)   r  r_   rO  r   r   r   r   r*   r[   r  staticmethodr  r   r  r  r`   ra   s   @r5   r  r    s       
 $L./      (! ! !" " " +*+GHH+BQcddd 151537>B7;UYKO59$(,0/3&*59S
 S
E,-S
 !.S
 u/0	S

 !)): ;S
 'u|4S
 (0elEL6P0Q'RS
 "%tE4E/F(F"GHS
   12S
 D>S
 $D>S
 'tnS
 d^S
 !!12S
 
u--	.S
 S
 S
 ed IHS
l?? l? 	?
 ?  ? ? ? ?B 555 5 {	5
 5 5 5 5 5 \5 5 5 5 5r7   r  z;The Mllama Text Model with a language modeling head on top.c            %       F    e Zd ZeZdZdgZ fdZd Zd Z	d Z
d Zd Zd	 Z ee           eed
          	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 deej                 deej                 deeej        ej        f                  deeeeej                 f                  deej                 deej                 dee         dee         dee         dee         deej                 dedeeef         f d                        Z xZS ) MllamaForCausalLMr~  zlm_head.weightc                    t                                          |                                           |                                | _        | j        j        | _        t
                              | j        |j                  | _        t          j
        | j        j        | j        d          | _        |                                  d S )N)attn_implementationFr   )rJ   rK   r  text_configr  r  _from_configr   r~  r   rw   rL   lm_headr  r{   s     r5   rK   zMllamaForCausalLM.__init__4  s    //11222!1133*5$11$2BX^Xs1tt
y!1!=tUZ[[[r7   c                     | j         j        S rt   r~  r  r   s    r5   r  z&MllamaForCausalLM.get_input_embeddings=  s    z&&r7   c                     || j         _        d S rt   r  r  s     r5   r  z&MllamaForCausalLM.set_input_embeddings@  s    "'
r7   c                     | j         S rt   r  r   s    r5   get_output_embeddingsz'MllamaForCausalLM.get_output_embeddingsC  s
    |r7   c                     || _         d S rt   r	  rT   new_embeddingss     r5   set_output_embeddingsz'MllamaForCausalLM.set_output_embeddingsF  s    %r7   c                     || _         d S rt   r~  rT   decoders     r5   set_decoderzMllamaForCausalLM.set_decoderI  s    


r7   c                     | j         S rt   r  r   s    r5   get_decoderzMllamaForCausalLM.get_decoderL  s
    zr7   r   r  Nr   r  rA   r)  r   r   r4   r  r  labelsr   r   r   r   r   num_logits_to_keepr   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|                     |||||||||
||||          }|d         }|                     |dd| dddf                                                   }d}|	 | j        ||	| j        fi |}|s|f|dd         z   }||f|z   n|S t          |||j
        |j        |j                  S )a  
        Args:
            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]`.

            num_logits_to_keep (`int`, *optional*):
                Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.

        Returns:

        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   rA   r)  r   r4   r  r  r   r   r   r   r   r   r   )losslogitsr  r|   r   )rF   r   r   r   r~  r  rs  loss_functionr  r   r  r|   r   )rT   r  rA   r)  r   r   r4   r  r  r  r   r   r   r   r   r  loss_kwargsr   r|   r  r  r   s                         r5   r[   zMllamaForCausalLM.forwardO  s`   l 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B] **#9)%!5*G+'/!5#)  
 
   
mAAA0B/B/C/CQQQ,FGHHNNPP%4%ffdoUUUUD 	DY,F'+'7D7V##VC%#3!/)
 
 
 	
r7   )NNNNNNNNNNNNNNr   )r\   r]   r^   r   r  r  _tied_weights_keysrK   r  r  r
  r  r  r  r   MLLAMA_INPUTS_DOCSTRINGr   r   r)   r  r   r_   r   r   r   r   rO  r*   r  r[   r`   ra   s   @r5   r  r  +  s^       
 $L*+    ' ' '( ( (  & & &     +*+BCC+APbccc '+1537=A;?UYKO59-1$(,0/3&*59"#!\
 \
#\
 !.\
 u/0	\

 !))9 :\
 'u'78\
 (0elEL6P0Q'R\
 "%tE4E/F(F"GH\
   12\
 )*\
 D>\
 $D>\
 'tn\
 d^\
 !!12\
   !\
$ 
u,,	-%\
 \
 \
 dc DC\
 \
 \
 \
 \
r7   r  zIThe Mllama model which consists of a vision encoder and a language model.c            )           e Zd ZdZdef fdZd Zd Zd Zd Z	d Z
d	 Zd
 Z ee           eed          	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d$deej                 deej                 deej                 deej                 deej                 deej                 deej                 deej                 deeej                          deej                 deej                 dee         dee         dee         dee         deej                 ded eeef         f$d!                        Z	 	 	 	 	 	 	 	 	 	 	 	 d%d"Z fd#Z xZS )&MllamaForConditionalGenerationFrF   c                 (   t                                          |           |j        j        | _        |j        j        | _        |j        j        | _        |j        j        | _        | j        j	        | j        j	        nd| _	        t                              |j                  | _        t                              |j                  | _        t          j        |j        j        |j        j        d          | _        |                                  d S )Nr"   Tr   )rJ   rK   r  r  rL   vision_configr@   vision_output_dimrF   r  r  r  r  r  language_modelr   rw   multi_modal_projectorr  r{   s     r5   rK   z'MllamaForConditionalGeneration.__init__  s        ,7!-9#1?!'!5!G8<8P8\DK44bd-::6;OPP/<<V=OPP%'Y 2*&
 &
 &
"
 	r7   c                 4    | j                                         S rt   )r$  r  r   s    r5   r  z3MllamaForConditionalGeneration.get_input_embeddings  s    "77999r7   c                 :    | j                             |           d S rt   )r$  r  r  s     r5   r  z3MllamaForConditionalGeneration.set_input_embeddings  s    0077777r7   c                 4    | j                                         S rt   )r$  r
  r   s    r5   r
  z4MllamaForConditionalGeneration.get_output_embeddings  s    "88:::r7   c                 :    | j                             |           d S rt   )r$  r  r  s     r5   r  z4MllamaForConditionalGeneration.set_output_embeddings  s    11.AAAAAr7   c                 :    | j                             |           d S rt   )r$  r  r  s     r5   r  z*MllamaForConditionalGeneration.set_decoder  s    ''00000r7   c                 4    | j                                         S rt   )r$  r  r   s    r5   r  z*MllamaForConditionalGeneration.get_decoder      "..000r7   c                 4    | j                                         S rt   )r$  tie_weightsr   s    r5   r.  z*MllamaForConditionalGeneration.tie_weights  r,  r7   r   r  Nr   r  r  r8   rW   rA   r   r   r)  r  r  r  r   r   r   r   r   r  r   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|du |
duz  rt	          d          ||
t	          d          ||t	          d          |n|t	          d          |                     ||||||          }|d         }|                     |                              d|j        d	         | j	                  }|%t          || j        j        | j        
          \  }}nd}| ||dddd|f         }|dddd|f         }|                     |||||||	||
||||||          }|S )a  
        Args:
            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]`.

            num_logits_to_keep (`int`, *optional*):
                Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.


        Returns:

        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']
        ```
        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  rW   r8   r   r   r   r   r"   r<   )r   r   )r  rA   r)  r   r   r4   r  r   r  r  r   r   r   r   r  )rF   r   r   r   r  r  r%  r>   r#   rL   r6   r9   r   r$  )rT   r  r  r8   rW   rA   r   r   r)  r  r  r  r   r   r   r   r   r  vision_outputsr4   r   s                        r5   r[   z&MllamaForConditionalGeneration.forward  s   @ 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]-t";< 	[YZZZ#(Av   #(>(Jlmmm#' !deee!..)!1"3%9"3' /  N &4A%6"%)%?%?@V%W%W%_%_*04d6F& &"  +B_$"&"3"?jC C C? "?"? -1)+0J#7111n8L#M ,I!!!QQQP^J^,_)%%)%#9!5*G+'!5/#)1 & 
 
$ r7   c           	         |	E||d d |j         d          d f         }n(|j         d         |j         d         k    r|d d |f         }|||                                                    d          dz
  }|                    |dk    d           |	r:|d d |j         d          d f         }|                    t
          j                  }||d         dk    r|d d}n#|                    t
          j                  d d}|||d<   |                    |||	|
||d           |d         dk    r||d	<   ||d
<   ||d<   |S )Nr   r   r"   )memory_format)r  r  )r  r  r  )r)  r   r  r   rA   r   r  rW   r8   )r#   longcumsummasked_fill_r  r)   contiguous_formatr  )rT   r  r  rA   r)  r  rW   r8   r   r  r   r   r  r:  model_inputss                  r5   prepare_inputs_for_generationz<MllamaForConditionalGeneration.prepare_inputs_for_generation`  s   * &(%aaa.*>q*A)A)C)C&CD		#~';A'>>>%aaa&78	 %,*>)..0077;;a?L%%n&91=== Y+AAA	0B/B/D/D,DE  ,11@W1XX $):a)?)?-:NNLL *3uG^)_)_rvwwL)1CL-. ,"0#2&"0(< 		
 		
 		
 !!!+7L(/?L+,0AL,-r7   c                     |                     dd           } t                      j        d|||d|}|(t          j        ||d d dd df         gd          |d<   |S )Nr   )r   model_kwargsis_encoder_decoderr"   .r   r    r   )getrJ   #_update_model_kwargs_for_generationr)   r  )rT   r   r:  r;  r:  cross_attention_mask_prevrU   s         r5   r=  zBMllamaForConditionalGeneration._update_model_kwargs_for_generation  s    $0$4$45KT$R$R!BuwwB 
%1
 
 	
 
 %0389*,Eaaack,RSYZ4 4 4L/0 r7   )NNNNNNNNNNNNNNNNr   )NNNNNNNNNFNN)r\   r]   r^   r  r   rK   r  r  r
  r  r  r  r.  r   r  r   r   r   r)   r  rO  r_   r   r*   r  r   r   r[   r8  r=  r`   ra   s   @r5   r   r     s       
 !&|      ": : :8 8 8; ; ;B B B1 1 11 1 11 1 1 +*+BCC+AP^___ 15484837157;9=37=A59-1$(,0/3&*59"#% E,- u01 $EL1	
 #5<0 !. 'u|4 !) 6 u/0 "$u'8"9:   12 )* D> $D> 'tn  d^!" !!12#$  %& 
u,,	-'   `_ DCF !B B B BH        r7   r   rI   )Pr   r   typingr   r   r   r   r)   torch.nn.functionalr   r   r   torch.utils.checkpoint r	   activationsr
   cache_utilsr   r   
generationr   modeling_attn_mask_utilsr   modeling_outputsr   r   r   modeling_rope_utilsr   utilsr   r   r   r   configuration_mllamar   r   r   
get_loggerr\   r   r_   r  ru  r6   r   rC   ModulerE   rc   rr   r   r   r   r   r   r   r   r  r#  r-  r  r4  r>  rS  rK  rA  rI  rQ  rY  r}  MLLAMA_START_DOCSTRINGr  r  r  r  r  r  r   r   r7   r5   <module>rN     sY      / / / / / / / / / / / /                           ! ! ! ! ! ! - - - - - - - - ) ) ) ) ) ) > > > > > > ` ` ` ` ` ` ` ` ` ` 6 6 6 6 6 6            U T T T T T T T T T 
	H	%	%?,?? ? 5<%&	? ? ? ?8|  ;	
 \   6    BI   ." " " " " " " "L    bi   0$ 0$ 0$ 0$ 0$BI 0$ 0$ 0$f* * * * * 5 * * *Z -BKd"e"e . . . . .ry . . .bT
 T
 T
 T
 T
") T
 T
 T
pJ J J J J	 J J J(S9 S9 S9 S9 S9ry S9 S9 S9l[1 [1 [1 [1 [1#; [1 [1 [1~( ( (   8	UU\ 	U# 	U%, 	U 	U 	U 	UE9 E9 E9 E9 E9bi E9 E9 E9PO1 O1 O1 O1 O1"9 O1 O1 O1d 1IRn&o&o #*AKf g g P P P P PBI P P P"P P P P Pbi P P Pf9 9 9 9 9ux 9 9 9x4< 4< 4< 4< 4<BI 4< 4< 4<n ;  ;  ;  ;  ;O  ;  ;  ;F "" DR  jg T H P
 P
 P
 P
 P
- P
 P
	 P
f c n n n n n+ n n	 nb	 E ~
 ~
 ~
 ~
 ~
- ~
 ~
	 ~
B S ~ ~ ~ ~ ~%:O ~ ~	 ~ ~ ~r7   