
    qim                        d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	Z	ddl
mc mZ ddl	mZ dd	lmZ dd
lmZmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZmZmZ ddlm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3m4Z4  e+jj                  e6      Z7ee) G d de                    Z8 G d dejr                        Z: G d dejr                        Z;d Z<dOdZ= G d  d!ejr                        Z> G d" d#ej~                        Z@d$e	j                  d%eBd&e	j                  fd'ZC	 dPd(ejr                  d)e	j                  d*e	j                  d+e	j                  d,e	j                  dz  d-eDd.eDd/e&e(   fd0ZE G d1 d2ejr                        ZF G d3 d4e      ZG G d5 d6e      ZH G d7 d8ejr                        ZI G d9 d:ejr                        ZJ G d; d<ejr                        ZK G d= d>ejr                        ZL G d? d@ejr                        ZM G dA dB      ZNe) G dC dDe$             ZO e)dEF       G dG dHeO             ZPe) G dI dJeO             ZQ e)dKF       G dL dMeOe             ZRg dNZSy)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                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	ej                  dz  ed<   y)ChameleonVQVAEModelOutputa  
    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____doc__r%   torchFloatTensor__annotations__r&   r'        b/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/chameleon/modeling_chameleon.pyr$   r$   2   sJ     =A!2!2T!9@-1L%##d*1/3NE%%,3r0   r$   c                   h     e Zd Zddeddf fdZdej                  dej                  fdZd Z xZ	S )	ChameleonRMSNormepsreturnNc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z?
        ChameleonRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parameterr,   onesweightvariance_epsilon)selfhidden_sizer4   	__class__s      r1   r8   zChameleonRMSNorm.__init__E   s1     	ll5::k#:; #r0   hidden_statesc                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )N   T)keepdim)	dtypetor,   float32powmeanrsqrtr<   r;   )r=   r@   input_dtypevariances       r1   forwardzChameleonRMSNorm.forwardM   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r0   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler;   shaper<   r=   s    r1   
extra_reprzChameleonRMSNorm.extra_reprT   s*    ))*+6$2G2G1HIIr0   )ư>)
r(   r)   r*   floatr8   r,   TensorrM   rR   __classcell__r?   s   @r1   r3   r3   D   s7    $ $$ $;U\\ ;ell ;Jr0   r3   c                        e Zd ZU ej                  ed<   ddef fdZe	 	 	 ddedz  de	d   de
dz  ded	ef   fd
       Z ej                         ed               Z xZS )ChameleonRotaryEmbeddinginv_freqNconfigc                    t         |           |j                  | _        |j                  | _        || _        | j
                  j                  d   | _        | j                  }| j                  dk7  rt        | j                     } || j
                  |      \  }| _
        | j                  d|d       | j                  d|j                         d       y )N	rope_typedefaultrZ   F)
persistentoriginal_inv_freq)r7   r8   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr[   rope_parametersr]   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r=   r[   devicerope_init_fnrZ   r?   s        r1   r8   z!ChameleonRotaryEmbedding.__init__\   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr0   ri   ztorch.deviceseq_lenr5   ztorch.Tensorc                    | j                   d   }t        | dd      xs | j                  | j                  z  }d}d|t	        j
                  d|dt        j                        j                  |t        j                        |z  z  z  }||fS )	a  
        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   rB   rE   )ri   rE   )	rd   getattrr>   num_attention_headsr,   arangeint64rF   rT   )r[   ri   rk   basedimattention_factorrZ   s          r1   re   z8ChameleonRotaryEmbedding.compute_default_rope_parametersl   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r0   c                 N   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   rC   r    mpscpuF)device_typeenabledrB   ru   ro   )rZ   rT   expandrP   rF   ri   
isinstancetypestrr   	transposer,   catcosrf   sinrE   )
r=   xposition_idsinv_freq_expandedposition_ids_expandedrz   freqsembr   r   s
             r1   rM   z ChameleonRotaryEmbedding.forward   sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfkUC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s   BFF$N)NNN)r(   r)   r*   r,   rU   r.   r!   r8   staticmethodr   intrO   rT   re   no_gradr   rM   rV   rW   s   @r1   rY   rY   Y   s    llV V  )-+/"*$&*(* t* 
