
    Uhl7                       d dl Z d dl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 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ 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. ddl/m0Z0m1Z1m2Z2  e-       rd dl3m4Z4 ddl5m6Z6  e.jn                  e8      Z9 ed       G d dejt                               Z; G d dejt                        Z<d Z=dadZ>de	j~                  de@de	j~                  fdZA	 dbd ejt                  d!e	j~                  d"e	j~                  d#e	j~                  d$ee	j~                     d%eBd&eBfd'ZC G d( d)ejt                        ZD G d* d+e      ZE G d, d-ejt                        ZF G d. d/ejt                        ZG G d0 d1ejt                        ZH G d2 d3ejt                        ZI G d4 d5ejt                        ZJ G d6 d7ejt                        ZK G d8 d9ejt                        ZL G d: d;ejt                        ZM G d< d=ejt                        ZN G d> d?ejt                        ZO G d@ dAej                        ZQ G dB dCejt                        ZR G dD dEejt                        ZS G dF dGejt                        ZT G dH dIejt                        ZU G dJ dKejt                        ZV e+dLM       G dN dOe&             ZW G dP dQ      ZXe+ G dR dSe&             ZY G dT dUejt                        ZZe+ G dV dWeY             Z[ G dX dYee*      Z\e+ G dZ d[eYe             Z] G d\ d]eY      Z^ G d^ d_eYe      Z_g d`Z`y)c    N)cached_property)CallableListOptionalTupleUnion   )ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hub)AttentionMaskConverter)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)
LossKwargsauto_docstringcan_return_tupleis_torch_flex_attn_availablelogging   )
Emu3ConfigEmu3TextConfigEmu3VQVAEConfig)	BlockMask)make_flex_block_causal_maskRMSNormc                   ,     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      x/var/www/catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/emu3/modeling_emu3.pyr)   zEmu3RMSNorm.__init__9   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rsqrtr/   r.   )r0   hidden_statesinput_dtypevariances       r4   forwardzEmu3RMSNorm.forwardA   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r5   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler.   shaper/   r0   s    r4   
extra_reprzEmu3RMSNorm.extra_reprH   s*    ))*+6$2G2G1HIIr5   )ư>)__name__
__module____qualname__r)   rC   rH   __classcell__r3   s   @r4   r&   r&   7   s    $;Jr5   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)   configr1   intermediate_sizer*   Linearmlp_bias	gate_projup_proj	down_projr
   
hidden_actact_fnr0   rT   r3   s     r4   r)   zEmu3MLP.__init__M   s    !--!'!9!94#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r5   c                     | j                  | j                  | j                  |            | j                  |      z        }|S N)rZ   r\   rX   rY   )r0   xrZ   s      r4   rC   zEmu3MLP.forwardW   s6    NN4;;t~~a/@#ADLLQRO#ST	r5   rJ   rK   rL   r)   rC   rM   rN   s   @r4   rP   rP   L   s    0r5   rP   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..Nr8   r7   dim)rF   r,   cat)r`   x1x2s      r4   rotate_halfrh   \   sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r5   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.
    )	unsqueezerh   )qkcossinposition_idsunsqueeze_dimq_embedk_embeds           r4   apply_rotary_pos_embrs   c   sY    ( --
&C
--
&C3w;q>C/0G3w;q>C/0GGr5   r@   n_repreturnc                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)rF   expandreshape)r@   rt   batchnum_key_value_headsslenhead_dims         r4   	repeat_kvr}   ~   so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr5   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 )Nr7   r	   r8   )rd   r:   )ptrainingr   )r}   num_key_value_groupsr,   matmul	transposerF   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                r4   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$$r5   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' paperrT   	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|         TrR   )r(   r)   rT   r   getattrr1   num_attention_headsr|   rz   r   r   attention_dropout	is_causalr*   rV   attention_biasq_projk_projv_projo_projr0   rT   r   r3   s      r4   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
r5   r@   position_embeddingsr   past_key_valuecache_positionr   ru   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 )Nr8   r   r7   )rn   rm   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   )rF   r|   r   viewr   r   r   rs   updater   r   rT   _attn_implementationgetloggerwarning_oncer   r   r   r   rx   r   r   )r0   r@   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   rm   rn   cache_kwargsattention_interfacer   r   s                     r4   rC   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((r5   NN)rJ   rK   rL   __doc__r   intr)   r,   Tensorr   r   r   
LongTensorr   r   rC   rM   rN   s   @r4   r   r      s    G
z 
c 
8 +/590)||0) #5<<#=>0) !.	0)
 !0) !!1!120) -.0) 
