Ë
    S^(h\Ø  ã                   ól  — d dl Z d dlmZ d dlmZmZmZmZ d dlZd dl	m
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 dd	lmZmZmZmZmZ dd
lmZ ddlm Z m!Z! ddl"m#Z#m$Z$m%Z% ddl&m'Z' ddl(m)Z)m*Z*m+Z+ dZ,dZ- ej\                  e/«      Z0 G d„ de#«      Z1 G d„ de
jd                  «      Z3 G d„ de!«      Z4 G d„ de
jd                  «      Z5 G d„ de
jd                  «      Z6 G d„ de
jd                  «      Z7 G d„ d e
jd                  «      Z8 G d!„ d"e
jd                  «      Z9 G d#„ d$e
jd                  «      Z: G d%„ d&e
jd                  «      Z; G d'„ d(e'«      Z< G d)„ d*e
jz                  «      Z> G d+„ d,e
jd                  «      Z? G d-„ d.e
jd                  «      Z@ G d/„ d0e
jd                  «      ZA G d1„ d2e
jd                  «      ZB G d3„ d4e
jd                  «      ZCd5ZD ed6eD«       G d7„ d8e«      «       ZE G d9„ d:«      ZF G d;„ d<e eE«      ZGd=ZHd>ZI G d?„ d@e%eG«      ZJ G dA„ dBe$eGe«      ZK G dC„ dDeGe«      ZLg dE¢ZMy)Fé    N)Úcached_property)ÚListÚOptionalÚTupleÚUnioné   )ÚCache)ÚGenerationMixin)ÚCausalLMOutputWithPast)ÚPreTrainedModel)Úadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚcan_return_tupleÚloggingÚreplace_return_docstrings)Údeprecate_kwargé   )ÚChameleonPreTrainedModelÚ#ChameleonVQVAEEncoderConvDownsample)ÚLlamaDecoderLayerÚLlamaForCausalLMÚ
LlamaModel)ÚSiglipAttentioné   )Ú
Emu3ConfigÚEmu3TextConfigÚEmu3VQVAEConfigr   zBAAI/Emu3-Chat-hfc                   óf  ‡ — 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ej                  ej                  f      deej                  eeej                  ej                  f      f   fd„Zˆ xZS )ÚEmu3DecoderLayerÚconfigÚ	layer_idxc                 ón   •— t         ‰| �  ||«       t        j                  |j                  «      | _        y ©N)ÚsuperÚ__init__ÚnnÚDropoutÚattention_dropoutÚdropout©Úselfr    r!   Ú	__class__s      €úc/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/emu3/modular_emu3.pyr%   zEmu3DecoderLayer.__init__=   s(   ø€ Ü‰Ñ˜ Ô+Ü—z‘z &×":Ñ":Ó;ˆ�ó    Úhidden_statesÚattention_maskÚposition_idsÚpast_key_valueÚoutput_attentionsÚ	use_cacheÚcache_positionÚposition_embeddingsÚreturnc	                 ó  — |}
| j                  |«      } | j                  d||||||||dœ|	¤Ž\  }}|
| j                  |«      z   }|}
| j                  |«      }| j	                  |«      }|
| j                  |«      z   }|f}|r||fz  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        )r/   r0   r1   r2   r3   r4   r5   r6   © )Úinput_layernormÚ	self_attnr)   Úpost_attention_layernormÚmlp)r+   r/   r0   r1   r2   r3   r4   r5   r6   ÚkwargsÚresidualÚself_attn_weightsÚoutputss                r-   ÚforwardzEmu3DecoderLayer.forwardA   sÃ   € ð> !ˆà×,Ñ,¨]Ó;ˆð ,:¨4¯>©>ð 
,
Ø'Ø)Ø%Ø)Ø/ØØ)Ø 3ñ
,
ð ñ
,
Ñ(ˆÐ(ð ! 4§<¡<°Ó#>Ñ>ˆð !ˆØ×5Ñ5°mÓDˆØŸ™ Ó/ˆØ  4§<¡<°Ó#>Ñ>ˆà Ð"ˆáØÐ)Ð+Ñ+ˆGàˆr.   )NNNFFNN)Ú__name__Ú
__module__Ú__qualname__r   Úintr%   ÚtorchÚTensorr   Ú
LongTensorr	   Úboolr   ÚFloatTensorrB   Ú__classcell__©r,   s   @r-   r   r   <   sû   ø„ ð<˜zð <°cõ <ð 26Ø37Ø*.Ø,1Ø$)Ø59ØKOñ<à—|‘|ð<ð ! §¡Ñ.ð<ð ˜u×/Ñ/Ñ0ð	<ð
 ! ™ð<ð $ D™>ð<ð ˜D‘>ð<ð ! ×!1Ñ!1Ñ2ð<ð & e¨E¯L©L¸%¿,¹,Ð,FÑ&GÑHð<ð 
ˆu× Ñ  (¨5°×1BÑ1BÀE×DUÑDUÐ1UÑ+VÑ"WÐWÑ	X÷<r.   r   c                   óH   ‡ — e Zd ZdZdefˆ fd„Zdej                  fd„Zˆ xZ	S )ÚEmu3VQVAEVectorQuantizeraâ  
    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.
    r    c                 ó  •— t         ‰| �  «        t        j                  |j                  |j
                  «      | _        | j                  j                  j                  j                  d|j                  z  d|j                  z  «       y )Ng      ð¿g      ð?)
r$   r%   r&   Ú	EmbeddingÚcodebook_sizeÚ	embed_dimÚ	embeddingÚweightÚdataÚuniform_©r+   r    r,   s     €r-   r%   z!Emu3VQVAEVectorQuantizer.__init__‹   sb   ø€ Ü‰ÑÔÜŸ™ f×&:Ñ&:¸F×<LÑ<LÓMˆŒØ�‰×Ñ×"Ñ"×+Ñ+¨D°6×3GÑ3GÑ,GÈÈv×OcÑOcÑIcÕdr.   Úhidden_statec                 ó  — |j                   \  }}}}}|j                  ddddd«      j                  «       }|j                  d|«      }t	        j
                  |dz  dd¬«      }t	        j
                  | j                  j                  dz  d¬	«      }	dt	        j                  || j                  j                  j                  dd«      «      z  }
||	z   |
z
  }
t	        j                  |
d¬	«      }|j                  ||||«      }|S )
Nr   r   r   é   r   éÿÿÿÿT)ÚdimÚkeepdim©r]   )ÚshapeÚpermuteÚ
contiguousÚviewrG   ÚsumrT   rU   ÚmatmulÚ	transposeÚargmin)r+   rY   Ú
batch_sizeÚtemporalÚchannelsÚheightÚwidthÚhidden_state_flattenedÚhidden_state_sumÚembedding_sumÚ	distancesÚmin_encoding_indicess               r-   rB   z Emu3VQVAEVectorQuantizer.forward�   sõ   € Ø8D×8JÑ8JÑ5ˆ
�H˜h¨°Ø#×+Ñ+¨A¨q°!°Q¸Ó:×EÑEÓGˆØ!-×!2Ñ!2°2°xÓ!@Ðô !Ÿ9™9Ð%;¸QÑ%>ÀAÈtÔTÐÜŸ	™	 $§.¡.×"7Ñ"7¸Ñ":ÀÔBˆð œŸ™Ð%;¸T¿^¹^×=RÑ=R×=\Ñ=\Ð]^Ð`aÓ=bÓcÑcˆ	Ø$ }Ñ4°yÑ@ˆ	ä$Ÿ|™|¨I¸1Ô=ÐØ3×8Ñ8¸ÀXÈvÐW\Ó]ÐØ#Ð#r.   )
rC   rD   rE   Ú__doc__r   r%   rG   rH   rB   rL   rM   s   @r-   rO   rO   €   s&   ø„ ñðe˜õ eð
$ E§L¡L÷ $r.   rO   c                   ó   — e Zd Zy)ÚEmu3VQVAEEncoderConvDownsampleN)rC   rD   rE   r9   r.   r-   rt   rt   ¢   s   „ Ør.   rt   c                   ó$   ‡ — e Zd Zˆ fd„Zd„ Zˆ xZS )ÚEmu3VQVAEEncoderConvUpsamplec                 ó`   •— t         ‰| �  «        t        j                  ||ddd¬«      | _        y )Nr   r   ©Úkernel_sizeÚstrideÚpadding)r$   r%   r&   ÚConv2dÚconv)r+   Úin_channelsr,   s     €r-   r%   z%Emu3VQVAEEncoderConvUpsample.__init__§   s'   ø€ Ü‰ÑÔÜ—I‘I˜k¨;ÀAÈaÐYZÔ[ˆ�	r.   c                 óX   — t        j                  |dd¬«      }| j                  |«      }|S )Nç       @Únearest©Úscale_factorÚmode)ÚFÚinterpolater}   ©r+   r/   s     r-   rB   z$Emu3VQVAEEncoderConvUpsample.forward«   s(   € ÜŸ™ mÀ#ÈIÔVˆØŸ	™	 -Ó0ˆØÐr.   ©rC   rD   rE   r%   rB   rL   rM   s   @r-   rv   rv   ¦   s   ø„ ô\ör.   rv   c            	       ó\   ‡ — e Zd Zdededee   dee   fˆ fd„Zdej                  fd„Zˆ xZ	S )ÚEmu3VQVAEConv3dÚ
in_channelÚout_channelry   rz   c                 óP  •— t         ‰	| �  «        t        |dd  |dd  «      D ��cg c]
  \  }}||z
  ‘Œ }}}d| _        |d d d…   D ]%  }| xj                  |dz  |dz  z   |dz  fz  c_        Œ' | xj                  dz  c_        t	        j
                  ||||¬«      | _        y c c}}w )Nr   r9   r\   r   )r   r   )rz   )r$   r%   Úzipr{   r&   ÚConv3dr}   )
r+   r‹   rŒ   ry   rz   Ú
one_kernelÚ
one_strideÚpadding_sizesÚpad_sizer,   s
            €r-   r%   zEmu3VQVAEConv3d.__init__²   s½   ø€ ô 	‰ÑÔäORÐS^Ð_`Ð_aÐSbÐdjÐklÐkmÐdnÓOo×pÑ5K°ZÀ˜ jÓ0ÐpˆÑpØˆŒØ%¡d¨ dÑ+ò 	JˆHØ�LŠL˜X¨™]¨X¸©\Ñ9¸8Àq¹=ÐIÑIŽLð	Jà�Š˜Ñ�ä—I‘IØØØØô	
