o
    Zh                     @   s  d dl Z d dlmZ d dl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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 ddlmZmZmZ ddlm Z m!Z! ddl"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z*m+Z+m,Z, e-e.Z/G dd de$Z0G dd de
j1Z2G dd de!Z3G dd de
j1Z4G dd de
j1Z5G dd de
j1Z6G dd de
j1Z7G d d! d!e
j1Z8G d"d# d#e
j1Z9G d$d% d%e
j1Z:G d&d' d'e(Z;G d(d) d)e
j<Z=G d*d+ d+e
j1Z>G d,d- d-e
j1Z?G d.d/ d/e
j1Z@G d0d1 d1e
j1ZAG d2d3 d3e
j1ZBed4d5G d6d7 d7eZCG d8d9 d9ZDG d:d; d;e eCZEG d<d= d=e&eEZFG d>d? d?e%eEeZGG d@dA dAeEZHG dBdC dCeEeZIg dDZJdS )E    N)cached_property)ListOptionalTupleUnion   )Cache)GenerationMixin)FlashAttentionKwargs)CausalLMOutputWithPast)PreTrainedModel)Unpack)auto_docstringcan_return_tuplelogging   )ChameleonPreTrainedModel#ChameleonVQVAEEncoderConvDownsample)KwargsForCausalLMLlamaDecoderLayerLlamaForCausalLM
LlamaModel)SiglipAttention   )
Emu3ConfigEmu3TextConfigEmu3VQVAEConfigc                       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 )Emu3DecoderLayerconfig	layer_idxc                    s    t  || t|j| _d S N)super__init__nnZDropoutZattention_dropoutdropout)selfr   r   	__class__ T/var/www/auris/lib/python3.10/site-packages/transformers/models/emu3/modular_emu3.pyr"   ,   s   zEmu3DecoderLayer.__init__NFhidden_statesattention_maskposition_idspast_key_valueoutput_attentions	use_cachecache_positionposition_embeddingsreturnc	                 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*   r+   r,   r-   r.   r/   r0   r1   Nr(   )Zinput_layernormZ	self_attnr$   Zpost_attention_layernormZmlp)r%   r*   r+   r,   r-   r.   r/   r0   r1   kwargsresidualZself_attn_weightsoutputsr(   r(   r)   forward0   s.   
	



zEmu3DecoderLayer.forward)NNNFFNN)__name__
__module____qualname__r   intr"   torchTensorr   
LongTensorr   boolr   FloatTensorr6   __classcell__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.
    r   c                    s>   t    t|j|j| _| jjj	d|j d|j  d S )Ng            ?)
