o
    wi                    @   s  d dl Z d dlmZ d dlmZmZmZ d dlZd dlm	Z	 d dl
m	  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+ ddl,m-Z-m.Z.m/Z/ e+0e1Z2edG dd de	j3Z4G dd de	j3Z5dd Z6ddddZ7dej8de9dej8fdd Z:	!ded"e	j3d#ej8d$ej8d%ej8d&eej8 d'e;d(e;fd)d*Z<G d+d, d,e	j3Z=G d-d. d.eZ>G d/d0 d0e	j3Z?G d1d2 d2e	j3Z@G d3d4 d4e	j3ZAG d5d6 d6e	j3ZBG d7d8 d8e	j3ZCG d9d: d:e	j3ZDG d;d< d<e	j3ZEG d=d> d>e	j3ZFG d?d@ d@e	j3ZGG dAdB dBe	j3ZHG dCdD dDe	jIZJG dEdF dFe	j3ZKG dGdH dHe	j3ZLG dIdJ dJe	j3ZMG dKdL dLe	j3ZNG dMdN dNe	j3ZOe)dOdPG dQdR dRe$ZPG dSdT dTZQe)G dUdV dVe$ZRG dWdX dXe	j3ZSe)G dYdZ dZeRZTG d[d\ d\ee(ZUe)G d]d^ d^eReZVG d_d` d`eRZWG dadb dbeReZXg dcZYdS )f    N)cached_property)CallableOptionalUnion   )ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hub)create_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)
LossKwargsauto_docstringcan_return_tuplelogging   )
Emu3ConfigEmu3TextConfigEmu3VQVAEConfigRMSNormc                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	Emu3RMSNormư>c                    s&   t    tt|| _|| _dS )z:
        Emu3RMSNorm is equivalent to T5LayerNorm
        N)super__init__nn	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__ c/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/transformers/models/emu3/modeling_emu3.pyr"   3   s   

zEmu3RMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )N   T)keepdim)	dtypetor%   float32powmeanrsqrtr(   r'   )r)   hidden_statesinput_dtypevariancer.   r.   r/   forward;   s
   zEmu3RMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupler'   shaper(   r)   r.   r.   r/   
extra_reprB   s   zEmu3RMSNorm.extra_repr)r    )__name__
__module____qualname__r"   r<   r@   __classcell__r.   r.   r,   r/   r   1   s    r   c                       $   e Zd Z fddZdd Z  ZS )Emu3MLPc                    sx   t    || _|j| _|j| _tj| j| j|jd| _tj| j| j|jd| _	tj| j| j|jd| _
t|j | _d S )Nbias)r!   r"   configr*   intermediate_sizer#   Linearmlp_bias	gate_projup_proj	down_projr   
hidden_actact_fnr)   rI   r,   r.   r/   r"   G   s   
zEmu3MLP.__init__c                 C   s$   |  | | || | }|S N)rO   rQ   rM   rN   )r)   xrO   r.   r.   r/   r<   Q   s    zEmu3MLP.forwardrA   rB   rC   r"   r<   rD   r.   r.   r,   r/   rF   F   s    
rF   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..Nr1   r0   dim)r>   r%   cat)rT   x1x2r.   r.   r/   rotate_halfV   s   r[   c                 C   sD   | |}| |}| | t| |  }|| t||  }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezer[   )qkcossinposition_idsunsqueeze_dimq_embedk_embedr.   r.   r/   apply_rotary_pos_emb]   s
   

re   r9   n_repreturnc                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||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)r>   expandreshape)r9   rf   batchnum_key_value_headsslenhead_dimr.   r.   r/   	repeat_kvx   s
   0rn           modulequerykeyvalueattention_maskscalingdropoutc                 K   s   t || j}t || j}	t||dd| }
|d ur3|d d d d d d d |jd f }|
| }
tjj|
dtj	d
|j}
tjj|
|| jd}
t|
|	}|dd }||
fS )Nr0   r   r1   )rW   r3   )ptrainingr   )rn   num_key_value_groupsr%   matmul	transposer>   r#   
functionalsoftmaxr5   r4   r3   rv   ry   
contiguous)rp   rq   rr   rs   rt   ru   rv   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputr.   r.   r/   eager_attention_forward   s   
&r   c                       s   e Zd ZdZdedef fd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dZ  ZS )Emu3Attention=Multi-headed attention from 'Attention Is All You Need' paperrI   	layer_idxc                    s   t    || _|| _t|d|j|j | _|j|j | _	| jd | _
|j| _d| _tj|j|j| j |jd| _tj|j|j| j |jd| _tj|j|j| j |jd| _tj|j| j |j|jd| _d S )Nrm         TrG   )r!   r"   rI   r   getattrr*   num_attention_headsrm   rk   rz   ru   attention_dropout	is_causalr#   rK   attention_biasq_projk_projv_projo_projr)   rI   r   r,   r.   r/   r"      s(   
zEmu3Attention.__init__Nr9   position_embeddingsrt   past_key_valuecache_positionr   rg   c                 K   s$  |j d d }g |d| jR }| ||dd}	| ||dd}
| ||dd}|\}}t|	|
||\}	}
|d urW|||d}||
|| j	|\}
}t
}| jjdkret| jj }|| |	|
||f| jsqdn| j| jd|\}}|jg |dR   }| |}||fS )Nr1   r   r0   )r`   r_   r   eagerro   )rv   ru   )r>   rm   r   viewr|   r   r   re   updater   r   rI   _attn_implementationr   ry   r   ru   ri   r   r   )r)   r9   r   rt   r   r   r   input_shapehidden_shapequery_statesr   r   r_   r`   cache_kwargsattention_interfacer   r   r.   r.   r/   r<      s8   	

