a
    h4                 
   @   sr  d Z ddlZddl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 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, ddl-m.Z.m/Z/ ddl0m1Z1m2Z2m3Z3 e) rFddl4m5Z5 ddl6m7Z7 e*8e9Z:ej;e<e=e>ej;ej;f dddZ?ej;e<e<ej@ej;dddZAG dd dejBZCG dd  d ejBZDG d!d" d"ejBZEej;e<ej;d#d$d%ZFdUejBej;ej;ej;eej; eGeGe$e& d'd(d)ZHG d*d+ d+ejBZIG d,d- d-ejBZJG d.d/ d/ejBZKG d0d1 d1ejBZLG d2d3 d3ejBZMd4d5 ZNdVd6d7ZOG d8d9 d9ejBZPG d:d; d;ejBZQG d<d= d=eZRG d>d? d?eZSG d@dA dAejBZTe'G dBdC dCe"ZUe'dDdEG dFdG dGeUZVe'dHdEG dIdJ dJeUZWe'dKdEG dLdM dMeUeZXe'dNdEG dOdP dPeUZYe'dQdEG dRdS dSeUeZZg dTZ[dS )WzPyTorch Mllama model.    N)CallableOptionalUnion)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputBaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tupleis_torch_flex_attn_availablelogging)deprecate_kwarg)OutputRecordercheck_model_inputs   )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 r9   f/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/mllama/modeling_mllama.py_prepare_cross_attention_mask1   s    
r;   )aspect_ratio_masknum_patchestarget_lengthr&   r'   c                 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	transposer1   r3   r4   r.   )r<   r=   r>   r&   r6   max_num_tilesattention_maskZpad_patchesr9   r9   r:   $_prepare_aspect_ratio_attention_maskM   s    

rE   c                       s>   e Zd Zdeed fddZejejejdddZ  Z	S )	%MllamaPrecomputedAspectRatioEmbeddingTconfigis_gatedc                    s^   t    |j| _|j| _|j| _|| _t| jd | j| j | _|rZt	t
d| _d S )Nr   )super__init__rC   hidden_sizemax_aspect_ratio_idrI   r   	Embedding	embedding	Parameterr1   zerosgateselfrH   rI   	__class__r9   r:   rK   i   s    
z.MllamaPrecomputedAspectRatioEmbedding.__init__hidden_stateaspect_ratio_idsr'   c                 C   s>   |  |}|d| jd| j}| jr2|| j  }|| }|S )Nr*   r   )rO   rA   rC   rL   rI   rR   tanh)rT   rX   rY   Z
embeddingsr9   r9   r:   forwardt   s    
z-MllamaPrecomputedAspectRatioEmbedding.forward)T)
__name__
__module____qualname__r!   r2   rK   r1   Tensorr[   __classcell__r9   r9   rU   r:   rF   h   s   rF   c                       s:   e Zd Zed fddZejejejdddZ  ZS )"MllamaPrecomputedPositionEmbeddingrH   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         )rJ   rK   rC   rM   
image_size
patch_sizer=   rL   scaler   rP   r1   rQ   rR   randnrO   rN   tile_embedding)rT   rH   Zposition_embeddingrU   r9   r:   rK      s    
z+MllamaPrecomputedPositionEmbedding.__init__rW   c                 C   sp   d| j   | j }||dd| j| j }| |}|jd }||| j	| j| j}| j  | }|| }|S )Nr   r   )
rR   rZ   rO   r-   r=   rL   ri   r,   rA   rC   )rT   rX   rY   Zgated_position_embeddingZtile_position_embeddingr6   Zgated_tile_position_embeddingr9   r9   r:   r[      s    

z*MllamaPrecomputedPositionEmbedding.forward)	r\   r]   r^   r!   rK   r1   r_   r[   r`   r9   r9   rU   r:   ra      s   ra   c                       s0   e Zd Z fddZejejdddZ  ZS )MllamaVisionMLPc                    sD   t    || _t|j | _t|j|j	| _
t|j	|j| _d S N)rJ   rK   rH   r   
hidden_actactivation_fnr   LinearrL   intermediate_sizefc1fc2rT   rH   rU   r9   r:   rK      s
    
zMllamaVisionMLP.__init__)hidden_statesr'   c                 C   s"   |  |}| |}| |}|S rk   )rp   rm   rq   )rT   rs   r9   r9   r:   r[      s    


zMllamaVisionMLP.forward)r\   r]   r^   rK   r1   r_   r[   r`   r9   r9   rU   r:   rj      s   rj   )rs   n_repr'   c                 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,   expandrA   )rs   rt   batchnum_key_value_headsslenhead_dimr9   r9   r:   	repeat_kv   s
    0rz           )modulequerykeyvaluerD   scalingdropoutkwargsc                 K   s   t || j}t || j}	t||dd| }