ˆ�	ùó qs   ¥B"r/   c                 óh   — t        j                  || j                  «      }| j                  |«      }|S r#   )r…   Úpadr{   r}   r‡   s     r-   rB   zEmu3VQVAEConv3d.forwardÈ   s*   € ÜŸ™˜m¨T¯\©\Ó:ˆØŸ	™	 -Ó0ˆØÐr.   )
rC   rD   rE   rF   r   r%   rG   rH   rB   rL   rM   s   @r-   rŠ   rŠ   ±   sF   ø„ ð
àð
ð ð
ð ˜3‘Zð	
ð
 �c‘
õ
ð, U§\¡\÷ r.   rŠ   c                   ó`   ‡ — e Zd Zdedefˆ fd„Zdej                  dej                  fd„Zˆ xZS )ÚEmu3VQVAESpatialNormr~   Úout_channelsc                 óÚ   •— t         ‰| �  «        t        j                  |ddd¬«      | _        t        j
                  ||ddd¬«      | _        t        j
                  ||ddd¬«      | _        y )Né    ç�íµ ÷Æ°>T©Únum_channelsÚ
num_groupsÚepsÚaffiner   r   rx   )r$   r%   r&   Ú	GroupNormÚ
norm_layerr|   Úconv_yÚconv_b©r+   r~   r˜   r,   s      €r-   r%   zEmu3VQVAESpatialNorm.__init__Ï   sn   ø€ ô
 	‰ÑÔÜŸ,™,Ø%ØØØô	
ˆŒô —i‘iØØØØØô
ˆŒô —i‘iØØØØØô
ˆ�r.   r/   Úquant_statesc                 ó¾   — t        j                  ||j                  dd  d¬«      }| j                  |«      }|| j	                  |«      z  | j                  |«      z   }|S )Néþÿÿÿr�   )Úsizer„   )r…   r†   r`   r¢   r£   r¤   )r+   r/   r¦   s      r-   rB   zEmu3VQVAESpatialNorm.forwardë   sX   € Ü—}‘} \¸×8KÑ8KÈBÈCÐ8PÐW`ÔaˆØŸ™¨Ó6ˆØ%¨¯©°LÓ(AÑAÀDÇKÁKÐP\ÓD]Ñ]ˆØÐr.   ©	rC   rD   rE   rF   r%   rG   rH   rB   rL   rM   s   @r-   r—   r—   Î   s5   ø„ ð
àð
ð õ
ð8 U§\¡\ð ÀÇÁ÷ r.   r—   c                   óH   ‡ — e Zd Zdedefˆ fd„Zdej                  fd„Zˆ xZS )ÚEmu3VQVAETemporalUpsampler‹   rŒ   c                 óJ   •— t         ‰| �  «        t        ||dd¬«      | _        y )N©r   r   r   ©r   r   r   ©ry   rz   ©r$   r%   rŠ   r}   ©r+   r‹   rŒ   r,   s      €r-   r%   z"Emu3VQVAETemporalUpsample.__init__ó   ó(   ø€ ô
 	‰ÑÔÜ#ØØØ!Øô	
ˆ�	r.   r/   c                 óP  — |j                   \  }}}}}|j                  ddddd«      j                  «       j                  |d|«      }t	        j
                  |dd¬	«      }|j                  ||||d«      j                  ddddd«      j                  «       }| j                  |«      }|S )
Nr   r   r   r[   r   r\   r€   r�   r‚   )r`   ra   rb   rc   r…   r†   r}   )r+   r/   rh   rj   ri   rk   rl   s          r-   rB   z!Emu3VQVAETemporalUpsample.forward   sª   € Ø8E×8KÑ8KÑ5ˆ
�H˜h¨°Ø%×-Ñ-¨a°°A°q¸!Ó<×GÑGÓI×NÑNÈzÐ[]Ð_gÓhˆÜŸ™ mÀ#ÈIÔVˆØ%×*Ñ*¨:°xÀÈÐPRÓS×[Ñ[Ð\]Ð_`ÐbcÐefÐhiÓj×uÑuÓwˆØŸ	™	 -Ó0ˆØÐr.   rª   rM   s   @r-   r¬   r¬   ò   s*   ø„ ð
àð
ð õ
ð U§\¡\÷ r.   r¬   c                   óH   ‡ — e Zd Zdedefˆ fd„Zdej                  fd„Zˆ xZS )ÚEmu3VQVAETemporalDownsampler‹   rŒ   c                 óJ   •— t         ‰| �  «        t        ||dd¬«      | _        y )N)r[   r   r   )r   r   r   r°   r±   r²   s      €r-   r%   z$Emu3VQVAETemporalDownsample.__init__
  r³   r.   r/   c                 ó(   — | j                  |«      }|S r#   )r}   r‡   s     r-   rB   z#Emu3VQVAETemporalDownsample.forward  s   € ØŸ	™	 -Ó0ˆØÐr.   rª   rM   s   @r-   r¶   r¶   	  s*   ø„ ð
àð
ð õ
ð U§\¡\÷ r.   r¶   c                   ó(   ‡ — e Zd Z	 dˆ fd„	Zd„ Zˆ xZS )ÚEmu3VQVAETemporalResnetBlockc                 óp  •— t         ‰| �  «        || _        |€|n|| _        t	        j
                  |«      | _        t        ||dd¬«      | _        t	        j
                  |«      | _	        t        ||dd¬«      | _
        | j                  | j                  k7  r t	        j                  ||ddd¬«      | _        y y )Nr®   r¯   r°   r   r   rx   )r$   r%   r~   r˜   r&   ÚBatchNorm3dÚnorm1rŠ   Úconv1Únorm2Úconv2r�   Únin_shortcutr¥   s      €r-   r%   z%Emu3VQVAETemporalResnetBlock.__init__  s´   ø€ ô
 	‰ÑÔØ&ˆÔØ+7Ð+?™KÀ\ˆÔä—^‘^ KÓ0ˆŒ
Ü$ØØØ!Øô	
ˆŒ
ô —^‘^ LÓ1ˆŒ
Ü$ØØØ!Øô	
ˆŒ
ð ×Ñ˜t×0Ñ0Ò0Ü "§	¡	ØØØØØô!ˆDÕð 1r.   c                 óL  — |}| j                  |«      }|t        j                  |«      z  }| j                  |«      }| j	                  |«      }|t        j                  |«      z  }| j                  |«      }| j                  | j                  k7  r| j                  |«      }||z   S r#   )	r½   rG   Úsigmoidr¾   r¿   rÀ   r~   r˜   rÁ   )r+   r/   r?   s      r-   rB   z$Emu3VQVAETemporalResnetBlock.forward=  s”   € Ø ˆØŸ
™
 =Ó1ˆØœŸ™ }Ó5Ñ5ˆØŸ
™
 =Ó1ˆàŸ
™
 =Ó1ˆØœŸ™ }Ó5Ñ5ˆØŸ
