o
    Zhd^                    @   s  d Z ddlZddlmZmZmZmZmZ ddlZddl	m
  mZ ddl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 ddlmZmZmZ ddlmZmZ ddl m!Z!m"Z" ddl#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z,m-Z-m.Z. e) rddl/m0Z0 ddl1m2Z2 e*3e4Z5dej6de7de8deej6ej6f fddZ9dej6de7de7dej:dej6f
ddZ;G dd  d e
j<Z=G d!d" d"e
j<Z>G d#d$ d$e
j<Z?d%ej6d&e7dej6fd'd(Z@	)d`d*e
j<d+ej6d,ej6d-ej6d.eej6 d/eAd0eAfd1d2ZBG d3d4 d4e
j<ZCG d5d6 d6e
j<ZDG d7d8 d8e
j<ZEG d9d: d:e
j<ZFG d;d< d<e
j<ZGd=d> ZHdad?d@ZIG dAdB dBe
j<ZJG dCdD dDe
j<ZKG dEdF dFe
j<ZLG dGdH dHej
j<ZMG dIdJ dJe
j<ZNe'G dKdL dLe"ZOe'dMdNG dOdP dPeOZPe'dQdNG dRdS dSeOZQG dTdU dUee&ZRe'dVdNG dWdX dXeOeZSe'dYdNG dZd[ d[eOZTe'd\dNG d]d^ d^eOeZUg d_ZVdS )bzPyTorch Mllama model.    N)CallableListOptionalTupleUnion)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs)BaseModelOutputBaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)
LossKwargsauto_docstringcan_return_tupleis_torch_flex_attn_availablelogging   )MllamaConfigMllamaTextConfigMllamaVisionConfig)	BlockMask)make_flex_block_causal_maskcross_attention_masknum_vision_tokensdtypereturnc           	      C   s   | j ^}}}| j|dd} | ||d} | d} d|  |}||tjt|j	} t|j	}| |kj
dd| d }| |9 } | |fS )Nr   dimr         ?).N)shapeZrepeat_interleaveview	unsqueezetomasked_filltorchboolfinfominanyZtype_as)	r"   r#   r$   
batch_sizeZtext_total_length_Zinverted_cross_attn_maskZnegative_inf_valuefull_text_row_masked_out_mask r7   Y/var/www/auris/lib/python3.10/site-packages/transformers/models/mllama/modeling_mllama.py_prepare_cross_attention_mask/   s   
r9   aspect_ratio_masknum_patchestarget_lengthc                 C   s   | j \}}| ||dd|}|dd|d}|| }d|d d d d | d f< d| }|||| d}||dd t|j }|	d}|S )Nr   r   r(   )
r*   r+   r-   repeatreshape	transposer/   r1   r2   r,   )r:   r;   r<   r$   r4   max_num_tilesattention_maskZpad_patchesr7   r7   r8   $_prepare_aspect_ratio_attention_maskK   s   

rC   c                       sD   e Zd Zddedef fddZdejdejdejfd	d
Z  Z	S )%MllamaPrecomputedAspectRatioEmbeddingTconfigis_gatedc                    sb   t    |j| _|j| _|j| _|| _t| jd | j| j | _|r/t	t
d| _d S d S Nr   )super__init__rA   hidden_sizemax_aspect_ratio_idrF   r   	Embedding	embedding	Parameterr/   zerosgateselfrE   rF   	__class__r7   r8   rI   g   s   
z.MllamaPrecomputedAspectRatioEmbedding.__init__hidden_stateaspect_ratio_idsr%   c                 C   s>   |  |}|d| jd| j}| jr|| j  }|| }|S )Nr(   r   )rM   r?   rA   rJ   rF   rP   tanh)rR   rU   rV   Z
embeddingsr7   r7   r8   forwardr   s   
z-MllamaPrecomputedAspectRatioEmbedding.forward)T)
__name__
__module____qualname__r   r0   rI   r/   TensorrX   __classcell__r7   r7   rS   r8   rD   f   s    $rD   c                       s>   e Zd Zdef fddZdejdejdejfddZ  ZS )	"MllamaPrecomputedPositionEmbeddingrE   c                    s   t    |j| _|j| _|j|j d d | _|j| _|jd | _t	
td| _t| j| j}t	
| j| | _t	| jd | j| j | j | _d S )N   r         )rH   rI   rA   rK   
image_size
patch_sizer;   rJ   scaler   rN   r/   rO   rP   randnrM   rL   tile_embedding)rR   rE   Zposition_embeddingrS   r7   r8   rI   ~   s   

z+MllamaPrecomputedPositionEmbedding.__init__rU   rV   r%   c                 C   sp   d| j   | j }||dd| j| j }| |}|jd }||| j	| j| j}| j  | }|| }|S )Nr   r   )
rP   rW   rM   r+   r;   rJ   re   r*   r?   rA   )rR   rU   rV   Zgated_position_embeddingZtile_position_embeddingr4   Zgated_tile_position_embeddingr7   r7   r8   rX      s   

z*MllamaPrecomputedPositionEmbedding.forward)	rY   rZ   r[   r   rI   r/   r\   rX   r]   r7   r7   rS   r8   r^   }   s    $r^   c                       s2   e Zd Z fddZdejdejfddZ  ZS )MllamaVisionMLPc                    sD   t    || _t|j | _t|j|j	| _
t|j	|j| _d S N)rH   rI   rE   r	   
hidden_actactivation_fnr   LinearrJ   intermediate_sizefc1fc2rR   rE   rS   r7   r8   rI      s
   
