o
    Zh                     @   s  d Z ddlmZ ddlmZmZmZmZ ddlZddl	m
  mZ ddlZddlm
Z
 ddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZ ddlmZmZ ddlm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+m,Z, e' rddl-m.Z. ddl/m0Z0 e)1e2Z3G dd de
j4Z5e"6e5 G dd de
j4Z7G dd de7Z8G dd de7Z9dd Z:dTdd Z;G d!d" d"e
j4Z<G d#d$ d$e
j=Z>d%ej?d&e@d'ej?fd(d)ZA	*dUd+e
j4d,ej?d-ej?d.ej?d/eej? d0eBd1eBfd2d3ZCG d4d5 d5e
j4ZDG d6d7 d7e
j4ZEG d8d9 d9e
j4ZFG d:d; d;e
j4ZGG d<d= d=e
j4ZHG d>d? d?e
j4ZIG d@dA dAe
j4ZJG dBdC dCe
j4ZKG dDdE dEZLe%G dFdG dGeZMe%dHdIG dJdK dKeMZNe%G dLdM dMeMZOG dNdO dOee$ZPe%dPdIG dQdR dReMeZQg dSZRdS )VzPyTorch Chameleon model.    )cached_property)CallableOptionalTupleUnionN)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs)BaseModelOutputWithPastCausalLMOutputWithPast)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)ALL_LAYERNORM_LAYERS)
LossKwargsauto_docstringcan_return_tupleis_torch_flex_attn_availableis_torchdynamo_compilinglogging   )ChameleonConfigChameleonVQVAEConfig)	BlockMask)make_flex_block_causal_maskc                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	ChameleonRMSNormư>c                    s&   t    tt|| _|| _dS )z?
        ChameleonRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	ParametertorchZonesweightvariance_epsilon)selfhidden_sizeeps	__class__ _/var/www/auris/lib/python3.10/site-packages/transformers/models/chameleon/modeling_chameleon.pyr#   8   s   

zChameleonRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )N   T)keepdim)	dtypetor%   float32powmeanZrsqrtr'   r&   )r(   hidden_statesZinput_dtypeZvariancer-   r-   r.   forward@   s
   zChameleonRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupler&   shaper'   r(   r-   r-   r.   
extra_reprG   s   zChameleonRMSNorm.extra_repr)r!   )__name__
__module____qualname__r#   r8   r<   __classcell__r-   r-   r+   r.   r    7   s    r    c                       s.   e Zd Zd	 fdd	Ze dd Z  ZS )
ChameleonRotaryEmbedding   '  N      ?c                    sn   t    || _|| _|| _|| _d| jtjd| jdtjdj	|tj
d| j   }| jd|dd || _d S )	NrD   r   r/   r2   devicer2   inv_freqF
persistent)r"   r#   scaling_factordimmax_position_embeddingsbaser%   arangeint64r3   floatregister_bufferZmax_seq_len_cached)r(   rL   rM   rN   rG   rK   rH   r+   r-   r.   r#   Q   s   
&
z!ChameleonRotaryEmbedding.__init__c           
      C   s   | j d d d d f  |jd dd}|d d d d d f  }|jj}t|tr0|dkr0|nd}tj	|dd% | |  