zEmu3Attention.forwardNN)rA   rB   rC   __doc__r   intr"   r%   Tensorr=   r   r   
LongTensorr   r   r<   rD   r.   r.   r,   r/   r      s(    r   c                       s   e Zd Zdedef fd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dZ  ZS )Emu3DecoderLayerrI   r   c                    s`   t    |j| _t||d| _t|| _t|j|jd| _	t|j|jd| _
t|j| _d S )N)rI   r   r+   )r!   r"   r*   r   	self_attnrF   mlpr   rms_norm_epsinput_layernormpost_attention_layernormr#   Dropoutr   rv   r   r,   r.   r/   r"      s   

zEmu3DecoderLayer.__init__NFr9   rt   ra   r   output_attentions	use_cacher   r   rg   c	                 K   s   |}
|  |}| jd||||||||d|	\}}|
| | }|}
| |}| |}|
| | }|f}|r>||f7 }|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
        )r9   rt   ra   r   r   r   r   r   Nr.   )r   r   rv   r   r   )r)   r9   rt   ra   r   r   r   r   r   r   residualself_attn_weightsoutputsr.   r.   r/   r<      s.   
	



zEmu3DecoderLayer.forward)NNNFFNN)rA   rB   rC   r   r   r"   r%   r   r   r   r   boolr=   FloatTensorr<   rD   r.   r.   r,   r/   r      s8    	r   c                       s6   e Zd ZdZdef fddZdejfddZ  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.
    rI   c                    s>   t    t|j|j| _| jjj	d|j d|j  d S )Ng            ?)
r!   r"   r#   	Embeddingcodebook_size	embed_dim	embeddingr'   datauniform_rR   r,   r.   r/   r"   :  s   
"z!Emu3VQVAEVectorQuantizer.__init__hidden_statec                 C   s   |j \}}}}}|ddddd }|d|}tj|d ddd}tj| jjd dd	}	dt|| jj	dd }
||	 |
 }
tj
|
dd	}|||||}|S )
Nr   r   r      r0   r1   T)rW   r2   rV   )r>   permuter   r   r%   sumr   r'   r{   r|   argmin)r)   r   
batch_sizetemporalchannelsheightwidthhidden_state_flattenedhidden_state_sumembedding_sum	distancesmin_encoding_indicesr.   r.   r/   r<   ?  s   z Emu3VQVAEVectorQuantizer.forward)
rA   rB   rC   r   r   r"   r%   r   r<   rD   r.   r.   r,   r/   r   /  s    
r   c                       rE   )Emu3VQVAEEncoderConvDownsamplec                    s$   t    tj||dddd| _d S )Nr   r0   r   kernel_sizestridepaddingr!   r"   r#   Conv2dconvr)   in_channelsr,   r.   r/   r"   R     
z'Emu3VQVAEEncoderConvDownsample.__init__c                 C   s    t j|dddd}| |}|S )N)r   r   r   r   constantr   )padmoders   )Fr   r   r)   r9   r.   r.   r/   r<   V  s   
z&Emu3VQVAEEncoderConvDownsample.forwardrU   r.   r.   r,   r/   r   Q      r   c                       rE   )Emu3VQVAEEncoderConvUpsamplec                    s$   t    tj||dddd| _d S )Nr   r   r   r   r   r,   r.   r/   r"   ^  r   z%Emu3VQVAEEncoderConvUpsample.__init__c                 C   s   t j|ddd}| |}|S )N       @nearestscale_factorr   )r   interpolater   r   r.   r.   r/   r<   b  s   
z$Emu3VQVAEEncoderConvUpsample.forwardrU   r.   r.   r,   r/   r   ]  r   r   c                	       sF   e Zd Zdededee dee f fddZdejfdd	Z  Z	S )
Emu3VQVAEConv3d
in_channelout_channelr   r   c                    s   t    dd t|dd  |dd  D }d| _|d d d D ]}|  j|d |d  |d f7  _q!|  jd7  _tj||||d| _d S )	Nc                 S   s   g | ]\}}|| qS r.   r.   ).0
one_kernel
one_strider.   r.   r/   
<listcomp>r  s    z,Emu3VQVAEConv3d.__init__.<locals>.<listcomp>r   r.   r1   r0   )r0   r   )r   )r!   r"   zipr   r#   Conv3dr   )r)   r   r   r   r   padding_sizespad_sizer,   r.   r/   r"   i  s   
$$zEmu3VQVAEConv3d.__init__r9   c                 C   s   t || j}| |}|S rS   )r   r   r   r   r   r.   r.   r/   r<     s   
zEmu3VQVAEConv3d.forward)
rA   rB   rC   r   r=   r"   r%   r   r<   rD   r.   r.   r,   r/   r   h  s    r   c                       s<   e Zd Zdedef fddZdejdejfddZ  ZS )	Emu3VQVAESpatialNormr   out_channelsc                    sN   t    tj|dddd| _tj||dddd| _tj||dddd| _d S )N    r    Tnum_channels
num_groupsr+   affiner   r   r   )r!   r"   r#   	GroupNorm
norm_layerr   conv_yconv_br)   r   r   r,   r.   r/   r"     s*   
zEmu3VQVAESpatialNorm.__init__r9   quant_statesc                 C   s@   t j||jdd  dd}| |}|| | | | }|S )Nrw   r   )sizer   )r   r   r>   r   r   r   )r)   r9   r   r.   r.   r/   r<     s   
zEmu3VQVAESpatialNorm.forward	rA   rB   rC   r   r"   r%   r   r<   rD   r.   r.   r,   r/   r     s    r   c                       6   e Zd Zdedef fddZdejfddZ  ZS )Emu3VQVAETemporalUpsampler   r   c                        t    t||ddd| _d S )Nr   r   r   r   r   r   r   r   r!   r"   r   r   r)   r   r   r,   r.   r/   r"        
z"Emu3VQVAETemporalUpsample.__init__r9   c                 C   sr   |j \}}}}}|ddddd |d|}tj|ddd	}|||||dddddd }| |}|S )
Nr   r   r   r   r0   r1   r   r   r   )r>   r   r   r   r   r   r   )r)   r9   r   r   r   r   r   r.   r.   r/   r<     s    $
z!Emu3VQVAETemporalUpsample.forwardr   r.   r.   r,   r/   r         r   c                       r   )Emu3VQVAETemporalDownsampler   r   c                    r   )N)r   r   r   )r0   r   r   r  r  r  r,   r.   r/   r"     r  z$Emu3VQVAETemporalDownsample.__init__r9   c                 C   s   |  |}|S rS   )r   r   r.   r.   r/   r<     s   
z#Emu3VQVAETemporalDownsample.forwardr   r.   r.   r,   r/   r    r  r  c                       s(   e Zd Z	d fdd	Zdd Z  ZS )Emu3VQVAETemporalResnetBlockNc                    s   t    || _|d u r|n|| _t|| _t||ddd| _t|| _	t||ddd| _
| j| jkrBtj||dddd| _d S d S )Nr   r  r  r   r   r   )r!   r"   r   r   r#   BatchNorm3dnorm1r   conv1norm2conv2r   nin_shortcutr   r,   r.   r/   r"     s4   
z%Emu3VQVAETemporalResnetBlock.__init__c                 C   sf   |}|  |}|t|9 }| |}| |}|t|9 }| |}| j| jkr/| |}|| S rS   )	r
  r%   sigmoidr  r  r  r   r   r  )r)   r9   r   r.   r.   r/   r<     s   




z$Emu3VQVAETemporalResnetBlock.forwardrS   rU   r.   r.   r,   r/   r    s     r  c                       sT   e Zd Z		d
dedee dee f fddZddejdeej fdd	Z  Z	S )Emu3VQVAEResnetBlockNr   r   quant_channelsc                    s   t    || _|d u r|n|}|| _|| _|d u r/tj|dddd| _tj|dddd| _nt	||| _t	||| _tj
||dddd| _tj
||dddd| _| j| jkrdtj
||dddd| _d S d S )	Nr   r    Tr   r   r   r   r   )r!   r"   r   r   r  r#   r   r
  r  r   r   r  r  r  )r)   r   r   r  r,   r.   r/   r"     sB   
zEmu3VQVAEResnetBlock.__init__r9   c                 C   s   | j d u rdn|f}|}| j|g|R  }|t|9 }| |}| j|g|R  }|t|9 }| |}| j| jkrA| 	|}|| S Nr.   )
r  r
  r%   r  r  r  r  r   r   r  )r)   r9   r  	norm_argsr   r.   r.   r/   r<   1  s   


zEmu3VQVAEResnetBlock.forwardr   rS   )
rA   rB   rC   r   r   r"   r%   r   r<   rD   r.   r.   r,   r/   r    s    $,r  c                       sb   e Zd ZdZdef fddZ		ddejdeej d	ee	 d
e
ejeej f fddZ  ZS )Emu3VQVAEAttentionBlockr   rI   c                    s   t    || _|j| _|j| _| j| j | _| j| j | jkr-td| j d| j d| jd | _	|j
| _d| _t| j| j| _t| j| j| _t| j| j| _t| j| j| _d| _d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).r   Fr   )r!   r"   rI   r*   r   r   	num_headsrm   
ValueErrorscaler   rv   r   r#   rK   r   r   r   out_projrz   rR   r,   r.   r/   r"   F  s&   


z Emu3VQVAEAttentionBlock.__init__NFr9   rt   r   rg   c              
   C   s  |j \}}}| |}| |}| |}	|||| j| jdd}|||| j| jdd}|	||| j| jdd}	t}
| j	j
dkr[| j	j
dkrU|rUtd nt| j	j
 }
|
| |||	|| j| j| jsjdn| jd\}}|||| }| |}|sd}||fS )	z#Input shape: Batch x Time x Channelr   r0   r   sdpaz`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.ro   )r   ru   rv   N)r>   r   r   r   r   r  rm   r|   r   rI   r   loggerwarning_oncer   r   r  ry   rv   ri   r   r  )r)   r9   rt   r   r   
seq_lengthr   querieskeysvaluesr   r   r   r.   r.   r/   r<   ]  s:   




