
    %	&hIS                    L   d dl Z d dlmZ d dlmZmZmZmZmZ d dl	Z	d dl
mZ d dlmc mZ d dlZ	d dlmZ ddlmZ ddlmZ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 m!Z! ddl"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/m0Z0m1Z1  e,       rd dl2m3Z3 ddl4m5Z5  e-jl                  e7      Z8dZ9dZ: G d dejv                        Z< G d dejv                        Z= G d de	j                  jv                        Z> G d dejv                        Z? G d dejv                        Z@ G d  d!ejv                        ZAd"e	j                  d#e	j                  d$e	j                  d%ee	j                  e	j                  f   fd&ZCd'e	j                  d(eDd%e	j                  fd)ZE	 d]d*ejv                  d+e	j                  d,e	j                  d-e	j                  d.ee	j                     d/eFd0eFfd1ZG G d2 d3ejv                        ZH G d4 d5ejv                        ZId6ZJ e*d7eJ       G d8 d9e&             ZKd:ZL e*d7eJ       G d; d<eK             ZM G d= d>eKe      ZNe G d? d@e!             ZO G dA dBe	j                  jv                        ZP G dC dDejv                        ZQdE ZR G dF dGejv                        ZSdHZTdIe	j                  d+e	j                  fdJZUd+e	j                  d,e	j                  dIe	j                  d%ee	j                  e	j                  f   fdKZV G dL dMejv                        ZW G dN dOejv                        ZX G dP dQejv                        ZY G dR dSejv                        ZZ G dT dUejv                        Z[ G dV dWejv                        Z\ G dX dYeK      Z] G dZ d[eKe      Z^g d\Z_y)^    N)	dataclass)CallableListOptionalTupleUnion)Llama4VisionConfig   )ACT2FN)CacheHybridChunkedCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs)BaseModelOutputBaseModelOutputWithPastCausalLMOutputWithPastModelOutput)ROPE_INIT_FUNCTIONS)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)add_start_docstrings%add_start_docstrings_to_model_forwardis_torch_flex_attn_availableloggingreplace_return_docstrings   )Llama4ConfigLlama4TextConfig)	BlockMask)make_flex_block_causal_maskzmeta-ai/Llama-4-17Br   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )Llama4TextExpertsconfigc                    t         |           |j                  | _        |j                  | _        |j
                  | _        | j                  | _        t        j                  t        j                  | j                  | j
                  d| j                  z              | _        t        j                  t        j                  | j                  | j                  | j
                  f            | _        t        |j                     | _        y N   )super__init__num_local_expertsnum_expertsintermediate_sizehidden_size
expert_dimnn	Parametertorchemptygate_up_proj	down_projr   
hidden_actact_fnselfr%   	__class__s     /var/www/pru.catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/llama4/modeling_llama4.pyr*   zLlama4TextExperts.__init__>   s    !33!'!9!9!--00LLT5E5EtGWGWYZ]a]l]lYl)mnekk43C3CT__VZVfVf2g&hiV../    hidden_statesreturnc                 \   |j                  | j                  d| j                        }t        j                  || j
                        }|j                  dd      \  }}t        j                  || j                  |      z  | j                        }|j                  d| j                        }|S )a2  
        This should really not be run on a single machine, as we are reaching compute bound:
        - the inputs are expected to be "sorted" per expert already.
        - the weights are viewed with another dim, to match num_expert, 1, shape * num_tokens, shape

        Args:
            hidden_states (torch.Tensor): (batch_size * token_num, hidden_size)
            selected_experts (torch.Tensor): (batch_size * token_num, top_k)
            routing_weights (torch.Tensor): (batch_size * token_num, top_k)
        Returns:
            torch.Tensor
        r(   dim)	viewr,   r.   r2   bmmr4   chunkr7   r5   )r9   r=   gate_upgateupnext_statess         r;   forwardzLlama4TextExperts.forwardH   s     &**4+;+;RAQAQR))M4+<+<====+biidkk$&7!7$..I!&&r4+;+;<r<   )	__name__
__module____qualname__r   r*   r2   TensorrJ   __classcell__r:   s   @r;   r$   r$   =   s*    0| 0U\\ ell r<   r$   c                   &     e Zd Zd fd	Zd Z xZS )Llama4TextMLPc                 f   t         |           ||j                  }|| _        t	        j
                  |j                  |d      | _        t	        j
                  |j                  |d      | _        t	        j
                  ||j                  d      | _	        t        |j                     | _        y NFbias)r)   r*   r-   r%   r0   Linearr.   	gate_projup_projr5   r   r6   activation_fn)r9   r%   r-   r:   s      r;   r*   zLlama4TextMLP.__init___   s    $ & 8 86#5#57HuUyy!3!35FUS#4f6H6HuU#F$5$56r<   c                     | j                  | j                  |            | j                  |      z  }| j                  |      S N)rZ   rX   rY   r5   )r9   xr5   s      r;   rJ   zLlama4TextMLP.forwardk   s7    &&t~~a'89DLLOK	~~i((r<   r\   rK   rL   rM   r*   rJ   rO   rP   s   @r;   rR   rR   ^   s    
7)r<   rR   c                   8     e Zd Zddef fdZd Zd Zd Z xZS )Llama4TextL2Normepsc                 0    t         |           || _        y r\   )r)   r*   ra   )r9   ra   r:   s     r;   r*   zLlama4TextL2Norm.__init__q   s    r<   c                     |t        j                  |j                  d      j                  dd      | j                  z         z  S Nr(   r@   T)keepdimr2   rsqrtpowmeanra   r9   r]   s     r;   _normzLlama4TextL2Norm._normu   4    5;;quuQx}}R}>IJJJr<   c                 ^    | j                  |j                               j                  |      S r\   )rk   floattype_asrj   s     r;   rJ   zLlama4TextL2Norm.forwardx   s"    zz!'')$,,Q//r<   c                      d| j                    S )Nzeps=ra   r9   s    r;   
extra_reprzLlama4TextL2Norm.extra_repr{   s    dhhZ  r<   )gư>)	rK   rL   rM   rn   r*   rk   rJ   rs   rO   rP   s   @r;   r`   r`   p   s    E K0!r<   r`   c                   2     e Zd Zd fd	Zd Zd Zd Z xZS )Llama4TextRMSNormc                     t         |           || _        t        j                  t        j                  |            | _        y)z<
        Llama4RMSNorm is equivalent to T5LayerNorm
        N)r)   r*   ra   r0   r1   r2   onesweight)r9   r.   ra   r:   s      r;   r*   zLlama4TextRMSNorm.__init__   s0     	ll5::k#:;r<   c                     |t        j                  |j                  d      j                  dd      | j                  z         z  S rd   rf   rj   s     r;   rk   zLlama4TextRMSNorm._norm   rl   r<   c                 |    | j                  |j                               j                  |      }|| j                  z  S r\   )rk   rn   ro   rx   )r9   r]   outputs      r;   rJ   zLlama4TextRMSNorm.forward   s0    AGGI&..q1##r<   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tuplerx   shapera   rr   s    r;   rs   zLlama4TextRMSNorm.extra_repr   s'    ))*+6$((<<r<   )gh㈵>)rK   rL   rM   r*   rk   rJ   rs   rO   rP   s   @r;   ru   ru      s    <K$=r<   ru   c                   $     e Zd Z fdZd Z xZS )Llama4TextMoec                 *   t         |           |j                  | _        |j                  | _        |j                  | _        t        |      | _	        t        j                  |j                  |j                  d      | _        t        |      | _        y rT   )r)   r*   num_experts_per_toktop_kr.   
hidden_dimr+   r,   r$   expertsr0   rW   routerrR   shared_expertr8   s     r;   r*   zLlama4TextMoe.__init__   sp    //
 ,,!33(0ii 2 2F4L4LSXY*62r<   c                 ,   |j                   \  }}}|j                  d| j                        }| j                  |      j	                  dd      }||z  }t        j                  |j	                  dd      | j                  d      \  }}t        j                  |j	                  dd      t        d            j                  d||      j	                  dd      }	t        j                  ||j                        j                  dd      j                  |	j                  d      d      }t        j                  |	j                               j!                  |j"                        }	|j%                  dd      j                  d|      }t        j&                  |d|      j!                  |j                        }
|
|	j%                  dd      z  }
| j)                  |
      }| j+                  |      }|j-                  d||j                  d|             ||	fS )	Nr@   r   r   rA   z-infdevice)inputrB   index)rB   r   src)r~   rC   r   r   	transposer2   topkr   	full_likern   scatter_aranger   expandsizesigmoidtodtypereshapegatherr   r   scatter_add_)r9   r=   batchseq_lenr   router_logitstokens_per_expertrouter_top_valuerouter_indicesrouter_scores	routed_in
routed_outouts                r;   rJ   zLlama4TextMoe.forward   s   %2%8%8"w
%**2t?M2<<QB!GO+0::m6M6MaQR6SUYU_U_ef+g(.OOM33Aq95=IXa)9:Yq!_ 	 LL*=3G3GHMMaQST[[\i\n\nop\qsuv 	 m&9&9&;<??@S@ST'//A6==b*MLL 
 "]!!
"	 	  5 5b! <<	\\),
  / 	Qn*//"j:YZM!!r<   r^   rP   s   @r;   r   r      s    3!"r<   r   c                   Z     e Zd Zddef fdZd Z ej                         d        Z xZ	S )Llama4TextRotaryEmbeddingr%   c                 `   t         |           |j                  dnd| _        |j                  | _        |j                  | _        || _        t        | j                     | _	        | j                  | j                  |      \  }| _
        | j                  d|d       | j                  | _        y )Nllama3defaultinv_freqF
