Ë
    S^(h- ã                   ó  — 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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*m+Z+ ddl,m-Z-m.Z.  e(«       rddl/m0Z0 ddl1m2Z2  e*jf                  e4«      Z5dZ6dZ7g d¢Z8dZ9dZ: G d„ de
jv                  «      Z< e#jz                  e<«        G d„ de
jv                  «      Z> G d„ de>«      Z? G d „ d!e>«      Z@d"„ ZAdRd#„ZB G d$„ d%e
jv                  «      ZC G d&„ d'e
jˆ                  «      ZEd(ejŒ                  d)eGd*ejŒ                  fd+„ZH G d,„ d-e
jv                  «      ZI G d.„ d/eI«      ZJ G d0„ d1eI«      ZKeIeJeKd2œZL G d3„ d4e
jv                  «      ZM G d5„ d6e
jv                  «      ZN G d7„ d8e
jv                  «      ZO G d9„ d:e
jv                  «      ZP G d;„ d<e
jv                  «      ZQ G d=„ d>e
jv                  «      ZR G d?„ d@e
jv                  «      ZS G dA„ dB«      ZTdCZU e&dDeU«       G dE„ dFe!«      «       ZVdGZW e&dHeW«       G dI„ dJeV«      «       ZXdKZY e&dDeU«       G dL„ dMeV«      «       ZZ e&dNeU«       G dO„ dPeVe«      «       Z[g dQ¢Z\y)SzPyTorch Chameleon model.é    N)Úcached_property)ÚOptionalÚTupleÚUnion)Únn)ÚCrossEntropyLossé   )ÚACT2FN)ÚCacheÚDynamicCacheÚStaticCache)ÚGenerationMixin)ÚAttentionMaskConverter)Ú_flash_attention_forwardÚ!flash_attn_supports_top_left_mask)ÚBaseModelOutputWithPastÚCausalLMOutputWithPast)ÚPreTrainedModel)ÚALL_LAYERNORM_LAYERS)Úadd_code_sample_docstringsÚadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚis_torch_flex_attn_availableÚis_torchdynamo_compilingÚloggingÚreplace_return_docstringsé   )ÚChameleonConfigÚChameleonVQVAEConfig)Ú	BlockMask)Úmake_flex_block_causal_maskr   zmeta/chameleon-7b)r   é   i   g{®Gázð?z	'LABEL_0'c                   ó,   ‡ — e Zd Zdˆ fd„	Zd„ Zd„ Zˆ xZS )ÚChameleonRMSNormc                 óŠ   •— t         ‰| �  «        t        j                  t	        j
                  |«      «      | _        || _        y)z?
        ChameleonRMSNorm is equivalent to T5LayerNorm
        N)ÚsuperÚ__init__r   Ú	ParameterÚtorchÚonesÚweightÚvariance_epsilon)ÚselfÚhidden_sizeÚepsÚ	__class__s      €ún/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/chameleon/modeling_chameleon.pyr'   zChameleonRMSNorm.__init__C   s1   ø€ ô 	‰ÑÔÜ—l‘l¤5§:¡:¨kÓ#:Ó;ˆŒØ #ˆÕó    c                 ó"  — |j                   }|j                  t        j                  «      }|j	                  d«      j                  dd¬«      }|t        j                  || j                  z   «      z  }| j                  |j                  |«      z  S )Né   éÿÿÿÿT)Úkeepdim)	ÚdtypeÚtor)   Úfloat32ÚpowÚmeanÚrsqrtr,   r+   )r-   Úhidden_statesÚinput_dtypeÚvariances       r1   ÚforwardzChameleonRMSNorm.forwardK   sy   € Ø#×)Ñ)ˆØ%×(Ñ(¬¯©Ó7ˆØ ×$Ñ$ QÓ'×,Ñ,¨R¸Ð,Ó>ˆØ%¬¯©°H¸t×?TÑ?TÑ4TÓ(UÑUˆØ�{‰{˜]×-Ñ-¨kÓ:Ñ:Ð:r2   c                 ó^   — t        | j                  j                  «      › d| j                  › �S )Nz, eps=)Útupler+   Úshaper,   ©r-   s    r1   Ú
extra_reprzChameleonRMSNorm.extra_reprR   s*   € Ü˜Ÿ™×)Ñ)Ó*Ð+¨6°$×2GÑ2GÐ1HÐIÐIr2   )ç�íµ ÷Æ°>)Ú__name__Ú
__module__Ú__qualname__r'   r@   rE   Ú__classcell__©r0   s   @r1   r$   r$   B   s   ø„ õ$ò;öJr2   r$   c                   óN   ‡ — e Zd Zdˆ fd„	Z ej
                  «       d„ «       Zˆ xZS )ÚChameleonRotaryEmbeddingc                 ój  •— t         ‰| �  «        || _        || _        || _        || _        d| j
                  t        j                  d| j                  dt        j                  ¬«      j                  |t        j                  ¬«      | j                  z  z  z  }| j                  d|d¬«       || _        y )	Nç      ð?r   r4   ©r7   ©Údevicer7   Úinv_freqF©Ú
persistent)r&   r'   Úscaling_factorÚdimÚmax_position_embeddingsÚbaser)   ÚarangeÚint64r8   ÚfloatÚregister_bufferÚmax_seq_len_cached)r-   rW   rX   rY   rR   rV   rS   r0   s          €r1   r'   z!ChameleonRotaryEmbedding.__init__\   sŸ   ø€ Ü‰ÑÔØ,ˆÔØˆŒØ'>ˆÔ$ØˆŒ	ØØ�I‰IÜ—‘˜Q §¡¨!´5·;±;Ô?×BÑBÈ&ÔX]×XcÑXcÐBÓdÐgk×goÑgoÑoñqñ
ˆð 	×Ñ˜Z¨¸eÐÔDà"9ˆÕr2   c                 ó°  — | j                   d d d …d f   j                  «       j                  |j                  d   dd«      }|d d …d d d …f   j                  «       }|j                  j
                  }t        |t        «      r|dk7  r|nd}t        j                  |d¬«      5  |j                  «       |j                  «       z  j                  dd«      }t        j                  ||fd¬	«      }|j                  «       }|j                  «       }	d d d «       j                  |j                  ¬
«      	j                  |j                  ¬
«      fS # 1 sw Y   ŒAxY w)Nr   r5   r   ÚmpsÚcpuF)Údevice_typeÚenabledr4   ©rW   rP   )rS   r\   ÚexpandrC   rR   Ú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.forwardj   s%  € ð !ŸM™M¨$²°4¨-Ñ8×>Ñ>Ó@×GÑGÈ×HZÑHZÐ[\ÑH]Ð_aÐcdÓeÐØ ,ªQ°²a¨ZÑ 8× >Ñ >Ó @Ðð —h‘h—m‘mˆÜ%/°¼SÔ%AÀkÐUZÒFZ‘kÐ`eˆÜ�^‰^¨¸UÔCñ 	Ø&×,Ñ,Ó.Ð1F×1LÑ1LÓ1NÑN×YÑYÐZ[Ð]^Ó_ˆEÜ—)‘)˜U E˜N°Ô3ˆCØ—'‘'“)ˆCØ—'‘'“)ˆC÷		ð
 �v‰v˜AŸG™GˆvÓ$ c§f¡f°1·7±7 fÓ&;Ð;Ð;÷	ð 	ús   Â!A+EÅE)i   i'  NrO   )rG   rH   rI   r'   r)   Úno_gradr@   rJ   rK   s   @r1   rM   rM   [   s$   ø„ õ:ð €U‡]�]ƒ_ñ<ó ô<r2   rM   c                   ó"   ‡ — e Zd ZdZˆ fd„Zˆ xZS )Ú%ChameleonLinearScalingRotaryEmbeddingz_ChameleonRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendevc                 ól   •— |j                  «       | j                  z  }t        ‰| �  ||«      \  }}||fS ©N)r\   rV   r&   r@   )r-   rn   ro   rl   rm   r0   s        €r1   r@   z-ChameleonLinearScalingRotaryEmbedding.forward~   s9   ø€ à#×)Ñ)Ó+¨d×.AÑ.AÑAˆÜ‘7‘? 1 lÓ3‰ˆˆSØ�Cˆxˆr2   ©rG   rH   rI   Ú__doc__r@   rJ   rK   s   @r1   rv   rv   {   s   ø„ Ù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                  kD  r×| j                  | j                  |z  | j                  z  | j                  dz
  z
  | j
                  | j
                  dz
  z  z  z  }d|t        j                  d| j
                  dt         j                  ¬«      j                  |j                  t         j                  ¬«      | j
                  z  z  z  }| j                  d|d¬	«       t        ‰| �5  ||«      \  }}||fS )
