
    cCii                     P   S SK r S SKJr  S SKJrJrJr  S SKrS SKJ	r	  S SK
J	s  Jr  SSKJr  SSKJrJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJrJr  SSKJrJr  SSK J!r!J"r"  SSK#J$r$  SSK%J&r&J'r'J(r(  SSK)J*r*  SSK+J,r,  SSK-J.r.J/r/J0r0  S r1S_S jr2S\Rf                  S\4S\Rf                  4S jr5 S`S\	Rl                  S\Rf                  S\Rf                  S\Rf                  S\\Rf                     S\7S \7S!\$\&   4S" jjr8 " S# S$\	Rl                  5      r9\" S%5       " S& S'\	Rl                  5      5       r: " S( S)\	Rl                  5      r; " S* S+\5      r< " S, S-\	Rl                  5      r= " S. S/\	Rl                  5      r> " S0 S1\	Rl                  5      r? " S2 S3\	Rl                  5      r@ " S4 S5\	Rl                  5      rA " S6 S7\	Rl                  5      rB " S8 S9\	Rl                  5      rC " S: S;\	Rl                  5      rD " S< S=\	Rl                  5      rE " S> S?\	Rl                  5      rF " S@ SA\	R                  5      rH " SB SC\	Rl                  5      rI " SD SE\	Rl                  5      rJ " SF SG\	Rl                  5      rK " SH SI\	Rl                  5      rL " SJ SK\	Rl                  5      rM\'" SLSM9 " SN SO\"5      5       rN " SP SQ5      rO\' " SR SS\"5      5       rP " ST SU\	Rl                  5      rQ\' " SV SW\P5      5       rR\' " SX SY\P\5      5       rS " SZ S[\P5      rT " S\ S]\P\5      rU/ S^QrVg)a    N)cached_property)CallableOptionalUnion   )ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hub)create_causal_mask)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuple)deprecate_kwarg)check_model_inputs   )
Emu3ConfigEmu3TextConfigEmu3VQVAEConfigc                     U SSU R                   S   S-  24   nU SU R                   S   S-  S24   n[        R                  " U* U4SS9$ )z*Rotates half the hidden dims of the input..N   dim)shapetorchcat)xx1x2s      `/home/james-whalen/.local/lib/python3.13/site-packages/transformers/models/emu3/modeling_emu3.pyrotate_halfr+   /   sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''    c                     UR                  U5      nUR                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nXg4$ )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kcossinposition_idsunsqueeze_dimq_embedk_embeds           r*   apply_rotary_pos_embr7   6   sS    ( --
&C
--
&Cw;q>C/0Gw;q>C/0Gr,   hidden_statesn_repreturnc                     U R                   u  p#pEUS:X  a  U $ U SS2SS2SSS2SS24   R                  X#XU5      n U R                  X#U-  XE5      $ )z
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
r   N)r$   expandreshape)r8   r9   batchnum_key_value_headsslenhead_dims         r*   	repeat_kvrB   Q   s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr,   modulequerykeyvalueattention_maskscalingdropoutkwargsc                 @   [        X R                  5      n[        X0R                  5      n	[        R                  " XR	                  SS5      5      U-  n
Ub"  US S 2S S 2S S 2S UR
                  S   24   nX-   n
[        R                  R                  U
S[        R                  S9R                  UR                  5      n
[        R                  R                  XU R                  S9n
[        R                  " X5      nUR	                  SS5      R                  5       nX4$ )Nr!   r   r    )r#   dtype)ptrainingr   )rB   num_key_value_groupsr%   matmul	transposer$   nn
functionalsoftmaxfloat32torM   rI   rO   
contiguous)rC   rD   rE   rF   rG   rH   rI   rJ   
key_statesvalue_statesattn_weightscausal_maskattn_outputs                r*   eager_attention_forwardr^   ]   s     3 ; ;<JU$?$?@L<<';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#1==((2U]](SVVW\WbWbcL==((6??([L,,|:K''1-88:K$$r,   c                   4  ^  \ rS rSrSrS\S\4U 4S jjr\" SSSS	9  SS
\	R                  S\\	R                  \	R                  4   S\\	R                     S\\   S\\	R                     S\\   S\\	R                  \	R                  4   4S jj5       rSrU =r$ )Emu3Attentionw   =Multi-headed attention from 'Attention Is All You Need' paperconfig	layer_idxc                 P  > [         TU ]  5         Xl        X l        [	        USUR
                  UR                  -  5      U l        UR                  UR                  -  U l	        U R                  S-  U l
        UR                  U l        SU l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR                  U R                  -  UR
                  UR                  S9U l        g )NrA         Tbias)super__init__rc   rd   getattrhidden_sizenum_attention_headsrA   r?   rP   rH   attention_dropout	is_causalrS   Linearattention_biasq_projk_projv_projo_projselfrc   rd   	__class__s      r*   rj   Emu3Attention.__init__z   sI   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
r,   past_key_valuepast_key_values4.58new_nameversionr8   position_embeddingsrG   cache_positionrJ   r:   c                 4   UR                   S S n/ UQSPU R                  P7nU R                  U5      R                  U5      R	                  SS5      n	U R                  U5      R                  U5      R	                  SS5      n
U R                  U5      R                  U5      R	                  SS5      nUu  p[        XX5      u  pUb$  XUS.nUR                  XU R                  U5      u  p[        nU R                  R                  S:w  a  [        U R                  R                     nU" U U	U
UU4U R                  (       d  SOU R                  U R                   S.UD6u  nnUR"                  " / UQSP76 R%                  5       nU R'                  U5      nUU4$ )Nr    r   r!   )r2   r1   r   eager        )rI   rH   )r$   rA   rr   viewrR   rs   rt   r7   updaterd   r^   rc   _attn_implementationr   rO   rn   rH   r=   rX   ru   )rw   r8   r   rG   r{   r   rJ   input_shapehidden_shapequery_statesrY   rZ   r1   r2   cache_kwargsattention_interfacer]   r[   s                     r*   forwardEmu3Attention.forward   s    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&#7RU#[ &#&nUL'6'='=jX\XfXfht'u$J(?;;++w6"9$++:Z:Z"[$7	%
  $}}C$2H2HLL	%
 	%
!\ "));;;;FFHkk+.L((r,   )rn   rc   rA   ro   rs   rd   rP   ru   rr   rH   rt   NN)__name__
__module____qualname____firstlineno____doc__r   intrj   r   r%   Tensortupler   r	   
LongTensorr   r   r   __static_attributes____classcell__rx   s   @r*   r`   r`   w   s    G
z 
c 
. %0A6R ,059))||)) #5<<#=>)) !.	))
 "%)) !!1!12)) +,)) 
u||U\\)	*)) S))r,   r`   RMSNormc                   8   ^  \ rS rSrSU 4S jjrS rS rSrU =r$ )Emu3RMSNorm   c                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z*
Emu3RMSNorm is equivalent to T5LayerNorm
N)ri   rj   rS   	Parameterr%   onesweightvariance_epsilon)rw   rl   epsrx   s      r*   rj   Emu3RMSNorm.__init__   s/     	ll5::k#:; #r,   c                    UR                   nUR                  [        R                  5      nUR	                  S5      R                  SSS9nU[        R                  " X0R                  -   5      -  nU R                  UR                  U5      -  $ )Nr!   r    T)keepdim)	rM   rW   r%   rV   powmeanrsqrtr   r   )rw   r8   input_dtypevariances       r*   r   Emu3RMSNorm.forward   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::r,   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)r   r   r$   r   rw   s    r*   
extra_reprEmu3RMSNorm.extra_repr   s*    ))*+6$2G2G1HIIr,   )r   r   )ư>)	r   r   r   r   rj   r   r   r   r   r   s   @r*   r   r      s    $;J Jr,   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )Emu3MLP   c                   > [         TU ]  5         Xl        UR                  U l        UR                  U l        [
        R                  " U R                  U R                  UR                  S9U l        [
        R                  " U R                  U R                  UR                  S9U l	        [
        R                  " U R                  U R                  UR                  S9U l
        [        UR                     U l        g )Nrg   )ri   rj   rc   rl   intermediate_sizerS   rp   mlp_bias	gate_projup_proj	down_projr   
hidden_actact_fnrw   rc   rx   s     r*   rj   Emu3MLP.__init__   s    !--!'!9!94#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r,   c                     U R                  U R                  U R                  U5      5      U R                  U5      -  5      nU$ N)r   r   r   r   )rw   r'   r   s      r*   r   Emu3MLP.forward   s6    NN4;;t~~a/@#ADLLQRO#ST	r,   )r   rc   r   r   rl   r   r   r   r   r   r   rj   r   r   r   r   s   @r*   r   r      s    0 r,   r   c                   H  ^  \ rS rSrS\S\4U 4S jjr\" SSSS9      SS	\R                  S
\
\R                     S\
\R                     S\
\   S\
\   S\
\R                     S\
\\R                  \R                  4      S\\   S\R                  4S jj5       rSrU =r$ )Emu3DecoderLayer   rc   rd   c                 V  > [         TU ]  5         UR                  U l        [        XS9U l        [        U5      U l        [        UR                  UR                  S9U l	        [        UR                  UR                  S9U l
        [        R                  " UR                  5      U l        g )N)rc   rd   r   )ri   rj   rl   r`   	self_attnr   mlpr   rms_norm_epsinput_layernormpost_attention_layernormrS   Dropoutrn   rI   rv   s      r*   rj   Emu3DecoderLayer.__init__   s    !--&fJ6?*6+=+=6CVCVW(3F4F4FFL_L_(`%zz&":":;r,   rz   r{   r|   r}   r8   rG   r3   	use_cacher   r   rJ   r:   c                     Un	U R                  U5      nU R                  " SUUUUUUUS.UD6u  pXR                  U5      -   nUn	U R                  U5      nU R	                  U5      nXR                  U5      -   nU$ )N)r8   rG   r3   r{   r   r   r    )r   r   rI   r   r   )rw   r8   rG   r3   r{   r   r   r   rJ   residual_s              r*   r   Emu3DecoderLayer.forward   s     !,,];>> 	
')%+) 3	
 	
 !<<#>> 55mD/ <<#>>r,   )rI   rl   r   r   r   r   )NNNFNN)r   r   r   r   r   r   rj   r   r%   r   r   r   r	   boolr   r   r   r   r   r   r   s   @r*   r   r      s    	<z 	<c 	< %0A6R 2637+/$)59KO|| !. u//0	
 "% D> !!1!12 &eELL%,,,F&GH +, 
 Sr,   r   c                   V   ^  \ rS rSrSrS\4U 4S jjrS\R                  4S jr	Sr
U =r$ )Emu3VQVAEVectorQuantizeri  a  
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.
rc   c                   > [         TU ]  5         [        R                  " UR                  UR
                  5      U l        U R                  R                  R                  R                  SUR                  -  SUR                  -  5        g )Ng            ?)
ri   rj   rS   	Embeddingcodebook_size	embed_dim	embeddingr   datauniform_r   s     r*   rj   !Emu3VQVAEVectorQuantizer.__init__  sb    f&:&:F<L<LM""++D63G3G,GvOcOcIcdr,   hidden_statec                    UR                   u  p#pEnUR                  SSSSS5      R                  5       nUR                  SU5      n[        R
                  " US-  SSS9n[        R
                  " U R                  R                  S-  SS	9n	S[        R                  " XpR                  R                  R                  SS5      5      -  n
X-   U
-
  n
[        R                  " U
SS	9nUR                  X#XV5      nU$ )
Nr   r   r      r!   r    T)r#   r   r"   )r$   permuterX   r   r%   sumr   r   rQ   rR   argmin)rw   r   
batch_sizetemporalchannelsheightwidthhidden_state_flattenedhidden_state_sumembedding_sum	distancesmin_encoding_indicess               r*   r    Emu3VQVAEVectorQuantizer.forward!  s    8D8J8J5
h#++Aq!Q:EEG!-!2!22x!@ !99%;Q%>AtT		$.."7"7":B %;^^=R=R=\=\]^`a=bcc	$4y@	$||I1=388v]##r,   )r   )r   r   r   r   r   r   rj   r%   r   r   r   r   r   s   @r*   r   r     s+    e e
$ELL $ $r,   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )Emu3VQVAEEncoderConvDownsamplei3  c                 Z   > [         TU ]  5         [        R                  " XSSSS9U l        g )Nr   r!   r   kernel_sizestridepaddingri   rj   rS   Conv2dconvrw   in_channelsrx   s     r*   rj   'Emu3VQVAEEncoderConvDownsample.__init__4  %    IIkAaYZ[	r,   c                 V    [         R                  " USSSS9nU R                  U5      nU$ )N)r   r   r   r   constantr   )padmoderF   )Fr  r   rw   r8   s     r*   r   &Emu3VQVAEEncoderConvDownsample.forward8  s+    mJVWX		-0r,   r   r   r   s   @r*   r   r   3  s    \ r,   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )Emu3VQVAEEncoderConvUpsamplei?  c                 Z   > [         TU ]  5         [        R                  " XSSSS9U l        g )Nr   r   r   r   r   s     r*   rj   %Emu3VQVAEEncoderConvUpsample.__init__@  r  r,   c                 T    [         R                  " USSS9nU R                  U5      nU$ )N       @nearestscale_factorr  )r  interpolater   r  s     r*   r   $Emu3VQVAEEncoderConvUpsample.forwardD  s(    m#IV		-0r,   r	  r   r   s   @r*   r  r  ?  s    \ r,   r  c            	       j   ^  \ rS rSrS\S\S\\   S\\   4U 4S jjrS\R                  4S jr	S	r
U =r$ )
Emu3VQVAEConv3diJ  
in_channelout_channelr   r   c                 R  > [         T	U ]  5         [        USS  USS  5       VVs/ s H	  u  pVXV-
  PM     nnnSU l        US S S2    H&  nU =R                  US-  US-  -   US-  4-  sl        M(     U =R                  S-  sl        [        R
                  " UUUUS9U l        g s  snnf )Nr   r   r    r!   )r!   r   )r   )ri   rj   zipr   rS   Conv3dr   )
rw   r  r  r   r   
one_kernel
one_stridepadding_sizespad_sizerx   s
            r*   rj   Emu3VQVAEConv3d.__init__K  s     	ORS^_`_aSbdjklkmdnOopOo5KZ0Oop%dd+HLLX]X\98q=IIL ,II	
	 qs   B#r8   c                 h    [         R                  " XR                  5      nU R                  U5      nU$ r   )r  r  r   r   r  s     r*   r   Emu3VQVAEConv3d.forwarda  s(    m\\:		-0r,   )r   r   )r   r   r   r   r   r   rj   r%   r   r   r   r   r   s   @r*   r  r  J  sK    

 
 3Z	

 c

,U\\  r,   r  c                   n   ^  \ rS rSrS\S\4U 4S jjrS\R                  S\R                  4S jrSr	U =r
$ )	Emu3VQVAESpatialNormig  r   out_channelsc                    > [         TU ]  5         [        R                  " USSSS9U l        [        R
                  " UUSSSS9U l        [        R
                  " UUSSSS9U l        g )N    r   Tnum_channels
num_groupsr   affiner   r   r   )ri   rj   rS   	GroupNorm
norm_layerr   conv_yconv_brw   r   r%  rx   s      r*   rj   Emu3VQVAESpatialNorm.__init__h  sn    
 	,,%	
 ii
 ii
r,   r8   quant_statesc                     [         R                  " X!R                  SS  SS9nU R                  U5      nXR	                  U5      -  U R                  U5      -   nU$ )NrL   r  )sizer  )r  r  r$   r-  r.  r/  )rw   r8   r2  s      r*   r   Emu3VQVAESpatialNorm.forward  sT    }}\8K8KBC8PW`a6%L(AADKKP\D]]r,   )r/  r.  r-  r   r   r   r   r   rj   r%   r   r   r   r   r   s   @r*   r$  r$  g  s:    

 
8U\\   r,   r$  c                   V   ^  \ rS rSrS\S\4U 4S jjrS\R                  4S jrSr	U =r
$ )Emu3VQVAETemporalUpsamplei  r  r  c                 D   > [         TU ]  5         [        UUSSS9U l        g )Nr   r   r   r   r   r   r   r   ri   rj   r  r   rw   r  r  rx   s      r*   rj   "Emu3VQVAETemporalUpsample.__init__  (    
 	#!	
	r,   r8   c                 D   UR                   u  p#pEnUR                  SSSSS5      R                  5       R                  USU5      n[        R
                  " USSS	9nUR                  X#XVS5      R                  SSSSS5      R                  5       nU R                  U5      nU$ )
