o
    	۷iK                     @   s  d dl mZmZmZ d dl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 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 m!Z! ddl"m#Z# ddl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0 ddl1m2Z2 e( rddl3m4Z4 e*5e6Z7e&G dd de!Z8G dd dej9Z:G dd dej9Z;edG dd dej9Z<G dd  d ej9Z=d!d" Z>dId#d$Z?d%ej@d&eAd'ej@fd(d)ZB	*dJd+ej9d,ej@d-ej@d.ej@d/eej@ d0eCd1eCd2e#e% fd3d4ZDG d5d6 d6ej9ZEG d7d8 d8ej9ZFG d9d: d:eZGG d;d< d<e8ZHG d=d> d>eZIG d?d@ d@e8ZJe&dAdBG dCdD dDe8ZKe&dEdBG dFdG dGe8e2ZLg dHZMdS )K    )CallableOptionalUnionN)nn   )ACT2FN)CacheDynamicCacheEncoderDecoderCache)use_kernel_forward_from_hub)create_causal_mask)_prepare_4d_attention_mask#_prepare_4d_attention_mask_for_sdpa)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tupleis_torch_flex_attn_availableis_torchdynamo_compilinglogging)deprecate_kwarg   )	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 r9   r9   Z/home/ubuntu/vllm_env/lib/python3.10/site-packages/transformers/models/dia/modeling_dia.pyr'   ?   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__r9   r:   rB   Z   s   
z!DiaMultiChannelEmbedding.__init__audio_codesreturnc                 C   sH   || j |j d}| ||jd |jd d| j}|jddS )Nr!   r      dim)	r>   todevicesqueezerG   viewshaperF   sum)rL   rO   tokensembedsr9   r9   r:   forwardb   s   $z DiaMultiChannelEmbedding.forward)
r-   r.   r/   __doc__r#   rB   rH   Tensorr]   __classcell__r9   r9   rM   r:   r;   L   s    r;   c                       s2   e Zd Z fddZdejdejfddZ  ZS )DiaMLPc                    sP   t    || _tj|jd|j dd| _tj|j|jdd| _t	|j
 | _d S )NrR   Fbias)rA   rB   r(   r   LinearrF   intermediate_sizegate_up_proj	down_projr   
hidden_actactivation_fnrL   r(   rM   r9   r:   rB   i   s
   
zDiaMLP.__init__hidden_statesrP   c                 C   s4   |  |}|jddd\}}|| | }| |S )NrR   rQ   rS   )rf   chunkri   rg   )rL   rk   	up_statesgater9   r9   r:   r]   q   s   

zDiaMLP.forward)r-   r.   r/   rB   rH   FloatTensorr]   r`   r9   r9   rM   r:   ra   h   s    ra   RMSNormc                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	
DiaRMSNormư>c                    s&   t    tt|| _|| _dS )z9
        DiaRMSNorm is equivalent to T5LayerNorm
        N)rA   rB   r   	ParameterrH   onesweightvariance_epsilon)rL   rF   epsrM   r9   r:   rB   |   s   

zDiaRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )NrR   rQ   T)keepdim)	r=   rU   rH   float32powmeanrsqrtrv   ru   )rL   rk   input_dtypevariancer9   r9   r:   r]      s
   zDiaRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupleru   rY   rv   rL   r9   r9   r:   
extra_repr   s   zDiaRMSNorm.extra_repr)rr   )r-   r.   r/   rB   r]   r   r`   r9   r9   rM   r:   rq   z   s    rq   c                       sD   e Zd ZU ejed< ddef fddZe e	dd Z
  ZS )	DiaRotaryEmbeddinginv_freqNr(   c                    s   t    t|drt|jt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defaultr   Fr?   )rA   rB   hasattr
isinstancer   dictgetr   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr(   r   rope_init_fnattention_scalingrK   r   original_inv_freq)rL   r(   rV   r   rM   r9   r:   rB      s   
zDiaRotaryEmbedding.__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   rQ   r!   mpscpuF)device_typeenabledrR   rS   r<   )r   floatexpandrY   rU   rV   r   r   strrH   autocast	transposecatcosr   sinr=   )
rL   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   r9   r9   r:   r]      s   0&zDiaRotaryEmbedding.forwardN)r-   r.   r/   rH   r_   r0   r"   rB   no_gradr   r]   r`   r9   r9   rM   r:   r      s   
 
r   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..NrQ   rR   rS   )rY   rH   r   )r   x1x2r9   r9   r:   rotate_half   s   r   c                 C   sD   | |}| |}| | t| |  }|| t||  }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezer   )qkr   r   r   unsqueeze_dimq_embedk_embedr9   r9   r:   apply_rotary_pos_emb   s
   

r   rk   n_reprP   c                 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)rY   r   reshape)rk   r   batchnum_key_value_headsslenhead_dimr9   r9   r:   	repeat_kv   s
   0r           modulequerykeyvalueattention_maskscalingdropoutkwargsc                 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 )NrR   r   rQ   )rT   r=   )ptrainingr!   )r   num_key_value_groupsrH   matmulr   rY   r   