u||Xell3XeELL>Q5RR	S0)r5   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 )Emu3DecoderLayerrT   r   c                 h   t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        t        j                  |j                        | _        y )N)rT   r   r2   )r(   r)   r1   r   	self_attnrP   mlpr&   rms_norm_epsinput_layernormpost_attention_layernormr*   Dropoutr   r   r   s      r4   r)   zEmu3DecoderLayer.__init__   s    !--&f	J6?*6+=+=6CVCVW(3F4F4FFL_L_(`%zz&":":;r5   r@   r   ro   r   r   	use_cacher   r   ru   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
        )r@   r   ro   r   r   r   r   r    )r   r   r   r   r   )r0   r@   r   ro   r   r   r   r   r   r   residualself_attn_weightsoutputss                r4   rC   zEmu3DecoderLayer.forward   s    > !,,]; ,:4>> 
,
')%)/) 3
,
 
,
(( !4<<#>> !55mD/ 4<<#>> ")++Gr5   )NNNFFNN)rJ   rK   rL   r   r   r)   r,   r   r   r   r   boolr   FloatTensorrC   rM   rN   s   @r4   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<r5   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.
    rT   c                    t         |           t        j                  |j                  |j
                        | _        | j                  j                  j                  j                  d|j                  z  d|j                  z         y )Ng            ?)
r(   r)   r*   	Embeddingcodebook_size	embed_dim	embeddingr.   datauniform_r]   s     r4   r)   z!Emu3VQVAEVectorQuantizer.__init__G  sb    f&:&:F<L<LM""++D63G3G,GvOcOcIcdr5   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	      r7   r8   T)rd   r9   rc   )rF   permuter   r   r,   sumr   r.   r   r   argmin)r0   r   
batch_sizetemporalchannelsheightwidthhidden_state_flattenedhidden_state_sumembedding_sum	distancesmin_encoding_indicess               r4   rC   z Emu3VQVAEVectorQuantizer.forwardL  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\]##r5   )
rJ   rK   rL   r   r!   r)   r,   r   rC   rM   rN   s   @r4   r   r   <  s&    e e
$ELL $r5   r   c                   $     e Zd Z fdZd Z xZS )Emu3VQVAEEncoderConvDownsamplec                 `    t         |           t        j                  ||ddd      | _        y )Nr	   r7   r   kernel_sizestridepaddingr(   r)   r*   Conv2dconvr0   in_channelsr3   s     r4   r)   z'Emu3VQVAEEncoderConvDownsample.__init___  '    IIk;AaYZ[	r5   c                 Z    t        j                  |ddd      }| j                  |      }|S )N)r   r   r   r   constantr   )padmoder   )Fr   r   r0   r@   s     r4   rC   z&Emu3VQVAEEncoderConvDownsample.forwardc  s+    mJVWX		-0r5   ra   rN   s   @r4   r   r   ^  s    \r5   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     r4   r)   z%Emu3VQVAEEncoderConvUpsample.__init__k  r   r5   c                 X    t        j                  |dd      }| j                  |      }|S )N       @nearestscale_factorr   )r   interpolater   r   s     r4   rC   z$Emu3VQVAEEncoderConvUpsample.forwardo  s(    m#IV		-0r5   ra   rN   s   @r4   r   r   j  s    \r5   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   r8   r7   )r7   r   )r   )r(   r)   zipr   r*   Conv3dr   )
r0   r	  r
  r   r   
one_kernel
one_stridepadding_sizespad_sizer3   s
            r4   r)   zEmu3VQVAEConv3d.__init__v  s     	ORS^_`_aSbdjklkmdnOop5KZj0pp%dd+ 	JHLLX]X\98q=IIL	JII	
	 qs   B"r@   c                 h    t        j                  || j                        }| j                  |      }|S r_   )r   r   r   r   r   s     r4   rC   zEmu3VQVAEConv3d.forward  s*    mT\\:		-0r5   )
rJ   rK   rL   r   r   r)   r,   r   rC   rM   rN   s   @r4   r  r  u  sF    

 
 3Z	

 c

,U\\ r5   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    rI   Tnum_channels
num_groupsr2   affiner   r   r   )r(   r)   r*   	GroupNorm
norm_layerr   conv_yconv_br0   r   r  r3   s      r4   r)   zEmu3VQVAESpatialNorm.__init__  sn    
 	,,%	
 ii
 ii
r5   r@   quant_statesc                     t        j                  ||j                  dd  d      }| j                  |      }|| j	                  |      z  | j                  |      z   }|S )Nr   r  )sizer   )r   r  rF   r  r  r  )r0   r@   r!  s      r4   rC   zEmu3VQVAESpatialNorm.forward  sX    }}\8K8KBC8PW`a6%L(AADKKP\D]]r5   	rJ   rK   rL   r   r)   r,   r   rC   rM   rN   s   @r4   r  r    s5    

 
8U\\  r5   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   r0   r	  r
  r3   s      r4   r)   z"Emu3VQVAETemporalUpsample.__init__  (    
 	#!	
	r5   r@   c                 P   |j                   \  }}}}}|j                  ddddd      j                         j                  |d|      }t	        j
                  |dd	      }|j                  ||||d      j                  ddddd      j                         }| j                  |      }|S )
Nr   r   r	   r   r7   r8   r  r  r  )rF   r   r   r   r   r  r   )r0   r@   r   r   r   r   r   s          r4   rC   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r5   r$  rN   s   @r4   r&  r&    s*    

 
U\\ r5   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	   )r7   r   r   r*  r+  r,  s      r4   r)   z$Emu3VQVAETemporalDownsample.__init__  r-  r5   r@   c                 (    | j                  |      }|S r_   )r   r   s     r4   rC   z#Emu3VQVAETemporalDownsample.forward  s    		-0r5   r$  rN   s   @r4   r0  r0    s*    

 
U\\ r5   r0  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      r4   r)   z%Emu3VQVAETemporalResnetBlock.__init__  s    
 	&+7+?K\^^K0
