
    gJ/                    *   d Z ddl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 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 ddl m!Z! ddl"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+m,Z,  e&            r
ddl-m.Z.m/Z/m0Z0  e(j1        e2          Z3dZ4dZ5g dZ6dZ7dZ8 G d de
j9                  Z: e!j;        e:            G d de
j9                  Z< G d de<          Z= G d d e<          Z>d! Z?dPd"Z@ G d# d$e
j9                  ZA G d% d&e
jB                  ZCd'ejD        d(eEd)ejD        fd*ZF G d+ d,e
j9                  ZG G d- d.eG          ZH G d/ d0eG          ZIeGeHeId1ZJ G d2 d3e
j9                  ZK G d4 d5e
j9                  ZL G d6 d7e
j9                  ZM G d8 d9e
j9                  ZN G d: d;e
j9                  ZO G d< d=e
j9                  ZP G d> d?e
j9                  ZQd@ZR e$dAeR           G dB dCe                      ZS G dD dE          ZTdFZU e$dGeU           G dH dIe                      ZVdJZW e$dGeU           G dK dLeV                      ZX e$dMeU           G dN dOeVe                      ZYdS )QzPyTorch Chameleon model.    N)cached_property)OptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)CacheStaticCache)GenerationMixin)AttentionMaskConverter)_flash_attention_forward)BaseModelOutputWithPastCausalLMOutputWithPast)PreTrainedModel)ALL_LAYERNORM_LAYERS)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )ChameleonConfigChameleonVQVAEConfig)index_first_axis	pad_inputunpad_inputr   zmeta/chameleon-7b)r      i   g{Gz?z	'LABEL_0'c                   ,     e Zd Zd fd	Zd Zd Z xZS )ChameleonRMSNormư>c                     t                                                       t          j        t	          j        |                    | _        || _        dS )z?
        ChameleonRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      l/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/chameleon/modeling_chameleon.pyr'   zChameleonRMSNorm.__init__A   sD     	l5:k#:#:;; #    c                    |j         }|                    t          j                  }|                    d                              dd          }|t          j        || j        z             z  }| j        |                    |          z  S )N   T)keepdim)	dtypetor)   float32powmeanrsqrtr,   r+   )r-   hidden_statesinput_dtypevariances       r1   forwardzChameleonRMSNorm.forwardI   s|    #)%((77 $$Q'',,R,>>%Ht?T4T(U(UU{]--k::::r2   c                 H    t          | j        j                   d| j         S )Nz, eps=)tupler+   shaper,   r-   s    r1   
extra_reprzChameleonRMSNorm.extra_reprP   s&    )**II$2GIIIr2   )r$   )__name__
__module____qualname__r'   r@   rE   __classcell__r0   s   @r1   r#   r#   @   sb        $ $ $ $ $ $; ; ;J J J J J J Jr2   r#   c                   P     e Zd Zd fd	Z ej                    d             Z xZS )ChameleonRotaryEmbedding   '  N      ?c                 |   t                                                       || _        || _        || _        || _        d| j        t          j        d| j        dt          j                  	                                
                    |          | j        z  z  z  }|                     d|d           || _        d S )NrO   r   r4   r7   inv_freqF
persistent)r&   r'   scaling_factordimmax_position_embeddingsbaser)   arangeint64floatr8   register_buffermax_seq_len_cached)r-   rV   rW   rX   devicerU   rR   r0   s          r1   r'   z!ChameleonRotaryEmbedding.__init__Z   s    ,'>$	$)Q!5;(W(W(W(](](_(_(b(bci(j(jmqmu(uvwZeDDD"9r2   c                    | j         d d d d f                                                             |j        d         dd          }|d d d d d f                                         }|j        j        }t          |t                    r|dk    r|nd}t          j	        |d          5  |                                |                                z  
                    dd          }t          j        ||fd	          }|                                }|                                }	d d d            n# 1 swxY w Y   |                    |j        
          |	                    |j        
          fS )Nr   r5   r   mpscpuF)device_typeenabledr4   rV   rQ   )rR   r[   expandrC   r^   type
isinstancestrr)   autocast	transposecatcossinr8   r7   )
r-   xposition_idsinv_freq_expandedposition_ids_expandedrb   freqsembrl   rm   s
             r1   r@   z ChameleonRotaryEmbedding.forwarde   s    !M$4-8>>@@GGHZ[\H]_acdee ,QQQaaaZ 8 > > @ @ hm%/S%A%AekUZFZFZkk`e^UCCC 	 	&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C''))C''))C		 	 	 	 	 	 	 	 	 	 	 	 	 	 	
 vvAGv$$cff17f&;&;;;s   'A>D11D58D5)rM   rN   NrO   )rF   rG   rH   r'   r)   no_gradr@   rI   rJ   s   @r1   rL   rL   Y   s`        	: 	: 	: 	: 	: 	: U]__< < _< < < < <r2   rL   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                     |                                 | j        z  }t                                          ||          \  }}||fS N)r[   rU   r&   r@   )r-   rn   ro   rl   rm   r0   s        r1   r@   z-ChameleonLinearScalingRotaryEmbedding.forward{   s@    #))++d.AA77??1l33SCxr2   rF   rG   rH   __doc__r@   rI   rJ   s   @r1   rv   rv   x   s>        ii        r2   rv   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        k    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        z  z  z  }|                     d|d           t                                          ||          \  }}||fS )	Nr   r4   rO   r   rQ   rR   FrS   )r)   maxrW   rX   rU   rV   rY   rZ   r[   r8   r^   r\   r&   r@   )	r-   rn   ro   seq_lenrX   rR   rl   rm   r0   s	           r1   r@   z1ChameleonDynamicNTKScalingRotaryEmbedding.forward   s    )L))A-T1119$w.1MMRVRehiRij(dhl+ - -D a1EKHHHNNPPSSTUT\]]`d`hhiH   X% HHH77??1l33SCxr2   ry   rJ   s   @r1   r|   r|      s>        {{        r2   r|   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..Nr5   r4   rd   )rC   r)   rk   )rn   x1x2s      r1   rotate_halfr      s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r2   c                     |                     |          }|                     |          }| |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.
    )	unsqueezer   )qkrl   rm   ro   unsqueeze_dimq_embedk_embeds           r1   apply_rotary_pos_embr      sc    ( --
&
&C
--
&
&C3w;q>>C/0G3w;q>>C/0GGr2   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                 | _        d S )Nbias)r&   r'   configr.   intermediate_sizer   Linearmlp_bias	gate_projup_proj	down_projr
   
