o
    Zhl7                    @   s  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  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- rd dl3m4Z4 ddl5m6Z6 e.7e8Z9edG dd dej:Z;G dd dej:Z<dd Z=dfddZ>de	j?de@d e	j?fd!d"ZA	#dgd$ej:d%e	j?d&e	j?d'e	j?d(ee	j? d)eBd*eBfd+d,ZCG d-d. d.ej:ZDG d/d0 d0eZEG d1d2 d2ej:ZFG d3d4 d4ej:ZGG d5d6 d6ej:ZHG d7d8 d8ej:ZIG d9d: d:ej:ZJG d;d< d<ej:ZKG d=d> d>ej:ZLG d?d@ d@ej:ZMG dAdB dBej:ZNG dCdD dDej:ZOG dEdF dFejPZQG dGdH dHej:ZRG dIdJ dJej:ZSG dKdL dLej:ZTG dMdN dNej:ZUG dOdP dPej:ZVe+dQdRG dSdT dTe&ZWG dUdV dVZXe+G dWdX dXe&ZYG dYdZ dZej:ZZe+G d[d\ d\eYZ[G d]d^ d^ee*Z\e+G d_d` d`eYeZ]G dadb dbeYZ^G dcdd ddeYeZ_g deZ`dS )h    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_maskZ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__ U/var/www/auris/lib/python3.10/site-packages/transformers/models/emu3/modeling_emu3.pyr&   9   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meanZrsqrtr,   r+   )r-   hidden_statesZinput_dtypeZvariancer2   r2   r3   forwardA   s
   zEmu3RMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupler+   shaper,   r-   r2   r2   r3   
extra_reprH   s   zEmu3RMSNorm.extra_repr)r$   )__name__
__module____qualname__r&   r=   rA   __classcell__r2   r2   r0   r3   r#   7   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.   Zintermediate_sizer'   LinearZmlp_bias	gate_projup_proj	down_projr	   Z
hidden_actact_fnr-   rJ   r0   r2   r3   r&   M   s   
zEmu3MLP.__init__c                 C   s$   |  | | || | }|S N)rN   rO   rL   rM   )r-   xrN   r2   r2   r3   r=   W   s    zEmu3MLP.forwardrB   rC   rD   r&   r=   rE   r2   r2   r0   r3   rG   L   s    
rG   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..Nr5   r4   dim)r?   r)   cat)rR   x1Zx2r2   r2   r3   rotate_half\   s   rX   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.
    )	unsqueezerX   )qkcossinposition_idsZunsqueeze_dimZq_embedZk_embedr2   r2   r3   apply_rotary_pos_embc   s
   

r_   r<   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)r<   r`   batchnum_key_value_headsslenhead_dimr2   r2   r3   	repeat_kv~   s
   0rh           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 )Nr4   r   r5   )rU   r7   )ptrainingr   )rh   num_key_value_groupsr)   matmul	transposer?   r'   
functionalZsoftmaxr9   r8   r7   rp   rs   
contiguous)rj   rk   rl   rm   rn   ro   rp   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputr2   r2   r3   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' paperrJ   	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 )Nrg         TrH   )r%   r&   rJ   r   getattrr.   num_attention_headsrg   re   rt   ro   attention_dropout	is_causalr'   rK   Zattention_biasq_projk_projv_projo_projr-   rJ   r   r0   r2   r3   r&      s(   
zEmu3Attention.__init__Nr<   position_embeddingsrn   past_key_valuecache_positionry   ra   c                 K   sH  |j d d }g |d| jR }| ||dd}	| ||dd}
| ||dd}|\}}t|	|
||\}	}
|d urW|||d}||
|| j	|\}
}t
}| jjdkrw| jjdkrq|ddrqtd	 nt| jj }|| |	|
||f| jsd
n| j| jd|\}}|jg |dR   }| |}||fS )Nr5   r   r4   )r]   r\   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.ri   )rp   ro   )r?   rg   r   viewrv   r   r   r_   updater   r   rJ   _attn_implementationgetloggerwarning_oncer   rs   r   ro   rc   rx   r   )r-   r<   r   rn   r   r   ry   Zinput_shapeZhidden_shapeZquery_statesrz   r{   r\   r]   Zcache_kwargsattention_interfacer~   r|   r2   r2   r3   r=      s@   	

zEmu3Attention.forwardNN)rB   rC   rD   __doc__r   intr&   r)   Tensorr   r   r
   
LongTensorr   r   r=   rE   r2   r2   r0   r3   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 )Emu3DecoderLayerrJ   r   c                    s`   t    |j| _t||d| _t|| _t|j|jd| _	t|j|jd| _
t|j| _d S )N)rJ   r   r/   )r%   r&   r.   r   	self_attnrG   mlpr#   rms_norm_epsinput_layernormpost_attention_layernormr'   ZDropoutr   rp   r   r0   r2   r3   r&      s   