~u$	%	* *: U]]_<  <r0   rY   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..NrC   rB   r|   )rP   r,   r   )r   x1x2s      r1   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r0   c                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        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          r1   apply_rotary_pos_embr      sY    $ --
&C
--
&C3w;q>C/0G3w;q>C/0GGr0   c                   $     e Zd Z fdZd Z xZS )ChameleonMLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  |j                        | _        t        j                  | j                  | j                  |j                        | _	        t        j                  | j                  | j                  |j                        | _
        t        |j                     | _        y )Nbias)r7   r8   r[   r>   intermediate_sizer   Linearmlp_bias	gate_projup_proj	down_projr	   
hidden_actact_fnr=   r[   r?   s     r1   r8   zChameleonMLP.__init__   s    !--!'!9!94#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r0   c                     | j                  | j                  | j                  |            | j                  |      z        }|S r   )r   r   r   r   )r=   r   r   s      r1   rM   zChameleonMLP.forward   s6    NN4;;t~~a/@#ADLLQRO#ST	r0   r(   r)   r*   r8   rM   rV   rW   s   @r1   r   r      s    0r0   r   c                   (     e Zd ZdZ fdZd Z xZS )ChameleonLayerNorma  
    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                 B    t        |   |g|i | |d   f| _        y )NrC   )r7   r8   normalized_shape)r=   r>   argskwargsr?   s       r1   r8   zChameleonLayerNorm.__init__   s)    6t6v6!,R 2r0   c                     t        j                  || j                  d d d      }|| j                  z  | j                  z   }|S )Ngh㈵>r4   )F
