
    %	&hN                       d dl Z d dlmZmZ d dlmZ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mZ ddlmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ ddlm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3m4Z4  e,       rd dl5m6Z6 ddl7m8Z8  e-jr                  e:      Z;dZ< G d dejz                        Z> G d dejz                        Z?d Z@dcdZAde
j                  deCde
j                  fdZD	 dddejz                  d e
j                  d!e
j                  d"e
j                  d#ee
j                     d$eEd%eEfd&ZF G d' d(ejz                        ZG G d) d*ejz                        ZH G d+ d,ejz                        ZI G d- d.ejz                        ZJ G d/ d0ejz                        ZK G d1 d2ejz                        ZL G d3 d4ejz                        ZM G d5 d6ejz                        ZN G d7 d8ejz                        ZO G d9 d:ejz                        ZP G d; d<ejz                        ZQ G d= d>ejz                        ZR G d? d@ej                        ZT G dA dBejz                        ZU G dC dDejz                        ZV G dE dFejz                        ZW G dG dHejz                        ZX G dI dJejz                        ZYdKZZ e)dLeZ       G dM dNe$             Z[ G dO dP      Z\dQZ] e)dRe]       G dS dTe$             Z^ G dU dVejz                        Z_dWZ` e)dXe]       G dY dZe^             Za G d[ d\ee(      Zb G d] d^e^e      Zcd_Zd G d` dae^e      Zeg dbZfy)e    N)cached_propertypartial)CallableListOptionalTupleUnion   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)
LossKwargsadd_start_docstrings%add_start_docstrings_to_model_forwardcan_return_tupleis_torch_flex_attn_availableloggingreplace_return_docstrings)deprecate_kwarg   )
Emu3ConfigEmu3TextConfigEmu3VQVAEConfig)	BlockMask)make_flex_block_causal_maskr"   c                   ,     e Zd Zd fd	Zd Zd Z xZS )Emu3RMSNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z:
        Emu3RMSNorm is equivalent to T5LayerNorm
        N)super__init__nn	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      |/var/www/pru.catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/emu3/modeling_emu3.pyr+   zEmu3RMSNorm.__init__B   s1     	ll5::k#:; #    c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )N   T)keepdim)	dtypetor.   float32powmeanrsqrtr1   r0   )r2   hidden_statesinput_dtypevariances       r6   forwardzEmu3RMSNorm.forwardJ   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r7   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler0   shaper1   r2   s    r6   
extra_reprzEmu3RMSNorm.extra_reprQ   s*    ))*+6$2G2G1HIIr7   )ư>)__name__
__module____qualname__r+   rE   rJ   __classcell__r5   s   @r6   r(   r(   A   s    $;Jr7   r(   c                   $     e Zd Z fdZd Z xZS )Emu3MLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  |j                        | _        t        j                  | j                  | j                  |j                        | _	        t        j                  | j                  | j                  |j                        | _
        t        |j                     | _        y )Nbias)r*   r+   configr3   intermediate_sizer,   Linearmlp_bias	gate_projup_proj	down_projr   
hidden_actact_fnr2   rV   r5   s     r6   r+   zEmu3MLP.__init__V   s    !--!'!9!94#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r7   c                     | j                  | j                  | j                  |            | j                  |      z        }|S N)r\   r^   rZ   r[   )r2   xr\   s      r6   rE   zEmu3MLP.forward`   s6    NN4;;t~~a/@#ADLLQRO#ST	r7   rL   rM   rN   r+   rE   rO   rP   s   @r6   rR   rR   U   s    0r7   rR   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..Nr:   r9   dim)rH   r.   cat)rb   x1x2s      r6   rotate_halfrj   e   sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r7   c                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezerj   )qkcossinposition_idsunsqueeze_dimq_embedk_embeds           r6   apply_rotary_pos_embru   l   sY    ( --
&C
--
&C3w;q>C/0G3w;q>C/0GGr7   rB   n_repreturnc                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r!   N)rH   expandreshape)rB   rv   batchnum_key_value_headsslenhead_dims         r6   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr7   modulequerykeyvalueattention_maskscalingdropoutc                 T   t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
|#|d d d d d d d |j
                  d   f   }|
|z   }
t        j                  j                  |
dt        j                        j                  |j                        }
t        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr9   r
   r:   )rf   r<   )ptrainingr!   )r   num_key_value_groupsr.   matmul	transposerH   r,   
functionalsoftmaxr>   r=   r<   r   r   
contiguous)r   r   r   r   r   r   r   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputs                r6   eager_attention_forwardr      s    3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#k1==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r7   c                   6    e Zd ZdZdedef fdZ	 	 ddej                  de	ej                  ej                  f   de
ej                     de
e   d	e
ej                     d
ee   de	ej                  e
ej                     e
e	ej                        f   fdZ xZS )Emu3Attention=Multi-headed attention from 'Attention Is All You Need' paperrV   	layer_idxc                 d   t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  |j                  z  | _	        | j                  dz  | _
        |j                  | _        d| _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j                  | j                  z  |j
                  |j                        | _        y )Nr~         TrT   )r*   r+   rV   r   getattrr3   num_attention_headsr~   r|   r   r   attention_dropout	is_causalr,   rX   attention_biasq_projk_projv_projo_projr2   rV   r   r5   s      r6   r+   zEmu3Attention.__init__   sM   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