Nr   r4   rO   r   rP   rQ   rS   FrT   )r)   ÚmaxrX   rY   rV   rW   rZ   r[   r8   rR   r\   r]   r&   r@   )	r-   rn   ro   Úseq_lenrY   rS   rl   rm   r0   s	           €r1   r@   z1ChameleonDynamicNTKScalingRotaryEmbedding.forwardˆ   s   ø€ ä—)‘)˜LÓ)¨AÑ-ˆØ�T×1Ñ1Ò1Ø—9‘9Ø×$Ñ$ wÑ.°×1MÑ1MÑMÐRV×ReÑReÐhiÑRiÑjØ—(‘(˜dŸh™h¨™lÑ+ñ -ñ -ˆDð ØÜ—L‘L  D§H¡H¨a´u·{±{ÔC×FÑFÈaÏhÉhÔ^c×^iÑ^iÐFÓjÐmq×muÑmuÑuñwñˆHð × Ñ  ¨XÀ%Ð ÔHä‘7‘? 1 lÓ3‰ˆˆSØ�Cˆxˆr2   ry   rK   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ƒ   š   sZ   € à	
ˆ3Ð"�!—'‘'˜"‘+ Ñ"Ð"Ð"Ñ	#€BØ	
ˆ3�—‘˜‘˜qÑ Ñ"Ð"Ñ	#€BÜ�9‰9�r�c˜2�Y BÔ'Ð'r2   c                 óž   — |j                  |«      }|j                  |«      }| |z  t        | «      |z  z   }||z  t        |«      |z  z   }||fS )aÛ  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )Ú	unsqueezerƒ   )ÚqÚkrl   rm   ro   Úunsqueeze_dimÚq_embedÚk_embeds           r1   Úapply_rotary_pos_embr‹   ¢   sY   € ð( �-‰-˜Ó
&€CØ
�-‰-˜Ó
&€CØ�3‰wœ; q›>¨CÑ/Ñ0€GØ�3‰wœ; q›>¨CÑ/Ñ0€GØ�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                     | _        y )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Ñ!9ˆÔÜŸ™ 4×#3Ñ#3°T×5KÑ5KÐRX×RaÑRaÔbˆŒÜ—y‘y ×!1Ñ!1°4×3IÑ3IÐPV×P_ÑP_Ô`ˆŒÜŸ™ 4×#9Ñ#9¸4×;KÑ;KÐRX×RaÑRaÔbˆŒÜ˜V×.Ñ.Ñ/ˆ�r2   c                 óˆ   — | j                  | j                  | j                  |«      «      | j                  |«      z  «      }|S rx   )r—   r™   r•   r–   )r-   rn   r—   s      r1   r@   zChameleonMLP.forwardÊ   s6   € Ø—N‘N 4§;¡;¨t¯~©~¸aÓ/@Ó#AÀDÇLÁLÐQRÃOÑ#SÓTˆ	ØÐr2   ©rG   rH   rI   r'   r@   rJ   rK   s   @r1   r�   r�   ¾   s   ø„ ô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                 óB   •— t        ‰| �  |g|¢­i |¤Ž |d   f| _        y )Nr5   )r&   r'   Únormalized_shape)r-   r.   ÚargsÚkwargsr0   s       €r1   r'   zChameleonLayerNorm.__init__×   s)   ø€ Ü‰Ñ˜Ð6 tÒ6¨vÒ6Ø!,¨R¡Ð 2ˆÕr2   c                 ó†   — t        j                  || j                  d d d¬«      }|| j                  z  | j                  z   }|S )Ngñhãˆµøä>©r/   )ÚFÚ
layer_normr    r+   r�   ©r-   r=   s     r1   r@   zChameleonLayerNorm.forwardÛ   s=   € ÜŸ™ ]°D×4IÑ4IÈ4ÐQUÐ[_Ô`ˆØ%¨¯©Ñ3°d·i±iÑ?ˆØÐr2   )rG   rH   rI   rz   r'   r@   rJ   rK   s   @r1   rž   rž   Ï   s   ø„ ñô3ör2   rž   r=   Ún_repÚreturnc                 óª   — | j                   \  }}}}|dk(  r| S | dd…dd…ddd…dd…f   j                  |||||«      } | j                  |||z  ||«      S )zÔ
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)rC   re   Úreshape)r=   r¨   ÚbatchÚnum_key_value_headsÚslenÚhead_dims         r1   Ú	repeat_kvr°   â   so   € ð
 2?×1DÑ1DÑ.€EÐ  hØ�‚zØÐØ!¢!¢Q¨ªa²Ð"2Ñ3×:Ñ:¸5ÐBUÐW\Ð^bÐdlÓm€MØ× Ñ  Ð(;¸eÑ(CÀTÈ8ÓTÐTr2   c                   ó2  ‡ — e Zd ZdZddedee   fˆ fd„Zd„ Z	 	 	 	 	 	 dde	j                  dee	j                     dee	j                     d	ee   d
ededee	j                     dee	j                  ee	j                     eee	j                        f   fd„Zˆ xZS )ÚChameleonAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr‘   Ú	layer_idxc                 ó†  •— t         ‰| �  «        || _        || _        |€-t        j                  d| j                  j                  › d�«       |j                  | _        |j                  | _	        |j                  | _        | j                  | j                  z  | _        |j                  | _        | j                  | j                  z  | _        |j                  | _        |j                   | _        d| _        |j$                  | _        | j                  | j                  z  | j                  k7  r&t'        d| j                  › d| j                  › d�«      ‚t)        j*                  | j                  | j                  | j                  z  |j,                  ¬«      | _        t)        j*                  | j                  | j                  | j                  z  |j,                  ¬«      | _        t)        j*                  | j                  | j                  | j                  z  |j,                  ¬«      | _        t)        j*                  | j                  | j                  |j,                  ¬«      | _        t7        | j                  | j                  f«      | _        t7        | j                  | j                  f«      | _        | j=                  «        y )NzInstantiating z¹ without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.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   rG   Úattention_dropoutr.   Únum_attention_headsÚ	num_headsr¯   r­   Únum_key_value_groupsrX   Ú
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Ñ!8Ð 9ð :,ð ,ôð "(×!9Ñ!9ˆÔØ!×-Ñ-ˆÔØ×3Ñ3ˆŒØ×(Ñ(¨D¯N©NÑ:ˆŒØ#)×#=Ñ#=ˆÔ Ø$(§N¡N°d×6NÑ6NÑ$NˆÔ!Ø'-×'EÑ'EˆÔ$Ø ×+Ñ+ˆŒØˆŒØ#)×#=Ñ#=ˆÔ à�M‰M˜DŸN™NÑ*¨t×/?Ñ/?Ò?ÜØQÐRV×RbÑRbÐQcØ$ T§^¡^Ð$4°Bð8óð ô
 —i‘i × 0Ñ 0°$·.±.À4Ç=Á=Ñ2PÐW]×WlÑWlÔmˆŒÜ—i‘i × 0Ñ 0°$×2JÑ2JÈTÏ]É]Ñ2ZÐag×avÑavÔwˆŒÜ—i‘i × 0Ñ 0°$×2JÑ2JÈTÏ]É]Ñ2ZÐag×avÑavÔwˆŒÜ—i‘i × 0Ñ 0°$×2BÑ2BÈ×I^ÑI^Ô_ˆŒÜ(¨$¯.©.¸$¿-¹-Ð)HÓIˆŒÜ(¨$×*BÑ*BÀDÇMÁMÐ)RÓSˆŒØ�‰Õr2   c                 óò  — | j                   j                  €2t        | j                  | j                  | j
                  ¬«      | _        y | j                   j                  d   }| j                   j                  d   }|dk(  r3t        | j                  | j                  || j
                  ¬«      | _        y |dk(  r3t        | j                  | j                  || j
                  ¬«      | _        y t        d|› �«      ‚)N)rX   rY   rf   ÚfactorÚlinear)rX   rV   rY   ÚdynamiczUnknown RoPE scaling type )
r‘   Úrope_scalingrM   r¯   rX   r»   Ú
rotary_embrv   r|   r¾   )r-   Úscaling_typerV   s      r1   rÆ   zChameleonAttention._init_rope  sÒ   € Ø�;‰;×#Ñ#Ð+Ü6Ø—‘Ø(,×(DÑ(DØ—_‘_ôˆD�Oð  Ÿ;™;×3Ñ3°FÑ;ˆLØ!Ÿ[™[×5Ñ5°hÑ?ˆNØ˜xÒ'Ü"GØ—M‘MØ,0×,HÑ,HØ#1ØŸ™ô	#�•ð  Ò*Ü"KØ—M‘MØ,0×,HÑ,HØ#1ØŸ™ô	#�•ô !Ð#=¸l¸^Ð!LÓMÐMr2   r=   Úattention_maskro   Úpast_key_valueÚoutput_attentionsÚ	use_cacheÚcache_positionr©   c                 ó(  — |j                  «       \  }	}
}| j                  |«      }| j                  |«      }| j                  |«      }|j	                  d| j
                  | j                  «      }| j                  |«      }|j	                  d| j                  | j                  «      }| j                  |«      }|j	                  |	|
| j
                  | j                  «      j                  dd«      }|j	                  |	|
| j                  | j                  «      j                  dd«      }|j                  |	|
| j                  | j                  «      j                  dd«      }| j                  ||«      \  }}t        ||||«      \  }}|�'|||dœ}|j                  ||| j                  |«      \  }}t!        || j"                  «      }t!        || j"                  «      }t%        j&                  ||j                  dd«      «      t)        j*                  | j                  «      z  }|�#|d d …d d …d d …d |j,                  d   …f   }||z   }t.        j0                  j3                  |dt$        j4                  ¬«      j7                  |j8                  «      }t.        j0                  j;                  || j<                  | j>                  ¬«      }t%        j&                  ||«      }|j                  «       |	| j
                  |
| j                  fk7  r7tA        d	|	| j
                  |
| j                  f› d
|j                  «       › �«      ‚|j                  dd«      jC                  «       }|j	                  |	|
| jD                  «      }| jG                  |«      }|sd }|||fS )Nr5   r   r4   ©rm   rl   rÓ   r	   éþÿÿÿ)rW   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.forward2  s:  € ð &×*Ñ*Ó,‰ˆˆU�Aà—{‘{ =Ó1ˆØ—[‘[ Ó/ˆ
Ø—{‘{ =Ó1ˆà#×+Ñ+¨B°·±ÀÇÁÓNˆØ—{‘{ <Ó0ˆà×'Ñ'¨¨D×,DÑ,DÀdÇmÁmÓTˆ
Ø—[‘[ Ó,ˆ
à#×+Ñ+¨C°¸¿¹ÈÏÉÓV×`Ñ`ÐabÐdeÓfˆØ×'Ñ'¨¨U°D×4LÑ4LÈdÏmÉmÓ\×fÑfÐghÐjkÓlˆ
Ø#×(Ñ(¨¨e°T×5MÑ5MÈtÏ}É}Ó]×gÑgÐhiÐklÓmˆà—?‘? <°Ó>‰ˆˆSÜ#7¸ÀjÐRUÐWZÓ#[Ñ ˆ�jàÐ%à#&¨sÀnÑUˆLØ'5×'<Ñ'<¸ZÈÐW[×WeÑWeÐgsÓ'tÑ$ˆJ˜ä˜z¨4×+DÑ+DÓEˆ
Ü  ¨t×/HÑ/HÓIˆä—|‘| L°*×2FÑ2FÀqÈ!Ó2LÓMÔPT×PYÑPYÐZ^×ZgÑZgÓPhÑhˆàÐ%Ø(ªªAªqÐ2H°J×4DÑ4DÀRÑ4HÐ2HÐ)HÑIˆKØ'¨+Ñ5ˆLô —}‘}×,Ñ,¨\¸rÌÏÉÐ,ÓW×ZÑZÐ[g×[mÑ[mÓnˆÜ—}‘}×,Ñ,¨\¸T×=SÑ=SÐ^b×^kÑ^kÐ,ÓlˆÜ—l‘l <°Ó>ˆà×ÑÓ # t§~¡~°u¸d¿m¹mÐ!LÒLÜØ2°C¸¿¹ÈÐPT×P]ÑP]Ð3^Ð2_ð `Ø×$Ñ$Ó&Ð'ð)óð ð
 "×+Ñ+¨A¨qÓ1×<Ñ<Ó>ˆØ!×)Ñ)¨#¨u°d×6FÑ6FÓGˆØ—k‘k +Ó.ˆá ØˆLà˜L¨.Ð8Ð8r2   rx   ©NNNFFN)rG   rH   rI   rz   r   r   Úintr'   rÆ   r)   ÚTensorÚ
LongTensorr   Úboolr   r@   rJ   rK   s   @r1   r²   r²   î   sÙ   ø„ ÙGñ"˜ð "¸8ÀC¹=õ "òLNð< 26Ø37Ø*.Ø"'ØØ59ñ>9à—|‘|ð>9ð ! §¡Ñ.ð>9ð ˜u×/Ñ/Ñ0ð	>9ð
 ! ™ð>9ð  ð>9ð ð>9ð ! ×!1Ñ!1Ñ2ð>9ð 
ˆu�|‰|˜X e§l¡lÑ3°X¸eÀEÇLÁLÑ>QÑ5RÐRÑ	S÷>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        ‰| �  |i |¤Ž t        «       | _        y rx   )r&   r'   r   Ú_flash_attn_uses_top_left_mask)r-   r¡   r¢   r0   s      €r1   r'   z!ChameleonFlashAttention2.__init__|  s#   ø€ Ü‰Ñ˜$Ð) &Ò)ô
 /PÓ.QˆÕ+r2   r=   rÏ   ro   rÐ   rÑ   rÒ   rÓ   r©   c                 óÖ  — t        |t        «      rt        d«      ‚d}|j                  «       \  }	}
}| j	                  |«      }| j                  |«      }| j                  |«      }|j                  d| j                  | j                  «      }| j                  |«      }|j                  d| j                  | j                  «      }| j                  |«      }|j                  |	|
| j                  | j                  «      j                  dd«      }|j                  |	|
| j                  | j                  «      j                  dd«      }|j                  |	|
| j                  | j                  «      j                  dd«      }| j                  ||«      \  }}t!        ||||«      \  }}|�'|||dœ}|j#                  ||| j$                  |«      \  }}|j                  dd«      }|j                  dd«      }|j                  dd«      }| j&                  r| j(                  nd}|j*                  }|t,        j.                  k(  rÂt-        j0                  «       rt-        j2                  «       }nMt5        | j6                  d«      r| j6                  j8                  }n | j                  j:                  j*                  }t<        j?                  d	|› d
�«       |jA                  |«      }|jA                  |«      }|jA                  |«      }tC        |||||
|tE        | dd «      | jF                  | jH                  ¬«	      }|j                  |	|
d«      jK                  «       }| jM                  |«      }|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_dtypez¾The 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  € ô �n¤kÔ2Üð}óð ð
 "Ðà%×*Ñ*Ó,‰ˆˆU�Aà—{‘{ =Ó1ˆØ—[‘[ Ó/ˆ