Nr   r   r   r   r!   r    r  r  r  )r$   r   rX   r   r  r  r   )rw   r8   r   r   r   r   r   s          r*   r   !Emu3VQVAETemporalUpsample.forward  s    8E8K8K5
h%--aAq!<GGINNz[]_ghm#IV%**:PRS[[\]_`bcefhijuuw		-0r,   r	  r6  r   s   @r*   r8  r8    s/    

 
U\\  r,   r8  c                   V   ^  \ rS rSrS\S\4U 4S jjrS\R                  4S jrSr	U =r
$ )Emu3VQVAETemporalDownsamplei  r  r  c                 D   > [         TU ]  5         [        UUSSS9U l        g )N)r   r   r   )r!   r   r   r<  r=  r>  s      r*   rj   $Emu3VQVAETemporalDownsample.__init__  r@  r,   r8   c                 (    U R                  U5      nU$ r   r	  r  s     r*   r   #Emu3VQVAETemporalDownsample.forward  s    		-0r,   r	  r6  r   s   @r*   rD  rD    s/    

 
U\\  r,   rD  c                   4   ^  \ rS rSr SU 4S jjrS rSrU =r$ )Emu3VQVAETemporalResnetBlocki  c                 f  > [         TU ]  5         Xl        Uc  UOUU l        [        R
                  " U5      U l        [        UUSSS9U l        [        R
                  " U5      U l	        [        UUSSS9U l
        U R                  U R                  :w  a  [        R                  " UUSSSS9U l        g g )Nr:  r;  r<  r   r   r   )ri   rj   r   r%  rS   BatchNorm3dnorm1r  conv1norm2conv2r  nin_shortcutr0  s      r*   rj   %Emu3VQVAETemporalResnetBlock.__init__  s    
 	&+7+?K\^^K0
$!	

 ^^L1
$!	

 t000 "		!D 1r,   c                 P   UnU R                  U5      nU[        R                  " U5      -  nU R                  U5      nU R	                  U5      nU[        R                  " U5      -  nU R                  U5      nU R                  U R                  :w  a  U R                  U5      nX!-   $ r   )	rM  r%   sigmoidrN  rO  rP  r   r%  rQ  )rw   r8   r   s      r*   r   $Emu3VQVAETemporalResnetBlock.forward  s     

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

=1

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

=1t000((2H''r,   )rN  rP  r   rQ  rM  rO  r%  r   r   r   s   @r*   rJ  rJ    s     @( (r,   rJ  c                      ^  \ rS rSr  S	S\S\\   S\\   4U 4S jjjrS
S\R                  S\\R                     4S jjr	Sr
U =r$ )Emu3VQVAEResnetBlocki  r   r%  quant_channelsc                   > [         TU ]  5         Xl        Uc  UOUnX l        X0l        Uc9  [
        R                  " USSSS9U l        [
        R                  " USSSS9U l        O [        X15      U l        [        X25      U l        [
        R                  " UUSSSS9U l        [
        R                  " UUSSSS9U l        U R                  U R                  :w  a  [
        R                  " UUSSSS9U l        g g )	Nr'  r   Tr(  r   r   r   r   )ri   rj   r   r%  rX  rS   r,  rM  rO  r$  r   rN  rP  rQ  )rw   r   r%  rX  rx   s       r*   rj   Emu3VQVAEResnetBlock.__init__  s     	&&2&:{(,!;2SW`deDJ<BTXaefDJ-nJDJ-nKDJYY

 YY

 t000 "		!D 1r,   r8   c                 |   U R                   c  SOU4nUnU R                  " U/UQ76 nU[        R                  " U5      -  nU R	                  U5      nU R
                  " U/UQ76 nU[        R                  " U5      -  nU R                  U5      nU R                  U R                  :w  a  U R                  U5      nXA-   $ Nr   )
rX  rM  r%   rT  rN  rO  rP  r   r%  rQ  )rw   r8   rX  	norm_argsr   s        r*   r   Emu3VQVAEResnetBlock.forward  s    --5BN;L	 

==9=}55

=1

==9=}55

=1t000((2H''r,   )rN  rP  r   rQ  rM  rO  r%  rX  r   r   )r   r   r   r   r   r   rj   r%   r   r   r   r   r   s   @r*   rW  rW    s_     '+(,	** sm* !	* *X(U\\ (8ELLCY ( (r,   rW  c            
          ^  \ rS rSrSrS\4U 4S jjr S
S\R                  S\	\R                     S\
\R                  \	\R                     4   4S jjrS	rU =r$ )Emu3VQVAEAttentionBlocki%  rb   rc   c                 .  > [         TU ]  5         Xl        UR                  U l        UR
                  U l        U R                  U R                  -  U l        U R                  U R                  -  U R                  :w  a&  [        SU R                   SU R                   S35      eU R                  S-  U l	        UR                  U l        SU l        [        R                  " U R                  U R                  5      U l        [        R                  " U R                  U R                  5      U l        [        R                  " U R                  U R                  5      U l        [        R                  " U R                  U R                  5      U l        SU l        g )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).rf   Fr   )ri   rj   rc   rl   r   rm   	num_headsrA   
ValueErrorscalern   rI   ro   rS   rp   rs   rt   rr   out_projrP   r   s     r*   rj    Emu3VQVAEAttentionBlock.__init__(  s"   ++33$..8==4>>)T^^;MdnnM] ^NN#2'  ]]D(
//ii?ii?ii?		$..$..A %&!r,   r8   rG   r:   c                 2   UR                   u  pEnU R                  U5      nU R                  U5      nU R                  U5      n	UR	                  XEU R
                  U R                  5      R                  SS5      nUR	                  XEU R
                  U R                  5      R                  SS5      nU	R	                  XEU R
                  U R                  5      R                  SS5      n	[        n
U R                  R                  S:w  a  [        U R                  R                     n
U
" U UUU	UU R                  U R                  U R                  (       d  SOU R                  S9u  pUR!                  XEU5      R#                  5       nU R%                  U5      nX4$ )z#Input shape: Batch x Time x Channelr   r!   r   r   )ro   rH   rI   )r$   rr   rs   rt   r   rb  rA   rR   r^   rc   r   r   ro   rd  rO   rI   r=   rX   re  )rw   r8   rG   rJ   r   
seq_lengthr   querieskeysvaluesr   r]   r[   s                r*   r   Emu3VQVAEAttentionBlock.forward?  sS    -:,?,?)
	++m,{{=)]+,,zt~~t}}U__`acdeyyOYYZ[]^_ZT^^T]]S]]^_abc(?;;++w6"9$++:Z:Z"[$7nnJJ#}}C$,,	%
! "))*)LWWYmmK0((r,   )rc   rI   r   rA   ro   rs   rb  rP   re  rr   rd  rt   r   )r   r   r   r   r   r   rj   r%   r   r   r   r   r   r   r   s   @r*   r`  r`  %  sa    G& &4 26$)||$) !.$)
 
u||Xell33	4$) $)r,   r`  c                   6   ^  \ rS rSrSrU 4S jrSS jrSrU =r$ )Emu3VQVAEGroupNormif  z
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U ]  " S0 UD6  g r\  )ri   rj   )rw   rJ   rx   s     r*   rj   Emu3VQVAEGroupNorm.__init__m  s    "6"r,   c                     [         R                  " XR                  U R                  U R                  U R
                  5      $ r   )r  