$!	

 ^^L1
$!	

 t000 "		!D 1r5   c                 L   |}| j                  |      }|t        j                  |      z  }| j                  |      }| j	                  |      }|t        j                  |      z  }| j                  |      }| j                  | j                  k7  r| j                  |      }||z   S r_   )	r7  r,   sigmoidr8  r9  r:  r   r  r;  )r0   r@   r   s      r4   rC   z$Emu3VQVAETemporalResnetBlock.forward  s     

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

=1

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

=1t000((2H-''r5   r_   ra   rN   s   @r4   r4  r4    s     @(r5   r4  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  rI   Tr  r	   r   r   r   )r(   r)   r   r  r@  r*   r  r7  r9  r  r   r8  r:  r;  )r0   r   r  r@  r3   s       r4   r)   zEmu3VQVAEResnetBlock.__init__  s    	&&2&:{(,!;2SW`deDJ<BTXaefDJ-nkJDJ-nlKDJYY

 YY

 t000 "		!D 1r5   r@   c                 v   | j                   dn|f}|} | j                  |g| }|t        j                  |      z  }| j	                  |      } | j
                  |g| }|t        j                  |      z  }| j                  |      }| j                  | j                  k7  r| j                  |      }||z   S Nr   )
r@  r7  r,   r=  r8  r9  r:  r   r  r;  )r0   r@   r@  	norm_argsr   s        r4   rC   zEmu3VQVAEResnetBlock.forward>  s    --5BN;L	 "

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

=1"

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

=1t000((2H-''r5   r   r_   )
rJ   rK   rL   r   r   r)   r,   r   rC   rM   rN   s   @r4   r?  r?    sU     '+(,	** sm* !	*X(U\\ (8ELLCY (r5   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   rT   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)   rT   r1   r   r   	num_headsr|   
ValueErrorscaler   r   r   r*   rV   r   r   r   out_projr   r]   s     r4   r)   z Emu3VQVAEAttentionBlock.__init__S  s$   ++33$..8==4>>)T^^;MdnnM] ^NN#2'  ]]D(
//ii?ii?ii?		$..$..A %&!r5   r@   r   r   ru   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   r7   r   r   r   r   )r   r   r   N)rF   r   r   r   r   rH  r|   r   r   rT   r   r   r   r   r   rJ  r   r   rx   r   rK  )r0   r@   r   r   r   
seq_lengthr   querieskeysvaluesr   r   r   s                r4   rC   zEmu3VQVAEAttentionBlock.forwardj  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((r5   )NF)rJ   rK   rL   r   r!   r)   r,   r   r   r   r   rC   rM   rN   s   @r4   rF  rF  P  sm    G& &4 26,1	-)||-) !.-) $D>	-)
 
u||Xell33	4-)r5   rF  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 rC  )r(   r)   )r0   r   r3   s     r4   r)   zEmu3VQVAEGroupNorm.__init__  s    "6"r5   c                     t        j                  || j                  | j                  | j                  | j
                        S r_   )r   
group_normr  r.   rS   r2   )r0   inputr!  s      r4   rC   zEmu3VQVAEGroupNorm.forward  s)    ||E4??DKKDHHUUr5   r_   )rJ   rK   rL   r   r)   rC   rM   rN   s   @r4   rR  rR    s    #Vr5   rR  c                   `     e Zd Zd fd	Zddej
                  deej
                     fdZ xZS )Emu3VQVAEMiddleBlockc                     t         |           t        |||      | _        t	        |      | _        |t        |ddd      | _        nt        ||      | _        t        |||      | _	        y )Nr   r  r@  r  rI   Tr  )
r(   r)   r?  block_1rF  attn_1rR  	attn_normr  block_2)r0   rT   r   r@  r3   s       r4   r)   zEmu3VQVAEMiddleBlock.__init__  so    +#$)

 .f5!/[UW]ajnoDN1.+NDN+#$)
r5   r@   r!  c                 b   | j                  ||      }|}| j                  ||      }|j                  \  }}}}|j                  ||||z        j	                  dd      }| j                  |      d   }|j                  ||||      j                  dddd      }||z   }| j                  ||      }|S )Nr   r7   r   r	   )	r[  r]  rF   r   r   r\  rx   r   r^  )r0   r@   r!  r   r   r   r   r   s           r4   rC   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r5   r_   )	rJ   rK   rL   r)   r,   r   r   rC   rM   rN   s   @r4   rX  rX    s,    
(
U%6%6 
huO`O`Fa 
r5   rX  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  rI   Tr  r   )r(   r)   lenchannel_multipliernum_resolutionsnum_res_blocksbase_channelsrE   in_channel_multiplierr*   
ModuleListdownrangeappendr?  attn_resolutionsrF  r  Moduleblockattn
attn_normsr   
downsample)r0   rT   rh  re  ri  i_levelrp  rq  rr  block_in	block_outi_blockrk  r3   s                r4   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	#r5   r@   c                 >   t        | j                        D ]  \  }}t        | j                        D ]  } |j                  |   |      }t        |j                        dkD  s1|} |j                  |   |      }|j                  \  }}}}	|j                  ||||	z        j                  dd      } |j                  |   |      d   }|j                  |||	|      j                  dddd      }||z   } || j                  dz
  k7  s|j                  |      } |S )Nr   r   r7   r	   )	enumeraterk  rl  rg  rp  rd  rq  rr  rF   r   r   rx   r   rf  rs  )
