o
    	۷i                     @   s  d Z ddlmZmZmZ ddlZddlmZ ddlmZ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mZ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#m$Z$m%Z%m&Z&m'Z' ddl(m)Z) ddl*m+Z+m,Z,m-Z- ddl.m/Z/ e  rddl0m1Z1 e"2e3Z4eG dd deZ5G dd dej6Z7G dd de)Z8G dd de%Z9G dd de&Z:G d d! d!e$Z;G d"d# d#ej6Z<G d$d% d%eZ=G d&d' d'e5Z>G d(d) d)eZ?G d*d+ d+e5Z@ed,d-G d.d/ d/e5ZAed0d-G d1d2 d2e5e/ZBg d3ZCdS )4zPyTorch Dia model.    )CallableOptionalUnionN)nn   )DynamicCacheEncoderDecoderCache)create_causal_mask)_prepare_4d_attention_mask#_prepare_4d_attention_mask_for_sdpa)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)auto_docstringcan_return_tupleis_torch_flex_attn_availableis_torchdynamo_compilinglogging   )LlamaAttentionLlamaRMSNormLlamaRotaryEmbeddingeager_attention_forward)Phi3MLP   )	DiaConfigDiaDecoderConfigDiaEncoderConfig)DiaGenerationMixin)make_flex_block_causal_maskc                   @   s:   e Zd ZU eed< dZdZdZdZdZ	dZ
dZddgZdS )DiaPreTrainedModelconfigmodelT	input_idsDiaEncoderLayerDiaDecoderLayerN)__name__
__module____qualname__r!   __annotations__base_model_prefixsupports_gradient_checkpointing_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraphmain_input_name_no_split_modules r8   r8   Y/home/ubuntu/vllm_env/lib/python3.10/site-packages/transformers/models/dia/modular_dia.pyr&   9   s   
 r&   c                       s<   e Zd ZdZdef fddZdejdejfddZ  Z	S )	DiaMultiChannelEmbeddinga  In order to efficiently compute the audio embedding from the 9 different channels,
    we vectorize the embedding process by using a single embedding layer and an offset.
    Example:
    - num_embeds = 4
    - vocab_size = 8
    - num_channels = 3
    We would have offsets = [0, 8, 16]
    If audio_codes = [0, 1, 2, 3], [1, 3, 4, 7], [5, 6, 7, 8],
    then tokens = audio_codes + offsets
                = [0, 1, 2, 3, 9, 11, 12, 15, 21, 22, 23, 24]
    This allows us to use a single embedding layer for all channels.
    r'   c                    s^   t    t|j|j |j| _|j| _|j| _tj	|jtj
d|j }| jd|dd d S )N)dtypeoffsetsF)
persistent)super__init__r   	Embedding
vocab_sizenum_channelshidden_sizeembedtorcharangelongregister_buffer)selfr'   r<   	__class__r8   r9   r?   T   s   
z!DiaMultiChannelEmbedding.__init__audio_codesreturnc                 C   sH   || j |j d}| ||jd |jd d| j}|jddS )Nr    r   r   )dim)	r<   todevicesqueezerD   viewshaperC   sum)rI   rL   tokensembedsr8   r8   r9   forward\   s   $z DiaMultiChannelEmbedding.forward)
r,   r-   r.   __doc__r"   r?   rE   TensorrX   __classcell__r8   r8   rJ   r9   r:   F   s    r:   c                   @      e Zd ZdS )DiaMLPNr,   r-   r.   r8   r8   r8   r9   r]   b       r]   c                   @   r\   )
DiaRMSNormNr^   r8   r8   r8   r9   r`   f   r_   r`   c                   @   r\   )DiaRotaryEmbeddingNr^   r8   r8   r8   r9   ra   j   r_   ra   c                   @   s0   e Zd ZdZd	deeef dedefddZ	dS )
DiaSelfAttention=Multi-headed attention from 'Attention Is All You Need' paperFr'   	layer_idx	is_causalc                 C   s   t j|  || _|| _|j| _| jj| _| jjp| j| _| j| j | _	t
|d|j| j | _d| _d| _|| _t j| j| j| j dd| _t j| j| j| j dd| _t j| j| j| j dd| _t j| j| j | jdd| _d S )Nhead_dimr            Fbias)r   Moduler?   r'   rd   rC   num_attention_heads	num_headsnum_key_value_headsnum_key_value_groupsgetattrrf   scalingattention_dropoutre   Linearq_projk_projv_projo_proj)rI   r'   rd   re   r8   r8   r9   r?   q   s   
 zDiaSelfAttention.__init__N)F)