dd}tj||fdd	}| }| }	W d    n1 saw   Y  |j|jd
|	j|jd
fS )Nr   r0   r   ZmpscpuF)device_typeenabledr/   rL   rE   )rH   rQ   expandr:   rG   type
isinstancestrr%   Zautocast	transposecatcossinr3   r2   )
r(   xposition_idsZinv_freq_expandedZposition_ids_expandedrT   ZfreqsZembr]   r^   r-   r-   r.   r8   _   s   (
z ChameleonRotaryEmbedding.forward)rB   rC   NrD   )r=   r>   r?   r#   r%   Zno_gradr8   r@   r-   r-   r+   r.   rA   P   s    rA   c                           e Zd ZdZ fddZ  ZS )%ChameleonLinearScalingRotaryEmbeddingz_ChameleonRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendevc                    s(   |  | j }t ||\}}||fS N)rQ   rK   r"   r8   )r(   r_   r`   r]   r^   r+   r-   r.   r8   s   s   z-ChameleonLinearScalingRotaryEmbedding.forwardr=   r>   r?   __doc__r8   r@   r-   r-   r+   r.   rb   p       rb   c                       ra   ))ChameleonDynamicNTKScalingRotaryEmbeddingzqChameleonRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozillac                    s   t |d }|| jkrE| j| j| | j | jd  | j| jd    }d|t jd| jdt jdj|j	t j
d| j   }| jd|dd	 t ||\}}||fS )
Nr   r/   rD   r   rE   rF   rH   FrI   )r%   maxrM   rN   rK   rL   rO   rP   r3   rG   rQ   rR   r"   r8   )r(   r_   r`   Zseq_lenrN   rH   r]   r^   r+   r-   r.   r8   }   s   
(z1ChameleonDynamicNTKScalingRotaryEmbedding.forwardrd   r-   r-   r+   r.   rg   z   rf   rg   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..Nr0   r/   rV   )r:   r%   r\   )r_   x1Zx2r-   r-   r.   rotate_half   s   rj   c                 C   sD   | |}| |}| | t| |  }|| t||  }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezerj   )qkr]   r^   r`   Zunsqueeze_dimZq_embedZk_embedr-   r-   r.   apply_rotary_pos_emb   s
   

rn   c                       $   e Zd Z fddZdd Z  ZS )ChameleonMLPc                    sx   t    || _|j| _|j| _tj| j| j|jd| _tj| j| j|jd| _	tj| j| j|jd| _
t|j | _d S )Nbias)r"   r#   configr)   Zintermediate_sizer   LinearZmlp_bias	gate_projup_proj	down_projr	   Z
hidden_actact_fnr(   rs   r+   r-   r.   r#      s   
zChameleonMLP.__init__c                 C   s$   |  | | || | }|S rc   )rw   rx   ru   rv   )r(   r_   rw   r-   r-   r.   r8      s    zChameleonMLP.forwardr=   r>   r?   r#   r8   r@   r-   r-   r+   r.   rp      s    rp   c                       s(   e Zd ZdZ fddZdd Z  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                    s*   t  j|g|R i | |d f| _d S )Nr0   )r"   r#   normalized_shape)r(   r)   argskwargsr+   r-   r.   r#      s   zChameleonLayerNorm.__init__c                 C   s*   t j|| jd d dd}|| j | j }|S )Ngh㈵>r*   )FZ
layer_normr|   r&   rr   r(   r7   r-   r-   r.   r8      s   zChameleonLayerNorm.forward)r=   r>   r?   re   r#   r8   r@   r-   r-   r+   r.   r{      s    r{   r7   n_repreturnc                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)r:   rW   reshape)r7   r   batchnum_key_value_headsslenhead_dimr-   r-   r.   	repeat_kv   s
   0r           modulequerykeyvalueattention_maskscalingdropoutc                 K   s   t || j}t || j}	t||dd| }
|d ur3|d d d d d d d |jd f }|
| }
tjj|
dtj	d
|j}
tjj|
|| jd}
t|
|	}|dd }||
fS )Nr/   r   r0   )rL   r2   )ptrainingr   )r   num_key_value_groupsr%   matmulr[   r:   r   
functionalsoftmaxr4   r3   r2   r   r   
contiguous)r   r   r   r   r   r   r   r~   
key_statesvalue_statesattn_weightscausal_maskattn_outputr-   r-   r.   eager_attention_forward   s   
&r   c                       s   e Zd ZdZddedee f fddZd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dZ  ZS )ChameleonAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNrs   	layer_idxc                    sh  t    || _|| _|d u rtd| jj d |j| _|j	| _	|j
| _| j	| j | _|j| _| j| j | _|j| _|j| _d| _|j| _| jd | _| j| j | j	krctd| j	 d| j dtj| j	| j| j |jd| _tj| j	| j| j |jd| _tj| j	| j| j |jd| _tj| j	| j	|jd| _t| j| jf| _t| j| jf| _|   d S )	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).rq   ) r"   r#   rs   r   loggerwarning_oncer,   r=   attention_dropoutr)   Znum_attention_heads	num_headsr   r   r   rM   
rope_thetaZ	is_causalZmodel_parallel_sizer   
ValueErrorr   rt   Zattention_biasq_projk_projv_projo_projr{   q_normk_norm
_init_roper(   rs   r   r+   r-   r.   r#     s>   

zChameleonAttention.__init__c                 C   s   | j jd u rt| j| j| jd| _d S | j jd }| j jd }|dkr1t| j| j|| jd| _d S |dkrCt| j| j|| jd| _d S t	d| )N)rM   rN   rX   factorZlinear)rM   rK   rN   ZdynamiczUnknown RoPE scaling type )
rs   Zrope_scalingrA   r   rM   r   
rotary_embrb   rg   r   )r(   Zscaling_typerK   r-   r-   r.   r   (  s.   zChameleonAttention._init_ropeFr7   r   r`   past_key_valueoutput_attentions	use_cachecache_positionr   c                 K   s  |  \}	}
}| |}| |}| |}|d| j| j}| |}|d| j| j}| 	|}||	|
| j| j
dd}||	|
| j| j
dd}||	|
| j| j
dd}| ||\}}t||||\}}|d ur|||d}|||| j|\}}t}| jjdkr| jjdkr|rtd nt| jj }|| ||||f| jsdn| j| jd	|\}}||	|
d }| |}|sd }|||fS )
Nr0   r   r/   )r^   r]   r   eagersdpaz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r   )r   r   )sizer   r   r   r   r   r   r   r   r   r[   viewr   rn   updater   r   rs   _attn_implementationr   r   r   r   r   r   r   r   )r(   r7   r   r`   r   r   r   r   r~   ZbszZq_len_query_statesr   r   r]   r^   Zcache_kwargsZattention_interfacer   r   r-   r-   r.   r8   C  sP   







zChameleonAttention.forwardrc   NNNFFN)r=   r>   r?   re   r   r   intr#   r   r%   Tensor
LongTensorr
   boolr   r8   r@   r-   r-   r+   r.   r      s6    '
r   c                          e Zd Zdedef fd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dZ  ZS )ChameleonDecoderLayerrs   r   c                    R   t    |j| _t||d| _t|| _t|j|jd| _	t|j|jd| _
d S N)rs   r   r   r"   r#   r)   r   	self_attnrp   mlpr    rms_norm_epsinput_layernormpost_attention_layernormr   r+   r-   r.   r#        

zChameleonDecoderLayer.__init__NFr7   r   r`   r   r   r   r   r   c              
   K   s   |}	|  |}| jd|||||||d|\}}
}|	| }|}	| |}| |}|	| }|f}|r8||
f7 }|r?||f7 }|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
        r7   r   r`   r   r   r   r   Nr-   )r   r   r   r   r(   r7   r   r`   r   r   r   r   r~   residualZself_attn_weightsZpresent_key_valueoutputsr-   r-   r.   r8     s0   