r7   rB   position_embeddingsr   past_key_valuecache_positionr   rw   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }|\  }}t        |	|
||      \  }	}
|'|||d}|j                  |
|| j                  |      \  }
}t        }| j                  j                  dk7  r^| j                  j                  dk(  r(|j                  dd      rt        j                  d	       nt         | j                  j                     } || |	|
||f| j"                  sd
n| j$                  | j&                  d|\  }} |j(                  g |d j+                         }| j-                  |      }||fS )Nr:   r!   r9   )rp   ro   r   eagersdpaoutput_attentionsF`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.        )r   r   )rH   r~   r   viewr   r   r   ru   updater   r   rV   _attn_implementationgetloggerwarning_oncer   r   r   r   rz   r   r   )r2   rB   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   ro   rp   cache_kwargsattention_interfacer   r   s                     r6   rE   z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&S#7jRUWZ#[ j%#&snUL'5'<'<ZW[WeWegs't$J(?;;++w6{{//69fjjI\^c>d##L
 '>dkk>^>^&_#$7	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r7   NN)rL   rM   rN   __doc__r"   intr+   r.   Tensorr   r   r   
LongTensorr   r   rE   rO   rP   s   @r6   r   r      s    G
z 
c 
8 +/59/)||/) #5<<#=>/) !.	/)
 !/) !!1!12/) -./) 
u||Xell3XeELL>Q5RR	S/)r7   r   c                   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 )Emu3DecoderLayerrV   r   c                 h   t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        t        j                  |j                        | _        y )N)rV   r   r4   )r*   r+   r3   r   	self_attnrR   mlpr(   rms_norm_epsinput_layernormpost_attention_layernormr,   Dropoutr   r   r   s      r6   r+   zEmu3DecoderLayer.__init__   s    !--&f	J6?*6+=+=6CVCVW(3F4F4FFL_L_(`%zz&":":;r7   rB   r   rq   r   r   	use_cacher   r   rw   c	                    |}
| 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
        )rB   r   rq   r   r   r   r   r    )r   r   r   r   r   )r2   rB   r   rq   r   r   r   r   r   r   residualself_attn_weightsoutputss                r6   rE   zEmu3DecoderLayer.forward  s    > !,,]; ,:4>> 
,
')%)/) 3
,
 
,
(( !4<<#>> !55mD/ 4<<#>> ")++Gr7   )NNNFFNN)rL   rM   rN   r"   r   r+   r.   r   r   r   r   boolr   FloatTensorrE   rO   rP   s   @r6   r   r      s    	<z 	<c 	< 2637*.,1$)59KO<||< !.< u//0	<
 !< $D>< D>< !!1!12< &eELL%,,,F&GH< 
u  (51B1BEDUDU1U+V"WW	X<r7   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.
    rV   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	embeddingr0   datauniform_r_   s     r6   r+   z!Emu3VQVAEVectorQuantizer.__init__O  sb    f&:&:F<L<LM""++D63G3G,GvOcOcIcdr7   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
      r9   r:   T)rf   r;   re   )rH   permuter   r   r.   sumr   r0   r   r   argmin)r2   r   
batch_sizetemporalchannelsheightwidthhidden_state_flattenedhidden_state_sumembedding_sum	distancesmin_encoding_indicess               r6   rE   z Emu3VQVAEVectorQuantizer.forwardT  s    8D8J8J5
Hh#++Aq!Q:EEG!-!2!22x!@ !99%;Q%>AtT		$.."7"7":B %;T^^=R=R=\=\]^`a=bcc	$}4y@	$||I1=388XvW\]##r7   )
rL   rM   rN   r   r$   r+   r.   r   rE   rO   rP   s   @r6   r   r   D  s&    e e
$ELL $r7   r   c                   $     e Zd Z fdZd Z xZS )Emu3VQVAEEncoderConvDownsamplec                 `    t         |           t        j                  ||ddd      | _        y )Nr
   r9   r   kernel_sizestridepaddingr*   r+   r,   Conv2dconvr2   in_channelsr5   s     r6   r+   z'Emu3VQVAEEncoderConvDownsample.__init__g  '    IIk;AaYZ[	r7   c                 Z    t        j                  |ddd      }| j                  |      }|S )N)r   r!   r   r!   constantr   )padmoder   )Fr   r   r2   rB   s     r6   rE   z&Emu3VQVAEEncoderConvDownsample.forwardk  s+    mJVWX		-0r7   rc   rP   s   @r6   r   r   f  s    \r7   r   c                   $     e Zd Z fdZd Z xZS )Emu3VQVAEEncoderConvUpsamplec                 `    t         |           t        j                  ||ddd      | _        y )Nr
   r!   r   r   r   s     r6   r+   z%Emu3VQVAEEncoderConvUpsample.__init__s  r   r7   c                 X    t        j                  |dd      }| j                  |      }|S )N       @nearestscale_factorr   )r   interpolater   r   s     r6   rE   z$Emu3VQVAEEncoderConvUpsample.forwardw  s(    m#IV		-0r7   rc   rP   s   @r6   r   r   r  s    \r7   r   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_channelr   r   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!   r   r:   r9   )r9   r   )r   )r*   r+   zipr   r,   Conv3dr   )
r2   r
  r  r   r   
one_kernel
one_stridepadding_sizespad_sizer5   s
            r6   r+   zEmu3VQVAEConv3d.__init__~  s     	ORS^_`_aSbdjklkmdnOop5KZj0pp%dd+ 	JHLLX]X\98q=IIL	JII	
	 qs   B"rB   c                 h    t        j                  || j                        }| j                  |      }|S ra   )r   r   r   r   r   s     r6   rE   zEmu3VQVAEConv3d.forward  s*    mT\\:		-0r7   )
rL   rM   rN   r   r   r+   r.   r   rE   rO   rP   s   @r6   r	  r	  }  sF    

 
 3Z	

 c

,U\\ r7   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    rK   Tnum_channels
num_groupsr4   affiner!   r   r   )r*   r+   r,   	GroupNorm
norm_layerr   conv_yconv_br2   r   r  r5   s      r6   r+   zEmu3VQVAESpatialNorm.__init__  sn    
 	,,%	
 ii
 ii
r7   rB   quant_statesc                     t        j                  ||j                  dd  d      }| j                  |      }|| j	                  |      z  | j                  |      z   }|S )Nr   r  )sizer   )r   r  rH   r  r  r   )r2   rB   r"  s      r6   rE   zEmu3VQVAESpatialNorm.forward  sX    }}\8K8KBC8PW`a6%L(AADKKP\D]]r7   	rL   rM   rN   r   r+   r.   r   rE   rO   rP   s   @r6   r  r    s5    

 
8U\\  r7   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!   r   r   r*   r+   r	  r   r2   r
  r  r5   s      r6   r+   z"Emu3VQVAETemporalUpsample.__init__  (    
 	#!	
	r7   rB   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   r9   r:   r  r  r  )rH   r   r   r   r   r  r   )r2   rB   r   r   r   r   r   s          r6   rE   z!Emu3VQVAETemporalUpsample.forward  s    8E8K8K5