group_normr*  r   rh   r   )rw   inputr2  s      r*   r   Emu3VQVAEGroupNorm.forwardp  s'    ||E??DKKDHHUUr,   r   r   )	r   r   r   r   r   rj   r   r   r   r   s   @r*   rn  rn  f  s    #V Vr,   rn  c                   p   ^  \ rS rSrSU 4S jjrSS\R                  S\\R                     4S jjrSr	U =r
$ )Emu3VQVAEMiddleBlockit  c                    > [         TU ]  5         [        UUUS9U l        [	        U5      U l        Uc  [        USSSS9U l        O[        X25      U l        [        UUUS9U l	        g )Nr   r%  rX  r'  r   Tr(  )
ri   rj   rW  block_1r`  attn_1rn  	attn_normr$  block_2)rw   rc   r   rX  rx   s       r*   rj   Emu3VQVAEMiddleBlock.__init__u  sm    +#$)

 .f5!/[UW]ajnoDN1.NDN+#$)
r,   r8   r2  c                 N   U R                  X5      nUnU R                  X5      nUR                  u  pEpgUR                  XEXg-  5      R	                  SS5      nU R                  U5      S   nUR                  XFXu5      R                  SSSS5      nX1-   nU R                  X5      nU$ )Nr   r!   r   r   )	ry  r{  r$   r   rR   rz  r=   r   r|  )rw   r8   r2  r   r   r   r   r   s           r*   r   Emu3VQVAEMiddleBlock.forward  s    ]A }C.;.A.A+
f%**:PZZ[\^_`M215%--j%RZZ[\^_abdef 0]Ar,   )rz  r{  ry  r|  r   )r   r   r   r   rj   r%   FloatTensorr   r   r   r   r   s   @r*   rv  rv  t  s1    
(
U%6%6 
huO`O`Fa 
 
r,   rv  c                   J   ^  \ rS rSrU 4S jrS\R                  4S jrSrU =r	$ )Emu3VQVAEDownBlocki  c                   > [         TU ]  5         [        UR                  5      U l        UR
                  U l        UR                  nUR                  nS[        U5      -   nX@l        [        R                  " 5       U l        [        U R                  5       GHL  n[        R                  " 5       n[        R                  " 5       n[        R                  " 5       nX$U   -  n	X#U   -  n
[        U R
                  5       H~  nUR                  [        U	U
S95        U
n	UR                  c  M-  XQR                  ;   d  M>  UR                  [!        U5      5        UR                  [        R"                  " U	SSSS95        M     [        R$                  " 5       nXll        X|l        Xl        XPR                  S-
  :w  a  [-        U	5      Ul        U R                  R                  U5        GMO     g )N)r   r   r%  r'  r   Tr(  r   )ri   rj   lenchannel_multipliernum_resolutionsnum_res_blocksbase_channelsr   in_channel_multiplierrS   
ModuleListdownrangeappendrW  attn_resolutionsr`  r,  Moduleblockattn
attn_normsr   
downsample)rw   rc   r  r  r  i_levelr  r  r  block_in	block_outi_blockr  rx   s                r*   rj   Emu3VQVAEDownBlock.__init__  s   "6#<#<=$33,,#66 $u-?'@ @%:"MMO	T112GMMOE==?DJ$W'EEH%7(CCI !4!45($,%. %**67F]F];]KK 7 ?@%%bllUW]ajn&op 6 99;DJI(O..22"@"JIIT"1 3r,   r8   c                 <   [        U R                  5       GH  u  p#[        U R                  5       H  nUR                  U   " U5      n[        UR                  5      S:  d  M3  UnUR                  U   " U5      nUR                  u  pgpUR                  XgX-  5      R                  SS5      nUR                  U   " U5      S   nUR                  XhX5      R                  SSSS5      nXQ-   nM     X R                  S-
  :w  d  M  UR                  U5      nGM     U$ )Nr   r   r!   r   )	enumerater  r  r  r  r  r  r  r$   r   rR   r=   r   r  r  )
rw   r8   r  blocksr  r   r   r   r   r   s
             r*   r   Emu3VQVAEDownBlock.forward  s   (3OG !4!45 &W 5m Dv{{#a',H$*$5$5g$>}$MM:G:M:M7J&$1$6$6zV^$\$f$fghjk$lM$*KK$8$G$JM$1$9$9*e$^$f$fghjkmnpq$rM$,$<M 6 ..22 & 1 1- @  4" r,   )r  r  r  r  
r   r   r   r   rj   r%   r  r   r   r   r   s   @r*   r  r    s     ##JU%6%6  r,   r  c                   b   ^  \ rS rSrU 4S jrS\R                  S\R                  4S jrSrU =r	$ )Emu3VQVAEUpBlocki  c           
        > [         TU ]  5         [        UR                  5      U l        UR
                  U l        UR                  nUR                  UR                  S   -  n[        R                  " 5       U l
        [        [        U R                  5      5       GH8  n[        R                  " 5       n[        R                  " 5       n[        R                  " 5       nUR                  UR                  U   -  n[        U R
                  S-   5       Hd  n	UR                  [        UUUS95        UnXAR                  ;   d  M0  UR                  [!        U5      5        UR                  [#        X#5      5        Mf     [        R$                  " 5       n
XZl        Xjl        Xzl        US:w  a  [-        U5      U
l        U R                  R1                  SU
5        GM;     g )Nr    r   rx  r   )ri   rj   r  r  r  r  r   r  rS   r  upreversedr  r  rW  r  r`  r$  r  r  r  r  r  upsampleinsert)rw   rc   rX  r  r  r  r  r  r  r  r  rx   s              r*   rj   Emu3VQVAEUpBlock.__init__  si   "6#<#<=$33))''&*C*CB*GG--/d&:&: ;<GMMOE==?DJ,,v/H/H/QQI !4!4q!89($,%.'5 %555KK 7 ?@%%&:>&TU : BHG&M!|:8DGGNN1b!3 =r,   r8   r2  c                 b   [        U R                  S S S2   5       GH  u  p4[        U R                  S-   5       H  nUR                  U   " X5      n[        UR                  5      S:  d  M3  UnUR                  U   " X5      nUR                  u  pxpUR                  XxX-  5      R                  SS5      nUR                  U   " U5      S   nUR                  XyX5      R                  SSSS5      nXa-   nM     U[        U R                  5      S-
  :w  d  M  UR                  U5      nGM     U$ )Nr    r   r   r!   r   )r  r  r  r  r  r  r  r  r$   r   rR   r=   r   r  )rw   r8   r2  r  r  r  r   r   r   r   r   s              r*   r   Emu3VQVAEUpBlock.forward  s   (27OG !4!4q!89 &W 5m Rv{{#a',H$*$5$5g$>}$[M:G:M:M7J&$1$6$6zV^$\$f$fghjk$lM$*KK$8$G$JM$1$9$9*e$^$f$fghjkmnpq$rM$,$<M : #dgg,** & >  8  r,   )r  r  r  r  r   s   @r*   r  r    s-    #"JU%6%6 eFWFW  r,   r  c                   J   ^  \ rS rSrU 4S jrS\R                  4S jrSrU =r	$ )Emu3VQVAEEncoderi  c                   > [         TU ]  5         UR                  nUR                  nUR                  nUR
                  nUR                  nU(       a  SU-  OUnX&S   -  n[        R                  R                  X2SSSS9U l
        [        U5      U l        [        X5      U l        [        R                  R                  SUSSS	9U l        [        R                  R                  UUSSSS9U l        [%        [&        R(                  " UR*                  5      5      n	[        R,                  " 5       U l        [        R,                  " 5       U l        [3        U	5       H)  n
[5        Xw5      nU R.                  R7                  U5        M+     [3        UR8                  5       H(  n[;        UUS
9nU R0                  R7                  U5        M*     g )Nr!   r    r   r   r   r'  r   T)r*  r)  r   r+  r  )ri   rj   r  r   double_latentlatent_channelsr  r%   rS   r   conv_inr  
down_blockrv  middle_blockr,  norm_outconv_outr   mathlog2temporal_downsample_factorr  	time_convtime_res_stackr  rD  r  r  rJ  )rw   rc   r  r   r  r  r  r%  r  temporal_down_blocksir   r   time_res_convrx   s                 r*   rj   Emu3VQVAEEncoder.__init__  s   ,,((,, 00#66.;q?* b#99xx{qYZdef,V40B**bxUYbf*g ( 
  #499V-N-N#OP mmo+,A.|JDNN!!$' - v,,-A8()M &&}5 .r,   pixel_valuesc                 t   UR                   S   nUR                  " S/UR                   SS  Q76 nU R                  U5      nU R                  U5      nU R	                  U5      nU R                  U5      nU[        R                  " U5      -  nU R                  U5      nUR                  " SU/UR                   SS  Q76 nUR                  SSSSS5      nU R                   H$  nU" U5      nU[        R                  " U5      -  nM&     U R                   H  nU" U5      nM     UR                  SSSSS5      nU$ )Nr   r    r!   r   r   r   )r$   r=   r  r  r  r  r%   rT  r  r   r  r  )rw   r  temporal_dimr8   r   layers         r*   r   Emu3VQVAEEncoder.forward3  s:   #))!,#++BH1C1CAB1GH \26))-8 m4}55m4%--b,YATATUVUWAXY%--aAq!< NND /MU]]=99M # ((E!-0M ) &--aAq!<r,   )r  r  r  r  r  r  r  )
r   r   r   r   rj   r%   r   r   r   r   r   s   @r*   r  r    s     %6NE$4$4  r,   r  c                   j   ^  \ rS rSrS\4U 4S jjrS\R                  S\R                  4S jrSr	U =r
$ )Emu3VQVAEDecoderiQ  rc   c                   > [         T	U ]  5         UR                  nUR                  UR                  S   -  n[
        R                  " 5       U l        [        UR                  5       H<  n[        UR                  UR                  S9nU R                  R                  U5        M>     [        [        R                  " UR                   5      5      n[
        R                  " 5       U l        [        U5       H>  n[%        UR                  UR                  5      nU R"                  R                  U5        M@     [
        R&                  " UR                  USSSS9U l        [+        XUS9U l        [/        U5      U l        UR                  UR                  S   -  n[3        X#5      U l        [
        R&                  " UUR6                  SSSS9U l        g )Nr    r  r   r   r   )rX  r   )ri   rj   r   r  r  rS   r  r  r  r  rJ  r  r  r   r  r  r  r  r8  r   r  rv  r  r  up_blockr$  r  r%  r  )
rw   rc   rX  r  r   r  temp_upsample_block_numr  r   rx   s
            r*   rj   Emu3VQVAEDecoder.__init__R  s|   ))''&*C*CB*GG mmov,,-A8"22AWAWM &&}5	 . #&dii0Q0Q&R"S./A,V-C-CVE[E[\DNN!!$' 0 yy""
 1R`a(0''&*C*CA*FF,^F		
r,   r8   r2  c                    [         R                  " X4SS9nUR                  SSSSS5      nU R                   H  nU" U5      nM     U R                   H$  nU" U5      nU[         R
                  " U5      -  nM&     UR                  SSSSS5      n[         R                  " USSS9u  pUR                  " S/UR                  SS  Q76 nUR                  " S/UR                  SS  Q76 nU R                  U5      nU R                  X5      nU R                  X5      nU R                  X5      nU[         R
                  " U5      -  nU R                  U5      nU$ )Nr   r"   r!   r   r   r   r    )r%   r&   r   r  r  rT  chunkr=   r$   r  r  r  r  r  )rw   r8   r2  hidden_quant_statesr  s        r*   r   Emu3VQVAEDecoder.forwardy  sV   #ii(E1M199!Q1aH ((E"'(;"< ) ^^E"'(;"<5==1D#EE $ 299!Q1aH&+kk2Eqa&P#%--bK=3F3Fqr3JK#++BH1C1CAB1GH]3 ))-FmBmB}55m4r,   )r  r  r  r  r  r  r  )r   r   r   r   r   rj   r%   r   r   r   r   r   s   @r*   r  r  Q  s0    %
 %
NU\\   r,   r  aR  
    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://huggingface.co/papers/2203.13131).
    )custom_introc                      ^  \ rS rSr% \\S'   SrSrSrSr	Sr
Sr/ SQrS rS\4U 4S jjrS\R                   S	\R                   4S
 jrS\R                   4S jrSrU =r$ )	Emu3VQVAEi  rc   
emuvideovqr  T)rJ  r`  rW  r   c                    [        U[        R                  [        R                  45      (       a  [        R                  R                  UR                  SSS9  UR                  bq  [        R                  R                  UR                  5      u  p#S[        R                  " U5      -  n[        R                  R                  UR                  U* U5        g g [        U[        R                  5      (       a  [        R                  R                  UR                  [        R                  " S5      S9  UR                  by  [        R                  R                  UR                  5      u  p#US:  a  S[        R                  " U5      -  OSn[        R                  R                  UR                  U* U5        g g [        U[        R                  [        R                  [        R                   45      (       aU  [        R                  R#                  UR                  S5        [        R                  R#                  UR                  S	5        g [        U[        R$                  5      (       ad  UR                  R&                  R)                  5         UR*                  b2  UR                  R&                  UR*                     R-                  5         g g g )
Nfan_outrelu)r  nonlinearityr      )ar   r   r   )
isinstancerS   r   r  initkaiming_normal_r   rh   _calculate_fan_in_and_fan_outr  sqrtr   rp   kaiming_uniform_BatchNorm2drL  r,  	constant_r   r   normal_padding_idxzero_)rw   rC   fan_inr   bounds        r*   _init_weightsEmu3VQVAE._init_weights  s   fryy"))455GG##FMM	PV#W{{&GGAA&--P	DIIf--  ufe< ' 		**GG$$V]]diil$C{{&GGAA&--P	17!DIIf--  ufe< '  NOOGGfmmS1GGfkk3/--MM&&(!!-""6#5#56<<> . .r,   c                   > [         TU ]  U5        Xl        [        U5      U l        [        U5      U l        [        U5      U l        S[        UR                  5      S-
  -  U l        [        UR                  UR                  SSS9U l        [        UR                  UR                  SSS9U l        S[        UR                  5      S-
  -  U l        U R%                  5         U R'                  5         g )Nr!   r   )r   r   r   r;  r<  )ri   rj   rc   r  encoderr  decoderr   quantizer  r  vision_spatial_factorr  r  r   
quant_convpost_quant_convspatial_scale_factoreval	post_initr   s     r*   rj   Emu3VQVAE.__init__  s     '/'/08%&3v/H/H+IA+M%N")""F$4$4)T]
  /f44)T] 
 %&#f.G.G*H1*L$M!		r,   image_sizesc                    UR                   S:H  nU(       aJ  U R                  R                  nUR                  u  pVpxUR	                  S5      R                  SUSSS5      nOUR                  u  pTpgnU R                  U5      n	U	R                  SSSSS5      n	U R                  U	5      n	U	R                  SSSSS5      n	U R                  U	5      n
U(       a  U
R                  S5      OU
n[        X5       VVs/ s HB  u  pUS [        US   U R                  -  5      2S [        US   U R                  -  5      24   PMD     nnnU$ s  snnf )Nr   r   r   r!   r   )ndimrc   r  r$   r.   repeatr  r   r  r  squeezer  r   r  )rw   r  r  is_imager   r   r   r   r   r8   codesimage_tokenssingle_imager4  s                 r*   encodeEmu3VQVAE.encode  sP   $$){{==H2>2D2D/J&'11!4;;AxAqQL<H<N<N9J(E\2 &--aAq!<6 &--aAq!<m,+3u}}Q' '*,&D
&D" D3tAw)C)CCDDFqDQRGVZVpVpLpHqFqqr&D 	 

 
s   6A	Er8   c                    UR                   S:H  nU(       a  UR                  S5      nUR                  u  p4pVU R                  R	                  UR                  5       5      nUR                  S   nUR                  X4XVU5      R                  SSSSS5      R                  5       nU R                  U5      n	UR                  SSSSS5      nU	R                  SSSSS5      n	U R                  X5      n
U
R                  UX@R                  R                  -  U R                  R                  XPR                  -  X`R                  -  5      n
U(       a	  U
S S 2S4   $ U
$ )Nr   r   r    r   r   r!   )r  r.   r$   r  r   flattenr   r   rX   r  r  r=   rc   r  r%  r  )rw   r8   r  r   r   r   r   quantr   
post_quantvideos              r*   decodeEmu3VQVAE.decode  s;    %%*)33A6M.;.A.A+
f''(=(=(?@;;r?

:IQQRSUVXY[\^_`kkm))%0
aAq!,''1aA6
Z/{{===KK$$...---
 'uQT{1E1r,   )rc   r  r  r  r  r  r  r  )r   r   r   r   r   __annotations__base_model_prefixmain_input_name_supports_sdpa_supports_flash_attn_supports_flex_attn_supports_attention_backend_no_split_modulesr  rj   r%   r   r  r  r   r   r   s   @r*   r  r    sv     $$ON"&?* *5<< ell 82ELL 2 2r,   r  c                       \ rS rSrSrS r\S 5       r\S 5       r\S 5       r	\S 5       r
\S 5       r\S	 5       rS
\\R                     S\R                  4S jrS
\R                  S\R                  4S jrSrg)Emu3ImageVocabularyMappingi  zE
A class for mapping discrete image tokens from VQGAN to BPE tokens.
c                 h    Xl         UR                  S5      U l        UR                  S5      U l        g )Nz<|extra_200|>z<image>)	vocab_mapgeteol_token_idimage_token_id)rw   r  s     r*   rj   #Emu3ImageVocabularyMapping.__init__  s)    "%MM/:'mmI6r,   c           	          [        U R                  R                  5        VVs/ s H  u  pUR                  S5      (       d  M  UPM!     snn5      $ s  snnf Nz<|visual tokensortedr  items
startswithrw   namevals      r*   r  'Emu3ImageVocabularyMapping.image_tokens  s<    DNN,@,@,Bh,BytdooVfFgs,Bhiih   A
A
c           	          [        U R                  R                  5        VVs/ s H  u  pUR                  S5      (       d  M  UPM!     snn5      $ s  snnf r  r  r  s      r*   image_tokens_str+Emu3ImageVocabularyMapping.image_tokens_str  s<    T^^-A-A-Ci-C	tWgGht-Cijjir  c                 z    U R                    Vs0 s H  n[        USS 5      U R                  U   _M!     sn$ s  snf )NirL   )r  r   r  )rw   tokens     r*   img2bpe"Emu3ImageVocabularyMapping.img2bpe   s;    FJF[F[\F[UE"RL!4>>%#88F[\\\s   &8c                 l    U R                   R                  5        VVs0 s H  u  pX!_M	     snn$ s  snnf r   )r!  r  )rw   r0   vs      r*   bpe2img"Emu3ImageVocabularyMapping.bpe2img$  s-    !%!3!3!56!5!5666s   0c                     [         R                  " [        U R                  R	                  5       5      S-   [         R
                  S9nU R                  R                  5        H	  u  p#X1U'   M     U$ Nr   rM   )r%   zerosmaxr%  rj  r   r  rw   mappingr0   r$  s       r*   bpe2img_mapping_tensor1Emu3ImageVocabularyMapping.bpe2img_mapping_tensor(  R    ++c$,,"3"3"56:%))LLL&&(DAAJ )r,   c                     [         R                  " [        U R                  R	                  5       5      S-   [         R
                  S9nU R                  R                  5        H	  u  p#X1U'   M     U$ r(  )r%   r*  r+  r!  rj  r   r  r,  s       r*   img2bpe_mapping_tensor1Emu3ImageVocabularyMapping.img2bpe_mapping_tensor/  r0  r,   	img_batchr:   c                 "   UR                   n[        R                  " UR                  S   S4[        R                  S9U R
                  -  nU R                  UR                  S5         n[        R                  " XC/SS9nUR                  U5      $ )Nr   r   r)  cpur    r"   )	devicer%   r   r$   r   r  r2  rW   r&   )rw   r4  r7  eol_row
img_tokenss        r*   convert_img2bpe*Emu3ImageVocabularyMapping.convert_img2bpe6  su    !!**iooa0!4EIIFIZIZZ00e1DE
YY
4"=
}}V$$r,   c                     UR                   nUSS S24   nU R                  UR                  S5         nUR                  U5      $ )N.r    r6  )r7  r.  rW   )rw   r4  r7  r9  s       r*   convert_bpe2img*Emu3ImageVocabularyMapping.convert_bpe2img=  sG    !!c3B3h'	00e1DE
}}V$$r,   )r  r  r  N)r   r   r   r   r   rj   r   r  r  r!  r%  r.  r2  listr%   r   r:  r=  r   r   r,   r*   r
  r
    s    7
 j j k k ] ] 7 7    %ell); % %% %%,, %r,   r
  c                   N    \ rS rSr% \\S'   SrSrS/rSS/r	Sr
SrSrSrSrSrS	rg
)Emu3PreTrainedModeliD  rc   modelTr   r{   r\   Fr   N)r   r   r   r   r   r  r  supports_gradient_checkpointingr  _skip_keys_device_placementr  r  _can_compile_fullgraph!_supports_param_buffer_assignmentr  r  r   r   r,   r*   rA  rA  D  sO    &*# $5m"DN!(-%"&r,   rA  c                      ^  \ rS rSr% \R
                  \S'   SS\4U 4S jjjr\R                  " 5       \
S 5       5       rSrU =r$ )Emu3RotaryEmbeddingiV  inv_freqrc   c                   > [         TU ]  5         [        US5      (       aZ  [        UR                  [
        5      (       a;  UR                  R                  SUR                  R                  S5      5      U l        OSU l        UR                  U l	        UR                  U l
        Xl        [        U R                     U l        U R                  U R                  U5      u  o0l        U R                  SUSS9  U R                   U l        g )Nrope_scaling	rope_typetypedefaultrI  F)
persistent)ri   rj   hasattrr  rK  dictr  rL  max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrc   r   rope_init_fnattention_scalingregister_bufferrI  original_inv_freq)rw   rc   r7  rI  rx   s       r*   rj   Emu3RotaryEmbedding.__init__Y  s    6>**z&:M:Mt/T/T#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q((ZeD!%r,   c                 b   U R                   S S S 2S 4   R                  5       R                  UR                  S   SS5      R	                  UR
                  5      nUS S 2S S S 24   R                  5       n[        UR
                  R                  [        5      (       a0  UR
                  R                  S:w  a  UR
                  R                  OSn[        R                  " USS9   UR                  5       UR                  5       -  R                  SS5      n[        R                  " Xf4SS	9nUR                  5       U R                  -  nUR                  5       U R                  -  n	S S S 5        WR	                  UR                   S
9W	R	                  UR                   S
94$ ! , (       d  f       N@= f)Nr   r    r   mpsr6  F)device_typeenabledr!   r"   r)  )rI  floatr<   r$   rW   r7  r  rM  strr%   autocastrR   r&   r1   rV  r2   rM   )
rw   r'   r3   inv_freq_expandedposition_ids_expandedr\  freqsembr1   r2   s
             r*   r   Emu3RotaryEmbedding.forwardj  sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E'E!((--[`J`ahhmmfk^^UC&,,.1F1L1L1NNYYZ[]^_E))UN3C'')d444C'')d444C	 D vvAGGv$cff177f&;;; DCs   $BF  
F.)rV  rc   rS  rX  rT  rU  rL  r   )r   r   r   r   r%   r   r  r   rj   no_gradr   r   r   r   r   s   @r*   rH  rH  V  s@    ll/z / /" ]]_<  <r,   rH  c                   ,  ^  \ rS rSr\\S.rS\4U 4S jjr\	" 5       \
       SS\\R                     S\\R                     S\\R                     S\\   S	\\R                      S
\\R                     S\\   S\\   S\4S jj5       5       rSrU =r$ )Emu3TextModeliz  )r8   
attentionsrc   c           	        > [         TU ]  U5        UR                  U l        UR                  U l        [
        R                  " UR                  UR                  U R                  5      U l        [
        R                  " [        UR                  5       Vs/ s H  n[        X5      PM     sn5      U l        [        UR                  UR                  S9U l        [#        US9U l        SU l        U R)                  5         g s  snf )Nr   rc   F)ri   rj   pad_token_idr  
vocab_sizerS   r   rl   embed_tokensr  r  num_hidden_layersr   layersr   r   normrH  
rotary_embgradient_checkpointingr  rv   s      r*   rj   Emu3TextModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammBGH`H`BabBaYf0Bab
   2 28K8KL	-V<&+# 	 cs   C?	input_idsrG   r3   r{   inputs_embedsr   r   rJ   r:   c           
      J   US L US L-  (       a  [        S5      eUc  U R                  U5      nU(       a  Uc  [        U R                  S9nUcD  Ub  UR	                  5       OSn	[
        R                  " XUR                  S   -   UR                  S9nUc  UR                  S5      n[        U R                  UUUUUS9n
UnU R                  X5      nU R                  S U R                  R                    H  nU" U4U
UUUUS.UD6nM     U R                  U5      n[        UUS9$ )	Nz:You must specify exactly one of input_ids or inputs_embedsrk  r   r   )r7  )rc   input_embedsrG   r   r{   r3   )rG   r3   r{   r   r   )last_hidden_stater{   )rc  rn  r
   rc   get_seq_lengthr%   aranger$   r7  r.   r   rr  rp  ro  rq  r   )rw   ru  rG   r3   r{   rv  r   r   rJ   past_seen_tokensr\   r8   r   decoder_layers                 r*   r   Emu3TextModel.forward  sR    -t";<YZZ *.*;*;I*FM0*$++>O!CRC^==?de+0<< ]5H5H5K"KTaThTh,N )33A6L(;;&))+%
 &"oomJ![[)H4;;+H+HIM)*) /-$7 M J 		-0&++
 	
r,   )rn  rs  rp  rq  r  rr  rm  )NNNNNNN)r   r   r   r   r   r`   _can_record_outputsr   rj   r   r   r   r%   r   r   r	   r  r   r   r   r   r   r   r   r   s   @r*   rh  rh  z  s     *#
z    151537+/5959$(8
E,,-8
 !.8
 u//0	8

 "%8
   1 128
 !!1!128
 D>8
 +,8
 
!8
  8
r,   rh  c                   ~  ^  \ rS rSr% S/rSS0rSS/S/40r\\S'   U 4S jr	\
\         SS	\\R                     S
\\R                     S\\R                     S\\   S\\R"                     S\\R                     S\\   S\\R                     S\\\R                  4   S\\   S\4S jj5       5       rSrU =r$ )Emu3ForCausalLMi  lm_head.weightlm_headcolwise_repr8   logitsrc   c                    > [         TU ]  U5        [        U5      U l        UR                  U l        [
        R                  " UR                  UR                  SS9U l        U R                  5         g NFrg   )
ri   rj   rh  rB  rm  rS   rp   rl   r  r  r   s     r*   rj   Emu3ForCausalLM.__init__  sU     "6*
 ++yy!3!3V5F5FUS 	r,   ru  rG   r3   r{   rv  labelsr   r   logits_to_keeprJ   r:   c
                 ~   U R                   " SUUUUUUUS.U
D6nUR                  n[        U	[        5      (       a  [	        U	* S5      OU	nU R                  USS2USS24   5      nSnUb)  U R                  " SXU R                  R                  S.U
D6n[        UUUR                  UR                  UR                  S9$ )aC  
Example:

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

>>> model = Emu3ForCausalLM.from_pretrained("BAAI/Emu3-Chat-hf", 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]
```ru  rG   r3   r{   rv  r   r   Nr  r  rm  lossr  r{   r8   ri  r   )rB  ry  r  r   slicer  loss_functionrc   rm  r   r{   r8   ri  )rw   ru  rG   r3   r{   rv  r  r   r   r  rJ   outputsr8   slice_indicesr  r  s                   r*   r   Emu3ForCausalLM.forward  s    @ ,0:: 	,
)%+')	,
 	,
  118B>SV8W8W~ot4]kmA}a,?@A%%pVt{{OeOepiopD%#33!//))
 	
r,   )r  rB  rm  )	NNNNNNNNr   )r   r   r   r   _tied_weights_keys_tp_plan_pp_planr   r  rj   r   r   r   r%   r   r   r	   r  r   r   r   r   r   r   r   r   r   r   s   @r*   r  r    s6   *+=)H_-z:;H  151537+/59-1$(59348
E,,-8
 !.8
 u//0	8

 "%8
   1 128
 ))*8
 D>8
 !!1!128
 c5<</08
 +,8
 
 8
  8
r,   r  c                     ^  \ rS rSrSS0rU 4S jrS rS rS rS r	S	\
R                  S
\
R                  4S jrS	\
R                  S
\
R                  4S jr\
R                  S\
R                  S\S\4S j5       rS\
R                  S\
R                  S\
R                  4S jr\\         SS\\
R                     S	\\
R                     S
\\
R,                     S\\
R,                     S\\
R                     S\\   S\\
R                     S\\   S\\
R                     S\\   S\\\4   4S jj5       5       rSrU =r $ )	Emu3Modeli  ztext_model.model
text_modelc                    > [         TU ]  U5        [        R                  UR                  5      U l        [        UR                  5      U l        [        UR                  5      U l        U R                  5         g r   )ri   rj   rh  _from_configtext_configr  r  	vq_configvqmodelr
  vocabulary_mapvocabulary_mappingr  r   s     r*   rj   Emu3Model.__init__  sY     '44V5G5GH !1!12"<V=R=R"S 	r,   c                 6    U R                   R                  5       $ r   )r  get_input_embeddingsr   s    r*   r  Emu3Model.get_input_embeddings'  s    3355r,   c                 :    U R                   R                  U5        g r   )r  set_input_embeddingsrw   rF   s     r*   r  Emu3Model.set_input_embeddings*  s    ,,U3r,   c                     Xl         g r   r  rw   r  s     r*   set_decoderEmu3Model.set_decoder-  s    !r,   c                     U R                   $ r   r  r   s    r*   get_decoderEmu3Model.get_decoder0  s    r,   r  r  c                     U R                   R                  X5      nU Vs/ s H+  o@R                  R                  U5      R	                  5       PM-     nn[
        R                  " U5      nU$ s  snf )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  r  r  r:  r  r%   r&   )rw   r  r  image_tokens_listtokensbpe_tokens_list
bpe_tokenss          r*   get_image_tokensEmu3Model.get_image_tokens3  sb     !LL//JctuctY_22BB6JRRTctuYY/
 vs   2A,c                    U R                  X5      nU VVs/ s H9  u  pEX@R                  R                  -  XPR                  R                  -  S-   -  PM;     nnnU R                  5       " U5      n[        R
                  " Xv5      nU$ s  snnf )a  
Tokenizes images into discrete tokens with VQGAN module and embeds
them with text embeddings layer

Args:
    pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
        The tensors corresponding to the input images.
r   )r  r  r  r  r%   split)rw   r  r  r  r   r   split_sizesimage_featuress           r*   get_image_featuresEmu3Model.get_image_featuresD  s     ,,\G "-
!, ||999e||GiGi>ilm>mn!, 	 
 224\B^A
s   A Br  r   r   c                     USS2SS24   R                  SX#S-   5      nU R                  R                  U5      nU R                  R	                  U5      nU$ )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.
Nr    r   )r   r  r=  r  r  )rw   r  r   r   	sequencesimages         r*   decode_image_tokensEmu3Model.decode_image_tokensV  sV     !CRC(--b&!)D	..>>yI##L1r,   ru  rv  r  c           	      J   Ucj  X R                  5       " [        R                  " U R                  R                  [        R
                  UR                  S95      :H  nUR                  S5      nOXR                  R                  :H  nUR                  5       nUR                  S5      R                  U5      R                  UR                  5      nUR                  S   UR                  S   -  nX$   R                  5       UR                  5       :w  a  [        SU SU 35      eU$ )z
Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
equal to the length of multimodal features. If the lengths are different, an error is raised.
)rM   r7  r    r   r   z6Image features and image tokens do not match: tokens: z, features )r  r%   tensorr  r  longr7  allr   r.   	expand_asrW   r$   numelrc  )rw   ru  rv  r  special_image_maskn_image_tokensn_image_featuress          r*   get_placeholder_maskEmu3Model.get_placeholder_maski  s    !.2K2K2MT44CC5::^k^r^rs3 " "4!7!7!;!*.E.E.T.T!T+//1/99"=GGVYYZgZnZno)//2^5I5I!5LL,2248L8L8NNHHXXcdtcuv  "!r,   rG   r3   r{   r   r   rJ   r:   c
           
      0   USL USL-  (       a  [        S5      eUc  U R                  5       " U5      nUbG  U R                  X#5      n[        R                  " USS9nU R                  XUS9nUR                  X5      nU R                  " SUUUUUU	S.U
D6nU$ )aH  
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).
NzaYou cannot specify both input_ids and inputs_embeds at the same time, and must specify either oner   r"   )rv  r  )rG   r3   r{   rv  r   r   r   )rc  r  r  r%   r&   r  masked_scatterr  )rw   ru  r  r  rG   r3   r{   rv  r   r   rJ   image_embedsr  r  s                 r*   r   Emu3Model.forward  s    * -t";<s    557	BM#22<ML 99\q9L!%!:!:| "; " *889KZM // 
)%+')
 
 r,   )r  r  r  )	NNNNNNNNN)!r   r   r   r   _checkpoint_conversion_mappingrj   r  r  r  r  r%   r  r   r  r  rf  r   r  r  r   r   r   r   r	   r   r   r   r   r   r   r   r   r   r   s   @r*   r  r    s   &8,%G"64"U->-> UM]M] "u/@/@ uO_O_ $ ]]0@0@ # VY  $"))":?:K:K"]b]n]n"0  1548.21537+/59$(59.E,,-. u001. ell+	.
 !.. u//0. "%.   1 12. D>. !!1!12. +,. 