layer_normr   r;   r   r=   r@   s     r1   rM   zChameleonLayerNorm.forward   s=    ]D4I4I4QU[_`%3dii?r0   )r(   r)   r*   r+   r8   rM   rV   rW   s   @r1   r   r      s    3r0   r   r@   n_repr5   c                     | 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)rP   r}   reshape)r@   r   batchnum_key_value_headsslenrn   s         r1   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr0   modulequerykeyvalueattention_maskscalingdropoutr   c                    t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
||
|z   }
t
        j                  j                  |
dt        j                        j                  |j                        }
t
        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )NrB   r   rC   )ru   rE   )ptrainingr    )r   num_key_value_groupsr,   matmulr   r   
functionalsoftmaxrG   rF   rE   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               r1   eager_attention_forwardr      s     3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r0   c                   L    e Zd ZdZddededz  f fdZ	 	 	 	 	 	 	 ddej                  dej                  dz  dej                  dz  d	e
dz  d
ededej                  dz  dej                  dz  deej                  ej                  dz  eej                     dz  f   fdZ xZS )ChameleonAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNr[   	layer_idxc                 l   t         |           || _        || _        |-t        j                  d| j                  j                   d       |j                  | _        |j                  | _	        |j                  | _        | j                  | j                  z  | _        |j                  | _        | j                  | j                  z  | _        |j                  | _        d| _        |j"                  | _        | j                  dz  | _        | j                  | j                  z  | j                  k7  r&t'        d| j                   d| j                   d      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                  |j,                        | _        t7        | j                  | j                  f      | _        t7        | j                  | j                  f      | _        y )	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   )r7   r8   r[   r   loggerwarning_oncer?   r(   attention_dropoutr>   rq   	num_headsrn   r   r   ra   	is_causalmodel_parallel_sizer   
ValueErrorr   r   attention_biasq_projk_projv_projo_projr   q_normk_normr=   r[   r   r?   s      r1   r8   z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r0   r@   r   r   past_key_valuesoutput_attentions	use_cachecache_positionposition_embeddingsr5   c	                 p   |j                         \  }
}}| j                  |      }| j                  |      }| j                  |      }|j	                  d| j
                  | j                        }| j                  |      }|j	                  d| j                  | j                        }| j                  |      }|j	                  |
|| j
                  | j                        j                  dd      }|j	                  |
|| j                  | j                        j                  dd      }|j                  |
|| j                  | j                        j                  dd      }|\  }}t        ||||      \  }}|'|||d}|j                  ||| j                  |      \  }}t        j                   | j"                  j$                  t&              } || ||||f| j(                  sdn| j*                  | j,                  d|	\  }}|j	                  |
|d      j/                         }| j1                  |      }||fS )NrC   r    rB   )r   r   r           )r   r   )sizer   r   r   r   r   rn   r   r   r   r   viewr   updater   r   get_interfacer[   _attn_implementationr   r   r   r   r   r   )r=   r@   r   r   r   r   r   r   r   r   bszq_len_query_statesr   r   r   r   cache_kwargsattention_interfacer   r   s                         r1   rM   zChameleonAttention.forward.  s    &**,UA{{=1[[/
{{=1#++BN{{<0''D,D,DdmmT
[[,
#++CV``abdef''UD4L4Ldmm\ffghjkl
#((eT5M5Mt}}]gghiklm&S#7jRUWZ#[ j&#&snUL'6'='=j,X\XfXfht'u$J(?(M(MKK,,.E)
 %8	%
  $}}C$2H2HLL	%
 	%
!\ "))#ub9DDFkk+.L((r0   r   NNNFFNN)r(   r)   r*   r+   r!   r   r8   r,   rU   
LongTensorr
   boolrO   rM   rV   rW   s   @r1   r   r     s    G"T "T3: "TN /304(,"'26376)||6) t+6) &&-	6)
 6)  6) 6) ((4/6) #\\D06) 
u||U\\D0%2E2LL	M6)r0   r   c                   H    e Zd Zdedef fdZ	 	 	 	 	 	 	 ddej                  dej                  dz  dej                  dz  de	dz  d	e
dz  d
e
dz  dej                  dz  dej                  dz  deej                  eej                  ej                  f   dz  f   fdZ xZS )ChameleonDecoderLayerr[   r   c                     t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y N)r[   r   r   r7   r8   r>   r   	self_attnr   mlpr3   rms_norm_epsinput_layernormpost_attention_layernormr   s      r1   r8   zChameleonDecoderLayer.__init__i  m    !--+6YO'/0B0BH[H[\(89K9KQWQdQd(e%r0   Nr@   r   r   r   r   r   r   r   r5   c	                     |}
| j                  |      } | j                  d||||||||d|	\  }}|
|z   }|}
| j                  |      }| j                  |      }|
|z   }|f}|r||fz  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_values (`Cache`, *optional*): cached past key and value projection states
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        r@   r   r   r   r   r   r   r   r/   )r  r   r  r   r=   r@   r   r   r   r   r   r   r   r   residualself_attn_weightsoutputss                r1   rM   zChameleonDecoderLayer.forwards  s    > !,,]; ,:4>> 
,
')%+/) 3
,
 
,
(( !=0 !55mD/ =0 ")++Gr0   r   r(   r)   r*   r!   r   r8   r,   rU   r   r
   r   rO   r-   rM   rV   rW   s   @r1   r   r   h  s    f f3 f /304(,).!&2637<||< t+< &&-	<
 <  $;< $;< ((4/< #\\D0< 
u  %(9(95;L;L(L"MPT"TT	U<r0   r   c                   H    e Zd Zdedef fdZ	 	 	 	 	 	 	 ddej                  dej                  dz  dej                  dz  de	dz  d	e
dz  d
e
dz  dej                  dz  dej                  dz  deej                  eej                  ej                  f   dz  f   fdZ xZS )ChameleonSwinDecoderLayerr[   r   c                     t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y r   r   r   s      r1   r8   z"ChameleonSwinDecoderLayer.__init__  r  r0   Nr@   r   r   r   r   r   r   r   r5   c	                     |}
 | j                   d||||||||d|	\  }}| j                  |      }|
|z   }|}
| j                  |      }| j                  |      }|
|z   }|f}|r||fz  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`):
                input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            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`).
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence.
        r  r/   )r   r  r   r  r  s                r1   rM   z!ChameleonSwinDecoderLayer.forward  s    @ ! ,:4>> 
,
')%+/) 3
,
 
,
(( ,,]; =0 /55mD =0 ")++Gr0   r   r  rW   s   @r1   r  r    s    f f3 f /304(,).!&2637:||: t+: &&-	:
 :  $;: $;: ((4/: #\\D0: 
u  %(9(95;L;L(L"MPT"TT	U:r0   r  c                   B     e Zd ZdZ fdZdej                  fdZ xZS )ChameleonVQVAEVectorQuantizera  
    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         |           |j                  | _        |j                  | _        t        |dd      | _        t        j                  | j                  | j                        | _	        y )Nbetag      ?)
r7   r8   num_embeddings	embed_dimembedding_dimrp   r  r   	Embedding	embeddingr   s     r1   r8   z&ChameleonVQVAEVectorQuantizer.__init__  sX    $33#--FFD1	d&9&94;M;MNr0   hidden_statec           
      L   |j                  dddd      j                         }|j                  d| j                        }t	        j
                  |dz  dd      t	        j
                  | j                  j                  dz  d      z   dt	        j                  d	|| j                  j                  j                  dd            z  z
  }t	        j                  |d      }| j                  |      j                  |j                        }t	        j                  |j                         |z
  dz        | j                  t	        j                  ||j                         z
  dz        z  z   }|||z
  j                         z   }|j                  dddd      j                         }|||fS )
Nr   rB   r   r    rC   T)ru   rD   r|   z	bd,dn->bn)permuter   r   r  r,   sumr  r;   einsumr   argminrP   rI   detachr  )r=   r  hidden_state_flattened	distancesmin_encoding_indiceshidden_state_quantlosss          r1   rM   z%ChameleonVQVAEVectorQuantizer.forward  s   #++Aq!Q7BBD!-!2!22t7I7I!J II,a/QEii--q0a89%,,{,BDNNDYDYDcDcdeghDi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!4)===r0   )	r(   r)   r*   r+   r8   r,   rU   rM   rV   rW   s   @r1   r  r    s    O>ELL >r0   r  c                   $     e Zd Z fdZd Z xZS )#ChameleonVQVAEEncoderConvDownsamplec                 `    t         |           t        j                  ||ddd      | _        y )Nr   rB   r   kernel_sizestridepadding)r7   r8   r   Conv2dconvr=   in_channelsr?   s     r1   r8   z,ChameleonVQVAEEncoderConvDownsample.__init__*  s'    IIk;AaYZ[	r0   c                 Z    t        j                  |ddd      }| j                  |      }|S )N)r   r    r   r    constantr   )padmoder   )r   r2  r-  r   s     r1   rM   z+ChameleonVQVAEEncoderConvDownsample.forward.  s+    mJVWX		-0r0   r   rW   s   @r1   r&  r&  )  s    \r0   r&  c                   *     e Zd Z	 	 d fd	Zd Z xZS ) ChameleonVQVAEEncoderResnetBlockc                    t         |           || _        ||n|| _        || _        t
        j                  j                  d|dd      | _        t
        j                  j                  ||ddd      | _
        t
        j                  j                  d|dd      | _        t
        j                  j                  |j                        | _        t
        j                  j                  ||ddd      | _        | j                  | j                  k7  r`| j                  r*t
        j                  j                  ||ddd      | _        y t
        j                  j                  ||ddd      | _        y y )	N    rS   T
num_groupsnum_channelsr4   affiner   r    r(  r   )r7   r8   r/  out_channelsuse_conv_shortcutr,   r   	GroupNormnorm1r,  conv1norm2Dropoutr   conv2conv_shortcutnin_shortcut)r=   r[   r/  r<  rD  r?   s        r1   r8   z)ChameleonVQVAEEncoderResnetBlock.__init__6  s1    	&+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!	 1r0   c                    |}| j                  |      }|t        j                  |      z  }| j                  |      }| j	                  |      }|t        j                  |      z  }| j                  |      }| j                  |      }| j                  | j                  k7  r3| j                  r| j                  |      }||z   S | j                  |      }||z   S r   )r?  r,   sigmoidr@  rA  r   rC  r/  r<  r=  rD  rE  )r=   r@   r  s      r1   rM   z(ChameleonVQVAEEncoderResnetBlock.forwardM  s     

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

=1

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

=1t000%%--h7 -''  ,,X6-''r0   )NFr   rW   s   @r1   r5  r5  5  s    
 s.(r0   r5  c                   $     e Zd Z fdZd Z xZS )ChameleonVQVAEEncoderAttnBlockc                    t         |           || _        t        j                  j                  d|dd      | _        t        j                  j                  ||ddd      | _        t        j                  j                  ||ddd      | _	        t        j                  j                  ||ddd      | _
        t        j                  j                  ||ddd      | _        y )Nr7  rS   Tr8  r    r   r(  )r7   r8   r/  r,   r   r>  normr,  r   r   vproj_outr.  s     r1   r8   z'ChameleonVQVAEEncoderAttnBlock.__init__b  s    &HH&&";TXae&f	kqQR\]^kqQR\]^kqQR\]^[aXYcder0   c                 t   |}| j                  |      }| j                  |      }| j                  |      }| j                  |      }|j                  \  }}}}	|j                  ||||	z        j                  ddd      }|j                  ||||	z        }t        j                  ||      }
|
t        |      dz  z  }
t        j                  |
d      }
|j                  ||||	z        }|
j                  ddd      }
t        j                  ||
      j                  ||||	      }| j                  |      }||z   S )Nr   rB   r    r   r|   )rK  r   r   rL  rP   r   r  r,   bmmr   r   r   rM  )r=   r@   r  r   r   r   
batch_sizechannelsheightwidthr   r   s               r1   rM   z&ChameleonVQVAEEncoderAttnBlock.forwardl  s5    		-0vvm,VVM*
vvm, /;.@.@+
Hfe#++J&5.QYYZ[]^`ab''
HfunM
yyz:#s8}'>?yy15 $++J&5.Q#++Aq!4iil;CCJPXZ`bghmmK0+%%r0   r   rW   s   @r1   rI  rI  a  s    f&r0   rI  c                   >     e Zd Z fdZdej
                  fdZ xZS )ChameleonVQVAEEncoderc           	         t         |           t        |j                        | _        |j
                  | _        |j                  }|j                  }|j                  }|j                  }|j                  }|j                  }t        j                  j                  ||ddd      | _        |}dt        |      z   }	|	| _        t        j"                         | _        t'        | j                        D ]  }