Hh%--aAq!<GGINNz[]_ghm#IV%**:xPRS[[\]_`bcefhijuuw		-0r7   r%  rP   s   @r6   r'  r'    s*    

 
U\\ r7   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
   )r9   r!   r!   r+  r,  r-  s      r6   r+   z$Emu3VQVAETemporalDownsample.__init__  r.  r7   rB   c                 (    | j                  |      }|S ra   )r   r   s     r6   rE   z#Emu3VQVAETemporalDownsample.forward  s    		-0r7   r%  rP   s   @r6   r1  r1    s*    

 
U\\ r7   r1  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   r   )r*   r+   r   r  r,   BatchNorm3dnorm1r	  conv1norm2conv2r  nin_shortcutr!  s      r6   r+   z%Emu3VQVAETemporalResnetBlock.__init__  s    
 	&+7+?K\^^K0
$!	

 ^^L1
$!	

 t000 "		!D 1r7   c                 L   |}| j                  |      }|t        j                  |      z  }| j                  |      }| j	                  |      }|t        j                  |      z  }| j                  |      }| j                  | j                  k7  r| j                  |      }||z   S ra   )	r8  r.   sigmoidr9  r:  r;  r   r  r<  )r2   rB   r   s      r6   rE   z$Emu3VQVAETemporalResnetBlock.forward	  s     

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

=1

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

=1t000((2H-''r7   ra   rc   rP   s   @r6   r5  r5    s     @(r7   r5  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  rK   Tr  r
   r!   r   r   )r*   r+   r   r  rA  r,   r  r8  r:  r  r   r9  r;  r<  )r2   r   r  rA  r5   s       r6   r+   zEmu3VQVAEResnetBlock.__init__  s    	&&2&:{(,!;2SW`deDJ<BTXaefDJ-nkJDJ-nlKDJYY

 YY

 t000 "		!D 1r7   rB   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 Nr   )
rA  r8  r.   r>  r9  r:  r;  r   r  r<  )r2   rB   rA  	norm_argsr   s        r6   rE   zEmu3VQVAEResnetBlock.forwardF  s    --5BN;L	 "

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

=1"

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

=1t000((2H-''r7   r   ra   )
rL   rM   rN   r   r   r+   r.   r   rE   rO   rP   s   @r6   r@  r@    sU     '+(,	** sm* !	*X(U\\ (8ELLCY (r7   r@  c                        e Zd ZdZdef fdZ	 	 d	dej                  deej                     dee	   de
ej                  eej                     f   fdZ xZS )
Emu3VQVAEAttentionBlockr   rV   c                 &   t         |           || _        |j                  | _        |j
                  | _        | j                  | j                  z  | _        | j                  | j                  z  | j                  k7  r&t        d| j                   d| j                   d      | j                  dz  | _	        |j                  | _        d| _        t        j                  | j                  | j                        | _        t        j                  | j                  | j                        | _        t        j                  | j                  | j                        | _        t        j                  | j                  | j                        | _        d| _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).r   Fr!   )r*   r+   rV   r3   r   r   	num_headsr~   
ValueErrorscaler   r   r   r,   rX   r   r   r   out_projr   r_   s     r6   r+   z Emu3VQVAEAttentionBlock.__init__[  s$   ++33$..8==4>>)T^^;MdnnM] ^NN#2'  ]]D(
//ii?ii?ii?		$..$..A %&!r7   rB   r   r   rw   c           
         |j                   \  }}}| j                  |      }| j                  |      }| j                  |      }	|j	                  ||| j
                  | j                        j                  dd      }|j	                  ||| j
                  | j                        j                  dd      }|	j	                  ||| j
                  | j                        j                  dd      }	t        }
| j                  j                  dk7  rN| j                  j                  dk(  r|rt        j                  d       nt        | j                  j                     }
 |
| |||	|| j                  | j                  | j                   sdn| j"                        \  }}|j%                  |||      j'                         }| j)                  |      }|sd}||fS )	z#Input shape: Batch x Time x Channelr!   r9   r   r   r   r   )r   r   r   N)rH   r   r   r   r   rI  r~   r   r   rV   r   r   r   r   r   rK  r   r   rz   r   rL  )r2   rB   r   r   r   
seq_lengthr   querieskeysvaluesr   r   r   s                r6   rE   zEmu3VQVAEAttentionBlock.forwardr  s    -:,?,?)
J	++m,{{=)]+,,z:t~~t}}U__`acdeyyZOYYZ[]^_ZT^^T]]S]]^_abc(?;;++w6{{//69>O##L
 '>dkk>^>^&_#$7nnJJ#}}C$,,	%
!\ "))*j)LWWYmmK0 LL((r7   )NF)rL   rM   rN   r   r$   r+   r.   r   r   r   r   rE   rO   rP   s   @r6   rG  rG  X  sm    G& &4 26,1	-)||-) !.-) $D>	-)
 
u||Xell33	4-)r7   rG  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 rD  )r*   r+   )r2   r   r5   s     r6   r+   zEmu3VQVAEGroupNorm.__init__  s    "6"r7   c                     t        j                  || j                  | j                  | j                  | j
                        S ra   )r   