zEmu3VQVAEAttentionBlock.forward)NF)rA   rB   rC   r   r   r"   r%   r   r   r   r=   r<   rD   r.   r.   r,   r/   r  C  s    r  c                       s*   e Zd ZdZ fddZdddZ  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                    s   t  jdi | d S r  )r!   r"   r)   r   r,   r.   r/   r"     s   zEmu3VQVAEGroupNorm.__init__Nc                 C   s   t || j| j| j| jS rS   )r   
group_normr   r'   rH   r+   )r)   inputr   r.   r.   r/   r<     s   zEmu3VQVAEGroupNorm.forwardrS   )rA   rB   rC   r   r"   r<   rD   r.   r.   r,   r/   r     s    r   c                       s:   e Zd Zd fdd	Zddejdeej fddZ  ZS )	Emu3VQVAEMiddleBlockNc                    s`   t    t|||d| _t|| _|d u r t|dddd| _nt||| _t|||d| _	d S )Nr   r   r  r   r    Tr   )
r!   r"   r  block_1r  attn_1r   	attn_normr   block_2)r)   rI   r   r  r,   r.   r/   r"     s   

zEmu3VQVAEMiddleBlock.__init__r9   r   c                 C   s   |  ||}|}| ||}|j\}}}}||||| dd}| |d }|||||dddd}|| }| ||}|S )Nr   r0   r   r   )	r&  r(  r>   r   r|   r'  ri   r   r)  )r)   r9   r   r   r   r   r   r   r.   r.   r/   r<     s   zEmu3VQVAEMiddleBlock.forwardrS   )	rA   rB   rC   r"   r%   r   r   r<   rD   r.   r.   r,   r/   r$    s    $r$  c                       ,   e Zd Z fddZdejfddZ  ZS )Emu3VQVAEDownBlockc              
      s(  t    t|j| _|j| _|j}|j}dt| }|| _t	
 | _t| jD ]i}t	
 }t	
 }t	
 }|||  }	|||  }