r,   r-   r.   rY   r   r#   r"   intboolr?   r8   r8   r8   r9   rb   n   s    $rb   c                       st   e Zd ZdZdedef fddZ		ddejdejd	e	ej d
e	e
 dee deeje	ej f fddZ  ZS )DiaCrossAttentionrc   r'   rd   c                    s   t    || _|| _|j| _|j| _| jj| _| jj| _	| j| j	 | _
|j| _d| _d| _d| _tj| j| j| j dd| _tj| j| j	| j dd| _tj| j| j	| j dd| _tj| j| j | jdd| _d S )Nr    rg   Frh   )r>   r?   r'   rd   rC   cross_hidden_sizecross_num_attention_headsrl   cross_num_key_value_headsrm   rn   cross_head_dimrf   rp   rq   re   r   rr   rs   rt   ru   rv   rI   r'   rd   rJ   r8   r9   r?      s    


 zDiaCrossAttention.__init__Nhidden_statescross_attention_statesattention_maskpast_key_valueskwargsrM   c                 K   sb  |j d d }g |d| jR }g |j d d d| jR }| ||dd}	|d ur7|j| jnd}
|d urP|
rP|jj	| j j
}|jj	| j j}n-| ||dd}| ||dd}|d ur}|j||| j\}}d|j| j< t}| jjdkrt| jj }|| |	|||fd| ji|\}}|g |dR  }| |}||fS )NrN   r    r   FTeagerrp   )rT   rf   rs   rS   	transpose
is_updatedgetrd   cross_attention_cachelayerskeysvaluesrt   ru   updater   r'   _attn_implementationr   rp   reshape
contiguousrv   )rI   r   r   r   r   r   input_shapehidden_shapecross_shapequery_statesr   
key_statesvalue_statesattention_interfaceattn_outputattn_weightsr8   r8   r9   rX      sD   


zDiaCrossAttention.forwardNN)r,   r-   r.   rY   r"   rw   r?   rE   rZ   r   r   r   r   tuplerX   r[   r8   r8   rJ   r9   ry      s$    ry   c                       sv   e Zd Zdedef fddZ		ddejdee	ejejf  deej d	e
e d
e	ejeej f f
ddZ  ZS )r*   r'   rd   c                    sL   t    t|j|jd| _t||dd| _t|j|jd| _t	|| _
d S )NepsFre   )r>   r?   r`   rC   norm_epspre_sa_normrb   self_attentionpost_sa_normr]   mlpr~   rJ   r8   r9   r?      s
   
zDiaEncoderLayer.__init__Nr   position_embeddingsr   r   rM   c           
      K   sZ   |}|  |}| j|f||d|\}}|| }|}| |}| |}	||	 }||fS )Nr   r   )r   r   r   r   )
rI   r   r   r   r   residualnormed_statesself_attn_outputself_attn_weightsmlp_outr8   r8   r9   rX      s    



zDiaEncoderLayer.forwardr   )r,   r-   r.   r#   rw   r?   rE   rZ   r   r   r   r   rX   r[   r8   r8   rJ   r9   r*      s    
r*   c                       s   e Zd Zdef fddZee			ddejde	ej de	e
 d	e	e
 d
ee deeef fddZdeejdf dejfddZ  ZS )
DiaEncoderr'   c                    sd   t     | _t j j| _t fddt	 j
D | _t j jd| _t | _d S )Nc                       g | ]}t  |qS r8   )r*   .0rd   r'   r8   r9   
<listcomp>       z'DiaEncoder.__init__.<locals>.<listcomp>r   )r>   r?   r'   r   r@   rA   rC   	embedding
ModuleListrangenum_hidden_layersr   r`   r   normra   rotary_embeddingsrI   r'   rJ   r   r9   r?      s   zDiaEncoder.__init__NFr)   r   output_attentionsoutput_hidden_statesr   rM   c                 K   s   |  |}tj|jd |jdd d d f }| ||}| ||}|r&dnd }	|r,dnd }
| jD ]!}|r:|	|f }	||f||d|}|d }|rR|
|d f }
q1| |}|r_|	|f7 }	t	||	|
dS )NrN   rQ   r8   r   r   r    last_hidden_stater   
attentions)
r   rE   rF   rT   rQ   r   _update_full_maskr   r   r   )rI   r)   r   r   r   r   r   position_idsr   encoder_statesall_attentionsencoder_layerlayer_outputsr8   r8   r9   rX      s<   

