
    Z j                     V   S SK Jr  S SKJr  S SKrS SKJr  SSKJr  SSK	J
r
  SSKJrJrJr  SS	KJrJrJr  SS
KJrJr  SSKJr  SSKJr  SSKJrJrJrJr  SSKJ r J!r!  SSK"J#r#J$r$  SSK%J&r&  SSK'J(r(J)r)J*r*J+r+J,r,  SSK-J.r.J/r/  SSK0J1r1  SSK2J3r3J4r4J5r5  SSK6J7r7  \,Rp                  " \95      r:\) " S S\$5      5       r; " S S\Rx                  5      r= " S S\Rx                  5      r>\" S5       " S S\Rx                  5      5       r? " S  S!\Rx                  5      r@S" rA\" S#5      SFS$ j5       rBS%\R                  S&\DS'\R                  4S( jrE SGS)\Rx                  S*\R                  S+\R                  S,\R                  S-\R                  S-  S.\FS/\FS0\&\(   4S1 jjrG\" \B5       " S2 S3\Rx                  5      5       rH " S4 S5\Rx                  5      rI " S6 S7\5      rJ " S8 S9\;5      rK " S: S;\5      rL " S< S=\;5      rM\)" S>S?9 " S@ SA\;5      5       rN\)" SBS?9 " SC SD\;\75      5       rO/ SEQrPg)H    )Callable)OptionalN)nn   )initialization)ACT2FN)CacheDynamicCacheEncoderDecoderCache)use_kernel_forward_from_hubuse_kernel_func_from_hubuse_kernelized_func)create_bidirectional_maskcreate_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tupleis_torchdynamo_compilinglogging)maybe_autocastmerge_with_config_defaults)capture_outputs   )	DiaConfigDiaDecoderConfigDiaEncoderConfig)DiaGenerationMixinc                   X   ^  \ rS rSr% \\S'   SrSrSrSr	Sr
SrSrSS/rU 4S jrS	rU =r$ )
DiaPreTrainedModel5   configmodelT	input_idsDiaEncoderLayerDiaDecoderLayerc                 .  > [         TU ]  U5        [        U[        5      (       ap  [        R
                  " U R                  R                  [        R                  S9U R                  R                  -  n[        R                  " UR                  U5        g g )Ndtype)super_init_weights
isinstanceDiaMultiChannelEmbeddingtorcharanger,   num_channelslong
vocab_sizeinitcopy_offsets)selfmoduler?   	__class__s      u/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/transformers/models/dia/modeling_dia.pyr5    DiaPreTrainedModel._init_weightsA   se    f%f677ll4;;#;#;5::NQUQ\Q\QgQggGJJv~~w/ 8     )__name__
__module____qualname____firstlineno__r%   __annotations__base_model_prefixsupports_gradient_checkpointing_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraphmain_input_name_no_split_modulesr5   __static_attributes____classcell__rB   s   @rC   r*   r*   5   sG    &*#N!!O*,=>0 0rE   r*   c                   n   ^  \ rS rSrSrS\4U 4S jjrS\R                  S\R                  4S jr	Sr
U =r$ )	r7   H   a  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                 v  > [         TU ]  5         [        R                  " UR                  UR
                  -  UR                  5      U l        UR                  U l        UR
                  U l        [        R                  " UR
                  [        R                  S9UR                  -  nU R                  SUSS9  g )Nr2   r?   F
persistent)r4   __init__r   	Embeddingr<   r:   hidden_sizeembedr8   r9   r;   register_buffer)r@   r,   r?   rB   s      rC   r\   !DiaMultiChannelEmbedding.__init__V   s    \\&"3"3f6I6I"I6K]K]^
!--"//,,v22%**EHYHYYYEBrE   audio_codesreturnc                    XR                   R                  UR                  5      -   R                  S5      nU R	                  U5      R                  UR                  S   UR                  S   SU R                  5      nUR                  SS9$ )Nr$   r      dim)	r?   todevicesqueezer_   viewshaper^   sum)r@   rb   tokensembedss       rC   forward DiaMultiChannelEmbedding.forward^   ss    0B0B CCLLQOF#((a+:K:KA:NPRTXTdTdezzaz  rE   )r_   r^   r:   )rG   rH   rI   rJ   __doc__r&   r\   r8   Tensorrq   rT   rU   rV   s   @rC   r7   r7   H   s7    C/ C!5<< !ELL ! !rE   r7   c                   b   ^  \ rS rSrU 4S jrS\R                  S\R                  4S jrSrU =r	$ )DiaMLPd   c                    > [         TU ]  5         Xl        [        R                  " UR
                  SUR                  -  SS9U l        [        R                  " UR                  UR
                  SS9U l        [        UR                     U l        g )Nrf   Fbias)r4   r\   r,   r   Linearr^   intermediate_sizegate_up_proj	down_projr   