Ø—{‘{ =Ó1ˆà#×+Ñ+¨B°·±ÀÇÁÓNˆØ—{‘{ <Ó0ˆà×'Ñ'¨¨D×,DÑ,DÀdÇmÁmÓTˆ
Ø—[‘[ Ó,ˆ
ð
 $×(Ñ(¨¨e°T·^±^ÀTÇ]Á]ÓS×]Ñ]Ð^_ÐabÓcˆØ—_‘_ S¨%°×1IÑ1IÈ4Ï=É=ÓY×cÑcÐdeÐghÓiˆ
Ø#×(Ñ(¨¨e°T×5MÑ5MÈtÏ}É}Ó]×gÑgÐhiÐklÓmˆà—?‘? <°Ó>‰ˆˆSÜ#7¸ÀjÐRUÐWZÓ#[Ñ ˆ�jàÐ%à#&¨sÀnÑUˆLØ'5×'<Ñ'<¸ZÈÐW[×WeÑWeÐgsÓ'tÑ$ˆJ˜ð $×-Ñ-¨a°Ó3ˆØ×)Ñ)¨!¨QÓ/ˆ
Ø#×-Ñ-¨a°Ó3ˆà15·²�t×-Ò-ÀCˆð #×(Ñ(ˆØœ%Ÿ-™-Ò'Ü×(Ñ(Ô*Ü$×;Ñ;Ó=‘ä˜Ÿ™Ð&?Ô@Ø#Ÿ{™{×BÑB‘à#Ÿ{™{×1Ñ1×7Ñ7�ä×Ñðà �> ð$ôð (Ÿ?™?¨<Ó8ˆLØ#Ÿ™ |Ó4ˆJØ'Ÿ?™?¨<Ó8ˆLä.ØØØØØØ Ü" 4Ð)9¸4Ó@Ø"×AÑAØ—n‘nô

ˆð "×)Ñ)¨#¨u°bÓ9×DÑDÓFˆØ—k‘k +Ó.ˆá ØˆLà˜L¨.Ð8Ð8r2   rí   )rG   rH   rI   rz   r'   r)   rï   r   rð   r   rñ   r   r@   rJ   rK   s   @r1   ró   ró   u  sÎ   ø„ ñôRð 6:Ø37Ø*.Ø"'ØØ59ñb9à—|‘|ðb9ð ! ×!1Ñ!1Ñ2ðb9ð ˜u×/Ñ/Ñ0ð	b9ð
 ! ™ðb9ð  ðb9ð ðb9ð ! ×!1Ñ!1Ñ2ðb9ð 
ˆu�|‰|˜X e§l¡lÑ3°X¸eÀEÇLÁLÑ>QÑ5RÐRÑ	S÷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.
    r=   rÏ   ro   rÐ   rÑ   rÒ   rÓ   r©   c           	      ó<  •— |r+t         j                  d«       t        ‰| �  |||||||¬«      S |j	                  «       \  }}	}
| j                  |«      }| j                  |«      }| j                  |«      }|j                  d| j                  | j                  «      }| j                  |«      }|j                  d| j                  | j                  «      }| j                  |«      }|j                  ||	| j                  | j                  «      j                  dd«      }|j                  ||	| j                  | j                  «      j                  dd«      }|j                  ||	| j                  | j                  «      j                  dd«      }| j!                  ||«      \  }}t#        ||||d «      \  }}|�'|||dœ}|j%                  ||| j&                  |«      \  }}t)        || j*                  «      }t)        || j*                  «      }|}|� |�|d d …d d …d d …d |j,                  d   …f   }|j.                  j0                  dk(  r2|�0|j3                  «       }|j3                  «       }|j3                  «       }|€|	dkD  rd	nd
}t4        j6                  j8                  j;                  ||||| j<                  r| j>                  nd|¬«      }|j                  dd«      j3                  «       }|j                  ||	| j@                  «      }| jC                  |«      }|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   rR   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ò  s  ø€ ñ ä×Ñð[ôô ‘7‘?Ø+Ø-Ø)Ø-Ø"3Ø#Ø-ð #ó ð ð &×*Ñ*Ó,‰ˆˆU�Aà—{‘{ =Ó1ˆØ—[‘[ Ó/ˆ
Ø—{‘{ =Ó1ˆà#×+Ñ+¨B°·±ÀÇÁÓNˆØ—{‘{ <Ó0ˆà×'Ñ'¨¨D×,DÑ,DÀdÇmÁmÓTˆ
Ø—[‘[ Ó,ˆ
à#×+Ñ+¨C°¸¿¹ÈÏÉÓV×`Ñ`ÐabÐdeÓfˆØ×'Ñ'¨¨U°D×4LÑ4LÈdÏmÉmÓ\×fÑfÐghÐjkÓlˆ
Ø#×(Ñ(¨¨e°T×5MÑ5MÈtÏ}É}Ó]×gÑgÐhiÐklÓmˆà—?‘? <°Ó>‰ˆˆSÜ#7¸ÀjÐRUÐWZÐ\`Ó#aÑ ˆ�jàÐ%à#&¨sÀnÑUˆLØ'5×'<Ñ'<¸ZÈÐW[×WeÑWeÐgsÓ'tÑ$ˆJ˜ä˜z¨4×+DÑ+DÓEˆ
Ü  ¨t×/HÑ/HÓIˆà$ˆØÐ%¨.Ð*DØ%¢aªªAÐ/E°×1AÑ1AÀ"Ñ1EÐ/EÐ&EÑFˆKð ×Ñ×#Ñ# vÒ-°+Ð2IØ'×2Ñ2Ó4ˆLØ#×.Ñ.Ó0ˆJØ'×2Ñ2Ó4ˆLð (Ð/°E¸A²I‘DÀ5ˆ	ä—h‘h×)Ñ)×FÑFØØØØ!Ø04·²�d×,Ò,À3Øð Gó 
ˆð "×+Ñ+¨A¨qÓ1×<Ñ<Ó>ˆØ!×&Ñ& s¨E°4×3CÑ3CÓDˆà—k‘k +Ó.ˆà˜D .Ð0Ð0r2   rí   )rG   rH   rI   rz   r)   rï   r   rð   r   rñ   r   r@   rJ   rK   s   @r1   r  r  ê  sÌ   ø„ ñð 26Ø37Ø*.Ø"'ØØ59ñR1à—|‘|ðR1ð ! §¡Ñ.ðR1ð ˜u×/Ñ/Ñ0ð	R1ð
 ! ™ðR1ð  ðR1ð ðR1ð ! ×!1Ñ!1Ñ2ðR1ð 
ˆu�|‰|˜X e§l¡lÑ3°X¸eÀEÇLÁLÑ>QÑ5RÐRÑ	S÷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                 ó:  •— t         ‰| �  «        |j                  | _        t        |j                     ||¬«      | _        t        |«      | _        t        |j                  |j                  ¬«      | _
        t        |j                  |j                  ¬«      | _        y ©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__Q  óz   ø€ Ü‰ÑÔØ!×-Ñ-ˆÔä4°V×5PÑ5PÑQÐY_ÐktÔuˆŒä Ó'ˆŒÜ/°×0BÑ0BÈ×H[ÑH[Ô\ˆÔÜ(8¸×9KÑ9KÐQW×QdÑQdÔ(eˆÕ%r2   r=   rÏ   ro   rÐ   rÑ   rÒ   rÓ   r©   c                 óê   — |}	| j                  |«      } | j                  d|||||||dœ|¤Ž\  }}
}|	|z   }|}	| j                  |«      }| j                  |«      }|	|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.forward[  sÃ   € ð< !ˆà×,Ñ,¨]Ó;ˆð ?M¸d¿n¹nð 	?
Ø'Ø)Ø%Ø)Ø/ØØ)ñ	?
ð ñ	?
Ñ;ˆÐ(Ð*;ð ! =Ñ0ˆð !ˆØ×5Ñ5°mÓDˆØŸ™ Ó/ˆØ  =Ñ0ˆà Ð"ˆáØÐ)Ð+Ñ+ˆGáØÐ)Ð+Ñ+ˆGàˆr2   rí   ©rG   rH   rI   r   rî   r'   r)   rï   r   rð   r   rñ   r   ÚFloatTensorr@   rJ   rK   s   @r1   r  r  P  sÚ   ø„ ðf˜ð f¸3õ fð 26Ø37Ø*.Ø,1Ø$)Ø59ñ=à—|‘|ð=ð ! §¡Ñ.ð=ð ˜u×/Ñ/Ñ0ð	=ð
 ! ™ð=ð $ D™>ð=ð ˜D‘>ð=ð ! ×!1Ñ!1Ñ2ð=ð 
ˆu× Ñ  (¨5°×1BÑ1BÀE×DUÑDUÐ1UÑ+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                 ó:  •— t         ‰| �  «        |j                  | _        t        |j                     ||¬«      | _        t        |«      | _        t        |j                  |j                  ¬«      | _
        t        |j                  |j                  ¬«      | _        y r  r  rÇ   s      €r1   r'   z"ChameleonSwinDecoderLayer.__init__œ  r  r2   r=   rÏ   ro   rÐ   rÑ   rÒ   rÓ   r©   c                 óê   — |}	 | j                   d|||||||dœ|¤Ž\  }}
}| j                  |«      }|	|z   }|}	| j                  |«      }| j                  |«      }|	|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¸d¿n¹nð 	?
Ø'Ø)Ø%Ø)Ø/ØØ)ñ	?
ð ñ	?
Ñ;ˆÐ(Ð*;ð ×,Ñ,¨]Ó;ˆØ  =Ñ0ˆà ˆØŸ™ Ó/ˆØ×5Ñ5°mÓDˆØ  =Ñ0ˆØ Ð"ˆáØÐ)Ð+Ñ+ˆGáØÐ)Ð+Ñ+ˆGàˆr2   rí   r!  rK   s   @r1   r$  r$  ›  sÚ   ø„ ðf˜ð f¸3õ fð 26Ø37Ø*.Ø,1Ø$)Ø59ñ;à—|‘|ð;ð ! §¡Ñ.ð;ð ˜u×/Ñ/Ñ0ð	;ð
 ! ™ð;ð $ D™>ð;ð ˜D‘>ð;ð ! ×!1Ñ!1Ñ2ð;ð 