hidden_actact_fnr-   r   r0   s     r1   r'   zChameleonMLP.__init__   s    !-!'!94#3T5KRXRabbby!143IPVP_```4#94;KRXRabbbV./r2   c                     |                      |                     |                     |                    |                     |          z            }|S rx   )r   r   r   r   )r-   rn   r   s      r1   r@   zChameleonMLP.forward   sA    NN4;;t~~a/@/@#A#ADLLQROO#STT	r2   rF   rG   rH   r'   r@   rI   rJ   s   @r1   r   r      sG        0 0 0 0 0      r2   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                 ^     t                      j        |g|R i | |d         f| _        d S )Nr5   )r&   r'   normalized_shape)r-   r.   argskwargsr0   s       r1   r'   zChameleonLayerNorm.__init__   s?    6t666v666!,R 2r2   c                 f    t          j        || j        d d d          }|| j        z  | j        z   }|S )Ngh㈵>r/   )F
layer_normr   r+   r   r-   r=   s     r1   r@   zChameleonLayerNorm.forward   s:    ]D4I4QU[_```%3di?r2   )rF   rG   rH   rz   r'   r@   rI   rJ   s   @r1   r   r      sQ         3 3 3 3 3      r2   r   r=   n_repreturnc                     | j         \  }}}}|dk    r| S | dddddddddf                             |||||          } |                     |||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)rC   re   reshape)r=   r   batchnum_key_value_headsslenhead_dims         r1   	repeat_kvr      s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr2   c                   "    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' paperNr   	layer_idxc                 ^   t                                                       || _        || _        |(t                              d| j        j         d           |j        | _        |j	        | _	        |j
        | _        | j	        | j        z  | _        |j        | _        | j        | j        z  | _        |j        | _        |j        | _        d| _        |j        | _        | j        | j        z  | j	        k    r t'          d| j	         d| j         d          t)          j        | j	        | j        | j        z  |j                  | _        t)          j        | j	        | j        | j        z  |j                  | _        t)          j        | j	        | j        | j        z  |j                  | _        t)          j        | j	        | j	        |j                  | _        t7          | j        | j        f          | _        t7          | j        | j        f          | _        |                                  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.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).r   )r&   r'   r   r   loggerwarning_oncer0   rF   attention_dropoutr.   num_attention_heads	num_headsr   r   num_key_value_groupsrW   
rope_theta	is_causalmodel_parallel_size
ValueErrorr   r   attention_biasq_projk_projv_projo_projr   q_normk_norm
_init_roper-   r   r   r0   s      r1   r'   zChameleonAttention.__init__   s   ",!8 , , ,   "(!9!-3(DN:#)#= $(Nd6N$N!'-'E$ +#)#= MDN*t/???8RVRb 8 8%)^8 8 8  
 i 0$.4=2PW]Wlmmmi 0$2JT]2Zagavwwwi 0$2JT]2Zagavwwwi 0$2BI^___($.$-)HII($*BDM)RSSr2   c                    | j         j        (t          | j        | j        | j                  | _        d S | j         j        d         }| j         j        d         }|dk    r)t          | j        | j        || j                  | _        d S |dk    r)t          | j        | j        || j                  | _        d S t          d|           )N)rW   rX   rf   factorlinear)rW   rU   rX   dynamiczUnknown RoPE scaling type )
r   rope_scalingrL   r   rW   r   
rotary_embrv   r|   r   )r-   scaling_typerU   s      r1   r   zChameleonAttention._init_rope  s    ;#+6(,(D_  DOOO  ;3F;L![5h?Nx''"GM,0,H#1	# # # **"KM,0,H#1	# # # !!Ll!L!LMMMr2   Fr=   attention_maskro   past_key_valueoutput_attentions	use_cachecache_positionr   c                 "   |                                 \  }	}
}|                     |          }|                     |          }|                     |          }|                    d| j        | j                  }|                     |          }|                    d| j        | j                  }| 	                    |          }|                    |	|
| j        | j                  
                    dd          }|                    |	|
| j        | j                  
                    dd          }|                    |	|
| j        | j                  
                    dd          }|                     ||          \  }}t          ||||          \  }}|&|||d}|                    ||| j        |          \  }}t!          || j                  }t!          || j                  }t%          j        ||
                    dd                    t)          j        | j                  z  }|$|d d d d d d d |j        d         f         }||z   }t.          j                            |dt$          j                                      |j                  }t.          j                            || j        | j                  }t%          j        ||          }|                                 |	| j        |
| j        fk    r5tA          d	|	| j        |
| j        f d
|                                            |
                    dd          !                                }|                    |	|
| j"                  }| #                    |          }|sd }|||fS )Nr5   r   r4   rm   rl   r   r	   )rV   r7   )ptrainingz `attn_output` should be of size z	, but is )$sizer   r   r   r   r   r   r   r   r   rj   viewr   r   updater   r   r   r)   matmulmathsqrtrC   r   
functionalsoftmaxr9   r8   r7   dropoutr   r   r   
contiguousr.   r   )r-   r=   r   ro   r   r   r   r   r   bszq_len_query_states
key_statesvalue_statesrl   rm   cache_kwargsattn_weightscausal_maskattn_outputs                        r1   r@   zChameleonAttention.forward0  ss    &**,,UA{{=11[[//
{{=11#++BNN{{<00''D,DdmTT
[[,,
#++CVV``abdeff''UD4Ldm\\ffghjkll
#((eT5Mt}]]gghiklmm??<>>S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII|L*2F2Fq!2L2LMMPTPYZ^ZgPhPhh%(AAAqqq2HJ4DR4H2H)HIK'+5L },,\r,WWZZ[g[mnn},,\T=S^b^k,lll<>>#t~udm!LLL)CPTP]3^ ) )$$&&) )  
 "++Aq11<<>>!))#ud6FGGkk+..  	 LL.88r2   rx   NNNFFN)rF   rG   rH   rz   r   r   intr'   r   r)   Tensor
LongTensorr   boolr   r@   rI   rJ   s   @r1   r   r      s&       GG" " "8C= " " " " " "LN N N< 2637*."'59>9 >9|>9 !.>9 u/0	>9
 !>9  >9 >9 !!12>9 
u|Xel3XeEL>Q5RR	S>9 >9 >9 >9 >9 >9 >9 >9r2   r   c                       e Zd ZdZ f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 )ChameleonFlashAttention2aN  
    Chameleon flash attention module. This module inherits from `ChameleonAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                 b     t                      j        |i | t                       | _        d S rx   )r&   r'   r   _flash_attn_uses_top_left_mask)r-   r   r   r0   s      r1   r'   z!ChameleonFlashAttention2.__init__z  s9    $)&)))
 3V2W2W.W+++r2   NFr=   r   ro   r   r   r   r   r   c                    t          |t                    rt          d          d}|                                \  }	}
}|                     |          }|                     |          }|                     |          }|                    d| j        | j	                  }| 
                    |          }|                    d| j        | j	                  }|                     |          }|                    |	|