persistent)r)   r*   rope_scaling	rope_typemax_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr%   r   rope_init_fnattention_scalingregister_bufferr   original_inv_freq)r9   r%   r   r   r:   s       r;   r*   z"Llama4TextRotaryEmbedding.__init__   s    %+%8%8%D)"("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%r<   c                    t        j                  |      dz   }|| j                  kD  rA| j                  | j                  ||      \  }| _        | j                  d|d       || _        || j                  k  rj| j                  | j                  kD  rP| j                  j                  |      | _        | j                  d| j                  d       | j                  | _        yyy)a  
        dynamic RoPE layers should recompute `inv_freq` in the following situations:
        1 - growing beyond the cached sequence length (allow scaling)
        2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
        r   )r   r   Fr   N)
r2   maxr   r   r%   r   r   r   r   r   )r9   position_idsr   r   r   s        r;   _dynamic_frequency_updatez3Llama4TextRotaryEmbedding._dynamic_frequency_update   s     ))L)A-T,,,/3/@/@f^e/@/f,Hd,  X% H&-D#T...43J3JTMfMf3f &*%;%;%>%>v%FD"  T-C-CPU V&*&?&?D# 4g.r<   c                    d| j                   v r| j                  ||j                         | j                  d d d d f   j	                         j                  |j                  d   dd      }|d d d d d f   j	                         }|j                  j                  }t        |t              r|dk7  r|nd}t        j                  |d	      5  |j                  |j                        |z  j                  dd
      }t        j                  t        j                  |      |      }d d d        | j                   z  }|S # 1 sw Y   xY w)Ndynamicr   r   r@   r   mpscpuF)device_typeenabledr(   )r   r   r   r   rn   r   r~   type
isinstancestrr2   autocastr   r   polar	ones_liker   )r9   r]   r   inv_freq_expandedposition_ids_expandedr   freqs	freqs_ciss           r;   rJ   z!Llama4TextRotaryEmbedding.forward   s!   &**<*I MM$4-8>>@GGHZHZ[\H]_acde ,QaZ 8 > > @hhmm%/S%AkUZFZk`e^^UC 	C&))!((36KKVVWXZ[\EEOOE$:EBI	C
  6 66		C 	Cs   AD==Er\   )
rK   rL   rM   r    r*   r   r2   no_gradrJ   rO   rP   s   @r;   r   r      s2    // /@& U]]_ r<   r   xqxkr   r>   c           	      &   t        j                   | j                         j                  g | j                  d d dd       }t        j                   |j                         j                  g |j                  d d dd       }t        j
                  ||d d d d d d d f   z        j                  d      }t        j
                  ||d d d d d d d f   z        j                  d      }|j                  |       |j                  |      fS )Nr@   r(   r
   )r2   view_as_complexrn   r   r~   view_as_realflattenro   )r   r   r   xq_xk_xq_outxk_outs          r;   apply_rotary_embr      s    
 

 2
 2 2 IBHHSbM I2 Iq I
JC


 2
 2 2 IBHHSbM I2 Iq I
JCi1dA&> >?GGJFi1dA&> >?GGJF>>"v~~b111r<   r=   n_repc                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)r~   r   r   )r=   r   r   num_key_value_headsslenhead_dims         r;   	repeat_kvr     so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr<   modulequerykeyvalueattention_maskscalingdropoutc                    t        || j                        }t        || j                        }	t        j                  ||j	                  dd            t        j                  | j                        z  }
|#|d d d d d d d |j                  d   f   }|
|z   }
t        j                  j                  |
j                         d      j                  |j                        }
t        j                  j                  |
|| j                         }
t        j                  |
|	      }|j	                  dd      j#                         }||
fS )Nr(   r
   r@   rA   ptrainingr   )r   num_key_value_groupsr2   matmulr   mathsqrtr   r~   r0   
functionalsoftmaxrn   r   r   r   r   
contiguous)r   r   r   r   r   r   r   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputs                r;   eager_attention_forwardr     s    3 ; ;<JUF$?$?@L<<z';';Aq'ABTYYvE__L!$Q1.D
0@0@0D.D%DE#k1==((););)=2(FII%++VL==((6??([L,,|\:K''1-88:K$$r<   c                   2    e Zd ZdZdef fdZ	 	 ddej                  deej                  ej                  f   de	ej                     de	e
   de	ej                     d	ee   d
eej                  e	ej                     e	eej                        f   fdZ xZS )Llama4TextAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr%   c                    t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  | _        |j                  |j                  z  | _	        |j                  | _        | j                  dz  | _
        |j                  | _        |j                  | _        |j                  | _        |j                  | _        d| _        t!        |dz   dz  dk7        | _        t%        j&                  |j
                  |j                  | j                  z  |j(                        | _        t%        j&                  |j
                  |j                  | j                  z  |j(                        | _        t%        j&                  |j
                  |j                  | j                  z  |j(                        | _        t%        j&                  |j                  | j                  z  |j
                  |j(                        | _        | j                  j2                  r(| j"                  rt5        |j6                        | _        y y y )Nr         Tr      r   rU   )r)   r*   r%   	layer_idxgetattrr.   num_attention_headsr   r   r   r   
attn_scalefloor_scaleattn_temperature_tuningattention_dropout	is_causalintuse_roper0   rW   attention_biasq_projk_projv_projo_projuse_qk_normr`   rms_norm_epsqk_normr9   r%   r   r:   s      r;   r*   zLlama4TextAttention.__init__+  s   "
F4F4F&JdJd4de#)#=#= $*$>$>&B\B\$\!#)#=#= }}d* ++!--'-'E'E$!'!9!9Y]a/145ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
 ;;""t}}+F,?,?@DL (5"r<   r=   position_embeddingsr   past_key_valuecache_positionr   r>   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      }	 | j	                  |      j                  g |d| j                   }
| j                  |      j                  |      j                  dd      }| j                  r)t        |	|
|j                  |	j                              \  }	}
t        | d      r"| j                  |	      }	| j                  |
      }