r!   r"   r#   	EmbeddingZcodebook_size	embed_dim	embeddingweightdatauniform_r%   r   r&   r(   r)   r"   z   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      r   T)dimZkeepdimrM   )shapepermute
contiguousviewr;   sumrE   rF   matmul	transposeZargmin)r%   rJ   
batch_sizetemporalchannelsheightwidthZhidden_state_flattenedZhidden_state_sumZembedding_sumZ	distancesZmin_encoding_indicesr(   r(   r)   r6      s   z Emu3VQVAEVectorQuantizer.forward)
r7   r8   r9   __doc__r   r"   r;   r<   r6   r@   r(   r(   r&   r)   rA   o   s    
rA   c                   @   s   e Zd ZdS )Emu3VQVAEEncoderConvDownsampleN)r7   r8   r9   r(   r(   r(   r)   r\      s    r\   c                       s$   e Zd Z fddZdd Z  ZS )Emu3VQVAEEncoderConvUpsamplec                    s$   t    tj||dddd| _d S )Nr   r   kernel_sizestridepadding)r!   r"   r#   Conv2dconv)r%   in_channelsr&   r(   r)   r"      s   
z%Emu3VQVAEEncoderConvUpsample.__init__c                 C   s   t j|ddd}| |}|S )N       @nearestZscale_factormode)Finterpolaterc   r%   r*   r(   r(   r)   r6      s   
z$Emu3VQVAEEncoderConvUpsample.forwardr7   r8   r9   r"   r6   r@   r(   r(   r&   r)   r]      s    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(   ).0Z
one_kernelZ
one_strider(   r(   r)   
<listcomp>   s    z,Emu3VQVAEConv3d.__init__.<locals>.<listcomp>r   r(   rL   r   )r   r   )r`   )r!   r"   zipra   r#   Conv3drc   )r%   rn   ro   r_   r`   Zpadding_sizesZpad_sizer&   r(   r)   r"      s   
$$zEmu3VQVAEConv3d.__init__r*   c                 C   s   t || j}| |}|S r    )ri   padra   rc   rk   r(   r(   r)   r6      s   
zEmu3VQVAEConv3d.forward)
r7   r8   r9   r:   r   r"   r;   r<   r6   r@   r(   r(   r&   r)   rm      s    rm   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 )	Emu3VQVAESpatialNormrd   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    ư>Tnum_channels
num_groupsepsaffiner   r   r^   )r!   r"   r#   	GroupNorm
norm_layerrb   conv_yconv_br%   rd   rv   r&   r(   r)   r"      s*   
zEmu3VQVAESpatialNorm.__init__r*   quant_statesc                 C   s@   t j||jdd  dd}| |}|| | | | }|S )Nrf   )sizerh   )ri   rj   rO   r   r   r   )r%   r*   r   r(   r(   r)   r6      s   
zEmu3VQVAESpatialNorm.forward	r7   r8   r9   r:   r"   r;   r<   r6   r@   r(   r(   r&   r)   ru      s    ru   c                       6   e Zd Zdedef fddZdejfddZ  ZS )Emu3VQVAETemporalUpsamplern   ro   c                        t    t||ddd| _d S )Nr   r   r   r   r   r   r_   r`   r!   r"   rm   rc   r%   rn   ro   r&   r(   r)   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   rK   r   rL   re   rf   rg   )rO   rP   rQ   rR   ri   rj   rc   )r%   r*   rV   rX   rW   rY   rZ   r(   r(   r)   r6      s    $
z!Emu3VQVAETemporalUpsample.forwardr   r(   r(   r&   r)   r          r   c                       r   )Emu3VQVAETemporalDownsamplern   ro   c                    r   )N)rK   r   r   )r   r   r   r   r   r   r&   r(   r)   r"      r   z$Emu3VQVAETemporalDownsample.__init__r*   c                 C   s   |  |}|S r    )rc   rk   r(   r(   r)   r6     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"   rd   rv   r#   BatchNorm3dnorm1rm   conv1norm2conv2rs   nin_shortcutr   r&   r(   r)   r"     s4   
z%Emu3VQVAETemporalResnetBlock.__init__c                 C   sf   |}|  |}|t|9 }| |}| |}|t|9 }| |}| j| jkr/| |}|| S r    )	r   r;   sigmoidr   r   r   rd   rv   r   )r%   r*   r4   r(   r(   r)   r6   ,  s   




z$Emu3VQVAETemporalResnetBlock.forwardr    rl   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 )Emu3VQVAEResnetBlockNrd   rv   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 )	Nrw   rx   Try   r   r   r^   r   )r!   r"   rd   rv   r   r#   r~   r   r   ru   rb   r   r   r   )r%   rd   rv   r   r&   r(   r)   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 Nr(   )
r   r   r;   r   r   r   r   rd   rv   r   )r%   r*   r   Z	norm_argsr4   r(   r(   r)   r6   i  s   


zEmu3VQVAEResnetBlock.forward)NNr    )
r7   r8   r9   r:   r   r"   r;   r<   r6   r@   r(   r(   r&   r)   r   <  s    $,r   c                       "   e Zd Zdef fddZ  ZS )Emu3VQVAEAttentionBlockr   c                    s   t  | d| _d S )Nr   )r!   r"   Znum_key_value_groupsrI   r&   r(   r)   r"   |  s   
z Emu3VQVAEAttentionBlock.__init__)r7   r8   r9   r   r"   r@   r(   r(   r&   r)   r   {      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%   r3   r&   r(   r)   r"     s   zEmu3VQVAEGroupNorm.__init__Nc                 C   s   t || j| j| j| jS r    )ri   Z
group_normr{   rF   biasr|   )r%   inputr   r(   r(   r)   r6     s   zEmu3VQVAEGroupNorm.forwardr    )r7   r8   r9   r[   r"   r6   r@   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rd   rv   r   rw   rx   Try   )
r!   r"   r   block_1r   attn_1r   	attn_normru   block_2)r%   r   rd   r   r&   r(   r)   r"     s   

zEmu3VQVAEMiddleBlock.__init__r*   r   c                 C   s   |  ||}|}| ||}|j\}}}}||||| dd}| |d }|||||dddd}|| }| ||}|S )Nr   r   r   r   )	r   r   rO   rR   rU   r   reshaperP   r   )r%   r*   r   r4   rV   rX   rY   rZ   r(   r(   r)   r6     s   zEmu3VQVAEMiddleBlock.forwardr    )	r7   r8   r9   r"   r;   r?   r   r6   r@   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   rd   rv   rw   rx   Try   r   )r!   r"   lenchannel_multipliernum_resolutionsnum_res_blocksbase_channelstuplein_channel_multiplierr#   
ModuleListdownrangeappendr   attn_resolutionsr   r~   Moduleblockattn
attn_normsr\   
downsample)r%   r   r   r   r   i_levelr   r   r   block_in	block_outi_blockr   r&   r(   r)   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   r   r   )	enumerater   r   r   r   r   r   r   rO   rR   rU   r   rP   r   r   )
r%   r*   r   blocksr   r4   rV   rX   rY   rZ   r(   r(   r)   r6     s    
zEmu3VQVAEDownBlock.forwardr7   r8   r9   r"   r;   r?   r6   r@   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 )NrL   r   r   r   )r!   r"   r   r   r   r   rD   r   r#   r   upreversedr   r   r   r   r   ru   r   r   r   r   r]   upsampleinsert)r%   r   r   r   r   r   r   r   r   r   r   r&   r(   r)   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 )NrL   r   r   r   r   )r   r   r   r   r   r   r   r   rO   rR   rU   r   rP   r   )r%   r*   r   r   r   r   r4   rV   rX   rY   rZ   r(   r(   r)   r6     s    
zEmu3VQVAEUpBlock.forwardr   r(   r(   r&   r)   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 )Nr   rL   r   r   r^   rw   rx   T)r{   rz   r|   r}   r   )r!   r"   r   rd   double_latentlatent_channelsr   r;   r#   rb   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%   r   r   rd   r   r   r   rv   r   Ztemporal_down_blocksirc   _time_res_convr&   r(   r)   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   rL   r   r   r   rK   )rO   r   r   r   r   r   r;   r   r   rP   r   r   )r%   r   Ztemporal_dimr*   rc   layerr(   r(   r)   r6   P  s"   