|d urf|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 )Nrc   r   r?   r*   )r)   r&   )ptrainingr   )rz   num_key_value_groupsr1   matmulrB   r,   r   
functionalZsoftmaxfloat32r/   r&   r   r   
contiguous)r|   r}   r~   r   rD   r   r   r   
key_statesvalue_statesattn_weightscausal_maskattn_outputr9   r9   r:   eager_attention_forward   s    
&r   c                       sN   e Zd Zed fddZdejeej eejeej f dddZ	  Z
S )	MllamaVisionAttentionrb   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 )Nrd   r   Fbias)rJ   rK   rH   rL   Z	embed_dimattention_heads	num_headsry   r   r   r   rn   q_projk_projv_projo_projrr   rU   r9   r:   rK      s    
zMllamaVisionAttention.__init__N)rX   rD   r'   c                 K   s   |  |}| |}| |}|j\}}}	|j\}	}
}	|||| j| jdd}|||
| j| jdd}|||
| j| jdd}t}| j	j
dkrt| j	j
 }|| ||||fd| jd|\}}|||d }| |}||fS )Nr   rc   eagerr{   r   r   r*   )r   r   r   r,   r-   r   ry   rB   r   rH   _attn_implementationr   r   rA   r   r   )rT   rX   rD   r   r}   r~   r   r6   Z	q_seq_lenr7   Z
kv_seq_lenattention_interfacer   r   r9   r9   r:   r[      s4    




zMllamaVisionAttention.forward)N)r\   r]   r^   r!   rK   r1   r_   r   tupler[   r`   r9   r9   rU   r:   r      s    r   c                       s@   e Zd Zd	eed fddZd
ejeej dddZ	  Z
S )MllamaVisionEncoderLayerFrG   c                    s   t    |j| _|j| _|| _|j| _t|| _t	|| _
tj| j|jd| _tj| j|jd| _|rttdtj d | _ttdtj d | _d S )Nepsr      )rJ   rK   rL   r   num_attention_headsrI   ro   r   	self_attnrj   mlpr   	LayerNormZnorm_epsinput_layernormpost_attention_layernormrP   r1   onesmathpi	gate_attngate_ffnrS   rU   r9   r:   rK     s    


z!MllamaVisionEncoderLayer.__init__NrX   rD   c                 C   st   |}|  |}| j||d\}}| jr4| j | }|| }|}| |}| |}| jrh| j | }|| }|S )NrD   )r   r   rI   r   rZ   r   r   r   )rT   rX   rD   residualr   r9   r9   r:   r[   &  s    


z MllamaVisionEncoderLayer.forward)F)N)r\   r]   r^   r!   r2   rK   r1   r_   r   r[   r`   r9   r9   rU   r:   r     s    r   c                       sD   e Zd ZdZded fddZdejeej e	d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
        Frb   c                    s@   t     | _t fddt|D | _d| _ | _d S )Nc                    s   g | ]}t  qS r9   )r   ).0r7   rG   r9   r:   
<listcomp>J      z0MllamaVisionEncoder.__init__.<locals>.<listcomp>F)rJ   rK   rH   r   
ModuleListrangelayersgradient_checkpointing)rT   rH   Z
num_layersrI   rU   rG   r:   rK   G  s
    
 zMllamaVisionEncoder.__init__N)rs   rD   r'   c                 C   s2   d}| j D ]}|||d}||f }q
