
    rh                        d Z ddlmZ ddlmZmZmZ ddlZddlm	c m
Z ddlZddlm	Z	 ddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZ ddlmZ 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& ddl'm(Z(m)Z)  e&jT                  e+      Z, G d de	jZ                        Z. G d de	jZ                        Z/ G d de/      Z0 G d de/      Z1d Z2dLdZ3 G d de	jZ                        Z4 G d d e	jj                        Z6d!ejn                  d"e8d#ejn                  fd$Z9	 dMd%e	jZ                  d&ejn                  d'ejn                  d(ejn                  d)eejn                     d*e:d+e:d,e!e#   fd-Z; G d. d/e	jZ                        Z< G d0 d1e      Z= G d2 d3e      Z> G d4 d5e	jZ                        Z? G d6 d7e	jZ                        Z@ G d8 d9e	jZ                        ZA G d: d;e	jZ                        ZB G d< d=e	jZ                        ZC G d> d?      ZDe$ G d@ dAe             ZE e$dBC       G dD dEeE             ZFe$ G dF dGeE             ZG e$dHC       G dI dJeEe             ZHg dKZIy)NzPyTorch Chameleon model.    )cached_property)CallableOptionalUnionN)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)create_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuplelogging   )ChameleonConfigChameleonVQVAEConfigc                   ,     e Zd Zd fd	Zd Zd Z xZS )ChameleonRMSNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z?
        ChameleonRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      /var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/models/chameleon/modeling_chameleon.pyr    zChameleonRMSNorm.__init__0   s1     	ll5::k#:; #    c                 "   |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&   hidden_statesinput_dtypevariances       r*   forwardzChameleonRMSNorm.forward8   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r+   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler$   shaper%   r&   s    r*   
extra_reprzChameleonRMSNorm.extra_repr?   s*    ))*+6$2G2G1HIIr+   )ư>)__name__
__module____qualname__r    r9   r>   __classcell__r)   s   @r*   r   r   /   s    $;Jr+   r   c                   N     e Zd Zd fd	Z ej
                         d        Z xZS )ChameleonRotaryEmbeddingc                 j   t         |           || _        || _        || _        || _        d| j
                  t        j                  d| j                  dt        j                        j                  |t        j                        | j                  z  z  z  }| j                  d|d       || _        y )	N      ?r   r-   r0   devicer0   inv_freqF
persistent)r   r    scaling_factordimmax_position_embeddingsbaser"   arangeint64r1   floatregister_buffermax_seq_len_cached)r&   rP   rQ   rR   rK   rO   rL   r)   s          r*   r    z!ChameleonRotaryEmbedding.__init__F   s    ,'>$	IIQ!5;;?BB&X]XcXcBdgkgogooq
 	ZeD"9r+   c                    | j                   d d d d f   j                         j                  |j                  d   dd      }|d d d d d f   j                         }|j                  j
                  }|dk7  r|nd}t        j                  |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         }|j                         }	d d d        j                  |j                  
      	j                  |j                  
      fS # 1 sw Y   AxY w)Nr   r.   r   mpscpuF)device_typeenabledr-   rP   rI   )rL   rU   expandr<   rK   typer"   autocast	transposecatcossinr1   r0   )
r&   xposition_idsinv_freq_expandedposition_ids_expandedr[   freqsembrc   rd   s
             r*   r9   z ChameleonRotaryEmbedding.forwardT   s    !MM$4-8>>@GGHZHZ[\H]_acde ,QaZ 8 > > @ hhmm%0E%9ku^^UC 	&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')C'')C		
 vvAGGv$cff177f&;;;	 	s   A+D<<E)i   i'  NrH   )r@   rA   rB   r    r"   no_gradr9   rC   rD   s   @r*   rF   rF   E   s$    : U]]_< <r+   rF   c                   "     e Zd ZdZ fdZ xZS )%ChameleonLinearScalingRotaryEmbeddingz_ChameleonRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendevc                 l    |j                         | j                  z  }t        |   ||      \  }}||fS N)rU   rO   r   r9   )r&   re   rf   rc   rd   r)   s        r*   r9   z-ChameleonLinearScalingRotaryEmbedding.forwardh   s9    #))+d.A.AA7?1l3SCxr+   r@   rA   rB   __doc__r9   rC   rD   s   @r*   rm   rm   e   s    i r+   rm   c                   "     e Zd ZdZ fdZ xZS ))ChameleonDynamicNTKScalingRotaryEmbeddingzqChameleonRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozillac                 .   t        j                  |      dz   }|| j                  kD  r| j                  | j                  |z  | j                  z  | j                  dz
  z
  | j
                  | j
                  dz
  z  z  z  }d|t        j                  d| j
                  dt         j                        j                  |j                  t         j                        | j
                  z  z  z  }| j                  d|d	       t        | 5  ||      \  }}||fS )