™
 =Ó1ˆà×Ñ˜t×0Ñ0Ò0Ø×(Ñ(¨Ó2ˆHà˜-Ñ'Ð'r.   r#   rˆ   rM   s   @r-   rº   rº     s   ø„ ð õö@(r.   rº   c                   ó~   ‡ — e Zd Z	 	 ddedee   dee   fˆ fd„Zddej                  deej                     fd„Zˆ xZ	S )	ÚEmu3VQVAEResnetBlockr~   r˜   Úquant_channelsc                 ó  •— t         ‰| �  «        || _        |€|n|}|| _        || _        |€=t        j                  |ddd¬«      | _        t        j                  |ddd¬«      | _        n"t        ||«      | _        t        ||«      | _        t        j                  ||ddd¬«      | _        t        j                  ||ddd¬«      | _        | j                  | j                  k7  r t        j                  ||ddd¬«      | _        y y )	Nrš   r›   Trœ   r   r   rx   r   )r$   r%   r~   r˜   rÆ   r&   r¡   r½   r¿   r—   r|   r¾   rÀ   rÁ   )r+   r~   r˜   rÆ   r,   s       €r-   r%   zEmu3VQVAEResnetBlock.__init__N  s  ø€ ô 	‰ÑÔØ&ˆÔØ&2Ð&:‘{ÀˆØ(ˆÔØ,ˆÔàÐ!ÜŸ™°;È2ÐSWÐ`dÔeˆDŒJÜŸ™°<ÈBÐTXÐaeÔfˆD�Jä-¨n¸kÓJˆDŒJÜ-¨n¸lÓKˆDŒJä—Y‘YØØØØØô
ˆŒ
ô —Y‘YØØØØØô
ˆŒ
ð ×Ñ˜t×0Ñ0Ò0Ü "§	¡	ØØØØØô!ˆDÕð 1r.   r/   c                 óv  — | j                   €dn|f}|} | j                  |g|¢­Ž }|t        j                  |«      z  }| j	                  |«      } | j
                  |g|¢­Ž }|t        j                  |«      z  }| j                  |«      }| j                  | j                  k7  r| j                  |«      }||z   S ©Nr9   )
rÆ   r½   rG   rÃ   r¾   r¿   rÀ   r~   r˜   rÁ   )r+   r/   rÆ   Ú	norm_argsr?   s        r-   rB   zEmu3VQVAEResnetBlock.forwardz  s·   € Ø×-Ñ-Ð5‘B¸NÐ;Lˆ	à ˆØ"˜Ÿ
™
 =Ð=°9Ò=ˆØœŸ™ }Ó5Ñ5ˆØŸ
™
 =Ó1ˆà"˜Ÿ
™
 =Ð=°9Ò=ˆØœŸ™ }Ó5Ñ5ˆØŸ
™
 =Ó1ˆà×Ñ˜t×0Ñ0Ò0Ø×(Ñ(¨Ó2ˆHà˜-Ñ'Ð'r.   )NNr#   )
rC   rD   rE   rF   r   r%   rG   rH   rB   rL   rM   s   @r-   rÅ   rÅ   M  sU   ø„ ð '+Ø(,ñ	*àð*ð ˜s‘mð*ð ! ™õ	*ñX( U§\¡\ð (À8ÈEÏLÉLÑCY÷ (r.   rÅ   c                   ó$   ‡ — e Zd Zdefˆ fd„Zˆ xZS )ÚEmu3VQVAEAttentionBlockr    c                 ó2   •— t         ‰| �  |«       d| _        y )Nr   )r$   r%   Únum_key_value_groupsrX   s     €r-   r%   z Emu3VQVAEAttentionBlock.__init__�  s   ø€ Ü‰Ñ˜Ô ð %&ˆÕ!r.   )rC   rD   rE   r   r%   rL   rM   s   @r-   rÌ   rÌ   Œ  s   ø„ ð&˜÷ &ñ &r.   rÌ   c                   ó*   ‡ — e Zd ZdZˆ fd„Zdd„Zˆ xZS )ÚEmu3VQVAEGroupNormzá
    Same as the torch GroupNorm with the only difference that this ones accepts
    an optional kwarg `quant_states` which is not used. This class makes it easier to
    use SpatialNorm or GroupNorm without conditionals
    c                 ó$   •— t        ‰| �  di |¤Ž y rÉ   )r$   r%   )r+   r>   r,   s     €r-   r%   zEmu3VQVAEGroupNorm.__init__›  s   ø€ Ü‰ÑÑ"˜6Ó"r.   c                 ó„   — t        j                  || j                  | j                  | j                  | j
                  «      S r#   )r…   Ú
group_normrž   rU   ÚbiasrŸ   )r+   Úinputr¦   s      r-   rB   zEmu3VQVAEGroupNorm.forwardž  s)   € Ü�|‰|˜E 4§?¡?°D·K±KÀÇÁÈDÏHÉHÓUÐUr.   r#   )rC   rD   rE   rr   r%   rB   rL   rM   s   @r-   rÐ   rÐ   ”  s   ø„ ñô#÷Vr.   rÐ   c                   ó`   ‡ — e Zd Zdˆ fd„	Zddej
                  deej
                     fd„Zˆ xZS )ÚEmu3VQVAEMiddleBlockc                 óÞ   •— t         ‰| �  «        t        |||¬«      | _        t	        |«      | _        |€t        |ddd¬«      | _        nt        ||«      | _        t        |||¬«      | _	        y )N©r~   r˜   rÆ   rš   r›   Trœ   )
r$   r%   rÅ   Úblock_1rÌ   Úattn_1rÐ   Ú	attn_normr—   Úblock_2)r+   r    r~   rÆ   r,   s       €r-   r%   zEmu3VQVAEMiddleBlock.__init__£  so   ø€ Ü‰ÑÔä+Ø#Ø$Ø)ô
ˆŒô
 .¨fÓ5ˆŒØÐ!Ü/¸[ÐUWÐ]aÐjnÔoˆD�Nä1°.À+ÓNˆDŒNä+Ø#Ø$Ø)ô
ˆ�r.   r/   r¦   c                 ób  — | j                  ||«      }|}| j                  ||«      }|j                  \  }}}}|j                  ||||z  «      j	                  dd«      }| j                  |«      d   }|j                  ||||«      j                  dddd«      }||z   }| j                  ||«      }|S )Nr   r   r   r   )	rÚ   rÜ   r`   rc   rf   rÛ   Úreshapera   rÝ   )r+   r/   r¦   r?   rh   rj   rk   rl   s           r-   rB   zEmu3VQVAEMiddleBlock.forward·  sÀ   € ØŸ™ ]°LÓAˆØ ˆØŸ™ }°lÓCˆØ.;×.AÑ.AÑ+ˆ
�H˜f eØ%×*Ñ*¨:°xÀÈ%ÁÓP×ZÑZÐ[\Ð^_Ó`ˆØŸ™ MÓ2°1Ñ5ˆØ%×-Ñ-¨j¸&À%ÈÓR×ZÑZÐ[\Ð^_ÐabÐdeÓfˆØ  =Ñ0ˆØŸ™ ]°LÓAˆØÐr.   r#   )	rC   rD   rE   r%   rG   rK   r   rB   rL   rM   s   @r-   r×   r×   ¢  s,   ø„ õ
ñ(
 U×%6Ñ%6ð 
ÀhÈu×O`ÑO`ÑFa÷ 
r.   r×   c                   ó>   ‡ — e Zd Zˆ fd„Zdej
                  fd„Zˆ xZS )ÚEmu3VQVAEDownBlockc           
      óÌ  •— t         ‰| �  «        t        |j                  «      | _        |j
                  | _        |j                  }|j                  }dt        |«      z   }|| _        t        j                  «       | _        t        | j                  «      D �]K  }t        j                  «       }t        j                  «       }t        j                  «       }|||   z  }	|||   z  }
t        | j
                  «      D ]~  }|j                  t        |	|
¬«      «       |
}	|j                  €Œ.||j                  v sŒ=|j                  t!        |«      «       |j                  t        j"                  |	ddd¬«      «       Œ€ t        j$                  «       }||_        ||_        ||_        || j                  dz
  k7  rt-        |	«      |_        | j                  j                  |«       �ŒN y )N)r   ©r~   r˜   rš   r›   Trœ   r   )r$   r%   ÚlenÚchannel_multiplierÚnum_resolutionsÚnum_res_blocksÚbase_channelsÚtupleÚin_channel_multiplierr&   Ú