t||dS )a8  
        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)

        r9   r   )last_hidden_staters   )r   r   )rT   rs   rD   Zencoder_statesZencoder_layerr9   r9   r:   r[   N  s    
zMllamaVisionEncoder.forward)r   F)N)r\   r]   r^   __doc__r!   rK   r1   r_   r   r   r[   r`   r9   r9   rU   r:   r   >  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)rJ   rK   r   rP   r1   r   weightvariance_epsilon)rT   rL   r   rU   r9   r:   rK   o  s    
zMllamaTextRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )Nrc   r*   T)Zkeepdim)	r&   r/   r1   r   powmeanZrsqrtr   r   )rT   rs   Zinput_dtypeZvariancer9   r9   r:   r[   w  s
    zMllamaTextRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)r   r   r,   r   rT   r9   r9   r:   
extra_repr~  s    zMllamaTextRMSNorm.extra_repr)r   )r\   r]   r^   rK   r[   r   r`   r9   r9   rU   r:   r   n  s   r   c                       s   e Zd ZdZdee ee d fddZedddd	de	j
ee	j
 ee ee	j
 ee ee	j ee	j
ee	j
 eee	j
  f d
ddZ  ZS )MllamaTextCrossAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNrH   	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 )Nrd   Fr   r   )rJ   rK   rH   r   r   rw   r   rL   ry   r   r   r   r   rn   r   r   r   r   r   rms_norm_epsq_normk_normrT   rH   r   rU   r9   r:   rK     s     


z!MllamaTextCrossAttention.__init__past_key_valuepast_key_values4.58new_nameversion)rs   cross_attention_statesr   rD   	use_cachecache_positionr'   c                 K   sh  |  \}}	}
| |}|||	| j| jdd}| |}|dur| |}| |}||d| j	| jdd}||d| j	| jdd}| 
|}|dur|||| jd|i\}}n4|d dkr|j| j j|j| j j }}ntdt}| jjdkrt| jj }|| ||||f| js,d	n| j| jd
|\}}|||	d }| |}||fS )z#Input shape: Batch x Time x Channelr   rc   Nr*   r   r   z^Cross attention layer can't find neither `cross_attn_states` nor cached values for key/values!r   r{   r   )sizer   r-   r   ry   rB   r   r   r   rw   r   updater   r   keysvalues
ValueErrorr   rH   r   r   r   r   r   rA   r   r   )rT   rs   r   r   rD   r   r   r   bszq_lenr7   query_statesr   r   r   r   r   r9   r9   r:   r[     sN    







z MllamaTextCrossAttention.forward)NN)NNNNN)r\   r]   r^   r   r   r    intrK   r   r1   r_   r   r2   
LongTensorr   r[   r`   r9   r9   rU   r:   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*   rc   r(   )r,   r1   cat)xx1Zx2r9   r9   r:   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_embedr9   r9   r:   apply_rotary_pos_emb  s
    

r   c                       sN   e Zd Zeed fddZedddddejejeje	d
ddZ
  ZS )MllamaTextSelfAttentionr   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 )Nrd   Fr   )rJ   rK   rH   r   r   r   rL   rw   ry   r   r   Z
rope_thetar   r   rn   r   r   r   r   r   rU   r9   r:   rK      s    
z MllamaTextSelfAttention.__init__r   r   r   r   FN)rs   rD   position_embeddingsr   c                 K   s4  |  \}}	}
| |}| |}| |}|||	| j| jdd}|||	| j| jdd}|||	| j| jdd}|\}}t	||||\}}|d ur|||d}|
||| j|\}}t}| jjdkrt| jj }|| ||||f| jsdn| j| jd|\}}|||	d }| |}||fS )Nr   rc   )r   r   r   r   r{   r   r*   )r   r   r   r   r-   r   ry   rB   rw   r   r   r   r   rH   r   r   r   r   r   rA   r   r   )rT   rs   rD   r   r   r   r   r   r   r   r7   r   r   r   r   r   Zcache_kwargsr   r   r   r9   r9   r:   r[     s<    




zMllamaTextSelfAttention.forward)FNN)r\   r]   r^   r    r   rK   r   r1   r_   r2   r[   r`   r9   r9   rU   r:   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   )rJ   rK   rH   rL   ro   r   rn   	gate_projup_proj	down_projr   rl   act_fnrr   rU   r9   r:   rK   G  s    
zMllamaTextMLP.__init__c                 C   s$   |  | | || | }|S rk   )r   r   r   r   )rT   r   r   r9   r9   r:   r[   R  s     zMllamaTextMLP.forward)r\   r]   r^   rK   r[   r`   r9   r9   rU   r:   r   F  s   r   c                       s   e Zd Zeed fddZedddddeje	ej e	ej e	ej e	e
ejejf  e	ej e	e e	e e	ej e	e
ejejf  ee e
eje	e
ejejf  f d
ddZ  ZS )MllamaSelfAttentionDecoderLayerr   c                    sX   t    |j| _t||d| _t|| _t|j|jd| _	t|j|jd| _
|| _d S )Nr   r   )rJ   rK   rL   r   r   r   r   r   r   r   r   r   r   rU   r9   r:   rK   Y  s    

z(MllamaSelfAttentionDecoderLayer.__init__r   r   r   r   NFrs   r   r$   rD   r8   r   r   r   r   r   r   r'   c              
   K   s^   |}|  |}| jf ||||||	|
d|\}}|| }|}| |}| |}|| }|S )aZ  
        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.

            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_values (`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
        )rs   rD   r   r   r   r   r   )r   r   r   r   )rT   rs   r   r$   rD   r8   r   r   r   r   r   r   r   Zself_attn_weightsr9   r9   r:   r[   e  s&    #




z'MllamaSelfAttentionDecoderLayer.forward)	NNNNNNFNN)r\   r]   r^   r    r   rK   r   r1   r_   r   r   r   r   r2   r   r   FloatTensorr[   r`   r9   r9   rU   r:   r   X  s2            r   c                       s   e Zd ZdZeedd fddZedddd	dej	ej	ej	ej	e
ej	ej	f eej ee ee eej eej	 ee e
ej	 dddZ  ZS ) MllamaCrossAttentionDecoderLayerzLCross-attention transformer block with tanh-gated attention and feedforward.N)rH   r   r'   c                    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   )rJ   rK   r   r   
cross_attnr   rL   r   r   r1   r   rP   rQ   cross_attn_attn_gater   r   r   cross_attn_mlp_gater   rU   r9   r:   rK     s    