Nr   r-   rH   r   rI   rJ   rL   FrM   )r"   maxrQ   rR   rO   rP   rS   rT   r1   rK   rU   rV   r   r9   )	r&   re   rf   seq_lenrR   rL   rc   rd   r)   s	           r*   r9   z1ChameleonDynamicNTKScalingRotaryEmbedding.forwardr   s    ))L)A-T11199$$w.1M1MMRVReRehiRij((dhhl+ - -D LLDHHau{{CFFahh^c^i^iFjmqmumuuwH   X% H7?1l3SCxr+   rp   rD   s   @r*   rs   rs   o   s    { r+   rs   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..Nr.   r-   r]   )r<   r"   rb   )re   x1x2s      r*   rotate_halfrz      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r+   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.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezerz   )qkrc   rd   rf   unsqueeze_dimq_embedk_embeds           r*   apply_rotary_pos_embr      sY    ( --
&C
--
&C3w;q>C/0G3w;q>C/0GGr+   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)r   r    configr'   intermediate_sizer   Linearmlp_bias	gate_projup_proj	down_projr	   
hidden_actact_fnr&   r   r)   s     r*   r    zChameleonMLP.__init__   s    !--!'!9!94#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r+   c                     | j                  | j                  | j                  |            | j                  |      z        }|S ro   )r   r   r   r   )r&   re   r   s      r*   r9   zChameleonMLP.forward   s6    NN4;;t~~a/@#ADLLQRO#ST	r+   r@   rA   rB   r    r9   rC   rD   s   @r*   r   r      s    0r+   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 )Nr.   )r   r    normalized_shape)r&   r'   argskwargsr)   s       r*   r    zChameleonLayerNorm.__init__   s)    6t6v6!,R 2r+   c                     t        j                  || j                  d d d      }|| j                  z  | j                  z   }|S )Ngh㈵>r(   )F
layer_normr   r$   r   r&   r6   s     r*   r9   zChameleonLayerNorm.forward   s=    ]D4I4I4QU[_`%3dii?r+   )r@   rA   rB   rq   r    r9   rC   rD   s   @r*   r   r      s    3r+   r   r6   n_repreturnc                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)r<   r^   reshape)r6   r   batchnum_key_value_headsslenhead_dims         r*   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr+   modulequerykeyvalueattention_maskscalingdropoutr   c                 T   t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
|#|d d d d d d d |j
                  d   f   }|
|z   }
t        j                  j                  |
dt        j                        j                  |j                        }
t        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr-   r   r.   )rP   r0   )ptrainingr   )r   num_key_value_groupsr"   matmulra   r<   r   
functionalsoftmaxr2   r1   r0   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightscausal_maskattn_outputs                r*   eager_attention_forwardr      s    3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#k1==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r+   c                   2    e Zd ZdZddedee   f fdZd Z	 	 	 	 	 	 dde	j                  dee	j                     dee	j                     d	ee   d
ededee	j                     dee	j                  ee	j                     eee	j                        f   fdZ xZS )ChameleonAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr   	layer_idxc                    t         |           || _        || _        |-t        j                  d| j                  j                   d       |j                  | _        |j                  | _	        |j                  | _        | j                  | j                  z  | _        |j                  | _        | j                  | j                  z  | _        |j                  | _        |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.                        | _        t9        | j                  | j                  f      | _        t9        | j                  | j                  f      | _        | j?                          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   ) r   r    r   r   loggerwarning_oncer)   r@   attention_dropoutr'   num_attention_heads	num_headsr   r   r   rQ   
rope_theta	is_causalmodel_parallel_sizer   
ValueErrorr   r   attention_biasq_projk_projv_projo_projr   q_normk_norm
_init_roper&   r   r   r)   s      r*   r    zChameleonAttention.__init__   s0   " !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r+   c                    | j                   j                  2t        | j                  | j                  | j
                        | _        y | j                   j                  d   }| j                   j                  d   }|dk(  r3t        | j                  | j                  || j
                        | _        y |dk(  r3t        | j                  | j                  || j
                        | _        y t        d|       )N)rQ   rR   r_   factorlinear)rQ   rO   rR   dynamiczUnknown RoPE scaling type )
r   rope_scalingrF   r   rQ   r   
rotary_embrm   rs   r   )r&   scaling_typerO   s      r*   r   zChameleonAttention._init_rope  s    ;;##+6(,(D(D__DO  ;;33F;L![[55h?Nx'"GMM,0,H,H#1	# *"KMM,0,H,H#1	# !#=l^!LMMr+   r6   r   rf   past_key_valueoutput_attentions	use_cachecache_positionr   c                    |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      }| j                  ||      \  }}t        ||||      \  }}|'|||d}|j                  ||| j                  |      \  }}t         }| j"                  j$                  dk7  rt&        | j"                  j$                     } || ||||f| j(                  sdn| j*                  | j,                  d|\  }}|j	                  |	|
d      j/                         }| j1                  |      }||fS )Nr.   r   r-   )rd   rc   r   eager        )r   r   )sizer   r   r   r   r   r   r   r   r   ra   viewr   r   updater   r   r   _attn_implementationr   r   r   r   r   r   )r&   r6   r   rf   r   r   r   r   r   bszq_len_query_statesr   r   rc   rd   cache_kwargsattention_interfacer   r   s                        r*   r9   zChameleonAttention.forward8  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'5'<'<ZW[WeWegs't$J(?;;++w6"9$++:Z:Z"[$7	%
  $}}C$2H2HLL	%
 	%
!\ "))#ub9DDFkk+.L((r+   ro   NNNFFN)r@   rA   rB   rq   r   r   intr    r   r"   Tensor
LongTensorr
   boolr;   r9   rC   rD   s   @r*   r   r      s    G# #8C= #NN< 2637*."'595)||5) !.5) u//0	5)
 !5)  5) 5) !!1!125) 
u||Xell3XeELL>Q5RR	S5)r+   r   c                   (    e Zd Zdedef fdZ	 	 	 	 	 	 ddej                  deej                     deej                     dee
   dee   d	ee   d
eej                     deej                  eeej                  ej                  f      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   r   r    r'   r   	self_attnr   mlpr   rms_norm_epsinput_layernormpost_attention_layernormr   s      r*   r    zChameleonDecoderLayer.__init__r  m    !--+6YO'/0B0BH[H[\(89K9KQWQdQd(e%r+   r6   r   rf   r   r   r   r   r   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_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        r6   r   rf   r   r   r   r    )r   r   r   r   r&   r6   r   rf   r   r   r   r   r   residualself_attn_weightsoutputss               r*   r9   zChameleonDecoderLayer.forward|  s    < !,,]; ,:4>> 	,
')%)/)	,
 	,
(( !=0 !55mD/ =0 ")++Gr+   r   r@   rA   rB   r   r   r    r"   r   r   r   r
   r   r;   FloatTensorr9   rC   rD   s   @r*   r   r   q  s    f f3 f 2637*.,1$)59:||: !.: u//0	:
 !: $D>: D>: !!1!12: 
u  (51B1BEDUDU1U+V"WW	X:r+   r   c                   (    e Zd Zdedef fdZ	 	 	 	 	 	 ddej                  deej                     deej                     dee
   dee   d	ee   d
eej                     deej                  eeej                  ej                  f      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      r*   r    z"ChameleonSwinDecoderLayer.__init__  r   r+   r6   r   rf   r   r   r   r   r   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_value (`Tuple(torch.FloatTensor)`, *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               r*   r9   z!ChameleonSwinDecoderLayer.forward  s    > ! ,:4>> 	,
')%)/)	,
 	,
(( ,,]; =0 /55mD =0 ")++Gr+   r   r  rD   s   @r*   r  r    s    f f3 f 2637*.,1$)598||8 !.8 u//0	8
 !8 $D>8 D>8 !!1!128 
u  (51B1BEDUDU1U+V"WW	X8r+   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      ?)
r   r    num_embeddings	embed_dimembedding_dimgetattrr  r   	Embedding	embeddingr   s     r*   r    z&ChameleonVQVAEVectorQuantizer.__init__
  sX    $33#--FFD1	d&9&94;M;MNr+   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   r-   r   r   r.   T)rP   r/   r]   z	bd,dn->bn)permuter   r   r  r"   sumr  r$   einsumra   argminr<   r4   detachr  )r&   r  hidden_state_flattened	distancesmin_encoding_indiceshidden_state_quantlosss          r*   r9   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)===r+   )	r@   rA   rB   rq   r    r"   r   r9   rC   rD   s   @r*   r  r    s    O>ELL >r+   r  c                   $     e Zd Z fdZd Z xZS )#ChameleonVQVAEEncoderConvDownsamplec                 `    t         |           t        j                  ||ddd      | _        y )Nr   r-   r   kernel_sizestridepadding)r   r    r   Conv2dconvr&   in_channelsr)   s     r*   r    z,ChameleonVQVAEEncoderConvDownsample.__init__/  s'    IIk;AaYZ[	r+   c                 Z    t        j                  |ddd      }| j                  |      }|S )N)r   r   r   r   constantr   )padmoder   )r   r-  r(  r   s     r*   r9   z+ChameleonVQVAEEncoderConvDownsample.forward3  s+    mJVWX		-0r+   r   rD   s   @r*   r!  r!  .  s    \r+   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    r?   T