t| jD ]*}|t|	|
d |
}	|jd urq||jv rq|t| |t	j|	dddd qGt	 }||_||_||_|| jd krt|	|_| j| q(d S )Nr   r   r   r   r    Tr   r   )r!   r"   lenchannel_multipliernum_resolutionsnum_res_blocksbase_channelsr=   in_channel_multiplierr#   
ModuleListdownrangeappendr  attn_resolutionsr  r   Moduleblockattn
attn_normsr   
downsample)r)   rI   r2  r/  r3  i_levelr:  r;  r<  block_in	block_outi_blockr5  r,   r.   r/   r"     sD   


zEmu3VQVAEDownBlock.__init__r9   c           
      C   s   t | jD ]^\}}t| jD ]H}|j| |}t|jdkrV|}|j| |}|j\}}}}	|	||||	 
dd}|j| |d }||||	|dddd}|| }q|| jd krc||}q|S )Nr   r   r0   r   )	enumerater5  r6  r1  r:  r.  r;  r<  r>   r   r|   ri   r   r0  r=  )
r)   r9   r>  blocksrA  r   r   r   r   r   r.   r.   r/   r<     s    
zEmu3VQVAEDownBlock.forwardrA   rB   rC   r"   r%   r   r<   rD   r.   r.   r,   r/   r+    s    %r+  c                       s2   e Zd Z fddZdejdejfddZ  ZS )Emu3VQVAEUpBlockc              	      s  t    t|j| _|j| _|j}|j|jd  }t	 | _
tt| jD ]]}t	 }t	 }t	 }|j|j|  }t| jd D ]"}	|t|||d |}||jv re|t| |t|| qCt }
||
_||
_||
_|dkr|t||
_| j
d|
 q&d S )Nr1   r   r%  r   )r!   r"   r.  r/  r0  r1  r   r2  r#   r4  upreversedr6  r7  r  r8  r  r   r9  r:  r;  r<  r   upsampleinsert)r)   rI   r  r?  r>  r:  r;  r<  r@  rA  rF  r,   r.   r/   r"     s@   



zEmu3VQVAEUpBlock.__init__r9   r   c                 C   s   t | jd d d D ]d\}}t| jd D ]J}|j| ||}t|jdkr_|}|j| ||}|j\}}}	}
|	|||	|
 
dd}|j| |d }|||	|
|dddd}|| }q|t| jd krn||}q
|S )Nr1   r   r   r0   r   )rB  rF  r6  r1  r:  r.  r;  r<  r>   r   r|   ri   r   rH  )r)   r9   r   r>  rC  rA  r   r   r   r   r   r.   r.   r/   r<     s    
zEmu3VQVAEUpBlock.forwardrD  r.   r.   r,   r/   rE    s    %rE  c                       r*  )Emu3VQVAEEncoderc                    s  t    |j}|j}|j}|j}|j}|rd| n|}||d  }tjj	||dddd| _
t|| _t||| _tjjd|ddd	| _tjj	||dddd| _tt|j}	t | _t | _t|	D ]}
t||}| j| qft|jD ]}t||d
}| j| qyd S )Nr0   r1   r   r   r   r   r    T)r   r   r+   r   r-  )r!   r"   r2  r   double_latentlatent_channelsr/  r%   r#   r   conv_inr+  
down_blockr$  middle_blockr   norm_outconv_outr   mathlog2temporal_downsample_factorr4  	time_convtime_res_stackr6  r  r7  r1  r  )r)   rI   r2  r   rK  rL  r/  r   r?  temporal_down_blocksir   _time_res_convr,   r.   r/   r"   3  s@   




zEmu3VQVAEEncoder.__init__pixel_valuesc                 C   s   |j d }|jdg|j dd  R  }| |}| |}| |}| |}|t|9 }| |}|jd|g|j dd  R  }|	ddddd}| j
D ]}||}|t|9 }qN| jD ]}||}q_|	ddddd}|S )Nr   r1   r0   r   r   r   )r>   ri   rM  rN  rO  rP  r%   r  rQ  r   rU  rV  )r)   r[  temporal_dimr9   r   layerr.   r.   r/   r<   Z  s"   








zEmu3VQVAEEncoder.forward)rA   rB   rC   r"   r%   r   r<   rD   r.   r.   r,   r/   rJ  2  s    'rJ  c                       s8   e Zd Zdef fddZdejdejfddZ  ZS )Emu3VQVAEDecoderrI   c           	         s  t    |j}|j|jd  }t | _t|j	D ]}t
|j|jd}| j| qtt|j}t | _t|D ]}t|j|j}| j| q<tj|j|dddd| _t|||d| _t|| _|j|jd  }t||| _tj||jdddd| _d S )Nr1   r-  r   r   r   )r  r   )r!   r"   r   r2  r/  r#   r4  rV  r6  r1  r  rL  r7  r   rR  rS  rT  rU  r   r   rM  r$  rO  rE  up_blockr   rP  r   rQ  )	r)   rI   r  r?  rY  rZ  temp_upsample_block_numrX  r   r,   r.   r/   r"   y  s@   