ModuleListÚdownÚrangeÚappendrÅ   Úattn_resolutionsrÌ   r¡   ÚModuleÚblockÚattnÚ
attn_normsrt   Ú
downsample)r+   r    rè   rå   rê   Úi_levelrñ   rò   ró   Úblock_inÚ	block_outÚi_blockrì   r,   s                €r-   r%   zEmu3VQVAEDownBlock.__init__Å  s¢  ø€ Ü‰ÑÔä" 6×#<Ñ#<Ó=ˆÔØ$×3Ñ3ˆÔØ×,Ñ,ˆØ#×6Ñ6Ðà $¤uÐ-?Ó'@Ñ @ÐØ%:ˆÔ"Ü—M‘M“OˆŒ	Ü˜T×1Ñ1Ó2ó 	#ˆGÜ—M‘M“OˆEÜ—=‘=“?ˆDÜŸ™›ˆJØ$Ð'<¸WÑ'EÑEˆHØ%Ð(:¸7Ñ(CÑCˆIÜ  ×!4Ñ!4Ó5ò 
q�Ø—‘Ü(Ø$,Ø%.ôôð %�Ø×*Ñ*Ñ6¸7Àf×F]ÑF]Ò;]Ø—K‘KÔ 7¸Ó ?Ô@Ø×%Ñ%¤b§l¡lÀÐUWÐ]aÐjnÔ&oÕpð
qô —9‘9“;ˆDØˆDŒJØˆDŒIØ(ˆDŒOØ˜$×.Ñ.°Ñ2Ò2Ü"@ÀÓ"J�”Ø�I‰I×Ñ˜TÖ"ñ1	#r.   r/   c                 ó>  — t        | j                  «      D �]  \  }}t        | j                  «      D ]Á  } |j                  |   |«      }t        |j                  «      dkD  sŒ1|} |j                  |   |«      }|j                  \  }}}}	|j                  ||||	z  «      j                  dd«      } |j                  |   |«      d   }|j                  |||	|«      j                  dddd«      }||z   }ŒÃ || j                  dz
  k7  sŒó|j                  |«      }�Œ |S )Nr   r   r   r   )Ú	enumeraterì   rí   rç   rñ   rä   rò   ró   r`   rc   rf   rß   ra   ræ   rô   )
r+   r/   rõ   Úblocksrø   r?   rh   rj   rk   rl   s
             r-   rB   zEmu3VQVAEDownBlock.forwardê  s5  € Ü(¨¯©Ó3ó 	A‰OˆG�VÜ  ×!4Ñ!4Ó5ò =�Ø 5 §¡¨WÑ 5°mÓ D�Ü�v—{‘{Ó# aÓ'Ø,�HØ$> F×$5Ñ$5°gÑ$>¸}Ó$M�Mà:G×:MÑ:MÑ7�J ¨&°%Ø$1×$6Ñ$6°zÀ8ÈVÐV[É^Ó$\×$fÑ$fÐghÐjkÓ$l�MØ$8 F§K¡K°Ñ$8¸Ó$GÈÑ$J�Mà$1×$9Ñ$9¸*ÀfÈeÐU]Ó$^×$fÑ$fÐghÐjkÐmnÐpqÓ$r�MØ$,¨}Ñ$<‘Mð=ð ˜$×.Ñ.°Ñ2Ó2Ø &× 1Ñ 1°-Ó @’ð	Að" Ðr.   ©rC   rD   rE   r%   rG   rK   rB   rL   rM   s   @r-   rá   rá   Ä  s   ø„ ô##ðJ U×%6Ñ%6÷ r.   rá   c                   óV   ‡ — e Zd Zˆ fd„Zdej
                  dej
                  fd„Zˆ xZS )ÚEmu3VQVAEUpBlockc           	      ó¨  •— t         ‰| �  «        t        |j                  «      | _        |j
                  | _        |j                  }|j                  |j                  d   z  }t        j                  «       | _
        t        t        | j                  «      «      D �]5  }t        j                  «       }t        j                  «       }t        j                  «       }|j                  |j                  |   z  }t        | j
                  dz   «      D ]e  }	|j                  t        |||¬«      «       |}||j                  v sŒ1|j                  t!        |«      «       |j                  t#        ||«      «       Œg t        j$                  «       }
||
_        ||
_        ||
_        |dk7  rt-        |«      |
_        | j                  j1                  d|
«       �Œ8 y )Nr\   r   rÙ   r   )r$   r%   rä   rå   ræ   rç   rS   rè   r&   rë   ÚupÚreversedrí   rî   rÅ   rï   rÌ   r—   rð   rñ   rò   ró   rv   ÚupsampleÚinsert)r+   r    rÆ   rö   rõ   rñ   rò   ró   r÷   rø   r   r,   s              €r-   r%   zEmu3VQVAEUpBlock.__init__   s  ø€ Ü‰ÑÔä" 6×#<Ñ#<Ó=ˆÔØ$×3Ñ3ˆÔà×)Ñ)ˆØ×'Ñ'¨&×*CÑ*CÀBÑ*GÑGˆä—-‘-“/ˆŒÜ¤ d×&:Ñ&:Ó ;Ó<ó 	"ˆGÜ—M‘M“OˆEÜ—=‘=“?ˆDÜŸ™›ˆJØ×,Ñ,¨v×/HÑ/HÈÑ/QÑQˆIÜ  ×!4Ñ!4°qÑ!8Ó9ò V�Ø—‘Ü(Ø$,Ø%.Ø'5ôôð %�Ø˜f×5Ñ5Ò5Ø—K‘KÔ 7¸Ó ?Ô@Ø×%Ñ%Ô&:¸>È8Ó&TÕUðVô —‘“ˆBØˆBŒHØˆBŒGØ&ˆBŒMØ˜!Š|Ü:¸8ÓD�”à�G‰G�N‰N˜1˜bÖ!ñ3	"r.   r/   r¦   c                 óh  — t        | j                  d d d…   «      D �]  \  }}t        | j                  dz   «      D ]Ã  } |j                  |   ||«      }t        |j                  «      dkD  sŒ2|} |j                  |   ||«      }|j                  \  }}}	}
|j                  |||	|
z  «      j                  dd«      } |j                  |   |«      d   }|j                  ||	|
|«      j                  dddd«      }||z   }ŒÅ |t        | j                  «      dz
  k7  s�Œ|j                  |«      }�Œ |S )Nr\   r   r   r   r   )rú   r   rí   rç   rñ   rä   rò   ró   r`   rc   rf   rß   ra   r  )r+   r/   r¦   rõ   rû   rø   r?   rh   rj   rk   rl   s              r-   rB   zEmu3VQVAEUpBlock.forward%  sD  € Ü(¨¯©±°2°©Ó7ó 	?‰OˆG�VÜ  ×!4Ñ!4°qÑ!8Ó9ò =�Ø 5 §¡¨WÑ 5°mÀ\Ó R�Ü�v—{‘{Ó# aÓ'Ø,�HØ$> F×$5Ñ$5°gÑ$>¸}ÈlÓ$[�Mà:G×:MÑ:MÑ7�J ¨&°%Ø$1×$6Ñ$6°zÀ8ÈVÐV[É^Ó$\×$fÑ$fÐghÐjkÓ$l�MØ$8 F§K¡K°Ñ$8¸Ó$GÈÑ$J�Mà$1×$9Ñ$9¸*ÀfÈeÐU]Ó$^×$fÑ$fÐghÐjkÐmnÐpqÓ$r�MØ$,¨}Ñ$<‘Mð=ð œ#˜dŸg™g›,¨Ñ*Ô*Ø &§¡°Ó >’ð	?ð  Ðr.   rü   rM   s   @r-   rþ   rþ   ÿ  s(   ø„ ô#"ðJ U×%6Ñ%6ð Àe×FWÑFW÷ r.   rþ   c                   ó>   ‡ — e Zd Zˆ fd„Zdej
                  fd„Zˆ xZS )ÚEmu3VQVAEEncoderc                 ó˜  •— t         ‰| �  «        |j                  }|j                  }|j                  }|j
                  }|j                  }|rd|z  n|}||d   z  }t        j                  j                  ||ddd¬«      | _
        t        |«      | _        t        ||«      | _        t        j                  j                  d|dd¬	«      | _        t        j                  j                  ||ddd¬«      | _        t%        t'        j(                  |j*                  «      «      }	t        j,                  «       | _        t        j,                  «       | _        t3        |	«      D ])  }