z)MllamaCrossAttentionDecoderLayer.__init__r   r   r   r   Fr   c                 K   s   |}|  |}| jf |||||	d|\}}|| j |  }|}| |}| |}|d urt|d d df | }|| j |  }|S )N)rs   rD   r   r   r   r   )r   r   r   rZ   r   r   r   )rT   rs   r   r$   rD   r8   r   r   r   r   r   r   r   r   r9   r9   r:   r[     s&    



z(MllamaCrossAttentionDecoderLayer.forward)NNFNN)r\   r]   r^   r   r    r   rK   r   r1   r_   r   r   r   r   r2   r   r   r[   r`   r9   r9   rU   r:   r     s,        r   c                       sD   e Zd ZU ejed< ded fddZe e	dd Z
  ZS )	MllamaRotaryEmbeddinginv_freqNrb   c                    sh   t    |jd | _|j| _|j| _|| _t| j | _	| 	| j|\}| _
| jd|dd | j| _d S )N	rope_typer   F)
persistent)rJ   rK   Zrope_scalingr   Zmax_position_embeddingsZmax_seq_len_cachedZoriginal_max_seq_lenrH   r   Zrope_init_fnattention_scalingZregister_bufferr   Zoriginal_inv_freq)rT   rH   devicer   rU   r9   r:   rK     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rd|jjdkrd|jjnd}tj	|ddV | |  
dd}tj||fdd	}| | j }| | j }	W d    n1 s0    Y  |j|jd
|	j|jd
fS )Nr   r*   r   ZmpscpuF)device_typeZenabledrc   r(   )r&   )r   floatru   r,   
isinstancer   typestrr1   ZautocastrB   r   r   r   r   r/   r&   )
rT   r   r   Zinv_freq_expandedZposition_ids_expandedr   ZfreqsZembr   r   r9   r9   r:   r[     s    (&,zMllamaRotaryEmbedding.forward)N)r\   r]   r^   r1   r_   __annotations__r    rK   Zno_gradr   r[   r`   r9   r9   rU   r:   r     s
   

r   c                   @   s   e Zd ZU eed< dZdZg dZdZdZ	dZ
dZdZeegeedddeedd	deedd	dgd
Zdd Zdeejdf ejejeedddZeejeeejejedddZdS )MllamaPreTrainedModelrH    T)r   r   r   Fr   r   )indexZ
layer_namer   )rs   
attentionsc                 C   s  t | jd| j j}t|tjtjfrT|jj	j
d|d |jd urP|jj	  nVt|tjr|jj	j
d|d |jd ur|jj	|j   nt|tjr|jj	d |jj	  nt|tr|jj	d nt|trtjj
|jj	|d nt|tr&tjj
|jj	|d tj|jj	 nt|trd|jrdtjj
|jj	|d tjj
|jj	|d nFt|tr|jj	  |jj	  n t|t r|jr|jj	  d S )Ninitializer_ranger{   )r   stdr+   )r  )!getattrrH   get_text_configr  r   r   rn   Conv2dr   dataZnormal_r   Zzero_rN   padding_idxr   Zfill_r   MllamaVisionModelinitclass_embeddingra   rO   Zzeros_rR   r   rI   r   r   r   r   r   rF   )rT   r|   r  r9   r9   r:   _init_weights  s8    