r0   r@   rt  blocksrw  r   r   r   r   r   s
             r4   rC   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" r5   rJ   rK   rL   r)   r,   r   rC   rM   rN   s   @r4   ra  ra    s    ##JU%6%6 r5   ra  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 )Nr8   r   rZ  r   )r(   r)   rd  re  rf  rg  r   rh  r*   rj  upreversedrl  rm  r?  rn  rF  r  ro  rp  rq  rr  r   upsampleinsert)r0   rT   r@  ru  rt  rp  rq  rr  rv  rw  r  r3   s              r4   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	"r5   r@   r!  c                 h   t        | j                  d d d         D ]  \  }}t        | j                  dz         D ]  } |j                  |   ||      }t        |j                        dkD  s2|} |j                  |   ||      }|j                  \  }}}	}
|j                  |||	|
z        j                  dd      } |j                  |   |      d   }|j                  ||	|
|      j                  dddd      }||z   } |t        | j                        dz
  k7  s|j                  |      } |S )Nr8   r   r   r7   r	   )ry  r  rl  rg  rp  rd  rq  rr  rF   r   r   rx   r   r  )r0   r@   r!  rt  rz  rw  r   r   r   r   r   s              r4   rC   zEmu3VQVAEUpBlock.forward+  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,** & >	?  r5   r{  rN   s   @r4   r}  r}    s(    #"JU%6%6 eFWFW r5   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 )Nr7   r8   r	   r   r   r  rI   T)r  r  r2   r  rc  )r(   r)   rh  r   double_latentlatent_channelsre  r,   r*   r   conv_inra  
down_blockrX  middle_blockr  norm_outconv_outr   mathlog2temporal_downsample_factorrj  	time_convtime_res_stackrl  r0  rm  rg  r4  )r0   rT   rh  r   r  r  re  r  ru  temporal_down_blocksir   _time_res_convr3   s                 r4   r)   zEmu3VQVAEEncoder.__init__@  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	6r5   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   r8   r7   r   r	   r   )rF   rx   r  r  r  r  r,   r=  r  r   r  r  )r0   r  temporal_dimr@   r   layers         r4   rC   zEmu3VQVAEEncoder.forwardg  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!<r5   )rJ   rK   rL   r)   r,   r   rC   rM   rN   s   @r4   r  r  ?  s    %6NE$4$4 r5   r  c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )Emu3VQVAEDecoderrT   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 )Nr8   rc  r	   r   r   )r@  r   )r(   r)   r   rh  re  r*   rj  r  rl  rg  r4  r  rm  r   r  r  r  r  r&  r   r  rX  r  r}  up_blockr  r  r  r  )
r0   rT   r@  ru  r  r  temp_upsample_block_numr  r   r3   s
            r4   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		
r5   r@   r!  c                    t        j                  ||fd      }|j                  ddddd      }| j                  D ]
  } ||      } | j                  D ]"  } ||      }|t        j
                  |      z  }$ |j                  ddddd      }t        j                  |dd      \  }} |j                  dg|j                  dd   } |j                  dg|j                  dd   }| j                  |      }| j                  ||      }| j                  ||      }| j                  ||      }|t        j
                  |      z  }| j                  |      }|S )Nr   rc   r7   r   r	   r   r8   )r,   re   r   r  r  r=  chunkrx   rF   r  r  r  r  r  )r0   r@   r!  hidden_quant_statesr  s        r4   rC   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r5   )	rJ   rK   rL   r!   r)   r,   r   rC   rM   rN   s   @r4   r  r    s+    %
 %
NU\\  r5   r  aF  
    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).
    )custom_introc                        e Zd ZeZd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)r4  rF  r?  r   c                 |   t        |t        j                  t        j                  f      rt        j                  j                  |j                  dd       |j                  qt        j                  j                  |j                        \  }}dt        j                  |      z  }t        j                  j                  |j                  | |       y 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 t        |t        j$                        rc|j                  j&                  j)                          |j*                  2|j                  j&                  |j*                     j-                          y y y )