t5        ||«      }| j.                  j7                  |«       Œ+ t3        |j8                  «      D ]*  }t;        ||¬
«      }| j0                  j7                  |«       Œ, y )Nr   r\   r   r   rx   rš   r›   T)rž   r�   rŸ   r    rã   )r$   r%   rè   r~   Údouble_latentÚlatent_channelsrå   rG   r&   r|   Úconv_inrá   Ú
down_blockr×   Úmiddle_blockr¡   Únorm_outÚconv_outrF   ÚmathÚlog2Útemporal_downsample_factorrë   Ú	time_convÚtime_res_stackrí   r¶   rî   rç   rº   )r+   r    rè   r~   r  r	  rå   r˜   rö   Útemporal_down_blocksÚir}   Ú_Útime_res_convr,   s                 €r-   r%   zEmu3VQVAEEncoder.__init__:  s”  ø€ Ü‰ÑÔà×,Ñ,ˆØ×(Ñ(ˆØ×,Ñ,ˆØ ×0Ñ0ˆØ#×6Ñ6ÐÙ.;�q˜?Ò*ÀˆØ Ð#5°bÑ#9Ñ9ˆä—x‘x—‘ {°MÈqÐYZÐde�ÓfˆŒÜ,¨VÓ4ˆŒÜ0°¸ÓBˆÔäŸ™×*Ñ*°bÀxÐUYÐbfÐ*ÓgˆŒÜŸ™Ÿ™ØØØØØð (ó 
ˆŒô  #¤4§9¡9¨V×-NÑ-NÓ#OÓPÐÜŸ™›ˆŒÜ Ÿm™m›oˆÔäÐ+Ó,ò 	(ˆAÜ.¨|¸\ÓJˆDØ�N‰N×!Ñ! $Õ'ð	(ô �v×,Ñ,Ó-ò 	6ˆAÜ8Ø(Ø)ôˆMð ×Ñ×&Ñ& }Õ5ñ	6r.   Úpixel_valuesc                 óh  — |j                   d   } |j                  dg|j                   dd  ¢­Ž }| j                  |«      }| j                  |«      }| j	                  |«      }| j                  |«      }|t        j                  |«      z  }| j                  |«      } |j                  d|g|j                   dd  ¢­Ž }|j                  ddddd«      }| j                  D ]"  } ||«      }|t        j                  |«      z  }Œ$ | j                  D ]
  } ||«      }Œ |j                  ddddd«      }|S )Nr   r\   r   r   r   r[   )r`   rß   r
  r  r  r  rG   rÃ   r  ra   r  r  )r+   r  Útemporal_dimr/   r}   Úlayers         r-   rB   zEmu3VQVAEEncoder.forwarda  sH  € Ø#×)Ñ)¨!Ñ,ˆØ+�|×+Ñ+¨BÐH°×1CÑ1CÀAÀBÐ1GÒHˆð Ÿ™ \Ó2ˆØŸ™¨Ó6ˆØ×)Ñ)¨-Ó8ˆð Ÿ™ mÓ4ˆØœŸ™ }Ó5Ñ5ˆØŸ™ mÓ4ˆà-˜×-Ñ-¨b°,ÐYÀ×ATÑATÐUVÐUWÐAXÒYˆØ%×-Ñ-¨a°°A°q¸!Ó<ˆð —N‘Nò 	:ˆDÙ  Ó/ˆMØœUŸ]™]¨=Ó9Ñ9‰Mð	:ð ×(Ñ(ò 	1ˆEÙ! -Ó0‰Mð	1ð &×-Ñ-¨a°°A°q¸!Ó<ˆàÐr.   )rC   rD   rE   r%   rG   rI   rB   rL   rM   s   @r-   r  r  9  s   ø„ ô%6ðN E×$4Ñ$4÷ r.   r  c                   ó\   ‡ — e Zd Zdefˆ fd„Zdej                  dej                  fd„Zˆ xZS )ÚEmu3VQVAEDecoderr    c                 ó¬  •— t         ‰	| �  «        |j                  }|j                  |j                  d   z  }t        j                  «       | _        t        |j                  «      D ]>  }t        |j                  |j                  ¬«      }| j                  j                  |«       Œ@ t        t        j                  |j                   «      «      }t        j                  «       | _        t        |«      D ]=  }t%        |j                  |j                  «      }| j"                  j                  |«       Œ? t        j&                  |j                  |ddd¬«      | _        t+        |||¬«      | _        t/        |«      | _        |j                  |j                  d   z  }t3        ||«      | _        t        j&                  ||j6                  ddd¬«      | _        y )Nr\   rã   r   r   rx   )rÆ   r   )r$   r%   rS   rè   rå   r&   rë   r  rí   rç   rº   r	  rî   rF   r  r  r  r  r¬   r|   r
  r×   r  rþ   Úup_blockr—   r  r˜   r  )
r+   r    rÆ   rö   r  r  Útemp_upsample_block_numr  r}   r,   s
            €r-   r%   zEmu3VQVAEDecoder.__init__€  sŠ  ø€ Ü‰ÑÔà×)Ñ)ˆØ×'Ñ'¨&×*CÑ*CÀBÑ*GÑGˆÜ Ÿm™m›oˆÔÜ�v×,Ñ,Ó-ò 	6ˆAÜ8Ø"×2Ñ2À×AWÑAWôˆMð ×Ñ×&Ñ& }Õ5ð		6ô #&¤d§i¡i°×0QÑ0QÓ&RÓ"SÐÜŸ™›ˆŒÜÐ.Ó/ò 	(ˆAÜ,¨V×-CÑ-CÀV×E[ÑE[Ó\ˆDØ�N‰N×!Ñ! $Õ'ð	(ô —y‘yØ×"Ñ"ØØØØô
ˆŒô 1°¸ÐR`ÔaˆÔÜ(¨Ó0ˆŒà×'Ñ'¨&×*CÑ*CÀAÑ*FÑFˆÜ,¨^¸XÓFˆŒÜŸ	™	ØØ×ÑØØØô
ˆ�r.   r/   r¦   c                 ó¶  — t        j                  ||fd¬«      }|j                  ddddd«      }| j                  D ]
  } ||«      }Œ | j                  D ]"  } ||«      }|t        j
                  |«      z  }Œ$ |j                  ddddd«      }t        j                  |dd¬«      \  }} |j                  dg|j                  dd  ¢­Ž } |j                  dg|j                  dd  ¢­Ž }| j                  |«      }| j                  ||«      }| j                  ||«      }| j                  ||«      }|t        j
                  |«      z  }| j                  |«      }|S )Nr   r_   r   r   r   r[   r\   )rG   Úcatra   r  r  rÃ   Úchunkrß   r`   r
  r  r  r  r  )r+   r/   r¦   Úhidden_quant_statesr  s        r-   rB   zEmu3VQVAEDecoder.forward§  sp  € Ü#Ÿi™i¨¸Ð(EÈ1ÔMÐØ1×9Ñ9¸!¸QÀÀ1ÀaÓHÐð ×(Ñ(ò 	=ˆEÙ"'Ð(;Ó"<Ñð	=ð —^‘^ò 	FˆEÙ"'Ð(;Ó"<ÐØ¤5§=¡=Ð1DÓ#EÑEÑð	Fð 2×9Ñ9¸!¸QÀÀ1ÀaÓHÐÜ&+§k¡kÐ2EÀqÈaÔ&PÑ#ˆ�|Ø-˜×-Ñ-¨bÐK°=×3FÑ3FÀqÀrÐ3JÒKˆØ+�|×+Ñ+¨BÐH°×1CÑ1CÀAÀBÐ1GÒHˆàŸ™ ]Ó3ˆð ×)Ñ)¨-¸ÓFˆØŸ™ m°\ÓBˆàŸ™ m°\ÓBˆØœŸ™ }Ó5Ñ5ˆØŸ™ mÓ4ˆàÐr.   )	rC   rD   rE   r   r%   rG   rH   rB   rL   rM   s   @r-   r  r    s+   ø„ ð%
˜õ %
ðN U§\¡\ð ÀÇÁ÷ r.   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 ([`Emu3VQVAEConfig`]):
            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.
aA  The VQ-VAE model used in Emu3 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                   ó¢   ‡ — e Zd ZeZdZdZdZdZdZ	g d¢Z
d„ Zdefˆ fd„Zdej                  dej                  fd	„Zd
ej                  fd„Zˆ xZS )Ú	Emu3VQVAEÚ
emuvideovqr  T)rº   rÌ   rÅ   rO   c                 óˆ  — t        |t        j                  t        j                  f«      r-t        j                  j                  |j                  dd¬«       y t        |t        j                  «      rÃt        j                  j                  |j                  t        j                  d«      ¬«       |j                  �xt        j                  j                  |j                  «      \  }}|dkD  rdt        j                  |«      z  nd}t        j                  j                  |j                  | |«       y y t        |t        j                  t        j                  t        j                   f«      rUt        j                  j#                  |j                  d«       t        j                  j#                  |j                  d«       y y )NÚfan_outÚrelu)r„   Únonlinearityé   )Úar   r   )Ú
isinstancer&   r|   r�   ÚinitÚkaiming_normal_rU   ÚLinearÚkaiming_uniform_r  ÚsqrtrÔ   Ú_calculate_fan_in_and_fan_outrW   ÚBatchNorm2dr¼   r¡   Ú	constant_)r+   ÚmoduleÚfan_inr  Úbounds        r-   Ú_init_weightszEmu3VQVAE._init_weightsë  s  € Ü�fœrŸy™y¬"¯)©)Ð4Ô5Ü�G‰G×#Ñ# F§M¡M¸	ÐPVÐ#ÕWÜ˜¤§	¡	Ô*Ü�G‰G×$Ñ$ V§]¡]´d·i±iÀ³lÐ$ÔCØ�{‰{Ð&ÜŸG™G×AÑAÀ&Ç-Á-ÓP‘	�˜Ø17¸!²˜œDŸI™I fÓ-Ò-À�Ü—‘× Ñ  §¡¨u¨f°eÕ<ð 'ô ˜¤§¡´·±ÄÇÁÐ NÔOÜ�G‰G×Ñ˜fŸm™m¨QÔ/Ü�G‰G×Ñ˜fŸk™k¨1Õ-ð Pr.   r    c                 óò  •— t         ‰| �  |«       || _        t        |«      | _        t        |«      | _        t        |«      | _        dt        |j                  «      dz
  z  | _        t        |j                  |j                  dd¬«      | _        t        |j                  |j                  dd¬«      | _        dt        |j                  «      dz
  z  | _        | j%                  «        | j'                  «        y )Nr   r   )r   r   r   r¯   r°   )r$   r%   r    r  Úencoderr  ÚdecoderrO   Úquantizerä   rå   Úvision_spatial_factorrŠ   r	  rS   Ú
quant_convÚpost_quant_convÚspatial_scale_factorÚevalÚ	post_initrX   s     €r-   r%   zEmu3VQVAE.__init__ø  sÑ   ø€ Ü‰Ñ˜Ô àˆŒä'¨Ó/ˆŒÜ'¨Ó/ˆŒÜ0°Ó8ˆŒØ%&¬3¨v×/HÑ/HÓ+IÈAÑ+MÑ%NˆÔ"ä)Ø×"Ñ" F×$4Ñ$4À)ÐT]ô
ˆŒô  /Ø×Ñ˜f×4Ñ4À)ÐT]ô 
ˆÔð %&¬#¨f×.GÑ.GÓ*HÈ1Ñ*LÑ$MˆÔ!Ø�	‰	Œà�‰Õr.   Úimage_sizesc                 ó†  — |j                   dk(  }|rL| j                  j                  }|j                  \  }}}}|j	                  d«      j                  d|ddd«      }n|j                  \  }}}}}| j                  |«      }	|	j                  ddddd«      }	| j                  |	«      }	|	j                  ddddd«      }	| j                  |	«      }
|r|
j                  d«      n|
}t        ||«      D ��cg c]B  \  }}|d t        |d   | j                  z  «      …d t        |d   | j                  z  «      …f   ‘ŒD }}}|S c c}}w )Nr[   r   r   r   r   )Úndimr    r  r`   Ú	unsqueezeÚrepeatr<  ra   r@  r>  ÚsqueezerŽ   rF   r?  )r+   r  rE  Úis_imageri   rh   rj   rk   rl   r/   ÚcodesÚimage_tokensÚsingle_imager©   s                 r-   ÚencodezEmu3VQVAE.encode  sX  € Ø×$Ñ$¨Ñ)ˆÙØ—{‘{×=Ñ=ˆHØ2>×2DÑ2DÑ/ˆJ˜ &¨%Ø'×1Ñ1°!Ó4×;Ñ;¸A¸xÈÈAÈqÓQ‰Là<H×<NÑ<NÑ9ˆJ˜ (¨F°EàŸ™ \Ó2ˆð &×-Ñ-¨a°°A°q¸!Ó<ˆØŸ™¨Ó6ˆð &×-Ñ-¨a°°A°q¸!Ó<ˆØ—‘˜mÓ,ˆá+3�u—}‘} QÔ'¸ˆô '*¨,¸Ó&D÷
á"�˜dð ÐDœ3˜t A™w¨×)CÑ)CÑCÓDÐDÐFqÌÈDÐQRÉGÐVZ×VpÑVpÑLpÓHqÐFqÐqÓrð
ˆñ 
ð
 Ðùó
s   Ã1AD=r/   c                 ó¬  — |j                   dk(  }|r|j                  d«      }|j                  \  }}}}| j                  j	                  |j                  «       «      }|j                  d   }|j                  |||||«      j                  ddddd«      j                  «       }| j                  |«      }	|j                  ddddd«      }|	j                  ddddd«      }	| j                  |	|«      }
|
j                  ||| j                  j                  z  | j                  j                  || j                  z  || j                  z  «      }
|r	|
d d …df   S |
S )Nr   r   r\   r   r[   r   )rG  rH  r`   r>  rT   Úflattenrc   ra   rb   rA  r=  rß   r    r  r˜   rB  )r+   r/   rK  rh   ri   rk   rl   Úquantrj   Ú
post_quantÚvideos              r-   ÚdecodezEmu3VQVAE.decode)  sK  € Ø ×%Ñ%¨Ñ*ˆÙØ)×3Ñ3°AÓ6ˆMà.;×.AÑ.AÑ+ˆ
�H˜f eØ—‘×'Ñ'¨×(=Ñ(=Ó(?Ó@ˆà—;‘;˜r‘?ˆØ—
‘
˜: x°¸ÀÓI×QÑQÐRSÐUVÐXYÐ[\Ð^_Ó`×kÑkÓmˆØ×)Ñ)¨%Ó0ˆ
à—‘˜a  A q¨!Ó,ˆØ×'Ñ'¨¨1¨a°°AÓ6ˆ
à—‘˜Z¨Ó/ˆØ—‘ØØ�t—{‘{×=Ñ=Ñ=Ø�K‰K×$Ñ$Ø�T×.Ñ.Ñ.Ø�D×-Ñ-Ñ-ó
ˆñ 'ˆu’Q˜�T‰{Ð1¨EÐ1r.   )rC   rD   rE   r   Úconfig_classÚbase_model_prefixÚmain_input_nameÚ_supports_sdpaÚ_supports_flash_attn_2Ú_supports_flex_attnÚ_no_split_modulesr:  r%   rG   rH   rO  rU  rL   rM   s   @r-   r&  r&  Ö  sj   ø„ ð #€LØ$ÐØ$€OØ€NØ!ÐØÐòÐò.ð˜õ ð* 5§<¡<ð ¸e¿l¹ló ð82 E§L¡L÷ 2r.   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ej                     d
ej                  fd„Zd	ej                  d
ej                  fd„Zy)ÚEmu3ImageVocabularyMappingzM
    A class for mapping discrete image tokens from VQGAN to BPE tokens.
    c                 ój   — || _         |j                  d«      | _        |j                  d«      | _        y )Nz<|extra_200|>z<image>)Ú	vocab_mapÚgetÚeol_token_idÚimage_token_id)r+   r`  s     r-   r%   z#Emu3ImageVocabularyMapping.__init__H  s+   € Ø"ˆŒØ%ŸM™M¨/Ó:ˆÔØ'Ÿm™m¨IÓ6ˆÕr.   c           	      óž   — t        | j                  j                  «       D ��cg c]  \  }}|j                  d«      sŒ|‘Œ c}}«      S c c}}w ©Nz<|visual token©Úsortedr`  ÚitemsÚ