zChameleonDecoderLayer.forwardr   r=   r>   r?   r   r   r#   r%   r   r   r   r
   r   r   FloatTensorr8   r@   r-   r-   r+   r.   r     2    
r   c                       r   )ChameleonSwinDecoderLayerrs   r   c                    r   r   r   r   r+   r-   r.   r#     r   z"ChameleonSwinDecoderLayer.__init__NFr7   r   r`   r   r   r   r   r   c              
   K   s   |}	| j d|||||||d|\}}
}| |}|	| }|}	| |}| |}|	| }|f}|r8||
f7 }|r?||f7 }|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   Nr-   )r   r   r   r   r   r-   r-   r.   r8     s0   





z!ChameleonSwinDecoderLayer.forwardr   r   r-   r-   r+   r.   r     r   r   c                       s0   e Zd ZdZ fddZdejfddZ  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                    s>   t    |j| _|j| _t|dd| _t| j| j| _	d S )Nbetag      ?)
r"   r#   Znum_embeddings	embed_dimembedding_dimgetattrr   r   	Embedding	embeddingry   r+   r-   r.   r#   %  s
   
z&ChameleonVQVAEVectorQuantizer.__init__hidden_statec              
   C   s   | dddd }|d| j}tj|d dddtj| jjd dd dtd	|| jj	dd  }tj