num_groupsnum_channelsr(   affiner   r   r#  r   )r   r    r*  out_channelsuse_conv_shortcutr"   r   	GroupNormnorm1r'  conv1norm2Dropoutr   conv2conv_shortcutnin_shortcut)r&   r   r*  r7  r?  r)   s        r*   r    z)ChameleonVQVAEEncoderResnetBlock.__init__;  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!	 1r+   c                    |}| j                  |      }|t        j                  |      z  }| j                  |      }| j	                  |      }|t        j                  |      z  }| j                  |      }| j                  |      }| j                  | j                  k7  r3| j                  r| j                  |      }||z   S | j                  |      }||z   S ro   )r:  r"   sigmoidr;  r<  r   r>  r*  r7  r8  r?  r@  )r&   r6   r  s      r*   r9   z(ChameleonVQVAEEncoderResnetBlock.forwardR  s     

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

=1

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

=1t000%%--h7 -''  ,,X6-''r+   )NFr   rD   s   @r*   r0  r0  :  s    
 s.(r+   r0  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 )Nr2  r?   Tr3  r   r   r#  )r   r    r*  r"   r   r9  normr'  r}   r~   vproj_outr)  s     r*   r    z'ChameleonVQVAEEncoderAttnBlock.__init__g  s    &HH&&";TXae&f	kqQR\]^kqQR\]^kqQR\]^[aXYcder+   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   r-   r   r   r]   )rF  r}   r~   rG  r<   r   r  r"   bmmr   r   r   rH  )r&   r6   r  r   r   r   