z#MllamaPreTrainedModel._init_weightsr"   )rD   input_tensorr   r   output_attentionsc                 C   sB  | j jdkr(|d ur$|dk r$|S d S | j jdkrLt|tjrHt|}|S |d ur\| nd}|d urn|jnd}| j jdkr|s|st	j
|||| jdrd S |j}|jd }	|r| }
n"t|tjr|jd	 n
||	 d }
| j||	|
|||jd d
}| j jdkr>|d ur>|jjdv r>|s>t|j}t	||}|S )NZflash_attention_2r{   Zflex_attentionr   FZsdpa)inputs_embedsZpast_key_values_lengthZis_trainingr   r*   )sequence_lengthr>   r&   r   r6   )cudaZxpuZnpu)rH   r   r5   r   r1   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   r3   r4   Z_unmask_unattended)rT   rD   r  r   r   r  past_seen_tokensZusing_compilable_cacher&   r  r>   r   	min_dtyper9   r9   r:   _update_causal_mask.  sZ    






	z)MllamaPreTrainedModel._update_causal_mask)rD   r  r>   r&   r   r6   c                 K   sF  | dur|   dkr| }n&t|j}tj||f|||jd}|dkrVtj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| durB|
 }| 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)   r1   r3   r4   fullr   ZtriuarangerA   ru   cloner,   r/   r0   )rD   r  r>   r&   r   r6   r   r   r  Zmask_lengthZpadding_maskr9   r9   r:   r  r  s*     $

6  zKMllamaPreTrainedModel._prepare_4d_causal_attention_mask_with_cache_positionN)F)r\   r]   r^   r   r  base_model_prefixZsupports_gradient_checkpointingZ_no_split_modules_can_compile_fullgraphZ_supports_sdpaZ_supports_flash_attnZ_supports_flex_attnZ_supports_attention_backendr   r   r   r   r   Z_can_record_outputsr  r   r1   r_   r   r2   r  staticmethodr   r&   r  r9   r9   r9   r:   r    s@   
	& Dr  zH
    The Mllama Vision Model which consists of two vision encoders.
    )Zcustom_introc                       sn   e Zd ZU eed< dZed fddZdd Zej	ej	dd	d