group_normr  r0   rU   r4   )r2   inputr"  s      r6   rE   zEmu3VQVAEGroupNorm.forward  s)    ||E4??DKKDHHUUr7   ra   )rL   rM   rN   r   r+   rE   rO   rP   s   @r6   rS  rS    s    #Vr7   rS  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  rA  r  rK   Tr  )
r*   r+   r@  block_1rG  attn_1rS  	attn_normr  block_2)r2   rV   r   rA  r5   s       r6   r+   zEmu3VQVAEMiddleBlock.__init__  so    +#$)

 .f5!/[UW]ajnoDN1.+NDN+#$)
r7   rB   r"  c                 b   | j                  ||      }|}| j                  ||      }|j                  \  }}}}|j                  ||||z        j	                  dd      }| j                  |      d   }|j                  ||||      j                  dddd      }||z   }| j                  ||      }|S )Nr!   r9   r   r
   )	r\  r^  rH   r   r   r]  rz   r   r_  )r2   rB   r"  r   r   r   r   r   s           r6   rE   zEmu3VQVAEMiddleBlock.forward  s    ]LA }lC.;.A.A+
Hfe%**:x%PZZ[\^_`M215%--j&%RZZ[\^_abdef =0]LAr7   ra   )	rL   rM   rN   r+   r.   r   r   rE   rO   rP   s   @r6   rY  rY    s,    
(
U%6%6 
huO`O`Fa 
r7   rY  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  rK   Tr  r!   )r*   r+   lenchannel_multipliernum_resolutionsnum_res_blocksbase_channelsrG   in_channel_multiplierr,   
ModuleListdownrangeappendr@  attn_resolutionsrG  r  Moduleblockattn
attn_normsr   
downsample)r2   rV   ri  rf  rj  i_levelrq  rr  rs  block_in	block_outi_blockrl  r5   s                r6   r+   zEmu3VQVAEDownBlock.__init__  s   "6#<#<=$33,,#66 $u-?'@ @%:"MMO	T112 	#GMMOE==?DJ$'<W'EEH%(:7(CCI !4!45 
q($,%. %**67fF]F];]KK 7 ?@%%bllUW]ajn&op
q 99;DDJDI(DO$..22"@"JIIT"1	#r7   rB   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!   r9   r
   )	enumeraterl  rm  rh  rq  re  rr  rs  rH   r   r   rz   r   rg  rt  )
r2   rB   ru  blocksrx  r   r   r   r   r   s
             r6   rE   zEmu3VQVAEDownBlock.forward  s5   (3 	AOGV !4!45 = 5W 5m Dv{{#a',H$>F$5$5g$>}$MM:G:M:M7J&%$1$6$6z8VV[^$\$f$fghjk$lM$8FKK$8$G$JM$1$9$9*feU]$^$f$fghjkmnpq$rM$,}$<M= $..22 & 1 1- @	A" r7   rL   rM   rN   r+   r.   r   rE   rO   rP   s   @r6   rb  rb    s    ##JU%6%6 r7   rb  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+   re  rf  rg  rh  r   ri  r,   rk  upreversedrm  rn  r@  ro  rG  r  rp  rq  rr  rs  r   upsampleinsert)r2   rV   rA  rv  ru  rq  rr  rs  rw  rx  r  r5   s              r6   r+   zEmu3VQVAEUpBlock.__init__  s   "6#<#<=$33))''&*C*CB*GG--/d&:&: ;< 	"GMMOE==?DJ,,v/H/H/QQI !4!4q!89 V($,%.'5 %f555KK 7 ?@%%&:>8&TUV BBHBG&BM!|:8DGGNN1b!3	"r7   rB   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   r9   r
   )rz  r  rm  rh  rq  re  rr  rs  rH   r   r   rz   r   r  )r2   rB   r"  ru  r{  rx  r   r   r   r   r   s              r6   rE   zEmu3VQVAEUpBlock.forward3  sD   (27 	?OGV !4!4q!89 = 5W 5m\ Rv{{#a',H$>F$5$5g$>}l$[M:G:M:M7J&%$1$6$6z8VV[^$\$f$fghjk$lM$8FKK$8$G$JM$1$9$9*feU]$^$f$fghjkmnpq$rM$,}$<M= #dgg,** & >	?  r7   r|  rP   s   @r6   r~  r~    s(    #"JU%6%6 eFWFW r7   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 )Nr9   r:   r
   r!   r   r  rK   T)r  r  r4   r  rd  )r*   r+   ri  r   double_latentlatent_channelsrf  r.   r,   r   conv_inrb  
down_blockrY  middle_blockr  norm_outconv_outr   mathlog2temporal_downsample_factorrk  	time_convtime_res_stackrm  r1  rn  rh  r5  )r2   rV   ri  r   r  r  rf  r  rv  temporal_down_blocksir   _time_res_convr5   s                 r6   r+   zEmu3VQVAEEncoder.__init__H  s   ,,((,, 00#66.;q?* #5b#99xx{MqYZdef,V40B**bxUYbf*g ( 
  #499V-N-N#OP mmo+, 	(A.|\JDNN!!$'	( v,,- 	6A8()M &&}5	6r7   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:   r9   r   r
   r   )rH   rz   r  r  r  r  r.   r>  r  r   r  r  )r2   r  temporal_dimrB   r   layers         r6   rE   zEmu3VQVAEEncoder.forwardo  sH   #))!,+|++BH1C1CAB1GH \26))-8 m4}55m4---b,YATATUVUWAXY%--aAq!< NN 	:D /MU]]=99M	: (( 	1E!-0M	1 &--aAq!<r7   )rL   rM   rN   r+   r.   r   rE   rO   rP   s   @r6   r  r  G  s    %6NE$4$4 r7   r  c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )Emu3VQVAEDecoderrV   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:   rd  r
   r!   r   )rA  r   )r*   r+   r   ri  rf  r,   rk  r  rm  rh  r5  r  rn  r   r  r  r  r  r'  r   r  rY  r  r~  up_blockr  r  r  r  )
r2   rV   rA  rv  r  r  temp_upsample_block_numr  r   r5   s
            r6   r+   zEmu3VQVAEDecoder.__init__  s   ))''&*C*CB*GG mmov,,- 	6A8"22AWAWM &&}5		6 #&dii0Q0Q&R"S./ 	(A,V-C-CVE[E[\DNN!!$'	( yy""
 1R`a(0''&*C*CA*FF,^XF		
r7   rB   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   re   r9   r!   r
   r   r:   )r.   rg   r   r  r  r>  chunkrz   rH   r  r  r  r  r  )r2   rB   r"  hidden_quant_statesr  s        r6   rE   zEmu3VQVAEDecoder.forward  sp   #ii(E1M199!Q1aH (( 	=E"'(;"<	= ^^ 	FE"'(;"<5==1D#EE	F 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r7   )	rL   rM   rN   r$   r+   r.   r   rE   rO   rP   s   @r6   r  r    s+    %
 %
NU\\  r7   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)r5  rG  r@  r   c                    t        |t        j                  t        j                  f      r-t        j                  j                  |j                  dd       y t        |t        j                        rt        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_r0   rX   kaiming_uniform_r  sqrtrU   _calculate_fan_in_and_fan_outr   BatchNorm2dr7  r  	constant_)r2   r   fan_inr  bounds        r6   _init_weightszEmu3VQVAE._init_weights  s   fryy"))45GG##FMM	PV#W		*GG$$V]]diil$C{{&GGAA&--P	17!DIIf--  ufe< '  NOGGfmmQ/GGfkk1- Pr7   rV   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 )Nr9   r!   )r
   r!   r!   r*  r+  )r*   r+   rV   r  encoderr  decoderr   quantizere  rf  vision_spatial_factorr	  r  r   