batch_sizechannelsheightwidthr   r   s               r*   r9   z&ChameleonVQVAEEncoderAttnBlock.forwardq  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+%%r+   r   rD   s   @r*   rD  rD  f  s    f&r+   rD  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*  r7  vanillar-   r2  r?   Tr3  )&r   r    lenchannel_multipliernum_resolutionsnum_res_blocksbase_channels
resolutionr*  double_latentlatent_channelsr"   r   r'  conv_inr;   in_channel_multiplier
ModuleListdownrangeappendr0  attn_resolutions	attn_typerD  Moduleblockattnr!  
downsamplemidblock_1Identityattn_1block_2r9  norm_outconv_out)r&   r   rW  rX  r*  rY  rZ  rT  curr_resr\  i_levelrd  re  block_in	block_outi_blockr^  r)   s                    r*   r    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 ( 
r+   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 )Nr.   r   r   )r[  r_  rU  rV  r^  rd  rS  re  r`  rf  rg  rh  rj  rk  rl  r"   rB  rm  )r&   rs  r6   ro  rr  r  last_hidden_states          r*   r9   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*;<  r+   )r@   rA   rB   r    r"   r   r9   rC   rD   s   @r*   rP  rP    s    C
J!E$4$4 !r+   rP  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&   ry  s     r*   r    z(ChameleonImageVocabularyMapping.__init__  s    "'mmI6r+   c                 j    | j                   j                         D ci c]  \  }}||
 c}}S c c}}w ro   )ry  itemsr&   r~   rG  s      r*   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)sortedry  r}  
startswith)r&   namevals      r*   image_tokensz,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_namer   c                 P    dj                  fd| t        d      d D              S )N c              3   B   K   | ]  }j                  ||        y wro   )rz  ).0cimg_tkn_chr_mappings     r*   	<genexpr>zIChameleonImageVocabularyMapping.bpe2img.<locals>.remap.<locals>.<genexpr>   s     _Q.221a8_s   r  r.   )joinrS  )r  r  s    r*   remapz6ChameleonImageVocabularyMapping.bpe2img.<locals>.remap  s$    77_(3x=[]B^___r+   )r_  chrordstrr  r   r  )r&   ir  tokr  s       @r*   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 ro   )r  r}  r~  s      r*   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 ro   )r"   tensorr  r  keysvaluesr=   s    r*   bpe2img_search_tensorsz6ChameleonImageVocabularyMapping.bpe2img_search_tensors  sC    ||F4<<#4#4#678%,,vdllNaNaNcGd:eeer+   c                     t        j                  t        | j                  j	                               dz   t         j
                        }| j                  j                         D ]
  \  }}|||<    |S )Nr   rI   )r"   zerosru   r  r  r   r}  )r&   mappingr~   rG  s       r*   img2bpe_mapping_tensorz6ChameleonImageVocabularyMapping.img2bpe_mapping_tensor  s[    ++c$,,"3"3"56:%))LLL&&( 	DAqGAJ	r+   	img_batchr   c                 x    |j                   }| j                  |j                  d         }|j                  |      S )NrZ   )rK   r  r1   )r&   r  rK   
img_tokenss       r*   convert_img2bpez/ChameleonImageVocabularyMapping.convert_img2bpe  s5    !!00e1DE
}}V$$r+   N)r@   rA   rB   rq   r    r   r  r  r  r  r  r  r"   r   r  r   r+   r*   rw  rw    s    7 9 9 b b R R 7 7 f f  % %%,, %r+   rw  c                   H    e Zd ZU eed<   dZdZddgZddgZdZ	dZ
dZdZdZdZy	)
ChameleonPreTrainedModelr   modelTr   r  past_key_valuesr   FN)r@   rA   rB   r   __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_can_compile_fullgraph!_supports_param_buffer_assignment_supports_flex_attn_supports_attention_backendr   r+   r*   r  r    sN    &*#02MN#4m"DN!(-%"&r+   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                   X     e Zd ZU eed<   g dZdef fdZdej                  fdZ	 xZ
S )ChameleonVQVAEr   )r  rD  r0  c                 l   t         |   |       t        |      | _        t	        |      | _        t        j                  j                  |j                  |j                  d      | _        t        j                  j                  |j                  |j                  d      | _        | j                          y Nr   )r   r    rP  encoderr  quantizer"   r   r'  rZ  r  
quant_convpost_quant_convevalr   s     r*   r    zChameleonVQVAE.__init__9  s|     ,V45f=((//&*@*@&BRBRTUV$xxv/?/?AWAWYZ[		r+   rs  c                 z    | j                  |      }| j                  |      }| j                  |      \  }}}|||fS ro   )r  r  r  )r&   rs  r6   quantemb_lossindicess         r*   encodezChameleonVQVAE.encodeB  s@    \26#'==#? xh''r+   )r@   rA   rB   r   r  r  r    r"   r   r  rC   rD   s   @r*   r  r  )  s2     ! 3 (5#3#3 (r+   r  c                       e Zd Zdef fdZdej                  fdZdej                  fdZdej                  dej                  dej                  fd	Z
e	 	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     d
eej                     deej                     dee   deej                     dee   dee   dee   dee   deej                     dee   deeef   fd       Z 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                        | _        d| _        | j9                          y c c}w )Nr   F)r   r    pad_token_idpadding_idx
vocab_sizer   r  r'   embed_tokensrw  vocabulary_mapvocabulary_mappingr   	swin_normr   r  r]  r_  num_hidden_layerslayersr   r   rF  r  _from_config	vq_configvqmodelgradient_checkpointing	post_init)r&   r   decoder_layerr   r)   s       r*   r    zChameleonModel.__init__K  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&+# 	 `s   Ers  c                     |j                   d   }| j                  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   r.   )r<   r  r  r  r  r   )r&   rs  rK  r   
image_toksbpe_tokss         r*   get_image_tokenszChameleonModel.get_image_tokens]  sZ     "''*
<<..|<1j**:::F==R0r+   c                 T    | j                  |      } | j                         |      }|S )a7  
        Tokenizes images into discrete tokens with VQGAN module and embeds
        them with text embeddings layer

        Args:
            pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
                The tensors corresponding to the input images.
        )r  get_input_embeddings)r&   rs  r  vision_embeddingss       r*   get_image_featuresz!ChameleonModel.get_image_featuresm  s0     ,,\:7D557E  r+   	input_idsinputs_embedsimage_featuresc                 P   |m| | j                         t        j                  | j                  j                  t        j
                  |j                              k(  }|j                  d      }n|| j                  j                  k(  }|j                         }|j                  d      j                  |      j                  |j                        }|j                  d   |j                  d   z  }||   j                         |j                         k7  rt        d| d|       |S )z
        Obtains multimodal placeholdr 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.
        )r0   rK   r.   r   r   z6Image features and image tokens do not match: tokens: z, features )r  r"   r  r  r{  longrK   allr  r|   	expand_asr1   r<   numelr   )r&   r  r  r  special_image_maskn_image_tokensn_image_featuress          r*   get_placeholder_maskz#ChameleonModel.get_placeholder_maskz  s    !.2M$2K2K2MT44CC5::^k^r^rs3 " "4!7!7!;!*d.E.E.T.T!T+//1/99"=GGVYYZgZnZno)//2^5I5I!5LL+,2248L8L8NNHHXXcdtcuv  "!r+   r   rf   r  r   r   output_hidden_statesreturn_dictr   r   r   c                 H   ||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                  |      }|7| j                  |      }| j                  |||      }|j                  ||      }|r*|(t        j                  j!                         s