zEmu3DecoderLayer.__init__NFr<   rn   r^   r   r   	use_cacher   r   ra   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
        )r<   rn   r^   r   r   r   r   r   Nr2   )r   r   rp   r   r   )r-   r<   rn   r^   r   r   r   r   r   ry   residualZself_attn_weightsoutputsr2   r2   r3   r=      s.   
	



zEmu3DecoderLayer.forward)NNNFFNN)rB   rC   rD   r   r   r&   r)   r   r   r   r
   boolr   FloatTensorr=   rE   r2   r2   r0   r3   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.
    rJ   c                    s>   t    t|j|j| _| jjj	d|j d|j  d S )Ng            ?)
r%   r&   r'   	EmbeddingZcodebook_size	embed_dim	embeddingr+   datauniform_rP   r0   r2   r3   r&   G  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      r4   r5   T)rU   r6   rT   )r?   permuterx   r   r)   sumr   r+   ru   rv   Zargmin)r-   r   
batch_sizetemporalchannelsheightwidthZhidden_state_flattenedZhidden_state_sumZembedding_sumZ	distancesZmin_encoding_indicesr2   r2   r3   r=   L  s   z Emu3VQVAEVectorQuantizer.forward)
rB   rC   rD   r   r    r&   r)   r   r=   rE   r2   r2   r0   r3   r   <  s    
r   c                       rF   )Emu3VQVAEEncoderConvDownsamplec                    s$   t    tj||dddd| _d S )Nr   r4   r   kernel_sizestridepaddingr%   r&   r'   Conv2dconvr-   in_channelsr0   r2   r3   r&   _     
z'Emu3VQVAEEncoderConvDownsample.__init__c                 C   s    t j|dddd}| |}|S )N)r   r   r   r   Zconstantr   )padmoderm   )Fr   r   r-   r<   r2   r2   r3   r=   c  s   
z&Emu3VQVAEEncoderConvDownsample.forwardrS   r2   r2   r0   r3   r   ^      r   c                       rF   )Emu3VQVAEEncoderConvUpsamplec                    s$   t    tj||dddd| _d S )Nr   r   r   r   r   r0   r2   r3   r&   k  r   z%Emu3VQVAEEncoderConvUpsample.__init__c                 C   s   t j|ddd}| |}|S )N       @nearestZscale_factorr   )r   interpolater   r   r2   r2   r3   r=   o  s   
z$Emu3VQVAEEncoderConvUpsample.forwardrS   r2   r2   r0   r3   r   j  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 r2   r2   ).0Z
one_kernelZ
one_strider2   r2   r3   
<listcomp>  s    z,Emu3VQVAEConv3d.__init__.<locals>.<listcomp>r   r2   r5   r4   )r4   r   )r   )r%   r&   zipr   r'   Conv3dr   )r-   r   r   r   r   Zpadding_sizesZpad_sizer0   r2   r3   r&   v  s   
$$zEmu3VQVAEConv3d.__init__r<   c                 C   s   t || j}| |}|S rQ   )r   r   r   r   r   r2   r2   r3   r=     s   
zEmu3VQVAEConv3d.forward)
rB   rC   rD   r   r   r&   r)   r   r=   rE   r2   r2   r0   r3   r   u  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   r0   r2   r3   r&     s*   
zEmu3VQVAESpatialNorm.__init__r<   quant_statesc                 C   s@   t j||jdd  dd}| |}|| | | | }|S )Nrq   r   )sizer   )r   r   r?   r   r   r   )r-   r<   r   r2   r2   r3   r=     s   
zEmu3VQVAESpatialNorm.forward	rB   rC   rD   r   r&   r)   r   r=   rE   r2   r2   r0   r3   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   r0   r2   r3   r&        
z"Emu3VQVAETemporalUpsample.__init__r<   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   r4   r5   r   r   r   )r?   r   rx   r   r   r   r   )r-   r<   r   r   r   r   r   r2   r2   r3   r=     s    $
z!Emu3VQVAETemporalUpsample.forwardr   r2   r2   r0   r3   r         r   c                       r   )Emu3VQVAETemporalDownsampler   r   c                    r   )N)r   r   r   )r4   r   r   r   r   r   r0   r2   r3   r&     r   z$Emu3VQVAETemporalDownsample.__init__r<   c                 C   s   |  |}|S rQ   )r   r   r2   r2   r3   r=     s   
z#Emu3VQVAETemporalDownsample.forwardr   r2   r2   r0   r3   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   r0   r2   r3   r&     s4   
z%Emu3VQVAETemporalResnetBlock.__init__c                 C   sf   |}|  |}|t|9 }| |}| |}|t|9 }| |}| j| jkr/| |}|| S rQ   )	r   r)   sigmoidr   r   r   r   r   r   )r-   r<   r   r2   r2   r3   r=     s   