zEmu3VQVAEEncoder.forward)r7   r8   r9   r"   r;   r=   r6   r@   r(   r(   r&   r)   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 )Emu3VQVAEDecoderr   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 )NrL   r   r   r   r^   )r   r   )r!   r"   rD   r   r   r#   r   r   r   r   r   r   r   r:   r   r   r   r   r   rb   r   r   r   r   up_blockru   r   rv   r   )	r%   r   r   r   r   r   Ztemp_upsample_block_numr   rc   r&   r(   r)   r"   o  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   rN   r   r   r   rK   rL   )r;   catrP   r   r   r   chunkr   rO   r   r   r   r   r   )r%   r*   r   Zhidden_quant_statesr   r(   r(   r)   r6     s$   




zEmu3VQVAEDecoder.forward)	r7   r8   r9   r   r"   r;   r<   r6   r@   r(   r(   r&   r)   r   n  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   rA   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)rh   Znonlinearityr      )ar   rB           )
isinstancer#   rb   rs   initZkaiming_normal_rF   r   Z_calculate_fan_in_and_fan_outr   sqrtrH   LinearZkaiming_uniform_ZBatchNorm2dr   r~   Z	constant_rC   rG   normal_padding_idxzero_)r%   moduleZfan_inr   boundr(   r(   r)   _init_weights  s.   