zEmu3VQVAEDecoder.__init__r9   r   c                 C   s  t j||fdd}|ddddd}| jD ]}||}q| jD ]}||}|t |9 }q|ddddd}t j|ddd\}}|jdg|jdd  R  }|jdg|jdd  R  }| 	|}| 
||}| ||}| ||}|t |9 }| |}|S )Nr   rV   r0   r   r   r   r1   )r%   rX   r   rV  rU  r  chunkri   r>   rM  rO  r_  rP  rQ  )r)   r9   r   hidden_quant_statesr]  r.   r.   r/   r<     s$   




zEmu3VQVAEDecoder.forward)	rA   rB   rC   r   r"   r%   r   r<   rD   r.   r.   r,   r/   r^  x  s    'r^  aR  
    The VQ-VAE model used in Emu3 for encoding/decoding images into discrete tokens.
    This model follows the "Make-a-scene: Scene-based text-to-image generation with human priors" paper from
    [ Oran Gafni, Adam Polyak, Oron Ashual, Shelly Sheynin, Devi Parikh, and Yaniv
    Taigman](https://huggingface.co/papers/2203.13131).
    )custom_introc                       st   e Zd ZeZdZdZdZdZdZ	dZ
g dZdd Zdef fdd	Zdejd
ejfddZdejfddZ  ZS )	Emu3VQVAE
emuvideovqr[  T)r  r  r  r   c                 C   s\  t |tjtjfr6tjj|jddd |jd ur4tj|j\}}dt	
| }tj|j| | d S d S t |tjrqtjj|jt	
dd |jd urotj|j\}}|dkradt	
| nd}tj|j| | d S d S t |tjtjtjfrtj|jd tj|jd	 d S t |tjr|jj  |jd ur|jj|j   d S d S d S )
Nfan_outrelu)r   nonlinearityr      )ar   r   ro   )
isinstancer#   r   r   initkaiming_normal_r'   rH   _calculate_fan_in_and_fan_outrR  sqrtr   rK   kaiming_uniform_BatchNorm2dr	  r   	constant_r   r   normal_padding_idxzero_)r)   rp   fan_inrY  boundr.   r.   r/   _init_weights  s.   


zEmu3VQVAE._init_weightsrI   c                    s   t  | || _t|| _t|| _t|| _dt	|j
d  | _t|j|jddd| _t|j|jddd| _dt	|j
d  | _|   |   d S )Nr0   r   )r   r   r   r  r  )r!   r"   rI   rJ  encoderr^  decoderr   quantizer.  r/  vision_spatial_factorr   rL  r   
quant_convpost_quant_convspatial_scale_factoreval	post_initrR   r,   r.   r/   r"     s   


zEmu3VQVAE.__init__image_sizesc                    s   |j dk}|r jj}|j\}}}}|dd|ddd}n|j\}}}}} |}	|	ddddd}	 |	}	|	ddddd}	 	|	}
|rO|

dn|
} fddt||D }|S )Nr   r   r   r0   r   c                    s@   g | ]\}}|d t |d  j d t |d  j f qS )Nr   r   )r   r|  )r   single_imager   r?   r.   r/   r     s    .z$Emu3VQVAE.encode.<locals>.<listcomp>)ndimrI   rT  r>   r\   repeatry  r   r}  r{  squeezer   )r)   r[  r  is_imager   r   r   r   r   r9   codesimage_tokensr.   r?   r/   encode  s    




zEmu3VQVAE.encoder9   c                 C   s   |j dk}|r|d}|j\}}}}| j| }|jd }||||||ddddd }| 	|}	|ddddd}|	ddddd}	| 
|	|}
|
||| jj | jj|| j || j }
|rn|
d d df S |
S )Nr   r   r1   r   r   r0   )r  r\   r>   r{  r   flattenr   r   r   r~  rz  ri   rI   rT  r   r  )r)   r9   r  r   r   r   r   quantr   
post_quantvideor.   r.   r/   decode  s&   


$

zEmu3VQVAE.decode)rA   rB   rC   r   config_classbase_model_prefixmain_input_name_supports_sdpa_supports_flash_attn_2_supports_flex_attn_supports_attention_backend_no_split_modulesrx  r"   r%   r   r  r  rD   r.   r.   r,   r/   rd    s    	rd  c                   @   s   e Zd ZdZdd Zedd Zedd Zedd	 Zed
d Z	edd Z
edd Zdeej dejfddZdejdejfddZdS )Emu3ImageVocabularyMappingzM
    A class for mapping discrete image tokens from VQGAN to BPE tokens.
    c                 C   s"   || _ |d| _|d| _d S )Nz<|extra_200|>z<image>)	vocab_mapgeteol_token_idimage_token_id)r)   r  r.   r.   r/   r"   :  s   z#Emu3ImageVocabularyMapping.__init__c                 C      t dd | j D S )Nc                 S   s   g | ]\}}| d r|qS z<|visual token