hidden_actactivation_fnr@   r,   rB   s     rC   r\   DiaMLP.__init__e   sn    IIf&8&8!f>V>V:V]bc6#;#;V=O=OV[\#F$5$56rE   hidden_statesrc   c                     U R                  U5      nUR                  SSS9u  p2X R                  U5      -  nU R                  U5      $ )Nrf   re   rg   )r}   chunkr   r~   )r@   r   	up_statesgates       rC   rq   DiaMLP.forwardm   sH    %%m4	#//!/4 2 24 88	~~i((rE   )r   r,   r~   r}   )
rG   rH   rI   rJ   r\   r8   FloatTensorrq   rT   rU   rV   s   @rC   rv   rv   d   s,    7)U%6%6 )5;L;L ) )rE   rv   RMSNormc                   x   ^  \ rS rSrS
S\SS4U 4S jjjrS\R                  S\R                  4S jrS r	S	r
U =r$ )
DiaRMSNormv   epsrc   Nc                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z)
DiaRMSNorm is equivalent to T5LayerNorm
N)r4   r\   r   	Parameterr8   onesweightvariance_epsilon)r@   r^   r   rB   s      rC   r\   DiaRMSNorm.__init__x   s/     	ll5::k#:; #rE   r   c                    UR                   nUR                  [        R                  5      nUR	                  S5      R                  SSS9nU[        R                  " X0R                  -   5      -  nU R                  UR                  U5      -  $ )Nrf   re   T)keepdim)	r3   ri   r8   float32powmeanrsqrtr   r   )r@   r   input_dtypevariances       rC   rq   DiaRMSNorm.forward   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::rE   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)tupler   rm   r   )r@   s    rC   
extra_reprDiaRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIrE   )r   r   )gư>)rG   rH   rI   rJ   floatr\   r8   rt   rq   r   rT   rU   rV   s   @rC   r   r   v   sB    $ $$ $ $;U\\ ;ell ;J JrE   r   c                      ^  \ rS rSr% \R
                  \S'   SS\4U 4S jjjr\	   SS\S-  S\
S   S\S-  S	\S
\4   4S jj5       r\R                  " 5       \S 5       5       rSrU =r$ )DiaRotaryEmbedding   inv_freqNr,   c                   > [         TU ]  5         UR                  U l        UR                  U l        Xl        U R
                  R                  S   U l        U R                  nU R                  S:w  a  [        U R                     nU" U R
                  U5      u  o@l
        U R                  SUSS9  U R                  SUR                  5       SS9  g )N	rope_typedefaultr   FrZ   original_inv_freq)r4   r\   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr,   rope_parametersr   compute_default_rope_parametersr   attention_scalingr`   clone)r@   r,   rj   rope_init_fnr   rB   s        rC   r\   DiaRotaryEmbedding.__init__   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L((ZeD0(..2BuUrE   rj   ztorch.deviceseq_lenrc   ztorch.Tensorc           	         U R                   S   n[        U SS5      =(       d    U R                  U R                  -  nSnSU[        R
                  " SUS[        R                  S9R                  U[        R                  S9U-  -  -  nXe4$ )	aH  
Computes the inverse frequencies according to the original RoPE implementation
Args:
    config ([`~transformers.PreTrainedConfig`]):
        The model configuration.
    device (`torch.device`):
        The device to use for initialization of the inverse frequencies.
    seq_len (`int`, *optional*):
        The current sequence length. Unused for this type of RoPE.
Returns:
    Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
    post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).

rope_thetahead_dimNg      ?r   rf   r2   )rj   r3   )	r   getattrr^   num_attention_headsr8   r9   int64ri   r   )r,   rj   r   baserh   attention_factorr   s          rC   r   2DiaRotaryEmbedding.compute_default_rope_parameters   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 ))rE   c                 L   U R                   S S S 2S 4   R                  5       R                  UR                  S   SS5      R	                  UR
                  5      nUS S 2S S S 24   R                  5       n[        UR
                  R                  [        5      (       a0  UR
                  R                  S:w  a  UR
                  R                  OSn[        USS9   UR                  5       UR                  5       -  R                  SS5      n[        R                  " Xf4SS	9nUR                  5       U R                  -  nUR                  5       U R                  -  n	S S S 5        WR	                  UR                   S
9W	R	                  UR                   S
94$ ! , (       d  f       N@= f)Nr   re   r$   mpscpuF)device_typeenabledrf   rg   r2   )r   r   expandrm   ri   rj   r6   typestrr!   	transposer8   catcosr   sinr3   )
r@   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             rC   rq   DiaRotaryEmbedding.forward   sN    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E'E!((--[`J`ahhmmfkUC&,,.1F1L1L1NNYYZ[]^_E))UN3C'')d444C'')d444C	 D vvAGGv$cff177f&;;; DCs   BF
F#)r   r,   r   r   r   NNNN)rG   rH   rI   rJ   r8   rt   rK   r%   r\   staticmethodr   intr   r   r   no_gradr   rq   rT   rU   rV   s   @rC   r   r      s    llVy V V  #'+/"*D *(* t* 
~u$	%	* *: ]]_<  <rE   r   c                     U SSU R                   S   S-  24   nU SU R                   S   S-  S24   n[        R                  " U* U4SS9$ )z*Rotates half the hidden dims of the input..Nre   rf   rg   )rm   r8   r   )r   x1x2s      rC   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''rE   rotary_pos_embc                     UR                  U5      nUR                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nXV4$ )aI  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.
    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   unsqueeze_dimq_embedk_embeds          rC   apply_rotary_pos_embr      sS    & --
&C
--
&Cw;q>C/0Gw;q>C/0GrE   r   n_reprc   c                     U R                   u  p#pEUS:X  a  U $ U SS2SS2SSS2SS24   R                  X#XU5      n U R                  X#U-  XE5      $ )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)rm   r   reshape)r   r   batchnum_key_value_headsslenr   s         rC   	repeat_kvr      s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTrE   rA   querykeyvalueattention_maskscalingdropoutkwargsc                    [        X R                  5      n[        X0R                  5      n	[        R                  " XR	                  SS5      5      U-  n
Ub  X-   n
[
        R                  R                  U
S[        R                  S9R                  UR                  5      n
[
        R                  R                  XU R                  S9n
[        R                  " X5      nUR	                  SS5      R                  5       nX4$ )Nrf   r   re   )rh   r3   )ptrainingr$   )r   num_key_value_groupsr8   matmulr   r   
functionalsoftmaxr   ri   r3   r   r   
contiguous)rA   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               rC   eager_attention_forwardr      s     3 ; ;<JU$?$?@L<<';';Aq'ABWLL!#4==((2U]](SVVW\WbWbcL==((6??([L,,|:K''1-88:K$$rE   c                     ^  \ rS rSrSrSS\\-  S\S\4U 4S jjjr	   SS\
R                  S	\\
R                  \
R                  4   S-  S
\
R                  S-  S\S-  S\\   S\\
R                  \
R                  4   4S jjrSrU =r$ )DiaSelfAttentioni  =Multi-headed attention from 'Attention Is All You Need' paperr,   	layer_idx	is_causalc                   > [         TU ]  5         Xl        X l        UR                  U l        U R                  R
                  U l        U R                  R                  =(       d    U R                  U l        U R                  U R                  -  U l        [        USUR                  U R                  -  5      U l
        SU l        SU l        X0l        [        R                  " U R                  U R                  U R                  -  SS9U l        [        R                  " U R                  U R                  U R                  -  SS9U l        [        R                  " U R                  U R                  U R                  -  SS9U l        [        R                  " U R                  U R                  -  U R                  SS9U l        g )Nr   r$           Fry   )r4   r\   r,   r  r^   r   	num_headsr   r   r   r   r   attention_dropoutr  r   r{   q_projk_projv_projo_proj)r@   r,   r  r  rB   s       rC   r\   DiaSelfAttention.__init__  s@   "!--88#';;#B#B#Tdnn $(NNd6N6N$N!
F4F4F$..4XY!$"ii 0 0$..4==2PW\]ii 0 0$2J2JT]]2Zafgii 0 0$2J2JT]]2Zafgii >@P@PW\]rE   Nr   position_embeddingsr   past_key_valuesr   rc   c                    UR                   S S n/ UQSPU R                  P7nU R                  U5      R                  U5      R	                  SS5      nU R                  U5      R                  U5      R	                  SS5      n	U R                  U5      R                  U5      R	                  SS5      n
Uu  p[        XX5      u  pUb  UR                  XU R                  5      u  p[        R                  " U R                  R                  [        5      nU" U UU	U
U4U R                  (       d  SOU R                   U R"                  S.UD6u  pUR$                  " / UQSP76 R'                  5       nU R)                  U5      nX4$ )Nre   r$   rf   r  )r   r   )rm   r   r  rl   r   r  r	  r   updater  r   get_interfacer,   _attn_implementationr   r   r  r   r   r   r
  )r@   r   r  r   r  r   input_shapehidden_shapequery_statesr   r   r   r   attention_interfacer   r   s                   rC   rq   DiaSelfAttention.forward(  s~    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&#7RU#[ &'6'='=jX\XfXf'g$J(?(M(MKK,,.E)
 %8	%
  $}}C$2H2HLL	%
 	%
! "));;;;FFHkk+.((rE   )r  r,   r   r^   r  r  r  r  r   r   r
  r  r   r	  )Fr   )rG   rH   rI   rJ   rs   r'   r&   r   boolr\   r8   rt   r   r	   r   r   rq   rT   rU   rV   s   @rC   r   r     s    G^/2BB ^s ^_c ^ ^* IM.2(,&)||&) #5<<#=>E&) t+	&)
 &) +,&) 
u||U\\)	*&) &)rE   r   c                      ^  \ rS rSrSrS\S\4U 4S jjr  SS\R                  S\R                  S	\R                  S-  S
\
S-  S\\   S\\R                  \R                  S-  4   4S jjrSrU =r$ )DiaCrossAttentioniQ  r   r,   r  c                 R  > [         TU ]  5         Xl        X l        UR                  U l        UR
                  U l        U R                  R                  U l        U R                  R                  U l	        U R                  U R                  -  U l
        UR                  U l        SU l        SU l        SU l        [         R"                  " U R                  U R                  U R                  -  SS9U l        [         R"                  " U R
                  U R                  U R                  -  SS9U l        [         R"                  " U R
                  U R                  U R                  -  SS9U l        [         R"                  " U R                  U R                  -  U R                  SS9U l        g )Nr$   r  Fry   )r4   r\   r,   r  r^   cross_hidden_sizecross_num_attention_headsr  cross_num_key_value_headsr   r   cross_head_dimr   r   r  r  r   r{   r  r  r	  r
  r@   r,   r  rB   s      rC   r\   DiaCrossAttention.__init__T  s;   "!--!'!9!9>>#';;#H#H $(NNd6N6N$N!--!$ii 0 0$..4==2PW\]ii 6 68P8PSWS`S`8`glmii 6 68P8PSWS`S`8`glmii >@P@PW\]rE   Nr   cross_attention_statesr   r  r   rc   c                 R   UR                   S S n/ UQSPU R                  P7n/ UR                   S S QSPU R                  P7nU R                  U5      R                  U5      R	                  SS5      n	Ub%  UR
                  R                  U R                  5      OSn
Ubb  U
(       a[  UR                  R                  U R                     R                  nUR                  R                  U R                     R                  nOU R                  U5      R                  U5      R	                  SS5      nU R                  U5      R                  U5      R	                  SS5      nUbB  UR                  R                  UUU R                  5      u  pSUR
                  U R                  '   [        R                   " U R"                  R$                  [&        5      nU" U U	UUU4SU R(                  0UD6u  pUR+                  / UQSP75      R-                  5       nU R/                  U5      nX4$ )Nre   r$   rf   FTr   )rm   r   r  rl   r   
is_updatedgetr  cross_attention_cachelayerskeysvaluesr  r	  r  r   r  r,   r  r   r   r   r   r
  )r@   r   r!  r   r  r   r  r  cross_shaper  r#  r   r   r  r   r   s                   rC   rq   DiaCrossAttention.forwardg  s    $))#2.88b8$--8M.44Sb9M2Mt}}M{{=166|DNNqRSTGVGb_//33DNNChm
&:(>>EEdnnUZZJ*@@GGW^^L%;<AA+NXXYZ\]^J;;'=>CCKPZZ[\^_`L*+:+P+P+W+W NN,(
 >B**4>>:(?(M(MKK,,.E)
 %8%
 LL%
 %
! "))*<K*<*<=HHJkk+.((rE   )r  r,   r  r   r^   r  r  r  r  r   r   r
  r  r   r	  NN)rG   rH   rI   rJ   rs   r&   r   r\   r8   rt   r   r   r   r   rq   rT   rU   rV   s   @rC   r  r  Q  s    G^/ ^C ^. /36:1)||1) !&1) t+	1)
 -t31) -.1) 