zEmu3VQVAE._init_weightsr   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 )Nr   r   )r   r   r   r   r   )r!   r"   r   r   encoderr   decoderrA   quantizer   r   vision_spatial_factorrm   r   rD   
quant_convpost_quant_convspatial_scale_factoreval	post_initrI   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 )NrK   r   r   r   r   c                    s@   g | ]\}}|d t |d  j d t |d  j f qS )Nr   r   )r:   r   )rp   Zsingle_imager   r%   r(   r)   rq   	  s    .z$Emu3VQVAE.encode.<locals>.<listcomp>)ndimr   r   rO   	unsqueezerepeatr   rP   r   r   Zsqueezerr   )r%   r   r   is_imagerW   rV   rX   rY   rZ   r*   codesimage_tokensr(   r   r)   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   rL   r   rK   r   )r   r   rO   r   rE   flattenrR   rP   rQ   r   r   r   r   r   rv   r   )r%   r*   r   rV   rW   rY   rZ   ZquantrX   Z
post_quantZvideor(   r(   r)   decode  s&   


$

zEmu3VQVAE.decode)r7   r8   r9   r   config_classbase_model_prefixZmain_input_nameZ_supports_sdpaZ_supports_flash_attn_2_supports_flex_attn_supports_attention_backend_no_split_modulesr   r"   r;   r<   r   r  r@   r(   r(   r&   r)   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_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rp   namevalr(   r(   r)   rq   6      z;Emu3ImageVocabularyMapping.image_tokens.<locals>.<listcomp>sortedr  itemsr   r(   r(   r)   r   4     z'Emu3ImageVocabularyMapping.image_tokensc                 C   r  )Nc                 S   s   g | ]\}}| d r|qS r  r  r  r(   r(   r)   rq   :  r  z?Emu3ImageVocabularyMapping.image_tokens_str.<locals>.<listcomp>r  r   r(   r(   r)   image_tokens_str8  r  z+Emu3ImageVocabularyMapping.image_tokens_strc                    s    fdd j D S )Nc                    s$   i | ]}t |d d  j| qS )ir   )r:   r  )rp   tokenr   r(   r)   
<dictcomp>>  s   $ z6Emu3ImageVocabularyMapping.img2bpe.<locals>.<dictcomp>)r  r   r(   r   r)   img2bpe<     z"Emu3ImageVocabularyMapping.img2bpec                 C   s   dd | j  D S )Nc                 S   s   i | ]\}}||qS r(   r(   )rp   kvr(   r(   r)   r  B      z6Emu3ImageVocabularyMapping.bpe2img.<locals>.<dictcomp>)r  r  r   r(   r(   r)   bpe2img@  r  z"Emu3ImageVocabularyMapping.bpe2imgc                 C   >   t jt| j d t jd}| j D ]\}}|||< q|S Nr   dtype)r;   zerosmaxr   keysr:   r  r%   mappingr  r  r(   r(   r)   bpe2img_mapping_tensorD     
z1Emu3ImageVocabularyMapping.bpe2img_mapping_tensorc                 C   r!  r"  )r;   r%  r&  r  r'  r:   r  r(  r(   r(   r)   img2bpe_mapping_tensorK  r+  z1Emu3ImageVocabularyMapping.img2bpe_mapping_tensor	img_batchr2   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#  cpurL   rN   )	devicer;   ZonesrO   r:   r
  r,  tor   )r%   r-  r/  Zeol_row