startswithr   namevalr.   r.   r/   r   A      z;Emu3ImageVocabularyMapping.image_tokens.<locals>.<listcomp>sortedr  itemsr?   r.   r.   r/   r  ?     z'Emu3ImageVocabularyMapping.image_tokensc                 C   r  )Nc                 S   s   g | ]\}}| d r|qS r  r  r  r.   r.   r/   r   E  r  z?Emu3ImageVocabularyMapping.image_tokens_str.<locals>.<listcomp>r  r?   r.   r.   r/   image_tokens_strC  r  z+Emu3ImageVocabularyMapping.image_tokens_strc                    s    fdd j D S )Nc                    s$   i | ]}t |d d  j| qS )irw   )r   r  )r   tokenr?   r.   r/   
<dictcomp>I  s   $ z6Emu3ImageVocabularyMapping.img2bpe.<locals>.<dictcomp>)r  r?   r.   r?   r/   img2bpeG     z"Emu3ImageVocabularyMapping.img2bpec                 C   s   dd | j  D S )Nc                 S   s   i | ]\}}||qS r.   r.   )r   r^   vr.   r.   r/   r  M      z6Emu3ImageVocabularyMapping.bpe2img.<locals>.<dictcomp>)r  r  r?   r.   r.   r/   bpe2imgK  r  z"Emu3ImageVocabularyMapping.bpe2imgc                 C   >   t jt| j d t jd}| j D ]\}}|||< q|S Nr   r3   )r%   zerosmaxr  r  r   r  r)   mappingr^   r  r.   r.   r/   bpe2img_mapping_tensorO     
z1Emu3ImageVocabularyMapping.bpe2img_mapping_tensorc                 C   r  r  )r%   r  r  r  r  r   r  r  r.   r.   r/   img2bpe_mapping_tensorV  r  z1Emu3ImageVocabularyMapping.img2bpe_mapping_tensor	img_batchrg   c                 C   sR   |j }tj|jd dftjd| j }| j|d }tj||gdd}||S )Nr   r   r  cpur1   rV   )	devicer%   r&   r>   r   r  r  r4   rX   )r)   r  r  eol_row
img_tokensr.   r.   r/   convert_img2bpe]  s
    
z*Emu3ImageVocabularyMapping.convert_img2bpec                 C   s0   |j }|dd df }| j|d }||S )N.r1   r  )r  r  r4   )r)   r  r  r  r.   r.   r/   convert_bpe2imgd  s   
z*Emu3ImageVocabularyMapping.convert_bpe2imgN)rA   rB   rC   r   r"   r   r  r  r  r  r  r  listr%   r   r  r  r.   r.   r.   r/   r  5  s"    





r  c                   @   sN   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d Zd	S )
Emu3PreTrainedModelmodelTr   past_key_valuesr   Fc                 C   s   | j  j}t|tjtjfr'|jjj	d|d |j
d ur%|j
j  d S d S t|tjrH|jjj	d|d |jd urF|jj|j   d S d S t|trV|jjd d S d S )Nro   )r7   stdr   )rI   get_text_configinitializer_rangerk  r#   rK   r   r'   r   rs  rH   ru  r   rt  r   fill_)r)   rp   r  r.   r.   r/   rx  }  s   


z!Emu3PreTrainedModel._init_weightsN)rA   rB   rC   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  rx  r.   r.   r.   r/   r  k  s     r  c                       s8   e Zd Zddef fddZe edd Z  Z	S )Emu3RotaryEmbeddingNrI   c                    s   t    t|dr|jd ur|jd|jd| _nd| _|j| _|j| _|| _	t
| j | _| | j	|\}| _| jd|dd | j| _d S )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_lenrI   r   rope_init_fnattention_scalingregister_bufferr  original_inv_freq)r)   rI   r  r  r,   r.   r/   r"     s   
zEmu3RotaryEmbedding.__init__c           
      C   s   | j d d d d f  |jd dd|j}|d d d d d f  }t|jjtr6|jjdkr6|jjnd}t	j
|dd+ | |  dd}t	j||fdd	}| | j }| | j }	W d    n1 smw   Y  |j|jd
|	j|jd
fS )Nr   r1   r   mpsr  F)device_typeenabledr0   rV   r  )r  floatrh   r>   r4   r  rk  r  strr%   autocastr|   rX   r_   r  r`   r3   )
r)   rT   ra   inv_freq_expandedposition_ids_expandedr  freqsembr_   r`   r.   r.   r/   r<     s   0&zEmu3RotaryEmbedding.forwardrS   )
rA   rB   rC   r   r"   r%   no_gradr   r<   rD   r.   r.   r,   r/   r    s
    r  c                       s   e Zd Zdef fddZdd Zd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dZ  ZS )Emu3TextModelrI   c                    s   t     j| _ j| _t j j| j| _t	 fddt
 jD | _t j jd| _t d| _d| _|   d S )Nc                    s   g | ]}t  |qS r.   )r   )r   r   rI   r.   r/   r     r  z*Emu3TextModel.__init__.<locals>.<listcomp>r   r  F)r!   r"   pad_token_idrt  
vocab_sizer#   r   r*   embed_tokensr4  r6  num_hidden_layerslayersr   r   normr  
rotary_embgradient_checkpointingr  rR   r,   r  r/   r"     s   zEmu3TextModel.__init__c                 C      | j S rS   r  r?   r.   r.   r/   get_input_embeddings     z"Emu3TextModel.get_input_embeddingsc                 C   
   || _ d S rS   r  r)   rs   r.   r.   r/   set_input_embeddings     
z"Emu3TextModel.set_input_embeddingsN	input_idsrt   ra   r  inputs_embedsr   r   output_hidden_statesr   flash_attn_kwargsrg   c
                 K   s  |d ur|n| j j}|d ur|n| j j}|d ur|n| j j}|d u |d uA r*td| jr9| jr9|r9td d}t	|t