| j                  r| j                  st        j                  t        j                   |j#                         dz   | j$                  z        dz         | j&                  z  dz   }|j                  d|d   ddf      j)                  g |dd      }|	|z  j                  |	j*                        }	|	j                  dd      }	|
j                  dd      }
|%d|i}|j-                  |
|| j.                  |      \  }
}t0        }| j2                  j4                  dk7  r^| j2                  j4                  dk(  r(|j7                  d	d
      rt8        j;                  d       nt<        | j2                  j4                     } || |	|
||f| j>                  sdn| j@                  | jB                  d|\  }} |jD                  g |d jG                         }| jI                  |      }||fS )Nr@   r   r(   r        ?r  eagersdpaoutput_attentionsF`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.        )r   r   )%r~   r   r  rC   r  r  r   r  r   r   r   hasattrr  r   r2   logfloorrn   r   r   r   r   updater   r   r%   _attn_implementationgetloggerwarning_oncer   r   r  r   r   r   r	  )r9   r=   r  r   r  r  r   input_shapehidden_shapequery_statesr   r   attn_scalescache_kwargsattention_interfacer   r   s                    r;   rJ   zLlama4TextAttention.forwardI  s    $))#2.88b8$--8{{=166|D4T[[/44UkU2Ut}}U
{{=166|DNNqRST=='7j*=*@*@ATAT*U($L* 4#<<5Lj1J ''		%++~';';'='CtGWGW&WX[^^_bfbqbqqtww  &**A{21+EFMMNbP[Nb]^Nb`aNbcK(;6::<;M;MNL#--a3))!Q/
%,n=L'5'<'<ZW[WeWegs't$J(?;;++w6{{//69fjjI\^c>d##L
 '>dkk>^>^&_#$7	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r<   NN)rK   rL   rM   __doc__r    r*   r2   rN   r   r   r   
LongTensorr   r   rJ   rO   rP   s   @r;   r   r   (  s    GA/ AF +/59?)||?) #5<<#=>?) !.	?)
 !?) !!1!12?) -.?) 
u||Xell3XeELL>Q5RR	S?)r<   r   c                       e Zd Z fdZ	 	 	 	 	 	 	 	 	 ddej
                  deej
                     deej
                     deej                     de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Z xZS )Llama4TextDecoderLayerc                    t         |           |j                  | _        t        ||      | _        t        |dz   dz  dk7        | _        ||j                  v | _        | j                  rt        |      | _
        nt        ||j                        | _
        t        |j                  |j                        | _        t        |j                  |j                        | _        || _        y )Nr   r   r   )r-   rq   )r)   r*   r.   r   	self_attnr  use_chunked_attention
moe_layersis_moe_layerr   feed_forwardrR   intermediate_size_mlpru   r  input_layernormpost_attention_layernormr   r  s      r;   r*   zLlama4TextDecoderLayer.__init__  s    !--,VY?%()a-1)<)A%B"%):):: -f 5D -fHdHd eD01C1CI\I\](9&:L:LRXReRe(f%"r<   r=   r   chunk_causal_maskr   r  r  output_router_logits	use_cacher  r  r   r>   c                 b   |}| j                  |      }| j                  r||} | j                  d||
|||||	d|\  }}||z   }|}| j                  |      }| j	                  |      }| j
                  r|\  }}nd }||j                  |j                        z   }|f}|r||fz  }|r||fz  }|S )N)r=   r  r   r  r  r6  r   )r2  r-  r,  r3  r0  r/  rC   r~   )r9   r=   r   r4  r   r  r  r5  r6  r  r  r   residualattention_statesself_attn_weightsr   outputss                    r;   rJ   zLlama4TextDecoderLayer.forward  s     !,,]; %%*;*G.N /=dnn 	/
' 3))/)	/
 	/
++ !#33 !55mD))-8+8(M= M =#5#5hnn#EE ")++G''Gr<   )	NNNNFFFNN)rK   rL   rM   r*   r2   rN   r   r(  r   boolr   r   FloatTensorrJ   rO   rP   s   @r;   r*  r*    s.   #& 2648378<,1/4$)59KO5||5 !.5 $ELL1	5
 u//05 !u||!455 $D>5 'tn5 D>5 !!1!125 &eELL%,,,F&GH5 -.5 
u  (51B1BEDUDU1U+V"WW	X5r<   r*  aK  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

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

    Parameters:
        config ([`Llama4Config`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zTThe bare Llama4 Model outputting raw hidden-states without any specific head on top.c                   <    e Zd ZeZdZdgZdZdZdZ	dZ
dZdZdZd Zy)Llama4PreTrainedModelTpast_key_valuesFc                    t        | j                  d      r| j                  j                  n| j                  j                  j                  }t	        |t
        j                        rY|j                  j                  j                  d|       |j                  %|j                  j                  j                          y y t	        |t
        j                        rf|j                  j                  j                  d|       |j                  2|j                  j                  |j                     j                          y y y )Ninitializer_ranger  )ri   std)r  r%   rC  text_configr   r0   rW   rx   datanormal_rV   zero_	Embeddingpadding_idx)r9   r   rD  s      r;   _init_weightsz#Llama4PreTrainedModel._init_weights  s     t{{$78 KK))((:: 	
 fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . .r<   N)rK   rL   rM   r   config_classsupports_gradient_checkpointing_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_flex_attn_supports_cache_class_supports_quantized_cache_supports_static_cache_supports_attention_backendrK  r8  r<   r;   r@  r@    sF    
  L&*##4"5"N  $!"&?r<   r@  a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

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

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

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

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

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

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

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

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

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

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance, see our
            [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
            - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
            cache format.

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

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                       e Zd ZdgZdZeZdef fdZd Zd Z	 e
e      	 	 	 	 	 	 	 	 	 	 d"dej                  deej                     d	eej                     d
ee   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       Zej2                  j5                  d      	 	 	 d#dej                  dej                  dej                  d
edef
d       Zdedededej:                  dej                  f
dZedej                  dededej@                  dej:                  dej                  d efd!       Z! xZ"S )$Llama4TextModelr*  modelr%   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nrq   )r%   F)r)   r*   pad_token_idrJ  
vocab_sizer0   rI  r.   embed_tokens
ModuleListrangenum_hidden_layersr*  layersru   r  normr   
rotary_embgradient_checkpointing	post_initr  s      r;   r*   zLlama4TextModel.__init__Y  s     !.. ++LL):):F<N<NPTP`P`ammHMfNfNfHgh9#FI6h
 &f&8&8f>Q>QR	36B&+# 	 is   Dc                     | j                   S r\   r\  rr   s    r;   get_input_embeddingsz$Llama4TextModel.get_input_embeddingsi  s       r<   c                     || _         y r\   rf  r9   r   s     r;   set_input_embeddingsz$Llama4TextModel.set_input_embeddingsl  s
    !r<   	input_idsr   r   rA  inputs_embedsr6  r  output_hidden_statesreturn_dictr  flash_attn_kwargsr>   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|	|	n| j                   j                  }	|d u |d uz  rt        d      | j                  r%| j                  r|rt        j                  d       d}|>| j                  |j                  | j                  j                  j                              }|r3|1t        | j                   |j                  d   |j                  d         }|
F||j!                         nd}t#        j$                  |||j                  d   z   |j                        }
||
j'                  d      }| j)                  |||
|||      \  }}|}| j+                  ||      }|rdnd }|rdnd }| j,                  d | j                   j.                   D ]k  }|r||fz  }| j                  r2| j                  r&| j1                  |j2                  ||||||d||
|      }n ||f|||||||
|d	|}|d   }|sc||d   fz  }m | j5                  |      }|r||fz  }t7        ||r|nd ||
      }|	r|S |j9                         S )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   )r6  r8  )r   r4  r   r  r  r6  r  r  )last_hidden_staterA  r=   