t        j"                         }t        j"                         }||	|
   z  }|||
   z  }t'        | j
                        D ]g  }|j)                  t+        |||             |}|j,                  /||j,                  v s>|j.                  dk(  sN|j)                  t1        |             i t        j2                         }||_        ||_        |
| j                  dz
  k7  rt9        |      |_        |dz  }| j$                  j)                  |       ! t        j2                         | _        t+        ||      | j<                  _        |j.                  dk(  rt1        |      nt        j@                         | j<                  _!        t+        |||      | j<                  _"        t        j                  jG                  d|d	d
      | _$        t        j                  j                  ||rd|z  n|ddd      | _%        y )Nr   r    r(  r    )r[   r/  r<  vanillarB   r7  rS   Tr8  )&r7   r8   lenchannel_multipliernum_resolutionsnum_res_blocksbase_channels
resolutionr/  double_latentlatent_channelsr,   r   r,  conv_inrO   in_channel_multiplier
ModuleListdownrangeappendr5  attn_resolutions	attn_typerI  Moduleblockattnr&  
downsamplemidblock_1Identityattn_1block_2r>  norm_outconv_out)r=   r[   r]  r^  r/  r_  r`  rZ  curr_resrb  i_levelrj  rk  block_in	block_outi_blockrd  r?   s                    r1   r8   zChameleonVQVAEEncoder.__init__  s   "6#<#<=$33,,&&
((,, 00#66xx{MqYZdef $u-?'@ @%:"MMO	T112 	#GMMOE==?D$'<W'EEH%(:7(CCI !4!45 J4%$,%. %++7 F$;$;;((I5KK >x HIJ  99;DDJDI$..22"Eh"O#q=IIT"7	#: 99;; !

 GMFVFVZcFc8Bikititiv; !
 **bxUYbf*g#0Ao ( 
r0   pixel_valuesc                 2   | j                  |      g}t        | j                        D ]  }t        | j                        D ]  } | j                  |   j
                  |   |d         }t        | j                  |   j                        dkD  r" | j                  |   j                  |   |      }|j                  |        || j                  dz
  k7  s|j                  | j                  |   j                  |d                 |d   }| j                  j                  |      }| j                  j                  |      }| j                  j                  |      }| j                  |      }|t        j                   |      z  }| j#                  |      }|S )NrC   r   r    )ra  re  r[  r\  rd  rj  rY  rk  rf  rl  rm  rn  rp  rq  rr  r,   rG  rs  )r=   ry  r@   ru  rx  r  last_hidden_states          r1   rM   zChameleonVQVAEEncoder.forward  s   l34T112 		WG !4!45 3@tyy177@!"%  tyy)../!3#C499W#5#:#:7#CL#QL$$\23 $..22$$TYYw%7%B%B=QSCT%UV		W *"- HH,,->? HHOO,=> HH,,->? !MM*;<U]]+<== MM*;<  r0   )r(   r)   r*   r8   r,   r   rM   rV   rW   s   @r1   rU  rU    s    C
J!E$4$4 !r0   rU  c                       e Zd ZdZd Zed        Zed        Zed        Zed        Z	ed        Z
ed        Zd	ej                  d
ej                  fdZy)ChameleonImageVocabularyMappingzM
    A class for mapping discrete image tokens from VQGAN to BPE tokens.
    c                 >    || _         |j                  d      | _        y )Nz<image>)	vocab_mapgetimage_token_id)r=   r  s     r1   r8   z(ChameleonImageVocabularyMapping.__init__  s    "'mmI6r0   c                 j    | j                   j                         D ci c]  \  }}||
 c}}S c c}}w r   )r  itemsr=   r   rL  s      r1   val2namez(ChameleonImageVocabularyMapping.val2name  s+    !%!5!5!78A1888   /c           	          t        | j                  j                         D cg c]  \  }}|j                  d      s| c}}      S c c}}w )NIMGIMG)sortedr  r  
startswith)r=   namevals      r1   r&   z,ChameleonImageVocabularyMapping.image_tokens  s8    DNN,@,@,B`ytSdooV^F_s`aa`s
   A	
