
    Z j                        S r SSKJr  SSKJr  SSKJr  SSKJr  SSK	r	SSK
Js  Jr  SSK	Jr  SS	KJr  SS
KJrJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJrJrJr  SSKJ r J!r!  SSK"J#r#J$r$  SSK%J&r&  SSK'J(r(J)r)J*r*J+r+J,r,  SSK-J.r.J/r/  SSK0J1r1  SSK2J3r3J4r4  \+Rj                  " \65      r7\)\ " S S\5      5       5       r8 " S S\Rr                  5      r: " S S\Rr                  5      r;S r<SOS jr= " S  S!\Rr                  5      r> " S" S#\R~                  5      r@S$\	R                  S%\BS&\	R                  4S' jrC SPS(\Rr                  S)\	R                  S*\	R                  S+\	R                  S,\	R                  S-  S-\DS.\DS/\&\(   4S0 jjrE " S1 S2\Rr                  5      rF " S3 S4\5      rG " S5 S6\5      rH " S7 S8\Rr                  5      rI " S9 S:\Rr                  5      rJ " S; S<\Rr                  5      rK " S= S>\Rr                  5      rL " S? S@\Rr                  5      rM " SA SB5      rN\) " SC SD\$5      5       rO\)" SESF9 " SG SH\O5      5       rP\) " SI SJ\O5      5       rQ\)" SKSF9 " SL SM\O\5      5       rR/ SNQrSg)QzPyTorch Chameleon model.    )Callable)	dataclass)cached_property)OptionalN)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)create_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastBaseModelOutputWithPoolingCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tupleloggingtorch_compilable_check)maybe_autocastmerge_with_config_defaults)capture_outputs   )ChameleonConfigChameleonVQVAEConfigc                       \ rS rSr% SrSr\R                  S-  \S'   Sr	\R                  S-  \S'   Sr
\R                  S-  \S'   Srg)ChameleonVQVAEModelOutput2   a  
quantized_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
    Quantized last hidden state from the VQ-VAE model.
image_tokens (`torch.FloatTensor` of shape `(batch_size, config.vocab_size`):
    Indices of the image tokens predicted by the VQ-VAE model.
embedding_loss (`torch.FloatTensor`):
    The embedding loss computed during quantization.
Nquantized_last_hidden_stateimage_tokensembedding_loss )__name__
__module____qualname____firstlineno____doc__r&   torchFloatTensor__annotations__r'   r(   __static_attributes__r)       ځ/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/transformers/models/chameleon/modeling_chameleon.pyr$   r$   2   sJ     =A!2!2T!9@-1L%##d*1/3NE%%,3r3   r$   c                   x   ^  \ rS rSrS
S\SS4U 4S jjjrS\R                  S\R                  4S jrS r	S	r
U =r$ )ChameleonRMSNormD   epsreturnNc                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z/
ChameleonRMSNorm is equivalent to T5LayerNorm
N)super__init__r   	Parameterr/   onesweightvariance_epsilon)selfhidden_sizer8   	__class__s      r4   r<   ChameleonRMSNorm.__init__E   s/     	ll5::k#:; #r3   hidden_statesc                    UR                   nUR                  [        R                  5      nUR	                  S5      R                  SSS9nU[        R                  " X0R                  -   5      -  nU R                  UR                  U5      -  $ )N   T)keepdim)	dtypetor/   float32powmeanrsqrtr@   r?   )rA   rE   input_dtypevariances       r4   forwardChameleonRMSNorm.forwardM   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::r3   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)tupler?   shaper@   rA   s    r4   
extra_reprChameleonRMSNorm.extra_reprT   s*    ))*+6$2G2G1HIIr3   )r@   r?   )ư>)r*   r+   r,   r-   floatr<   r/   TensorrR   rX   r2   __classcell__rC   s   @r4   r6   r6   D   sB    $ $$ $ $;U\\ ;ell ;J Jr3   r6   c                      ^  \ rS rSr% \R
                  \S'   SS\4U 4S jjjr\	   SS\S-  S\
S   S\S-  S	\S
\4   4S jj5       r\R                  " 5       \S 5       5       rSrU =r$ )ChameleonRotaryEmbeddingY   inv_freqNconfigc                   > [         TU ]  5         UR                  U l        UR                  U l        Xl        U R
                  R                  S   U l        U R                  nU R                  S:w  a  [        U R                     nU" U R
                  U5      u  o@l
        U R                  SUSS9  U R                  SUR                  5       SS9  g )N	rope_typedefaultrb   F)