quant_convpost_quant_convspatial_scale_factoreval	post_initr_   s     r6   r+   z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!		r7   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   r9   r
   )ndimrV   r  rH   rl   repeatr  r   r  r  squeezer  r   r  )r2   r  r  is_imager   r   r   r   r   rB   codesimage_tokenssingle_imager$  s                 r6   encodezEmu3VQVAE.encode  sX   $$){{==H2>2D2D/J&%'11!4;;AxAqQL<H<N<N9J(FE\2 &--aAq!<6 &--aAq!<m,+3u}}Q' '*,&D
"d D3tAw)C)CCDDFqDQRGVZVpVpLpHqFqqr
 

 
s   1AD=rB   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   r9   )r  rl   rH   r  r   flattenr   r   r   r  r  rz   rV   r  r  r  )r2   rB   r  r   r   r   r   quantr   
post_quantvideos              r6   decodezEmu3VQVAE.decode7  sK    %%*)33A6M.;.A.A+
Hfe''(=(=(?@;;r?

:xIQQRSUVXY[\^_`kkm))%0
aAq!,''1aA6
Z/t{{===KK$$T...D---
 'uQT{1E1r7   )rL   rM   rN   r$   config_classbase_model_prefixmain_input_name_supports_sdpa_supports_flash_attn_2_supports_flex_attn_no_split_modulesr  r+   r.   r   r  r  rO   rP   s   @r6   r  r    sj     #L$$ON!. *5<< ell 82ELL 2r7   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_mapr   eol_token_idimage_token_id)r2   r  s     r6   r+   z#Emu3ImageVocabularyMapping.__init__V  s+    "%MM/:'mmI6r7   c           	          t        | j                  j                         D cg c]  \  }}|j                  d      s| c}}      S c c}}w Nz<|visual tokensortedr  items
startswithr2   namevals      r6   r  z'Emu3ImageVocabularyMapping.image_tokens[  s8    DNN,@,@,BhytSdooVfFgshiih
   A	
A	
c           	          t        | j                  j                         D cg c]  \  }}|j                  d      s| c}}      S c c}}w r  r  r  s      r6   image_tokens_strz+Emu3ImageVocabularyMapping.image_tokens_str_  s8    T^^-A-A-Ci	ctWgGhtijjir  c                 t    | j                   D ci c]  }t        |dd       | j                  |     c}S c c}w )Nir   )r  r   r  )r2   tokens     r6   img2bpez"Emu3ImageVocabularyMapping.img2bpec  s5    FJF[F[\UE"RL!4>>%#88\\\s   #5c                 j    | j                   j                         D ci c]  \  }}||
 c}}S c c}}w ra   )r  r  )r2   rn   vs      r6   bpe2imgz"Emu3ImageVocabularyMapping.bpe2imgg  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!   r<   )r.   zerosmaxr  rP  r   r  r2   mappingrn   r  s       r6   bpe2img_mapping_tensorz1Emu3ImageVocabularyMapping.bpe2img_mapping_tensork  [    ++c$,,"3"3"56:%))LLL&&( 	DAqGAJ	r7   c                     t        j                  t        | j                  j	                               dz   t         j
                        }| j                  j                         D ]
  \  }}|||<    |S r  )r.   r  r  r  rP  r   r  r  s       r6   img2bpe_mapping_tensorz1Emu3ImageVocabularyMapping.img2bpe_mapping_tensorr  r  r7   	img_batchrw   c                 ,   |j                   }t        j                  |j                  d   dft        j                        | j
                  z  }| j                  |j                  d         }t        j                  ||gd      }|j                  |      S )Nr   r!   r  cpur:   re   )	devicer.   r/   rH   r   r  r  r=   rg   )r2   r  r  eol_row
img_tokenss        r6   convert_img2bpez*Emu3ImageVocabularyMapping.convert_img2bpey  sw    !!**iooa0!4EIIFIZIZZ00e1DE
YY
G4"=
}}V$$r7   c                     |j                   }|dd df   }| j                  |j                  d         }|j                  |      S )N.r:   r  )r  r  r=   )r2   r  r  r  s       r6   convert_bpe2imgz*Emu3ImageVocabularyMapping.convert_bpe2img  sG    !!c3B3h'	00e1DE
}}V$$r7   N)rL   rM   rN   r   r+   r   r  r  r  r  r  r  r   r.   r   r  r  r   r7   r6   r  r  Q  s    7
 j j k k ] ] 7 7    %ell); % %% %%,, %r7   r  aI  
    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 ([`Emu3Config`]):
            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.
zRThe bare emu3 Model outputting raw hidden-states without any specific head on top.c                   H    e Zd ZeZdZdZdgZddgZdZ	dZ
dZdZdZdZdZd Zy)	Emu3PreTrainedModelmodelTr   past_key_valuesr   Fc                    | 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 )Nr   )r@   std)rV   get_text_configinitializer_ranger  r  applyr  r,   rX   r   r0   r   normal_rU   zero_r   padding_idx)r2   r   r
  s      r6   r  z!Emu3PreTrainedModel._init_weights  s    kk))+==fi(LL--.BII 67MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . .r7   N)rL   rM   rN   r"   r  r  supports_gradient_checkpointingr  _skip_keys_device_placementr  r  _supports_quantized_cache_supports_cache_class_supports_static_cache!_supports_param_buffer_assignmentr  r  r   r7   r6   r  r    s[    
 L&*# $5m"D!N $ !(-%?r7   r  c                   ^     e Zd Zddef fdZ ej                         ed               Z xZ	S )Emu3RotaryEmbeddingrV   c                    t         |           t        |d      rG|j                  ;|j                  j	                  d|j                  j	                  d            | _        nd| _        |j                  | _        |j                  | _        || _	        t        | j
                     | _        | j                  | j                  |      \  }| _        | j                  d|d       | j                  | _        y )Nrope_scaling	rope_typetypedefaultinv_freqF)
persistent)r*   r+   hasattrr  r   r  max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrV   r   rope_init_fnattention_scalingregister_bufferr  original_inv_freq)r2   rV   r  r  r5   s       r6   r+   zEmu3RotaryEmbedding.__init__  s    6>*v/B/B/N#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%r7   c                 b   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        j                  |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   r:   r!   mpsr  F)device_typeenabledr9   re   r  )r  floatry   rH   r=   r  r  r  strr.   autocastr   rg   ro   r%  rp   r<   )
r2   rb   rq   inv_freq_expandedposition_ids_expandedr*  freqsembro   rp   s
             r6   rE   zEmu3RotaryEmbedding.forward  sV    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfk^^UC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s    BF%%F.ra   )
rL   rM   rN   r"   r+   r.   no_gradr   rE   rO   rP   s   @r6   r  r    s3    /z /" U]]_<  <r7   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.
zVThe bare Emu3Text Model outputting raw hidden-states without any specific head on top.c                       e Zd ZdZdef fdZd Zd Ze e	e
      	 	 	 	 	 	 	 	 	 d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   defd              Z	 ddej                  dej                  dej                  d	edef
dZedej                  dededej2                  dej4                  dej                  defd       Z xZS )Emu3TextModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Emu3TextDecoderLayer`]

    Args:
        config: Emu3TextConfig
    rV   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nr   )rV   F)r*   r+   pad_token_idr  
vocab_sizer,   r   r3   embed_tokensrk  rm  num_hidden_layersr   layersr(   r   normr  
rotary_embgradient_checkpointingr  r   s      r6   r+   zEmu3TextModel.__init__/  s     !.. ++LL):):F<N<NPTP`P`ammBGH`H`BabYfi0b
   2 28K8KL	-V<&+# 	 cs   Dc                     | j                   S ra   r9  rI   s    r6   get_input_embeddingsz"Emu3TextModel.get_input_embeddings?  s       r7   c                     || _         y ra   r@  r2   r   s     r6   set_input_embeddingsz"Emu3TextModel.set_input_embeddingsB  s
    !r7   	input_idsr   rq   r  inputs_embedsr   r   output_hidden_statesr   flash_attn_kwargsrw   c
                 ^   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|d u |d uz  rt	        d      | j
                  r%| j                  r|rt        j                  d       d}t        |t        d       t        f      st	        d      || j                  |      }|r|