u||U\\D00	11) 1)rE   r  c                      ^  \ rS rSrS\S\4U 4S jjr  SS\R                  S\	\R                  \R                  4   S-  S\R                  S-  S	\
\   S
\	\R                  \R                  S-  4   4
S jjrSrU =r$ )r/   i  r,   r  c                    > [         TU ]  5         [        UR                  UR                  S9U l        [        XSS9U l        [        UR                  UR                  S9U l        [        U5      U l
        g )Nr   Fr  )r4   r\   r   r^   norm_epspre_sa_normr   self_attentionpost_sa_normrv   mlpr  s      rC   r\   DiaEncoderLayer.__init__  sZ    %f&8&8fooN.vER&v'9'9vO&>rE   Nr   r  r   r   rc   c                     UnU R                  U5      nU R                  " U4UUS.UD6u  pxXW-   nUnU R                  U5      nU R                  U5      n	XY-   nU$ )N)r  r   )r1  r2  r3  r4  )
r@   r   r  r   r   residualnormed_statesself_attn_output_mlp_outs
             rC   rq   DiaEncoderLayer.forward  s     !((7"11
 3)
 	
 !3 ))-8((=) *rE   )r4  r3  r1  r2  r+  )rG   rH   rI   rJ   r'   r   r\   r8   rt   r   r   r   rq   rT   rU   rV   s   @rC   r/   r/     s    "/ "C " IM.2	|| #5<<#=>E t+	
 -. 