"



zDiaEncoder.forwardinputs_embedsc                 C   s   |d ur>| j jdkrd|v r|}|S d }|S | j jdkr$t||j}|S | j jdkr8t|tjr6t|dd}|S t||j}|S )Nflash_attention_2r   sdpaflex_attentionFr   	r'   r   r   r;   
isinstancerE   rZ   r%   r
   )rI   r   r   r8   r8   r9   r   .  s   zDiaEncoder._update_full_mask)NFF)r,   r-   r.   r#   r?   r   r   rE   rZ   r   rx   r   r   r   r   r   rX   r   r[   r8   r8   rJ   r9   r      s2    
1r   c                       s   e Zd Zdedef fddZ						ddejdee	ejejf  deej d	eej d
eej dee
 deej de	ejeej eej f fddZ  ZS )r+   r'   rd   c                    sr   t    |j| _t||dd| _t||| _t|j|j	d| _
t|j|j	d| _t|j|j	d| _t|| _d S )NTr   r   )r>   r?   rC   	embed_dimrb   r   ry   cross_attentionr`   r   r   pre_ca_normpre_mlp_normr]   r   r~   rJ   r8   r9   r?   F  s   
zDiaDecoderLayer.__init__Nr   r   r   encoder_hidden_statesencoder_attention_maskr   cache_positionrM   c                 K   s   |}	t |	tr
|	j}	|}
| |}| j||||	fd|i|\}}|
| }|}
| |}| j||f||d|\}}|
| }|}
| |}| |}|
| }|||fS )Nr   )r   r   )	r   r   self_attention_cacher   r   r   r   r   r   )rI   r   r   r   r   r   r   r   r   self_attn_cacher   r   r   r   cross_statescross_attn_weightsr   r8   r8   r9   rX   P  sB   








zDiaDecoderLayer.forward)NNNNNN)r,   r-   r.   r"   rw   r?   rE   rZ   r   r   r   
LongTensorrX   r[   r8   r8   rJ   r9   r+   E  s2    
r+   c                       s   e Zd ZdZdef fddZee								ddej	de
ej d	e
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f fddZd
eej	df deej	df dejdej	fddZ  ZS )
DiaDecoderz-Transformer Decoder Stack using DenseGeneral.r'   c                    sf   t     j| _ j| _t | _t | _t	 fddt
 jD | _t j jd| _d S )Nc                    r   r8   )r+   r   r   r8   r9   r     r   z'DiaDecoder.__init__.<locals>.<listcomp>r   )r>   r?   rB   rA   r:   
embeddingsra   r   r   r   r   r   r   r`   rC   r   r   r   rJ   r   r9   r?     s   

zDiaDecoder.__init__NFr)   r   r   r   r   r   r   r   r   rM   c
                 K   s  |  dd \}}|dur| nd}|	du r#tj||| |jd}	|du r/|	dddf }| |}| ||}|du rNt sN|| }tj|||jd}t	| j