z$Emu3VQVAETemporalResnetBlock.forwardrQ   rS   r2   r2   r0   r3   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   r0   r2   r3   r&     sB   
zEmu3VQVAEResnetBlock.__init__r<   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 Nr2   )
r   r   r)   r   r   r   r   r   r   r   )r-   r<   r   Z	norm_argsr   r2   r2   r3   r=   >  s   


zEmu3VQVAEResnetBlock.forwardr   rQ   )
rB   rC   rD   r   r   r&   r)   r   r=   rE   r2   r2   r0   r3   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   rJ   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&   rJ   r.   r   r   	num_headsrg   
ValueErrorscaler   rp   r   r'   rK   r   r   r   out_projrt   rP   r0   r2   r3   r&   S  s&   


z Emu3VQVAEAttentionBlock.__init__NFr<   rn   r   ra   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   r4   r   r   r   ri   )r   ro   rp   N)r?   r   r   r   r   r   rg   rv   r   rJ   r   r   r   r   r   r   rs   rp   rc   rx   r  )r-   r<   rn   r   r   Z
seq_lengthr   Zquerieskeysvaluesr   r~   r|   r2   r2   r3   r=   j  s:   




zEmu3VQVAEAttentionBlock.forward)NF)rB   rC   rD   r   r    r&   r)   r   r   r   r   r=   rE   r2   r2   r0   r3   r   P  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-   ry   r0   r2   r3   r&     s   zEmu3VQVAEGroupNorm.__init__Nc                 C   s   t || j| j| j| jS rQ   )r   Z
group_normr   r+   rI   r/   )r-   inputr   r2   r2   r3   r=     s   zEmu3VQVAEGroupNorm.forwardrQ   )rB   rC   rD   r   r&   r=   rE   r2   r2   r0   r3   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-   rJ   r   r   r0   r2   r3   r&     s   

zEmu3VQVAEMiddleBlock.__init__r<   r   c                 C   s   |  ||}|}| ||}|j\}}}}||||| dd}| |d }|||||dddd}|| }| ||}|S )Nr   r4   r   r   )	r  r
  r?   r   rv   r	  rc   r   r  )r-   r<   r   r   r   r   r   r   r2   r2   r3   r=     s   zEmu3VQVAEMiddleBlock.forwardrQ   )	rB   rC   rD   r&   r)   r   r   r=   rE   r2   r2   r0   r3   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-   rJ   r  r  r  i_levelr  r  r  block_in	block_outi_blockr  r0   r2   r3   r&     sD   