A	
c           
         t        d      D ci c]#  }t        t        d      |z         t        |      % c}dt        dt        ffd}| j                  D ci c]!  }|t         || j                  |               # c}S c c}w c c}w )N
   Aold_namer5   c                 P    dj                  fd| t        d      d D              S )N c              3   B   K   | ]  }j                  ||        y wr   )r  ).0cimg_tkn_chr_mappings     r1   	<genexpr>zIChameleonImageVocabularyMapping.bpe2img.<locals>.remap.<locals>.<genexpr>  s     _Q.221a8_s   r  rC   )joinrY  )r  r  s    r1   remapz6ChameleonImageVocabularyMapping.bpe2img.<locals>.remap  s$    77_(3x=[]B^___r0   )re  chrordr   r&   r   r  )r=   ir  tokr  s       @r1   bpe2imgz'ChameleonImageVocabularyMapping.bpe2img  s    BG)LQs3s8a<0#a&8L	`C 	`C 	` @D?P?PQSt}}S1233QQ M
 Rs   (B&Bc                 j    | j                   j                         D ci c]  \  }}||
 c}}S c c}}w r   )r  r  r  s      r1   img2bpez'ChameleonImageVocabularyMapping.img2bpe  s+    !%!3!3!56A1666r  c                     t        j                  t        | j                  j	                                     t        j                  t        | j                  j                                     fS r   )r,   tensorr  r  keysvaluesrQ   s    r1   bpe2img_search_tensorsz6ChameleonImageVocabularyMapping.bpe2img_search_tensors  sC    ||F4<<#4#4#678%,,vdllNaNaNcGd:eeer0   c                     t        j                  t        | j                  j	                               dz   t         j
                        }| j                  j                         D ]
  \  }}|||<    |S )Nr    ro   )r,   zerosmaxr  r  r   r  )r=   mappingr   rL  s       r1   img2bpe_mapping_tensorz6ChameleonImageVocabularyMapping.img2bpe_mapping_tensor  s[    ++c$,,"3"3"56:%))LLL&&( 	DAqGAJ	r0   	img_batchr5   c                 x    |j                   }| j                  |j                  d         }|j                  |      S )Nry   )ri   r  rF   )r=   r  ri   
img_tokenss       r1   convert_img2bpez/ChameleonImageVocabularyMapping.convert_img2bpe  s5    !!00e1DE
}}V$$r0   N)r(   r)   r*   r+   r8   r   r  r&   r  r  r  r  r,   rU   r  r/   r0   r1   r}  r}    s    7 9 9 b b R R 7 7 f f  % %%,, %r0   r}  c                   V    e Zd ZU eed<   dZdZdZddgZddgZ	dZ
dZdZdZdZeeged	Zy
)ChameleonPreTrainedModelr[   model)imagetextTr   r  r   causal_maskr@   
attentionsN)r(   r)   r*   r!   r.   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_outputsr/   r0   r1   r  r    sb    (&*#02MN#4m"DN!"&/1JK(r0   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                        e Zd ZU eed<   g dZeedZdef fdZ	e
edej                  dee   defd              Z xZS )	ChameleonVQVAEr[   )r  rI  r5  r  c                    t         |   |       t        |      | _        t	        |      | _        t        j                  j                  |j                  |j                  d      | _        t        j                  j                  |j                  |j                  d      | _        | j                          | j                          y )Nr    )r7   r8   rU  encoderr  quantizer,   r   r,  r`  r  
quant_convpost_quant_conveval	post_initr   s     r1   r8   zChameleonVQVAE.__init__<  s     ,V45f=((//&*@*@&BRBRTUV$xxv/?/?AWAWYZ[		r0   ry  r   r5   c                     | j                  |      }| j                  |      }| j                  |      \  }}}t        ||||      S )N)r{  r%   r&   r'   )r  r  r  r$   )r=   ry  r   r@   conv_hidden_statesr%   emb_lossindicess           r1   encodezChameleonVQVAE.encodeF  sQ    
 \2!__];9=GY9Z6#Xw(+(C #	
 	
r0   )r(   r)   r*   r"   r.   r  r5  rI  r  r8   r   r   r,   r   r   r   r$   r  rV   rW   s   @r1   r  r  (  sp     !  :4
3   
!,,
8>?Q8R
	"
   
r0   r  c                       e Zd Zdef fdZdej                  fdZe e	d      dej                  de
e   deez  fd	              Zd
ej                  dej                  dej                  fdZe		 	 	 	 	 	 	 	 	 	 	 dd
ej                  dz  dej                  dz  dej"                  dz  dej                  dz  dedz  dej                  dz  dedz  dedz  dedz  dedz  dej                  dz  de
e   deez  fd       Z xZS )ChameleonModelr[   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        |j                        | _        | j                  j                  st        nt        }t        j                   t#        |j$                        D cg c]  } |||       c}      | _        t)        |j                  |j*                        | _        t.        j1                  |j2                        | _        t7        |      | _        d| _        | j=                          y c c}w )Nr   r[   F)r7   r8   pad_token_idpadding_idx
vocab_sizer   r  r>   embed_tokensr}  vocabulary_mapvocabulary_mappingr[   	swin_normr   r  rc  re  num_hidden_layerslayersr3   r  rK  r  _from_config	vq_configvqmodelrY   
rotary_embgradient_checkpointingr  )r=   r[   decoder_layerr   r?   s       r1   r8   zChameleonModel.__init__X  s    !.. ++LL):):F<N<NPTP`P`a"A&BWBW"X59[[5J5J-Pimm?DVE]E]?^_)]69-_
 %V%7%7V=P=PQ	%2263C3CD2&A&+# 	 `s   Ery  c                     |j                   d   }| j                  j                  |d      }| j                  j	                  |j
                        }|j                  |d      }|S )as  
        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_dictrC   )rP   r  r  r  r  r&   r   )r=   ry  rP  vqmodel_outputsbpe_tokss        r1   get_image_tokenszChameleonModel.get_image_tokensk  s_     "''*