t#               }|F||j%                         nd}t        j&                  |||j(                  d   z   |j*                        }||j-                  d      }t/        | j                   |||||      }|}|	rd	nd }|rd	nd }| j0                  D ]+  }|	r||fz  } ||f||||||d
|}|d   }|s#||d   fz  }- | j3                  |      }|	r||fz  }|
st5        d ||||fD              S t7        ||||      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_embeds)r  r  r   r   )rK   )r   input_embedsr   r   r  rf   r   )r   rf   r   r   r   r   c              3   &   K   | ]	  }||  y wro   r   )r  rG  s     r*   r  z)ChameleonModel.forward.<locals>.<genexpr>  s      bcbos   )ru  r  r6   
attentions)r   r   r  r   use_return_dictr  r   r   r   r   r  r  r  masked_scatterr"   jit
is_tracingr   get_seq_lengthrS   r<   rK   r|   r   r  rF  r;   r   )r&   r  rs  r   rf   r  r  r   r   r  r  r   r   image_embedsr  past_seen_tokensr   r6   all_hidden_statesall_self_attnsr  layer_outputss                         r*   r9   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#22<@L!%!:!:| "; " *889K\ZM 09M9M9O*nO!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L(;;&))+%
 & #7BD0d![[ 	6M#!m%55!)	*)."3#-	 	M *!,M =#3"55%	6( 		-0  -!11 )?<M~^   '+++%	
 	