ˆu× Ñ  (¨5°×1BÑ1BÀE×DUÑDUÐ1UÑ+VÑ"WÐWÑ	X÷;r2   r$  c                   óB   ‡ — e Zd ZdZˆ fd„Zdej                  fd„Zˆ xZS )ÚChameleonVQVAEVectorQuantizeraâ  
    A module for vector quantization using learned embedding vectors.

    This module implements the quantization process similar to te one described in
    the VQ-VAE (Vector Quantized Variational AutoEncoder) paper. It quantizes continuous
    input vectors into discrete codebook vectors, which are learned during training.
    Current implementation improves over previous ones by avoiding costly matrix multiplications
    and allowing for post-hoc remapping of indices.
    c                 ó
  •— t         ‰| �  «        |j                  | _        |j                  | _        t        |dd«      | _        t        j                  | j                  | j                  «      | _	        | j                  | _
        y )NÚbetag      Ð?)r&   r'   Únum_embeddingsÚ	embed_dimÚembedding_dimrÿ   r*  r   Ú	EmbeddingÚ	embeddingÚre_embedrš   s     €r1   r'   z&ChameleonVQVAEVectorQuantizer.__init__ï  se   ø€ Ü‰ÑÔØ$×3Ñ3ˆÔØ#×-Ñ-ˆÔÜ˜F F¨DÓ1ˆŒ	äŸ™ d×&9Ñ&9¸4×;MÑ;MÓNˆŒØ×+Ñ+ˆ�r2   Úhidden_statec           
      óL  — |j                  dddd«      j                  «       }|j                  d| j                  «      }t	        j
                  |dz  dd¬«      t	        j
                  | j                  j                  dz  d¬«      z   dt	        j                  d	|| j                  j                  j                  dd«      «      z  z
  }t	        j                  |d¬«      }| j                  |«      j                  |j                  «      }t	        j                  |j                  «       |z
  dz  «      | j                  t	        j                  ||j                  «       z
  dz  «      z  z   }|||z
  j                  «       z   }|j                  dddd«      j                  «       }|||fS )
Nr   r4   r	   r   r5   T)rW   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ˆ  € Ø#×+Ñ+¨A¨q°!°QÓ7×BÑBÓDˆØ!-×!2Ñ!2°2°t×7IÑ7IÓ!JÐô �I‰IÐ,¨aÑ/°QÀÔEÜ�i‰i˜Ÿ™×-Ñ-¨qÑ0°aÔ8ñ9à”%—,‘,˜{Ð,BÀDÇNÁN×DYÑDY×DcÑDcÐdeÐghÓDiÓjÑjñkð 	ô  %Ÿ|™|¨I¸1Ô=ÐØ!Ÿ^™^Ð,@ÓA×FÑFÀ|×GYÑGYÓZÐô �z‰zÐ-×4Ñ4Ó6¸ÑEÈ!ÑKÓLÈtÏyÉyÔ[`×[eÑ[eØ ,×"5Ñ"5Ó"7Ñ7¸AÑ=ó\
ñ P
ñ 
ˆð
 *Ð-?À,Ñ-N×,VÑ,VÓ,XÑXÐð 0×7Ñ7¸¸1¸aÀÓC×NÑNÓPÐà! 4Ð)=Ð=Ð=r2   )	rG   rH   rI   rz   r'   r)   rï   r@   rJ   rK   s   @r1   r(  r(  ä  s   ø„ ñô,ð> E§L¡L÷ >r2   r(  c                   ó$   ‡ — e Zd Zˆ fd„Zd„ Zˆ xZS )Ú#ChameleonVQVAEEncoderConvDownsamplec                 ó`   •— t         ‰| �  «        t        j                  ||ddd¬«      | _        y )Nr	   r4   r   ©Úkernel_sizeÚstrideÚpadding)r&   r'   r   ÚConv2dÚconv©r-   Úin_channelsr0   s     €r1   r'   z,ChameleonVQVAEEncoderConvDownsample.__init__  s'   ø€ Ü‰ÑÔÜ—I‘I˜k¨;ÀAÈaÐYZÔ[ˆ�	r2   c                 óZ   — t        j                  |ddd¬«      }| j                  |«      }|S )N)r   r   r   r   Úconstantr   )ÚpadÚmodeÚvalue)r¥   rJ  rE  r§   s     r1   r@   z+ChameleonVQVAEEncoderConvDownsample.forward  s+   € äŸ™˜m°ÀJÐVWÔXˆØŸ	™	 -Ó0ˆØÐr2   rœ   rK   s   @r1   r>  r>    s   ø„ ô\ör2   r>  c                   ó*   ‡ — e Zd Z	 	 dˆ fd„	Zd„ Zˆ xZS )Ú ChameleonVQVAEEncoderResnetBlockc                 óæ  •— t         ‰| �  «        || _        |€|n|| _        || _        t
        j                  j                  d|dd¬«      | _        t
        j                  j                  ||ddd¬«      | _
        t
        j                  j                  d|dd¬«      | _        t
        j                  j                  |j                  «      | _        t
        j                  j                  ||ddd¬«      | _        | j                  | j                  k7  r`| j                  r*t
        j                  j                  ||ddd¬«      | _        y t
        j                  j                  ||ddd¬«      | _        y y )	Né    rF   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__!  s1  ø€ ô 	‰ÑÔØ&ˆÔØ+7Ð+?™KÀ\ˆÔØ!.ˆÔä—X‘X×'Ñ'°2ÀKÐUYÐbfÐ'ÓgˆŒ
Ü—X‘X—_‘_ [°,ÈAÐVWÐab�_ÓcˆŒ
Ü—X‘X×'Ñ'°2ÀLÐVZÐcgÐ'ÓhˆŒ
Ü—x‘x×'Ñ'¨¯©Ó7ˆŒÜ—X‘X—_‘_ \°<ÈQÐWXÐbc�_ÓdˆŒ
Ø×Ñ˜t×0Ñ0Ò0Ø×%Ò%Ü%*§X¡X§_¡_°[À,Ð\]ÐfgÐqr _Ó%s�Õ"ä$)§H¡H§O¡O°KÀÐ[\ÐefÐpq OÓ$r�Õ!ð	 1r2   c                 ó²  — |}| j                  |«      }|t        j                  |«      z  }| j                  |«      }| j	                  |«      }|t        j                  |«      z  }| j                  |«      }| j                  |«      }| j                  | j                  k7  r3| j                  r| j                  |«      }||z   S | j                  |«      }||z   S rx   )rX  r)   ÚsigmoidrY  rZ  rá   r\  rG  rU  rV  r]  r^  )r-   r=   r  s      r1   r@   z(ChameleonVQVAEEncoderResnetBlock.forward8  sÊ   € Ø ˆØŸ
™
 =Ó1ˆØœŸ™ }Ó5Ñ5ˆØŸ
™
 =Ó1ˆàŸ
™
 =Ó1ˆØœŸ™ }Ó5Ñ5ˆØŸ™ ]Ó3ˆØŸ
™
 =Ó1ˆà×Ñ˜t×0Ñ0Ò0Ø×%Ò%Ø×-Ñ-¨hÓ7�ð ˜-Ñ'Ð'ð  ×,Ñ,¨XÓ6�à˜-Ñ'Ð'r2   )NFrœ   rK   s   @r1   rN  rN     s   ø„ ð
 Øõsö.(r2   rN  c                   ó$   ‡ — e Zd Zˆ fd„Zd„ Zˆ xZS )ÚChameleonVQVAEEncoderAttnBlockc                 óÈ  •— t         ‰| �  «        || _        t        j                  j                  d|dd¬«      | _        t        j                  j                  ||ddd¬«      | _        t        j                  j                  ||ddd¬«      | _	        t        j                  j                  ||ddd¬«      | _
        t        j                  j                  ||ddd¬«      | _        y )NrP  rF   TrQ  r   r   r@  )r&   r'   rG  r)   r   rW  ÚnormrD  r†   r‡   ÚvÚproj_outrF  s     €r1   r'   z'ChameleonVQVAEEncoderAttnBlock.__init__M  s·   ø€ Ü‰ÑÔØ&ˆÔä—H‘H×&Ñ&°"À;ÐTXÐaeÐ&ÓfˆŒ	Ü—‘—‘ ¨kÀqÐQRÐ\]�Ó^ˆŒÜ—‘—‘ ¨kÀqÐQRÐ\]�Ó^ˆŒÜ—‘—‘ ¨kÀqÐQRÐ\]�Ó^ˆŒÜŸ™Ÿ™¨°[ÈaÐXYÐcd˜Óeˆ�r2   c                 ót  — |}| j                  |«      }| j                  |«      }| j                  |«      }| j                  |«      }|j                  \  }}}}	|j                  ||||	z  «      j                  ddd«      }|j                  ||||	z  «      }t        j                  ||«      }
|
t        |«      dz  z  }
t        j                  |
d¬«      }
|j                  ||||	z  «      }|
j                  ddd«      }
t        j                  ||
«      j                  ||||	«      }| j                  |«      }||z   S )Nr   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.forwardW  s5  € Ø ˆØŸ	™	 -Ó0ˆØ—v‘v˜mÓ,ˆØ—V‘V˜MÓ*ˆ
Ø—v‘v˜mÓ,ˆð /;×.@Ñ.@Ñ+ˆ
�H˜f eØ#×+Ñ+¨J¸À&È5Á.ÓQ×YÑYÐZ[Ð]^Ð`aÓbˆØ×'Ñ'¨
°H¸fÀu¹nÓMˆ
Ü—y‘y ¨zÓ:ˆØ#¤s¨8£}¸Ñ'>Ñ?ˆÜ—y‘y °1Ô5ˆð $×+Ñ+¨J¸À&È5Á.ÓQˆØ#×+Ñ+¨A¨q°!Ó4ˆÜ—i‘i ¨lÓ;×CÑCÀJÐPXÐZ`ÐbgÓhˆà—m‘m KÓ0ˆØ˜+Ñ%Ð%r2   rœ   rK   s   @r1   rb  rb  L  s   ø„ ôfö&r2   rb  c                   ó>   ‡ — e Zd Zˆ fd„Zdej
                  fd„Zˆ xZS )ÚChameleonVQVAEEncoderc           	      óø  •— t         ‰| �  «        t        |j                  «      | _        |j
                  | _        |j                  }|j                  }|j                  }|j                  }|j                  }|j                  }t        j                  j                  ||ddd¬«      | _        |}dt        |«      z   }	|	| _        t        j"                  «       | _        t'        | j                  «      D �]  }