| j        | j	                                      dd          }|                    |	|
| j        | j	                                      dd          }|                    |	|
| j        | j	                                      dd          }|                     ||          \  }}t!          ||||          \  }}|&|||d}|                    ||| j        |          \  }}|                    dd          }|                    dd          }|                    dd          }| j        r| j        nd}|j        }|t,          j        k    rt-          j                    rt-          j                    }n3t5          | j        d          r| j        j        }n| j        j        j        }t<                              d	| d
           |                     |          }|                     |          }|                     |          }tC          |||||
|tE          | dd           | j#        | j$        	  	        }|                    |	|
d          %                                }| &                    |          }|sd }|||fS )Nz`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformersFr5   r   r4   r           _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .sliding_window)r   r   use_top_left_maskr   )'rg   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   r   r   r   r   r   r   r7   r)   r9   is_autocast_enabledget_autocast_gpu_dtypehasattrr   r   r+   r   r   r8   r   getattrr   r   r   r   )r-   r=   r   ro   r   r   r   r   r   r   r   r   r   r   r   rl   rm   r   dropout_rater>   target_dtyper   r   s                          r1   r@   z ChameleonFlashAttention2.forward  s    nk22 	}  
 "%**,,UA{{=11[[//
{{=11#++BNN{{<00''D,DdmTT
[[,,

 $((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm??<>>S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$J $--a33))!Q//
#--a3315Gt--C #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L. "4)94@@"An

 

 

 "))#ub99DDFFkk+..  	 LL.88r2   r   )rF   rG   rH   rz   r'   r)   r   r   r   r   r   r   r@   rI   rJ   s   @r1   r   r   s  s        X X X X X 6:37*."'59b9 b9|b9 !!12b9 u/0	b9
 !b9  b9 b9 !!12b9 
u|Xel3XeEL>Q5RR	Sb9 b9 b9 b9 b9 b9 b9 b9r2   r   c                        e Z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 fdZ xZS )ChameleonSdpaAttentiona   
    Chameleon attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `ChameleonAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFr=   r   ro   r   r   r   r   r   c           	         |rBt                               d           t                                          |||||||          S |                                \  }}	}
|                     |          }|                     |          }|                     |          }|                    d| j	        | j
                  }|                     |          }|                    d| j        | j
                  }|                     |          }|                    ||	| j	        | j
                                      dd          }|                    ||	| j        | j
                                      dd          }|                    ||	| j        | j
                                      dd          }|                     ||          \  }}t#          ||||d           \  }}|&|||d}|                    ||| j        |          \  }}t)          || j                  }t)          || j                  }|}|!||d d d d d d d |j        d         f         }|j        j        dk    r>|<|                                }|                                }|                                }||	dk    rd	nd
}t4          j        j                            ||||| j        r| j        nd|          }|                    dd                                          }|                    ||	| j                   }| !                    |          }|d |fS )Na  ChameleonModel is using ChameleonSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r=   r   ro   r   r   r   r   r5   r   r4   r   r   cudaTFr   )	attn_mask	dropout_pr   )"r   r   r&   r@   r   r   r   r   r   r   r   r   r   r   rj   r   r   r   r   r   r   r   rC   r^   rf   r   r)   r   r   scaled_dot_product_attentionr   r   r.   r   )r-   r=   r   ro   r   r   r   r   r   r   r   r   r   r   rl   rm   r   r   r   r   r0   s                       r1   r@   zChameleonSdpaAttention.forward  sa     	[   77??+-)-"3#- #    &**,,UA{{=11[[//
{{=11#++BNN{{<00''D,DdmTT
[[,,
#++CVV``abdeff''UD4Ldm\\ffghjkll
#((eT5Mt}]]gghiklmm??<>>S#7jRUWZ\`#a#a j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII$%.*D%aaaAAA/E1A"1E/E&EFK #v--+2I'2244L#..00J'2244L (/EAIIDD5	h)FF!04Fd,,3 G 
 
 "++Aq11<<>>!&&sE43CDDkk+..D.00r2   r   )rF   rG   rH   rz   r)   r   r   r   r   r   r   r@   rI   rJ   s   @r1   r  r    s          2637*."'59R1 R1|R1 !.R1 u/0	R1
 !R1  R1 R1 !!12R1 
u|Xel3XeEL>Q5RR	SR1 R1 R1 R1 R1 R1 R1 R1 R1 R1r2   r  )eagerflash_attention_2sdpac                       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                 J   t                                                       |j        | _        t          |j                 ||          | _        t          |          | _        t          |j        |j	                  | _
        t          |j        |j	                  | _        d S N)r   r   r   r&   r'   r.   CHAMELEON_ATTENTION_CLASSES_attn_implementation	self_attnr   mlpr#   rms_norm_epsinput_layernormpost_attention_layernormr   s      r1   r'   zChameleonDecoderLayer.__init__O      !-4V5PQY_ktuuu''/0BH[\\\(89KQWQd(e(e(e%%%r2   NFr=   r   ro   r   r   r   r   r   c                     |}	|                      |          } | j        d|||||||d|\  }}
}|	|z   }|}	|                     |          }|                     |          }|	|z   }|f}|r||
fz  }|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
        r   )r  r  r  r  r-   r=   r   ro   r   r   r   r   r   residualself_attn_weightspresent_key_valueoutputss                r1   r@   zChameleonDecoderLayer.forwardY  s    < !,,];; ?Mdn 	?
')%)/)	?
 	?
 	?
 	?