|dd}| ||j}t| | d | jt||  d   }|||   }| dddd }|||fS )
Nr   r/   r   r   r0   T)rL   r1   rV   z	bd,dn->bn)permuter   r   r   r%   sumr   r&   Zeinsumr[   Zargminr:   r6   detachr   )r(   r   Zhidden_state_flattenedZ	distancesZmin_encoding_indicesZhidden_state_quantlossr-   r-   r.   r8   -  s    
z%ChameleonVQVAEVectorQuantizer.forward)	r=   r>   r?   re   r#   r%   r   r8   r@   r-   r-   r+   r.   r     s    
r   c                       ro   )#ChameleonVQVAEEncoderConvDownsamplec                    s$   t    tj||dddd| _d S )Nr   r/   r   Zkernel_sizeZstridepadding)r"   r#   r   Conv2dconvr(   in_channelsr+   r-   r.   r#   J  s   
z,ChameleonVQVAEEncoderConvDownsample.__init__c                 C   s    t j|dddd}| |}|S )N)r   r   r   r   Zconstantr   )padmoder   )r   r   r   r   r-   r-   r.   r8   N  s   
z+ChameleonVQVAEEncoderConvDownsample.forwardrz   r-   r-   r+   r.   r   I  s    r   c                       s*   e Zd Z		d fdd	Zdd Z  ZS ) ChameleonVQVAEEncoderResnetBlockNFc                    s   t    || _|d u r|n|| _|| _tjjd|ddd| _tjj	||dddd| _
tjjd|ddd| _tj|j| _tjj	||dddd| _| j| jkro| jratjj	||dddd| _d S tjj	||dddd| _d S d S )	N    r!   TZ
num_groupsZnum_channelsr*   Zaffiner   r   r   r   )r"   r#   r   out_channelsuse_conv_shortcutr%   r   	GroupNormnorm1r   conv1norm2ZDropoutr   conv2conv_shortcutnin_shortcut)r(   rs   r   r   r   r+   r-   r.   r#   V  s   
z)ChameleonVQVAEEncoderResnetBlock.__init__c                 C   s   |}|  |}|t|9 }| |}| |}|t|9 }| |}| |}| j| jkr@| j	r;| 
|}|| S | |}|| S rc   )r   r%   sigmoidr   r   r   r   r   r   r   r   r   )r(   r7   r   r-   r-   r.   r8   m  s   






z(ChameleonVQVAEEncoderResnetBlock.forward)NFrz   r-   r-   r+   r.   r   U  s
    r   c                       ro   )ChameleonVQVAEEncoderAttnBlockc                    s   t    || _tjjd|ddd| _tjj||dddd| _tjj||dddd| _	tjj||dddd| _