t        j"                  «       }t        j"                  «       }||	|
   z  }|||
   z  }t'        | j
                  «      D ]g  }|j)                  t+        |||¬«      «       |}|j,                  €Œ/||j,                  v sŒ>|j.                  dk(  sŒN|j)                  t1        |«      «       Œi t        j2                  «       }||_        ||_        |
| j                  dz
  k7  rt9        |«      |_        |dz  }| j$                  j)                  |«       �Œ! t        j2                  «       | _        t+        ||¬«      | j<                  _        |j.                  dk(  rt1        |«      nt        j@                  «       | j<                  _!        t+        |||¬«      | j<                  _"        t        j                  jG                  d|d	d
¬«      | _$        t        j                  j                  ||rd|z  n|ddd¬«      | _%        y )Nr	   r   r@  )r   )r‘   rG  rU  Úvanillar4   rP  rF   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__p  s¢  ø€ Ü‰ÑÔä" 6×#<Ñ#<Ó=ˆÔØ$×3Ñ3ˆÔØ×,Ñ,ˆØ×&Ñ&ˆ
Ø×(Ñ(ˆØ×,Ñ,ˆØ ×0Ñ0ˆØ#×6Ñ6Ðä—x‘x—‘ {°MÈqÐYZÐde�ÓfˆŒàˆØ $¤uÐ-?Ó'@Ñ @ÐØ%:ˆÔ"Ü—M‘M“OˆŒ	Ü˜T×1Ñ1Ó2ó 	#ˆGÜ—M‘M“OˆEÜ—=‘=“?ˆDØ$Ð'<¸WÑ'EÑEˆHØ%Ð(:¸7Ñ(CÑCˆIÜ  ×!4Ñ!4Ó5ò J�Ø—‘Ü4Ø%Ø$,Ø%.ôôð %�à×+Ñ+Ñ7Ø  F×$;Ñ$;Ò;Ø×(Ñ(¨IÓ5à—K‘KÔ >¸xÓ HÕIðJô  —9‘9“;ˆDØˆDŒJØˆDŒIØ˜$×.Ñ.°Ñ2Ò2Ü"EÀhÓ"O�”Ø# q™=�Ø�I‰I×Ñ˜TÖ"ð7	#ô: —9‘9“;ˆŒÜ;ØØ Ø!ô
ˆ�‰Ôð
 GM×FVÑFVÐZcÒFcÔ8¸ÔBÔik×itÑitÓivˆ�‰ŒÜ;ØØ Ø!ô
ˆ�‰Ôô Ÿ™×*Ñ*°bÀxÐUYÐbfÐ*ÓgˆŒÜŸ™Ÿ™ØÙ#0ˆA�Ò°oØØØð (ó 
ˆ�r2   Úpixel_valuesc                 ó2  — | j                  |«      g}t        | j                  «      D ]Ü  }t        | j                  «      D ]  } | j                  |   j
                  |   |d   «      }t        | j                  |   j                  «      dkD  r" | j                  |   j                  |   |«      }|j                  |«       Œ� || j                  dz
  k7  sŒ­|j                  | j                  |   j                  |d   «      «       ŒÞ |d   }| j                  j                  |«      }| j                  j                  |«      }| j                  j                  |«      }| j                  |«      }|t        j                   |«      z  }| j#                  |«      }|S )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Ð4ˆÜ˜T×1Ñ1Ó2ò 		WˆGÜ  ×!4Ñ!4Ó5ò 3�Ø@˜tŸy™y¨Ñ1×7Ñ7¸Ñ@Ø! "Ñ%ó �ô �t—y‘y Ñ)×.Ñ.Ó/°!Ò3Ø#C 4§9¡9¨WÑ#5×#:Ñ#:¸7Ñ#CÀLÓ#Q�LØ×$Ñ$ \Õ2ð3ð ˜$×.Ñ.°Ñ2Ó2Ø×$Ñ$ T§Y¡Y¨wÑ%7×%BÑ%BÀ=ÐQSÑCTÓ%UÕVð		Wð *¨"Ñ-ÐØ ŸH™H×,Ñ,Ð->Ó?ÐØ ŸH™HŸO™OÐ,=Ó>ÐØ ŸH™H×,Ñ,Ð->Ó?Ðð !ŸM™MÐ*;Ó<ÐØœUŸ]™]Ð+<Ó=Ñ=ÐØ ŸM™MÐ*;Ó<ÐØ Ð r2   )rG   rH   rI   r'   r)   rð   r@   rJ   rK   s   @r1   rn  rn  o  s   ø„ ôC
ðJ! E×$4Ñ$4÷ !r2   rn  c                   ó®   — e Zd ZdZd„ Zed„ «       Zed„ «       Zed„ «       Zed„ «       Z	ed„ «       Z
ed„ «       Zd	ej                  d
ej                  fd„Zy)ÚChameleonImageVocabularyMappingzM
    A class for mapping discrete image tokens from VQGAN to BPE tokens.
    c                 ó>   — || _         |j                  d«      | _        y )Nz<image>)Ú	vocab_mapÚgetÚimage_token_id)r-   r—  s     r1   r'   z(ChameleonImageVocabularyMapping.__init__Õ  s   € Ø"ˆŒØ'Ÿm™m¨IÓ6ˆÕr2   c                 ój   — | j                   j                  «       D ��ci c]  \  }}||“Œ
 c}}S c c}}w rx   )r—  Úitems©r-   r‡   re  s      r1   Úval2namez(ChameleonImageVocabularyMapping.val2nameÙ  s+   € à!%§¡×!5Ñ!5Ó!7×8™˜˜A��1‘Ó8Ð8ùÓ8ó   ž/c           	      óž   — t        | j                  j                  «       D ��cg c]  \  }}|j                  d«      sŒ|‘Œ c}}«      S c c}}w )NÚIMGIMG)Úsortedr—  r›  Ú