Nfan_outrelu)r   nonlinearityr      )ar   r   r   )
isinstancer*   r   r  initkaiming_normal_r.   rS   _calculate_fan_in_and_fan_outr  sqrtr   rV   kaiming_uniform_BatchNorm2dr6  r  	constant_r   r   normal_padding_idxzero_)r0   r~   fan_inr  bounds        r4   _init_weightszEmu3VQVAE._init_weights  s   fryy"))45GG##FMM	PV#W{{&GGAA&--P	DIIf--  ufe< ' 		*GG$$V]]diil$C{{&GGAA&--P	17!DIIf--  ufe< '  NOGGfmmS1GGfkk3/-MM&&(!!-""6#5#56<<> . .r5   rT   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 )Nr7   r   )r	   r   r   r)  r*  )r(   r)   rT   r  encoderr  decoderr   quantizerd  re  vision_spatial_factorr  r  r   
quant_convpost_quant_convspatial_scale_factoreval	post_initr]   s     r4   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!		r5   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   r7   r	   )ndimrT   r  rF   rj   repeatr  r   r  r  squeezer  r   r  )r0   r  r  is_imager   r   r   r   r   r@   codesimage_tokenssingle_imager#  s                 r4   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=r@   c                    |j                   dk(  }|r|j                  d      }|j                  \  }}}}| j                  j	                  |j                               }|j                  d   }|j                  |||||      j                  ddddd      j                         }| j                  |      }	|j                  ddddd      }|	j                  ddddd      }	| j                  |	|      }
|
j                  ||| j                  j                  z  | j                  j                  || j                  z  || j                  z        }
|r	|
d d df   S |
S )Nr	   r   r8   r   r   r7   )r  rj   rF   r  r   flattenr   r   r   r  r  rx   rT   r  r  r  )r0   r@   r  r   r   r   r   quantr   
post_quantvideos              r4   decodezEmu3VQVAE.decode'  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1r5   )rJ   rK   rL   r!   config_classbase_model_prefixmain_input_name_supports_sdpa_supports_flash_attn_2_supports_flex_attn_supports_attention_backend_no_split_modulesr  r)   r,   r   r  r  rM   rN   s   @r4   r  r    sp     #L$$ON!"&?* *5<< ell 82ELL 2r5   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)r0   r  s     r4   r)   z#Emu3ImageVocabularyMapping.__init__F  s+    "%MM/:'mmI6r5   c           	          t        | j                  j                         D cg c]  \  }}|j                  d      s| c}}      S c c}}w Nz<|visual tokensortedr  items
startswithr0   namevals      r4   r  z'Emu3ImageVocabularyMapping.image_tokensK  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      r4   image_tokens_strz+Emu3ImageVocabularyMapping.image_tokens_strO  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  )r0   tokens     r4   img2bpez"Emu3ImageVocabularyMapping.img2bpeS  s5    FJF[F[\UE"RL!4>>%#88\\\s   #5c                 j    | j                   j                         D ci c]  \  }}||
 c}}S c c}}w r_   )r  r  )r0   rl   vs      r4   bpe2imgz"Emu3ImageVocabularyMapping.bpe2imgW  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  rO  r   r  r0   mappingrl   r  s       r4   bpe2img_mapping_tensorz1Emu3ImageVocabularyMapping.bpe2img_mapping_tensor[  [    ++c$,,"3"3"56:%))LLL&&( 	DAqGAJ	r5   c                     t        j                  t        | j                  j	                               dz   t         j
                        }| j                  j                         D ]
  \  }}|||<    |S r  )r,   r  r  r  rO  r   r  r  s       r4   img2bpe_mapping_tensorz1Emu3ImageVocabularyMapping.img2bpe_mapping_tensorb  r  r5   	img_batchru   c                 ,   |j                   }t        j                  |j                  d   dft        j                        | j
                  z  }| j                  |j                  d         }t        j                  ||gd      }|j                  |      S )Nr   r   r  cpur8   rc   )	devicer,   r-   rF   r   r  r  r;   re   )r0   r   r  eol_row
img_tokenss        r4   convert_img2bpez*Emu3ImageVocabularyMapping.convert_img2bpei  sw    !!**iooa0!4EIIFIZIZZ00e1DE
YY
G4"=
}}V$$r5   c                     |j                   }|dd df   }| j                  |j                  d         }|j                  |      S )N.r8   r  )r  r  r;   )r0   r   r  r  s       r4   convert_bpe2imgz*Emu3ImageVocabularyMapping.convert_bpe2imgp  sG    !!c3B3h'	00e1DE
}}V$$r5   N)rJ   rK   rL   r   r)   r   r  r  r  r  r  r  r   r,   r   r  r  r   r5   r4   r  r  A  s    7
 j j k k ] ] 7 7    %ell); % %% %%,, %r5   r  c                   L    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d Zy)	Emu3PreTrainedModelmodelTr   past_key_valuesr   Fc                    | j                   j                         j                  }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 t        |t              r&|j                  j                  j                  d       y y )Nr   )r>   stdr   )rT   get_text_configinitializer_ranger  r*   rV   r   r.   r   r  rS   r  r   r  r&   fill_)r0   r~   r  s      r4   r  z!Emu3PreTrainedModel._init_weights  s    kk))+==fryy"))45MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> .,MM$$S) -r5   N)rJ   rK   rL   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  r   r5   r4   r
  r
  w  s_    L&*# $5m"D!N $ !(-%"&*r5   r
  c                   ^     e Zd Zddef fdZ ej                         ed               Z xZ	S )Emu3RotaryEmbeddingrT   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_lenrT   r   rope_init_fnattention_scalingregister_bufferr  original_inv_freq)r0   rT   r  r  r3   s       r4   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!%r5   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   r8   r   mpsr  F)device_typeenabledr7   rc   r  )r  floatrw   rF   r;   r  r  r  strr,   autocastr   re   rm   r&  rn   r:   )