59\\5H5Hcg5H5h**::?;W;WX==R0r0   zcTokenizes images into discrete tokens with VQGAN module and embeds them with text embeddings layer.r  r   r5   c                      | j                   j                  |fddi|} | j                         |j                        |_        |S )z
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
            The tensors corresponding to the input images.
        r  T)r  r  get_input_embeddingsr&   pooler_output)r=   ry  r   r  s       r1   get_image_featuresz!ChameleonModel.get_image_features{  sK     6IT\\5H5H5rcg5rkq5r(C(A(A(COD`D`(a%r0   	input_idsinputs_embedsimage_featuresc                 N   |m| | j                         t        j                  | j                  j                  t        j
                  |j                              k(  }|j                  d      }n|| j                  j                  k(  }|j                         }|j                  d   |j                  d   z  }|j                  d      j                  |      j                  |j                        }t        ||   j                         |j                         k(  d| d|        |S )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.
        )rE   ri   rC   r   r    z6Image features and image tokens do not match, tokens: z, features: )r  r,   r  r  r  longri   allr  rP   r   	expand_asrF   r   numel)r=   r  r  r  special_image_maskn_image_tokensn_image_featuress          r1   get_placeholder_maskz#ChameleonModel.get_placeholder_mask  s    !.2M$2K2K2MT44CC5::^k^r^rs3 " "4!7!7!;!*d.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	
 "!r0   Nr   r   r   r   r   output_hidden_statesr  r   c                    ||n| j                   j                  }|	|	n| j                   j                  }	||n| j                   j                  }|