startswith)r-   ÚnameÚvals      r1   Úimage_tokensz,ChameleonImageVocabularyMapping.image_tokensÝ  s8   € ä¨D¯N©N×,@Ñ,@Ó,B×`™y˜t SÀdÇoÁoÐV^ÕF_’sÓ`ÓaÐaùÓ`s
   £A	
½A	
c           
      ó  ‡— t        d«      D �ci c]#  }t        t        d«      |z   «      t        |«      “Œ% c}Šdt        dt        fˆfd„}| j                  D �ci c]!  }|t         || j                  |   «      «      “Œ# c}S c c}w c c}w )Né
   ÚAÚold_namer©   c                 óP   •— dj                  ˆfd„| t        d«      d D «       «      S )NÚ c              3   óB   •K  — | ]  }‰j                  ||«      –— Œ y ­wrx   )r˜  )Ú.0ÚcÚimg_tkn_chr_mappings     €r1   ú	<genexpr>zIChameleonImageVocabularyMapping.bpe2img.<locals>.remap.<locals>.<genexpr>æ  s   øè ø€ Ò_¸QÐ.×2Ñ2°1°a×8Ñ_ùs   ƒr   r5   )Újoinrq  )r©  r¯  s    €r1   Úremapz6ChameleonImageVocabularyMapping.bpe2img.<locals>.remapå  s$   ø€ Ø—7‘7Ó_À(Ì3ÈxË=Ð[]ÐB^Ô_Ó_Ð_r2   )r}  ÚchrÚordrh   r¥  rî   r�  )r-   Úir²  Útokr¯  s       @r1   Úbpe2imgz'ChameleonImageVocabularyMapping.bpe2imgá  sƒ   ø€ äBGÈÃ)ÖL¸Qœs¤3 s£8¨a¡<Ó0´#°a³&Ñ8ÒLÐð	`œCð 	`¤Cõ 	`ð @D×?PÑ?PÖQ¸�”S™˜tŸ}™}¨SÑ1Ó2Ó3Ñ3ÒQÐQùò Mùò
 Rs   �(BÁ&Bc                 ój   — | j                   j                  «       D ��ci c]  \  }}||“Œ
 c}}S c c}}w rx   )r·  r›  rœ  s      r1   Úimg2bpez'ChameleonImageVocabularyMapping.img2bpeê  s+   € à!%§¡×!3Ñ!3Ó!5×6™˜˜A��1‘Ó6Ð6ùÓ6rž  c                 óÚ   — t        j                  t        | j                  j	                  «       «      «      t        j                  t        | j                  j                  «       «      «      fS rx   )r)   Útensorr¡  r·  ÚkeysÚvaluesrD   s    r1   Úbpe2img_search_tensorsz6ChameleonImageVocabularyMapping.bpe2img_search_tensorsî  sC   € ä�|‰|œF 4§<¡<×#4Ñ#4Ó#6Ó7Ó8¼%¿,¹,ÄvÈdÏlÉl×NaÑNaÓNcÓGdÓ:eÐeÐer2   c                 óæ   — t        j                  t        | j                  j	                  «       «      dz   t         j
                  ¬«      }| j                  j                  «       D ]
  \  }}|||<   Œ |S )Nr   rP   )r)   Úzerosr~   r¹  r¼  rî   r›  )r-   Úmappingr‡   re  s       r1   Úimg2bpe_mapping_tensorz6ChameleonImageVocabularyMapping.img2bpe_mapping_tensorò  s[   € ä—+‘+œc $§,¡,×"3Ñ"3Ó"5Ó6¸Ñ:Ä%Ç)Á)ÔLˆØ—L‘L×&Ñ&Ó(ò 	‰DˆAˆqØˆG�AŠJð	àˆr2   Ú	img_batchr©   c                 óx   — |j                   }| j                  |j                  d«         }|j                  |«      S )Nra   )rR   rÂ  r8   )r-   rÃ  rR   Ú
img_tokenss       r1   Úconvert_img2bpez/ChameleonImageVocabularyMapping.convert_img2bpeù  s5   € Ø×!Ñ!ˆØ×0Ñ0°·±¸eÓ1DÑEˆ
Ø�}‰}˜VÓ$Ð$r2   N)rG   rH   rI   rz   r'   r   r�  r¥  r·  r¹  r¾  rÂ  r)   rï   rÆ  r  r2   r1   r•  r•  Ð  s¥   „ ñò7ð ñ9ó ð9ð ñbó ðbð ñRó ðRð ñ7ó ð7ð ñ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                   óF   — 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y	)
ÚChameleonPreTrainedModelÚmodelTr  r$  Úpast_key_valuesrë   Fc                 óŽ  — | j                   j                  }t        |t        «      r|j	                  |j
                  «       y t        |t        j                  t        j                  f«      rY|j                  j                  j                  d|¬«       |j                  �%|j                  j                  j                  «        y y t        |t        j                  «      rf|j                  j                  j                  d|¬«       |j                  �2|j                  j                  |j                     j                  «        y y y )Nr÷   ©r;   Ústd)r‘   Úinitializer_rangerg   ÚChameleonVQVAEÚapplyÚ_init_weightsr   r“   rD  r+   ÚdataÚnormal_r�   Úzero_r.  Úpadding_idx©r-   ÚmodulerÍ  s      r1   rÑ  z&ChameleonPreTrainedModel._init_weights!  sè   € Ø�k‰k×+Ñ+ˆÜ�fœnÔ-Ø�L‰L˜×-Ñ-Õ.Ü˜¤§¡¬B¯I©IÐ 6Ô7Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø�{‰{Ð&Ø—‘× Ñ ×&Ñ&Õ(ð 'ä˜¤§¡Ô-Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø×!Ñ!Ð-Ø—‘×"Ñ" 6×#5Ñ#5Ñ6×<Ñ<Õ>ð .ð .r2   N)rG   rH   rI   r   Úconfig_classÚbase_model_prefixÚsupports_gradient_checkpointingÚ_no_split_modulesÚ_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È    sT   „ ð
 #€LØÐØ&*Ð#Ø0Ð2MÐNÐØ#4°mÐ"DÐØ!ÐØ€NØ $ÐØ ÐØ!ÐØ(-Ð%ó?r2   rÈ  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                   óT   ‡ — 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 )rÏ  r(  c                 ó‚  — | j                   j                  }t        |t        j                  «      r(|j
                  j                  j                  d|¬«       y t        |t        j                  «      rJ|j                  j                  j                  «        |j
                  j                  j                  d«       y t        |t        j                  t        j                  f«      rY|j
                  j                  j                  d|¬«       |j                  �%|j                  j                  j                  «        y y y )Nr÷   rÌ  rO   )r‘   rÎ  rg   r   r.  r+   rÒ  rÓ  rW  r�   rÔ  Úfill_r“   rD  rÖ  s      r1   rÑ  zChameleonVQVAE._init_weightsK  sÖ   € Ø�k‰k×+Ñ+ˆÜ�fœbŸl™lÔ+Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Õ9Ü˜¤§¡Ô-Ø�K‰K×Ñ×"Ñ"Ô$Ø�M‰M×Ñ×$Ñ$ SÕ)Ü˜¤§¡¬B¯I©IÐ 6Ô7Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø�{‰{Ð&Ø—‘× Ñ ×&Ñ&Õ(ð 'ð 8r2   r‘   c                 ól  •— t         ‰| �  |«       t        |«      | _        t	        |«      | _        t        j                  j                  |j                  |j                  d«      | _        t        j                  j                  |j                  |j                  d«      | _        | j                  «        y ©Nr   )r&   r'   rn  Úencoderr(  Úquantizer)   r   rD  rx  r,  Ú
quant_convÚpost_quant_convÚevalrš   s     €r1   r'   zChameleonVQVAE.__init__W  s|   ø€ Ü‰Ñ˜Ô ä,¨VÓ4ˆŒÜ5°fÓ=ˆŒÜŸ(™(Ÿ/™/¨&×*@Ñ*@À&×BRÑBRÐTUÓVˆŒÜ$Ÿx™xŸ™¨v×/?Ñ/?À×AWÑAWÐYZÓ[ˆÔØ�	‰	�r2   r‘  c                 óz   — | j                  |«      }| j                  |«      }| j                  |«      \  }}}|||fS rx   )rè  rê  ré  )r-   r‘  r=   ÚquantÚemb_lossÚindicess         r1   ÚencodezChameleonVQVAE.encode`  s@   € ØŸ™ \Ó2ˆØŸ™¨Ó6ˆØ#'§=¡=°Ó#?Ñ ˆˆx˜Ø�h Ð'Ð'r2   )rG   rH   rI   r   rØ  rÛ  rÑ  r'   r)   rð   rñ  rJ   rK   s   @r1   rÏ  rÏ  @  s7   ø„ ð (€LØ8Ð9Ðò
)ðÐ3õ ð( 5×#3Ñ#3÷ (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                   óv  ‡ — 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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ef   fd„«       «       Z	 d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           	      ó¤  •— t         ‰| �  |«       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                  «      | _        t        |j                  «      | _        | j                  j                  st        nt        }t        j                   t#        |j$                  «      D �cg c]  } |||«      ‘Œ c}«      | _        t)        |j                  |j*                  ¬«      | _        t.        j1                  |j2                  «      | _        d| _        | j9                  «        y c c}w )Nr¤   F)r&   r'   Úpad_token_idrÕ  Ú
vocab_sizer   r.  r.   Úembed_tokensr•  Úvocabulary_mapÚvocabulary_mappingr‘   Ú	swin_normr  r$  r{  r}  Únum_hidden_layersÚlayersr$   r  rd  rÏ  Ú_from_configÚ	vq_configÚvqmodelÚgradient_checkpointingÚ	post_init)r-   r‘   Údecoder_layerr³   r0   s       €r1   r'   zChameleonModel.__init__¸  sù   ø€ Ü‰Ñ˜Ô Ø!×.Ñ.ˆÔØ ×+Ñ+ˆŒäŸL™L¨×):Ñ):¸F×<NÑ<NÐPT×P`ÑP`ÓaˆÔÜ"AÀ&×BWÑBWÓ"XˆÔØ59·[±[×5JÒ5JÕ-ÔPiˆÜ—m‘mÜ?DÀV×E]ÑE]Ó?^Ö_°)‰]˜6 9Õ-Ò_ó
ˆŒô % V×%7Ñ%7¸V×=PÑ=PÔQˆŒ	Ü%×2Ñ2°6×3CÑ3CÓDˆŒØ&+ˆÔ#ð 	�‰Õùò `s   ÃEc                 ó   — | j                   S rx   ©r÷  rD   s    r1   Úget_input_embeddingsz#ChameleonModel.get_input_embeddingsÊ  s   € Ø× Ñ Ð r2   c                 ó   — || _         y rx   r  ©r-   rL  s     r1   Úset_input_embeddingsz#ChameleonModel.set_input_embeddingsÍ  s
   € Ø!ˆÕr2   r‘  c                 ó¼   — |j                   d   }| j                  j                  |«      \  }}}| j                  j	                  |«      }|j                  |d«      }|S )as  
        Tokenizes images into discrete tokens with VQGAN module. Converts
        obtained image tokens into BPE tokens and wraps with "boi" and "eoi"
        special tokens.

        Args:
            pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
                The tensors corresponding to the input images.
        r   r5   )rC   rÿ  rñ  rù  rÆ  rÚ   )r-   r‘  ri  rå   Ú