r0   r`   ro   inv_freq_expandedposition_ids_expandedr+  freqsembrm   rn   s
             r4   rC   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.r_   )
rJ   rK   rL   r   r)   r,   no_gradr   rC   rM   rN   s   @r4   r  r    s3    /z /" U]]_<  <r5   r  c                       e Zd Zdef fdZd Zd Z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e
j                  df   de
j                  de
j                  dedef
dZede
j                  dedede
j0                  de
j                  defd       Z xZS )Emu3TextModelrT   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   )rT   F)r(   r)   pad_token_idr  
vocab_sizer*   r   r1   embed_tokensrj  rl  num_hidden_layersr   layersr&   r   normr  
rotary_embgradient_checkpointingr  r   s      r4   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 r_   r:  rG   s    r4   get_input_embeddingsz"Emu3TextModel.get_input_embeddings  s       r5   c                     || _         y r_   rA  r0   r   s     r4   set_input_embeddingsz"Emu3TextModel.set_input_embeddings  s
    !r5   	input_idsr   ro   r  inputs_embedsr   r   output_hidden_statesr   flash_attn_kwargsru   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||fz  } ||f||||||	|d	|
}|d   }|s$||d   fz  }. | j1                  |      }|r||fz  }t3        ||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   ro   r   r   r   r   r   )last_hidden_stater  r@   
attentions)rT   r   rH  r   rI  r?  r   r   r   r  r  r   r:  r   get_seq_lengthr,   arangerF   r  rj   _update_causal_maskr>  r<  r;  r=  r   )r0   rF  r   ro   r  rG  r   r   rH  r   rI  past_seen_tokensr   r@   r   all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                      r4   rC   zEmu3TextModel.forward  sT    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!)
*)."3#-$7
 $
M *!,M =#3"55'	6* 		-0  -!11&+/8Od+%	
 	
r5   r"   input_tensorc           	         | j                   j                  dk(  r||dk(  j                         r|S y | j                   j                  dk(  r't        |t        j
                        rt        |      }|S ||j                         nd}||j                  nd}| j                   j                  dk(  r(|s&|s$t        j                  |||| j                        ry |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   Fr   )rG  past_key_values_lengthis_trainingr   r8   )sequence_lengthtarget_lengthr:   r   r   )cudaxpunpu)rT   r   anyr  r,   r   r#   rN  is_compileabler   _ignore_causal_mask_sdpar   r:   rF   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr  r  finfomin_unmask_unattended)r0   r   rV  r   r  r   rQ  using_compilable_cacher:   r\  r]  r   	min_dtypes                r4   rP  z!Emu3TextModel._update_causal_mask1  s    ;;++/BB)~/D.I.I.K%%;;++/??.%,,7!<^!L!!
 @O?Z?99;`aCRC^!?!?di ;;++v5>T]n%>>*'7 MM	 ""&,,Q/!+??AM nell; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCKQZ[Kr5   r\  r]  r:   r   c                    | | j                         dk(  r| }|S t        j                  |      j                  }t        j                  ||f|||j
                        }|dk7  rt        j                  |d      }|t        j                  ||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 	aM  
        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.
            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   )diagonalrK  r8   r   rd   r,   rf  rg  fullr  triurO  rx   rw   clonerF   r;   masked_fillr   r\  r]  r:   r   r   r   r   rj  mask_lengthpadding_masks              r4   re  zCEmu3TextModel._prepare_4d_causal_attention_mask_with_cache_positionu  s   < %.*<*<*>!*C(K* ' E*..I** -0Ye\j\q\qK !##jjqA5<<n>S>STWeWmWmnprsWtttK%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 r5   )	NNNNNNNNN)F)rJ   rK   rL   r   r)   rB  rE  r   r   r   r,   r   r   r   r   r   r   r   r   rC   r   rP  staticmethodr   r:   re  rM   rN   s   @r4   r6  r6    s   z  !"  151537+/59$(,0/359\
E,,-\
 !.\
 u//0	\

 "%\
   1 12\
 D>\
 $D>\
 'tn\
 !!1!12\
 $$89\
 
!\
  \
H #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4r5   r6  c                       e Zd Zy)KwargsForCausalLMN)rJ   rK   rL   r   r5   r4   ry  ry    s    r5   ry  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eej&                     deej(                     deej&                     dee   deej,                     deej&                     dee   dee   dee   deej&                     deeej(                  f   dee   defd              Z xZS )Emu3ForCausalLMzlm_head.weightlm_headcolwise_repr@   logitsc                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y NFrR   )
r(   r)   r6  r  r9  r*   rV   r1   r|  r  r]   s     r4   r)   zEmu3ForCausalLM.__init__  sU     "6*
 ++yy!3!3V5F5FUS 	r5   c                 .    | j                   j                  S r_   r  r:  rG   s    r4   rB  z$Emu3ForCausalLM.get_input_embeddings  s    zz&&&r5   c                 &    || j                   _        y r_   r  rD  s     r4   rE  z$Emu3ForCausalLM.set_input_embeddings  s    "'

r5   c                     | j                   S r_   r|  rG   s    r4   get_output_embeddingsz%Emu3ForCausalLM.get_output_embeddings  s    ||r5   c                     || _         y r_   r  )r0   new_embeddingss     r4   set_output_embeddingsz%Emu3ForCausalLM.set_output_embeddings  s	    %r5   c                     || _         y r_   r  )r0   r  s     r4   set_decoderzEmu3ForCausalLM.set_decoder  s	    
r5   c                     | j                   S r_   r  rG   s    r4   get_decoderzEmu3ForCausalLM.get_decoder  s    zzr5   rF  r   ro   r  rG  labelsr   r   rH  r   logits_to_keepr   ru   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 )aN  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

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

        >>> model = 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)	rF  r   ro   r  rG  r   r   rH  r   r~  r  r9  lossr~  r  r@   rM  r   )rT   r   rH  r  rL  r  r   slicer|  loss_functionr9  r   r  r@   rM  )r0   rF  r   ro   r  rG  r  r   r   rH  r   r  r   r   r@   slice_indicesr~  r  s                     r4   rC   zEmu3ForCausalLM.forward  s   N 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!//))
 	