;(*; !=0 !55mDD// =0 " 	,)++G 	,)++Gr2   r   rF   rG   rH   r   r   r'   r)   r   r   r   r   r   r   FloatTensorr@   rI   rJ   s   @r1   r  r  N  s       f f3 f f f f f f 2637*.,1$)59= =|= !.= u/0	=
 != $D>= D>= !!12= 
u (51BEDU1U+V"WW	X= = = = = = = =r2   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                 J   t                                                       |j        | _        t          |j                 ||          | _        t          |          | _        t          |j        |j	                  | _
        t          |j        |j	                  | _        d S r  r  r   s      r1   r'   z"ChameleonSwinDecoderLayer.__init__  r  r2   NFr=   r   ro   r   r   r   r   r   c                     |}	 | j         d|||||||d|\  }}
}|                     |          }|	|z   }|}	|                     |          }|                     |          }|	|z   }|f}|r||
fz  }|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                r1   r@   z!ChameleonSwinDecoderLayer.forward  s    > ! ?Mdn 	?
')%)/)	?
 	?
 	?
 	?
;(*; ,,];; =0 //55mDD =0 " 	,)++G 	,)++Gr2   r   r!  rJ   s   @r1   r$  r$    s       f f3 f f f f f f 2637*.,1$)59; ;|; !.; u/0	;
 !; $D>; D>; !!12; 
u (51BEDU1U+V"WW	X; ; ; ; ; ; ; ;r2   r$  c                   8     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                  | _	        | j        | _
        d S )Nbetag      ?)r&   r'   num_embeddings	embed_dimembedding_dimr   r*  r   	Embedding	embeddingre_embedr   s     r1   r'   z&ChameleonVQVAEVectorQuantizer.__init__  si    $3#-FFD11	d&94;MNN+r2   hidden_statec           
      R   |                     dddd                                          }|                    d| j                  }t	          j        |dz  dd          t	          j        | j        j        dz  d          z   dt	          j        d	|| j        j        	                    dd                    z  z
  }t	          j
        |d          }|                     |                              |j                  }t	          j        |                                |z
  dz            | j        t	          j        ||                                z
  dz            z  z   }|||z
                                  z   }|                     dddd                                          }|||fS )
Nr   r4   r	   r   r5   T)rV   r6   rd   z	bd,dn->bn)permuter   r   r-  r)   sumr/  r+   einsumrj   argminrC   r;   detachr*  )r-   r1  hidden_state_flattened	distancesmin_encoding_indiceshidden_state_quantlosss          r1   r@   z%ChameleonVQVAEVectorQuantizer.forward  s   #++Aq!Q77BBDD!-!2!22t7I!J!J I,a/QEEEi-q0a8889%,{,BDNDYDcDcdeghDiDijjjk 	  %|I1===!^^,@AAFF|GYZZ z-4466E!KLLty[`[e,"5"5"7"77A=\
 \
 P
 

 *-?,-N,V,V,X,XX 0771aCCNNPP!4)===r2   )	rF   rG   rH   rz   r'   r)   r   r@   rI   rJ   s   @r1   r(  r(    s_         , , , , ,>EL > > > > > > > >r2   r(  c                   $     e Zd Z fdZd Z xZS )#ChameleonVQVAEEncoderConvDownsamplec                     t                                                       t          j        ||ddd          | _        d S )Nr	   r4   r   kernel_sizestridepadding)r&   r'   r   Conv2dconvr-   in_channelsr0   s     r1   r'   z,ChameleonVQVAEEncoderConvDownsample.__init__  s:    Ik;AaYZ[[[			r2   c                 `    t          j        |ddd          }|                     |          }|S )N)r   r   r   r   constantr   )padmodevalue)r   rJ  rE  r   s     r1   r@   z+ChameleonVQVAEEncoderConvDownsample.forward  s2    mJVWXXX		-00r2   r   rJ   s   @r1   r>  r>    sL        \ \ \ \ \      r2   r>  c                   *     e Zd Z	 	 d fd	Zd Z xZS ) ChameleonVQVAEEncoderResnetBlockNFc                    t                                                       || _        ||n|| _        || _        t
          j                            d|dd          | _        t
          j        	                    ||ddd          | _
        t
          j                            d|dd          | _        t
          j                            |j                  | _        t
          j        	                    ||ddd          | _        | j        | j        k    r]| j        r+t
          j        	                    ||ddd          | _        d S t
          j        	                    ||ddd          | _        d S d S )	N    r$   T