zMllamaVisionMLP.__init__hidden_statesr%   c                 C   s"   |  |}| |}| |}|S rg   )rl   ri   rm   )rR   ro   r7   r7   r8   rX      s   


zMllamaVisionMLP.forward)rY   rZ   r[   rI   r/   r\   rX   r]   r7   r7   rS   r8   rf      s    rf   ro   n_repc                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||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?   )ro   rp   batchnum_key_value_headsslenhead_dimr7   r7   r8   	repeat_kv   s
   0rv           modulequerykeyvaluerB   scalingdropoutc                 K   s   t || j}t || j}	t||dd| }
|d ur3|d d d d d d d |jd f }|
| }
tjj|
dtj	d
|j}
tjj|
|| jd}
t|
|	}|dd }||
fS )Nr_   r   r=   r(   )r'   r$   )ptrainingr   )rv   num_key_value_groupsr/   matmulr@   r*   r   
functionalZsoftmaxfloat32r-   r$   r}   r   
contiguous)rx   ry   rz   r{   rB   r|   r}   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputr7   r7   r8   eager_attention_forward   s   
&r   c                       s^   e Zd Zdef fddZ		ddejdeej dee de	ejeej f fd	d
Z
  ZS )MllamaVisionAttentionrE   c                    s   t    || _|j| _|j| _|j|j | _| jd | _d| _	t
j| j| j| j dd| _t
j| j| j| j dd| _t
j| j| j| j dd| _t
j| j| j | jdd| _d S )Nr`   r   Fbias)rH   rI   rE   rJ   Z	embed_dimattention_heads	num_headsru   r|   r   r   rj   q_projk_projv_projo_projrn   rS   r7   r8   rI      s   
 zMllamaVisionAttention.__init__NrU   rB   output_attentionsr%   c                 K   s  |  |}| |}| |}|j\}}	}
|j\}
}}
|||	| j| jdd}|||| j| jdd}|||| j| jdd}t}| j	j
dkra| j	j
dkr[|r[td nt| j	j
 }|| ||||fd| jd|\}}|||	d }| |}|sd }||fS )	Nr   r_   eagersdpa`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.rw   r}   r|   r(   )r   r   r   r*   r+   r   ru   r@   r   rE   _attn_implementationloggerwarning_oncer   r|   r?   r   r   )rR   rU   rB   r   r   ry   rz   r{   r4   Z	q_seq_lenr5   Z
kv_seq_lenattention_interfacer   r   r7   r7   r8   rX      s@   




zMllamaVisionAttention.forwardNN)rY   rZ   r[   r   rI   r/   r\   r   r0   r   rX   r]   r7   r7   rS   r8   r      s    r   c                       sP   e Zd Zddedef fddZ		ddejdeej d	ee fd
dZ	  Z
S )MllamaVisionEncoderLayerFrE   rF   c                    s   t    |j| _|j| _|| _|j| _t|| _t	|| _
tj| j|jd| _tj| j|jd| _|rRttdtj d | _ttdtj d | _d S d S )Nepsr      )rH   rI   rJ   r   num_attention_headsrF   rk   r   	self_attnrf   mlpr   	LayerNormZnorm_epsinput_layernormpost_attention_layernormrN   r/   onesmathpi	gate_attngate_ffnrQ   rS   r7   r8   rI     s   


 z!MllamaVisionEncoderLayer.__init__NrU   rB   r   c                 C   s   |}|  |}| j||d\}}| jr| j | }|| }|}| |}| |}| jr4| j | }|| }|f}|rB||f7 }|S )N)rB   )r   r   rF   r   rW   r   r   r   )rR   rU   rB   r   residualr   outputsr7   r7   r8   rX   .  s    



z MllamaVisionEncoderLayer.forwardFr   )rY   rZ   r[   r   r0   rI   r/   r\   r   rX   r]   r7   r7   rS   r8   r     s    r   c                       sp   e Zd ZdZddef fd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dZ  ZS )MllamaVisionEncoderz
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`MllamaEncoderLayer`].

    Args:
        config: MllamaConfig
        FrE   c                    s@   t     | _t fddt|D | _d| _ | _d S )Nc                    s   g | ]}t  qS r7   )r   ).0r5   rE   rF   r7   r8   
<listcomp>X  s    z0MllamaVisionEncoder.__init__.<locals>.<listcomp>F)rH   rI   rE   r   
ModuleListrangelayersgradient_checkpointing)rR   rE   Z
num_layersrF   rS   r   r8   rI   U  s
   
 
zMllamaVisionEncoder.__init__Nro   rB   r   output_hidden_statesreturn_dictr%   c           
      C   s   |dur|n| j j}|dur|n| j j}|dur|n| j j}|r"dnd}|r(dnd}| jD ]-}|r6||f }| jrF| jrF| |j|||}	n||||d}	|rV||	d f }|	d }q-|rb||f }|spt	dd |||fD S t
|||d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.
        Nr7   )rU   rB   r   r   r   c                 s       | ]	}|d ur|V  qd S rg   r7   r   vr7   r7   r8   	<genexpr>      z.MllamaVisionEncoder.forward.<locals>.<genexpr>last_hidden_statero   
attentions)rE   r   r   use_return_dictr   r   r   _gradient_checkpointing_func__call__tupler   )
rR   ro   rB   r   r   r   Zencoder_statesZall_attentionsZencoder_layerlayer_outputsr7   r7   r8   rX   \  s>   