persistentoriginal_inv_freq)r;   r<   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrc   rope_parametersre   compute_default_rope_parametersr   attention_scalingregister_bufferclone)rA   rc   devicerope_init_fnrb   rC   s        r4   r<   !ChameleonRotaryEmbedding.__init__\   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L((ZeD0(..2BuUr3   rq   ztorch.deviceseq_lenr9   ztorch.Tensorc           	         U R                   S   n[        U SS5      =(       d    U R                  U R                  -  nSnSU[        R
                  " SUS[        R                  S9R                  U[        R                  S9U-  -  -  nXe4$ )	aH  
Computes the inverse frequencies according to the original RoPE implementation
Args:
    config ([`~transformers.PreTrainedConfig`]):
        The model configuration.
    device (`torch.device`):
        The device to use for initialization of the inverse frequencies.
    seq_len (`int`, *optional*):
        The current sequence length. Unused for this type of RoPE.
Returns:
    Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
    post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).

rope_thetahead_dimNg      ?r   rG   rJ   )rq   rJ   )	rl   getattrrB   num_attention_headsr/   arangeint64rK   r[   )rc   rq   rt   basedimattention_factorrb   s          r4   rm   8ChameleonRotaryEmbedding.compute_default_rope_parametersl   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 ))r3   c                 L   U R                   S S S 2S 4   R                  5       R                  UR                  S   SS5      R	                  UR
                  5      nUS S 2S S S 24   R                  5       n[        UR
                  R                  [        5      (       a0  UR
                  R                  S:w  a  UR
                  R                  OSn[        USS9   UR                  5       UR                  5       -  R                  SS5      n[        R                  " Xf4SS	9nUR                  5       U R                  -  nUR                  5       U R                  -  n	S S S 5        WR	                  UR                   S
9W	R	                  UR                   S
94$ ! , (       d  f       N@= f)Nr   rH   r    mpscpuF)device_typeenabledrG   r~   rx   )rb   r[   expandrV   rK   rq   
isinstancetypestrr   	transposer/   catcosrn   sinrJ   )
rA   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             r4   rR    ChameleonRotaryEmbedding.forward   sN    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E'E!((--[`J`ahhmmfkUC&,,.1F1L1L1NNYYZ[]^_E))UN3C'')d444C'')d444C	 D vvAGGv$cff177f&;;; DCs   BF
F#)rn   rc   rj   rk   re   N)NNN)r*   r+   r,   r-   r/   r\   r1   r!   r<   staticmethodr   intrU   r[   rm   no_gradr   rR   r2   r]   r^   s   @r4   r`   r`   Y   s    llV V V  )-+/"*$&*(* t* 
~u$	%	* *: ]]_<  <r3   r`   c                     U SSU R                   S   S-  24   nU SU R                   S   S-  S24   n[        R                  " U* U4SS9$ )z*Rotates half the hidden dims of the input..NrH   rG   r   )rV   r/   r   )r   x1x2s      r4   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r3   c                     UR                  U5      nUR                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nXV4$ )aI  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.
    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.
)	unsqueezer   )qkr   r   unsqueeze_dimq_embedk_embeds          r4   apply_rotary_pos_embr      sS    $ --
&C
--
&Cw;q>C/0Gw;q>C/0Gr3   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )ChameleonMLP   c                   > [         TU ]  5         Xl        UR                  U l        UR                  U l        [
        R                  " U R                  U R                  UR                  S9U l        [
        R                  " U R                  U R                  UR                  S9U l	        [
        R                  " U R                  U R                  UR                  S9U l
        [        UR                     U l        g )Nbias)r;   r<   rc   rB   intermediate_sizer   Linearmlp_bias	gate_projup_proj	down_projr	   
hidden_actact_fnrA   rc   rC   s     r4   r<   ChameleonMLP.__init__   s    !--!'!9!94#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r3   c                     U R                  U R                  U R                  U5      5      U R                  U5      -  5      nU$ r   )r   r   r   r   )rA   r   r   s      r4   rR   ChameleonMLP.forward   s6    NN4;;t~~a/@#ADLLQRO#ST	r3   )r   rc   r   r   rB   r   r   r*   r+   r,   r-   r<   rR   r2   r]   r^   s   @r4   r   r      s    0 r3   r   c                   2   ^  \ rS rSrSrU 4S jrS rSrU =r$ )ChameleonLayerNorm   ar  
LayerNorm but computes stats only over the last dim because Chameleon applies gamma and beta
from each shard separately to each head, instead of reducing. We can apply each head's own
gamma/beta by repeat-interleaving weights from each shard, but the stats have to be computed
in the last dimension. This module applies gamma/beta manually to fulfill this requirement.
c                 D   > [         TU ]  " U/UQ70 UD6  US   4U l        g )NrH   )r;   r<   normalized_shape)rA   rB   argskwargsrC   s       r4   r<   ChameleonLayerNorm.__init__   s)    6t6v6!,R 2r3   c                 ~    [         R                  " XR                  S S SS9nXR                  -  U R                  -   nU$ )Ngh㈵>r8   )F
layer_normr   r?   r   rA   rE   s     r4   rR   ChameleonLayerNorm.forward   s9    ]4I4I4QU[_`%3dii?r3   )r   )	r*   r+   r,   r-   r.   r<   rR   r2   r]   r^   s   @r4   r   r      s    3 r3   r   rE   n_repr9   c                     U R                   u  p#pEUS:X  a  U $ U SS2SS2SSS2SS24   R                  X#XU5      n U R                  X#U-  XE5      $ )z
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
r    N)rV   r   reshape)rE   r   batchnum_key_value_headsslenrw   s         r4   	repeat_kvr      s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr3   modulequerykeyvalueattention_maskscalingdropoutr   c                    [        X R                  5      n[        X0R                  5      n	[        R                  " XR	                  SS5      5      U-  n
Ub  X-   n
[
        R                  R                  U
S[        R                  S9R                  UR                  5      n
[
        R                  R                  XU R                  S9n
[        R                  " X5      nUR	                  SS5      R                  5       nX4$ )NrG   r   rH   )r~   rJ   )ptrainingr    )r   num_key_value_groupsr/   matmulr   r   
functionalsoftmaxrL   rK   rJ   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               r4   eager_attention_forwardr      s     3 ; ;<JU$?$?@L<<';';Aq'ABWLL!#4==((2U]](SVVW\WbWbcL==((6??([L,,|:K''1-88:K$$r3   c                   >  ^  \ rS rSrSrSS\S\S-  4U 4S jjjr      SS\R                  S\R                  S-  S	\R                  S-  S
\S-  S\S\S\R                  S-  S\\R                  \R                  S-  \\R                     S-  4   4S jjrSrU =r$ )ChameleonAttentioni  z=Multi-headed attention from 'Attention Is All You Need' paperNrc   	layer_idxc                 \  > [         TU ]  5         Xl        X l        Uc-  [        R                  SU R                  R                   S35        UR                  U l        UR                  U l	        UR                  U l        U R                  U R                  -  U l        UR                  U l        U R                  U R                  -  U l        UR                  U l        SU l        UR"                  U l        U R                  S-  U l        U R                  U R                  -  U R                  :w  a&  ['        SU R                   SU R                   S35      e[(        R*                  " U R                  U R                  U R                  -  UR,                  S9U l        [(        R*                  " U R                  U R                  U R                  -  UR,                  S9U l        [(        R*                  " U R                  U R                  U R                  -  UR,                  S9U l        [(        R*                  " U R                  U R                  UR,                  S9U l        [7        U R                  U R                  45      U l        [7        U R                  U R                  45      U l        g )	NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.T      z?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).r   )r;   r<   rc   r   loggerwarning_oncerC   r*   attention_dropoutrB   rz   	num_headsrw   r   r   ri   	is_causalmodel_parallel_sizer   
ValueErrorr   r   attention_biasq_projk_projv_projo_projr   q_normk_normrA   rc   r   rC   s      r4   r<   ChameleonAttention.__init__
  s   " !8!8 9 :, , "(!9!9!--33((DNN:#)#=#= $(NNd6N6N$N!'-'E'E$#)#=#= }}d*MMDNN*t/?/??QRVRbRbQc$T^^$4B8 
 ii 0 0$..4==2PW]WlWlmii 0 0$2J2JT]]2Zagavavwii 0 0$2J2JT]]2Zagavavwii 0 0$2B2BI^I^_($..$--)HI($*B*BDMM)RSr3   rE   r   r   past_key_valuesoutput_attentions	use_cacheposition_embeddingsr9   c                 ^   UR                  5       u  pnU R                  U5      nU R                  U5      nU R                  U5      nUR	                  SU R
                  U R                  5      nU R                  U5      nUR	                  SU R                  U R                  5      nU R                  U5      nUR	                  XU R
                  U R                  5      R                  SS5      nUR	                  XU R                  U R                  5      R                  SS5      nUR                  XU R                  U R                  5      R                  SS5      nUu  nn[        XUU5      u  pUb  UR                  XU R                  5      u  p[        R                   " U R"                  R$                  [&        5      nU" U UUUU4U R(                  (       d  SOU R*                  U R,                  S.UD6u  nnUR	                  XS5      R/                  5       nU R1                  U5      nUU4$ )NrH   r    rG           )r   r   )sizer   r   r   r   r   rw   r   r   r   r   viewr   updater   r   get_interfacerc   _attn_implementationr   r   r   r   r   r   )rA   rE   r   r   r   r   r   r   r   bszq_len_query_statesr   r   r   r   attention_interfacer   r   s                       r4   rR   ChameleonAttention.forward.  s    &**,A{{=1[[/
{{=1#++BN{{<0''D,D,DdmmT
[[,
#++CV``abdef''D4L4Ldmm\ffghjkl
#((T5M5Mt}}]gghiklm&S#7RUWZ#[ &'6'='=jX\XfXf'g$J(?(M(MKK,,.E)
 %8	%
  $}}C$2H2HLL	%
 	%
!\ "))#b9DDFkk+.L((r3   )r   rc   rw   rB   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   NNNFFN)r*   r+   r,   r-   r.   r!   r   r<   r/   r\   
LongTensorr
   boolrU   rR   r2   r]   r^   s   @r4   r   r     s    G"T "T3: "T "TN /304(,"'373)||3) t+3) &&-	3)
 3)  3) 3) #\\D03) 
u||U\\D0%2E2LL	M3) 3)r3   r   c                   8  ^  \ rS rSrS\S\4U 4S jjr      SS\R                  S\R                  S-  S\R                  S-  S	\
S-  S
\S-  S\S-  S\R                  S-  S\\R                  \\R                  \R                  4   S-  4   4S jjrSrU =r$ )ChameleonDecoderLayerie  rc   r   c                   > [         TU ]  5         UR                  U l        [        XS9U l        [        U5      U l        [        UR                  UR                  S9U l	        [        UR                  UR                  S9U l
        g N)rc   r   r   r;   r<   rB   r   	self_attnr   mlpr6   rms_norm_epsinput_layernormpost_attention_layernormr   s      r4   r<   ChameleonDecoderLayer.__init__f  k    !--+6O'/0B0BH[H[\(89K9KQWQdQd(e%r3   NrE   r   r   r   r   r   r   r9   c                     Un	U R                  U5      nU R                  " SUUUUUUUS.UD6u  pX-   nUn	U R                  U5      nU R                  U5      nX-   nU4nU(       a  X4-  nU$ )a  
Args:
    hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
    attention_mask (`torch.FloatTensor`, *optional*):
        attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
        query_sequence_length, key_sequence_length)` if default attention is used.
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
    use_cache (`bool`, *optional*):
        If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
        (see `past_key_values`).
    past_key_values (`Cache`, *optional*): cached past key and value projection states
    kwargs (`dict`, *optional*):
        Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
        into the model
rE   r   r   r   r   r   r   r)   )r  r  r  r  rA   rE   r   r   r   r   r   r   r   residualself_attn_weightsoutputss               r4   rR   ChameleonDecoderLayer.forwardp  s    8 !,,]; ,0>> 	,
')%+/ 3	,
 	,
( !0 !55mD/ 0 "++Gr3   rB   r  r  r  r  r  r*   r+   r,   r-   r!   r   r<   r/   r\   r	  r
   r
  rU   r0   rR   r2   r]   r^   s   @r4   r  r  e  s    f f3 f /304(,).!&378||8 t+8 &&-	8
 8  $;8 $;8 #\\D08 
u  %(9(95;L;L(L"MPT"TT	U8 8r3   r  c                   8  ^  \ rS rSrS\S\4U 4S jjr      SS\R                  S\R                  S-  S\R                  S-  S	\
S-  S
\S-  S\S-  S\R                  S-  S\\R                  \\R                  \R                  4   S-  4   4S jjrSrU =r$ )ChameleonSwinDecoderLayeri  rc   r   c                   > [         TU ]  5         UR                  U l        [        XS9U l        [        U5      U l        [        UR                  UR                  S9U l	        [        UR                  UR                  S9U l
        g r  r  r   s      r4   r<   "ChameleonSwinDecoderLayer.__init__  r  r3   NrE   r   r   r   r   r   r   r9   c                     Un	U R                   " SUUUUUUUS.UD6u  pU R                  U5      nX-   nUn	U R                  U5      nU R                  U5      nX-   nU4nU(       a  X4-  nU$ )a  
Args:
    hidden_states (`torch.FloatTensor`):
        input to the layer of shape `(batch, seq_len, embed_dim)`
    attention_mask (`torch.FloatTensor`, *optional*):
        attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
        query_sequence_length, key_sequence_length)` if default attention is used.
    position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
        Indices of positions of each input sequence tokens in the position embeddings
    past_key_values (`Cache`, *optional*): cached past key and value projection states
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
    use_cache (`bool`, *optional*):
        If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
        (see `past_key_values`).
r  r)   )r  r  r  r  r  s               r4   rR   !ChameleonSwinDecoderLayer.forward  s    : ! ,0>> 	,
')%+/ 3	,
 	,
( ,,]; 0 /55mD 0 "++Gr3   r  r  r  r^   s   @r4   r!  r!    s    f f3 f /304(,).!&376||6 t+6 &&-	6
 6  $;6 $;6 #\\D06 
u  %(9(95;L;L(L"MPT"TT	U6 6r3   r!  c                   N   ^  \ rS rSrSrU 4S jrS\R                  4S jrSr	U =r
$ )ChameleonVQVAEVectorQuantizeri  a  
A module for vector quantization using learned embedding vectors.

This module implements the quantization process similar to te one described in
the VQ-VAE (Vector Quantized Variational AutoEncoder) paper. It quantizes continuous
input vectors into discrete codebook vectors, which are learned during training.
Current implementation improves over previous ones by avoiding costly matrix multiplications
and allowing for post-hoc remapping of indices.
c                    > [         TU ]  5         UR                  U l        UR                  U l        [        USS5      U l        [        R                  " U R                  U R                  5      U l	        g )Nbetag      ?)
r;   r<   num_embeddings	embed_dimembedding_dimry   r)  r   	Embedding	embeddingr   s     r4   r<   &ChameleonVQVAEVectorQuantizer.__init__  sX    $33#--FFD1	d&9&94;M;MNr3   hidden_statec           
      >   UR                  SSSS5      R                  5       nUR                  SU R                  5      n[        R
                  " US-  SSS9[        R
                  " U R                  R                  S-  SS9-   S[        R                  " S	X R                  R                  R                  SS5      5      -  -
  n[        R                  " USS9nU R                  U5      R                  UR                  5      n[        R                  " UR                  5       U-
  S-  5      U R                  [        R                  " XQR                  5       -
  S-  5      -  -   nXU-
  R                  5       -   nUR                  SSSS5      R                  5       nXVU4$ )
Nr   rG   r   r    rH   T)r~   rI   r   z	bd,dn->bn)permuter   r   r,  r/   sumr.  r?   einsumr   argminrV   rN   detachr)  )rA   r0  hidden_state_flattened	distancesmin_encoding_indiceshidden_state_quantlosss          r4   rR   %ChameleonVQVAEVectorQuantizer.forward  s   #++Aq!Q7BBD!-!2!22t7I7I!J II,a/QEii--q0a89%,,{,BNNDYDYDcDcdeghDijjk 	  %||I1=!^^,@AFF|GYGYZ zz-446E!KLtyy[`[e[e"5"5"77A=\
 P
 

 *,-N,V,V,XX 0771aCNNP!)===r3   )r)  r.  r,  r*  )r*   r+   r,   r-   r.   r<   r/   r\   rR   r2   r]   r^   s   @r4   r'  r'    s#    O>ELL > >r3   r'  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )#ChameleonVQVAEEncoderConvDownsamplei  c                 Z   > [         TU ]  5         [        R                  " XSSSS9U l        g )Nr   rG   r   kernel_sizestridepadding)r;   r<   r   Conv2dconvrA   in_channelsrC   s     r4   r<   ,ChameleonVQVAEEncoderConvDownsample.__init__  s%    IIkAaYZ[	r3   c                 V    [         R                  " USSSS9nU R                  U5      nU$ )N)r   r    r   r    constantr   )padmoder   )r   rK  rE  r   s     r4   rR   +ChameleonVQVAEEncoderConvDownsample.forward#  s+    mJVWX		-0r3   )rE  r   r^   s   @r4   r>  r>    s    \ r3   r>  c                   6   ^  \ rS rSr  SU 4S jjrS rSrU =r$ ) ChameleonVQVAEEncoderResnetBlocki*  c                   > [         TU ]  5         X l        Uc  UOUU l        X@l        [
        R                  R                  SUSSS9U l        [
        R                  R                  X#SSSS9U l
        [
        R                  R                  SUSSS9U l        [
        R                  R                  UR                  5      U l        [
        R                  R                  X3SSSS9U l        U R                  U R                  :w  a]  U R                  (       a&  [
        R                  R                  X#SSSS9U l        g [
        R                  R                  X#SSSS9U l        g g )	N    rZ   T
num_groupsnum_channelsr8   affiner   r    r@  r   )r;   r<   rG  out_channelsuse_conv_shortcutr/   r   	GroupNormnorm1rD  conv1norm2Dropoutr   conv2conv_shortcutnin_shortcut)rA   rc   rG  rV  r^  rC   s        r4   r<   )ChameleonVQVAEEncoderResnetBlock.__init__+  s%    	&+7+?K\!.XX''2KUYbf'g
XX__[AVWab_c
XX''2LVZcg'h
xx''7XX__\QWXbc_d
t000%%%*XX__[\]fgqr_%s"$)HHOOK[\efpqO$r!	 1r3   c                    UnU R                  U5      nU[        R                  " U5      -  nU R                  U5      nU R	                  U5      nU[        R                  " U5      -  nU R                  U5      nU R                  U5      nU R                  U R                  :w  a7  U R                  (       a  U R                  U5      nX!-   $ U R                  U5      nX!-   $ r   )rY  r/   sigmoidrZ  r[  r   r]  rG  rV  rW  r^  r_  )rA   rE   r  s      r4   rR   (ChameleonVQVAEEncoderResnetBlock.forwardB  s     

=1}55

=1

=1}55]3

=1t000%%--h7 ''  ,,X6''r3   )
rZ  r]  r^  r   rG  r_  rY  r[  rV  rW  )NFr   r^   s   @r4   rO  rO  *  s    
 s.( (r3   rO  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )ChameleonVQVAEEncoderAttnBlockiV  c                   > [         TU ]  5         Xl        [        R                  R                  SUSSS9U l        [        R                  R                  XSSSS9U l        [        R                  R                  XSSSS9U l	        [        R                  R                  XSSSS9U l
        [        R                  R                  XSSSS9U l        g )NrQ  rZ   TrR  r    r   r@  )r;   r<   rG  r/   r   rX  normrD  r   r   vproj_outrF  s     r4   r<   'ChameleonVQVAEEncoderAttnBlock.__init__W  s    &HH&&";TXae&f	qQR\]^qQR\]^qQR\]^aXYcder3   c                 Z   UnU R                  U5      nU R                  U5      nU R                  U5      nU R                  U5      nUR                  u  pgpUR                  XgX-  5      R                  SSS5      nUR                  XgX-  5      n[        R                  " X45      n
U
[        U5      S-  -  n
[        R                  " U
SS9n
UR                  XgX-  5      nU
R                  SSS5      n
[        R                  " XZ5      R                  XgX5      nU R                  U5      nX+-   $ )Nr   rG   r    r   r   )rg  r   r   rh  rV   r   r2  r/   bmmr   r   r   ri  )rA   rE   r  r  r   r   
batch_sizechannelsheightwidthr   r   s               r4   rR   &ChameleonVQVAEEncoderAttnBlock.forwarda  s    		-0vvm,VVM*
vvm, /;.@.@+
f#++J&.QYYZ[]^`ab''
fnM
yy:#s8}'>?yy15 $++J&.Q#++Aq!4ii;CCJZ`hmmK0%%r3   )rG  r   rg  ri  r   rh  r   r^   s   @r4   re  re  V  s    f& &r3   re  c                   J   ^  \ rS rSrU 4S jrS\R                  4S jrSrU =r	$ )ChameleonVQVAEEncoderiy  c           
        > [         TU ]  5         [        UR                  5      U l        UR
                  U l        UR                  nUR                  nUR                  nUR                  nUR                  nUR                  n[        R                  R                  XBSSSS9U l        UnS[        U5      -   n	Xl        [        R"                  " 5       U l        ['        U R                  5       GH%  n
[        R"                  " 5       n[        R"                  " 5       nX)U
   -  nX'U
   -  n['        U R
                  5       Hk  nUR)                  [+        UUUS95        UnUR,                  c  M.  XR,                  ;   d  M?  UR.                  S:X  d  MQ  UR)                  [1        U5      5        Mm     [        R2                  " 5       nUUl        UUl        XR                  S-
  :w  a  [9        U5      Ul        US-  nU R$                  R)                  U5        GM(     [        R2                  " 5       U l        [+        UWUS9U R<                  l        UR.                  S:X  a  [1        U5      O[        R@                  " 5       U R<                  l!        [+        UUUS9U R<                  l"        [        R                  RG                  SUS	S
S9U l$        [        R                  R                  UU(       a  SU-  OUSSSS9U l%        g )Nr   r    r@  r    )rc   rG  rV  vanillarG   rQ  rZ   TrR  )&r;   r<   lenchannel_multipliernum_resolutionsnum_res_blocksbase_channels
resolutionrG  double_latentlatent_channelsr/   r   rD  conv_inrU   in_channel_multiplier
ModuleListdownrangeappendrO  attn_resolutions	attn_typere  Moduleblockattnr>  
downsamplemidblock_1Identityattn_1block_2rX  norm_outconv_out)rA   rc   r{  r|  rG  r}  r~  rx  curr_resr  i_levelr  r  block_in	block_outi_blockr  rC   s                    r4   r<   ChameleonVQVAEEncoder.__init__z  s   "6#<#<=$33,,&&
((,, 00#66xx{qYZdef $u-?'@ @%:"MMO	T112GMMOE==?D$W'EEH%7(CCI !4!454%$,%. %++7 $;$;;((I5KK >x HI 6  99;DDJDI..22"Eh"O#q=IIT"7 3: 99;; !

 GMFVFVZcFc8Bikititiv; !
 **bxUYbf*g#0Ao ( 
r3   pixel_valuesc                 @   U R                  U5      /n[        U R                  5       H  n[        U R                  5       H  nU R                  U   R
                  U   " US   5      n[        U R                  U   R                  5      S:  a"  U R                  U   R                  U   " U5      nUR                  U5        M     X0R                  S-
  :w  d  M  UR                  U R                  U   R                  US   5      5        M     US   nU R                  R                  U5      nU R                  R                  U5      nU R                  R                  U5      nU R                  U5      nU[        R                   " U5      -  nU R#                  U5      nU$ )NrH   r   r    )r  r  ry  rz  r  r  rw  r  r  r  r  r  r  r  r  r/   rb  r  )rA   r  rE   r  r  r0  last_hidden_states          r4   rR   ChameleonVQVAEEncoder.forward  sr   l34T112G !4!45#yy177@!"%  tyy)../!3#'99W#5#:#:7#CL#QL$$\2 6 ..22$$TYYw%7%B%B=QSCT%UV 3 *"- HH,,->? HHOO,=> HH,,->? !MM*;<U]]+<== MM*;<  r3   )r  r  r  r  r  r  rz  ry  )
r*   r+   r,   r-   r<   r/   r	  rR   r2   r]   r^   s   @r4   rs  rs  y  s!    C
J!E$4$4 ! !r3   rs  c                       \ rS rSrSrS r\S 5       r\S 5       r\S 5       r	\S 5       r
\S 5       r\S	 5       rS
\R                  S\R                  4S jrSrg)ChameleonImageVocabularyMappingi  zE
A class for mapping discrete image tokens from VQGAN to BPE tokens.
c                 <    Xl         UR                  S5      U l        g )Nz<image>)	vocab_mapgetimage_token_id)rA   r  s     r4   r<   (ChameleonImageVocabularyMapping.__init__  s    "'mmI6r3   c                 l    U R                   R                  5        VVs0 s H  u  pX!_M	     snn$ s  snnf r   )r  itemsrA   r   rh  s      r4   val2name(ChameleonImageVocabularyMapping.val2name  s-    !%!5!5!78!7!7888   0c           	          [        U R                  R                  5        VVs/ s H  u  pUR                  S5      (       d  M  UPM!     snn5      $ s  snnf )NIMGIMG)sortedr  r  
startswith)rA   namevals      r4   r'   ,ChameleonImageVocabularyMapping.image_tokens  s<    DNN,@,@,B`,BytdooV^F_s,B`aa`s   A
A
c           
      (  ^ [        S5       Vs0 s H$  n[        [        S5      U-   5      [        U5      _M&     snmS[        S[        4U4S jjnU R                   Vs0 s H!  o3[        U" U R                  U   5      5      _M#     sn$ s  snf s  snf )N
   Aold_namer9   c                 R   > SR                  U4S jU [        S5      S  5       5      $ )N c              3   F   >#    U  H  nTR                  X5      v   M     g 7fr   )r  ).0cimg_tkn_chr_mappings     r4   	<genexpr>IChameleonImageVocabularyMapping.bpe2img.<locals>.remap.<locals>.<genexpr>  s"     _B^Q.22188B^s   !r  rH   )joinrw  )r  r  s    r4   remap6ChameleonImageVocabularyMapping.bpe2img.<locals>.remap  s$    77_(3x=[]B^___r3   )r  chrordr   r'   r   r  )rA   ir  tokr  s       @r4   bpe2img'ChameleonImageVocabularyMapping.bpe2img  s    BG)L)Qs3s8a<0#a&8)L	`C 	`C 	` @D?P?PQ?PSt}}S1233?PQQ M
 Rs   +B
(Bc                 l    U R                   R                  5        VVs0 s H  u  pX!_M	     snn$ s  snnf r   )r  r  r  s      r4   img2bpe'ChameleonImageVocabularyMapping.img2bpe  s-    !%!3!3!56!5!5666r  c                     [         R                  " [        U R                  R	                  5       5      5      [         R                  " [        U R                  R                  5       5      5      4$ r   )r/   tensorr  r  keysvaluesrW   s    r4   bpe2img_search_tensors6ChameleonImageVocabularyMapping.bpe2img_search_tensors  sC    ||F4<<#4#4#678%,,vdllNaNaNcGd:eeer3   c                     [         R                  " [        U R                  R	                  5       5      S-   [         R
                  S9nU R                  R                  5        H	  u  p#X1U'   M     U$ )Nr    rx   )r/   zerosmaxr  r  r   r  )rA   mappingr   rh  s       r4   img2bpe_mapping_tensor6ChameleonImageVocabularyMapping.img2bpe_mapping_tensor  sR    ++c$,,"3"3"56:%))LLL&&(DAAJ )r3   	img_batchr9   c                 x    UR                   nU R                  UR                  S5         nUR                  U5      $ )Nr   )rq   r  rK   )rA   r  rq   
img_tokenss       r4   convert_img2bpe/ChameleonImageVocabularyMapping.convert_img2bpe  s5    !!00e1DE
}}V$$r3   )r  r  N)r*   r+   r,   r-   r.   r<   r   r  r'   r  r  r  r  r/   r\   r  r2   r)   r3   r4   r  r    s    7 9 9 b b R R 7 7 f f  % %%,, %r3   r  c                   ^    \ rS rSr% \\S'   SrSrSrSS/r	SS	/r
SrSrSrSrSr\\/\S
.rSrg)ChameleonPreTrainedModeli	  rc   model)imagetextTr  r!  r   causal_maskrE   
attentionsr)   N)r*   r+   r,   r-   r!   r1   base_model_prefixinput_modalitiessupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_can_compile_fullgraph_supports_flex_attn_supports_attention_backendr  r!  r   _can_record_outputsr2   r)   r3   r4   r  r  	  sb    (&*#02MN#4m"DN!"&/1JK(r3   r  aW  
    The VQ-VAE model used in Chameleon for encoding/decoding images into discrete tokens.
    This model follows the "Make-a-scene: Scene-based text-to-image generation with human priors" paper from
    [ Oran Gafni, Adam Polyak, Oron Ashual, Shelly Sheynin, Devi Parikh, and Yaniv
    Taigman](https://huggingface.co/papers/2203.13131).
    custom_introc                      ^  \ rS rSr% \\S'   / SQr\\S.r	S\4U 4S jjr
\\S\R                  S\\   S\4S	 j5       5       rS
rU =r$ )ChameleonVQVAEi  rc   )r'  re  rO  r  c                   > [         TU ]  U5        [        U5      U l        [	        U5      U l        [        R                  R                  UR                  UR                  S5      U l        [        R                  R                  UR                  UR                  S5      U l        U R                  5         U R                  5         g )Nr    )r;   r<   rs  encoderr'  quantizer/   r   rD  r~  r+  
quant_convpost_quant_conveval	post_initr   s     r4   r<   ChameleonVQVAE.__init__1  s     ,V45f=((//&*@*@&BRBRTUV$xxv/?/?AWAWYZ[		r3   r  r   r9   c                     U R                  U5      nU R                  U5      nU R                  U5      u  pVn[        UUUUS9$ )N)r  r&   r'   r(   )r  r  r  r$   )rA   r  r   rE   conv_hidden_statesr&   emb_lossindicess           r4   encodeChameleonVQVAE.encode;  sO    
 \2!__];9=GY9Z6#w(+(C #	
 	
r3   )r  r  r  r  )r*   r+   r,   r-   r"   r1   r  rO  re  r  r<   r   r   r/   r	  r   r   r$   r  r2   r]   r^   s   @r4   r  r    sp     !  :4
3   
!,,
8>?Q8R
	"
   
r3   r  c                     ^  \ rS rSrS\4U 4S jjrS\R                  4S jr\	\
" SS9S\R                  S\\   S	\\-  4S
 j5       5       rS\R                   S\R                  S\R                  4S jr\\\
       SS\R                   S-  S\R                  S-  S\R(                  S-  S\R                   S-  S\S-  S\R                  S-  S\S-  S\\   S	\\-  4S jj5       5       5       rSrU =r$ )ChameleonModeliK  rc   c           	        > [         TU ]  U5        UR                  U l        UR                  U l        [
        R                  " UR                  UR                  U R                  5      U l        [        UR                  5      U l        U R                  R                  (       d  [        O[        n[
        R                   " [#        UR$                  5       Vs/ s H
  o2" X5      PM     sn5      U l        [)        UR                  UR*                  S9U l        [.        R1                  UR2                  5      U l        [7        US9U l        SU l        U R=                  5         g s  snf )Nr   rc   F)r;   r<   pad_token_idpadding_idx
vocab_sizer   r-  rB   embed_tokensr  vocabulary_mapvocabulary_mappingrc   	swin_normr  r!  r  r  num_hidden_layerslayersr6   r  rg  r  _from_config	vq_configvqmodelr`   
rotary_embgradient_checkpointingr  )rA   rc   decoder_layerr   rC   s       r4   r<   ChameleonModel.__init__M  s	    !.. ++LL):):F<N<NPTP`P`a"A&BWBW"X59[[5J5J-Pimm?DVE]E]?^_?^)]6-?^_
 %V%7%7V=P=PQ	%2263C3CD2&A&+# 	 `s   E r  c                     UR                   S   nU R                  R                  USS9nU R                  R	                  UR
                  5      nUR                  US5      nU$ )a;  
Tokenizes images into discrete tokens with VQGAN module. Converts
obtained image tokens into BPE tokens and wraps with "boi" and "eoi"
special tokens.

Args:
    pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
        The tensors corresponding to the input images.
r   Treturn_dictrH   )rV   r  r  r  r  r'   r   )rA   r  rm  vqmodel_outputsbpe_tokss        r4   get_image_tokensChameleonModel.get_image_tokens`  s_     "''*
59\\5H5Hcg5H5h**::?;W;WX==R0r3   zcTokenizes images into discrete tokens with VQGAN module and embeds them with text embeddings layer.r  r   r9   c                    UR                   S   nU R                  R                  " U4SS0UD6nU R                  R	                  UR
                  5      R                  US5      nU R                  5       " U5      Ul        U$ )z
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
    The tensors corresponding to the input images.
r   r  TrH   )	rV   r  r  r  r  r'   r   get_input_embeddingspooler_output)rA   r  r   rm  r  
bpe_tokenss         r4   get_image_features!ChameleonModel.get_image_featuresp  s{     "''*
59\\5H5H5rcg5rkq5r,,<<_=Y=YZ__`jlno
(,(A(A(CJ(O%r3   	input_idsinputs_embedsimage_featuresc           	      F   Ucj  X R                  5       " [        R                  " U R                  R                  [        R
                  UR                  S95      :H  nUR                  S5      nOXR                  R                  :H  nUR                  5       nUR                  S   UR                  S   -  nUR                  S5      R                  U5      R                  UR                  5      n[        X$   R                  5       UR                  5       :H  SU SU 35        U$ )z
Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
equal to the length of multimodal features. If the lengths are different, an error is raised.
)rJ   rq   rH   r   r    z6Image features and image tokens do not match, tokens: z, features: )r  r/   r  r  r  longrq   allr3  rV   r   	expand_asrK   r   numel)rA   r  r   r!  special_image_maskn_image_tokensn_image_featuress          r4   get_placeholder_mask#ChameleonModel.get_placeholder_mask  s    !.2K2K2MT44CC5::^k^r^rs3 " "4!7!7!;!*.E.E.T.T!T+//1)//2^5I5I!5LL/99"=GGVYYZgZnZno-3359M9M9OOD^DTT`aq`rs	
 "!r3   Nr   r   r   r   c           
         US L US L-  (       a  [        S5      eUc  U R                  U5      nUb;  U R                  USS9R                  n	U R	                  XU	S9n
UR                  X5      nU(       a9  Uc6  [        R                  R                  5       (       d  [        U R                  S9nUcU  Ub  UR                  5       OSn[        R                  " UR                  S   UR                  S9U-   nUR                  S5      n[!        U R                  UUUUS	9nUnU R#                  XS
9nU R$                   H  nU" U4UUUUUS.UD6nUS   nM     U R'                  U5      n[)        UUS9$ )Nz:You must specify exactly one of input_ids or inputs_embedsTr  )r   r!  r  r   r    )rq   )rc   r   r   r   r   )r   )r   r   r   r   r   )r  r   )r   r  r  r  r*  masked_scatterr/   jit
is_tracingr   rc   get_seq_lengthr{   rV   rq   r   r   r  r
  rg  r   )rA   r  r  r   r   r   r   r   r   r!  r'  past_seen_tokensr  rE   r   r  layer_outputss                    r4   rR   ChameleonModel.forward  s    -t";<YZZ  --i8M#!44\t4TbbN!%!:!:~ "; " *889K\M 09M9M9O9O*$++>OCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L(;;')+%
 &"oomoW "[[M)*) /#$7 M *!,M ) 		-0&++
 	
r3   )	r  r  r
  rg  r  r  r  r  r  )NNNNNNN)r*   r+   r,   r-   r!   r<   r/   r0   r  r   r   r   r   rU   r   r  r	  r*  r   r   r\   r
   r
  r   r   rR   r2   r]   r^   s   @r4   r  r  K  s    &U->->   z!--9?@R9S	+	+ "))":?:K:K"]b]n]n"0   .215.204(,26!%@
##d*@
 ''$.@
 t+	@

 &&-@
 @
 ((4/@
 $;@
 -.@
 
(	(@
    @
r3   r  zb
    Chameleon Model with a head on top used for outputting logits for next token prediction.
    c                     ^  \ rS rSrSS0rU 4S jrS r\S\R                  S\
\   S\\-  4S	 j5       r\\         SS\R                   S
-  S\R                  S
-  S\R"                  S
-  S\R                   S
-  S\S
-  S\R                  S
-  S\R                   S
-  S\S
-  S\\R"                  -  S\
\   S\\-  4S jj5       5       r       SU 4S jjrSrU =r$ )!ChameleonForConditionalGenerationi  zlm_head.weightzmodel.embed_tokens.weightc                    > [         TU ]  U5        [        U5      U l        UR                  U l        [
        R                  " UR                  UR                  SS9U l        U R                  5         g )NFr   )
r;   r<   r  r  r  r   r   rB   lm_headr  r   s     r4   r<   *ChameleonForConditionalGeneration.__init__  sU     #F+
 ++yy!3!3V5F5FUS 	r3   c                 8    U R                   R                  U5      $ r   )r  r  )rA   r  s     r4   r  2ChameleonForConditionalGeneration.get_image_tokens  s    zz**<88r3   r  r   r9   c                 <    U R                   R                  " U40 UD6$ r   )r  r  )rA   r  r   s      r4   r  4ChameleonForConditionalGeneration.get_image_features  s     zz,,\DVDDr3   Nr  r   r   r   r   labelsr   logits_to_keepc
                    U R                   " SUUUUUUUS.U
D6nUS   n[        U	[        5      (       a  [        U	* S5      OU	nU R	                  USS2USS24   5      nU R                   R
                  R                  n[        R                  " UR                  5      R                  USS2SS2U4'   SnUb)  U R                  " SXU R                  R                  S.U
D6n[        UUUR                  UR                   UR"                  S9$ )a  
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 ChameleonProcessor, ChameleonForConditionalGeneration
>>> import torch
>>> import httpx
>>> from io import BytesIO
>>> from PIL import Image

>>> model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b", dtype=torch.bfloat16)
>>> processor = ChameleonProcessor.from_pretrained("facebook/chameleon-7b")

>>> prompt = "I used to know a lot about constellations when I was younger, but as I grew older, I forgot most of what I knew. These are the only two constellations that I really remember now.<image><image>I would like for you to tell me about 3 more constellations and give me a little bit of history about the constellation."
>>> url = "https://nineplanets.org/wp-content/uploads/2020/12/the-big-dipper-1.jpg"
>>> with httpx.stream("GET", url) as response:
...     image1 = Image.open(BytesIO(response.read()))

>>> url = "https://www.kxan.com/wp-content/uploads/sites/40/2020/10/ORION.jpg"
>>> with httpx.stream("GET", url) as response:
...     image2 = Image.open(BytesIO(response.read()))

>>> inputs = processor(images=[image1, image2], text=prompt, return_tensors="pt").to(model.device, torch.bfloat16)

>>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
>>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
```)r  r  r   r   r   r   r   r   N)logitsr=  r  )r;  r@  r   rE   r  r)   )r  r   r   slicer7  r  r'   r/   finforJ   minloss_functionrc   r  r   r   rE   r  )rA   r  r  r   r   r   r   r=  r   r>  r   r  rE   slice_indicesr@  r'   r;  s                    r4   rR   )ChameleonForConditionalGeneration.forward  s   ^ ,0:: 	,
%)%+'	,
 	,
  
8B>SV8W8W~ot4]kmA}a,?@A zz44AA%*[[%>%B%Bq!\!"%%pVt{{OeOepiopD%#33!//))
 	
r3   c	                 `   > [         TU ]  " U4UUUUUUUS.U	D6n
U(       d  U(       a  S U
S'   U
$ )N)r  r   r   r   r   r   is_first_iterationr  )r;   prepare_inputs_for_generation)rA   r  r  r   r   r   r   r   rH  r   model_inputsrC   s              r4   rI  ?ChameleonForConditionalGeneration.prepare_inputs_for_generationH  sT     w<

%+)'%1

 

 "i
 ,0L(r3   )r7  r  r  )	NNNNNNNNr   )NNNNNTF)r*   r+   r,   r-   _tied_weights_keysr<   r  r   r/   r0   r   r   rU   r   r  r   r	  r\   r
   r
  r   r   rR   rI  r2   r]   r^   s   @r4   r5  r5    s    +,GH9 E!--E9?@R9SE	+	+E E
  .215.204(,26*.!%-.K
##d*K
 ''$.K
 t+	K

 &&-K
 K
 ((4/K
   4'K
 $;K
 ell*K
 +,K
 
'	'K
  K
`  ! !r3   r5  )r5  r  r  r  ru  )r   )Tr.   collections.abcr   dataclassesr   	functoolsr   typingr   r/   torch.nn.functionalr   r   r   activationsr	   cache_utilsr
   r   
generationr   masking_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   utils.genericr   r   utils.output_capturingr   configuration_chameleonr!   r"   
get_loggerr*   r   r$   r  r6   r`   r   r   r   	LayerNormr   r\   r   r   r[   r   r   r  r!  r'  r>  rO  re  rs  r  r  r  r  r5  __all__r)   r3   r4   <module>rc     s    $ ! %      ! . ) / B 9 k k K F &  H 5 J 
		H	% 
4 : 4  4 Jryy J*><ryy ><D(4299 " &	UU\\ 	U# 	U%,, 	U( %II%<<% 
% <<	%
 LL4'% % % '(%2Z) Z)|C6 CLA : AH,>BII ,>^	")) 	)(ryy )(X &RYY  &F^!BII ^!B,% ,%^   & #
- #
#
L P
- P
 P
f 
E(@/ E
EP pr3   