tjj||dddd| _d S )Nr   r!   Tr   r   r   r   )r"   r#   r   r%   r   r   normr   rl   rm   vproj_outr   r+   r-   r.   r#     s   
z'ChameleonVQVAEEncoderAttnBlock.__init__c                 C   s   |}|  |}| |}| |}| |}|j\}}}}	|||||	 ddd}|||||	 }t||}
|
t	|d  }
t
j|
dd}
|||||	 }|
ddd}
t||
||||	}| |}|| S )Nr   r/   r   r   rV   )r   rl   rm   r   r:   r   r   r%   Zbmmr   r   r   r   )r(   r7   r   r   r   r   
batch_sizeZchannelsheightwidthr   r   r-   r-   r.   r8     s    




z&ChameleonVQVAEEncoderAttnBlock.forwardrz   r-   r-   r+   r.   r     s    
r   c                       s,   e Zd Z fddZdejfddZ  ZS )ChameleonVQVAEEncoderc              	      s  t    t|j| _|j| _|j}|j}|j}|j	}|j
}|j}tjj||dddd| _|}dt| }	|	| _t | _t| jD ]`}
t }t }||	|
  }|||
  }t| jD ]$}|t|||d |}|jd ur||jv r|jdkr|t| q]t }||_||_|
| jd krt||_|d }| j| qBt | _t|||d| j_|jdkrt|nt  | j_!t|||d| j_"tjj#d|d	d
d| _$tjj||rd| n|dddd| _%d S )Nr   r   r   )r   )rs   r   r   Zvanillar/   r   r!   Tr   )&r"   r#   lenchannel_multipliernum_resolutionsnum_res_blocksbase_channels
resolutionr   double_latentlatent_channelsr%   r   r   conv_inr9   in_channel_multiplier
ModuleListdownrangeappendr   Zattn_resolutionsZ	attn_typer   Moduleblockattnr   
downsamplemidblock_1ZIdentityattn_1block_2r   norm_outconv_out)r(   rs   r  r  r   r  r  r  Zcurr_resr
  i_levelr  r  Zblock_inZ	block_outi_blockr  r+   r-   r.   r#     sx   








zChameleonVQVAEEncoder.__init__pixel_valuesc                 C   s   |  |g}t| jD ]C}t| jD ]'}| j| j| |d }t| j| jdkr4| j| j| |}|| q|| jd krN|| j| 	|d  q|d }| j
|}| j
|}| j
|}| |}|t|9 }| |}|S )Nr0   r   r   )r	  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r%   r   r  )r(   r  r7   r  r  r   last_hidden_stater-   r-   r.   r8     s(   

zChameleonVQVAEEncoder.forward)r=   r>   r?   r#   r%   r   r8   r@   r-   r-   r+   r.   r     s    Er   c                   @   sv   e Zd ZdZdd Zedd Zedd Zedd	 Zed
d Z	edd Z
edd ZdejdejfddZdS )ChameleonImageVocabularyMappingzM
    A class for mapping discrete image tokens from VQGAN to BPE tokens.
    c                 C   s   || _ |d| _d S )Nz<image>)	vocab_mapgetimage_token_id)r(   r  r-   r-   r.   r#   
  s   z(ChameleonImageVocabularyMapping.__init__c                 C      dd | j  D S )Nc                 S      i | ]\}}||qS r-   r-   .0rm   r   r-   r-   r.   
<dictcomp>      z<ChameleonImageVocabularyMapping.val2name.<locals>.<dictcomp>)r  itemsr;   r-   r-   r.   val2name     z(ChameleonImageVocabularyMapping.val2namec                 C   s   t dd | j D S )Nc                 S   s   g | ]\}}| d r|qS )IMGIMG)
startswith)r$  namevalr-   r-   r.   
<listcomp>  s    z@ChameleonImageVocabularyMapping.image_tokens.<locals>.<listcomp>)sortedr  r'  r;   r-   r-   r.   image_tokens  s   z,ChameleonImageVocabularyMapping.image_tokensc                    s>   dd t dD  dtdtf fddfddjD S )	Nc                 S   s"   i | ]}t td | t|qS )A)chrordrZ   )r$  ir-   r-   r.   r%    s   " z;ChameleonImageVocabularyMapping.bpe2img.<locals>.<dictcomp>
   old_namer   c                    s$   d  fdd| tdd D S )N c                 3   s    | ]	}  ||V  qd S rc   )r  )r$  cimg_tkn_chr_mappingr-   r.   	<genexpr>      zIChameleonImageVocabularyMapping.bpe2img.<locals>.remap.<locals>.<genexpr>r*  r0   )joinr  )r6  r9  r-   r.   remap  s   $z6ChameleonImageVocabularyMapping.bpe2img.<locals>.remapc                    s    i | ]}|t  j| qS r-   )r   r(  )r$  tok)r>  r(   r-   r.   r%    s     )r  rZ   r0  r;   r-   )r:  r>  r(   r.   bpe2img  s   z'ChameleonImageVocabularyMapping.bpe2imgc                 C   r!  )Nc                 S   r"  r-   r-   r#  r-   r-   r.   r%  !  r&  z;ChameleonImageVocabularyMapping.img2bpe.<locals>.<dictcomp>)r@  r'  r;   r-   r-   r.   img2bpe  r)  z'ChameleonImageVocabularyMapping.img2bpec                 C   s(   t t| j t t| j fS rc   )r%   Ztensorr/  r@  keysvaluesr;   r-   r-   r.   bpe2img_search_tensors#  s   (z6ChameleonImageVocabularyMapping.bpe2img_search_tensorsc                 C   s>   t jt| j d t jd}| j D ]\}}|||< q|S )Nr   rE   )r%   Zzerosrh   rA  rB  r   r'  )r(   mappingrm   r   r-   r-   r.   img2bpe_mapping_tensor'  s   
z6ChameleonImageVocabularyMapping.img2bpe_mapping_tensor	img_batchr   c                 C   s    |j }| j|d }||S )NrS   )rG   rF  r3   )r(   rG  rG   Z
img_tokensr-   r-   r.   convert_img2bpe.  s   
z/ChameleonImageVocabularyMapping.convert_img2bpeN)r=   r>   r?   re   r#   r   r(  r0  r@  rA  rD  rF  r%   r   rH  r-   r-   r-   r.   r    s     





r  c                   @   sL   e Zd ZeZdZdZddgZddgZdZ	dZ
dZdZdZdZdZdd	 Zd
S )ChameleonPreTrainedModelmodelTr   r   past_key_valuesr   Fc                 C   s   | j j}t|tjtjfr%|jjjd|d |j	d ur#|j	j
  d S d S t|tjtjfr=|j	j
  |jjd d S t|trK|jjd d S t|tjrj|jjjd|d |jd url|jj|j 
  d S d S d S )Nr   )r6   stdrD   )rs   Zinitializer_rangerY   r   rt   r   r&   dataZnormal_rr   Zzero_r   	LayerNormZfill_r    r   padding_idx)r(   r   rL  r-   r-   r.   _init_weightsC  s"   


z&ChameleonPreTrainedModel._init_weightsN)r=   r>   r?   r   config_classZbase_model_prefixZsupports_gradient_checkpointing_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attn_2Z_supports_sdpaZ_supports_quantized_cacheZ_supports_cache_classZ_supports_static_cacheZ!_supports_param_buffer_assignmentZ_supports_attention_backendrP  r-   r-   r-   r.   rI  4  s    rI  aK  
    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://arxiv.org/abs/2203.13131).
    )Zcustom_introc                       s<   e Zd ZeZdgZdef fddZdejfddZ	  Z
S )ChameleonVQVAEr   rs   c                    sX   t  | t|| _t|| _tj|j	|j
d| _tj|j
|j	d| _|   d S Nr   )r"   r#   r   encoderr   quantizer%   r   r   r  r   
quant_convZpost_quant_convevalry   r+   r-   r.   r#   `  s   