zMllamaVisionEncoder.forward)r   F)NNNN)rY   rZ   r[   __doc__r   rI   r/   r\   r   r0   r   r   r   rX   r]   r7   r7   rS   r8   r   L  s(    

r   c                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	MllamaTextRMSNormư>c                    s&   t    tt|| _|| _dS )z@
        MllamaTextRMSNorm is equivalent to T5LayerNorm
        N)rH   rI   r   rN   r/   r   weightvariance_epsilon)rR   rJ   r   rS   r7   r8   rI     s   

zMllamaTextRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )Nr_   r(   T)Zkeepdim)	r$   r-   r/   r   powmeanZrsqrtr   r   )rR   ro   Zinput_dtypeZvariancer7   r7   r8   rX     s
   zMllamaTextRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)r   r   r*   r   rR   r7   r7   r8   
extra_repr  s   zMllamaTextRMSNorm.extra_repr)r   )rY   rZ   r[   rI   rX   r   r]   r7   r7   rS   r8   r     s    r   c                       s   e Zd ZdZ		ddee dee f fddZ						ddej	d	eej	 d
ee
 deej	 dedee deej deej	eej	 eeej	  f fddZ  ZS )MllamaTextCrossAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNrE   	layer_idxc                    s   t    || _| jj| _| jj| _|j| _|j| _|j| j | _|| _	| j| j | _
| jd | _tj| j| j| j dd| _tj| j| j| j dd| _tj| j| j| j dd| _tj| j| j | jdd| _t| j|jd| _t| j|jd| _d S )Nr`   Fr   r   )rH   rI   rE   r   r   rs   r}   rJ   ru   r   r   r|   r   rj   r   r   r   r   r   rms_norm_epsq_normk_normrR   rE   r   rS   r7   r8   rI     s    


z!MllamaTextCrossAttention.__init__Fro   cross_attention_statespast_key_valuerB   r   	use_cachecache_positionr%   c                 K   s  |  \}	}
}| |}||	|
| j| jdd}| |}|dur`| |}| |}||	d| j	| jdd}||	d| j	| jdd}| 
|}|dur_|||| jd|i\}}n|d dkrt|j| j |j| j }}ntdt}| jjdkr| jjd	kr|rtd
 nt| jj }|| ||||f| jsdn| j| jd|\}}||	|
d }| |}|sd}|||fS )z#Input shape: Batch x Time x Channelr   r_   Nr(   r   r   z^Cross attention layer can't find neither `cross_attn_states` nor cached values for key/values!r   r   r   rw   r   )sizer   r+   r   ru   r@   r   r   r   rs   r   updater   Z	key_cacheZvalue_cache
ValueErrorr   rE   r   r   r   r   r   r}   r|   r?   r   r   )rR   ro   r   r   rB   r   r   r   r   bszq_lenr5   query_statesr   r   r   r   r   r7   r7   r8   rX     s\   









z MllamaTextCrossAttention.forwardr   )NNNFNN)rY   rZ   r[   r   r   r   intrI   r/   r\   r
   r0   
LongTensorr   rX   r]   r7   r7   rS   r8   r     s@    
r   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..Nr(   r_   r&   )r*   r/   cat)xx1Zx2r7   r7   r8   rotate_half  s   r   c                 C   sD   | |}| |}| | t| |  }|| t||  }||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_idsZunsqueeze_dimZq_embedZk_embedr7   r7   r8   apply_rotary_pos_emb#  s
   