zEmu3VQVAEDownBlock.__init__r<   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   r4   r   )	enumerater  r  r  r  r  r  r  r?   r   rv   rc   r   r  r  )
r-   r<   r  blocksr"  r   r   r   r   r   r2   r2   r3   r=     s    
zEmu3VQVAEDownBlock.forwardrB   rC   rD   r&   r)   r   r=   rE   r2   r2   r0   r3   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 )Nr5   r   r  r   )r%   r&   r  r  r  r  r   r  r'   r  upreversedr  r  r   r  r   r   r  r  r  r  r   upsampleinsert)r-   rJ   r   r   r  r  r  r  r!  r"  r'  r0   r2   r3   r&     s@   



zEmu3VQVAEUpBlock.__init__r<   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 )Nr5   r   r   r4   r   )r#  r'  r  r  r  r  r  r  r?   r   rv   rc   r   r)  )r-   r<   r   r  r$  r"  r   r   r   r   r   r2   r2   r3   r=   +  s    
zEmu3VQVAEUpBlock.forwardr%  r2   r2   r0   r3   r&    s    %r&  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 )Nr4   r5   r   r   r   r   r$   T)r   r   r/   r   r  )r%   r&   r  r   double_latentlatent_channelsr  r)   r'   r   conv_inr  
down_blockr  middle_blockr   norm_outconv_outr   mathlog2temporal_downsample_factorr  	time_convtime_res_stackr  r   r  r  r   )r-   rJ   r  r   r,  r-  r  r   r   Ztemporal_down_blocksir   _time_res_convr0   r2   r3   r&   @  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   r5   r4   r   r   r   )r?   rc   r.  r/  r0  r1  r)   r   r2  r   r6  r7  )r-   r;  Ztemporal_dimr<   r   layerr2   r2   r3   r=   g  s"   








zEmu3VQVAEEncoder.forward)rB   rC   rD   r&   r)   r   r=   rE   r2   r2   r0   r3   r+  ?  s    'r+  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 )Emu3VQVAEDecoderrJ   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 )Nr5   r  r   r   r   )r   r   )r%   r&   r   r  r  r'   r  r7  r  r  r   r-  r  r   r3  r4  r5  r6  r   r   r.  r  r0  r&  up_blockr   r1  r   r2  )	r-   rJ   r   r   r9  r:  Ztemp_upsample_block_numr8  r   r0   r2   r3   r&     s@   



zEmu3VQVAEDecoder.__init__r<   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   rT   r4   r   r   r   r5   )r)   rV   r   r7  r6  r   chunkrc   r?   r.  r0  r>  r1  r2  )r-   r<   r   Zhidden_quant_statesr<  r2   r2   r3   r=     s$   




zEmu3VQVAEDecoder.forward)	rB   rC   rD   r    r&   r)   r   r=   rE   r2   r2   r0   r3   r=    s    '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).
    )Z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 )	Emu3VQVAEZ
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 )
NZfan_outZrelu)r   Znonlinearityr      )ar   r   ri   )
isinstancer'   r   r   initZkaiming_normal_r+   rI   Z_calculate_fan_in_and_fan_outr3  sqrtr   rK   Zkaiming_uniform_ZBatchNorm2dr   r   Z	constant_r   r   normal_padding_idxzero_)r-   rj   Zfan_inr9  boundr2   r2   r3   _init_weights  s.   


zEmu3VQVAE._init_weightsrJ   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 )Nr4   r   )r   r   r   r   r   )r%   r&   rJ   r+  encoderr=  decoderr   quantizer  r  vision_spatial_factorr   r-  r   
quant_convpost_quant_convspatial_scale_factoreval	post_initrP   r0   r2   r3   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   r4   r   c                    s@   g | ]\}}|d t |d  j d t |d  j f qS )Nr   r   )r   rN  )r   Zsingle_imager   r@   r2   r3   r      s    .z$Emu3VQVAE.encode.<locals>.<listcomp>)ndimrJ   r5  r?   rY   repeatrK  r   rO  rM  Zsqueezer   )r-   r;  rT  is_imager   r   r   r   r   r<   codesimage_tokensr2   r@   r3   encode  s    