Z
eeej	ej	ej	edddZ  ZS )r  rH   vision_modelrb   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 )	Nrc   r   rd   ZvalidF)Zin_channelsZout_channelsZkernel_sizeZstridepaddingr   T)rI   )rJ   rK   re   rf   rC   rL   num_channelsintermediate_layers_indicesr=   rg   r   r  patch_embeddingrP   r1   rh   r  ra   gated_positional_embeddingrF   pre_tile_positional_embeddingpost_tile_positional_embeddingr   layernorm_prelayernorm_postr   num_hidden_layerstransformerZnum_global_layersglobal_transformer	post_initrr   rU   r9   r:   rK     s4    	
zMllamaVisionModel.__init__c                 C   s   | j S )zg
        This function is used to fetch the first embedding layer to activate grads on inputs.
        )r'  r   r9   r9   r:   get_input_embeddings  s    z&MllamaVisionModel.get_input_embeddings)rX   r'   c                 C   s2   |j \}}}| j|d|}tj||gdd}|S )Nr   r(   )r,   r  ru   r1   r   )rT   rX   r6   r7   rL   r  r9   r9   r:   apply_class_embedding  s    z'MllamaVisionModel.apply_class_embedding)pixel_valuesrY   r<   r'   c                    s  |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r4| nd	}||| d}t|| j|j d | jd
}||| d|}| j||d  j}| |}||| ||| |}| ||}||| |||  |}| j||d}|j}||| ||| |}|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}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])
        ```
        r*   rc   r      r?   r   Zconstant)moder   N)r<   r=   r>   r&   r   c                    s   g | ]} j | qS r9   )rs   )r   ioutputr9   r:   r   ^  r   z-MllamaVisionModel.forward.<locals>.<listcomp>r(   )r   )r,   rA   r'  r   r&   r   r/   flattenrB   r)  r2  r(  r+  FpadrE   r=   r-   r.  r   r,  r*  r/  r&  r1   stackr   r   )rT   r3  rY   r<   r   r6   Znum_concurrent_mediaZ	num_tilesr%  heightwidthZtarget_dtypeZtarget_deviceZpatch_embedsrX   r7   r=   r)   Znum_padding_patchesr$  Zslice_indexrD   Zglobal_outputZall_intermediate_hidden_statesZintermediate_hidden_statesr9   r7  r:   r[     s|    -





zMllamaVisionModel.forward)r\   r]   r^   r!   r  r   rK   r1  r1   r_   r2  r   r   r   r[   r`   r9   r9   rU   r:   r    s   
%r  zc
    The Mllama Text Model which consists of transformer with self and cross attention layers.
    c                       s   e Zd ZU eed< dZed fddZeee	d
e
ej e
ej e
ej e
ej e
ej e
eejejf  e
eeeej f  e
ej e
e e
ej ee eddd	Z  ZS )MllamaTextModelrH   language_model.modelrb   c                    s   t  | |j| _|j| _t|jd |j| j| _|j	| _	g }t
|jD ]0}|| j	v rl|t|| qL|t|| qLt|| _t|j|jd| _t|d| _d| _|   d S )Nr4  r   rb   F)rJ   rK   pad_token_idr  
vocab_sizer   rN   rL   embed_tokenscross_attention_layersr   r-  appendr   r   r   r   r   r   normr   
rotary_embr   r0  )rT   rH   r   r   rU   r9   r:   rK   y  s    
zMllamaTextModel.__init__N)	input_idsrD   r   r   r$   r8   r   r  r   r   r   r'   c                 K   sN  |	dur|	n| j j}	|du |duA r,td|du r>| |}|}|	rZ|du rZt| j d}|
du r|durr| nd}tj|||jd  |j	d}
|du r|

d}| |||
|}| ||}t| jD ]l\}}|| jv }|du p|duo||dk}|r|du r|rq||f|||||||	|
|d	|}q| |}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_embedsrb   r   r   r  )	r   r$   rD   r8   r   r   r   r   r   )r   r   )rH   r   r   rC  r	   r  r1   r  r,   r   r.   r  rG  	enumerater   rD  rF  r   )rT   rH  rD   r   r   r$   r8   r   r  r   r   r   rs   r  r   r   idxZdecoder_layerZis_cross_attention_layerZis_cross_attention_cache_emptyr9   r9   r:   r[     sX    8



zMllamaTextModel.forward)
NNNNNNNNNN)r\   r]   r^   r    r  r   rK   r   r   r   r   r1   r   r_   r   r   r   r   listr2   r   r   r   r[   r`   r9   r9   rU   r:   r?  p  s<   
          r?  zE
    The Mllama Text Model with a language modeling head on top.
    c                       s   e Zd ZU eed< dZdZdgZ fddZe	e
deej eej eej eej eej eeejejf  eeeeej f  eej eej ee eej eeejf ee eeef d	d
dZ  ZS )MllamaForCausalLMrH   Tlanguage_modellm_head.weightc                    sV   t  |  | | _| jj| _t| j| _tj	| jj
| jdd| _|   d S r   )rJ   rK   r
  text_configrB  r?  _from_configmodelr   rn   rL   lm_headr0  rr   rU   r9   r:   rK     s    

zMllamaForCausalLM.__init__Nr   )rH  rD   r   r   r$   r8   r   r  labelsr   r   logits_to_keepr   r'   c                 K   s   | j f |||||||||
|d
|}|j}t|trBt| dn|}| |dd|ddf  }d}|	dur| j||	| jfi |}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
        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.
        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 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
        ```
        )