r   c                       sT   e Zd Zdedef fddZ				ddejdejd	ejd
edef
ddZ	  Z
S )MllamaTextSelfAttentionrE   r   c                    s   t    || _|j| _|j| _|j| _|j| _|j| j | _| j| j | _	| jd | _
|j| _|| _tj| j| j| j dd| _tj| j| j| j dd| _tj| j| j| j dd| _tj| j| j | jdd| _d S )Nr`   Fr   )rH   rI   rE   r   r   r}   rJ   rs   ru   r   r|   Z
rope_thetar   r   rj   r   r   r   r   r   rS   r7   r8   rI   ?  s   
 z MllamaTextSelfAttention.__init__FNro   rB   position_embeddingsr   r   c                 K   sZ  |  \}	}
}| |}| |}| |}||	|
| j| jdd}||	|
| j| jdd}||	|
| j| jdd}|\}}t	||||\}}|d urb|||d}|
||| j|\}}t}| jjdkr~| jjdkrx|rxtd nt| jj }|| ||||f| jsdn| j| jd|\}}||	|
d	 }| |}|sd }|||fS )
Nr   r_   )r   r   r   r   r   r   rw   r   r(   )r   r   r   r   r+   r   ru   r@   rs   r   r   r   r   rE   r   r   r   r   r   r}   r|   r?   r   r   )rR   ro   rB   r   r   r   r   r   r   r   r   r5   r   r   r   r   r   Zcache_kwargsr   r   r   r7   r7   r8   rX   Q  sH   





zMllamaTextSelfAttention.forward)FFNN)rY   rZ   r[   r   r   rI   r/   r\   r0   rX   r]   r7   r7   rS   r8   r   >  s"    r   c                       s$   e Zd Z fddZdd Z  ZS )MllamaTextMLPc                    sr   t    || _|j| _|j| _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _	t
|j | _d S NFr   )rH   rI   rE   rJ   rk   r   rj   	gate_projup_proj	down_projr	   rh   act_fnrn   rS   r7   r8   rI     s   
zMllamaTextMLP.__init__c                 C   s$   |  | | || | }|S rg   )r   r   r   r   )rR   r   r   r7   r7   r8   rX     s    zMllamaTextMLP.forward)rY   rZ   r[   rI   rX   r]   r7   r7   rS   r8   r     s    r   c                        s   e Zd Zdedef fd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 de	ejee	ejejf  f fddZ  ZS )MllamaSelfAttentionDecoderLayerrE   r   c                    sX   t    |j| _t||d| _t|| _t|j|jd| _	t|j|jd| _
|| _d S )N)rE   r   r   )rH   rI   rJ   r   r   r   r   r   r   r   r   r   r   rS   r7   r8   rI     s   


z(MllamaSelfAttentionDecoderLayer.__init__NFro   r   r"   rB   r6   r   r   r   r   r   r   r   r%   c                 K   s   |}|  |}| jd||||||	|
|d|\}}}|| }|}| |}| |}|| }|f}|r9||f7 }|	r@||f7 }|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
        )ro   rB   r   r   r   r   r   r   Nr7   )r   r   r   r   )rR   ro   r   r"   rB   r6   r   r   r   r   r   r   r   r   Zself_attn_weightsZpresent_key_valuer   r7   r7   r8   rX     s2   %
	



z'MllamaSelfAttentionDecoderLayer.forward)
NNNNNNFFNN)rY   rZ   r[   r   r   rI   r/   r\   r   r   r   r
   r0   r   r   FloatTensorrX   r]   r7   r7   rS   r8   r     sN    	
r   c                       s   e Zd ZdZdededdf fd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 de	ej fddZ  ZS ) MllamaCrossAttentionDecoderLayerzLCross-attention transformer block with tanh-gated attention and feedforward.rE   r   r%   Nc                    sx   t    || _t||d| _t|j|jd| _t	j
t	d| _t|| _t|j|jd| _t	j
t	d| _d S )N)r   r   r   )rH   rI   r   r   
cross_attnr   rJ   r   r   r/   r   rN   rO   cross_attn_attn_gater   r   r   cross_attn_mlp_gater   rS   r7   r8   rI     s   

z)MllamaCrossAttentionDecoderLayer.__init__Fro   r   r"   rB   r6   r   r   r   r   r   r   r   c              	   K   s   |}|  |}| jd||||||
d|\}}}|| j |  }|}| |}| |}|d ur<|d d df | }|| j |  }|f}|rO||f7 }|	rV||f7 }|S )N)ro   rB   r   r   r   r   r   r7   )r   r   r   rW   r   r   r   )rR   ro   r   r"   rB   r6   r   r   r   r   r   r   r   r   r   r   r7   r7   r8   rX     s2   
	



z(MllamaCrossAttentionDecoderLayer.forward)NNFFNN)rY   rZ   r[   r   r   r   rI   r/   r\   r   r   r   r
   r0   r   r   rX   r]   r7   r7   rS   r8   r     sH    	
r   c                       s8   e Zd Zddef fddZe edd Z  Z	S )MllamaRotaryEmbeddingNrE   c                    sh   t    |jd | _|j| _|j| _|| _t| j | _	| 	| j|\}| _
| jd|dd | j| _d S )N	rope_typeinv_freqF)
persistent)rH   rI   Zrope_scalingr   Zmax_position_embeddingsZmax_seq_len_cachedZoriginal_max_seq_lenrE   r   Zrope_init_fnattention_scalingZregister_bufferr   Zoriginal_inv_freq)rR   rE   devicer   rS   r7   r8   rI   4  s   
zMllamaRotaryEmbedding.__init__c           
      C   s   | j d d d d f  |jd dd}|d d d d d f  }t|jjtr2|jjdkr2|jjnd}tj	|dd+ | |  
dd}tj||fdd	}| | j }| | j }	W d    n1 siw   Y  |j|jd
|	j|jd
fS )Nr   r(   r   ZmpscpuF)device_typeenabledr_   r&   )r$   )r   floatrq   r*   
isinstancer  typestrr/   Zautocastr@   r   r   r   r   r-   r$   )
rR   r   r   Zinv_freq_expandedZposition_ids_expandedr  ZfreqsZembr   r   r7   r7   r8   rX   @  s   (&zMllamaRotaryEmbedding.forwardrg   )
rY   rZ   r[   r   rI   r/   Zno_gradr   rX   r]   r7   r7   rS   r8   r   3  s
    r   c                   @   s   e Zd ZeZdZdZg dZdZdZ	dZ
dZdZdZdd Z	ddeejdf d	ejd
ejdedef
ddZedejdededejd
ejdefddZdS )MllamaPreTrainedModel T)r   r   r   Fc                 C   s  t | jd| j j}t|tjtjfr,|jj	j
d|d |jd ur*|jj	  d S d S t|tjrM|jj	j
d|d |jd urK|jj	|j   d S d S t|tjrb|jj	d |jj	  d S t|trp|jj	d d S t|trtjj
|jj	|d d S t|trtjj
|jj	|d tj|jj	 d S t|tr|jrtjj
|jj	|d tjj
|jj	|d d S t|tr|jj	  |jj	  d S t|t r|jr|jj	  d S d S d S )Ninitializer_rangerw   )r   stdr)   )r  )!getattrrE   get_text_configr  r  r   rj   Conv2dr   dataZnormal_r   Zzero_rL   padding_idxr   Zfill_r   MllamaVisionModelinitclass_embeddingr^   rM   Zzeros_rP   r   rF   r   r   r   r   r   rD   )rR   rx   r  r7   r7   r8   _init_weightsa  s@   






z#MllamaPreTrainedModel._init_weightsrB   r    input_tensorr   past_key_valuesr   c                 C   s:  | j jdkr|d ur|dk r|S d S | j jdkr&t|tjr$t|}|S |d ur.| nd}|d ur7|jnd}| j jdkrO|sO|sOt	j
|||| jdrOd S |j}|jd }	|r^| }
nt|tjri|jd	 n||	 d }
| j||	|
|||jd d
}| j jdkr|d ur|jjdv r|st|j}t	||}|S )NZflash_attention_2rw   Zflex_attentionr   Fr   )inputs_embedsZpast_key_values_lengthZis_trainingr   r(   )sequence_lengthr<   r$   r   r4   )cudaZxpuZnpu)rE   r   r3   r  r/   r\   r!   get_seq_lengthZis_compileabler   Z_ignore_causal_mask_sdpar   r$   r*   Zget_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr  r  r1   r2   Z_unmask_unattended)rR   rB   r  r   r  r   past_seen_tokensZusing_compilable_cacher$   r  r<   r   	min_dtyper7   r7   r8   _update_causal_mask  sT   




z)MllamaPreTrainedModel._update_causal_maskr  r<   r$   r4   c                 K   sD  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	|ddddddd|	f | ddddddf |j }
|
dk}
|ddddddd|	f |
||ddddddd|	f< |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        Nr   )Z
fill_valuer$   r  r   )Zdiagonalr  r(   r   )r'   r/   r1   r2   fullr  Ztriuaranger?   rq   cloner*   r-   r.   )rB   r  r<   r$   r   r4   r   r   r  Zmask_lengthZpadding_maskr7   r7   r8   r    s,    $
6  zKMllamaPreTrainedModel._prepare_4d_causal_attention_mask_with_cache_positionNr   )rY   rZ   r[   r   config_classbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_supports_cache_class_supports_static_cacheZ_supports_sdpaZ_supports_flash_attn_2_supports_quantized_cacheZ_supports_attention_backendr  r   r/   r\   r
   r0   r  staticmethodr   r$   r  r7   r7   r7   r8   r	  P  sL    &
Dr	  zH
    The Mllama Vision Model which consists of two vision encoders.
    )Zcustom_introc                       s   e Zd ZeZdZdef fddZdd Zdej	dej	fd	d
Z
e			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dZ  ZS )r  vision_modelrE   c                    s
  t  | |j| _|j| _|j| _|j| _|j| _|j| _| j| j d d | _|jd | _	t
j|j| j| j| jddd| _t
| j	t| j | _t|| _t|dd| _t|dd| _t
| j| _t
| j| _t||jdd| _t||jdd| _|   d S )	Nr_   r   r`   ZvalidF)Zin_channelsZout_channelsZkernel_sizeZstridepaddingr   T)rF   )rH   rI   ra   rb   rA   rJ   num_channelsintermediate_layers_indicesr;   rc   r   r  patch_embeddingrN   r/   rd   r  r^   gated_positional_embeddingrD   pre_tile_positional_embeddingpost_tile_positional_embeddingr   layernorm_prelayernorm_postr   num_hidden_layerstransformerZnum_global_layersglobal_transformer	post_initrn   rS   r7   r8   rI     s4   	
zMllamaVisionModel.__init__c                 C      | j S )zg
        This function is used to fetch the first embedding layer to activate grads on inputs.
        )r-  r   r7   r7   r8   get_input_embeddings,  s   z&MllamaVisionModel.get_input_embeddingsrU   r%   c                 C   s2   |j \}}}| j|d|}tj||gdd}|S )Nr   r&   )r*   r  rq   r/   r   )rR   rU   r4   r5   rJ   r  r7   r7   r8   apply_class_embedding2  s   z'MllamaVisionModel.apply_class_embeddingNpixel_valuesrV   r:   r   r   r   .c                    sl  |dur|n| j j}|dur|n| j j}|dur|n| j j}|j\}}}	}
}}||| |	 |
||}||| d}| jjj}| jjj	}| |
||}|ddd}|j\}}}||| |	d|}| ||}||| |	 ||}| |}|d7 }||| |	||}| ||}| |}d|jd d  d }ddd|f}tj||ddd	}|dkr| nd}||| d}t|| j|jd | jd
}||| d|}| j||d|d  d }| |}||| |	|| |}| ||}||| |	||  |}| j||||d}|d }||| |	|| |}|ddddd|f }||||	||} fdd| jD }tj|dd}||| |	|| d}|ddddd|f }||||	|d}tj||gdd}|rt|t|d  }nd}|r|rt|d nt|d }t d | }nd}|stdd |||fD S t|||dS )a5  
        aspect_ratio_ids (`torch.Tensor` of shape `(batch_size, max_num_images)`, *optional*):
            Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image.
            These ids correspond to indices in the model's list of supported aspect ratios, offset by 1.

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

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

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

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

        Example:

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

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

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

        >>> output = model(**inputs)

        >>> print(output.last_hidden_state.shape)
        torch.Size([1, 1, 4, 1025, 7680])
        ```
        Nr(   r_   r      r=   r   Zconstant)moder{   )r:   r;   r<   r$   T)rB   r   r   c                    s   g | ]} d  | qS )r   r7   )r   ioutputr7   r8   r     s    z-MllamaVisionModel.forward.<locals>.<listcomp>r&   c                 s   r   rg   r7   r   r7   r7   r8   r     r   z,MllamaVisionModel.forward.<locals>.<genexpr>r   ) rE   r   r   r   r*   r?   r-  r   r$   r  r-   flattenr@   r/  r9  r.  r1  FpadrC   r;   r+   r4  r2  r0  r5  r,  r/   stackr   r   r   )rR   r:  rV   r:   r   r   r   r4   Znum_concurrent_mediaZ	num_tilesr+  heightwidthZtarget_dtypeZtarget_deviceZpatch_embedsrU   r5   r;   r'   Znum_padding_patchesr*  Zslice_indexrB   Zglobal_outputZall_intermediate_hidden_statesZintermediate_hidden_statesro   Zglobal_attnr   r7   r>  r8   rX   8  s   2





zMllamaVisionModel.forward)NNN)rY   rZ   r[   r   r$  r%  rI   r8  r/   r\   r9  r   r   r0   r   r   r   rX   r]   r7   r7   rS   r8   r    s2    %r  zc
    The Mllama Text Model which consists of transformer with self and cross attention layers.
    c                "       s  e Zd ZeZdZdef fddZdd Zdd Ze																											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 deeef fddZ  ZS )MllamaTextModellanguage_model.modelrE   c                    s   t  | |j| _|j| _t|jd |j| j| _|j	| _	g }t
|jD ]}|| j	v r6|t|| q&|t|| q&t|| _t|j|jd| _t|d| _d| _|   d S )Nr;  r   )rE   F)rH   rI   pad_token_idr  
vocab_sizer   rL   rJ   embed_tokenscross_attention_layersr   r3  appendr   r   r   r   r   r   normr   
rotary_embr   r6  )rR   rE   r   r   rS   r7   r8   rI     s   
zMllamaTextModel.__init__c                 C   r7  rg   rJ  r   r7   r7   r8   r8       z$MllamaTextModel.get_input_embeddingsc                 C   
   || _ d S rg   rO  rR   r{   r7   r7   r8   set_input_embeddings     
z$MllamaTextModel.set_input_embeddingsN	input_idsrB   r   r   r"   r6   r  r  r   r   r   r   r   r   r%   c                 K   sl  |
dur|
n| j j}
|dur|n| j j}|	dur|	n| j j}	|dur$|n| j j}|du |duA r4td| jrC| jrC|	rCt	d d}	|du rL| 
|}|}|	rW|du rWt }|du rs|durc| nd}tj|||jd  |jd}|du r||d}| |||||
}| ||}|rdnd}|
rdnd}d}t| jD ]k\}}|r||f7 }|| jv }|du p|duo||dk}|r|du r|rq| jr| jr| |j||||||||
|	||}n||f|||||||
|	||d	
|}|d }|	r||
rd
nd }|
r	||d f7 }q| |}|r||f7 }|	r|nd}|s.tdd ||||fD S t||||dS )aQ  
        cross_attention_states (`torch.FloatTensor`, *optional*):
            Output of the vision model, used for cross-attention. This tensor contains the processed image features that
            the language model will attend to.
        cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
            Cross-attention mask to control the interaction between text tokens and image tiles.
            This 4D tensor defines which image tiles each text token should attend to.

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

        Example:

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

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

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

        >>> output = model(**inputs)

        >>> print(output.last_hidden_state.shape)
        torch.Size([1, 13, 4096])
        ```
        N:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.Fr   r   r   r7   )