|
n| j                   j                  }
| j
                  r%| j                  r|rt        j                  d       d}|d u |d uz  rt        d      || j                  |      }|C| j                  |d      j                  }| j                  |||      }|j                  ||      }|r6|4t        j                   j#                         st%        | j                         }|F||j'                         nd}t        j(                  |||j*                  d	   z   |j,                  
      }||j/                  d      }t1        | j                   |||||      }|}| j3                  ||      }|	rdnd }|rdnd }| j4                  D ],  }|	r||fz  } ||f|||||||d|}|d   }|s$||d	   fz  }. | j7                  |      }|	r||fz  }|
st9        d ||||fD              S t;        ||||      S )NzX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.Fz:You must specify exactly one of input_ids or inputs_embedsTr  )r  r  r  r   r    )ri   )r[   r  r   r   r   r   )r   r/   )r   r   r   r   r   r   r   c              3   &   K   | ]	  }||  y wr   r/   )r  rL  s     r1   r  z)ChameleonModel.forward.<locals>.<genexpr>  s      bcbos   )r{  r   r@   r  )r[   r   r  r   use_return_dictr  r   r   r   r   r  r  r  r  masked_scatterr,   jit
is_tracingr   get_seq_lengthrr   rP   ri   r   r   r  r  rK  rO   r   )r=   r  ry  r   r   r   r  r   r   r  r  r   r   r  r  past_seen_tokensr  r@   r   all_hidden_statesall_self_attnsr  layer_outputss                          r1   rM   zChameleonModel.forward  s     2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]&&4==Yj I-t";<YZZ  --i8M#!44\t4TbbN!%!:!:~ "; " *889K^\M 09M9M9O*$++>O!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L(;;'))+%
 &"oom,oW #7BD0d![[ 	6M#!m%55!)
*) /"3#-$7
 
M *!,M =#3"55'	6* 		-0  -!11 )?<M~^   '+++%	
 	