t               }|	F||j                         nd}t        j                   |||j"                  d   z   |j$                        }	||	j'                  d      }| j)                  |||	||      }|}| j+                  ||      }|rdnd }|rdnd }| j,                  d | j                   j.                   D ]r  }|r||fz  }| j
                  r:| j                  r.| j1                  t3        |j4                  fi |
|||||||	|	      }n ||f||||||	|d	|
}|d   }|sj||d   fz  }t | j7                  |      }|r||fz  }t9        ||r|nd ||
      S )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FzBThe `past_key_values` should be either a `Cache` object or `None`.r   r!   r  r   )r   rq   r   r   r   r   r   )last_hidden_stater  rB   
attentions)rV   r   rG  r   rJ  r>  r   r   r   r  r  r   r9  r   get_seq_lengthr.   arangerH   r  rl   _update_causal_maskr=  r;  r:  _gradient_checkpointing_funcr   __call__r<  r   )r2   rE  r   rq   r  rF  r   r   rG  r   rH  past_seen_tokensr   rB   r   all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                      r6   rE   zEmu3TextModel.forwardE  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<YZZ&&4==Yj I /DJ+>?abb  --i8M0*nO!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L..M>?L]
 & #oom\J #7BD0d![[)H4;;+H+HI  	6M#!m%55!**t}} $ A AM22H6GH! #%"'