u,,	-.  .r,   r  c                   B  ^  \ rS rSrSrS/rSSSS.rU 4S jrS	 rS
 r	S\
R                  4S jrS rS r\S 5       r\S 5       r\S 5       rS r\\           S"S\\R0                     S\\R2                     S\\R4                     S\\R4                     S\\R0                     S\\   S\\R2                     S\\   S\\R0                     S\\R0                     S\\\R4                  4   S\\    S\\!\"4   4S jj5       5       r#       S#U 4S  jjr$S!r%U =r&$ )$Emu3ForConditionalGenerationi   r  zmodel.text_modelzmodel.vqmodelr  )z^text_model.modelz^vqmodelz^text_model.lm_headc                    > [         TU ]  U5        [        U5      U l        [        R
                  " UR                  R                  UR                  R                  SS9U l	        U R                  5         g r  )ri   rj   r  rB  rS   rp   r  rl   rm  r  r  r   s     r*   rj   %Emu3ForConditionalGeneration.__init__  sS     v&
yy!3!3!?!?ASASA^A^ejkr,   c                 6    U R                   R                  5       $ r   )rB  r  r   s    r*   r  1Emu3ForConditionalGeneration.get_input_embeddings  s    zz..00r,   c                 :    U R                   R                  U5        g r   )rB  r  r  s     r*   r  1Emu3ForConditionalGeneration.set_input_embeddings  s    