u||U\\D00	1 rE   r/   c                      ^  \ rS rSr\\S.rS\4U 4S jjr\	\
\ SS\R                  S\R                  S-  S\\   S	\4S
 jj5       5       5       rSrU =r$ )
DiaEncoderi  r   
attentionsr,   c           	        > [         TU ]  U5        Xl        [        R                  " UR
                  UR                  5      U l        [        R                  " [        UR                  5       Vs/ s H  n[        X5      PM     sn5      U l        [        UR                  UR                  S9U l        [!        US9U l        U R%                  5         g s  snf Nr.  r,   )r4   r\   r,   r   r]   r<   r^   	embedding
ModuleListrangenum_hidden_layersr/   r&  r   r0  normr   
rotary_emb	post_initr  s      rC   r\   DiaEncoder.__init__  s     f&7&79K9KLmmAFvG_G_A`aA`I_V/A`a
 v11vG	,F; bs   .CNr.   r   r   rc   c                 F   U R                  U5      n[        R                  " UR                  S   UR                  S9S S S 24   n[        U R                  UUS9nU R                  XES9nU R                   H  nU" U4UUUS.UD6nM     U R                  U5      n[        US9$ )Nre   rj   )r,   inputs_embedsr   r   )r   r   r  )last_hidden_state)rD  r8   r9   rm   rj   r   r,   rI  r&  rH  r   )r@   r.   r   r   r   r   r  encoder_layers           rC   rq   DiaEncoder.forward  s     y1
 ||IOOB$7	@P@PQRVXYRYZ2;;')

 #oomoW![[M)-)$7	
 M ) 		-0??rE   )r,   rD  r&  rH  rI  r   )rG   rH   rI   rJ   r/   r   _can_record_outputsr'   r\   r"   r#   r   r8   rt   r   r   r   rq   rT   rU   rV   s   @rC   r>  r>    s    (&
/    /3@<<@ t+@ +,	@
 
@    @rE   r>  c                   \  ^  \ rS rSrS\S\4U 4S jjr     SS\R                  S\	\R                  \R                  4   S-  S\R                  S-  S	\R                  S-  S
\R                  S-  S\
S-  S\	\R                  \R                  S-  \R                  S-  4   4S jjrSrU =r$ )r0   i  r,   r  c                 t  > [         TU ]  5         UR                  U l        [	        XSS9U l        [        X5      U l        [        UR                  UR                  S9U l
        [        UR                  UR                  S9U l        [        UR                  UR                  S9U l        [        U5      U l        g )NTr/  r.  )r4   r\   r^   	embed_dimr   r2  r  cross_attentionr   r0  r1  pre_ca_normpre_mlp_normrv   r4  r  s      rC   r\   DiaDecoderLayer.__init__  s    ++.vDQ0C%f&8&8fooN%f&8&8fooN&v'9'9vO&>rE   Nr   r  r   encoder_hidden_statesencoder_attention_maskr  rc   c                 Z   Un[        U[        5      (       a  UR                  nUn	U R                  U5      n
U R                  " U
UUU40 UD6u  pX-   nUn	U R                  U5      n
U R                  " U
U4UUS.UD6u  pX-   nUn	U R                  U5      n
U R                  U
5      nX-   nU$ )N)r   r  )	r6   r   self_attention_cacher1  r2  rX  rW  rY  r4  )r@   r   r  r   r[  r\  r  r   self_attn_cacher7  r8  r9  r:  cross_statesr;  s                  rC   rq   DiaDecoderLayer.forward  s     *o':;;-BBO ((7"11 
 
 !3 ((7..!
 2+	

 
 !/ ))-8((=) *rE   )rW  rV  r4  rX  rY  r1  r2  NNNNN)rG   rH   rI   rJ   r&   r   r\   r8   rt   r   r   rq   rT   rU   rV   s   @rC   r0   r0     s    "/ "C " IM.2596:6:+||+ #5<<#=>E+ t+	+
  %||d2+ !&t 3+ -t3+ 
u||U\\D0%,,2EE	F+ +rE   r0   c                   &  ^  \ rS rSrSr\\\/S.rS\	4U 4S jjr
\\\     SS\R                  S\R                   S-  S	\R                  S-  S
\R"                  S-  S\R                   S-  S\S-  S\\   S\\-  4S jj5       5       5       rSrU =r$ )
DiaDecoderi-  z-Transformer Decoder Stack using DenseGeneral.r?  r,   c           	        > [         TU ]  U5        UR                  U l        UR                  U l        [	        U5      U l        [        R                  " [        UR                  5       Vs/ s H  n[        X5      PM     sn5      U l        [        UR                  UR                  S9U l        [!        US9U l        U R%                  5         g s  snf rB  )r4   r\   r:   r<   r7   
embeddingsr   rE  rF  rG  r0   r&  r   r^   r0  rH  r   rI  rJ  r  s      rC   r\   DiaDecoder.__init__5  s     "// ++26:mmAFvG_G_A`aA`I_V/A`a
 v11vG	,F; bs   *CNr.   r   r   r[  r\  r  r   rc   c                 >   UR                  5       SS u  pUb  UR                  5       OSn
Uc2  [        R                  " XR                  S9U
-   nUR                  S5      nU R                  U5      nUc2  [        5       (       d#  X-   n[        R                  " XUR                  S9n[        U R                  UUUS9n[        U R                  UUUS9nU R                  XS9nU R                   H  nU" UUUU4UUUS.UD6nM     U R                  U5      n[        UUS	9$ )
z
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)
Nre   r   rM  )r,   rN  r   r  )r,   rN  r   r[  rO  )r\  r  r   )rP  r  )sizeget_seq_lengthr8   r9   rj   r   rf  r   r   r   r,   r   rI  r&  rH  r   )r@   r.   r   r   r[  r\  r  r   
batch_size
seq_lengthpast_key_values_lengthr   mask_seq_lengthr  layers                  rC   rq   DiaDecoder.forwardB  sK   ( "+!1#2!6
ETE`!?!?!Afg <<
;K;KLOeeL'11!4L 	2!*B*D*D4AO"ZZ
IL\L\]N+;;')+	
 ";;;'1"7	"
 #oomoW[[E! $% (> /) M ! 		-08++
 	
rE   )rf  r&  rH  r:   rI  r<   rb  )rG   rH   rI   rJ   rs   r0   r   r  rS  r&   r\   r"   r#   r   r8   rt   
LongTensorr   r   r   r   r   r   rq   rT   rU   rV   s   @rC   rd  rd  -  s    7 )'):;
/    15.2:>:>6:A
<<A
 &&-A
 t+	A

  %0047A
 !& 0 04 7A
 -t3A
 +,A
 
3U	:A
    A
rE   rd  z[
    The bare Dia model outputting raw hidden-states without any specific head on top.
    )custom_introc                   &  ^  \ rS rSrS\4U 4S jjr\\        SS\R                  S-  S\R                  S-  S\R                  S-  S\R                  S-  S	\R                  S-  S
\
\-  S-  S\S-  S\S-  S\\-  4S jj5       5       rSrU =r$ )DiaModeli  r,   c                    > [         TU ]  U5        Xl        [        UR                  5      U l        [        UR                  5      U l        U R                  5         g r   )
r4   r\   r,   r>  encoder_configencoderrd  decoder_configdecoderrJ  r   s     rC   r\   DiaModel.__init__  sC     !&"7"78!&"7"78rE   Nr.   r   decoder_input_idsdecoder_position_idsdecoder_attention_maskencoder_outputsr  	use_cacherc   c	                    Uc  Uc  [        S5      eU R                  (       a/  U R                  (       a  U(       a  [        R	                  S5        SnU(       a1  Uc.  [        [        U R                  S9[        U R                  S95      nUc  U R                  " SUUS.U	D6nOK[        U[        5      (       d6  [        US   [        U5      S:  a  US   OS[        U5      S	:  a  US	   OSS
9nUS   R                  S   SU R                  R                  R                  pn
UcA  [        R                   " U
SU4U R                  R                  R"                  U R$                  S9nUR&                  S	:X  a"  UR)                  XU5      R+                  SS	5      nU R,                  " SUUUUS   UUUS.U	D6n[/        UR0                  UR2                  UR4                  UR6                  UR8                  US   UR4                  UR6                  S9$ )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`...FrC  )r.   r   r   r$   rf   )rP  r   r@  re   )ri  
fill_valuerj   )r.   r   r   r[  r\  r  r  )rP  r  decoder_hidden_statesdecoder_attentionscross_attentionsencoder_last_hidden_stater[  encoder_attentionsrF   )
ValueErroris_gradient_checkpointingr   loggerwarning_oncer   r
   r,   rw  r6   r   lenrm   rx  r:   r8   fullbos_token_idrj   ndimr   r   ry  r   rP  r  r   r@  r  )r@   r.   r   r{  r|  r}  r~  r  r  r   bszr   channelsdecoder_outputss                 rC   rq   DiaModel.forward  s   H !8j  ))dmm##p "	01,dkk2RT`hlhshsTtuO""ll #- O O_==-"1!"4474H14Loa0RV14_1E1I?1-tO #2!"4":":1"=r4;;C]C]CjCjh$ %