zEmu3VQVAE.encoder<   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   r5   r   r   r4   )rU  rY   r?   rM  r   flattenr   r   rx   rP  rL  rc   rJ   r5  r   rQ  )r-   r<   rW  r   r   r   r   Zquantr   Z
post_quantZvideor2   r2   r3   decode'  s&   


$

zEmu3VQVAE.decode)rB   rC   rD   r    config_classbase_model_prefixZmain_input_name_supports_sdpa_supports_flash_attn_2_supports_flex_attn_supports_attention_backend_no_split_modulesrJ  r&   r)   r   rZ  r\  rE   r2   r2   r0   r3   r@    s    r@  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_mapr   eol_token_idimage_token_id)r-   re  r2   r2   r3   r&   F  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valr2   r2   r3   r   M      z;Emu3ImageVocabularyMapping.image_tokens.<locals>.<listcomp>sortedre  itemsr@   r2   r2   r3   rY  K     z'Emu3ImageVocabularyMapping.image_tokensc                 C   rh  )Nc                 S   s   g | ]\}}| d r|qS ri  rj  rl  r2   r2   r3   r   Q  ro  z?Emu3ImageVocabularyMapping.image_tokens_str.<locals>.<listcomp>rp  r@   r2   r2   r3   image_tokens_strO  rs  z+Emu3ImageVocabularyMapping.image_tokens_strc                    s    fdd j D S )Nc                    s$   i | ]}t |d d  j| qS )irq   )r   re  )r   tokenr@   r2   r3   
<dictcomp>U  s   $ z6Emu3ImageVocabularyMapping.img2bpe.<locals>.<dictcomp>)rt  r@   r2   r@   r3   img2bpeS     z"Emu3ImageVocabularyMapping.img2bpec                 C   s   dd | j  D S )Nc                 S   s   i | ]\}}||qS r2   r2   )r   r[   vr2   r2   r3   rv  Y      z6Emu3ImageVocabularyMapping.bpe2img.<locals>.<dictcomp>)rw  rr  r@   r2   r2   r3   bpe2imgW  rx  z"Emu3ImageVocabularyMapping.bpe2imgc                 C   >   t jt| j d t jd}| j D ]\}}|||< q|S Nr   r7   )r)   zerosmaxr{  r  r   rr  r-   mappingr[   ry  r2   r2   r3   bpe2img_mapping_tensor[     
z1Emu3ImageVocabularyMapping.bpe2img_mapping_tensorc                 C   r|  r}  )r)   r  r  rw  r  r   rr  r  r2   r2   r3   img2bpe_mapping_tensorb  r  z1Emu3ImageVocabularyMapping.img2bpe_mapping_tensor	img_batchra   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~  cpur5   rT   )	devicer)   r*   r?   r   rf  r  r8   rV   )r-   r  r  Zeol_row
img_tokensr2   r2   r3   convert_img2bpei  s
    
z*Emu3ImageVocabularyMapping.convert_img2bpec                 C   s0   |j }|dd df }| j|d }||S )N.r5   r  )r  r  r8   )r-   r  r  r  r2   r2   r3   convert_bpe2imgp  s   
z*Emu3ImageVocabularyMapping.convert_bpe2imgN)rB   rC   rD   r   r&   r   rY  rt  rw  r{  r  r  r   r)   r   r  r  r2   r2   r2   r3   rd  A  s"    





rd  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 )Nri   )r;   stdr   )rJ   Zget_text_configZinitializer_rangerC  r'   rK   r   r+   r   rF  rI   rH  r   rG  r#   Zfill_)r-   rj   r  r2   r2   r3   rJ    s   