rH  r   rD   r   r$   r8   r   r  r   r   Nlosslogitsr   rs   r  )rR  r   r   r   slicerS  r   loss_functionrB  r   r   rs   r  )rT   rH  rD   r   r   r$   r8   r   r  rT  r   r   rU  r   outputsrs   slice_indicesrX  rW  r9   r9   r:   r[     s6    ? zMllamaForCausalLM.forward)NNNNNNNNNNNr   )r\   r]   r^   r    r  r!  r   _tied_weights_keysrK   r   r   r   r1   r   r_   r   r   r   rL  r   r2   r   r   r   r   r[   r`   r9   r9   rU   r:   rM    sF   
	            
rM  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ed fddZdd Zdd	 Zd
d Zdd Z	e
eedeej eej eej eej eej eej eej eej ee eej ee eej ee edddZ  ZS )MllamaModelr@  rN  rb   c                    s   t  | |jj| _|jj| _|jj| _|jj| _| jj	d urH| jj	nd| _	t
|j| _t|j| _tj|jj|jjdd| _|   d S )Nr*   Tr   )rJ   rK   rP  rB  rL   Zvision_configrC   Zvision_output_dimrH   rA  r  rQ  r#  r?  rN  r   rn   multi_modal_projectorr0  rr   rU   r9   r:   rK   |  s    



zMllamaModel.__init__c                 C   s
   | j  S rk   )rN  r1  r   r9   r9   r:   r1    s    z MllamaModel.get_input_embeddingsc                 C   s   | j | d S rk   )rN  set_input_embeddingsrT   r   r9   r9   r:   r`    s    z MllamaModel.set_input_embeddingsc                 C   s
   || _ d S rk   rN  rT   decoderr9   r9   r:   set_decoder  s    zMllamaModel.set_decoderc                 C   s   | j S rk   rb  r   r9   r9   r:   get_decoder  s    zMllamaModel.get_decoderN)rH  r3  r<   rY   rD   r$   r   r   r   r  r   r   r   r'   c                 K   s  |du |
duA rt d|dur0|dur0t d|durz|du rHt d| j|||d}|j}| |d|jd | j}|durt|| jj| j	d\}}nd}|dur|dur|dddd|f }|dddd|f }| j
f |||||||	||
|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.
        NrI  zM`pixel_values` and `cross_attention_states` cannot be provided simultaneouslyzA`aspect_ratio_ids` must be provided if `pixel_values` is provided)r3  rY   r<   r*   r?   )r%   r&   )
rH  rD   r   r   r$   r8   r   r   r  r   )r   r   rs   r  )r   r#  r   r_  rA   r,   rL   r;   r=   r&   rN  r   r   rs   r  )rT   rH  r3  r<   rY   rD   r$   r   r   r   r  r   r   r   Zvision_outputsr8   r[  r9   r9   r:   r[     s\    0
zMllamaModel.forward)NNNNNNNNNNNN)r\   r]   r^   _checkpoint_conversion_mappingr   rK   r1  r`  re  rf  r   r   r   r   r1   r   r   r_   r   r2   r   r   r   r[   r`   r9   r9   rU   r:   r^  t  sJ               r^  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gZed 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d eej eej eej eej eej eej eej eej eeeeej f  eej eej ee eej eeejf ee eeef dddZd! fdd	Z fddZ   Z!S )"MllamaForConditionalGenerationzmodel.language_modelzmodel.vision_modelzmodel.multi_modal_projectorrS  )z^language_model.modelz^vision_modelz^multi_modal_projectorz^language_model.lm_headrO  rb   c                    s<   t  | t|| _tj|jj|jjdd| _	| 
  d S r   )rJ   rK   r^  rR  r   rn   rP  rL   rB  rS  r0  rr   rU   r9   r:   rK     s    