r+   NNNNNNNNNNN)r@   rA   rB   r   r    r"   r  r  r  r   r  r   r   r   r
   r   r   r   r   r;   r   r9   rC   rD   s   @r*   r  r  I  s    $U->->  !u/@/@ !"))":?:K:K"]b]n]n"0  15481537+/59$(,0/3&*59j
E,,-j
 u001j
 !.	j

 u//0j
 "%j
   1 12j
 D>j
 $D>j
 'tnj
 d^j
 !!1!12j
 -.j
 
u--	.j
 j
r+   r  zb
    Chameleon Model with a head on top used for outputting logits for next token prediction.
    c                       e Zd ZdgZ fdZd Zd Zd Zd Ze	e
	 	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     d	eej                     d
eej                     dee   deej                     deej                     dee   dee   dee   deej                     dee   deeef   fd              Z	 	 	 	 	 	 	 d fd	Z xZS )!ChameleonForConditionalGenerationzlm_head.weightc                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y )NFr   )
r   r    r  r  r  r   r   r'   lm_headr  r   s     r*   r    z*ChameleonForConditionalGeneration.__init__  sU     #F+
 ++yy!3!3V5F5FUS 	r+   c                     || _         y ro   r  )r&   decoders     r*   set_decoderz-ChameleonForConditionalGeneration.set_decoder  s	    