! !.!
!#.!-#2&7'#1(;
! (
! *!,M =#3"55A 	6D 		-0  -!11&+/8Od+%	
 	
r7   input_tensorc           
         | j                   j                  dk(  r||dk(  j                         r|S y | j                   j                  dk(  r7t        |t        j
                        rt        |      }t        |t              r|S ||j                         nd}t        |t              }| j                   j                  dk(  r(|s&|s$t        j                  |||| j                        ry |j                  |j                  }	}|j                  d   }
|r|j!                         }n1t        |t        j
                        r|j                  d   n||
z   dz   }| j#                  ||
|||	||j                  d   	      }| j                   j                  dk(  rQ|O|j                  j$                  d
v r7|s5t	        j&                  |      j(                  }t        j*                  ||      }|S )Nflash_attention_2r   flex_attentionr   r   )rF  past_key_values_lengthis_trainingr!   r:   )sequence_lengthtarget_lengthr<   r  r   r   )cudaxpu)rV   r   anyr  r.   r   r&   r%   rM  r   r   _ignore_causal_mask_sdpar   r<   r  rH   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr  finfomin_unmask_unattended)r2   r   rW  r   r  r   rR  using_static_cacher<   r  r]  r^  r   	min_dtypes                 r6   rO  z!Emu3TextModel._update_causal_mask  s    ;;++/BB)~/D.I.I.K%%;;++/??.%,,7!<^!L.)4%%
 @O?Z?99;`a'E ;;++v5>PYj%>>*'7 MM	 $**L,?,?v&,,Q/+??AM nell; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**o=%
 E*..I0CCKQZ[Kr7   r]  r^  r<   r  r   c                    | | j                         dk(  r| }|S t        j                  |      j                  }	t        j                  ||f|	||      }|dk7  rt        j
                  |d      }|t        j                  ||      |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }
|ddddddd|
f   | ddddddf   j                  |j                        z   }|dk(  }|ddddddd|
f   j                  ||	      |ddddddd|
f<   |S )	a  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to place the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        Nr   )
fill_valuer<   r  r!   )diagonalrJ  r:   r   )rf   r.   re  rf  fulltriurN  rz   ry   clonerH   r=   r  masked_fill)r   r]  r^  r<   r  r   r   r   r   ri  mask_lengthpadding_masks               r6   rd  zCEmu3TextModel._prepare_4d_causal_attention_mask_with_cache_position  sy   B %.*<*<*>!*C(K* ' E*..I** -0Ye\bK !##jjqA5<<fEH^H^_acdHeeeK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c )6Aq!\k\12 r7   )	NNNNNNNNN)F)rL   rM   rN   r   r"   r+   rA  rD  r   r   EMU3_TEXT_INPUTS_DOCSTRINGr   r.   r   r   r   r   r   r   r   r   rE   rO  staticmethodr   r<   r  rd  rO   rP   s   @r6   r5  r5  #  s   
z  !" *+EF 151537+/59$(,0/359i
E,,-i
 !.i
 u//0	i

 "%i
   1 12i
 D>i
 $D>i
 'tni
 !!1!12i
 $$89i
 
!i
 G i
b #(DD llD 	D
 D  DL 777 7 {{	7
 7 7 7 7r7   r5  c                       e Zd Zy)KwargsForCausalLMN)rL   rM   rN   r   r7   r6   rv  rv  3  s    r7   rv  c                       e Zd ZdgZddiZddgdgfiZeZ fdZd Z	d Z
d	 Zd
 Zd Zd Ze eddd       ee       eed      	 	 	 	 	 	 	 	 	 	 	 d deej.                     deej0                     deej.                     dee   deej4                     deej.                     dee   dee   dee   deej.                     deeej0                  f   dee   defd                            Z  xZ!S )!Emu3ForCausalLMzlm_head.weightlm_headcolwise_reprB   logitsc                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y )NFrT   )
r*   r+   r5  r  r8  r,   rX   r3   ry  r  r_   s     r6   r+   zEmu3ForCausalLM.__init__<  sU     "6*
 ++yy!3!3V5F5FUS 	r7   c                 .    | j                   j                  S ra   r  r9  rI   s    r6   rA  z$Emu3ForCausalLM.get_input_embeddingsE  s    zz&&&r7   c                 &    || j                   _        y ra   r~  rC  s     r6   rD  z$Emu3ForCausalLM.set_input_embeddingsH  s    "'

r7   c                     | j                   S ra   ry  rI   s    r6   get_output_embeddingsz%Emu3ForCausalLM.get_output_embeddingsK  s    ||r7   c                     || _         y ra   r  )r2   new_embeddingss     r6   set_output_embeddingsz%Emu3ForCausalLM.set_output_embeddingsN  s	    %r7   c                     || _         y ra   r  )r2   r  s     r6   set_decoderzEmu3ForCausalLM.set_decoderQ  s	    
r7   c                     | j                   S ra   r  rI   s    r6   get_decoderzEmu3ForCausalLM.get_decoderT  s    zzr7   num_logits_to_keepz4.50logits_to_keep)versionnew_namer#   output_typer  rE  r   rq   r  rF  labelsr   r   rG  r   r   rw   c                    ||n| j                   j                  }|	|	n| j                   j                  }	 | j                  d||||||||	|
d	|}|j                  }t        |t              rt        | d      n|}| j                  |dd|ddf         }d}|* | j                  d||| j                   j                  d|}t        |||j                  |j                  |j                        S )a  
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

            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]
        ```N)	rE  r   rq   r  rF  r   r   rG  r   )r{  r  r8  )lossr{  r  rB   rL  r   )rV   r   rG  r  rK  r  r   slicery  loss_functionr8  r   r  rB   rL  )r2   rE  r   rq   r  rF  r  r   r   rG  r   r  r   r   rB   slice_indicesr{  r  s                     r6   rE   zEmu3ForCausalLM.forwardW  s   d 2C1N-TXT_T_TqTq$8$D $++JjJj 	
 ,64:: ,
)%+'/!5),
 ,
  118B>SV8W~ot4]kmA}a,?@A%4%%pVFt{{OeOepiopD%#33!//))
 	
r7   )NNNNNNNNNNr   )"rL   rM   rN   _tied_weights_keys_tp_plan_pp_planr#   r  r+   rA  rD  r  r  r  r  r   r    r   rs  r   r   r   r.   r   r   r   r   r   r	   r   r   rv  rE   rO   rP   s   @r6   rx  rx  6  s   *+=)H_-z:;H!L'(& )6DTU*+EF+AP`a 151537+/59-1$(,0/35934P
E,,-P
 !.P
 u//0	P

 "%P
   1 12P
 ))*P
 D>P
 $D>P
 'tnP
 !!1!12P
 c5<</0P
 *+P
 
 P
 b G V P