attentions)r%   r  rm  r6  use_return_dict
ValueErrorrc  r   r  r  r\  r   rx   r   r   r~   get_seq_lengthr2   r   	unsqueeze_update_causal_maskrb  r`  r_  _gradient_checkpointing_func__call__ra  r   to_tuple)r9   rk  r   r   rA  rl  r6  r  rm  rn  r  ro  past_seen_tokensr   r4  r=   freq_cisall_hidden_statesall_self_attnsdecoder_layerlayer_outputsr{   s                         r;   rJ   zLlama4TextModel.forwardo  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]-t";<YZZ&&4==Yj I  --ill4;L;L;S;S;Z;Z.[\M00m>Q>QRS>TVcViVijkVlmO!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L)-)A)AM>?L]ir *B *
&& & ??=,? #7BD0d![[)H4;;+H+HI #	6M#!m%55!**t}} $ A A!**!% #%"! !.!!#.&7!-#2&7'#1(0! (! *!,M =#3"55G#	6J 		-0  -!11(+/8Od+%	
 %v;&//*;;r<   F)	recursiveinput_tensorc           
      2   | j                   j                  dk(  r||dk(  j                         r||fS y| j                   j                  dvry|j                  d   }|j	                  | j
                        }| j                   j                  }	|d   }
||j                         xs |}n||j                  d   n|}|
|	k\  }|
|	k  |
|z   |	kD  z  }|r5t        j                  ||	|z   dz
  t        j                  ||
|z   |	            n|}| j                   j                  dk(  r{t        |t        j                        rM|
t        |
|	z
  dz   d      f}t        || j                   j                  |||	      }t        ||||
df
      }||fS t        |t              r||fS |j                  |j
                  }}| j!                  ||t        ||	      ||||j                  d         }|| j                   j                  kD  r?t        |
|	z
  dz   d      }||z   }| j#                  | j                   j                  |||      }|d d ||f   }|j                  d   |	k  }|r2t$        j&                  j)                  |d|	|j                  d   z
  f      }|s|d d | d d d f   }n|d d |d d f   }|j+                  |j                  d   ddd      }||d d d d d d f   z  }| j                   j                  dk(  rHt        j,                  |      j.                  }t        j                  |dk(  |d      j	                  |      }| j                   j                  dk(  r`|^|j
                  j0                  dv rF|j2                  dk(  r7|s5t        j,                  |      j.                  }t5        j6                  ||      }| j                   j                  dk(  rG|E|j9                         }|j9                         }t5        j:                  |||
| j<                        rd }||fS )Nflash_attention_2r  r&  )r  flex_attentionr  r   r   r@   r  )offsets)query_length
key_lengthr  )sequence_lengthtarget_lengthr   r   r  
batch_size)startendr   r  r  )cudaxpur   )rl  past_key_values_lengthis_training)r%   r  anyr~   r   r   attention_chunk_sizeget_max_cache_shaper2   wherer   rN   r   r"   r!   r   5_prepare_4d_causal_attention_mask_with_cache_positioncreate_chunked_attention_maskr0   r   padr   finfominr   ndimr   _unmask_unattendedr=  _ignore_causal_mask_sdpar   )r9   r   r  r  rA  r  chunked_attention_maskr6  r  r  first_cache_positionfull_cache_lengthcond1cond2r  r  r   r   r   	start_idxend_idxlocal_attention_maskrequires_padding	min_dtypes                           r;   rx  z#Llama4TextModel._update_causal_mask  s    ;;++/BB)~/D.I.I.K%~55;;++3VV&,,Q/'**4;;7#{{??-a0& / C C E X<J<V 4 4R 8\k$(<<%(<< ?25II
  KK$6:E#7/#IK_` # 	 ;;++/??.%,,7/5IL`5`cd5dfg1hi)D"DKK$D$DoWakr*& "="!00115	" &'===.)4%'=== %**L,?,?vPP+/1EF)#))!, Q 
 t{{???03GG!KQOI*,G%)%G%G00	 &H &" $2!Yw5F2F#G 399"=@TT')}}'8'8(1.BEYE_E_`bEc.c*d($ $)?d_L\L]_`@`)a&)?dN\]@])^&%;%B%B<CUCUVWCXZ\^`bd%e"%;>RSTVZ\`bcSc>d%d"{{//7:!KK.22	).5Kq5PR[]`)a)d)dej)k& KK,,6*%%**o=##q(%
 E*..I0CCKQZ[K ;;++v5:P:\%;%@%@%B"%**,K%>>*'; MM	 #222r<   r  r  r  r   c                 (   t        j                  |||      }t        j                  |j                  d      |z  |j                  d      |z  z
        }|j                  d      |j                  d      z
  }|dk(  |dk  z  }|j	                  |      S )u  
        Generate the following:

        'What'      :  0 ■ ⬚ ⬚ ⬚ ⬚ ⬚    |
        '▁is'       :  1 ■ ■ ⬚ ⬚ ⬚ ⬚     |
        '▁ch'       :  2 ■ ■ ■ ⬚ ⬚ ⬚     |
        'unked'     :  3 ⬚ ⬚ ⬚ ■ ⬚ ⬚    |
        '▁attention':  4 ⬚ ⬚ ⬚ ■ ■ ⬚    |
        '?'         :  5 ⬚ ⬚ ⬚ ■ ■ ■     |

        If the chunk size is 3.
        This can just be appplied over the already created attention mask
        r   r   r   )r2   r   absrw  r   )	r9   r  r  r  r   arange_vector	block_pos	token_posmasks	            r;   r  z-Llama4TextModel.create_chunked_attention_mask[  s      UC?II##A&*>>AXAXYZA[_sAss
	 "++A.1H1H1KK	Q9>2wwvr<   r  r  r   r  c                    | | j                         dk(  r| }|S t        j                  |      j                  }	t        j                  ||f|	||      }|dk7  rt        j
                  |d      }|t        j                  ||      |j                  |      j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }
|ddddddd|
f   | ddddddf   j                  |      z   }|dk(  }|ddddddd|
f   j                  ||	      |ddddddd|
f<   |S )	a  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to plcae the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        Nr   
fill_valuer   r   r   diagonalr   r@   r   )rB   r2   r  r  fulltriur   r   r   r   cloner~   masked_fillr   r  r  r   r   r  r  r   r   r  mask_lengthpadding_masks               r;   r  zELlama4TextModel._prepare_4d_causal_attention_mask_with_cache_positions  sx   B %.*<*<*>!*C(K& # E*..I** -0Ye\bK !##jjqA5<<fEHYHYZ`HaHiHijlnoHpppK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDghnDoo+q05@Aq,;,AV5W5c5c )6Aq!\k\12 r<   )
NNNNNNNNNN)FNT)#rK   rL   rM   _no_split_modulesbase_model_prefixr    rL  r*   rg  rj  r   LLAMA4_INPUTS_DOCSTRINGr2   r(  r   rN   r   r>  r=  r   r   r   r   r   rJ   compilerdisablerx  r  r   r  staticmethodr   r  rO   rP   s   @r;   rW  rW  P  sU   
 22#L/  !" ++BC '+1537+/59$(,0/3&*59k<##k< !.k< u//0	k<
 "%k<   1 12k< D>k< $D>k< 'tnk< d^k< !!1!12k< $$89k< 