|||	||d}| |||jdd |}|rjdnd}|rpdnd}|rz|durzdnd}| jD ]0}|r||f7 }|||||f|||	d|
}|d }|r||d	 f }|dur||d f }q| |}|r||f7 }t|||||d
S )a  
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, num_codebooks)`):
            The original `decoder_input_ids` in 3D shape to facilitate more efficient computations.

            [What are input IDs?](../glossary#input-ids)
        NrN   r   r   )r'   input_embedsr   r   r   r   r   r8   )r   r   r   r    )r   r   r   r   cross_attentions)sizeget_seq_lengthrE   rF   rQ   r   r   r   onesr	   r'   _update_cross_attn_maskrT   r   r   r   )rI   r)   r   r   r   r   r   r   r   r   r   
batch_size
seq_lengthpast_key_values_lengthr   r   mask_seq_lengthall_hidden_statesall_self_attnsall_cross_attentionslayerr   r8   r8   r9   rX     sz   





zDiaDecoder.forwardr   r   c                 C   s   |d urM|d urM| j jdkrd|v r|}|S d }|S | j jdkr,t||j|d d}|S | j jdkrCt|tjrAt||d dd}|S t||j|d d}|S )	Nr   r   r   rN   )tgt_lenr   F)query_lengthre   r   )rI   r   r   r   r   r8   r8   r9   r     s2   z"DiaDecoder._update_cross_attn_mask)NNNNNFFN)r,   r-   r.   rY   r"   r?   r   r   rE   rZ   r   r   FloatTensorr   rx   r   r   r   rX   Sizer   r[   r8   r8   rJ   r9   r     sV    	

]r   z[
    The bare Dia model outputting raw hidden-states without any specific head on top.
    )custom_introc                       s   e Zd Zdef fddZdd Zee											ddee	j
 dee	j
 d	ee	j
 d
ee	j
 dee	j
 deeeef  dee dee dee dee dee	j
 deeef fddZ  ZS )DiaModelr'   c                    s6   t  | || _t|j| _t|j| _| 	  d S N)
r>   r?   r'   r   encoder_configencoderr   decoder_configdecoder	post_initr   rJ   r8   r9   r?     s
   zDiaModel.__init__c                 C   s   | j S r   )r   rI   r8   r8   r9   get_encoder  s   zDiaModel.get_encoderNr)   r   decoder_input_idsdecoder_position_idsdecoder_attention_maskencoder_outputsr   	use_cacher   r   r   rM   c                 K   s  |du r|du rt d|	dur|	n| jj}	|
dur|
n| jj}
|dur&|n| jj}| jr9| jr9|r9td d}|rL|du rLt	t
| jdt
| jd}|du r^| jd|||	|
d|}n"t|tst|d t|dkrq|d ndt|d	kr||d	 ndd
}|d jd d| jjj}}}|du rtj|d|f| jj| jd}|jd	kr||||dd	}| jd||||d |||	|
||d
|}t|j|j|j|j|j|d |j|jdS )a\  
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size * num_codebooks, target_sequence_length)
        or (batch_size, target_sequence_length, num_codebooks)`, *optional*):
            1. (batch_size * num_codebooks, target_sequence_length): corresponds to the general use case where
            the audio input codebooks are flattened into the batch dimension. This also aligns with the flat-
            tened audio logits which are used to calculate the loss.

            2. (batch_size, sequence_length, num_codebooks): corresponds to the internally used shape of
            Dia to calculate embeddings and subsequent steps more efficiently.

            If no `decoder_input_ids` are provided, it will create a tensor of `bos_token_id` with shape
            `(batch_size, 1, num_codebooks)`. Indices can be obtained using the [`DiaProcessor`]. See
            [`DiaProcessor.__call__`] for more details.

            [What are decoder input IDs?](../glossary#decoder-input-ids)
        decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
            Indices of positions of each input sequence tokens in the position embeddings.
            Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`.

            [What are position IDs?](../glossary#position-ids)
        NzXYou should either provide text ids or the cached text encodings. Neither has been found.zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   )r)   r   r   r   r   r    r   r   rN   )r   
fill_valuerQ   )
r)   r   r   r   r   r   r   r   r   r   )r   r   decoder_hidden_statesdecoder_attentionsr   encoder_last_hidden_stater   encoder_attentionsr8   ) 
ValueErrorr'   r   r   r   is_gradient_checkpointingtrainingloggerwarning_oncer   r   r   r   r   lenrT   r   rB   rE   fullbos_token_idrQ   ndimr   r   r   r   r   r   r   r   r   )rI   r)   r   r   r   r   r   r   r   r   r   r   r   bszseq_lenchannelsdecoder_outputsr8   r8   r9   rX   !  s|   '
 
zDiaModel.forward)NNNNNNNNNNN)r,   r-   r.   r!   r?   r   r   r   r   rE   r   r   r   r   r   rx   r   rX   r[   r8   r8   rJ   r9   r     sR    	

r   zl
    The Dia model consisting of a (byte) text encoder and audio decoder with a prediction head on top.
    c                       s   e Zd 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j de
ej de
eeef  de
e de
e de
e de
e de
ej de
ej deeef fddZ  ZS )DiaForConditionalGenerationr(   r'   c                    s`   t  | || _t|| _|jj| _|jj| _tj	|jj
| j| j dd| _d| _|   d S )NFrh   ForMaskedLM)r>   r?   r'   r   r(   r   rB   rA   r   rr   rC   logits_dense	loss_typer   r   rJ   r8   r9   r?     s   