r5   )NNNNNNNNNNr   )rJ   rK   rL   _tied_weights_keys_tp_plan_pp_planr    r  r)   rB  rE  r  r  r  r  r   r   r   r,   r   r   r   r   r   r   r   r   ry  r   rC   rM   rN   s   @r4   r{  r{    s   *+=)H_-z:;H!L'(&  151537+/59-1$(,0/35934G
E,,-G
 !.G
 u//0	G

 "%G
   1 12G
 ))*G
 D>G
 $D>G
 'tnG
 !!1!12G
 c5<</0G
 *+G
 
 G
  G
r5   r{  c            !       ,    e Zd ZddiZdZ fdZd Zd Zdej                  dej                  f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	 	 	 	 	 	 	 	 	 	 	 	 ddej                  dej                  dej$                  deej$                     deej                     dee   deej                     dee   dee   dee   dee   deej                     dee   deeef   fd              Z xZS )	Emu3Modelztext_model.model
text_modelFc                    t         |   |       t        j                  |j                        | _        | j
                  j                  ,| j
                  j                  D cg c]  }d| 	 c}| _        t        |j                        | _	        t        |j                        | _        | j                          y c c}w )Nztext_model.)r(   r)   r6  _from_configtext_configr  r  r  	vq_configvqmodelr  vocabulary_mapvocabulary_mappingr  )r0   rT   rl   r3   s      r4   r)   zEmu3Model.__init__"  s     '44V5G5GH??--9BF//BdBd&eQQC'8&eD# !1!12"<V=R=R"S 	 'fs   #B<c                 6    | j                   j                         S r_   )r  rB  rG   s    r4   rB  zEmu3Model.get_input_embeddings.  s    3355r5   c                 :    | j                   j                  |       y r_   )r  rE  rD  s     r4   rE  zEmu3Model.set_input_embeddings1  s    ,,U3r5   r  r  c                 N    t         j                  d       | j                  |      S )Nz`model.get_image_tokens()` is deprecated and will be removed in v4.58. To obtain discrete token use `model.get_image_features()`)r   warningget_image_featues)r0   r  r  s      r4   get_image_tokenszEmu3Model.get_image_tokens4  s'     O	
 %%l33r5   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,   re   )r0   r  r  image_tokens_listtokensbpe_tokens_list
bpe_tokenss          r4   get_image_featureszEmu3Model.get_image_features:  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.
        Nr8   r   )r   r  r  r  r  )r0   r  r   r   	sequencesimages         r4   decode_image_tokenszEmu3Model.decode_image_tokensK  sX     !CRC(--b&%!)D	..>>yI##L1r5   rF  r   ro   r  rG  r   r   rH  return_dictr   r   ru   c                    |	|	n| j                   j                  }	|
|
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                  d|||||||	|
d|d
|}|S )ap  
        image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
            The sizes of the images in the batch, being (height, width) for each image. Image sizes can be obtained using
            [`AutoImageProcessor`]. See [`Emu3ImageProcessor.__call__`] for details ([]`Emu3Processor`] uses
            [`Emu3ImageProcessor`] for processing images).
        NzaYou cannot specify both input_ids and inputs_embeds at the same time, and must specify either onezdYou cannot specify both pixel_values and inputs_embeds at the same time, and must specify either oneT
rF  r   ro   r  rG  r   r   rH  r  r   r   )rT   r   rH  use_return_dictrI  r  r  r  r;   r  r:   masked_scatterr  )r0   rF  r  r  r   ro   r  rG  r   r   rH  r  r   r   r  special_image_maskr   s                    r4   rC   zEmu3Model.forward^  s5   0 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]-t";<s  #(Av  #22<ML!*d.E.E.T.T!T'??9+;+;Y__ML!001C\RI "$// 
)%+'/!5)
 
 r5   )NNNNNNNNNNNN)rJ   rK   rL   _checkpoint_conversion_mappingr  r)   rB  rE  r,   r   r   r  r  r4  r   r  r   r   r   r   r   r   r   r   r   r   r   rC   rM   rN   s   @r4   r  r    s   &8,%G""
644U->-> 4UM]M] 4u/@/@ uO_O_ " ]]0@0@ # VY  $  '+*.$(1537+/59$(,0/3&*59;##; ''; \\	;
 !.; u//0; "%;   1 12; D>; $D>; 'tn; d^; !!1!12; -.; 
u,,	-;  ;r5   r  c            %       b    e Zd ZdZddddZdZ fdZd Zd	 Ze	d
        Z