u--	.k< Dk<Z ^^e, #(#{3{3 ll{3 	{3
 {3  {3 -{3z$'03:=GL||	0 555 5 {{	5
 5 5 5 5r<   rW  c                       e Zd ZdZdgZddiZeZdef fdZd Z	d Z
d	 Zd
 Zd Zd Z ee       eee      	 	 	 	 	 	 	 	 	 	 	 	 ddej*                  deej.                     deej*                     deeeeej6                     f      deej6                     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ef   fd              Z xZ S )Llama4ForCausalLMlanguage_modelzlm_head.weightlm_headcolwise_repr%   c                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y rT   )
r)   r*   rW  rX  r[  r0   rW   r.   r  rd  r8   s     r;   r*   zLlama4ForCausalLM.__init__  sU     $V,
 ++yy!3!3V5F5FUS 	r<   c                 .    | j                   j                  S r\   rX  r\  rr   s    r;   rg  z&Llama4ForCausalLM.get_input_embeddings  s    zz&&&r<   c                 &    || j                   _        y r\   r  ri  s     r;   rj  z&Llama4ForCausalLM.set_input_embeddings  s    "'

r<   c                     | j                   S r\   r  rr   s    r;   get_output_embeddingsz'Llama4ForCausalLM.get_output_embeddings  s    ||r<   c                     || _         y r\   r  r9   new_embeddingss     r;   set_output_embeddingsz'Llama4ForCausalLM.set_output_embeddings  s	    %r<   c                     || _         y r\   rX  r9   decoders     r;   set_decoderzLlama4ForCausalLM.set_decoder  s	    
r<   c                     | j                   S r\   r  rr   s    r;   get_decoderzLlama4ForCausalLM.get_decoder  s    zzr<   output_typerL  rk  r   r   rA  rl  labelsr6  r  rm  rn  r  logits_to_keepr>   c                 8   ||n| j                   j                  }|	|	n| j                   j                  }	|
|
n| j                   j                  }
 | j                  d||||||||	|
|d
|}|d   }t        |t              rt        | d      n|}| j                  |dd|ddf         }d}|* | j                  d||| j                   j                  d|}|
s|f|dd z   }||f|z   S |S t        |||j                  |j                  |j                        S )a>  
        Args:
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

            logits_to_keep (`int` or `torch.Tensor`, *optional*):
                If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
                If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
                This is useful when using packed tensor format (single dimension for batch and sequence length).

        Returns:

        Example:

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

        >>> model = Llama4ForCausalLM.from_pretrained("meta-llama4/Llama4-2-7b-hf")
        >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama4/Llama4-2-7b-hf")

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
        ```N)
rk  r   r   rA  rl  r6  r  rm  rn  r  r   )logitsr  r[  r   )lossr  rA  r=   rs  r8  )r%   r  rm  rt  rX  r   r  slicer  loss_functionr[  r   rA  r=   rs  )r9   rk  r   r   rA  rl  r  r6  r  rm  rn  r  r  r   r<  r=   slice_indicesr  r  r{   s                       r;   rJ   zLlama4ForCausalLM.forward  s`   d 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] $** 
)%+'/!5#)
 
  
8B>SV8W~ot4]kmA}a,?@A%4%%pVFt{{OeOepiopDY,F'+'7D7V#CVC%#33!//))
 	
r<   )NNNNNNNNNNNr   )!rK   rL   rM   r  _tied_weights_keys_tp_planr    rL  r*   rg  rj  r  r  r  r  r   r  r   r   _CONFIG_FOR_DOCr2   r(  r   rN   r   r   r   r>  r=  r  r   rJ   rO   rP   s   @r;   r  r    s   (*+=)H#L/ '(& ++BC+AP_` '+1537KO59-1$(,0/3&*5934W
##W
 !.W
 u//0	W

 "%tE4E4E/F(F"GHW
   1 12W
 ))*W
 D>W
 $D>W
 'tnW
 d^W
 !!1!12W
 c5<</0W
 
u,,	-W
 a DW
r<   r  c                      e Zd ZU dZdZeej                     ed<   dZ	ej                  ed<   dZ
eeej                        ed<   dZeeej                        ed<   dZeeej                        ed<   dZeej                     ed<   y)	Llama4CausalLMOutputWithPasta  
    Base class for Llava causal language model (or autoregressive) outputs.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

            Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        image_hidden_states (`torch.FloatTensor`, *optional*):
            A `torch.FloatTensor` of size (batch_size, num_images, sequence_length, hidden_size)`.
            image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
    Nr  r  rA  r=   rs  image_hidden_states)rK   rL   rM   r'  r  r   r2   r>  __annotations__r  rA  r   r=   r   rs  r  r8  r<   r;   r  r  )  s    < )-D(5$$
%, $FE$9=OXd5#4#456=8<M8E%"3"345<59Ju001297;%"3"34;r<   r  c                   $     e Zd Z fdZd Z xZS )Llama4VisionMLP2c                 ~   t         |           |j                  | _        |j                  | _        t	        j
                  | j                  |j                  d      | _        t	        j
                  |j                  |j                  d      | _	        t	        j                         | _        |j                  | _        y rT   )r)   r*   r.   r-   r0   rW   projector_input_dimfc1projector_output_dimfc2GELUrZ   projector_dropoutr   r8   s     r;   r*   zLlama4VisionMLP2.__init__R  s    !--!'!9!999T33V5O5OV[\99V88&:U:U\abWWY//r<   c                     | j                  |      }| j                  |      }t        j                  || j                  | j                        }| j                  | j                  |            S )Nr   )r  rZ   Fr   r   r  r9   r=   s     r;   rJ   zLlama4VisionMLP2.forward[  sT    /**=9		-4<<$--X!!$((="9::r<   r^   rP   s   @r;   r  r  Q  s    0;r<   r  c                   $     e Zd Z fdZd Z xZS )Llama4MultiModalProjectorc                     t         |           t        j                  |j                  j
                  |j                  j                  d      | _        y rT   )	r)   r*   r0   rW   vision_configvision_output_dimrE  r.   linear_1r8   s     r;   r*   z"Llama4MultiModalProjector.__init__c  s?    		  22**
r<   c                 (    | j                  |      }|S r\   )r  )r9   image_featuresr=   s      r;   rJ   z!Llama4MultiModalProjector.forwardk  s    n5r<   r^   rP   s   @r;   r  r  b  s    
r<   r  c           
      J   | j                   \  }}}t        t        j                  |            }| j	                  |||d      } | j                         \  }}}}| j	                  ||t        ||z        t        ||z              }|j                  dddd      j                         }|j	                  |t        ||z        t        ||z        t        ||dz  z              }|j                  dddd      j                         }|j	                  |d|j                   d         }	|	S )Nr@   r   r(   r   r
   )r~   r  r   r   rC   r   permuter   )
r  shuffle_ratior  num_patcheschannels
patch_sizeheightwidthreshaped_tensoroutput_tensors
             r;   pixel_shuffler  p  s%   (4(:(:%JXTYY{+,J$$ZZLL*6*;*;*='Jx"''
FC@U<VX[\dgt\tXuvO%--aAq9DDFO%**C./U]5J1KSQY]jlm]mQnMoO &--aAq9DDFO#((R9N9Nr9RSMr<   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )Llama4VisionPixelShuffleMLPc                     t         |           |j                  | _        t        |j                  | j                  dz  z        | _        |j                  | _        t        |      | _	        y r'   )
r)   r*   pixel_shuffle_ratior  r  	inner_dimr  
output_dimr  mlpr8   s     r;   r*   z$Llama4VisionPixelShuffleMLP.__init__  sX    #)#=#= V77D<T<TVW<WXY 55#F+r<   encoded_patchesr>   c                 P    t        || j                        }| j                  |      S r\   )r  r  r  )r9   r  s     r;   rJ   z#Llama4VisionPixelShuffleMLP.forward  s#    '9Q9QRxx((r<   rK   rL   rM   r*   r2   rN   rJ   rO   rP   s   @r;   r	  r	    s#    ,)u|| ) )r<   r	  ac  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

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

    Parameters:
        config ([`LlavaConfig`] or [`LlavaVisionConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