r   r"   rB   r6   r   r   r   r   r   r   r_   c                 s   r   rg   r7   r   r7   r7   r8   r     r   z*MllamaTextModel.forward.<locals>.<genexpr>r   r  ro   r   )rE   r   r   r   r   r   r   r   r   r   rJ  r   r  r/   r"  r*   r  r,   r  rN  	enumerater   rK  r   r   rM  r   r   )rR   rU  rB   r   r   r"   r6   r  r  r   r   r   r   r   r   ro   r  r   r   Zall_hidden_statesZall_self_attnsZnext_decoder_cacheidxZdecoder_layerZis_cross_attention_layerZis_cross_attention_cache_emptyr   Z
next_cacher7   r7   r8   rX     s   9






zMllamaTextModel.forward)NNNNNNNNNNNNN)rY   rZ   r[   r   r$  r%  rI   r8  rS  r   r   r/   r   r\   r   r   r   r
   r   r0   r   r   r   rX   r]   r7   r7   rS   r8   rF    sf    	

rF  c                   @   s   e Zd ZdS )KwargsForCausalLMN)rY   rZ   r[   r7   r7   r7   r8   rZ    s    rZ  zE
    The Mllama Text Model with a language modeling head on top.
    c                &       sH  e Zd ZeZdZdZdgZ fddZdd Z	dd	 Z
d
d Zdd Zdd Zdd Ze															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j dee dee dee d ee d!eej d"eeejf d#ee d$eeef f"d%d&Z  ZS )(MllamaForCausalLMTlanguage_modellm_head.weightc                    sV   t  |  | | _| jj| _t| j| _tj	| jj
| jdd| _|   d S r   )rH   rI   r  text_configrI  rF  _from_configmodelr   rj   rJ   lm_headr6  rn   rS   r7   r8   rI     s   