num_groupsnum_channelsr/   affiner	   r   r@  r   )r&   r'   rG  out_channelsuse_conv_shortcutr)   r   	GroupNormnorm1rD  conv1norm2Dropoutr   conv2conv_shortcutnin_shortcut)r-   r   rG  rU  r]  r0   s        r1   r'   z)ChameleonVQVAEEncoderResnetBlock.__init__  sR    	&+7+?KK\!.X''2KUYbf'gg
X__[,AVWab_cc
X''2LVZcg'hh
x''77X__\<QWXbc_dd
t000% s%*X__[,\]fgqr_%s%s"""$)HOOK[\efpqO$r$r!!!	 10r2   c                    |}|                      |          }|t          j        |          z  }|                     |          }|                     |          }|t          j        |          z  }|                     |          }|                     |          }| j        | j        k    r2| j	        r| 
                    |          }n|                     |          }||z   S rx   )rX  r)   sigmoidrY  rZ  r   r\  rG  rU  rV  r]  r^  )r-   r=   r  s      r1   r@   z(ChameleonVQVAEEncoderResnetBlock.forward6  s     

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

=11

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

=11t000% 7--h77,,X66-''r2   )NFr   rJ   s   @r1   rN  rN    sZ        
 s s s s s s.( ( ( ( ( ( (r2   rN  c                   $     e Zd Z fdZd Z xZS )ChameleonVQVAEEncoderAttnBlockc                    t                                                       || _        t          j                            d|dd          | _        t          j                            ||ddd          | _        t          j                            ||ddd          | _	        t          j                            ||ddd          | _
        t          j                            ||ddd          | _        d S )NrP  r$   TrQ  r   r   r@  )r&   r'   rG  r)   r   rW  normrD  r   r   vproj_outrF  s     r1   r'   z'ChameleonVQVAEEncoderAttnBlock.__init__K  s    &H&&";TXae&ff	kqQR\]^^kqQR\]^^kqQR\]^^[aXYcdeer2   c                    |}|                      |          }|                     |          }|                     |          }|                     |          }|j        \  }}}}	|                    ||||	z                                ddd          }|                    ||||	z            }t          j        ||          }
|
t          |          dz  z  }
t          j        |
d          }
|                    ||||	z            }|
                    ddd          }
t          j        ||
                              ||||	          }|                     |          }||z   S )Nr   r4   r   g      rd   )rd  r   r   re  rC   r   r3  r)   bmmr   r   r   rf  )r-   r=   r  r   r   r   
batch_sizechannelsheightwidthr   r   s               r1   r@   z&ChameleonVQVAEEncoderAttnBlock.forwardU  s[    		-00vvm,,VVM**
vvm,, /;.@+
Hfe#++J&5.QQYYZ[]^`abb''
HfunMM
yz::#s8}}'>?y1555 $++J&5.QQ#++Aq!44il;;CCJPXZ`bghhmmK00+%%r2   r   rJ   s   @r1   rb  rb  J  sL        f f f f f& & & & & & &r2   rb  c                   4     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                            ||ddd          | _        |}dt          |          z   }	|	| _        t          j                    | _        t'          | j                  D ]}
t          j                    }t          j                    }||	|
         z  }|||
         z  }t'          | j                  D ]f}|                    t+          |||                     |}|j        6||j        v r-|j        dk    r"|                    t1          |                     gt          j                    }||_        ||_        |
| j        dz
  k    rt9          |          |_        |dz  }| j                            |           t          j                    | _        t+          |||          | j        _        |j        dk    rt1          |          nt          j                     | j        _!        t+          |||          | j        _"        t          j        #                    d|d	d
          | _$        t          j                            ||rd|z  n|ddd          | _%        d S )Nr	   r   r@  )r   )r   rG  rU  vanillar4   rP  r$   TrQ  )&r&   r'   lenchannel_multipliernum_resolutionsnum_res_blocksbase_channels
resolutionrG  double_latentlatent_channelsr)   r   rD  conv_inrB   in_channel_multiplier
ModuleListdownrangeappendrN  attn_resolutions	attn_typerb  Moduleblockattnr>  
downsamplemidblock_1Identityattn_1block_2rW  norm_outconv_out)r-   r   ru  rv  rG  rw  rx  rr  curr_resrz  i_levelr  r  block_in	block_outi_blockr|  r0   s                    r1   r'   zChameleonVQVAEEncoder.__init__n  s   "6#<==$3,&
(, 0#6x{MqYZdeff $u-?'@'@ @%:"MOO	T122 	# 	#GMOOE=??D$'<W'EEH%(:7(CCI !455 J J4%$,%.     %+7 F$;;;(I55KK >x H HIII9;;DDJDI$.222"Eh"O"O#q=IT""""9;;; !
 
 

 GMFVZcFcFc8BBBikitiviv; !
 
 
 **bxUYbf*gg#0EAo ( 
 
r2   pixel_valuesc                 J   |                      |          g}t          | j                  D ]}t          | j                  D ]} | j        |         j        |         |d                   }t          | j        |         j                  dk    r! | j        |         j        |         |          }|                    |           || j        dz
  k    r9|                    | j        |         	                    |d                              |d         }| j
                            |          }| j
                            |          }| j
                            |          }|                     |          }|t          j        |          z  }|                     |          }|S )Nr5   r   r   )ry  r}  rs  rt  r|  r  rq  r  r~  r  r  r  r  r  r  r)   r`  r  )r-   r  r=   r  r  r1  last_hidden_states          r1   r@   zChameleonVQVAEEncoder.forward  s   l334T122 		W 		WG !455 3 3@ty17@!"%    ty).//!33#C49W#5#:7#CL#Q#QL$$\2222$.222$$TYw%7%B%B=QSCT%U%UVVV *"- H,,->?? HOO,=>> H,,->?? !MM*;<<U]+<=== MM*;<<  r2   )rF   rG   rH   r'   r)   r   r@   rI   rJ   s   @r1   rn  rn  m  s\        C
 C
 C
 C
 C
J!E$4 ! ! ! ! ! ! ! !r2   rn  aS  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

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

    Parameters:
        config ([`ChameleonVQVAEConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
aF  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).
    c                   J     e Zd ZeZdgZd Zdef fdZdej	        fdZ
 xZS )ChameleonVQVAEr(  c                 *   | j         j        }t          |t          j                  r#|j        j                            d|           d S t          |t          j                  r?|j	        j        
                                 |j        j                            d           d S t          |t          j        t          j        f          rH|j        j                            d|           |j	        "|j	        j        
                                 d S d S d S )Nr   r;   stdrO   )r   initializer_rangerg   r   r.  r+   datanormal_rW  r   zero_fill_r   rD  r-   moduler  s      r1   _init_weightszChameleonVQVAE._init_weights  s    k+fbl++ 	)M&&CS&99999-- 	)K""$$$M$$S)))))BI 677 	)M&&CS&999{& &&(((((	) 	)&&r2   r   c                    t                                          |           t          |          | _        t	          |          | _        t          j                            |j	        |j
        d          | _        t          j                            |j
        |j	        d          | _        |                                  d S Nr   )r&   r'   rn  encoderr(  quantizer)   r   rD  rx  r,  
quant_convpost_quant_convevalr   s     r1   r'   zChameleonVQVAE.__init__  s       ,V445f==(//&*@&BRTUVV$xv/?AWYZ[[		r2   r  c                     |                      |          }|                     |          }|                     |          \  }}}|||fS rx   )r  r  r  )r-   r  r=   quantemb_lossindicess         r1   encodezChameleonVQVAE.encode  sI    \2266#'==#?#? xh''r2   )rF   rG   rH   r   config_class_no_split_modulesr  r'   r)   r   r  rI   rJ   s   @r1   r  r    s         (L89
) 
) 
)3      (5#3 ( ( ( ( ( ( ( (r2   r  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dS )ChameleonImageVocabularyMappingzM
    A class for mapping discrete image tokens from VQGAN to BPE tokens.
    c                 H    || _         |                    d          | _        d S )Nz<image>)	vocab_mapgetimage_token_id)r-   r  s     r1   r'   z(ChameleonImageVocabularyMapping.__init__  s#    "'mmI66r2   c                 H    d | j                                         D             S )Nc                     i | ]\  }}||	S r  r  .0r   re  s      r1   