startswith©r+   ÚnameÚvals      r-   rM  z'Emu3ImageVocabularyMapping.image_tokensM  s8   € ä¨D¯N©N×,@Ñ,@Ó,B×h™y˜t SÀdÇoÁoÐVfÕFg’sÓhÓiÐiùÓhó
   £A	
½A	
c           	      óž   — t        | j                  j                  «       D ��cg c]  \  }}|j                  d«      sŒ|‘Œ c}}«      S c c}}w re  rf  rj  s      r-   Úimage_tokens_strz+Emu3ImageVocabularyMapping.image_tokens_strQ  s8   € ä¨T¯^©^×-AÑ-AÓ-C×i¡	  cÀtÇÁÐWgÕGh’tÓiÓjÐjùÓirm  c                 ót   — | j                   D �ci c]  }t        |dd «      | j                  |   “Œ  c}S c c}w )Niøÿÿÿr¨   )ro  rF   r`  )r+   Útokens     r-   Úimg2bpez"Emu3ImageVocabularyMapping.img2bpeU  s5   € àFJ×F[ÑF[Ö\¸U”�E˜"˜R�LÓ! 4§>¡>°%Ñ#8Ñ8Ò\Ð\ùÒ\s   �#5c                 ój   — | j                   j                  «       D ��ci c]  \  }}||“Œ
 c}}S c c}}w r#   )rr  rh  )r+   ÚkÚvs      r-   Úbpe2imgz"Emu3ImageVocabularyMapping.bpe2imgY  s+   € à!%§¡×!3Ñ!3Ó!5×6™˜˜A��1‘Ó6Ð6ùÓ6s   ž/c                 óæ   — t        j                  t        | j                  j	                  «       «      dz   t         j
                  ¬«      }| j                  j                  «       D ]
  \  }}|||<   Œ |S ©Nr   ©Údtype)rG   ÚzerosÚmaxrv  ÚkeysrF   rh  ©r+   Úmappingrt  ru  s       r-   Úbpe2img_mapping_tensorz1Emu3ImageVocabularyMapping.bpe2img_mapping_tensor]  ó[   € ä—+‘+œc $§,¡,×"3Ñ"3Ó"5Ó6¸Ñ:Ä%Ç)Á)ÔLˆØ—L‘L×&Ñ&Ó(ò 	‰DˆAˆqØˆG�AŠJð	àˆr.   c                 óæ   — t        j                  t        | j                  j	                  «       «      dz   t         j
                  ¬«      }| j                  j                  «       D ]
  \  }}|||<   Œ |S rx  )rG   r{  r|  rr  r}  rF   rh  r~  s       r-   Úimg2bpe_mapping_tensorz1Emu3ImageVocabularyMapping.img2bpe_mapping_tensord  r�  r.   Ú	img_batchr7   c                 ó,  — |j                   }t        j                  |j                  d   dft        j                  ¬«      | j
                  z  }| j                  |j                  d«         }t        j                  ||gd¬«      }|j                  |«      S )Nr   r   ry  Úcpur\   r_   )	ÚdevicerG   Úonesr`   rF   rb  rƒ  Útor"  )r+   r„  r‡  Úeol_rowÚ