r0   )NNNNNNNNNNN)r(   r)   r*   r!   r8   r,   r-   r  r   r   r   r   rO   r   r  r   r  rU   r
   r   r   r   rM   rV   rW   s   @r1   r  r  V  s    &U->->   z	!--	9?@R9S		+	+	 	"))":?:K:K"]b]n]n"0  .215.204(,26!%)-,0#'26l
##d*l
 ''$.l
 t+	l

 &&-l
 l
 ((4/l
 $;l
  $;l
 #Tkl
 D[l
 ((4/l
 -.l
 
(	(l
 l
r0   r  zb
    Chameleon Model with a head on top used for outputting logits for next token prediction.
    c                        e Zd ZddiZ fdZd Zedej                  de	e
   deez  fd       Zee	 	 	 	 	 	 	 	 	 	 	 	 dd
ej                  d	z  dej                  d	z  dej                   d	z  dej                  d	z  ded	z  dej                  d	z  dej                  d	z  ded	z  ded	z  ded	z  dej                  d	z  deej                   z  de	e
   deez  fd              Z	 	 	 	 	 	 	 	 d fd	Z xZS )!ChameleonForConditionalGenerationzlm_head.weightzmodel.embed_tokens.weightc                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y )NFr   )
r7   r8   r  r  r  r   r   r>   lm_headr  r   s     r1   r8   z*ChameleonForConditionalGeneration.__init__  sU     #F+
 ++yy!3!3V5F5FUS 	r0   c                 8    | j                   j                  |      S r   )r  r  )r=   ry  s     r1   r  z2ChameleonForConditionalGeneration.get_image_tokens#  s    zz**<88r0   ry  r   r5   c                 <     | j                   j                  |fi |S r   )r  r  )r=   ry  r   s      r1   r  z4ChameleonForConditionalGeneration.get_image_features&  s      -tzz,,\DVDDr0   Nr  r   r   r   r  labelsr   r   r  r   logits_to_keepc                    |	|	n| j                   j                  }	|
|
n| j                   j                  }
 | j                  d||||||||	|
d|d|}|d   }t	        |t
              rt        | d      n|}| j                  |dd|ddf         }| j                  j                  j                  }t        j                  |j                        j                  |dddd|f<   d}|* | j                  d||| j                   j                  d|}t!        |||j"                  |j$                  |j&                        S )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]
        ```NT)r  ry  r   r   r   r  r   r   r  r  r   r   )logitsr  r  )r$  r  r   r@   r  r/   )r[   r   r  r  r~   r   slicer
  r  r&   r,   finforE   minloss_functionr  r   r   r@   r  )r=   r  ry  r   r   r   r  r  r   r   r  r   r  r   r
  r@   slice_indicesr  r&   r$  s                       r1   rM   z)ChameleonForConditionalGeneration.forward,  sZ   d 2C1N-TXT_T_TqTq$8$D $++JjJj 	
 $** 
%)%+'/!5)
 
  
8B>SV8W~ot4]kmA}a,?@A zz44AA%*[[%>%B%Bq!\!"%4%%pVFt{{OeOepiopD%#33!//))
 	
r0   c
                 L    t        |   |f||||||||	d|
}|	s|rd |d<   |S )N)ry  r   r   r  r   r   r   is_first_iterationry  )r7   prepare_inputs_for_generation)r=   r  ry  r   r   r  r   r   r   r  r   model_inputsr?   s               r1   r  z?ChameleonForConditionalGeneration.prepare_inputs_for_generation  sW     w<
%+)')%1
 
 "i
 ,0L(r0   )NNNNNNNNNNNr   )NNNNNNTF)r(   r)   r*   _tied_weights_keysr8   r  r   r,   r-   r   r   rO   r   r  r   r   rU   r
   r   r   r   rM   r  rV   rW   s   @r1   r  r    s    +,GH9 E!--E9?@R9SE	+	+E E
  .215.204(,26*.!%)-,026-.X
##d*X
 ''$.X
 t+	X

 &&-X
 X
 ((4/X
   4'X
 $;X
  $;X
 #TkX
 ((4/X
 ell*X
 +,X
 
'	'X
  X
z  # #r0   r  )r  r  r  r  rW  )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$   ri  r3   rY   r   r   r   	LayerNormr   rU   r   r   rT   r   r   r   r  r  r&  r5  rI  rU  r}  r  r  r  r  __all__r/   r0   r1   <module>r1     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'% % % '(%2]) ])BG6 GTE : EP,>BII ,>^	")) 	)(ryy )(X &RYY  &F^!BII ^!B,% ,%^   & #
- #
#
L x
- x
 x
v 
T(@/ T
Tn pr0   