zMllamaForCausalLM.__init__c                 C      | j jS rg   r`  rJ  r   r7   r7   r8   r8    s   z&MllamaForCausalLM.get_input_embeddingsc                 C   s   || j _d S rg   rc  rR  r7   r7   r8   rS    s   z&MllamaForCausalLM.set_input_embeddingsc                 C   r7  rg   ra  r   r7   r7   r8   get_output_embeddings  rP  z'MllamaForCausalLM.get_output_embeddingsc                 C   rQ  rg   rd  rR   Znew_embeddingsr7   r7   r8   set_output_embeddings  rT  z'MllamaForCausalLM.set_output_embeddingsc                 C   rQ  rg   r`  )rR   decoderr7   r7   r8   set_decoder  rT  zMllamaForCausalLM.set_decoderc                 C   r7  rg   rh  r   r7   r7   r8   get_decoder  rP  zMllamaForCausalLM.get_decoderNr   rU  rB   r   r   r"   r6   r  r  labelsr   r   r   r   r   logits_to_keepr   r%   c                 K   s  |dur|n| j j}|dur|n| j j}|dur|n| j j}| jd|||||||||
||||d|}|d }t|trCt| dn|}| |dd|ddf 	 }d}|	durg| j
||	| jfi |}|s}|f|dd  }|dur{|f| S |S t|||j|j|jdS )a  
        cross_attention_states (`torch.FloatTensor`, *optional*):
            Output of the vision model, used for cross-attention. This tensor contains the processed image features that
            the language model will attend to.
        cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
            Cross-attention mask to control the interaction between text tokens and image tiles.
            This 4D tensor defines which image tiles each text token should attend to.

            For each text token (in seq_length):
            - 1 indicates the token **should attend** to the corresponding image tile
            - 0 indicates the token **should not attend** to the corresponding image tile
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
        full_text_row_masked_out_mask (`Tuple[torch.Tensor, torch.Tensor]`, *optional*):
            A tuple containing two tensors that mask out rows in the cross-attention mechanism:
            - The first tensor has shape `(batch_size, 1, seq_length, 1)` and contains values of 0 or 1.
              A value of 0 indicates that the corresponding text token's entire row in the cross-attention
              matrix should be masked out (all image tokens ignored).
            - The second tensor has the same shape and is used internally to apply the masking during
              the forward pass of cross-attention layers.
            This mask is derived from the cross_attention_mask and is used to handle cases where a text token
            should not attend to any image token.

        Example:

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

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

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

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=40, do_sample=True, temperature=0.6)
        >>> result = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        >>> print(result)
        If I had to write a haiku, it would be: "Snowflakes gently fall" - simple, yet peaceful.
        I love the idea of snowflakes gently falling, each one
        ```
        N)rU  r   rB   r   r"   r6   r  r  r   r   r   r   r   r   r   losslogitsr  ro   r   r7   )rE   r   r   r   r`  r  r   slicera  r  loss_functionrI  r   r  ro   r   )rR   rU  rB   r   r   r"   r6   r  r  rl  r   r   r   r   r   rm  r   r   ro   slice_indicesrp  ro  r?  r7   r7   r8   rX     sJ   @ zMllamaForCausalLM.forward)NNNNNNNNNNNNNNr   ) rY   rZ   r[   r   r$  r&  r%  _tied_weights_keysrI   r8  rS  re  rg  rj  rk  r   r   r/   r   r\   r   r   r
   r   r   r0   r   r   rZ  r   rX   r]   r7   r7   rS   r8   r[    s~    		

r[  zr
    The Mllama model which consists of a vision encoder and a language model without language modeling head.
    c                '       s  e Zd ZddiZdZdef fddZdd Zd	d
 Ze	e
															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 dee dee dee deej dee deeef f"ddZ  ZS ) MllamaModelrG  r\  FrE   c                    s   t  | |jj| _|jj| _|jj| _|jj| _| jj	d ur$| jj	nd| _	t
|j| _t|j| _tj|jj|jjdd| _|   d S )Nr(   Tr   )rH   rI   r^  rI  rJ   Zvision_configrA   Zvision_output_dimrE   rH  r  r_  r)  rF  r\  r   rj   multi_modal_projectorr6  rn   rS   r7   r8   rI   T  s   