<dictcomp>z<ChameleonImageVocabularyMapping.val2name.<locals>.<dictcomp>  s    888A1888r2   )r  itemsrD   s    r1   val2namez(ChameleonImageVocabularyMapping.val2name  s$    88!5!5!7!78888r2   c                 b    t          d | j                                        D                       S )Nc                 B    g | ]\  }}|                     d           |S )IMGIMG)
startswith)r  namevals      r1   
<listcomp>z@ChameleonImageVocabularyMapping.image_tokens.<locals>.<listcomp>  s.    ```ytSdooV^F_F_`s```r2   )sortedr  r  rD   s    r1   image_tokensz,ChameleonImageVocabularyMapping.image_tokens  s-    ``DN,@,@,B,B```aaar2   c                      d t          d          D             dt          dt          ffd fd j        D             S )Nc                 h    i | ]/}t          t          d           |z             t          |          0S )A)chrordrh   )r  is     r1   r  z;ChameleonImageVocabularyMapping.bpe2img.<locals>.<dictcomp>  s2    LLLQs3s88a<00#a&&LLLr2   
   old_namer   c                 p    d                     fd| t          d          d         D                       S )N c              3   D   K   | ]}                     ||          V  d S rx   )r  )r  cimg_tkn_chr_mappings     r1   	<genexpr>zIChameleonImageVocabularyMapping.bpe2img.<locals>.remap.<locals>.<genexpr>  s4      __Q.221a88______r2   r  r5   )joinrq  )r  r  s    r1   remapz6ChameleonImageVocabularyMapping.bpe2img.<locals>.remap  s;    77____(3x==[]K]B^______r2   c           	      X    i | ]&}|t           j        |                             'S r  )r   r  )r  tokr  r-   s     r1   r  z;ChameleonImageVocabularyMapping.bpe2img.<locals>.<dictcomp>  s4    QQQSt}S12233QQQr2   )r}  rh   r  )r-   r  r  s   `@@r1   bpe2imgz'ChameleonImageVocabularyMapping.bpe2img  sv    LL%))LLL	`C 	`C 	` 	` 	` 	` 	` 	` RQQQQt?PQQQQr2   c                 H    d | j                                         D             S )Nc                     i | ]\  }}||	S r  r  r  s      r1   r  z;ChameleonImageVocabularyMapping.img2bpe.<locals>.<dictcomp>"  s    666A1666r2   )r  r  rD   s    r1   img2bpez'ChameleonImageVocabularyMapping.img2bpe   s$    66!3!3!5!56666r2   c                     t          j        t          | j                                                            t          j        t          | j                                                            fS rx   )r)   tensorr  r  keysvaluesrD   s    r1   bpe2img_search_tensorsz6ChameleonImageVocabularyMapping.bpe2img_search_tensors$  sM    |F4<#4#4#6#67788%,vdlNaNaNcNcGdGd:e:eeer2   c                     t          j        t          | j                                                  dz   t           j                  }| j                                        D ]
\  }}|||<   |S )Nr   rQ   )r)   zerosr~   r  r  r   r  )r-   mappingr   re  s       r1   img2bpe_mapping_tensorz6ChameleonImageVocabularyMapping.img2bpe_mapping_tensor(  sd    +c$,"3"3"5"566:%)LLLL&&(( 	 	DAqGAJJr2   	img_batchr   c                 z    |j         }| j        |                    d                   }|                    |          S )Nra   )r^   r  r8   )r-   r  r^   
img_tokenss       r1   convert_img2bpez/ChameleonImageVocabularyMapping.convert_img2bpe/  s5    !0e1D1DE
}}V$$$r2   N)rF   rG   rH   rz   r'   r   r  r  r  r  r  r  r)   r   r  r  r2   r1   r  r    s         7 7 7 9 9 _9 b b _b R R _R 7 7 _7 f f _f   _% %%, % % % % % %r2   r  aN  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

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

    Parameters:
        config ([`ChameleonConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zWThe bare chameleon Model outputting raw hidden-states without any specific head on top.c                   H    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	S )
ChameleonPreTrainedModelmodelTr  r$  past_key_valuesr   Fc                 >   | j         j        }t          |t                    r|                    |j                   d S t          |t          j        t          j        f          rJ|j	        j
                            d|           |j         |j        j
                                         d S d S t          |t          j                  rS|j	        j
                            d|           |j        -|j	        j
        |j                                                  d S d S d S )Nr   r  )r   r  rg   r  applyr  r   r   rD  r+   r  r  r   r  r.  padding_idxr  s      r1   r  z&ChameleonPreTrainedModel._init_weightsW  s   k+fn-- 		?LL-.....BI 677 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r2   N)rF   rG   rH   r   r  base_model_prefixsupports_gradient_checkpointingr  _skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_quantized_cache_supports_cache_class_supports_static_cache!_supports_param_buffer_assignmentr  r  r2   r1   r  r  F  sp        
 #L&*#02MN#4m"D!N $ !(-%? ? ? ? ?r2   r  a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

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

            [What are input IDs?](../glossary#input-ids)
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
            The tensors corresponding to the input images. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`ChameleonImageProcessor.__call__`] for details.
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

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

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

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

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

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

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

            Should always be a [`~cache_utils.Cache`] instance and the model will output the same cache instance.
            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                   4    e Zd ZdZdef fdZd Zd Zdej	        fdZ
 ee           eeeee          	 	 	 	 	 	 	 	 	 	 	 dd
ej        dej	        deej                 deej                 dee         deej	                 dee         dee         dee         dee         deej                 deeef         fd                        Zdej        dej        dej        dedef
dZedej        dededej        dej        dej        defd            Z xZ S )ChameleonModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ChameleonDecoderLayer`]

    Args:
        config: ChameleonConfig
    r   c                 P   t                                                     j        | _        j        | _        t          j        j        j        | j                  | _        t          j
                  | _        | j        j        st          nt          t          j        fdt#          j                  D                       | _        t)          j        j                  | _        t/          j                  | _        d| _        |                                  d S )Nc                 (    g | ]} |          S r  r  )r  r   r   decoder_layers     r1   r  z+ChameleonModel.__init__.<locals>.<listcomp>  s%    ___)]]69--___r2   r   F)r&   r'   pad_token_idr  
vocab_sizer   r.  r.   embed_tokensr  vocabulary_mapvocabulary_mappingr   	swin_normr  r$  r{  r}  num_hidden_layerslayersr#   r  rd  r  	vq_configvqmodelgradient_checkpointing	post_init)r-   r   r  r0   s    `@r1   r'   zChameleonModel.__init__  s      !. +L):F<NPTP`aa"A&BW"X"X59[5Ji--Pim_____uVE]?^?^___
 
 %V%7V=PQQQ	%f&677&+# 	r2   c                     | j         S rx   r  rD   s    r1   get_input_embeddingsz#ChameleonModel.get_input_embeddings  s      r2   c                     || _         d S rx   r
  r-   rL  s     r1   set_input_embeddingsz#ChameleonModel.set_input_embeddings  s    !r2   r  c                     |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   r5   )rC   r  r  r  r  r   )r-   r  ri  r   
image_toksbpe_tokss         r1   get_image_tokenszChameleonModel.get_image_tokens  s[     "'*
<..|<<1j*:::FF==R00r2   )
checkpointoutput_typer  expected_outputN	input_idsr   ro   r  inputs_embedsr   r   output_hidden_statesreturn_dictr   r   c                 r   ||n| j         j        }|	|	n| j         j        }	||n| j         j        }|
|
n| j         j        }
| j        r%| j        r|rt                              d           d}|d u |d uz  rt          d          ||t          d          || 
                    |          }|| j        j        k                                                                    }|j        d         }||k    rt          d| d|           || j        j        k    }|                    |j        |j                  }|                    ||          }||                     |          }|B||                                nd}t-          j        |||j        d         z   |j        	          }||                    d          }|                     |||||          }|}|	rd