zChameleonVQVAE.__init__r  c                 C   s.   |  |}| |}| |\}}}|||fS rc   )rU  rW  rV  )r(   r  r7   ZquantZemb_lossindicesr-   r-   r.   encodei  s   


zChameleonVQVAE.encode)r=   r>   r?   r   rQ  rR  r#   r%   r   rZ  r@   r-   r-   r+   r.   rS  U  s
    	rS  c                       sL  e Zd Zdef fddZdd Zdd Zdejfd	d
Z	dejfd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dZ	d(deejdf dejdejdedef
dd Zedejd!ed"ed#ejdejd$efd%d&Z  ZS ))ChameleonModelrs   c                    s   t     j| _ j| _t j j| j| _t	 j
| _| jjs%tntt fddt jD | _t j jd| _t j| _d| _|   d S )Nc                    s   g | ]} |qS r-   r-   )r$  r   rs   decoder_layerr-   r.   r.  {  r&  z+ChameleonModel.__init__.<locals>.<listcomp>r   F)r"   r#   Zpad_token_idrO  
vocab_sizer   r   r)   embed_tokensr  Zvocabulary_mapvocabulary_mappingrs   Z	swin_normr   r   r  r  Znum_hidden_layerslayersr    r   r   rS  Z_from_configZ	vq_configvqmodelgradient_checkpointing	post_initry   r+   r\  r.   r#   r  s   zChameleonModel.__init__c                 C      | j S rc   r_  r;   r-   r-   r.   get_input_embeddings     z#ChameleonModel.get_input_embeddingsc                 C   
   || _ d S rc   rf  r(   r   r-   r-   r.   set_input_embeddings     
z#ChameleonModel.set_input_embeddingsr  c                 C   s   t d | |S )Nz`model.get_image_tokens()` is deprecated and will be removed in v4.58. To obtain discrete token use `model.get_image_features()`)r   warningZget_image_featues)r(   r  r-   r-   r.   get_image_tokens  s   
zChameleonModel.get_image_tokensc                 C   s8   |j d }| 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   r0   )r:   rb  rZ  r`  rH  r   )r(   r  r   r   Z
image_toksZbpe_toksr-   r-   r.   get_image_features  s
   

z!ChameleonModel.get_image_featuresN	input_idsr   r`   rK  inputs_embedsr   r   output_hidden_statesreturn_dictr   r~   r   c                 K   s  |d ur|n| j j}|	d ur|	n| j j}	|d ur|n| j j}|
d ur$|
n| j j}
| jr7| jr7|r7td d}|d u |d uA rCt	d|d urO|d urOt	d|d ur| 
|}|| jjk}t s||  | kr|| jjk }|jd |jd  }t	d| d| ||j|j}|||}|d u r| |}|r|d u rtj st }|d u r|d ur| nd}tj|||jd  |jd	}|d u r|d}| |||||}|}|	rd
nd }|rd
nd }d }| jD ]H}|	r||f7 }| jr| jr| |j |||||||}n||f||||||d|}|d }|r+||r(dnd }|r5||d f7 }q| !|}|	rC||f7 }d }|rJ|}|
sZt"dd ||||fD S t#||||d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_embedszdYou cannot specify both pixel_values and inputs_embeds at the same time, and must specify either oner   r   z6Image features and image tokens do not match: tokens: z, features rG   r-   )r   r`   r   r   r   r   r/   c                 s   s    | ]	}|d ur|V  qd S rc   r-   )r$  r   r-   r-   r.   r;    r<  z)ChameleonModel.forward.<locals>.<genexpr>)r  rK  r7   
attentions)$rs   r   rr  r   use_return_dictrc  r   r   r   r   ro  r`  r   r   Znumelr   r:   r3   rG   r2   Zmasked_scatterr_  r%   Zjit
is_tracingr   get_seq_lengthrO   rk   _update_causal_maskra  Z_gradient_checkpointing_func__call__r   r9   r   )r(   rp  r  r   r`   rK  rq  r   r   rr  rs  r   r~   r0  Zspecial_image_maskZn_image_tokens_in_textZn_image_featurespast_seen_tokensr   r7   Zall_hidden_statesZall_self_attnsZnext_decoder_cacher]  Zlayer_outputsZ
next_cacher-   r-   r.   r8     s   