functionalsoftmaxry   rU   r=   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightscausal_maskattn_outputr9   r9   r:   eager_attention_forward   s   
&r   c                       s   e Zd ZdZddeeef dedef fddZ	e
dd	d
d		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jf fddZ  ZS )DiaSelfAttention=Multi-headed attention from 'Attention Is All You Need' paperFr(   	layer_idx	is_causalc                    s   t    || _|| _|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 )Nr   r!   r   Frb   )rA   rB   r(   r   rF   num_attention_heads	num_headsr   r   getattrr   r   attention_dropoutr   r   rd   q_projk_projv_projo_proj)rL   r(   r   r   rM   r9   r:   rB      s   

 zDiaSelfAttention.__init__past_key_valuepast_key_valuesz4.58)new_nameversionNrk   position_embeddingsr   cache_positionr   rP   c                 K   s$  |j d d }g |d| jR }| ||dd}	| ||dd}
| ||dd}|\}}t|	|
||\}	}
|d urW|||d}||
|| j	|\}
}t
}| jjdkret| jj }|| |	|
||f| jsqdn| j| jd|\}}|jg |dR   }| |}||fS )NrQ   r!   rR   )r   r   r   eagerr   )r   r   )rY   r   r   rX   r   r   r   r   updater   r   r(   _attn_implementationr   r   r   r   r   r   r   )rL   rk   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   r   r   cache_kwargsattention_interfacer   r   r9   r9   r:   r]     s8   


zDiaSelfAttention.forward)FNN)r-   r.   r/   r^   r   r$   r#   intboolrB   r    rH   r_   r   r   r   
LongTensorr   r   r]   r`   r9   r9   rM   r:   r      s*    $r   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 )DiaCrossAttentionr   r(   r   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!   r   Frb   )rA   rB   r(   r   rF   cross_hidden_sizecross_num_attention_headsr   cross_num_key_value_headsr   r   cross_head_dimr   r   r   r   r   rd   r   r   r   r   rL   r(   r   rM   r9   r:   rB   @  s    


 zDiaCrossAttention.__init__Nrk   cross_attention_statesr   r   r   rP   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 )NrQ   r!   rR   FTr   r   )rY   r   r   rX   r   
is_updatedr   r   cross_attention_cachelayerskeysvaluesr   r   r   r   r(   r   r   r   r   r   r   )rL   rk   r   r   r   r   r   r   cross_shaper   r   r   r   r   r   r   r9   r9   r:   r]   S  sD   


zDiaCrossAttention.forwardr   )r-   r.   r/   r^   r#   r   rB   rH   r_   r   r
   r   r   r   r]   r`   r9   r9   rM   r:   r   =  s$    r   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(   r   c                    sL   t    t|j|jd| _t||dd| _t|j|jd| _t	|| _
d S )Nrw   Fr   )rA   rB   rq   rF   norm_epspre_sa_normr   self_attentionpost_sa_normra   mlpr   rM   r9   r:   rB     s
   
zDiaEncoderLayer.__init__Nrk   r   r   r   rP   c           
      K   sZ   |}|  |}| j|f||d|\}}|| }|}| |}| |}	||	 }||fS )Nr   r   )r   r   r   r   )
rL   rk   r   r   r   residualnormed_statesself_attn_outputself_attn_weightsmlp_outr9   r9   r:   r]     s    



zDiaEncoderLayer.forwardr   )r-   r.   r/   r$   r   rB   rH   r_   r   r   r   r   r]   r`   r9   r9   rM   r:   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 r9   )r+   .0r   r(   r9   r:   
<listcomp>      z'DiaEncoder.__init__.<locals>.<listcomp>r   )rA   rB   r(   r   rC   rD   rF   	embedding
ModuleListrangenum_hidden_layersr   rq   r   normr   rotary_embeddingsrj   rM   r
  r:   rB     s   zDiaEncoder.__init__NFr*   r   output_attentionsoutput_hidden_statesr   rP   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 )NrQ   rV   r9   r   r   r!   last_hidden_staterk   
attentions)
r  rH   rI   rY   rV   r  _update_full_maskr   r  r   )rL   r*   r   r  r  r   rk   r   r   encoder_statesall_attentionsencoder_layerlayer_outputsr9   r9   r:   r]     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=   r   rH   r_   r&   r   )rL   r   r  r9   r9   r:   r    s   zDiaEncoder._update_full_mask)NFF)r-   r.   r/   r$   rB   r   r   rH   r_   r   r   r   r   r   r   r   r]   r  r`   r9   r9   rM   r:   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(   r   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   )rA   rB   rF   	embed_dimr   r   r   cross_attentionrq   r   r   pre_ca_normpre_mlp_normra   r   r   rM   r9   r:   rB     s   
zDiaDecoderLayer.__init__Nrk   r   r   encoder_hidden_statesencoder_attention_maskr   r   rP   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   )rL   rk   r   r   r'  r(  r   r   r   self_attn_cacher  r  r  r  cross_statescross_attn_weightsr  r9   r9   r:   r]   	  sB   