img_tokensr(   r(   r)   convert_img2bpeR  s
    
z*Emu3ImageVocabularyMapping.convert_img2bpec                 C   s0   |j }|dd df }| j|d }||S )N.rL   r.  )r/  r*  r0  )r%   r-  r/  r1  r(   r(   r)   convert_bpe2imgY  s   
z*Emu3ImageVocabularyMapping.convert_bpe2imgN)r7   r8   r9   r[   r"   r   r   r  r  r   r*  r,  r   r;   r<   r2  r3  r(   r(   r(   r)   r  *  s"    





r  c                   @   s"   e Zd ZdgZdZdZdd ZdS )Emu3PreTrainedModelr   Tc                 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 )Nr   )meanstdrB   )r   Zget_text_configZinitializer_ranger   r#   r   rb   rF   rG   r   r   r   rC   r   ZEmu3RMSNormZfill_)r%   r   r6  r(   r(   r)   r   g  s   


z!Emu3PreTrainedModel._init_weightsN)r7   r8   r9   r  r  r  r   r(   r(   r(   r)   r4  `  s    r4  c                       r   )Emu3TextModelr   c                    s0   t    t fddt jD | _d S )Nc                    s   g | ]}t  |qS r(   )r   )rp   r   r   r(   r)   rq   y  r  z*Emu3TextModel.__init__.<locals>.<listcomp>)r!   r"   r#   r   r   Znum_hidden_layersZlayersrI   r&   r8  r)   r"   v  s   
zEmu3TextModel.__init__)r7   r8   r9   r   r"   r@   r(   r(   r&   r)   r7  u  r   r7  c                       s,   e Zd ZeZ fddZ fddZ  ZS )Emu3ForCausalLMc                    s   t  | t|| _d S r    )r!   r"   r7  modelrI   r&   r(   r)   r"     s   zEmu3ForCausalLM.__init__c                     s   t    dS )a  
        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!   r6   )Zsuper_kwargsr&   r(   r)   r6     s   zEmu3ForCausalLM.forward)r7   r8   r9   r   r  r"   r6   r@   r(   r(   r&   r)   r9  }  s    r9  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.r(   )rp   r  r(   r(   r)   rq     r  z&Emu3Model.__init__.<locals>.<listcomp>)r!   r"   r7  Z_from_configtext_configr<  Z_tied_weights_keysr   Z	vq_configvqmodelr  Zvocabulary_mapvocabulary_mappingr   rI   r&   r(   r)   r"     s   zEmu3Model.__init__c                 C   
   | j  S r    )r<  get_input_embeddingsr   r(   r(   r)   rA       
zEmu3Model.get_input_embeddingsc                 C      | j | d S r    )r<  set_input_embeddingsr%   valuer(   r(   r)   rD       zEmu3Model.set_input_embeddingsr   r   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()`)loggerwarningZget_image_featues)r%   r   r   r(   r(   r)   get_image_tokens  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 r(   )r?  r2  r   )rp   tokensr   r(   r)   rq     s    z0Emu3Model.get_image_features.<locals>.<listcomp>)r>  r   r;   r   )r%   r   r   Zimage_tokens_listZbpe_tokens_listZ
bpe_tokensr(   r   r)   get_image_features  s   
zEmu3Model.get_image_featuresr   rY   rZ   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.
        NrL   r   )rR   r?  r3  r>  r  )r%   r   rY   rZ   	sequencesimager(   r(   r)   decode_image_tokens  s   "zEmu3Model.decode_image_tokensN	input_idsr+   r,   past_key_valuesinputs_embedsr/   r.   output_hidden_statesreturn_dictr0   r3   r2   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
rQ  r+   r,   rR  rS  r/   r.   rT  rU  r0   r(   )r   r.   rT  use_return_dict
ValueErrorrL  r?  r  r0  r/  r$  Zmasked_scatterr<  )r%   rQ  r   r   r+   r,   rR  rS  r/   r.   rT  rU  r0   r3   r   Zspecial_image_maskr5   r(   r(   r)   r6     s@   zEmu3Model.forward)NNNNNNNNNNNN)r7   r8   r9   _checkpoint_conversion_mapping_supports_static_cacher"   rA  rD  r;   r?   r=   rJ  rL  Zno_gradr:   rP  r   r   r<   r   r   r>   r   r
   r   r   r   r6   r@   r(   r(   r&   r)   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.vqmodellm_head)z^text_model.modelz^vqmodelz^text_model.lm_headFc                    s<   t  | t|| _tj|jj|jjdd| _	| 
  d S )NF)r   )r!   r"   r;  r:  r#   r   r=  Zhidden_size