zChameleonModel.forwardFr   input_tensorc                 C   s:  | j jdkr|d ur|dk r|S d S | j jdkr&t|tjr$t|}|S |d ur.| nd}|d ur7|jnd}| j jdkrO|sO|sOt	j
|||| jdrOd S |j}|jd }	|r^| }
nt|tjri|jd	 n||	 d }
| j||	|
|||jd d
}| j jdkr|d ur|jjdv r|st|j}t	||}|S )NZflash_attention_2r   Zflex_attentionr   Fr   )rq  Zpast_key_values_lengthZis_trainingr   r0   )sequence_lengthtarget_lengthr2   r   r   )cudaZxpuZnpu)rs   r   anyrY   r%   r   r   rx  Zis_compileabler   Z_ignore_causal_mask_sdpar   r2   r:   Zget_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionrG   rX   finfominZ_unmask_unattended)r(   r   r|  r   rK  r   r{  Zusing_compilable_cacher2   r}  r~  r   	min_dtyper-   r-   r.   ry  %  sT   




z"ChameleonModel._update_causal_maskr}  r~  r2   r   c                 K   sD  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	|ddddddd|	f | ddddddf |j }
|
dk}
|ddddddd|	f |
||ddddddd|	f< |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )Z
fill_valuer2   rG   r   )Zdiagonalrt  r0   r   )rL   r%   r  r  fullrG   ZtriurO   r   rW   cloner:   r3   Zmasked_fill)r   r}  r~  r2   r   r   r~   r   r  Zmask_lengthZpadding_maskr-   r-   r.   r  i  s,    $
6  zDChameleonModel._prepare_4d_causal_attention_mask_with_cache_position)NNNNNNNNNNN)F)r=   r>   r?   r   r#   rg  rk  r%   r   rn  ro  r   r   r   r   r
   r   r   r   r   r   r   r8   ry  staticmethodr   r2   r  r@   r-   r-   r+   r.   r[  p  s    	

 
Dr[  c                   @   s   e Zd ZdS )KwargsForCausalLMN)r=   r>   r?   r-   r-   r-   r.   r    s    r  zb
    Chameleon Model with a head on top used for outputting logits for next token prediction.
    c                !       s  e Zd ZdgZ fddZdd Zdd Zdd	 Zd