zMllamaModel.__init__c                 C   
   | j  S rg   )r\  r8  r   r7   r7   r8   r8  e  rT  z MllamaModel.get_input_embeddingsc                 C      | j | d S rg   )r\  rS  rR  r7   r7   r8   rS  h     z MllamaModel.set_input_embeddingsNrU  r:  r:   rV   rB   r"   r   r   r  r  r   r   r   r   r   r   r%   c                 K   s|  |dur|n| j j}|dur|n| j j}|dur|n| j j}|du |
duA r*td|dur6|
dur6td|durB|durBtd|durk|du rNtd| j||||||d}|d }| |d|jd	 | j	}|dur|t
|| jj| jd
\}}nd}|dur|dur|dddd|f }|dddd|f }| jd|||||||	||
||d|d|}t|j|j|j|jdS )ar  
        aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*):
            Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`:

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

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

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

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

            For each text token (in seq_length):
            - 1 indicates the token **should attend** to the corresponding image tile
            - 0 indicates the token **should not attend** to the corresponding image tile
        cross_attention_states (`torch.FloatTensor`, *optional*):
            Output of the vision model, used for cross-attention. This tensor contains the processed image features that
            the language model will attend to.
        NrV  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:  rV   r:   r   r   r   r   r(   r=   )r#   r$   T)rU  rB   r   r   r"   r6   r  r   r  r   r   r   r   rW  r7   )rE   r   r   r   r   r)  rv  r?   r*   rJ   r9   r;   r$   r\  r   r   r  ro   r   )rR   rU  r:  r:   rV   rB   r"   r   r   r  r  r   r   r   r   r   r   Zvision_outputsr6   r   r7   r7   r8   rX   k  sx   2
zMllamaModel.forward)NNNNNNNNNNNNNNN)rY   rZ   r[   _checkpoint_conversion_mappingr'  r   rI   r8  rS  r   r   r   r/   r   r   r\   r   r0   r   r   r   r   r   rX   r]   r7   r7   rS   r8   ru  K  st    	

ru  zS
    The Mllama model which consists of a vision encoder and a language model.
    c                +       s  e Zd ZdddddZdZdgZdef fd	d
Zdd Zdd Z	dd Z
dd Zedd Zedd Zee																	d2d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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eejf d*ee d+eeef f&d,d-Z												d3 fd.d/	Z  fd0d1Z!  Z"S )4MllamaForConditionalGenerationzmodel.language_modelzmodel.vision_modelzmodel.multi_modal_projectorra  )z^language_model.modelz^vision_modelz^multi_modal_projectorz^language_model.lm_headFr]  rE   c                    s<   t  | t|| _tj|jj|jjdd| _	| 
  d S r   )rH   rI   ru  r`  r   rj   r^  rJ   rI  ra  r6  rn   rS   r7   r8   rI     s   