zDiaDecoderLayer.forward)NNNNNN)r-   r.   r/   r#   r   rB   rH   r_   r   r   r
   r   r]   r`   r9   r9   rM   r:   r,     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  r9   )r,   r  r
  r9   r:   r  C  r  z'DiaDecoder.__init__.<locals>.<listcomp>r   )rA   rB   rE   rD   r;   
embeddingsr   r  r   r  r  r  r   rq   rF   r   r  rj   rM   r
  r:   rB   <  s   

zDiaDecoder.__init__NFr*   r   r   r'  r(  r   r  r  r   rP   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)
        NrQ   r   r  )r(   input_embedsr   r   r   r   rR   r9   )r(  r   r   r!   )r  r   rk   r  cross_attentions)sizeget_seq_lengthrH   rI   rV   r.  r  r   rt   r   r(   _update_cross_attn_maskrY   r   r  r   )rL   r*   r   r   r'  r(  r   r  r  r   r   
batch_size
seq_lengthpast_key_values_lengthrk   r   mask_seq_lengthall_hidden_statesall_self_attnsall_cross_attentionslayerr  r9   r9   r:   r]   G  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   rQ   )tgt_lenr!  F)query_lengthr   r"  )rL   r'  r(  r   r  r9   r9   r:   r3    s2   z"DiaDecoder._update_cross_attn_mask)NNNNNFFN)r-   r.   r/   r^   r#   rB   r   r   rH   r_   r   r   ro   r
   r   r   r   r   r]   Sizer3  r`   r9   r9   rM   r:   r-  9  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 r   )
rA   rB   r(   r  encoder_configencoderr-  decoder_configdecoder	post_initrj   rM   r9   r:   rB     s
   zDiaModel.__init__c                 C   s   | j S r   )rB  r   r9   r9   r:   get_encoder  s   zDiaModel.get_encoderNr*   r   decoder_input_idsdecoder_position_idsdecoder_attention_maskencoder_outputsr   	use_cacher  r  r   rP   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!   rR   r  rQ   )r1  
fill_valuerV   )
r*   r   r   r'  r(  r   r  r  rK  r   )r  r   decoder_hidden_statesdecoder_attentionsr0  encoder_last_hidden_stater'  encoder_attentionsr9   ) 
ValueErrorr(   r  r  rK  is_gradient_checkpointingr   loggerwarning_oncer
   r	   rB  r   r   lenrY   rC  rE   rH   fullbos_token_idrV   ndimr   r   rD  r   r  r   rk   r  r0  )rL   r*   r   rG  rH  rI  rJ  r   rK  r  r  r   r   bszseq_lenchannelsdecoder_outputsr9   r9   r:   r]     s|   '
 
zDiaModel.forward)NNNNNNNNNNN)r-   r.   r/   r"   rB   rF  r   r   r   rH   r   r   r   r   r
   r   r   r]   r`   r9   r9   rM   r:   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 )NFrb   ForMaskedLM)rA   rB   r(   r@  r)   rC  rE   rD   r   rd   rF   logits_dense	loss_typerE  rj   rM   r9   r:   rB   R  s   


z$DiaForConditionalGeneration.__init__c                 C   
   | j  S r   )r)   rF  r   r9   r9   r:   rF  a     
z'DiaForConditionalGeneration.get_encoderc                 C   ra  r   )r)   get_decoderr   r9   r9   r:   rc  d  rb  z'DiaForConditionalGeneration.get_decoderNr*   r   rG  rH  rI  rJ  r   rK  r  r  labelsr   rP   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   rG  rH  rI  rJ  r   rK  r  r  r   r   rQ   r!   rR   N)logitsrd  rD   )	lossre  r   rM  rN  r0  rO  r'  rP  r9   )r)   rY   r_  rX   rE   rD   r   r   loss_functionr   r   rM  rN  r0  rO  r'  rP  )rL   r*   r   rG  rH  rI  rJ  r   rK  r  r  rd  r   r   outputsr  r4  audio_logitsrf  r9   r9   r:   r]   g  sJ   ,
z#DiaForConditionalGeneration.forward)NNNNNNNNNNNN)r-   r.   r/   r1   r"   rB   rF  rc  r   r   r   rH   r   r   r   r   r
   r   r   r]   r`   r9   r9   rM   r:   r]  J  s\    	

r]  )r@  r'   r]  )Nr!   )r   )Ntypingr   r   r   rH   r   activationsr   cache_utilsr   r	   r
   integrationsr   masking_utilsr   modeling_attn_mask_utilsr   r   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   r   utils.deprecationr    configuration_diar"   r#   r$   generation_diar%   integrations.flex_attentionr&   
get_loggerr-   rS  r'   Moduler;   ra   rq   r   r   r   r_   r   r   r   r   r   r   r+   r  r,   r-  r@  r]  __all__r9   r9   r9   r:   <module>   s    
$

BJ!V; {o