z!Emu3PreTrainedModel._init_weightsN)rB   rC   rD   r   r]  r^  Zsupports_gradient_checkpointingrc  Z_skip_keys_device_placementr`  r_  Z_supports_quantized_cacheZ_supports_cache_class_supports_static_cacheZ!_supports_param_buffer_assignmentrb  ra  rJ  r2   r2   r2   r3   r  w  s     r  c                       s8   e Zd Zddef fddZe edd Z  Z	S )Emu3RotaryEmbeddingNrJ   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  Zmax_position_embeddingsZmax_seq_len_cachedZoriginal_max_seq_lenrJ   r   Zrope_init_fnattention_scalingZregister_bufferr  Zoriginal_inv_freq)r-   rJ   r  r  r0   r2   r3   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   r5   r   Zmpsr  F)device_typeenabledr4   rT   r~  )r  floatrb   r?   r8   r  rC  r  strr)   Zautocastrv   rV   r\   r  r]   r7   )
r-   rR   r^   Zinv_freq_expandedZposition_ids_expandedr  ZfreqsZembr\   r]   r2   r2   r3   r=     s   0&zEmu3RotaryEmbedding.forwardrQ   )
rB   rC   rD   r   r&   r)   no_gradr   r=   rE   r2   r2   r0   r3   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	d"d
ee
jdf de
jde
jdedef
ddZed
e
jdedede
jde
jdefdd Z  ZS )#Emu3TextModelrJ   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 r2   )r   )r   r   rJ   r2   r3   r     rz  z*Emu3TextModel.__init__.<locals>.<listcomp>r   r  F)r%   r&   Zpad_token_idrG  
vocab_sizer'   r   r.   embed_tokensr  r  num_hidden_layerslayersr#   r   normr  
rotary_embgradient_checkpointingrS  rP   r0   r  r3   r&     s   zEmu3TextModel.__init__c                 C      | j S rQ   r  r@   r2   r2   r3   get_input_embeddings     z"Emu3TextModel.get_input_embeddingsc                 C   
   || _ d S rQ   r  r-   rm   r2   r2   r3   set_input_embeddings     
z"Emu3TextModel.set_input_embeddingsN	input_idsrn   r^   r  inputs_embedsr   r   output_hidden_statesr   flash_attn_kwargsra   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}| |||	||}|}| ||}|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  r2   )rn   r^   r   r   r   r   r   )last_hidden_stater  r<   
attentions)rJ   r   r  r   r   r  rs   r   r   rC  r  r
   r  r   get_seq_lengthr)   aranger?   r  rY   _update_causal_maskr  r  r  r  r   )r-   r  rn   r^   r  r  r   r   r  r   r  past_seen_tokensr}   r<   r   Zall_hidden_statesZall_self_attnsZdecoder_layerZlayer_outputsr2   r2   r3   r=     sx   



	


zEmu3TextModel.forwardFr!   input_tensorc                 C   s:  | j jdkr|d ur|dk r|S d S | j jdkr&t|tjr$t|}|S |d ur.| nd}|d ur7|jnd}| j jdkrO|sO|sOt	j
|||| jdrOd S |j}|jd }	|r^| }
nt|tjri|jd	 n||	 d }
| j||	|
|||jd d
}| j jdkr|d ur|jjdv r|st|j}t	||}|S )NZflash_attention_2ri   Zflex_attentionr   Fr   )r  Zpast_key_values_lengthZis_trainingr   r5   )sequence_lengthtarget_lengthr7   r   r   )cudaZxpuZnpu)rJ   r   anyrC  r)   r   r"   r  Zis_compileabler   Z_ignore_causal_mask_sdpars   r7   r?   Zget_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr  r  finfominZ_unmask_unattended)r-   rn   r  r   r  r   r  Zusing_compilable_cacher7   r  r  r}   	min_dtyper2   r2   r3   r  1  sT   




z!Emu3TextModel._update_causal_maskr  r  r7   r   c                 K   D  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	|ddddddd|	f | ddddddf |j }
|
dk}
|ddddddd|	f |
||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   )Z
fill_valuer7   r  r   )Zdiagonalr  r5   r   rU   r)   r  r  fullr  Ztriur  rc   rb   cloner?   r8   Zmasked_fillrn   r  r  r7   r   r   ry   r}   r  Zmask_lengthZpadding_maskr2   r2   r3   r  u  s,    $
6  zCEmu3TextModel._prepare_4d_causal_attention_mask_with_cache_position)	NNNNNNNNN)F)rB   rC   rD   r   r&   r  r  r   r   r   r)   r   r   r
   r   r   r   r   r   r=   r   r  staticmethodr   r7   r  rE   r2   r2   r0   r3   r    s    	
d
Dr  c                   @   s   e Zd ZdS )KwargsForCausalLMN)rB   rC   rD   r2   r2   r2   r3   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 )&Emu3ForCausalLMzlm_head.weightlm_headZcolwise_repr<   logitsc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S NFrH   )
r%   r&   r  r  r  r'   rK   r.   r  rS  rP   r0   r2   r3   r&     s
   
zEmu3ForCausalLM.__init__c                 C      | j jS rQ   r  r  r@   r2   r2   r3   r    s   z$Emu3ForCausalLM.get_input_embeddingsc                 C   s   || j _d S rQ   r  r  r2   r2   r3   r    s   z$Emu3ForCausalLM.set_input_embeddingsc                 C   r  rQ   r  r@   r2   r2   r3   get_output_embeddings  r  z%Emu3ForCausalLM.get_output_embeddingsc                 C   r  rQ   r  )r-   Znew_embeddingsr2   r2   r3   set_output_embeddings  r  z%Emu3ForCausalLM.set_output_embeddingsc                 C   r  rQ   r  )r-   rL  r2   r2   r3   set_decoder  r  zEmu3ForCausalLM.set_decoderc                 C   r  rQ   r  r@   r2   r2   r3   get_decoder  r  zEmu3ForCausalLM.get_decoderNr   r  rn   r^   r  r  labelsr   r   r  r   logits_to_keepry   ra   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  rn   r^   r  r  r   r   r  r   r  r  r  lossr  r  r<   r  r2   )rJ   r   r  r  r  rC  r   slicer  loss_functionr  r   r  r<   r  )r-   r  rn   r^   r  r  r  r   r   r  r   r  ry   r   r<   slice_indicesr  r  r2   r2   r3   r=     s:   '
zEmu3ForCausalLM.forward)NNNNNNNNNNr   )rB   rC   rD   _tied_weights_keysZ_tp_planZ_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=   rE   r2   r2   r0   r3   r    sh    		
r  c                !       s$  e Zd ZddiZdZ f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| _| jjd urdd | jjD | _t|j| _	t
|j| _|   d S )Nc                 S   s   g | ]}d | qS )ztext_model.r2   )r   r[   r2   r2   r3   r   &  rz  z&Emu3Model.__init__.<locals>.<listcomp>)r%   r&   r  Z_from_configtext_configr  r  r@  Z	vq_configvqmodelrd  Zvocabulary_mapvocabulary_mappingrS  rP   r0   r2   r3   r&   "  s   zEmu3Model.__init__c                 C   
   | j  S rQ   )r  r  r@   r2   r2   r3   r  .  r  zEmu3Model.get_input_embeddingsc                 C      | j | d S rQ   )r  r  r  r2   r2   r3   r  1     zEmu3Model.set_input_embeddingsr;  rT  c                 C   s   t d | |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   warningZget_image_featues)r-   r;  rT  r2   r2   r3   get_image_tokens4  s   
zEmu3Model.get_image_tokensc                    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 r2   )r  r  r[  )r   tokensr@   r2   r3   r   G  s    z0Emu3Model.get_image_features.<locals>.<listcomp>)r  rZ  r)   rV   )r-   r;  rT  Zimage_tokens_listZbpe_tokens_listZ
bpe_tokensr2   r@   r3   get_image_features:  s   
zEmu3Model.get_image_featuresrY  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.
        Nr5   r   )r   r  r  r  r\  )r-   rY  r   r   	sequencesimager2   r2   r3   decode_image_tokensK  s   "zEmu3Model.decode_image_tokensNr  rn   r^   r  r  r   r   r  return_dictr   ry   ra   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  rn   r^   r  r  r   r   r  r  r   r2   )rJ   r   r  use_return_dictr   r  r  rg  r8   r  r7   Zmasked_scatterr  )r-   r  r;  rT  rn   r^   r  r  r   r   r  r  r   ry   rY  Zspecial_image_maskr   r2   r2   r3   r=   ^  s@   zEmu3Model.forward)NNNNNNNNNNNN)rB   rC   rD   _checkpoint_conversion_mappingr  r&   r  r  r)   r   r   r  r  r  r   r  r   r   r   r   r
   r   r   r   r   r   r   r=   rE   r2   r2   r0   r3   r    sj    	

r  c                %       s^  e Zd ZdZddddZdZ fddZd	d
 Zdd Ze	dd Z
e	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j d eeejf d!ee d"eeef f d#d$Z						%	d/ fd&d'	Zedejd(ed)ed*ejdejd+efd,d-Z  Z S )0Emu3ForConditionalGeneration 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  rS  rP   r0   r2   r3   r&     s   
z%Emu3ForConditionalGeneration.__init__c                 C   r  rQ   )r  r  r@   r2   r2   r3   r    r  z1Emu3ForConditionalGeneration.get_input_embeddingsc                 C   r  rQ   )r  r  r  r2   r2   r3   r    r  z1Emu3ForConditionalGeneration.set_input_embeddingsc                 C   r  rQ   )r  r  r@   r2   r2   r3   r       z'Emu3ForConditionalGeneration.text_modelc                 C   r  rQ   )r  r  r@   r2   r2   r3   r    r  z$Emu3ForConditionalGeneration.vqmodelNr   r  r;  rT  rn   r^   r  r  r   r   r  r  r   r  r  ry   ra   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]
        ```NTr  r   r  r  r2   )rJ   r   r  r  r  rC  r   r  r  r  r  r  r   r  r<   r  )r-   r  r;  rT  rn   r^   r  r  r   r   r  r  r   r  r  ry   r   r<   r  r  r  r2   r2   r3   r=     sF   Az$Emu3ForConditionalGeneration.forwardTc	              
      s<   t  j|f|||||||d|	}