z'MllamaForConditionalGeneration.__init__c                 C   rw  rg   )r`  r8  r   r7   r7   r8   r8    rT  z3MllamaForConditionalGeneration.get_input_embeddingsc                 C   rx  rg   )r`  rS  rR  r7   r7   r8   rS    ry  z3MllamaForConditionalGeneration.set_input_embeddingsc                 C   r7  rg   rd  r   r7   r7   r8   re     rP  z4MllamaForConditionalGeneration.get_output_embeddingsc                 C   rQ  rg   rd  rf  r7   r7   r8   rg    rT  z4MllamaForConditionalGeneration.set_output_embeddingsc                 C   rb  rg   )r`  r\  r   r7   r7   r8   r\       z-MllamaForConditionalGeneration.language_modelc                 C   rb  rg   )r`  r)  r   r7   r7   r8   r)    r|  z+MllamaForConditionalGeneration.vision_modelNr   rU  r:  r:   rV   rB   r"   r   r   r  r  rl  r   r   r   r   r   rm  r   r%   c                 K   s   |dur|n| j j}|dur|n| j j}|dur|n| j j}| jd|||||||||	|
|||d|d|}|d }t|trEt| dn|}| |dd|ddf }d}|duri| j	||| j j
jfi |}t|||j|j|jdS )af  
        aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*):
            Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`:

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

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

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

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

            For each text token (in seq_length):
            - 1 indicates the token **should attend** to the corresponding image tile
            - 0 indicates the token **should not attend** to the corresponding image tile
        cross_attention_states (`torch.FloatTensor`, *optional*):
            Output of the vision model, used for cross-attention. This tensor contains the processed image features that
            the language model will attend to.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

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

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

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

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

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

        >>> prompt_len = inputs.input_ids.shape[-1]
        >>> generated_ids = output[:, prompt_len:]
        >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
        >>> print(generated_text)
        [', it would be:.\\nA stop sign in Chinatown.\\n']
        ```
        NT)rU  r:  r:   rV   r"   r   rB   r   r  r  r   r   r   r   r   r   rn  r7   )rE   r   r   r   r`  r  r   rq  ra  rr  r^  rI  r   r  ro   r   )rR   rU  r:  r:   rV   rB   r"   r   r   r  r  rl  r   r   r   r   r   rm  r   r   ro   rs  rp  ro  r7   r7   r8   rX     sH   Sz&MllamaForConditionalGeneration.forwardc                    sT   t  j|f|	|
|||||||||d|}|d dkr(d |d< d |d< d |d< |S )N)r  r   r  r   rB   r:  rV   r:   r"   r   rm  r   r:  rV   r:   )rH   prepare_inputs_for_generation)rR   rU  r  rB   r   r:  rV   r:   r"   r  r   r   rm  r   Zmodel_inputsrS   r7   r8   r}    s,   z<MllamaForConditionalGeneration.prepare_inputs_for_generationc                    sZ   | dd }t jd|||d|}|d ur+tj||d d dd df gdd|d< |S )Nr"   )r   model_kwargsis_encoder_decoderr(   .r   r&   r7   )getrH   #_update_model_kwargs_for_generationr/   r   )rR   r   r~  r  r   Zcross_attention_mask_prevrS   r7   r8   r    s   
zBMllamaForConditionalGeneration._update_model_kwargs_for_generation)NNNNNNNNNNNNNNNNr   )NNNNNNNNNFNN)#rY   rZ   r[   rz  r'  rt  r   rI   r8  rS  re  rg  propertyr\  r)  r   r   r   r/   r   r   r\   r   r
   r   r0   r   r   rZ  r   r   rX   r}  r  r]   r7   r7   rS   r8   r{    s    

	

}+r{  )r{  r[  rF  r  r	  ru  )rw   rG   )Wr   r   typingr   r   r   r   r   r/   Ztorch.nn.functionalr   r   rA  Ztorch.utils.checkpointZactivationsr	   Zcache_utilsr
   r   Z
generationr   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   Zmodeling_outputsr   r   r   Zmodeling_rope_utilsr   r   Zmodeling_utilsr   r   Zprocessing_utilsr   utilsr   r   r   r   r   Zconfiguration_mllamar   r   r   Z!torch.nn.attention.flex_attentionr    Zintegrations.flex_attentionr!   Z
get_loggerrY   r   r\   r   r  r9   r$   rC   ModulerD   r^   rf   rv   r  r   r   r   r   r   r   r   r   r   r   r   r   r   r	  r  rF  rZ  r[  ru  r{  __all__r7   r7   r7   r8   <module>   s   


&
A1Xc
PU> . c L   _