d tfsFtd|d u rO| |}|rX|d u rXt }|	d u rt|d urd| nd}tj|||jd  |jd}	|d u r}|	d}t| j |||	||d}|}| ||}|rd	nd }|rd	nd }| jd | j j D ]&}|r||f7 }||f||||||	|d
|
}|d }|r||d f7 }q| |}|r||f7 }t||r|nd ||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  )rI   input_embedsrt   r   r  ra   r.   )rt   ra   r   r   r   r   r   )last_hidden_stater  r9   
attentions)rI   r   r  r   r  r  ry   r  r  rk  r  r   r  r	   get_seq_lengthr%   aranger>   r  r\   r   r  r  r  r  r   )r)   r  rt   ra   r  r  r   r   r  r   r  past_seen_tokensr   r9   r   all_hidden_statesall_self_attnsdecoder_layerlayer_outputsr.   r.   r/   r<     s   

	
	


zEmu3TextModel.forward)	NNNNNNNNN)rA   rB   rC   r   r"   r  r  r   r   r   r%   r   r   r   r   r   r   r   r   r<   rD   r.   r.   r,   r/   r    sL    	
r  c                   @   s   e Zd ZdS )KwargsForCausalLMN)rA   rB   rC   r.   r.   r.   r/   r
  +  s    r
  c                       s  e Zd ZdgZddiZddgdgfiZeZ fddZdd	 Z	d
d Z
dd Zdd Zdd Zd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#d$Z  ZS )&Emu3ForCausalLMlm_head.weightlm_headcolwise_repr9   logitsc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S NFrG   )
r!   r"   r  r  r  r#   rK   r*   r  r  rR   r,   r.   r/   r"   5  s
   
zEmu3ForCausalLM.__init__c                 C      | j jS rS   r  r  r?   r.   r.   r/   r  >  s   z$Emu3ForCausalLM.get_input_embeddingsc                 C   s   || j _d S rS   r  r  r.   r.   r/   r  A  s   z$Emu3ForCausalLM.set_input_embeddingsc                 C   r  rS   r  r?   r.   r.   r/   get_output_embeddingsD  r  z%Emu3ForCausalLM.get_output_embeddingsc                 C   r  rS   r  r)   new_embeddingsr.   r.   r/   set_output_embeddingsG  r  z%Emu3ForCausalLM.set_output_embeddingsc                 C   r  rS   r  r)   rz  r.   r.   r/   set_decoderJ  r  zEmu3ForCausalLM.set_decoderc                 C   r  rS   r  r?   r.   r.   r/   get_decoderM  r  zEmu3ForCausalLM.get_decoderNr   r  rt   ra   r  r  labelsr   r   r  r   logits_to_keepr   rg   c                 K   s   |dur|n| j j}|	dur|	n| j j}	| jd||||||||	|
d	|}|j}t|tr4t| dn|}| |dd|ddf }d}|durX| j	d||| j j
d|}t|||j|j|jd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)	r  rt   ra   r  r  r   r   r  r   r  r  r  lossr  r  r9   r  r.   )rI   r   r  r  r  rk  r   slicer  loss_functionr  r   r  r9   r  )r)   r  rt   ra   r  r  r  r   r   r  r   r  r   r   r9   slice_indicesr  r   r.   r.   r/   r<   P  s:   '
zEmu3ForCausalLM.forward)NNNNNNNNNNr   )rA   rB   rC   _tied_weights_keys_tp_plan_pp_planr   r  r"   r  r  r  r  r  r  r   r   r   r%   r   r   r   r   r   r   r   r   r
  r   r<   rD   r.   r.   r,   r/   r  .  sh    		
r  c                !       s4  e Zd ZddiZdZ fddZdd Zdd	 Zd
d Zdd Z	de
jde
jfddZde
jde
jfddZe
jde
jdedefd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&d'Z  ZS ))	Emu3Modelztext_model.model
text_modelFc                    s>   t  | t|j| _t|j| _t	|j
| _|   d S rS   )r!   r"   r  _from_configtext_configr(  rd  	vq_configvqmodelr  vocabulary_mapvocabulary_mappingr  rR   r,   r.   r/   r"     s
   zEmu3Model.__init__c                 C   
   | j  S rS   )r(  r  r?   r.   r.   r/   r    r  zEmu3Model.get_input_embeddingsc                 C      | j | d S rS   )r(  r  r  r.   r.   r/   r       zEmu3Model.set_input_embeddingsc                 C   r  rS   r(  r  r.   r.   r/   r    r  zEmu3Model.set_decoderc                 C   r  rS   r2  r?   r.   r.   r/   r    r  zEmu3Model.get_decoderr[  r  c                    s.    j ||} fdd|D }t|}|S )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.
        c                    s   g | ]
} j | qS r.   )r.  r  r  )r   tokensr?   r.   r/   r     s    z.Emu3Model.get_image_tokens.<locals>.<listcomp>)r,  r  r%   rX   )r)   r[  r  image_tokens_listbpe_tokens_list
bpe_tokensr.   r?   r/   get_image_tokens  s   
zEmu3Model.get_image_tokensc                    s:     ||} fdd|D }  |}t||}|S )a7  
        Tokenizes images into discrete tokens with VQGAN module and embeds
        them with text embeddings layer

        Args:
            pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
                The tensors corresponding to the input images.
        c                    s,   g | ]\}}| j j | j j d   qS r,  )r,  r|  )r   r   r   r?   r.   r/   r     s    z0Emu3Model.get_image_features.<locals>.<listcomp>)r7  r  r%   split)r)   r[  r  r  split_sizesimage_featuresr.   r?   r/   get_image_features  s   	
zEmu3Model.get_image_featuresr  r   r   c                 C   s>   |ddddf  d||d }| 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.
        Nr1   r   )r   r.  r  r,  r  )r)   r  r   r   	sequencesimager.   r.   r/   decode_image_tokens  s   "zEmu3Model.decode_image_tokensNr  rt   ra   r  r  r   r   r  return_dictr   r   rg   c                 K   s   |	dur|	n| j j}	|