d Zdd Z	d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 deej dee deeef fdd Z							!d% fd"d#	Z  ZS )&!ChameleonForConditionalGenerationzlm_head.weightc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S )NFrq   )
r"   r#   r[  rJ  r^  r   rt   r)   lm_headrd  ry   r+   r-   r.   r#     s
   
z*ChameleonForConditionalGeneration.__init__c                 C   s   | j jS rc   rJ  r_  r;   r-   r-   r.   rg    s   z6ChameleonForConditionalGeneration.get_input_embeddingsc                 C   s   || j _d S rc   r  rj  r-   r-   r.   rk    s   z6ChameleonForConditionalGeneration.set_input_embeddingsc                 C   re  rc   r  r;   r-   r-   r.   get_output_embeddings  rh  z7ChameleonForConditionalGeneration.get_output_embeddingsc                 C   ri  rc   r  )r(   Znew_embeddingsr-   r-   r.   set_output_embeddings  rl  z7ChameleonForConditionalGeneration.set_output_embeddingsc                 C   ri  rc   rJ  )r(   decoderr-   r-   r.   set_decoder  rl  z-ChameleonForConditionalGeneration.set_decoderc                 C   re  rc   r  r;   r-   r-   r.   get_decoder  rh  z-ChameleonForConditionalGeneration.get_decoderNrp  r  r   r`   rK  rq  labelsr   r   rr  rs  r   r~   r   c                 K   s   |	dur|	n| j j}	|
dur|
n| j j}
|dur|n| j j}| jd||||||||	|
||d|}|d }| |}| jjj}t	|j
j|dddd|f< d}|durd| jd||| j jd|}t|||j|j|jd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]
        ```N)rp  r  r   r`   rK  rq  r   r   rr  rs  r   r   )logitsr  r^  )r   r  rK  r7   ru  r-   )rs   r   rr  rv  rJ  r  r`  r0  r%   r  r2   r  Zloss_functionr^  r   rK  r7   ru  )r(   rp  r  r   r`   rK  rq  r  r   r   rr  rs  r   r~   r   r7   r  r0  r   r-   r-   r.   r8     sB   ,

 z)ChameleonForConditionalGeneration.forwardTc	              
      s<   t  j|f|||||||d|	}
|d dkrd |
d< |
S )N)r  rK  r   rq  r   r`   r   r   r  )r"   prepare_inputs_for_generation)r(   rp  r  rK  r   rq  r   r`   r   r~   Zmodel_inputsr+   r-   r.   r    s    	z?ChameleonForConditionalGeneration.prepare_inputs_for_generation)NNNNNNNNNNNN)NNNNNNT)r=   r>   r?   Z_tied_weights_keysr#   rg  rk  r  r  r  r  r   r   r   r%   r   r   r   r
   r   r   r  r   r   r   r8   r  r@   r-   r-   r+   r.   r    sx    		

Vr  )r  r[  rI  rS  rT  )r   )Sre   	functoolsr   typingr   r   r   r   r%   Ztorch.nn.functionalr   r   r   Ztorch.utils.checkpointZactivationsr	   Zcache_utilsr
   r   Z
generationr   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   Zmodeling_outputsr   r   Zmodeling_utilsr   r   Zprocessing_utilsr   Zpytorch_utilsr   utilsr   r   r   r   r   r   Zconfiguration_chameleonr   r   Z!torch.nn.attention.flex_attentionr   Zintegrations.flex_attentionr   Z
get_loggerr=   r   r  r    r  rA   rb   rg   rj   rn   rp   rN  r{   r   r   r   rQ   r   r   r   r   r   r   r   r   r   r  rI  rS  r[  r  r  __all__r-   r-   r-   r.   <module>   s    

 


 	KI/,#a/   3 