freqs_cic                     |j                   }t        |j                        D cg c]  \  }}|dk(  s||dz
  k(  r|nd }}} | j                  | S c c}}w )Nr   )r  	enumerater~   rC   )r  r   r  idr~   s         r;   reshape_for_broadcastr    sW    ::D=Fu{{=STTQ!q&AMQq0TET8==%   Us   Ac                 B   t        j                   | j                         j                  g | j                  d d dd       }t        j                   |j                         j                  g |j                  d d dd       }t        ||      }|j                  |j                        }t        j                  ||z        j                  d      }t        j                  ||z        j                  d      }|j                  |       |j                  |      fS )Nr@   r(   )r  r   r
   )r2   r   rn   r   r~   r  r   r   r   r   ro   )r   r   r  query_key_	query_outkey_outs          r;   vision_apply_rotary_embr    s    
 ""#85;;=#8#8#R%++cr:J#RB#RPQ#RSF  !4!4!4!Lciin!Lb!L!!LMD$hfEH{{6==)H""6H#45==a@I  199!<GU#W__S%999r<   c                        e Zd Zdef fdZ	 	 d
dej                  dej                  deej                     dee   de	e
   deej                  eej                     eeej                        f   fd	Z xZS )Llama4VisionAttentionr%   c                    t         |           || _        |j                  | _        |j
                  | _        |j                  |j
                  z  | _        d| _        |j                  | _	        t        j                  | j                  | j                  | j                  z  d      | _        t        j                  | j                  | j                  | j                  z  d      | _        t        j                  | j                  | j                  | j                  z  d      | _        t        j                  | j                  | j                  z  | j                  d      | _        y )Nr   TrU   )r)   r*   r%   r.   	embed_dimr   	num_headsr   r   r  r0   rW   r  r  r  r	  r8   s     r;   r*   zLlama4VisionAttention.__init__  s    ++33**f.H.HH$%!!'!9!9ii0NUYZii0NUYZii0NUYZii >UYZr<   r=   r  r   r  r   r>   c                 R   |j                   d d }g |d| j                  }| j                  |      j                  |      }| j	                  |      j                  |      }	| j                  |      j                  |      }
t        ||	|      \  }}	|j                  dd      }|	j                  dd      }	|
j                  dd      }
t        }| j                  j                  dvr^| j                  j                  dk(  r(|j                  dd      rt        j                  d	       nt        | j                  j                     } || ||	|
d f| j                  sd
n| j                   d dd|\  }} |j"                  g |d j%                         }| j'                  |      }||fS )Nr@   )r  r   r(   )r  r  r  r  Fr  r  )r   r   r  )r~   r   r  rC   r  r  r  r   r   r%   r  r  r  r  r   r   r  r   r   r	  )r9   r=   r  r   r  r   r   r!  r"  r   r   r%  r   r   s                 r;   rJ   zLlama4VisionAttention.forward  s    $))#2.88b8$--8{{=166|D[[/44\B
{{=166|D#:<^f#g j#--a3))!Q/
#--a3(?;;++3NN{{//69fjjI\^c>d##L
 '>dkk>^>^&_#$7
%
  $}}C$2H2H
%
 
%
!\ *k));;;;FFHkk+.L((r<   r&  )rK   rL   rM   r	   r*   r2   rN   r   r   r   r   r   rJ   rO   rP   s   @r;   r  r    s    [1 [$ 26*..)||.) ,,.) !.	.)
 !.) -..) 
u||Xell3XeELL>Q5RR	S.)r<   r  c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )Llama4VisionMLPc                 &   t         |           || _        t        j                         | _        t        j                  |j                  |j                  d      | _	        t        j                  |j                  |j                  d      | _
        y )NTrU   )r)   r*   r%   r0   r  rZ   rW   r.   r-   r  r  r8   s     r;   r*   zLlama4VisionMLP.__init__  se    WWY99V//1I1IPTU99V55v7I7IPTUr<   r=   r>   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r\   )r  rZ   r  r  s     r;   rJ   zLlama4VisionMLP.forward  s4    /**=9/r<   r  rP   s   @r;   r%  r%    s$    VU\\ ell r<   r%  c            	            e Zd Zdef fdZ	 	 ddej                  dej                  deej                     defdZ	 xZ
S )	Llama4VisionEncoderLayerr%   c                    t         |           |j                  | _        t        |      | _        t        |      | _        t        j                  |j                        | _	        t        j                  |j                        | _
        y r\   )r)   r*   r.   r  r,  r%  r  r0   	LayerNormr2  r3  r8   s     r;   r*   z!Llama4VisionEncoderLayer.__init__  sb    !--.v6"6*!||F,>,>?(*V5G5G(H%r<   hidden_stater  r   r  c                     |}| j                  |      }| j                  |||      \  }}||z   }|}| j                  |      }| j                  |      }||z   }|f}|r||fz  }|S )N)r  r   )r2  r,  r3  r  )r9   r,  r  r   r  r9  r   r<  s           r;   rJ   z Llama4VisionEncoderLayer.forward  s      ++L9%)^^) &4 &
"l
  ,.  44\Bxx-,./&Gr<   r&  )rK   rL   rM   r	   r*   r2   rN   r   r=  rJ   rO   rP   s   @r;   r)  r)    sV    I1 I 26"&ll ,, !.	
  r<   r)  c                        e Zd ZdZdef fdZ	 	 	 	 ddej                  dej                  deej                     dee	   dee	   d	ee	   d
e
eef   fdZ xZS )Llama4VisionEncoderz
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`Llama4VisionEncoderLayer`].

    Args:
        config: Llama4VisionConfig
    r%   c                     t         |           || _        t        j                  t        |j                        D cg c]  }t        |       c}      | _        d| _	        || _        y c c}w )NF)