|d dkrd |
d< |
S )N)r  rn   r  r   r^   r;  r   r   r;  )r%   prepare_inputs_for_generation)r-   r  r  rn   r  r   r^   r   r;  ry   Zmodel_inputsr0   r2   r3   r  %  s    	z:Emu3ForConditionalGeneration.prepare_inputs_for_generationr  r  r7   r   c                 K   r  r  r  r  r2   r2   r3   r  D  s,    $
6  zREmu3ForConditionalGeneration._prepare_4d_causal_attention_mask_with_cache_position)NNNNNNNNNNNNNr   )NNNNNTN)!rB   rC   rD   r^  r  r  r&   r  r  propertyr  r  r   r   r)   r   r   r   r   r
   r   r   r   r   r  r   r   r=   r  r  r7   r  rE   r2   r2   r0   r3   r    s    

	

ir  )r  r  r  r  r@  r  )Nr   )ri   )ar3  	functoolsr   typingr   r   r   r   r   r)   Ztorch.nnr'   Ztorch.nn.functionalrw   r   Zactivationsr	   Zcache_utilsr
   r   Z
generationr   Zintegrationsr   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   Zmodeling_layersr   Zmodeling_outputsr   r   Zmodeling_rope_utilsr   r   Zmodeling_utilsr   r   Zprocessing_utilsr   utilsr   r   r   r   r   Zconfiguration_emu3r   r   r    Z!torch.nn.attention.flex_attentionr!   Zintegrations.flex_attentionr"   Z
get_loggerrB   r   r  r#   rG   rX   r_   r   r   rh   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  r  r  __all__r2   r2   r2   r3   <module>   s   


MK"$1?J";:FFo6" tm  `