image_toksÚbpe_tokss         r1   Úget_image_tokenszChameleonModel.get_image_tokensÐ  sZ   € ð "×'Ñ'¨Ñ*ˆ
ØŸ<™<×.Ñ.¨|Ó<Ñˆˆ1ˆjØ×*Ñ*×:Ñ:¸:ÓFˆØ—=‘= ¨RÓ0ˆØˆr2   )Ú
checkpointÚoutput_typerØ  Úexpected_outputÚ	input_idsrÏ   ro   rÊ  Úinputs_embedsrÒ   rÑ   Úoutput_hidden_statesÚreturn_dictrÓ   r©   c                 óT  — |�|n| j                   j                  }|	�|	n| j                   j                  }	|�|n| j                   j                  }|
�|
n| j                   j                  }
| j
                  r%| j                  r|rt        j                  d«       d}|d u |d uz  rt        d«      ‚|�|�t        d«      ‚|�ç| j                  |«      }|| j                  j                  k(  }t        «       s{||   j                  «       |j                  «       k7  rW|| j                  j                  k(  j                  «       }|j                   d   |j                   d   z  }t        d|› d|› �«      ‚|j#                  |j$                  |j&                  «      }|j)                  ||«      }|€| j+                  |«      }|r*|€(t,        j.                  j1                  «       s
t3        «       }|€F|�|j5                  «       nd}t-        j6                  |||j                   d   z   |j$                  ¬	«      }|€|j9                  d«      }| j;                  |||||«      }|}|	rd
nd }|rd
nd }d }| j<                  D ]p  }|	r||fz  }| j
                  r/| j                  r#| j?                  |j@                  |||||||«      }n ||||||||¬«      }|d   }|r	||rdnd   }|sŒh||d   fz  }Œr | jC                  |«      }|	r||fz  }d }|r|}|
stE        d„ ||||fD «       «      S tG        ||||¬«      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 ©rR   r  )rÏ   ro   rÐ   rÑ   rÒ   rÓ   r4   c              3   ó&   K  — | ]	  }|€Œ|–— Œ y ­wrx   r  )r­  re  s     r1   r°  z)ChameleonModel.forward.<locals>.<genexpr>_  s   è ø€ Òt˜qÐfgÑfsœÑtùs   ‚Š)r“  rÊ  r=   Ú
attentions)$r‘   rÑ   r  rÒ   Úuse_return_dictr   rØ   rµ   r¶   r¾   r  rù  r™  r   Únumelr4  rC   r8   rR   r7   Úmasked_scatterr÷  r)   ÚjitÚ
is_tracingr   Úget_seq_lengthrZ   r…   Ú_update_causal_maskrü  Ú_gradient_checkpointing_funcÚ__call__rd  rB   r   )r-   r  r‘  rÏ   ro   rÊ  r  rÒ   rÑ   r  r  rÓ   r¥  Úspecial_image_maskÚn_image_tokens_in_textÚn_image_featuresÚ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Ñ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð "+Ð!6‘I¸D¿K¹K×<QÑ<Qˆ	Ø%0Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà×&Ò&¨4¯=ª=¹YÜ×ÑØjôð ˆIà˜Ð -°tÐ";Ò<ÜÐYÓZÐZàÐ#¨Ð(AÜØvóð ð Ð#Ø×0Ñ0°Ó>ˆLØ!*¨d×.EÑ.E×.TÑ.TÑ!TÐÜ+Ô-°)Ð<NÑ2O×2UÑ2UÓ2WÐ[g×[mÑ[mÓ[oÒ2oØ*3°t×7NÑ7N×7]Ñ7]Ñ*]×)bÑ)bÓ)dÐ&Ø#/×#5Ñ#5°aÑ#8¸<×;MÑ;MÈaÑ;PÑ#PÐ Ü ØLÐMcÐLdÐdoð  qAð  pBð  Cóð ð (Ÿ?™?¨9×+;Ñ+;¸Y¿_¹_ÓMˆLØ!×0Ñ0Ð1CÀ\ÓRˆIàÐ Ø ×-Ñ-¨iÓ8ˆMñ ˜Ð0¼¿¹×9MÑ9MÔ9OÜ*›nˆOàÐ!ØCRÐC^˜×=Ñ=Ô?ÐdeÐÜ"Ÿ\™\Ø Ð"2°]×5HÑ5HÈÑ5KÑ"KÐTa×ThÑThôˆNð ÐØ)×3Ñ3°AÓ6ˆLà×.Ñ.Ø˜M¨>¸?ÐL]ó
ˆð
 &ˆñ #7™B¸DÐÙ0™°dˆØ!Ðà!Ÿ[™[ò  	6ˆMÙ#Ø! mÐ%5Ñ5Ð!à×*Ò*¨t¯}ª}Ø $× AÑ AØ!×*Ñ*Ø!ØØ Ø#Ø%ØØ"ó	!‘ñ !.Ø!Ø#.Ø!-Ø#2Ø&7Ø'Ø#1ô!�ð *¨!Ñ,ˆMáØ%2Ñ8I±1ÈqÑ%QÐ"â Ø =°Ñ#3Ð"5Ñ5‘ðA 	6ðD Ÿ	™	 -Ó0ˆñ  Ø -Ð!1Ñ1Ðàˆ
ÙØ+ˆJáÜÑt ]°JÐ@QÐSaÐ$bÔtÓtÐtä&Ø+Ø&Ø+Ø%ô	
ð 	
r2   Úinput_tensorc           
      óÆ  — | j                   j                  dk(  r|�|dk(  j                  «       r|S y | j                   j                  dk(  r7t        |t        j
                  «      rt        |«      }t        |t        «      r|S |�|j                  «       nd}t        |t        «      }| j                   j                  dk(  r(|s&|s$t        j                  |||| j                  ¬«      ry |j                  |j                  }	}|j                  d   }
|r|j!                  «       }n1t        |t        j
                  «      r|j                  d   n||