r)   r*   r%   r0   r]  r^  r_  r)  r`  rc  )r9   r%   _r:   s      r;   r*   zLlama4VisionEncoder.__init__;  sW    mmuU[UmUmOn$o!%=f%E$op&+# %ps   A*r=   r  r   r  rm  rn  r>   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|rdnd}|rdnd}| j                  D ]^  }	|r||fz   }| j
                  r,| j                  r | j                  |	j                  ||||      }
n |	||||      }
|r	||
d   fz   }|
d   }` |r||fz   }|st        d |||fD              S t        |||      S )ad  
        Args:
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
                This is useful if you want more control over how to convert `input_ids` indices into associated vectors
                than the model's internal embedding lookup matrix.
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

                [What are attention masks?](../glossary#attention-mask)
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        Nr8  )r,  r   r  r  r   r   c              3   &   K   | ]	  }||  y wr\   r8  .0vs     r;   	<genexpr>z.Llama4VisionEncoder.forward.<locals>.<genexpr>  s     eqWXWde   rr  r=   rs  )r%   r  rm  rt  r`  rc  r   ry  rz  r}   r   )r9   r=   r  r   r  rm  rn  encoder_statesall_attentionsencoder_layerr  s              r;   rJ   zLlama4VisionEncoder.forwardB  s6   > 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]30d![[ 	-M#!/=2B!B**t}} $ A A!**!"%! !.!.#1&7%	! !!/=3C2E!E)!,M-	-0  +}.>>Ne]NN$Seee+>Vd
 	
r<   NNNN)rK   rL   rM   r'  r	   r*   r2   rN   r   r=  r   r   r   rJ   rO   rP   s   @r;   r/  r/  2  s    1  26,0/3&*G
||G
 ,,G
 !.	G

 $D>G
 'tnG
 d^G
 
uo%	&G
r<   r/  c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )Llama4UnfoldConvolutionc                 <   t         |           |j                  }t        |t              r||f}t
        j                  j                  ||j                        | _        t        j                  |j                  |d   z  |d   z  |j                  d      | _        y )N)kernel_sizestrider   r   FrU   )r)   r*   r  r   r  r2   r0   UnfoldunfoldrW   num_channelsr.   linear)r9   r%   rA  r:   s      r;   r*   z Llama4UnfoldConvolution.__init__  s    ''k3'&4Khhoo+fFWFWoXii+a.0;q>A
r<   r=   r>   c                 p    | j                  |      }|j                  ddd      }| j                  |      }|S )Nr   r(   r   )rD  r  rF  r  s     r;   rJ   zLlama4UnfoldConvolution.forward  s8    M2%--aA6M2r<   r  rP   s   @r;   r?  r?    s#    

U\\ ell r<   r?  c                   $     e Zd Z fdZd Z xZS )Llama4VisionRotaryEmbeddingc                    t         |           |j                  |j                  z  }t	        j
                  |dz  t        j                        j                  |dz  d      }t	        j                  ||d d gd      }d|d<   ||z  }||z  }|j                  |j                  z  dz  }d|j                  t	        j
                  d|d      d |dz   j                         |z  z  z  }|dz   d	   |d d d d f   z  j                  dd
      }|dz   d	   |d d d d f   z  j                  dd
      }	t	        j                  ||	gd
      j                         j                         dd d df   }
|
j                  |j                  d
dd      dk  d      }
t	        j                   t	        j"                  t	        j$                  |
      t	        j&                  |
      gd
            }|| _        y )Nr(   )r   r   r   rA   r   )r@   r@   r  ).Nr@   .)r)   r*   
image_sizer  r2   r   int32r   catr.   r   
rope_thetarn   repeat_interleaver   r  r   stackcossinr  )r9   r%   idximg_idxfrequencies_xfrequencies_yfreq_dim	rope_freqfreqs_xfreqs_yr   r}  r:   s               r;   r*   z$Llama4VisionRotaryEmbedding.__init__  s   6#4#44,,sAvU[[9AA#q&!L))Wgbqk2:#3%%)C)CCqH6,,a11MN_QY]^Q^1`1f1f1hks1stu	!A%y1IdD!m4LL__`agi_j!A%y1IdD!m4LL__`agi_j		7G,"5;;=HHJ3PSRSPS8T!!'//"a";a"?C((eii6F		RWHX5Y_a)bc r<   c                 L    | j                   j                  |j                        S r\   )r  r   r   r  s     r;   rJ   z#Llama4VisionRotaryEmbedding.forward  s    }} 4 455r<   r^   rP   s   @r;   rI  rI    s    !"6r<   rI  c                        e Zd ZdZdgZeZdef fdZd Z	 	 	 	 dde	j                  dee	j                     dee   d	ee   d
ee   deeee	j                  df   f   fdZ xZS )Llama4VisionModelvision_modelr)  r%   c                 r   t         |   |       |j                  | _        |j                  | _        |j                  | _        |j
                  | _        | j                  | j                  z  dz  dz   | _        |j                  dz  | _        t        |      | _	        t        j                  | j                  t        j                  | j                        z        | _        t        j                  | j                  t        j                  | j                  | j                        z        | _        t!        |      | _        t        j$                  | j                        | _        t        j$                  | j                        | _        t+        |      | _        t/        |      | _        | j3                          y )Nr(   r   r   )r)   r*   rK  r  r.   rE  r   scaler?  patch_embeddingr0   r1   r2   randnclass_embeddingpositional_embedding_vlmrI  rotary_embeddingr+  layernorm_prelayernorm_postr/  rX  r	  vision_adapterrd  r8   s     r;   r*   zLlama4VisionModel.__init__  sA     ++ ++!--"// OOt>1DqH''-