nd }|rd
nd }d }| j        D ]p}|	r||fz  }| j        r)| j        r"|                     |j        |||||||          }n ||||||||          }|d         }|r||rdnd         }|r||d         fz  }q|                     |          }|	r||fz  }d }|r|}|
st=          d ||||fD                       S t?          ||||          S )NzX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.Fz:You must specify exactly one of input_ids or inputs_embedszdYou cannot specify both pixel_values and inputs_embeds at the same time, and must specify either oner   z6Image features and image tokens do not match: tokens: z, features r   r^   r  )r   ro   r   r   r   r   r4   c              3      K   | ]}||V  	d S rx   r  )r  re  s     r1   r  z)ChameleonModel.forward.<locals>.<genexpr>Y  s(      ttqfgfsfsfsfsfsttr2   )r  r  r=   
attentions) r   r   r  r   use_return_dictr  r   r   r   r   r  r  r  r4  itemrC   r8   r^   r7   masked_scatterr  get_seq_lengthr)   rY   r   _update_causal_maskr  _gradient_checkpointing_func__call__rd  rB   r   )r-   r  r  r   ro   r  r  r   r   r  r  r   r  n_image_tokens_in_textn_image_featuresspecial_image_maskpast_seen_tokensr   r=   all_hidden_statesall_self_attnsnext_decoder_cacher  layer_outputs
next_caches                            r1   r@   zChameleonModel.forward  s   * 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]& 	4= 	Y 	j   I-t";< 	[YZZZ#(Av   #00>>L&/43J3Y&Y%^%^%`%`%e%e%g%g"+1!4%)999  CMc  C  C  qA  C  C   "+d.E.T!T'??9+;Y_MML!001C\RRI  --i88M!CRC^==???de"\ "2]5H5K"KTaTh  N )33A66L..M>?L]
 

 & #7@BBD0:d!![  	6  	6M# 6!m%55!* t}  $ A A!*! #%"	! 	! !.!#.!-#2&7'#1! ! ! *!,M R%28I3P11q%Q"  6=#3"55		-00   	2-!11
 	,+J 	utt]J@QSa$btttttt&+&+%	
 
 
 	
r2   input_tensorc           
         | j         j        dk    r
|d|v r|S d S ||                                nd}t          |t                    }| j         j        dk    r#|s!|st          j        |||| j                  rd S |j        |j	        }	}|j
        d         }
|r|                                }n/t          |t          j                  r|j
        d         n||
z   dz   }|                     ||
|||	||j
        d                   }| j         j        dk    rB|@|j	        j        d	k    r0|s.t          j        |          j        }t          j        ||          }|S )
Nr  r   r   r  )r  past_key_values_lengthis_trainingr   r5   )sequence_lengthtarget_lengthr7   r^   r   ri  r  )r   r  r!  rg   r   r   _ignore_causal_mask_sdpar   r7   r^   rC   get_max_cache_shaper)   r   5_prepare_4d_causal_attention_mask_with_cache_positionrf   finfomin_unmask_unattended)r-   r   r.  r   r  r   r(  using_static_cacher7   r^   r2  r3  r   	min_dtypes                 r1   r"  z"ChameleonModel._update_causal_maskc  s    ;+/BBB)c^.C.C%%4
 @O?Z?99;;;`a'EE ;+v55>P5Yj5%>*'7 M	    t$*L,?v&,Q/ 	+??AAMM nel;;<$R((%7!;  PP+')#)!, Q 
 
 K,66*%*f44% 5 E**.I0CKQZ[[Kr2   r2  r3  r7   r^   ri  c                    | |                                  dk    r| }n+t          j        |          j        }	t          j        ||f|	||          }|dk    rt          j        |d          }|t          j        ||          |                    dd          k    z  }|ddddddf                             |ddd          }| |	                                }| j
        d         }
|ddddddd|
f         | ddddddf         z   }|dk    }|ddddddd|
f                             ||	          |ddddddd|
f<   |S )	a  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to plcae the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuer7   r^   r   )diagonalr  r5   r   )rV   r)   r7  r8  fulltriurY   r   re   clonerC   masked_fill)r   r2  r3  r7   r^   r   ri  r   r   r;  mask_lengthpadding_masks               r1   r6  zDChameleonModel._prepare_4d_causal_attention_mask_with_cache_position  s   D %.*<*<*>*>!*C*C(KKE**.I* -0Ye\b  K !###jqAAA5<fEEEH^H^_acdHeHeeeK%dD!!!QQQ&67>>z1bRTUUK))//11,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdd+q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 r2   )NNNNNNNNNNN)!rF   rG   rH   rz   r   r'   r  r  r)   r"  r  r   CHAMELEON_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPEr   r   r   r   r   r   r   r@   r"  staticmethodr   r7   r^   r6  rI   rJ   s   @r1   r  r    s       
       $! ! !" " "U->      +*+EFF&+$.	   '+*.1537+/59$(,0/3&*59{
 {
#{
 '{
 !.	{

 u/0{
 "%{
   12{
 D>{
 $D>{
 'tn{
 d^{
 !!12{
 
u--	.{
 {
 {
  GF{
|?? l? 	?
 ?  ? ? ? ?B 555 5 {	5
 5 5 5 5 5 \5 5 5 5 5r2   r  zXChameleon 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d Z	d Z
 ee           eee	          	 	 	 	 	 	 	 	 	 	 	 	 ddej        d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ef         fd                        Z	 	 	 	 	 	 	 ddZ xZS )!ChameleonForConditionalGenerationzlm_head.weightc                     t                                          |           t          |          | _        |j        | _        t          j        |j        |j        d          | _        | 	                                 d S )NFr   )
r&   r'   r  r  r  r   r   r.   lm_headr  r   s     r1   r'   z*ChameleonForConditionalGeneration.__init__  sj       #F++
 +y!3V5FUSSS 	r2   c                     | j         j        S rx   r  r  rD   s    r1   r  z6ChameleonForConditionalGeneration.get_input_embeddings  s    z&&r2   c                     || j         _        d S rx   rP  r  s     r1   r  z6ChameleonForConditionalGeneration.set_input_embeddings  s    "'
r2   c                     | j         S rx   rN  rD   s    r1   get_output_embeddingsz7ChameleonForConditionalGeneration.get_output_embeddings  s
    |r2   c                     || _         d S rx   rS  )r-   new_embeddingss     r1   set_output_embeddingsz7ChameleonForConditionalGeneration.set_output_embeddings  s    %r2   c                     || _         d S rx   r  )r-   decoders     r1   set_decoderz-ChameleonForConditionalGeneration.set_decoder  s    


r2   c                     | j         S rx   rY  rD   s    r1   get_decoderz-ChameleonForConditionalGeneration.get_decoder  s
    zr2   )r  r  Nr  r  r   ro   r  r  labelsr   r   r  r  r   r   c                 H   |	|	n| j         j        }	|
|
n| j         j        }
||n| j         j        }|                     ||||||||	|
||          }|d         }|                     |          }| j        j        j        }t          j	        |j
                  j        |dddd|f<   d}||                                }|dddddf                                         }|dddf                                         }t                      }|                    d| j         j                  }|                    d          }|                    |j                  } |||          }|s|f|dd         z   }||f|z   n|S t'          |||j        |j        |j                  S )a  
        Args:
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Returns:

        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)r  r  r   ro   r  r  r   r   r  r  r   r   .r5   r   )r<  logitsr  r=   r  )r   r   r  r  r  rN  r  r  r)   r7  r7   r8  r[   r   r   r   r  r8   r^   r   r  r=   r  )r-   r  r  r   ro   r  r  r^  r   r   r  r  r   r   r=   r`  r  r<  shift_logitsshift_labelsloss_fctoutputs                         r1   r@   z)ChameleonForConditionalGeneration.forward   s   \ 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B] **%)%+'/!5#)  
 
  