1h'DKK4N4N4[4[dhdodo! !!Q& 1 9 9# Q [ [\]_` a,, 	
'-1"1!"4#1+	
 	
 "-??+;;"1"?"?.99,==&5a&8"1"?"?.99	
 		
rE   )r,   ry  rw  )NNNNNNNN)rG   rH   rI   rJ   r%   r\   r   r   r8   rq  r   r   r   r  r   rq   rT   rU   rV   s   @rC   rt  rt    s    y   .226598<:>:>6:!%]
##d*]
 ((4/]
 !++d2	]

 $..5]
 !& 0 04 7]
 )5047]
 -t3]
 $;]
 
#	#]
  ]
rE   rt  zl
    The Dia model consisting of a (byte) text encoder and audio decoder with a prediction head on top.
    c                   N  ^  \ rS rSrSrSrS\4U 4S jjr\\	         SS\
R                  S-  S\
R                  S-  S	\
R                  S-  S
\
R                  S-  S\
R                  S-  S\\-  S-  S\S-  S\S-  S\
R                  S-  S\\-  4S jj5       5       rSrU =r$ )DiaForConditionalGenerationi  r-   )audior,   c                 v  > [         TU ]  U5        Xl        [        U5      U l        UR
                  R                  U l        UR
                  R                  U l        [        R                  " UR
                  R                  U R                  U R                  -  SS9U l        SU l        U R                  5         g )NFry   ForMaskedLM)r4   r\   r,   rt  r-   rx  r:   r<   r   r{   r^   logits_dense	loss_typerJ  r   s     rC   r\   $DiaForConditionalGeneration.__init__  s     f%
"11>> //::II!!--0A0ADOO0S[`
 ' 	rE   Nr.   r   r{  r|  r}  r~  r  r  labelsrc   c
                 P   U R                   " S	UUUUUUUUS.U
D6nUS   nUR                  S   nU R                  U5      R                  USU R                  U R
                  45      R                  SS5      R                  5       R                  XR                  -  SU R
                  5      nSnU	b  U R                  " S	XU R
                  S.U
D6n[        UUUR                  UR                  UR                  UR                  UR                  UR                  UR                   S9	$ )
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   re   r$   rf   N)logitsr  r<   )	lossr  r  r  r  r  r  r[  r  rF   )r-   rm   r  rl   r:   r<   r   r   loss_functionr   r  r  r  r  r  r[  r  )r@   r.   r   r{  r|  r}  r~  r  r  r  r   outputsrP  rk  audio_logitsr  s                   rC   rq   #DiaForConditionalGeneration.forward  s7   R ** 

)/!5#9++

 

 $AJ&,,Q/
 /0T:r4#4#4dooFGYq!_Z\T*000"dooF 	 %%o\UYUdUdohnoD#33")"?"?&99$55&-&G&G")"?"?&99

 
	