dur|
n| j j}
|dur|n| j j}|du |duA r*td|dur6|dur6td|durT| ||}|| jjk}||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
r  rt   ra   r  r  r   r   r  r@  r   r.   )rI   r   r  use_return_dictr  r7  r.  r  r4   r  r3   masked_scatterr(  )r)   r  r[  r  rt   ra   r  r  r   r   r  r@  r   r   r  special_image_maskr   r.   r.   r/   r<     s@   zEmu3Model.forward)NNNNNNNNNNNN)rA   rB   rC   _checkpoint_conversion_mappingr  r"   r  r  r  r  r%   r   r   r7  r;  r  r   r?  r   r   r   r   r   r   r   r   r   r=   r   r<   rD   r.   r.   r,   r/   r'    sn    		

r'  c                %       st  e Zd ZdZdgZddddZdZ fdd	Zd
d Zdd Z	de
jfddZdd Zdd Zdd Zedd Zedd Zedd Zdd Zee														 d5d!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 d0d1Z$						2	d6 fd3d4	Z%  Z&S )7Emu3ForConditionalGeneration r  zmodel.text_modelzmodel.vqmodelr  )z^text_model.modelz^vqmodelz^text_model.lm_headFc                    s<   t  | t|| _tj|jj|jjdd| _	| 
  d S r  )r!   r"   r'  r  r#   rK   r*  r*   r  r  r  rR   r,   r.   r/   r"   5  s   
z%Emu3ForConditionalGeneration.__init__c                 C   r/  rS   )r  r  r?   r.   r.   r/   r  <  r  z1Emu3ForConditionalGeneration.get_input_embeddingsc                 C   r0  rS   )r  r  r  r.   r.   r/   r  ?  r1  z1Emu3ForConditionalGeneration.set_input_embeddingsrg   c                 C   r  rS   r  r?   r.   r.   r/   r  B  r  z2Emu3ForConditionalGeneration.get_output_embeddingsc                 C   r  rS   r  r  r.   r.   r/   r  E  r  z2Emu3ForConditionalGeneration.set_output_embeddingsc                 C   r0  rS   )r  r  r  r.   r.   r/   r  H  r1  z(Emu3ForConditionalGeneration.set_decoderc                 C   r/  rS   )r  r  r?   r.   r.   r/   r  K  r  z(Emu3ForConditionalGeneration.get_decoderc                 C   r  rS   )r  r(  r?   r.   r.   r/   r(  O     z'Emu3ForConditionalGeneration.text_modelc                 C   r  rS   )r  r,  r?   r.   r.   r/   r,  S  rH  z$Emu3ForConditionalGeneration.vqmodelc                 C   r  rS   )r  r.  r?   r.   r.   r/   r.  W  rH  z/Emu3ForConditionalGeneration.vocabulary_mappingc                 K   s   | j jdi |S r  )r  r?  r!  r.   r.   r/   r?  [  s   z0Emu3ForConditionalGeneration.decode_image_tokensNr   r  r[  r  rt   ra   r  r  r   r   r  r@  r   r  r  r   c                 K   s   |	dur|	n| j j}	|
dur|
n| j j}
|dur|n| j j}| jd|||||||	|
d|d
|}|d }t|tr@t| dn|}| |dd|ddf }d}|dure| j	d||| j j
jd|}t|||j|j|jd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]
        ```NTrA  r   r  r  r.   )rI   r   r  rB  r  rk  r   r!  r  r"  r*  r  r   r  r9   r  )r)   r  r[  r  rt   ra   r  r  r   r   r  r@  r   r  r  r   r   r9   r#  r  r   r.   r.   r/   r<   ^  sF   Az$Emu3ForConditionalGeneration.forwardTc	              
      s<   t  j|f|||||||d|	}
|d dkrd |
d< |
S )N)r  rt   r  r   ra   r[  r   r   r[  )r!   prepare_inputs_for_generation)r)   r  r  rt   r  r   ra   r   r[  r   model_inputsr,   r.   r/   rI    s    	z:Emu3ForConditionalGeneration.prepare_inputs_for_generation)NNNNNNNNNNNNNr   )NNNNNTN)'rA   rB   rC   r  r$  rE  r  r"   r  r  r#   r9  r  r  r  r  propertyr(  r,  r.  r?  r   r   r%   r   r   r   r   r   r   r   r   r   r
  r=   r   r<   rI  rD   r.   r.   r,   r/   rF  +  s    


	

irF  )rF  r  r  r  rd  r'  )Nr   )ro   )ZrR  	functoolsr   typingr   r   r   r%   torch.nnr#   torch.nn.functionalr}   r   activationsr   cache_utilsr   r	   
generationr
   integrationsr   masking_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   configuration_emu3r   r   r   
get_loggerrA   r  r9  r   rF   r[   re   r   r   rn   r  r   r   r   r   r   r   r   r   r   r  r  r  r  r   r   r$  r+  rE  rJ  r^  rd  r  r  r  r  r
  r  r'  rF  __all__r.   r.   r.   r/   <module>   s   


FK"$1?J";:FFo6"}m  <