e	d        Zee	 	 	 	 	 	 	 	 	 	 	 	 	 	 d#dej                  dej                   dej"                  deej"                     deej                     dee   deej                      dee   dee   dee   dee   deej                     deej                     deeej"                  f   dee   deeef   f d              Z	 	 	 	 	 	 	 d$ fd	Zedej"                  deded ej<                  dej"                  d!efd"       Z xZ S )%Emu3ForConditionalGeneration zmodel.text_modelzmodel.vqmodelr|  )z^text_model.modelz^vqmodelz^text_model.lm_headFc                     t         |   |       t        |      | _        t	        j
                  |j                  j                  |j                  j                  d      | _	        | j                          y r  )r(   r)   r  r  r*   rV   r  r1   r9  r|  r  r]   s     r4   r)   z%Emu3ForConditionalGeneration.__init__  sS     v&
yy!3!3!?!?ASASA^A^ejkr5   c                 6    | j                   j                         S r_   )r  rB  rG   s    r4   rB  z1Emu3ForConditionalGeneration.get_input_embeddings  s    zz..00r5   c                 :    | j                   j                  |       y r_   )r  rE  rD  s     r4   rE  z1Emu3ForConditionalGeneration.set_input_embeddings  s    

''.r5   c                 .    | j                   j                  S r_   )r  r  rG   s    r4   r  z'Emu3ForConditionalGeneration.text_model  s    zz$$$r5   c                 .    | j                   j                  S r_   )r  r  rG   s    r4   r  z$Emu3ForConditionalGeneration.vqmodel  s    zz!!!r5   rF  r  r  r   ro   r  rG  r   r   rH  r  r   r  r  r   ru   c                 "   |	|	n| j                   j                  }	|
|
n| j                   j                  }
||n| j                   j                  } | j                  d|||||||	|
d|d
|}|d   }t        |t              rt        | d      n|}| j                  |dd|ddf         }d}|4 | j                  d||| j                   j                  j                  d|}t        |||j                  |j                  |j                        S )at  
        image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
            The sizes of the images in the batch, being (height, width) for each image. Image sizes can be obtained using
            [`AutoImageProcessor`]. See [`Emu3ImageProcessor.__call__`] for details ([]`Emu3Processor`] uses
            [`Emu3ImageProcessor`] for processing images).
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

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

        >>> model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", 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]
        ```NTr  r   r  r  r   )rT   r   rH  r  r  r  r   r  r|  r  r  r9  r   r  r@   rM  )r0   rF  r  r  r   ro   r  rG  r   r   rH  r  r   r  r  r   r   r@   r  r~  r  s                        r4   rC   z$Emu3ForConditionalGeneration.forward  sA   B 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]$** 
)%+'/!5)
 
  
8B>SV8W~ot4]kmA}a,?@A%4%% f9P9P9[9[_eD &#33!//))
 	
r5   c	                 R    t        |   |f|||||||d|	}
|d   dk7  rd |
d<   |
S )N)r  r   rG  r   ro   r  r   r   r  )r(   prepare_inputs_for_generation)r0   rF  r  r   rG  r   ro   r   r  r   model_inputsr3   s              r4   r  z:Emu3ForConditionalGeneration.prepare_inputs_for_generation%  sZ     w<

+)')%%

 

 !!+/L(r5   r\  r]  r:   r   c                    | | j                         dk(  r| }|S t        j                  |      j                  }t        j                  ||f|||j
                        }|dk7  rt        j                  |d      }|t        j                  ||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 rl  ro  rt  s              r4   re  zREmu3ForConditionalGeneration._prepare_4d_causal_attention_mask_with_cache_positionD  s   > %.*<*<*>!*C(K* ' E*..I** -0Ye\j\q\qK !##jjqA5<<n>S>STWeWmWmnprsWtttK%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 r5   )NNNNNNNNNNNNNr   )NNNNNTN)!rJ   rK   rL   r  r  r  r)   rB  rE  propertyr  r  r   r   r,   r   r   r   r   r   r   r   r   r   ry  r   r   rC   r  rw  r:   re  rM   rN   s   @r4   r  r    s>   /#(&"
 #1/ % % " "  '+*.$(1537+/59$(,0/3&*59-134d
##d
 ''d
 \\	d

 !.d
 u//0d
 "%d
   1 12d
 D>d
 $D>d
 'tnd
 d^d
 !!1!12d
 ))*d
 c5<</0d
  *+!d
" 
u,,	-#d
  d
R > 444 4 {{	4
 4 4 4r5   r  )r  r{  r6  r
  r  r  )Nr   )r   )ar  	functoolsr   typingr   r   r   r   r   r,   torch.nnr*   torch.nn.functionalr   r   activationsr
   cache_utilsr   r   
generationr   integrationsr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   configuration_emu3r   r    r!   !torch.nn.attention.flex_attentionr"   integrations.flex_attentionr#   
get_loggerrJ   r   ro  r&   rP   rh   rs   r   r   r}   r-  r   r   r   r   r   r   r  r  r&  r0  r4  r?  rF  r  rR  rX  ra  r}  r  r  r  r  r
  r  r6  ry  r{  r  r  __all__r   r5   r4   <module>r     sG  .  % 9 9     ! . ) 7 > B 9 O K F & h h K K  !;J 
		H	% Y'J")) J (J(bii  (6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % %4J)BII J)ZH1 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 l2 l2l2^3% 3%l */ * *><")) <D p' p pf ?,j > j
)? j
 j
Z}# }@\#6 \~r5   