img_tokenss        r-   Úconvert_img2bpez*Emu3ImageVocabularyMapping.convert_img2bpek  sw   € Ø×!Ñ!ˆÜ—*‘*˜iŸo™o¨aÑ0°!Ð4¼E¿I¹IÔFÈ×IZÑIZÑZˆØ×0Ñ0°·±¸eÓ1DÑEˆ
Ü—Y‘Y 
¨GÐ4¸"Ô=ˆ
Ø�}‰}˜VÓ$Ð$r.   c                 óŠ   — |j                   }|dd d…f   }| j                  |j                  d«         }|j                  |«      S )N.r\   r†  )r‡  r€  r‰  )r+   r„  r‡  r‹  s       r-   Úconvert_bpe2imgz*Emu3ImageVocabularyMapping.convert_bpe2imgr  sG   € Ø×!Ñ!ˆØ˜c 3 B 3˜hÑ'ˆ	Ø×0Ñ0°·±¸eÓ1DÑEˆ
Ø�}‰}˜VÓ$Ð$r.   N)rC   rD   rE   rr   r%   r   rM  ro  rr  rv  r€  rƒ  r   rG   rH   rŒ  rŽ  r9   r.   r-   r^  r^  C  sÅ   „ ñò7ð
 ñjó ðjð ñkó ðkð ñ]ó ð]ð ñ7ó ð7ð ñó ðð ñó ðð%¨¨e¯l©lÑ);ð %ÀÇÁó %ð%¨¯©ð %¸%¿,¹,ô %r.   r^  c                   ó   — e Zd ZdgZdZd„ Zy)ÚEmu3PreTrainedModelr   Tc                 óª  — | j                   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 )Ng        )ÚmeanÚstd)r    Úget_text_configÚinitializer_ranger.  r&  Úapplyr:  r&   r1  r|   rU   rV   Únormal_rÔ   Úzero_rQ   Úpadding_idx)r+   r7  r“  s      r-   r:  z!Emu3PreTrainedModel._init_weights  sñ   € Ø�k‰k×)Ñ)Ó+×=Ñ=ˆÜ�fœiÔ(Ø�L‰L˜×-Ñ-Õ.Ü˜¤§¡¬B¯I©IÐ 6Ô7Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø�{‰{Ð&Ø—‘× Ñ ×&Ñ&Õ(ð 'ä˜¤§¡Ô-Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø×!Ñ!Ð-Ø—‘×"Ñ" 6×#5Ñ#5Ñ6×<Ñ<Õ>ð .ð .r.   N)rC   rD   rE   r\  r[  r:  r9   r.   r-   r�  r�  y  s   „ àðÐð Ðó?r.   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)
        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`.

            Has to be an instance of [`~cache_utils.Cache`] instance, see our
            [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

            The model will output the same cache type that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            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.
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, max_num_images, max_num_tiles, channels, image_size, image_size)):
            The tensors corresponding to the input images. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`Emu3ImageProcessor.__call__`] for details ([]`Emu3Processor`] uses
            [`Emu3ImageProcessor`] for processing images).
        image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
                The sizes of the images in the batch, being (height, width) for each image. Image sizes can be obtained using
            [`AutoImageProcessor`]. See [`Emu3ImageProcessor.__call__`] for details ([]`Emu3Processor`] uses
            [`Emu3ImageProcessor`] for processing images).
        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` or `tuple(tuple(torch.FloatTensor))`, *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`.

            Has to be an instance of [`~cache_utils.Cache`] instance, see our
            [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            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                   óN   ‡ — e Zd Zdefˆ fd„Ze ee«      ˆ fd„«       «       Zˆ xZ	S )ÚEmu3TextModelr    c           	      ó¸   •— t         ‰| �  |«       t        j                  t	        |j
                  «      D �cg c]  }t        ||«      ‘Œ c}«      | _        y c c}w r#   )r$   r%   r&   rë   rí   Únum_hidden_layersr   Úlayersr*   s      €r-   r%   zEmu3TextModel.__init__$  sD   ø€ Ü‰Ñ˜Ô Ü—m‘mÜBGÈ×H`ÑH`ÓBaÖb°YÔ˜f iÕ0Òbó
ˆ�ùÚbs   ·Ac                 ó$   •— t        ‰| �  di |¤Ž y rÉ   ©r$   rB   )r+   Úsuper_kwargsr,   s     €r-   rB   zEmu3TextModel.forward*  s   ø€ ô 	‰‰Ñ'˜,Ó'r.   )
rC   rD   rE   r   r%   r   r   ÚEMU3_TEXT_INPUTS_DOCSTRINGrB   rL   rM   s   @r-   r›  r›  #  s2   ø„ ð
˜zõ 
ð Ù*Ð+EÓFó(ó Gó ô(r.   r›  c                   ó‚   ‡ — e Zd ZeZˆ fd„Ze eddd¬«       ee	«       e
ed¬«      ˆ fd„«       «       «       «       Zˆ xZS )	ÚEmu3ForCausalLMc                 óD   •— t         ‰| �  |«       t        |«      | _        y r#   )r$   r%   r›  ÚmodelrX   s     €r-   r%   zEmu3ForCausalLM.__init__3  s   ø€ Ü‰Ñ˜Ô Ü" 6Ó*ˆ�
r.   Únum_logits_to_keepz4.50Úlogits_to_keep)ÚversionÚnew_namer   ©Úoutput_typerV  c                  ó6   •— t        «       j                  «        y)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]`.

            logits_to_keep (`int` or `torch.Tensor`, *optional*):
                If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
                If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
                This is useful when using packed tensor format (single dimension for batch and sequence length).

        Returns:

        Example:

        ```python
        >>> from transformers import Emu3Processor, Emu3ForConditionalGeneration
        >>> import torch
        >>> import requests
        >>> from PIL import Image

        >>> model = Emu3ForCausalLM.from_pretrained("BAAI/Emu3-Chat-hf", torch_dtype=torch.bfloat16)
        >>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf")

        >>> inputs = processor(text=["Can you write me a poem about winter."], return_tensors="pt").to(model.device)

        >>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
        >>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
        ```Nr   )r¡  r,   s    €r-   rB   zEmu3ForCausalLM.forward7  s   ø€ ôH 	‹�‰Õr.   )rC   rD   rE   r   rV  r%   r   r   r   r¢  r   r   rB   rL   rM   s   @r-   r¤  r¤  0  sV   ø„ Ø!€Lô+ð ÙÐ)°6ÐDTÔUÙ*Ð+EÓFÙÐ+AÐP`Ôaó ó bó Gó Vó ô r.   r¤  c                    óh  ‡ — e Zd ZdgZdZˆ fd„Zd„ Zd„ Zdej                  dej                  fd„Zej                  d	ej                  d
edefd„«       Z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j                     dee   deej                     dee   dee   dee   deej                     deej                     deeej,                  f   defd„«       «       «       Z	 	 	 	 	 	 	 dˆ fd„	Zˆ xZS )ÚEmu3ForConditionalGenerationztext_model.lm_head.weightFc                 óô   •— t         ‰| �  |«       t        j                  |j                  «      | _        t        |j                  «      | _        t        |j                  «      | _        | j                  «        y r#   )r$   r%   r¤  Ú_from_configÚtext_configÚ
text_modelr&  Ú	vq_configÚvqmodelr^  Úvocabulary_mapÚvocabulary_mappingrD  rX   s     €r-   r%   z%Emu3ForConditionalGeneration.__init__b  sY   ø€ Ü‰Ñ˜Ô Ü)×6Ñ6°v×7IÑ7IÓJˆŒÜ  ×!1Ñ!1Ó2ˆŒÜ"<¸V×=RÑ=RÓ"SˆÔð 	�‰Õr.   c                 ó6   — | j                   j                  «       S r#   )r³  Úget_input_embeddings)r+   s    r-   r¹  z1Emu3ForConditionalGeneration.get_input_embeddingsk  s   € Ø�‰×3Ñ3Ó5Ð5r.   c                 ó:   — | j                   j                  |«       y r#   )r³  Úset_input_embeddings)r+   Úvalues     r-   r»  z1Emu3ForConditionalGeneration.set_input_embeddingsn  s   € Ø�‰×,Ñ,¨UÕ3r.   r  rE  c                 óÞ   — | j                   j                  ||«      }|D �cg c]+  }| j                  j                  |«      j	                  «       ‘Œ- }}t        j                  |«      }|S c c}w )a  
        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.
            image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
                The sizes of the images in the batch, being (height, width) for each image.
        )rµ  rO  r·  rŒ  rQ  rG   r"  )r+   r  rE  Úimage_tokens_listÚtokensÚbpe_tokens_listÚ
bpe_tokenss          r-   Úget_image_tokensz-Emu3ForConditionalGeneration.get_image_tokensq  sc   € ð !ŸL™L×/Ñ/°¸kÓJÐØctÖuÐY_˜4×2Ñ2×BÑBÀ6ÓJ×RÑRÕTÐuˆÐuÜ—Y‘Y˜Ó/ˆ
ØÐùò vs   ¡0A*rM  rk   rl   c                 ó°   — |dd…dd…f   j                  d||dz   «      }| j                  j                  |«      }| j                  j	                  |«      }|S )aå  
        Decodes generated image tokens from language model to continuous pixel values
        with VQGAN module via upsampling.

        Args:
            image_tokens (`torch.LongTensor` of shape `(batch_size, num_of_tokens)`):
                The tensors corresponding to the input images.
            height (`int`):
                Height of the generated image before upsampling.
            width (`int`):
                Width of the generated image before upsampling.
        Néýÿÿÿr\   r   )rc   r·  rŽ  rµ  rU  )r+   rM  rk   rl   Ú	sequencesÚimages         r-   Údecode_image_tokensz0Emu3ForConditionalGeneration.decode_image_tokens‚  sX   € ð !¢ C R C Ñ(×-Ñ-¨b°&¸%À!¹)ÓDˆ	Ø×.Ñ.×>Ñ>¸yÓIˆØ—‘×#Ñ# LÓ1ˆØˆr.   r«  Ú	input_idsr0   r1   Úpast_key_valuesÚinputs_embedsr4   r3   Úoutput_hidden_statesr5   Úlabelsr¨  r7   c                 ó°  — |	�|	n| j                   j                  }	|
�|
n| j                   j                  }
|du |duz  rt        d«      ‚|�|�t        d«      ‚|�c| j	                  ||«      }|| j
                  j                  k(  }|j                  |j                  |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]`.

            logits_to_keep (`int` or `torch.Tensor`, *optional*):
                If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
                If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
                This is useful when using packed tensor format (single dimension for batch and sequence length).

        Returns:

        Example:

        ```python
        >>> from transformers import Emu3Processor, Emu3ForConditionalGeneration
        >>> import torch
        >>> import requests
        >>> from PIL import Image

        >>> model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", torch_dtype=torch.bfloat16)
        >>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf")

        >>> conversation = [
        ...     {
        ...     "role": "system",
        ...     "content": [
        ...         {"type": "text", "text": "You are a helpful assistant."},
        ...         ],
        ...     },
        ...     {
        ...     "role": "user",
        ...     "content": [
        ...         {"type": "image"},
        ...         {"type": "text", "text": "Please describe the image."},
        ...         ],
        ...     },
        ... ]

        >>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
        >>> image = Image.open(requests.get("https://www.ilankelman.org/stopsigns/australia.jpg", stream=True).raw)

        >>> inputs = processor(images=[image], 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]
        ```NzaYou cannot specify both input_ids and inputs_embeds at the same time, and must specify either onezdYou cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one)