z'MllamaForConditionalGeneration.__init__c                 C   s
   | j  S rk   )rR  r1  r   r9   r9   r:   r1    s    z3MllamaForConditionalGeneration.get_input_embeddingsc                 C   s   | j | d S rk   )rR  r`  ra  r9   r9   r:   r`    s    z3MllamaForConditionalGeneration.set_input_embeddingsc                 C   s   | j | d S rk   )rR  re  rc  r9   r9   r:   re    s    z*MllamaForConditionalGeneration.set_decoderc                 C   s
   | j  S rk   )rR  rf  r   r9   r9   r:   rf    s    z*MllamaForConditionalGeneration.get_decoderc                 C   s   | j jS rk   )rR  rN  r   r9   r9   r:   rN  !  s    z-MllamaForConditionalGeneration.language_modelc                 C   s   | j jS rk   )rR  r#  r   r9   r9   r:   r#  %  s    z+MllamaForConditionalGeneration.vision_modelNr   )rH  r3  r<   rY   rD   r$   r   r   r   r  rT  r   r   rU  r   r'   c                 K   s   | j f |||||||||	|
||d|}|j}t|trFt| dn|}| |dd|ddf }d}|dur| 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']
        ```
        )rH  r3  r<   rY   r$   r   rD   r   r   r  r   r   NrV  )rR  r   r   r   rY  rS  rZ  rH   rP  rB  r   r   rs   r  )rT   rH  r3  r<   rY   rD   r$   r   r   r   r  rT  r   r   rU  r   r[  rs   r\  rX  rW  r9   r9   r:   r[   )  s:    Pz&MllamaForConditionalGeneration.forwardFc                    sT   t  j|f|	|
|||||||||d|}|d dkrPd |d< d |d< d |d< |S )N)r   r   r  r   rD   r3  rY   r<   r$   r   rU  r   r3  rY   r<   )rJ   prepare_inputs_for_generation)rT   rH  r  rD   r   r3  rY   r<   r$   r   r   r   rU  r   Zmodel_inputsrU   r9   r:   ri    s,    z<MllamaForConditionalGeneration.prepare_inputs_for_generationc                    sZ   | dd }t jf |||d|}|d urVtj||d d dd df gdd|d< |S )Nr$   )r[  model_kwargsis_encoder_decoderr*   .r   r(   )getrJ   #_update_model_kwargs_for_generationr1   r   )rT   r[  rj  rk  r   Zcross_attention_mask_prevrU   r9   r:   rm    s    
zBMllamaForConditionalGeneration._update_model_kwargs_for_generation)NNNNNNNNNNNNNr   )NNNNNNNNNFNN)"r\   r]   r^   rg  r]  r   rK   r1  r`  re  rf  propertyrN  r#  r   r   r   r1   r   r   r_   r   r   rL  r2   r   r   r   r   r   r[   ri  rm  r`   r9   r9   rU   r:   rh     s~   

              
q            +rh  )rh  rM  r?  r  r  r^  )r{   )Nr   )\r   r   typingr   r   r   r1   Ztorch.nn.functionalr   r   r:  Ztorch.utils.checkpointZactivationsr   Zcache_utilsr   r	   Z
generationr
   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   Zmodeling_layersr   Zmodeling_outputsr   r   r   Zmodeling_rope_utilsr   r   Zmodeling_utilsr   r   Zprocessing_utilsr   utilsr   r   r   r   r   Zutils.deprecationr   Zutils.genericr   r   Zconfiguration_mllamar   r    r!   Z!torch.nn.attention.flex_attentionr"   Zintegrations.flex_attentionr#   Z
get_loggerr\   loggerr_   r   r  r   r;   r&   rE   ModulerF   ra   rj   rz   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r?  rM  r^  rh  __all__r9   r9   r9   r:   <module>   s   
& 7+0Z
GJ5 5 A m  R