vocab_sizer]  r   rI   r&   r(   r)   r"   "  s   
z%Emu3ForConditionalGeneration.__init__c                 C   r@  r    )r:  rA  r   r(   r(   r)   rA  )  rB  z1Emu3ForConditionalGeneration.get_input_embeddingsc                 C   rC  r    )r:  rD  rE  r(   r(   r)   rD  ,  rG  z1Emu3ForConditionalGeneration.set_input_embeddingsc                 C      | j jS r    )r:  r<  r   r(   r(   r)   r<  0     z'Emu3ForConditionalGeneration.text_modelc                 C   r_  r    )r:  r>  r   r(   r(   r)   r>  4  r`  z$Emu3ForConditionalGeneration.vqmodelNr   rQ  r   r   r+   r,   rR  rS  r/   r.   rT  rU  r0   labelslogits_to_keepr3   r2   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]
        ```NTrV  r   )logitsra  r^  )lossrc  rR  r*   
attentionsr(   )r   r.   rT  rW  r:  r   r:   slicer]  Zloss_functionr=  r^  r   rR  r*   re  )r%   rQ  r   r   r+   r,   rR  rS  r/   r.   rT  rU  r0   ra  rb  r3   r5   r*   Zslice_indicesrc  rd  r(   r(   r)   r6   8  sF   Az$Emu3ForConditionalGeneration.forwardTc	              
      s<   t  j|f|||||||d|	}
|d dkrd |
d< |
S )N)rR  r+   rS  r0   r,   r   r/   r   r   )r!   prepare_inputs_for_generation)r%   rQ  rR  r+   rS  r0   r,   r/   r   r3   Zmodel_inputsr&   r(   r)   rg    s    	z:Emu3ForConditionalGeneration.prepare_inputs_for_generationsequence_lengthtarget_lengthr$  rV   c                 K   sD  | 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.
        NrK   )Z
fill_valuer$  r/  r   )Zdiagonal)r/  rL   r   )rM   r;   Zfinfominfullr/  ZtriuZaranger   expandclonerO   r0  Zmasked_fill)r+   rh  ri  r$  r0   rV   r3   Zcausal_maskZ	min_dtypeZmask_lengthZpadding_maskr(   r(   r)   5_prepare_4d_causal_attention_mask_with_cache_position  s,    $
6  zREmu3ForConditionalGeneration._prepare_4d_causal_attention_mask_with_cache_position)NNNNNNNNNNNNNr   )NNNNNTN)!r7   r8   r9   r  rY  rZ  r"   rA  rD  propertyr<  r>  r   r   r;   r=   r?   r<   r   r   r>   r   r:   r   r   r   r   r6   rg  staticmethodr$  rn  r@   r(   r(   r&   r)   r[    s    

	

ir[  )r[  r9  r7  r4  r   r;  )Kr   	functoolsr   typingr   r   r   r   r;   Ztorch.nnr#   Ztorch.nn.functionalZ
functionalri   Ztorch.utils.checkpointZcache_utilsr   Z
generationr	   Zmodeling_flash_attention_utilsr
   Zmodeling_outputsr   Zmodeling_utilsr   Zprocessing_utilsr   utilsr   r   r   Zchameleon.modeling_chameleonr   r   Zllama.modeling_llamar   r   r   r   Zsiglip.modeling_siglipr   Zconfiguration_emu3r   r   r   Z
get_loggerr7   rH  r   r   rA   r\   r]   rm   ru   r   r   r   r   r   r~   r   r   r   r   r   r   r   r  r4  r7  r9  r;  r[  __all__r(   r(   r(   r)   <module>   sb   
D"$1?";:FFo6  `