rE   )r,   r  r  r-   r:   r<   )	NNNNNNNNN)rG   rH   rI   rJ   rL   output_modalitiesr%   r\   r   r   r8   rq  r   r   r   r  r   rq   rT   rU   rV   s   @rC   r  r    s     "y   .226598<:>:>6:!%*.L
##d*L
 ((4/L
 !++d2	L

 $..5L
 !& 0 04 7L
 )5047L
 -t3L
 $;L
   4'L
 
	 L
  L
rE   r  )rt  r*   r  )r$   )r  )Qcollections.abcr   typingr   r8   r    r   r=   activationsr   cache_utilsr	   r
   r   integrationsr   r   r   masking_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    utils.genericr!   r"   utils.output_capturingr#   configuration_diar%   r&   r'   generation_diar(   
get_loggerrG   r  r*   Moduler7   rv   r   r   r   r   rt   r   r   r   r   r   r  r/   r>  r0   rd  rt  r  __all__rF   rE   rC   <module>r     sl  * %    & ! C C f f J B 9  L F & l l G 5 L L . 
		H	% 0 0 0$!ryy !8)RYY )$ Y'J J (J(>< ><B( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2 )*;)ryy ;) +;)|G)		 G)T0 B5@# 5@p60 6rY
# Y
x 
g
! g

g
T 
a
"46H a

a
H LrE   