r+   c                     | j                   S ro   r  r=   s    r*   get_decoderz-ChameleonForConditionalGeneration.get_decoder  s    zzr+   c                 8    | j                   j                  |      S ro   )r  r  r&   rs  s     r*   r  z2ChameleonForConditionalGeneration.get_image_tokens  s    zz**<88r+   c                 8    | j                   j                  |      S ro   )r  r  r
  s     r*   r  z4ChameleonForConditionalGeneration.get_image_features  s    zz,,\::r+   r  rs  r   rf   r  r  labelsr   r   r  r   r   r   c                 0   |	|	n| j                   j                  }	|
|
n| j                   j                  }
 | j                  d||||||||	|
d|d|}|d   }| j	                  |      }| 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 requests
        >>> from PIL import Image

        >>> model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b", torch_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."
        >>> image = Image.open(requests.get("https://nineplanets.org/wp-content/uploads/2020/12/the-big-dipper-1.jpg", stream=True).raw)
        >>> image_2 = Image.open(requests.get("https://www.kxan.com/wp-content/uploads/sites/40/2020/10/ORION.jpg", stream=True).raw)

        >>> inputs = processor(images=[image, image_2], 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  rs  r   rf   r  r  r   r   r  r  r   r   )logitsr  r  )r  r  r  r6   r  r   )r   r   r  r  r  r  r  r"   finfor0   minloss_functionr  r   r  r6   r  )r&   r  rs  r   rf   r  r  r  r   r   r  r   r   r  r6   r  r  r  s                     r*   r9   z)ChameleonForConditionalGeneration.forward  s3   V 2C1N-TXT_T_TqTq$8$D $++JjJj 	
 $** 
%)%+'/!5)
 
  
m, zz44AA%*[[%>%B%Bq!\!"%4%%pVFt{{OeOepiopD%#33!//))
 	
r+   c	                 R    t        |   |f|||||||d|	}
|d   dk7  rd |
d<   |
S )N)rs  r  r   r  r   rf   r   r   rs  )r   prepare_inputs_for_generation)r&   r  rs  r  r   r  r   rf   r   r   model_inputsr)   s              r*   r  z?ChameleonForConditionalGeneration.prepare_inputs_for_generationp  s\     w<

%+)')%

 

 !! ,0L(r+   r  )NNNNNNT)r@   rA   rB   _tied_weights_keysr    r  r  r  r  r   r   r   r"   r   r  r   r
   r   r   r   r   r;   r   r9   r  rC   rD   s   @r*   r   r      s    ++9;  15481537+/59-1$(,0/359O
E,,-O
 u001O
 !.	O

 u//0O
 "%O
   1 12O
 ))*O
 D>O
 $D>O
 'tnO
 !!1!12O
 +,O
 
u,,	-O
  O
h  r+   r   )r   r  r  r  r  )r   )Jrq   	functoolsr   typingr   r   r   r"   torch.nn.functionalr   r   r   torch.utils.checkpointactivationsr	   cache_utilsr
   r   
generationr   masking_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   configuration_chameleonr   r   
get_loggerr@   r   rc  r   rF   rm   rs   rz   r   r   	LayerNormr   r   r   r   rU   r   r   r   r  r  r!  r0  rD  rP  rw  r  r  r  r   __all__r   r+   r*   <module>r(     s    % , ,      ! . ) / B 9 O F &  K 
		H	%Jryy J,<ryy <@,D 0H *(8299 " &	UU\\ 	U# 	U%,, 	U( %II%<<% 
% <<	%
 U\\*% % % '(%4z) z)|E6 EPC : CL,>BII ,>^	")) 	)(ryy )(X &RYY  &F^!BII ^!B,% ,%^ ' ' ' (- ((0 s
- s
 s
l 
J(@/ J
JZ pr+   