m,, z4A%*[%>%>%Bqqq!!!\!"\\^^F!#ssAAA+.99;;L!#qrr'?5577L'))H',,R1GHHL',,R00L'??<+>??L8L,77D 	DY,F'+'7D7V##VC%#3!/)
 
 
 	
r2   Tc	                    |E||d d |j         d          d f         }n(|j         d         |j         d         k    r|d d |f         }|b|`|                                                    d          dz
  }|                    |dk    d           |r|d d |j         d          d f         }||d         dk    rd|i}
nd|                                i}
|d         dk    r||
d<   |
                    |||||d           |
S )Nr   r   r5   r  r  r  )ro   r   r  r   r   )rC   longcumsummasked_fill_r   r   )r-   r  r  r  r   r  r   ro   r   r   model_inputss              r1   prepare_inputs_for_generationz?ChameleonForConditionalGeneration.prepare_inputs_for_generatione  sg   " &(%aaa.*>q*A)A)C)C&CD		#~';A'>>>%aaa&78	%,*>)..0077;;a?L%%n&91=== F+AAA	0B/B/D/D,DE $):a)?)?+];LL')=)=)?)?@L!!! ,8L( ,"0#2&"0 	
 	
 	
 r2   )NNNNNNNNNNNN)NNNNNNT)rF   rG   rH   _tied_weights_keysr'   r  r  rT  rW  r[  r]  r   rF  r   r   rH  r)   r   r"  r   r   r   r   r   r   r@   rj  rI   rJ   s   @r1   rL  rL    s       
 ++    ' ' '( ( (  & & &     +*+EFF+AP_``` '+*.1537+/59-1$(,0/3&*59a
 a
#a
 'a
 !.	a

 u/0a
 "%a
   12a
 )*a
 D>a
 $D>a
 'tna
 d^a
 !!12a
 
u,,	-a
 a
 a
 a` GFa
L 2 2 2 2 2 2 2 2r2   rL  r  )Zrz   r   	functoolsr   typingr   r   r   r)   torch.nn.functionalr   r   r   torch.utils.checkpointtorch.nnr   activationsr
   cache_utilsr   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_outputsr   r   modeling_utilsr   pytorch_utilsr   utilsr   r   r   r   r   r   r   configuration_chameleonr   r   flash_attn.bert_paddingr   r   r    
get_loggerrF   r   rH  rG  rI  _SEQ_CLASS_EXPECTED_LOSS_SEQ_CLASS_EXPECTED_OUTPUTr  r#   r~  rL   rv   r|   r   r   r   	LayerNormr   r   r   r   r   r   r  r  r  r$  r(  r>  rN  rb  rn  CHAMELEON_VQ_START_DOCSTRINGr  r  CHAMELEON_START_DOCSTRINGr  rF  r  rL  r  r2   r1   <module>r     s@      % % % % % % ) ) ) ) ) ) ) ) ) )                     % % % % % % ! ! ! ! ! ! - - - - - - - - ) ) ) ) ) ) > > > > > > F F F F F F        . - - - - - 1 1 1 1 1 1                  K J J J J J J J  QPPPPPPPPPP 
	H	%	%#) %  ( J J J J Jry J J J(   , - - -
< < < < <ry < < <>    ,D       0H   (( ( (   8    29   "       &	UU\ 	U# 	U%, 	U 	U 	U 	UB9 B9 B9 B9 B9 B9 B9 B9Nr9 r9 r9 r9 r91 r9 r9 r9jZ1 Z1 Z1 Z1 Z1/ Z1 Z1 Z1|  1"  H H H H HBI H H HVF F F F F	 F F FR-> -> -> -> ->BI -> -> ->`	 	 	 	 	") 	 	 	)( )( )( )( )(ry )( )( )(X &  &  &  &  &RY  &  &  &F^! ^! ^! ^! ^!BI ^! ^! ^!B  "  ! ( ( ( ( (_ ( ( (@,% ,% ,% ,% ,% ,% ,% ,%^ " ] ? ? ? ? ? ? ?	 ?6B J ] m m m m m- m m	 m`	 ^ u u u u u(@/ u u	 u u ur2   