z   dz   }| j#                  ||
|||	||j                  d   ¬	«      }| j                   j                  dk(  rQ|�O|j                  j$                  d
v r7|s5t	        j&                  |«      j(                  }t        j*                  ||«      }|S )Nr  r÷   Úflex_attentionr   r  )r  Úpast_key_values_lengthÚis_trainingr   r5   )Úsequence_lengthÚtarget_lengthr7   rR   rÓ   ri  )r  Úxpu)r‘   r  Úanyrg   r)   rï   r!   r    r  r   r   Ú_ignore_causal_mask_sdparØ   r7   rR   rC   Úget_max_cache_shapeÚ5_prepare_4d_causal_attention_mask_with_cache_positionrf   ÚfinfoÚminÚ_unmask_unattended)r-   rÏ   r*  rÓ   rÊ  rÑ   r$  Úusing_static_cacher7   rR   r/  r0  rë   Ú	min_dtypes                 r1   r  z"ChameleonModel._update_causal_maski  sÖ  € ð �;‰;×+Ñ+Ð/BÒBØÐ)¨~ÀÑ/D×.IÑ.IÔ.KØ%Ð%ØØ�;‰;×+Ñ+Ð/?Ò?Ü˜.¬%¯,©,Ô7Ü!<¸^Ó!L�Ü˜.¬)Ô4Ø%Ð%ð
 @OÐ?Z˜?×9Ñ9Ô;Ð`aÐÜ'¨¼ÓEÐð �;‰;×+Ñ+¨vÒ5Ñ>PÑYjÜ%×>Ñ>ØØ*Ø'7Ø ŸM™Mõ	ð à$×*Ñ*¨L×,?Ñ,?ˆvˆØ&×,Ñ,¨QÑ/ˆÙØ+×?Ñ?ÓA‰Mô ˜n¬e¯l©lÔ;ð ×$Ñ$ RÒ(à%¨Ñ7¸!Ñ;ð ð ×PÑPØØ+Ø'ØØØ)Ø#×)Ñ)¨!Ñ,ð Qó 
ˆð �K‰K×,Ñ,°Ò6ØÐ*Ø×%Ñ%×*Ñ*¨oÑ=Ù%ô
 Ÿ™ EÓ*×.Ñ.ˆIÜ0×CÑCÀKÐQZÓ[ˆKàÐr2   r/  r0  r7   rR   ri  c                 ó˜  — | �| j                  «       dk(  r| }|S t        j                  |«      j                  }	t        j                  ||f|	||¬«      }|dk7  rt        j
                  |d¬«      }|t        j                  ||¬«      |j                  dd«      kD  z  }|dddd…dd…f   j                  |ddd«      }| �Œ|j                  «       }| j                  d   }
|dd…dd…dd…d|
…f   | dd…dddd…f   j                  |j                  «      z   }|dk(  }|dd…dd…dd…d|
…f   j                  ||	«      |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 place 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   rR   r   )Údiagonalr  r5   r   )rW   r)   r6  r7  ÚfullÚtriurZ   r«   re   ÚclonerC   r8   rR   Úmasked_fill)rÏ   r/  r0  r7   rR   rÓ   ri  r¢   rë   r:  Úmask_lengthÚpadding_masks               r1   r5  zDChameleonModel._prepare_4d_causal_attention_mask_with_cache_position¯  sy  € ðD Ð%¨.×*<Ñ*<Ó*>À!Ò*Cà(ˆKð* Ðô' Ÿ™ EÓ*×.Ñ.ˆIÜŸ*™*Ø  -Ð0¸YÈeÐ\bôˆKð  !Ò#Ü#Ÿj™j¨¸qÔA�Øœ5Ÿ<™<¨¸fÔEÈ×H^ÑH^Ð_aÐcdÓHeÑeÑeˆKØ% d¨D²!²QÐ&6Ñ7×>Ñ>¸zÈ1ÈbÐRTÓUˆKØÐ)Ø)×/Ñ/Ó1�Ø,×2Ñ2°2Ñ6�Ø*ª1ªa²°L°[°LÐ+@ÑAÀNÒSTÐVZÐ\`ÒbcÐScÑDd×DgÑDgØ×&Ñ&óEñ  �ð  ,¨qÑ0�Ø5@ÂÂAÂqÈ,È;È,ÐAVÑ5W×5cÑ5cØ  )ó6�šAšq¢! \ k \Ð1Ñ2ð Ðr2   )NNNNNNNNNNN)F)!rG   rH   rI   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   rR   r5  rJ   rK   s   @r1   ró  ró  ¬  s  ø„ ñ
ð˜õ ò$!ò"ð¨U×->Ñ->ó ñ  +Ð+EÓFÙØ&Ø+Ø$Ø.ô	ð 15Ø48Ø15Ø37Ø+/Ø59Ø$(Ø,0Ø/3Ø&*Ø59ñ
à˜E×,Ñ,Ñ-ð
ð ˜u×0Ñ0Ñ1ð
ð ! §¡Ñ.ð	
ð
 ˜u×/Ñ/Ñ0ð
ð " %™ð
ð   × 1Ñ 1Ñ2ð
ð ˜D‘>ð
ð $ D™>ð
ð ' t™nð
ð ˜d‘^ð
ð ! ×!1Ñ!1Ñ2ð
ð 
ˆuÐ-Ð-Ñ	.ò
óó Gð
ðP #(ñDàŸ™ðDð —l‘lðDð Ÿ™ð	Dð
 ðDð  óDðL ð7ØŸ™ð7àð7ð ð7ð �{‰{ð	7ð
 —‘ð7ð Ÿ™ð7ð ò7ó ô7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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ef   fd„«       «       Z	 	 	 	 	 	 	 dˆ fd„	Zˆ xZS )Ú!ChameleonForConditionalGenerationzlm_head.weightc                 óè   •— t         ‰| �  |«       t        |«      | _        |j                  | _        t        j                  |j                  |j                  d¬«      | _        | j                  «        y )NFr�   )
r&   r'   ró  rÉ  rö  r   r“   r.   Úlm_headr  rš   s     €r1   r'   z*ChameleonForConditionalGeneration.__init__ò  sU   ø€ Ü‰Ñ˜Ô Ü# FÓ+ˆŒ
Ø ×+Ñ+ˆŒÜ—y‘y ×!3Ñ!3°V×5FÑ5FÈUÔSˆŒð 	�‰Õr2   c                 ó.   — | j                   j                  S rx   ©rÉ  r÷  rD   s    r1   r  z6ChameleonForConditionalGeneration.get_input_embeddingsû  s   € Ø�z‰z×&Ñ&Ð&r2   c                 ó&   — || j                   _        y rx   rO  r  s     r1   r  z6ChameleonForConditionalGeneration.set_input_embeddingsþ  s   € Ø"'ˆ�
‰
Õr2   c                 ó   — | j                   S rx   ©rM  rD   s    r1   Úget_output_embeddingsz7ChameleonForConditionalGeneration.get_output_embeddings  s   € Ø�|‰|Ðr2   c                 ó   — || _         y rx   rR  )r-   Únew_embeddingss     r1   Úset_output_embeddingsz7ChameleonForConditionalGeneration.set_output_embeddings  s	   € Ø%ˆ�r2   c                 ó   — || _         y rx   ©rÉ  )r-   Údecoders     r1   Úset_decoderz-ChameleonForConditionalGeneration.set_decoder  s	   € Øˆ�
r2   c                 ó   — | j                   S rx   rX  rD   s    r1   Úget_decoderz-ChameleonForConditionalGeneration.get_decoder
  s   € Ø�z‰zÐr2   )r  rØ  r  r‘  rÏ   ro   rÊ  r  ÚlabelsrÒ   rÑ   r  r  rÓ   r©   c                 ó‚  — |	�|	n| j                   j                  }	|
�|
n| j                   j                  }
|�|n| j                   j                  }| j	                  ||||||||	|
||¬«      }|d   }| j                  |«      }| j                  j                  j                  }t        j                  |j                  «      j                  |dd…dd…|f<   d}|�¦|j                  «       }|ddd…dd…f   j                  «       }|ddd…f   j                  «       }t        «       }|j                  d| j                   j                   «      }|j                  d«      }|j#                  |j$                  «      } |||«      }|s|f|dd z   }|�|f|z   S |S t'        |||j(                  |j*                  |j,                  ¬«      S )aÿ  
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        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É  rM  rù  r¥  r)   r6  r7   r7  r\   râ   r   rÚ   rö  r8   rR   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Ö  € ðZ 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆð —*‘*ØØ%Ø)Ø%Ø+Ø'ØØ/Ø!5Ø#Ø)ð ó 
ˆð   ™
ˆØ—‘˜mÓ,ˆð —z‘z×4Ñ4×AÑAˆÜ%*§[¡[°·±Ó%>×%BÑ%BˆŠq’!�\Ð!Ñ"àˆØÐà—\‘\“^ˆFà! # s¨ sªA +Ñ.×9Ñ9Ó;ˆLØ! # q¡r '™?×5Ñ5Ó7ˆLä'Ó)ˆHØ'×,Ñ,¨R°·±×1GÑ1GÓHˆLØ'×,Ñ,¨RÓ0ˆLà'Ÿ?™?¨<×+>Ñ+>Ó?ˆLÙ˜L¨,Ó7ˆDáØ�Y ¨¨ Ñ,ˆFØ'+Ð'7�D�7˜VÑ#ÐC¸VÐCä%ØØØ#×3Ñ3Ø!×/Ñ/Ø×)Ñ)ô
ð 	
r2   c	                 óR   •— t        ‰| �  |f|||||||dœ|	¤Ž}
|d   dk7  rd |
d<   |
S )N)r‘  rÊ  rÏ   r  rÓ   ro   rÒ   r   r‘  )r&   Úprepare_inputs_for_generation)r-   r  r‘  rÊ  rÏ   r  rÓ   ro   rÒ   r¢   Úmodel_inputsr0   s              €r1   re  z?ChameleonForConditionalGeneration.prepare_inputs_for_generationq  s\   ø€ ô ‘wÑ<Øð

à%Ø+Ø)Ø'Ø)Ø%Øñ

ð ñ

ˆð ˜!Ñ Ò!ð ,0ˆL˜Ñ(àÐr2   )NNNNNNNNNNNN)NNNNNNT)rG   rH   rI   Ú_tied_weights_keysr'   r  r  rS  rV  rZ  r\  r   rE  r   r   rG  r   r)   rð   r"  rï   r   rñ   r   r   r@   re  rJ   rK   s   @r1   rK  rK  ë  sŸ  ø„ ð
 +Ð+Ðôò'ò(òò&òòñ +Ð+EÓFÙÐ+AÐP_Ô`ð 15Ø48Ø15Ø37Ø+/Ø59Ø-1Ø$(Ø,0Ø/3Ø&*Ø59ñ`
à˜E×,Ñ,Ñ-ð`
ð ˜u×0Ñ0Ñ1ð`
ð ! §¡Ñ.ð	`
ð
 ˜u×/Ñ/Ñ0ð`
ð " %™ð`
ð   × 1Ñ 1Ñ2ð`
ð ˜×)Ñ)Ñ*ð`
ð ˜D‘>ð`
ð $ D™>ð`
ð ' t™nð`
ð ˜d‘^ð`
ð ! ×!1Ñ!1Ñ2ð`
ð 
ˆuÐ,Ð,Ñ	-ò`
ó aó Gð`
ðJ ØØØØØØ÷ñ r2   rK  )rK  ró  rÈ  rÏ  rç  )]rz   rÝ   Ú	functoolsr   Útypingr   r   r   r)   Útorch.nn.functionalr   rß   r¥   Útorch.utils.checkpointÚtorch.nnr   Úactivationsr
   Úcache_utilsr   r   r   Ú
generationr   Úmodeling_attn_mask_utilsr   Úmodeling_flash_attention_utilsr   r   Úmodeling_outputsr   r   Úmodeling_utilsr   Úpytorch_utilsr   Úutilsr   r   r   r   r   r   r   Úconfiguration_chameleonr   r   Ú!torch.nn.attention.flex_attentionr    Úintegrations.flex_attentionr!   Ú
get_loggerrG   rµ   rG  rF  rH  Ú_SEQ_CLASS_EXPECTED_LOSSÚ_SEQ_CLASS_EXPECTED_OUTPUTr�  r$   r~  rM   rv   r|   rƒ   r‹   r�   Ú	LayerNormrž   rï   rî   r°   r²   ró   r  r  r  r$  r(  r>  rN  rb  rn  r•  ÚCHAMELEON_START_DOCSTRINGrÈ  ÚCHAMELEON_VQ_START_DOCSTRINGrÏ  rE  ró  rK  Ú__all__r  r2   r1   ú<module>r€     sÕ  ðñ ã Ý %ß )Ñ )ã ß Ð Û Ý Ý %å !ß ;Ñ ;Ý )Ý >ß i÷õ .Ý 1÷÷ ñ ÷ Kñ  Ô!Ý;åJð 
ˆ×	Ñ	˜HÓ	%€à#€Ø)Ð Ú%Ð ØÐ Ø(Ð ôJ�r—y‘yô Jð( Ð × Ñ Ð,Ô -ô
<˜rŸy™yô <ô@Ð,Dô ôÐ0Hô ò*(óô8�2—9‘9ô ô"˜Ÿ™ô ð&	U˜UŸ\™\ð 	U°#ð 	U¸%¿,¹,ó 	UôB9˜Ÿ™ô B9ôNr9Ð1ô r9ôjZ1Ð/ô Z1ð|  Ø1Ø"ñÐ ôH˜BŸI™Iô HôVF §	¡	ô FôR-> B§I¡Iô ->ô`	¨"¯)©)ô 	ô)( r§y¡yô )(ôX & R§Y¡Yô  &ôF^!˜BŸI™Iô ^!÷B,%ñ ,%ð^Ð ñ" Ø]Øóô?˜ó ?ó	ð?ð6 Ð ñ" ðð !óô(Ð-ó (óð(ð@BÐ ñJ Ø]ØóôxÐ-ó xó	ðxñv	 Ø^ØóôaÐ(@À/ó aó	ðaòH p�r2   