z$DiaForConditionalGeneration.__init__c                 C   
   | j  S r   )r(   r   r   r8   r8   r9   r        
z'DiaForConditionalGeneration.get_encoderc                 C   r  r   )r(   get_decoderr   r8   r8   r9   r    r  z'DiaForConditionalGeneration.get_decoderNr)   r   r   r   r   r   r   r   r   r   labelsr   rM   c                 K   s   | j d	|||||||||	|
|d|}|d }|jd }| ||d| j| jfdd || j d| j}d}|durM| jd	||| jd|}t	|||j
|j|j|j|j|j|jd	S )
a  
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size * num_codebooks, target_sequence_length)
        or (batch_size, target_sequence_length, num_codebooks)`, *optional*):
            1. (batch_size * num_codebooks, target_sequence_length): corresponds to the general use case where
            the audio input codebooks are flattened into the batch dimension. This also aligns with the flat-
            tened audio logits which are used to calculate the loss.

            2. (batch_size, sequence_length, num_codebooks): corresponds to the internally used shape of
            Dia to calculate embeddings and subsequent steps more efficiently.

            If no `decoder_input_ids` are provided, it will create a tensor of `bos_token_id` with shape
            `(batch_size, 1, num_codebooks)`. Indices can be obtained using the [`DiaProcessor`]. See
            [`DiaProcessor.__call__`] for more details.

            [What are decoder input IDs?](../glossary#decoder-input-ids)
        decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
            Indices of positions of each input sequence tokens in the position embeddings.
            Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`.

            [What are position IDs?](../glossary#position-ids)
        labels (`torch.LongTensor` of shape `(batch_size * num_codebooks,)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in
            `[0, ..., config.decoder_config.vocab_size - 1]` or -100. Tokens with indices set to `-100`
            are ignored (masked).
        )r)   r   r   r   r   r   r   r   r   r   r   r   rN   r    r   N)logitsr  rA   )	lossr  r   r   r   r   r   r   r   r8   )r(   rT   r  rS   rB   rA   r   r   loss_functionr   r   r   r   r   r   r   r   )rI   r)   r   r   r   r   r   r   r   r   r   r  r   r   outputsr   r   audio_logitsr  r8   r8   r9   rX     sJ   ,
z#DiaForConditionalGeneration.forward)NNNNNNNNNNNN)r,   r-   r.   r0   r!   r?   r   r  r   r   r   rE   r   r   r   r   r   rx   r   rX   r[   r8   r8   rJ   r9   r    s\    	

r  )r   r&   r  )DrY   typingr   r   r   rE   r   cache_utilsr   r   masking_utilsr	   modeling_attn_mask_utilsr
   r   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   llama.modeling_llamar   r   r   r   phi3.modeling_phi3r   configuration_diar!   r"   r#   generation_diar$   integrations.flex_attentionr%   
get_loggerr,   r  r&   rj   r:   r]   r`   ra   rb   ry   r*   r   r+   r   r   r  __all__r8   r8   r8   r9   <module>   sT   
J!V; {o