r7   rx  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                    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 ra   )r*   r+   rx  _from_configtext_config
text_modelr  	vq_configvqmodelr  vocabulary_mapvocabulary_mappingr  r_   s     r6   r+   z%Emu3ForConditionalGeneration.__init__  sY     )66v7I7IJ !1!12"<V=R=R"S 	r7   c                 6    | j                   j                         S ra   )r  rA  rI   s    r6   rA  z1Emu3ForConditionalGeneration.get_input_embeddings
  s    3355r7   c                 :    | j                   j                  |       y ra   )r  rD  rC  s     r6   rD  z1Emu3ForConditionalGeneration.set_input_embeddings  s    ,,U3r7   r  r  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  r  r  r  r  r.   rg   )r2   r  r  image_tokens_listtokensbpe_tokens_list
bpe_tokenss          r6   get_image_tokensz-Emu3ForConditionalGeneration.get_image_tokens  sc     !LL//kJctuY_422BB6JRRTuuYY/
 vs   0A*r  r   r   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.
        Nr:   r!   )r   r  r  r  r  )r2   r  r   r   	sequencesimages         r6   decode_image_tokensz0Emu3ForConditionalGeneration.decode_image_tokens!  sX     !CRC(--b&%!)D	..>>yI##L1r7   r  rE  r   rq   r  rF  r   r   rG  r   r  r  rw   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)
rE  r   rq   r  rF  r   r   rG  r   r  )rV   r   rG  rJ  r  r  r  r=   r  r<   masked_scatterr  )r2   rE  r  r  r   rq   r  rF  r   r   rG  r   r  r  r  special_image_masks                   r6   rE   z$Emu3ForConditionalGeneration.forward4  s   J 2C1N-TXT_T_TqTq$8$D $++JjJj 	 -t";<s  #(Av  #00{KL!*d.E.E.T.T!T'??9+;+;Y__ML!001C\RI )%+'/!5))  
 	
r7   c	                 R    t        |   |f|||||||d|	}
|d   dk7  rd |
d<   |
S )N)r  r   rF  r   rq   r  r   r   r  )r*   prepare_inputs_for_generation)r2   rE  r  r   rF  r   rq   r   r  r   model_inputsr5   s              r6   r  z:Emu3ForConditionalGeneration.prepare_inputs_for_generation  sZ     w<

+)')%%

 

 !!+/L(r7   )NNNNNNNNNNNNr   )NNNNNTN)rL   rM   rN   r  r  r+   rA  rD  r.   r   r   r  r3  r   r  r   r   EMU3_INPUTS_DOCSTRINGr   r   _CONFIG_FOR_DOCr   r   r   r   r	   rE   r  rO   rP   s   @r6   r  r    s    56"64U->-> UM]M] " ]]0@0@ # VY  $ *+@A+AP_` 1548.21537+/59$(,0/359-134c
E,,-c
 u001c
 ell+	c

 !.c
 u//0c
 "%c
   1 12c
 D>c
 $D>c
 'tnc
 !!1!12c
 ))*c
 c5<</0c
 
 c
 a B c
P  r7   r  )r  rx  r5  r  r  )Nr!   )r   )gr  	functoolsr   r   typingr   r   r   r   r	   r.   torch.nnr,   torch.nn.functionalr   r   activationsr   cache_utilsr   r   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   r   r   utils.deprecationr    configuration_emu3r"   r#   r$   !torch.nn.attention.flex_attentionr%   integrations.flex_attentionr&   
get_loggerrL   r   r  rp  r(   rR   rj   ru   r   r   r   r,  r   r   r   r   r   r   r	  r  r'  r1  r5  r@  rG  r  rS  rY  rb  r~  r  r  EMU3_VQ_START_DOCSTRINGr  r  EMU3_START_DOCSTRINGr  r  rs  r5  rv  rx  r  r  __all__r   r7   r6   <module>r     sg  .  . 9 9     ! ; ; ) > B O K F &   1 K K  !;J 
		H	% J")) J(bii  (6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % %4I)BII I)XHryy HV$ryy $D	RYY 	299 bii :!299 !H		 .")) &.(299 .(b<(299 <(~G)bii G)TV V299 D8 8v7ryy 7tCryy CLCryy CL "  c2 c2c2L3% 3%l " X?/ ?	?<<")) <DD N \I' I	IX ?,j >u
)? u
pL ^|#6 |~ sr7   