rÈ  r0   r1   rÉ  rÊ  r4   r3   rË  r5   r¨  )r    r3   rË  Ú
ValueErrorrÂ  r·  rc  r‰  r‡  rz  Úmasked_scatterr³  )r+   rÈ  r  rE  r0   r1   rÉ  rÊ  r4   r3   rË  r5   rÌ  r¨  rM  Úspecial_image_masks                   r-   rB   z$Emu3ForConditionalGeneration.forward•  s  € ðJ 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð ˜Ð -°tÐ";Ò<ÜØsóð ð Ð#¨Ð(AÜØvóð ð Ð#Ø×0Ñ0°¸{ÓKˆLØ!*¨d×.EÑ.E×.TÑ.TÑ!TÐØ'Ÿ?™?¨9×+;Ñ+;¸Y¿_¹_ÓMˆLØ!×0Ñ0Ð1CÀ\ÓRˆIð �‰ØØ)Ø%Ø+Ø'ØØ/Ø!5Ø)Ø)ð ó 
ð 	
r.   c	                 óR   •— t        ‰| �  |f|||||||dœ|	¤Ž}
|d   dk7  rd |
d<   |
S )N)rÉ  r0   rÊ  r5   r1   r  r4   r   r  )r$   Úprepare_inputs_for_generation)r+   rÈ  rÉ  r0   rÊ  r5   r1   r4   r  r>   Úmodel_inputsr,   s              €r-   rÒ  z:Emu3ForConditionalGeneration.prepare_inputs_for_generationý  sZ   ø€ ô ‘wÑ<Øð

à+Ø)Ø'Ø)Ø%Ø%Øñ

ð ñ

ˆð ˜!Ñ Ò!Ø+/ˆL˜Ñ(àÐr.   )NNNNNNNNNNNNr   )NNNNNTN)rC   rD   rE   Ú_tied_weights_keysÚ_supports_static_cacher%   r¹  r»  rG   rK   rI   rÂ  Úno_gradrF   rÇ  r   r   ÚEMU3_INPUTS_DOCSTRINGr   r   Ú_CONFIG_FOR_DOCr   rH   r	   rJ   r   rB   rÒ  rL   rM   s   @r-   r¯  r¯  ^  s   ø„ Ø5Ð6ÐØ"Ðôò6ò4ð¨U×->Ñ->ð ÈU×M]ÑM]ó ð" ‡]�]ð°×0@Ñ0@ð È#ð ÐVYò ó ðð$ Ù*Ð+@ÓAÙÐ+AÐP_Ô`ð 15Ø48Ø.2Ø15Ø37Ø+/Ø59Ø$(Ø,0Ø/3Ø59Ø-1Ø34ñc
à˜E×,Ñ,Ñ-ðc
ð ˜u×0Ñ0Ñ1ðc
ð ˜eŸl™lÑ+ð	c
ð
 ! §¡Ñ.ðc
ð ˜u×/Ñ/Ñ0ðc
ð " %™ðc
ð   × 1Ñ 1Ñ2ðc
ð ˜D‘>ðc
ð $ D™>ðc
ð ' t™nðc
ð ! ×!1Ñ!1Ñ2ðc
ð ˜×)Ñ)Ñ*ðc
ð ˜c 5§<¡<Ð/Ñ0ðc
ð 
 òc
ó aó Bó ðc
ðP ØØØØØØ÷ñ r.   r¯  )r¯  r¤  r›  r�  r&  )Nr  Ú	functoolsr   Útypingr   r   r   r   rG   Útorch.nnr&   Útorch.nn.functionalÚ
functionalr…   Útorch.utils.checkpointÚcache_utilsr	   Ú
generationr
   Úmodeling_outputsr   Úmodeling_utilsr   Úutilsr   r   r   r   r   Úutils.deprecationr   Úchameleon.modeling_chameleonr   r   Úllama.modeling_llamar   r   r   Úsiglip.modeling_siglipr   Úconfiguration_emu3r   r   r   rØ  Ú_CHECKPOINT_FOR_DOCÚ
get_loggerrC   Úloggerr   rð   rO   rt   rv   rŠ   r—   r¬   r¶   rº   rÅ   rÌ   r¡   rÐ   r×   rá   rþ   r  r  ÚEMU3_VQ_START_DOCSTRINGr&  r^  r�  r¢  r×  r›  r¤  r¯  Ú__all__r9   r.   r-   ú<module>rî     s1  ðó" Ý %ß /Ó /ã Ý ß Ð Û å  Ý )õõ .÷õ õ 1÷÷ñ õ
 5ß KÑ Kð €Ø)Ð à	ˆ×	Ñ	˜HÓ	%€ôAÐ(ô AôH$˜rŸy™yô $ôD	Ð%Hô 	ô 2§9¡9ô ô�b—i‘iô ô:!˜2Ÿ9™9ô !ôH §	¡	ô ô. "§)¡)ô ô&.( 2§9¡9ô .(ôb<(˜2Ÿ9™9ô <(ô~&˜oô &ôV˜Ÿ™ô Vô˜2Ÿ9™9ô ôD8˜Ÿ™ô 8ôv7�r—y‘yô 7ôtC�r—y‘yô CôLC�r—y‘yô CðLÐ ñ" ðð óôc2�ó c2óðc2÷L3%ñ 3%ôl?Ð2°Iô ?ð(DÐ ðNLÐ ô^
(�JÐ 3ô 
(ô+Ð&Ð(;¸_ô +ô\|Ð#6¸ô |ò~�r.   