''.r,   r:   c                     U R                   $ r   )r  r   s    r*   get_output_embeddings2Emu3ForConditionalGeneration.get_output_embeddings  s    ||r,   c                 :    U R                   R                  U5        g r   )rB  r  r  s     r*   r  (Emu3ForConditionalGeneration.set_decoder  s    

w'r,   c                 6    U R                   R                  5       $ r   )rB  r  r   s    r*   r  (Emu3ForConditionalGeneration.get_decoder  s    zz%%''r,   c                 .    U R                   R                  $ r   )rB  r  r   s    r*   r  'Emu3ForConditionalGeneration.text_model  s    zz$$$r,   c                 .    U R                   R                  $ r   )rB  r  r   s    r*   r  $Emu3ForConditionalGeneration.vqmodel  s    zz!!!r,   c                 .    U R                   R                  $ r   )rB  r  r   s    r*   r  /Emu3ForConditionalGeneration.vocabulary_mapping  s    zz,,,r,   c                 :    U R                   R                  " S0 UD6$ r\  )rB  r  )rw   rJ   s     r*   r  0Emu3ForConditionalGeneration.decode_image_tokens  s    zz--777r,   ru  r  r  rG   r3   r{   rv  r   r   r  r  rJ   c                    U R                   " SUUUUUUU	S.UD6nUS   n[        U[        5      (       a  [        U* S5      OUnU R	                  USS2USS24   5      nSnU
b3  U R
                  " SUXR                  R                  R                  S.UD6n[        UUUR                  UR                  UR                  S9$ )aF  
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).
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
    Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
    config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
    (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

Example:

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

>>> model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", 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]
```r  r   Nr  r  r   )rB  r  r   r  r  r  rc   r  rm  r   r{   r8   ri  )rw   ru  r  r  rG   r3   r{   rv  r   r   r  r  rJ   r  r8   r  r  r  s                     r*   r   $Emu3ForConditionalGeneration.forward  s    | ** 	
)%+')	
 	
  
8B>SV8W8W~ot4]kmA}a,?@A%% f9P9P9[9[_eD &#33!//))
 	
r,   c	                 V   > [         TU ]  " U4UUUUUUUS.U	D6n
US   S:w  a  S U
S'   U
$ )N)r{   rG   rv  r   r3   r  r   r   r  )ri   prepare_inputs_for_generation)rw   ru  r{   rG   rv  r   r3   r   r  rJ   model_inputsrx   s              r*   r  :Emu3ForConditionalGeneration.prepare_inputs_for_generation?  sZ     w<

+)')%%

 

 !!+/L(r,   )r  rB  )NNNNNNNNNNr   )NNNNNTN)'r   r   r   r   r  r  r  rj   r  r  rS   r  r  r  r  propertyr  r  r  r  r   r   r   r%   r   r  r   r	   r   r   r   r   r   r   r   r   r  r   r   r   s   @r*   r  r    s   *+/#(&"1/ryy (( % % " " - -8  1548.21537+/59$(59-134X
E,,-X
 u001X
 ell+	X

 !.X
 u//0X
 "%X
   1 12X
 D>X
 !!1!12X
 ))*X
 c5<</0X
 +,X
 
u,,	-X
  X
z  r,   r  )r  r  rh  rA  r  r  )Nr   )r   )Wr  	functoolsr   typingr   r   r   r%   torch.nnrS   torch.nn.functionalrT   r  activationsr   cache_utilsr	   r
   
generationr   integrationsr   masking_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   utils.deprecationr   utils.genericr   configuration_emu3r   r   r   r+   r7   r   r   rB   r  r^  r^   r`   r   r   r   r   r   r  r  r$  r8  rD  rJ  rW  r`  r,  rn  rv  r  r  r  r  r  r
  rA  rH  rh  r  r  r  __all__r   r,   r*   <module>r     s'  .  % , ,     ! . ) 7 / 9 O K F & I I 0 / K K(6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % % '(%4D)BII D)N Y'J")) J (J(bii  +1 +\$ryy $D	RYY 	299 bii :!299 !H		 .")) &.(299 .(b<(299 <(~>)bii >)BV V299 D8 8v7ryy 7tCryy CLCryy CL l2 l2l2^3% 3%l '/ ' '"!<")) !<H P
' P
 P
f I
)? I
 I
XV# Vrh#6 hVr,   