6v>!||DJJTEUEU9V,VW(*TZZ%++dN^N^`d`p`pBq5q(r% ;F C  \\$*:*:; ll4+;+;< )0
9&Ar<   c                     | j                   S )zg
        This function is used to fetch the first embedding layer to activate grads on inputs.
        )ra  rr   s    r;   rg  z&Llama4VisionModel.get_input_embeddings  s     ###r<   pixel_valuesr   r  rm  rn  r>   .c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|j                  \  }}}}	d}
d}| j                  |      }|j                  \  }}}|j                  ||
z  |z  ||      }| j                  j                  |j                  d   d|j                  d         }t        j                  ||gd      }|dz  }|j                  ||
z  |||      }| j                  j                  |j                  |j                        }||z   }| j                  |      }|j!                  |d|      }| j#                  |      }| j%                  |d|||      }|j&                  }| j)                  |      }|ddddddf   }| j+                  |      }|r|j,                  nd}|r|d   }nd}|st/        d	 |||fD              S t1        |||
      S )a  

        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@   rA   )r   r   )r   rm  r  r  r(   c              3   &   K   | ]	  }||  y wr\   r8  r4  s     r;   r7  z,Llama4VisionModel.forward.<locals>.<genexpr>3  s     _qQRQ^_r8  r9  )r%   r  rm  rt  r~   ra  r   rc  r   r2   rM  rd  r   r   r   rf  rC   re  rX  rr  rg  rh  r=   r}   r   )r9   rj  r   r  rm  rn  batch_size_times_num_tilesrE  r  r  num_concurrent_media
num_chunksr,  r1  r   r   rc  positional_embeddingr  r{   r=   rs  s                         r;   rJ   zLlama4VisionModel.forward  sS   > 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] COBTBT?"L&% 
++L9%1%7%7";
 $++&)==
JKYc
 ..55l6H6H6KQP\PbPbcePfgyy,!@aHq $++&)==z;Xb
  $<<??lFXFXamatat?u#&::)),7#(()CRT((6!5/  
 //**<8#AssAI. **<80D,,$JJ_\=*$M___*'!
 	
r<   r=  )rK   rL   rM   r  r  r	   rL  r*   rg  r2   rN   r   r=  r   r   r   rJ   rO   rP   s   @r;   r]  r]    s    &34%L1 2$ 26,0/3&*_
ll_
 !._
 $D>	_

 'tn_
 d^_
 
ellC&7 88	9_
r<   r]  c            &           e Zd Zi ZdZeZdZdef fdZd Z	d Z
d Zd Zd	 Zd
 Zdej                   deeee   f   defdZ eee      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d&dej2                  dej                   deej6                     deej2                     deeej                         deej                      deeeee   f      dee   deej2                     dee   dee   dee   dee   deej2                     deeej6                  f   dej6                  deeef   f"d       Z	 	 	 	 	 	 d'dZe dej6                  d ed!ed"ejB                  d#ejD                  dej6                  d$efd%       Z# xZ$S )(Llama4ForConditionalGeneration Tr%   c                 h   t         |   |       t        |j                        | _        t        |      | _        t        |j                        | _	        |j                  j                  | _
        | j                  j                  | j                  j                  nd| _        | j                          y )Nr@   )r)   r*   r]  r  r^  r  multi_modal_projectorr  rE  r  r[  r%   rZ  rd  r8   s     r;   r*   z'Llama4ForConditionalGeneration.__init__B  s     -f.B.BC%>v%F"/0B0BC ,,778<8P8P8\DKK44bdr<   c                 6    | j                   j                         S r\   )r  rg  rr   s    r;   rg  z3Llama4ForConditionalGeneration.get_input_embeddingsM  s    ""7799r<   c                 :    | j                   j                  |       y r\   )r  rj  ri  s     r;   rj  z3Llama4ForConditionalGeneration.set_input_embeddingsP  s    007r<   c                 6    | j                   j                         S r\   )r  r  rr   s    r;   r  z4Llama4ForConditionalGeneration.get_output_embeddingsS  s    ""88::r<   c                 :    | j                   j                  |       y r\   )r  r  r  s     r;   r  z4Llama4ForConditionalGeneration.set_output_embeddingsV  s    11.Ar<   c                 :    | j                   j                  |       y r\   )r  r  r  s     r;   r  z*Llama4ForConditionalGeneration.set_decoderY  s    ''0r<   c                 6    | j                   j                         S r\   )r  r  rr   s    r;   r  z*Llama4ForConditionalGeneration.get_decoder\  s    ""..00r<   rj  vision_feature_layervision_feature_select_strategyc                     |dvrt        d| j                         |j                         D ci c]  \  }}|	|| }}} | j                  |fddi|}|j                  }|S c c}}w )a  
        Obtains image last hidden states from the vision tower and apply al projection.

        Args:
            pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
               The tensors corresponding to the input images.
            vision_feature_layer (`Union[int, List[int]]`):
                The index of the layer to select the vision feature. If multiple indices are provided,
                the vision feature of the corresponding indices will be concatenated to form the
                vision features.
            vision_feature_select_strategy (`str`):
                The feature selection strategy used to select the vision feature from the vision backbone.
                Can be one of `"default"` or `"full"`
        Returns:
            image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
        )r   r  z$Unexpected select feature strategy: rm  F)ru  r}  itemsr^  rr  )	r9   rj  r|  r}  r   kr6  image_outputsr,  s	            r;   get_image_featuresz1Llama4ForConditionalGeneration.get_image_features_  s    . *1DDCDDgDgChijj#)<<>C41aQ]!Q$CC))),]U]V\]$66 Ds
   
A&A&r  rk  r   r   rA  rl  r  r6  r  rm  rn  r  r  image_sizesr>   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }||n| j                   j                  j
                  }||n| j                   j                  j                  }|du |duz  rt        d      ||t        d      | | j                         |      }|b| j                  ||||      }|j                  }|j                  d|j                  d            }| j                  |      }|| j                   j                  k(  j                  d      }|j!                  |j"                        }|j                  d|j                  d            }|d   j%                  d      }|j'                         }||j                  d      k7  r t        d| d	|j                  d             |j                  d      j)                  d|j                  d            }|j+                  ||      }|j                  |      } | j,                  d|||||
|||||d

|}|d   }d}|	<||dd|j                  d   dz
   df   j!                  |j"                        }|dddddf   |j!                  |j"                        dk7     j/                         }|	dddf   |j!                  |	j"                        dk7     j/                         } n1|dddddf   j/                         }|	dddf   j/                         } t1        j2                         }! |!|j                  d|j                  d            | j                  d      j!                  |j"                              }|s|f|dd z   }"||f|"z   S |"S t5        |||j6                  |j8                  |j:                  |      S d      S )aW  
            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]`.

            logits_to_keep (`int` or `torch.Tensor`, *optional*):
                If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
                If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
                This is useful when using packed tensor format (single dimension for batch and sequence length).


        Returns:

        Example:

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

        >>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
        >>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")

        >>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
        >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

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

        >>> # Generate
        >>> generate_ids = model.generate(**inputs, max_new_tokens=15)
        >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "USER:  \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
        ```Nrq  zdYou cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one)rj  r|  r}  r  r@   ).r   r   zMismatch: final_mask wants z0 embeddings, but multi_modal_projector returned )
r   r   rA  rl  r6  r  rm  rn  r  r  r   .)r  r  rA  r=   rs  r  r8  )r%   r  rm  rt  r  r|  r}  ru  rg  r  r~   rC   r   ru  image_token_indexrw  r   r   r   sumr   masked_scatterr  r   r0   CrossEntropyLossr  rA  r=   rs  )#r9   rk  rj  r   r   rA  rl  r|  r}  r  r6  r  rm  rn  r  r  r  	lm_kwargsr  original_inputs_embeds_shapevision_flatprojected_vision_flatspecial_image_mask
final_maskfinal_mask_1dnum_tokens_to_fillexpanded_maskr<  r  r  shift_attention_maskshift_logitsshift_labelsloss_fctr{   s#                                      r;   rJ   z&Llama4ForConditionalGeneration.forward}  sa   v 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] $/ !**?? 	 .9 +**II 	' -t";<YZZ#(Av   7D557	BM#!44)%9/M'	 5 N ,9+>+>((--b.2E2Eb2IJK$($>$>{$K!"+t{{/L/L"L!W!WXZ![+..}/C/CDJ)..r=3E3Eb3IJM&v.66r:M!.!2!2!4!%:%?%?%BB 12D1E F::O:T:TUV:W9XZ 
 *33B7>>r=CUCUVXCYZM)88H]^M)../KLM%$%% 
)%+'/!5#))
 
 ) (6a6<<?Q;N9O9Q6Q'R'U'UV\VcVc'd$%c3B3k23G3J3J6==3Y]^3^_jjl%c12g/C/F/Fv}}/UYZ/Z[ffh%c3B3k2==?%c12g99;**,H!!"l&7&7&;<l>O>OPR>S>V>VWcWjWj>kD Y,F'+'7D7V#CVC+#33!//))2>2J
 	
 QU
 	
r<   c           	      f     | j                   j                  |f|||||d|}	|d   dk(  r||	d<   |	S )N)rA  rl  r   r  r  r   rj  )r  prepare_inputs_for_generation)
r9   rk  rA  rl  rj  r   r  r  r   model_inputss
             r;   r  z<Llama4ForConditionalGeneration.prepare_inputs_for_generation  s_     It**HH
+')))
 
 !! ,8L(r<   r  r  r   r   r  c                    | | j                         dk(  r| }|S t        j                  |      j                  }	t        j                  ||f|	||      }|dk7  rt        j
                  |d      }|t        j                  ||      |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }
|ddddddd|
f   | ddddddf   j                  |j                        z   }|dk(  }|ddddddd|
f   j                  ||	      |ddddddd|
f<   |S )	a  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to place the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        Nr   r  r   r  r   r@   r   )rB   r2   r  r  r  r  r   r   r   r  r~   r   r   r  r  s               r;   r  zTLlama4ForConditionalGeneration._prepare_4d_causal_attention_mask_with_cache_position=  sy   B %.*<*<*>!*C(K* ' E*..I** -0Ye\bK !##jjqA5<<fEH^H^_acdHeeeK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c )6Aq!\k\12 r<   )NNNNNNNNNNNNNNr   N)NNNNNN)%rK   rL   rM   r  r  r   rL  rQ  r*   rg  rj  r  r  r  r  r2   r>  r   r  r   r   r  r   r  r  r(  r   rN   r=  r   rJ   r  r  r   r   r  rO   rP   s   @r;   rr  rr  <  s   HL	| 	:8;B11'' $CcN3 ),	< +GVef '+*.1537=A59@D8<-1$(,0/3&*5934$(#_
##_
 ''_
 !.	_

 u//0_
 "$u'8'8"9:_
   1 12_
 'uS$s)^'<=_
 )1_
 ))*_
 D>_
 $D>_
 'tn_
 d^_
 !!1!12_
  c5<</0!_
" \\#_
& 
u22	3'_
 g_
H < 777 7 {{	7
 7 7 7 7r<   rr  )r@  rW  r]  r  rr  )r  )`r   dataclassesr   typingr   r   r   r   r   r2   torch.nnr0   torch.nn.functionalr   r  torch.utils.checkpoint/transformers.models.llama4.configuration_llama4r	   activationsr   cache_utilsr   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_outputsr   r   r   r   modeling_rope_utilsr   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   configuration_llama4r   r    !torch.nn.attention.flex_attentionr!   integrations.flex_attentionr"   
get_loggerrK   r  _CHECKPOINT_FOR_DOCr  Moduler$   rR   r`   ru   r   r   rN   r   r  r   rn   r   r   r*  LLAMA4_START_DOCSTRINGr@  r  rW  r  r  r  r  r  r	  LLAVA_START_DOCSTRINGr  r  r  r%  r)  r/  r?  rI  r]  rr  __all__r8  r<   r;   <module>r     s     ! 9 9      N ! 4 ) > B  7 F &  A  !;J			H	%+  		 B)BII )$!uxx !=		 =(+"BII +"\3		 3l	2	2	2 ||	2 5<<%&		2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % %2`)")) `)FFRYY FR " Z?O ?	?8H V ZU+ U	Up
z
- z
z $<; $< $<N;uxx ;"		 (
)")) 
) $!ELL ! !:<<:	: ll: 5<<%&	:=)BII =)@bii )ryy )XW
")) W
tbii (6")) 6,C
- C
Ly%:O yx	r<   