
    UhT                       d dl mZ d dlmZmZmZmZmZ d dlZd dl	m
Z
 ddlmZ ddlmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZ ddlmZmZ ddl m!Z!m"Z" ddl#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2  e*       rd dl3m4Z4 ddl5m6Z6  e+jn                  e8      Z9e G d de'             Z: e(d      e( G d de"                    Z; ed       G d d e
jx                               Z= G d! d"e
jx                        Z> G d# d$e
jx                        Z?d% Z@dHd&ZAd'ej                  d(eCd)ej                  fd*ZD	 dId+e
jx                  d,ej                  d-ej                  d.ej                  d/eej                     d0eEd1eEfd2ZF G d3 d4e
jx                        ZG G d5 d6e      ZHe( G d7 d8e;             ZI G d9 d:e
jx                        ZJ G d; d<ee&      ZK e(d=       G d> d?e;e             ZL G d@ dAe
jx                        ZMe( G dB dCe;             ZN e(dD       G dE dFe;e2             ZOg dGZPy)J    )	dataclass)CallableListOptionalTupleUnionN   )ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hub)AttentionMaskConverter)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)
LossKwargsModelOutputauto_docstringcan_return_tupleis_torch_flex_attn_availablelogging   )	AutoModel   )	CsmConfigCsmDepthDecoderConfig)CsmGenerationMixin)	BlockMask)make_flex_block_causal_maskc                      e Zd ZU dZdZeej                     ed<   dZ	ej                  ed<   dZ
eeeej                           ed<   dZeeej                  df      ed<   dZeeej                  df      ed<   dZeej                     ed	<   dZej                  ed
<   dZeeeej                           ed<   dZeeej                  df      ed<   dZeeej                  df      ed<   dZeej                     ed<   y)CsmOutputWithPastaf  
    Base class for the model autoregressive outputs.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

            Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        depth_decoder_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction) of the depth decoder model.
        depth_decoder_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the depth decoder (scores for each vocabulary token before SoftMax).
        depth_decoder_past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
        depth_decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        depth_decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.
        backbone_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction) of the backbone model.
    Nlosslogitspast_key_values.hidden_states
attentionsdepth_decoder_lossdepth_decoder_logitsdepth_decoder_past_key_valuesdepth_decoder_hidden_statesdepth_decoder_attentionsbackbone_loss)__name__
__module____qualname____doc__r)   r   torchFloatTensor__annotations__r*   r+   r   r,   r-   r.   r/   r0   r1   r2   r3        v/var/www/catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/csm/modeling_csm.pyr(   r(   6   s(   *X )-D(5$$
%, $FE$AEOXeE%*;*;$<=>E=AM8E%"3"3S"89:A:>Ju00#567>6:!2!23:.2%++2OS!8E%8I8I2J,K#LSKO%0A0A30F*G!HOHLhuU->->-C'DEL15M8E--.5r<   r(   z[
    The bare Csm Model outputting raw hidden-states without any specific head on top.
    )custom_introc                   B    e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZdZd Zy)CsmPreTrainedModelmodelTCsmDecoderLayerr+   c                 6   | j                   j                  }t        |t        j                        rY|j
                  j                  j                  d|       |j                  %|j                  j                  j                          y y t        |t        j                        rf|j
                  j                  j                  d|       |j                  2|j
                  j                  |j                     j                          y y t        |t              rJ|j                  }t        |dz
        D ],  }|j
                  j                  |   j                  d|       . y t        |t              r&|j
                  j                  j!                  d       y y )N        )meanstdr!   g      ?)configinitializer_range
isinstancennLinearweightdatanormal_biaszero_	Embeddingpadding_idxCsmCodebooksHeadnum_codebooksrange
CsmRMSNormfill_)selfmodulerF   rT   is        r=   _init_weightsz CsmPreTrainedModel._init_weights   s8   kk++fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . 01"00M=1,- A""1%--3C-@A
+MM$$S) ,r<   N)r4   r5   r6   r"   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_supports_quantized_cache_supports_static_cache_supports_attention_backendr[   r;   r<   r=   r@   r@   q   sQ     L&*#*+#4"5!N ! $!"&*r<   r@   RMSNormc                   ,     e Zd Zd fd	Zd Zd Z xZS )rV   c                     t         |           t        j                  t	        j
                  |            | _        || _        y)z9
        CsmRMSNorm is equivalent to T5LayerNorm
        N)super__init__rJ   	Parameterr8   onesrL   variance_epsilon)rX   hidden_sizeeps	__class__s      r=   rk   zCsmRMSNorm.__init__   s1     	ll5::k#:; #r<   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )Nr   T)keepdim)	dtypetor8   float32powrE   rsqrtrn   rL   )rX   r,   input_dtypevariances       r=   forwardzCsmRMSNorm.forward   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r<   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tuplerL   shapern   rX   s    r=   
extra_reprzCsmRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIr<   )gư>)r4   r5   r6   rk   r|   r   __classcell__rq   s   @r=   rV   rV      s    $;Jr<   rV   c                   ^     e Zd Zddef fdZ ej                         ed               Z xZ	S )CsmRotaryEmbeddingrG   c                    t         |           t        |d      rG|j                  ;|j                  j	                  d|j                  j	                  d            | _        nd| _        |j                  | _        |j                  | _        || _	        t        | j
                     | _        | j                  | j                  |      \  }| _        | j                  d|d       | j                  | _        y )Nrope_scaling	rope_typetypedefaultinv_freqF
persistent)rj   rk   hasattrr   getr   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrG   r   rope_init_fnattention_scalingregister_bufferr   original_inv_freq)rX   rG   devicer   rq   s       r=   rk   zCsmRotaryEmbedding.__init__   s    6>*v/B/B/N#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%r<   c                 b   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        j                  |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   rs   r!   mpscpuF)device_typeenabledr   dim)ru   )r   floatexpandr   rv   r   rI   r   strr8   autocast	transposecatcosr   sinru   )
rX   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             r=   r|   zCsmRotaryEmbedding.forward   sV    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfk^^UC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s    BF%%F.N)
r4   r5   r6   r"   rk   r8   no_gradr   r|   r   r   s   @r=   r   r      s3    /y /" U]]_<  <r<   r   c                   $     e Zd Z fdZd Z xZS )CsmMLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  |j                        | _        t        j                  | j                  | j                  |j                        | _	        t        j                  | j                  | j                  |j                        | _
        t        |j                     | _        y )NrO   )rj   rk   rG   ro   intermediate_sizerJ   rK   mlp_bias	gate_projup_proj	down_projr
   
hidden_actact_fnrX   rG   rq   s     r=   rk   zCsmMLP.__init__   s    !--!'!9!94#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r<   c                     | j                  | j                  | j                  |            | j                  |      z        }|S r   )r   r   r   r   )rX   r   r   s      r=   r|   zCsmMLP.forward   s6    NN4;;t~~a/@#ADLLQRO#ST	r<   r4   r5   r6   rk   r|   r   r   s   @r=   r   r      s    0r<   r   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..Nrs   r   r   )r   r8   r   )r   x1x2s      r=   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r<   c                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||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_embeds           r=   apply_rotary_pos_embr      sY    ( --
&C
--
&C3w;q>C/0G3w;q>C/0GGr<   r,   n_repreturnc                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r!   N)r   r   reshape)r,   r   batchnum_key_value_headsslenhead_dims         r=   	repeat_kvr     so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr<   rY   querykeyvalueattention_maskscalingdropoutc                 T   t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
|#|d d d d d d d |j
                  d   f   }|
|z   }
t        j                  j                  |
dt        j                        j                  |j                        }
t        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr   r	   rs   )r   ru   )ptrainingr!   )r   num_key_value_groupsr8   matmulr   r   rJ   
functionalsoftmaxrw   rv   ru   r   r   
contiguous)rY   r   r   r   r   r   r   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputs                r=   eager_attention_forwardr     s    3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#k1==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r<   c                   6    e Zd ZdZdedef fdZ	 	 ddej                  de	ej                  ej                  f   de
ej                     de
e   d	e
ej                     d
ee   de	ej                  e
ej                     e
e	ej                        f   fdZ xZS )CsmAttentionz=Multi-headed attention from 'Attention Is All You Need' paperrG   	layer_idxc                 d   t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  |j                  z  | _	        | j                  dz  | _
        |j                  | _        d| _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j                  | j                  z  |j
                  |j                        | _        y )Nr   g      Tr   )rj   rk   rG   r   getattrro   num_attention_headsr   r   r   r   attention_dropout	is_causalrJ   rK   attention_biasq_projk_projv_projo_projrX   rG   r   rq   s      r=   rk   zCsmAttention.__init__*  sM   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
r<   r,   position_embeddingsr   past_key_valuecache_positionr   r   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }|\  }}t        |	|
||      \  }	}
|'|||d}|j                  |
|| j                  |      \  }
}t        }| j                  j                  dk7  r^| j                  j                  dk(  r(|j                  dd      rt        j                  d	       nt         | j                  j                     } || |	|
||f| j"                  sd
n| j$                  | j&                  d|\  }} |j(                  g |d j+                         }| j-                  |      }||fS )Nrs   r!   r   )r   r   r   eagersdpaoutput_attentionsFz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.rD   )r   r   )r   r   r   viewr   r   r   r   updater   r   rG   _attn_implementationr   loggerwarning_oncer   r   r   r   r   r   r   )rX   r,   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   r   r   cache_kwargsattention_interfacer   r   s                     r=   r|   zCsmAttention.forwardA  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&S#7jRUWZ#[ j%#&snUL'5'<'<ZW[WeWegs't$J(?;;++w6{{//69fjjI\^c>d##L
 '>dkk>^>^&_#$7	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r<   )NN)r4   r5   r6   r7   r"   intrk   r8   Tensorr   r   r   
LongTensorr   r   r|   r   r   s   @r=   r   r   '  s    G
y 
S 
8 +/590)||0) #5<<#=>0) !.	0)
 !0) !!1!120) -.0) 
u||Xell3XeELL>Q5RR	S0)r<   r   c                   p    e Zd Zdedef f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   deej                  eeej                  ej                  f      f   fdZ xZS )rB   rG   r   c                     t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y )N)rG   r   rp   )rj   rk   ro   r   	self_attnr   mlprV   rms_norm_epsinput_layernormpost_attention_layernormr   s      r=   rk   zCsmDecoderLayer.__init__u  sk    !--%VyI&>)&*<*<&BUBUV(263E3E6K^K^(_%r<   r,   r   r   r   r   	use_cacher   r   r   r   c	                     |}
| j                  |      } | j                  d||||||||d|	\  }}|
|z   }|}
| j                  |      }| j                  |      }|
|z   }|f}|r||fz  }|S )N)r,   r   r   r   r   r  r   r   r;   )r  r  r  r  )rX   r,   r   r   r   r   r  r   r   r   residualself_attn_weightsoutputss                r=   r|   zCsmDecoderLayer.forward  s     !,,]; ,:4>> 
,
')%)/) 3
,
 
,
(( !=0 !55mD/ =0 ")++Gr<   )NNNFFNN)r4   r5   r6   r"   r  rk   r8   r  r   r	  r   boolr   r   r   r9   r|   r   r   s   @r=   rB   rB   t  s   `y `S ` 2637*.,1$)59KO'||' !.' u//0	'
 !' $D>' D>' !!1!12' &eELL%,,,F&GH' -.' 
u  (51B1BEDUDU1U+V"WW	X'r<   rB   c                       e Zd ZeZ fdZd Zd Zee		 	 	 	 	 	 	 	 	 	 dde
j                  dee
j                     dee
j                     dee
j                     dee   d	ee
j                     d
ee   dee   dee   dee
j                     dee   deeef   fd              Z	 ddee
j                  df   de
j                  de
j                  dedef
dZede
j                  dedede
j4                  de
j                  defd       Z xZS )CsmDepthDecoderModelc           	      r   t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  z  |j                        | _	        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                   |j"                        | _        t'        |      | _        d| _        t        j,                  |j                  |j                   d      | _        | j1                          y c c}w )Nr  rG   Fr   )rj   rk   pad_token_idrR   
vocab_sizerJ   rQ   rT   backbone_hidden_sizeembed_tokens
ModuleListrU   num_hidden_layersrB   layersrV   ro   r  normr   
rotary_embgradient_checkpointingrK   inputs_embeds_projector	post_initr   s      r=   rk   zCsmDepthDecoderModel.__init__  s     !.. ++LL&*>*>ARAR*RU[UpUpqmmAFvG_G_A`aI_VY/a
 v11v7J7JK	,F;&+#')yy1L1LfN`N`gl'm$ 	 bs   D4c                     | j                   S r   r  r   s    r=   get_input_embeddingsz)CsmDepthDecoderModel.get_input_embeddings         r<   c                     || _         y r   r)  rX   r   s     r=   set_input_embeddingsz)CsmDepthDecoderModel.set_input_embeddings  
    !r<   	input_idsbackbone_last_hidden_stater   r   r+   inputs_embedsr  r   output_hidden_statesr   flash_attn_kwargsr   c                 B   |5t         j                  j                         st        j	                  d       d}||n| j
                  j                  }|	|	n| j
                  j                  }	||n| j
                  j                  }|du |duz  rt        d      | j                  r%| j                  r|rt        j	                  d       d}|r|
t               }|
i||j                         nd}||j                  d   n|j                  d   }||j                  n|j                  }t        j                   |||z   |      }
|t        j"                  |
dz
  d	      }|| j$                  z  }| j'                  ||z         }|
d   dk(  }|
||dddf<   n5t         j                  j                         s|rt        j)                  d
       | j+                  |      }| j-                  |||
||      }|}|
j/                  d      }| j1                  ||      }|	rdnd}|rdnd}| j2                  d| j
                  j4                   D ],  }|	r||fz  } ||f||||||
|d|}|d   }|s$||d   fz  }. | j7                  |      }|	r||fz  }t9        ||r|nd||      S )aJ  
        backbone_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, backbone_hidden_size)`, *optional*):
            The last hidden state of the backbone model. Such input is required when the first codebook token (the one generated by the backbone model)
            is provided in the `input_ids` argument.
        NzCustom `position_ids` were provided but will be ignored. CSM depth decoder automatically determines position_ids from `cache_position` and as it requires them to be identical across the batch, the provided position_ids will be ignored.z;You must specify exactly one of input_ids or inputs_embeds.X`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.Fr   r!   r   )minzvWhen the first codebook token is provided, `backbone_last_hidden_state` should also be provided for correct inference.r;   r   r   r   r   r  r   r   last_hidden_stater+   r,   r-   )r8   compileris_compilingr   r  rG   r   r3  r  
ValueErrorr%  r   r   get_seq_lengthr   r   arangeclampr  r  warningr&  _update_causal_maskr   r$  r"  r!  r#  r   )rX   r0  r1  r   r   r+   r2  r  r   r3  r   r4  past_seen_tokensinputs_seq_lengthr   codebook_idxsoffsetinput_ids_are_first_codebookr   r,   r   all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                            r=   r|   zCsmDepthDecoderModel.forward  s   * #ENN,G,G,IM  L1B1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<Z[[&&4==Yj I0*nO!CRC^==?de:G:S 3 3A 6YbYhYhijYk-:-F]))IL\L\F"\\*:<LO`<`iopN !KK(:BM"T__4F --i&.@AM+9!+<+A()5&@ad#~~2249UNN Q 44]C..M>?L]
 & &//2"oom\J #7BD0d![[)H4;;+H+HI 	6M#!m%55!)
*)."3#-$7
 $
M *!,M =#3"55'	6* 		-0  -!11&+/8Od+%	
 	
r<   r%   input_tensorc           	         | j                   j                  dk(  r||dk(  j                         r|S y | j                   j                  dk(  r't        |t        j
                        rt        |      }|S ||j                         nd}||j                  nd}| j                   j                  dk(  r(|s&|s$t        j                  |||| j                        ry |j                  }|j                  d   }	|r|j                         }
n1t        |t        j
                        r|j                  d	   n||	z   dz   }
| j                  ||	|
|||j                  d   
      }| j                   j                  dk(  rQ|O|j                   j"                  dv r7|s5t	        j$                  |      j&                  }t        j(                  ||      }|S Nflash_attention_2rD   flex_attentionr   Fr   )r2  past_key_values_lengthis_trainingr!   rs   )sequence_lengthtarget_lengthru   r   
batch_size)cudaxpunpurG   r   anyrI   r8   r  r&   r?  is_compileabler   _ignore_causal_mask_sdpar   ru   r   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr   r   finfor8  _unmask_unattendedrX   r   rM  r   r+   r   rD  using_compilable_cacheru   rT  rU  r   	min_dtypes                r=   rC  z(CsmDepthDecoderModel._update_causal_mask7      ;;++/BB)~/D.I.I.K%%;;++/??.%,,7!<^!L!!
 @O?Z?99;`aCRC^!?!?di ;;++v5>T]n%>>*'7 MM	 ""&,,Q/!+??AM nell; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCKQZ[Kr<   rT  rU  ru   rV  c                    | | j                         dk(  r| }|S t        j                  |      j                  }t        j                  ||f|||j
                        }|dk7  rt        j                  |d      }|t        j                  ||j
                        |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }	|ddddddd|	f   | ddddddf   j                  |j
                        z   }
|
dk(  }
|ddddddd|	f   j                  |
|      |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.
        N   )
fill_valueru   r   r!   )diagonalr7  rs   r   r   r8   r`  r8  fullr   triur@  r   r   cloner   rv   masked_fillr   rT  rU  ru   r   rV  r   r   rd  mask_lengthpadding_masks              r=   r_  zJCsmDepthDecoderModel._prepare_4d_causal_attention_mask_with_cache_position{     < %.*<*<*>!*C(K* ' E*..I** -0Ye\j\q\qK !##jjqA5<<n>S>STWeWmWmnprsWtttK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c )6Aq!\k\12 r<   )
NNNNNNNNNNF)r4   r5   r6   r#   r\   rk   r*  r.  r   r   r8   r	  r   r9   r  r   r  r   r   r   r   r   r|   rC  staticmethodr  ru   r_  r   r   s   @r=   r  r    s   (L !"  '+BF1537+/59$(,0/359p
##p
 %-U->->$?p
 !.	p

 u//0p
 "%p
   1 12p
 D>p
 $D>p
 'tnp
 !!1!12p
 $$89p
 
u--	.p
  p
p #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4r<   r  c                   &     e Zd Z fdZddZ xZS )rS   c                     t         |           || _        t        j                  t        j                  | j                  dz
  ||            | _        y Nr!   )rj   rk   rT   rJ   rl   r8   emptyrL   )rX   ro   rT   r  rq   s       r=   rk   zCsmCodebooksHead.__init__  s?    *ll5;;t/A/AA/E{T^#_`r<   c           
         |2|j                   d   }| j                  t        j                  |         }n|dz
  }| j                  |   }t	        |j                   d         D cg c]9  }t
        j                  j                  |d d |d d f   ||   j                        ; }}t        j                  |d      }|S c c}w )Nr!   r   r   )
r   rL   r8   r@  rU   rJ   r   linearTstack)rX   r,   r   
seq_lengthcodebook_weightrF  codebook_idxs          r=   r|   zCsmCodebooksHead.forward  s    !&,,Q/J"kk%,,z*BCO*Q.M"kk-8O !&o&;&;A&> ?
 MM  q,/A!BOT`DaDcDcd
 
 Mq9
s   #>B<r   r   r   s   @r=   rS   rS     s    a
r<   rS   c                       e Zd Zy)KwargsForCausalLMN)r4   r5   r6   r;   r<   r=   r  r    s    r<   r  a$  
    The CsmDepthDecoder Model transformer, with a [`CsmCodebooksHead`] on top,
    which can be seen a position-specific language modeling head, allowing to use a different linear layer for each codebook
    (e.g. position 0 is the first codebook and uses the first codebook head, etc.)
    c            !       \    e Zd ZdZdZdZ fdZd Zd Zd Z	d Z
ee	 	 	 	 	 	 	 	 	 	 	 	 ddej                  deej                      d	eej"                     d
eej                     deeeeej                      f      deej                      deej                     dee   dee   dee   deej                     deeej"                  f   dee   deeef   fd              Z	 	 	 	 ddej                  dee   d	eej                     deej                      deej                     f
 fdZ xZS )CsmDepthDecoderForCausalLMNc                     t         |   |       t        |      | _        |j                  | _        t        |j                  |j                  |j                        | _        | j                          y r   )
rj   rk   r  rA   r  rS   ro   rT   codebooks_headr'  r   s     r=   rk   z#CsmDepthDecoderForCausalLM.__init__  sY     )&1
 ++.v/A/A6CWCWY_YjYjk 	r<   c                 .    | j                   j                  S r   rA   r  r   s    r=   r*  z/CsmDepthDecoderForCausalLM.get_input_embeddings  s    zz&&&r<   c                 &    || j                   _        y r   r  r-  s     r=   r.  z/CsmDepthDecoderForCausalLM.set_input_embeddings  s    "'

r<   c                     || _         y r   rA   )rX   decoders     r=   set_decoderz&CsmDepthDecoderForCausalLM.set_decoder  s	    
r<   c                     | j                   S r   r  r   s    r=   get_decoderz&CsmDepthDecoderForCausalLM.get_decoder  s    zzr<   r0  r1  r   r   r+   r2  labelsr  r   r3  r   logits_to_keepr   r   c                 `   |	|	n| j                   j                  }	|
|
n| j                   j                  }
 | j                  d||||||||	|
|d
|}|d   }t	        |t
              r |dk(  rt        dd      }nt        | d      }n|}| j                  |dd|ddf   |||   nd      }|j                         }d}|B|dddf   j                         } | j                  d|d| j                   j                  |d|}t        |||j                  |j                  |j                        S )	a  
        backbone_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, backbone_hidden_size)`, *optional*):
            The last hidden state of the backbone model. Such input is required when the first codebook token (the one generated by the backbone model)
            is provided in the `input_ids` argument.
        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]`.
        N)
r0  r1  r   r   r+   r2  r  r   r3  r   r   r!   .)r*   r  r  shift_labels)r)   r*   r+   r,   r-   r;   )rG   r   r3  rA   rI   r  slicer  r   loss_functionr  r   r+   r,   r-   )rX   r0  r1  r   r   r+   r2  r  r  r   r3  r   r  r   r  r,   slice_indicesr*   r)   r  s                       r=   r|   z"CsmDepthDecoderForCausalLM.forward  sy   6 2C1N-TXT_T_TqTq$8$D $++JjJj 	
 $** 
'A)%+'/!5)
 
  
nc*" %a %~ot <*M$$!]A-.Q_Qk}0Mqu
 ""$!#qr'?557L%4%% dt{{7M7M\hlrD &#33!//))
 	
r<   c                     t        	|   |||||fi |}|d   d   dk(  }|s|j                  d       |j                  d       |S )Nr   r   r1  r   )rj   prepare_inputs_for_generationpop)
rX   r0  r+   r   r2  r   r   model_inputsis_first_generation_steprq   s
            r=   r  z8CsmDepthDecoderForCausalLM.prepare_inputs_for_generation<  sg     w<~
Y_
 $00@#A!#D#I '9: 	(r<   )NNNNNNNNNNNr   NNNN)r4   r5   r6   _tied_weights_keys_tp_plan_pp_planrk   r*  r.  r  r  r   r   r8   r	  r   r9   r  r   r   r   r  r  r   r  r   r   r|   r  r   r   s   @r=   r  r    s	    HH'(  '+BF1537KO59-1$(,0/35934J
##J
 %-U->->$?J
 !.	J

 u//0J
 "%tE4E4E/F(F"GHJ
   1 12J
 ))*J
 D>J
 $D>J
 'tnJ
 !!1!12J
 c5<</0J
 *+J
 
u,,	-J
  J
^ ,0595959## "% !!1!12	
   1 12 !!1!12 r<   r  c                   $     e Zd Z fdZd Z xZS )CsmBackboneModelEmbeddingsc                    t         |           t        j                  |j                  |j
                  z  |j                        | _        | j                  dt        j                  |j                        |j
                  z  d       y )Naudio_tokens_offsetsFr   )rj   rk   rJ   rQ   rT   r  ro   embed_audio_tokensr   r8   r@  r   s     r=   rk   z#CsmBackboneModelEmbeddings.__init__T  sn    "$,,0D0DvGXGX0X[a[m[m"n"ELL1E1E$FIZIZ$Zgl 	 	
r<   c                 f    | j                  || j                  z         }|j                  d      }|S )Nr   r   )r  r  sum)rX   r0  input_embedss      r=   r|   z"CsmBackboneModelEmbeddings.forward[  s6    ..y4;T;T/TU#''A'.r<   r   r   s   @r=   r  r  S  s    
r<   r  c                       e Zd Z fdZd Zd Zee	 	 	 	 	 	 	 	 	 ddee	j                     dee	j                     dee	j                     dee   dee	j                     d	ee   d
ee   dee   dee	j                     dee   defd              Z	 ddee	j                  df   de	j                  de	j                  ded
ef
dZede	j                  dedede	j.                  de	j                  defd       Z xZS )CsmBackboneModelc           	         t         |   |       |j                  | _        |j                  | _        t        |      | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nr  r  F)rj   rk   r  rR   r  r  r  rJ   r   rU   r!  rB   r"  rV   ro   r  r#  r   r$  r%  r'  r   s      r=   rk   zCsmBackboneModel.__init__c  s     !.. ++6v>mmAFvG_G_A`aI_VY/a
 v11v7J7JK	,F;&+# 	 bs   )Cc                     | j                   S r   r)  r   s    r=   r*  z%CsmBackboneModel.get_input_embeddingsr  r+  r<   c                     || _         y r   r)  r-  s     r=   r.  z%CsmBackboneModel.set_input_embeddingsu  r/  r<   r0  r   r   r+   r2  r  r   r3  r   r4  r   c
                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|du |duz  rt	        d      | j
                  r%| j                  r|rt        j                  d       d}t        |t        d      t        f      st	        d      || j                  |      }|r|
t               }|	F||j                         nd}t        j                   |||j"                  d   z   |j$                        }	||	j'                  d      }| j)                  |||	||      }|}| j+                  ||      }|rd	nd}|rd	nd}| j,                  d| j                   j.                   D ],  }|r||fz  } ||f||||||	|d
|
}|d   }|s$||d   fz  }. | j1                  |      }|r||fz  }t3        ||r|nd||      S )a&  
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, num_codebooks) or (batch_size, sequence_length)`):
            1. (batch_size, sequence_length): corresponds to the input sequence prepared with the processor from the text prompt. Such input
            requires `input_values` to be provided so that audio can be encoded in codebook tokens and then merged with the text tokens.

            2. (batch_size, sequence_length, num_codebooks): codebook tokens generated during the autoregressive decoding. Such input is not meant to be used by end users.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        Nz:You must specify exactly one of input_ids or inputs_embedsr6  FzBThe `past_key_values` should be either a `Cache` object or `None`.r   r!   r7  r;   r9  r:  )rG   r   r3  r  r>  r%  r   r   r  rI   r   r   r  r   r?  r8   r@  r   r   r   rC  r$  r"  r!  r#  r   )rX   r0  r   r   r+   r2  r  r   r3  r   r4  rD  r   r,   r   rI  rJ  rK  rL  s                      r=   r|   zCsmBackboneModel.forwardx  sT   6 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<YZZ&&4==Yj I /DJ+>?abb  --i8M0*nO!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L..M>?L]
 & #oom\J #7BD0d![[)H4;;+H+HI 	6M#!m%55!)
*)."3#-$7
 $
M *!,M =#3"55'	6* 		-0  -!11&+/8Od+%	
 	
r<   r%   rM  c           	         | j                   j                  dk(  r||dk(  j                         r|S y | j                   j                  dk(  r't        |t        j
                        rt        |      }|S ||j                         nd}||j                  nd}| j                   j                  dk(  r(|s&|s$t        j                  |||| j                        ry |j                  }|j                  d   }	|r|j                         }
n1t        |t        j
                        r|j                  d	   n||	z   dz   }
| j                  ||	|
|||j                  d   
      }| j                   j                  dk(  rQ|O|j                   j"                  dv r7|s5t	        j$                  |      j&                  }t        j(                  ||      }|S rO  rZ  rb  s                r=   rC  z$CsmBackboneModel._update_causal_mask  re  r<   rT  rU  ru   rV  c                    | | j                         dk(  r| }|S t        j                  |      j                  }t        j                  ||f|||j
                        }|dk7  rt        j                  |d      }|t        j                  ||j
                        |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }	|ddddddd|	f   | ddddddf   j                  |j
                        z   }
|
dk(  }
|ddddddd|	f   j                  |
|      |ddddddd|	f<   |S rg  rk  rp  s              r=   r_  zFCsmBackboneModel._prepare_4d_causal_attention_mask_with_cache_position(  rs  r<   )	NNNNNNNNNrt  )r4   r5   r6   rk   r*  r.  r   r   r   r8   r	  r  r   r9   r  r   r   r   r|   r   rC  ru  r  ru   r_  r   r   s   @r=   r  r  a  s   !"  151537+/59$(,0/359h
E,,-h
 !.h
 u//0	h

 "%h
   1 12h
 D>h
 $D>h
 'tnh
 !!1!12h
 $$89h
 
!h
  h
` #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4r<   r  z
    The Csm model consists of two llama-like auto-regressive transformer models: a backbone model that predicts the first codebook token and a depth decoder that predicts the other codebook tokens.
    c            #           e Zd ZddgZ fdZd Zd Zd Zd Zd Z	e
 fd	       Z fd
Z	 	 	 	 d"deej                     deej                     deej                     deej                     deej                     f
dZ	 	 	 	 d"dej"                  dee   deej"                     deej&                     deej"                     f
 f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eeej&                     f      deej&                     deej"                     dee   dee   dee   deej"                     deeej                  f   dee   deeef   fd              Ze dej                  dededejB                  dej                  d efd!       Z" xZ#S )$CsmForConditionalGenerationz5backbone_model.embed_tokens.embed_audio_tokens.weightz'depth_decoder.model.embed_tokens.weightc                    t         |   |       |j                  | _        t        j                  |j
                  |j                  d      | _        t        j                  |j                  |j
                        | _	        t        j                  |      | _        t        j                  |j                        | _        t!        j"                  |j$                        | _        | j)                          y )NFr   )rj   rk   r  rJ   rK   ro   lm_headrQ   text_vocab_sizeembed_text_tokensr  _from_configbackbone_modelr  depth_decoder_configdepth_decoderr    from_configcodec_configcodec_modelr'  r   s     r=   rk   z$CsmForConditionalGeneration.__init__k  s      ++yy!3!3V5F5FUS!#f.D.DfFXFX!Y.;;FC7DDVE`E`a$001D1DE 	r<   c                 .    | j                   j                  S r   r  r  r   s    r=   r*  z0CsmForConditionalGeneration.get_input_embeddingsw  s    ""///r<   c                 &    || j                   _        y r   r  r-  s     r=   r.  z0CsmForConditionalGeneration.set_input_embeddingsz  s    +0(r<   c                     | j                   S r   r  r   s    r=   get_output_embeddingsz1CsmForConditionalGeneration.get_output_embeddings}  s    ||r<   c                     || _         y r   r  )rX   new_embeddingss     r=   set_output_embeddingsz1CsmForConditionalGeneration.set_output_embeddings  s	    %r<   c                     | j                   j                  rO| j                  | j                  j                  j
                  | j                  j                  j                         y y r   )rG   tie_codebooks_embeddings_tie_or_clone_weightsr  r  r  r  rA   r   s    r=   _tie_weightsz(CsmForConditionalGeneration._tie_weights  sL    ;;//&&##00CC""((55 0r<   c                    |j                  dd      rt        
|   |i |\  }}nt        
|   |i |}d}t        |      }t	        |j
                        j                         D ci c]  \  }}|j                  |      r||d  | }	}}t	        |j                  j
                        j                  ddi|	       |	D ]  }t        |j
                  ||z           d|v r|fS |S c c}}w )Noutput_loading_infoFdepth_decoder__from_model_config)r   rj   from_pretrainedlenvarsgeneration_configitems
startswithr  r   delattr)clsargsr   rA   loading_infoprefix
prefix_lenattrr   depth_decoder_attrsrq   s             r=   r  z+CsmForConditionalGeneration.from_pretrained  s   ::+U3"''"94"J6"JE<G+T<V<E "[
  $E$;$;<BBD
ev& u$
 
 	U  223::<PRW;o[n;op ( 	<DE++Vd];	< !F*,&&L
s   )!C)c                     d}| j                   j                  j                         }|j                  dd        |j	                         D ]  \  }}t        | j                  ||z   |       ! t        |   |i | y )Nr  transformers_version)r  r  to_diff_dictr  r  setattrrj   save_pretrained)rX   r  r   r  r  r  r   rq   s          r=   r  z+CsmForConditionalGeneration.save_pretrained  s|    !"00BBOOQ 6=.446 	BKD%D**FTM5A	B 	00r<   r0  input_valuesinput_values_cutoffsr  r   c                    | j                  |      }|3t        j                  j                  |d      }||dk\     j	                         }||dkD     }t        j                  |j                         |j                        j                  t        |      d      }||j                  d      k  }g }t        ||      D ]  \  }	}
|
|
dk\     }
t        |
j                  d   dz
        D ]r  }|
|   }|
|dz      }|	d||f   }| j                  j!                  |j                  d            }|j"                  j%                  dd      }|j'                  |d          t  t        d |D              }t        j(                  |D cg c]6  }t        j                  j                  |ddd||j                  d   z
  f      8 c}      }| j                  j+                  |      }| j,                  j.                  }||k(  }| j0                  j3                  |      }||   ||<   t        j4                  dd| j,                  j6                  f|j                  t
        j8                  	      | j,                  j:                  z  }| j0                  j3                  |      j=                  d      }|| j,                  j>                  k(  }|jA                  |jC                         d      ||<   |e|j                  d      jA                  dd| j,                  j6                        }||   ||<   |d
k(  jE                  d      }d||d   |d   ddf<   |}||dS c c}w )a  
        Merges the input_ids and input_values to produce a single inputs_embeds tensor:
        1 - Infers the codec model on the input_values to retreive codebook token.
        2 - Embeds codebook tokens and places them at the correct positions in the inputs_embeds tensor.
        3 - If labels are provided, expands them to match codebook dimensions and position the target codebook tokens in the inputs_embeds tensor.

        Args:
            input_ids (`torch.Tensor` of shape `(batch_size, sequence_length)`):
                The input ids to embed.
            input_values (`torch.Tensor` of shape `(batch_size, channels, audio_sequence_length)`):
                The audio input values to embed.
            input_values_cutoffs (`torch.Tensor` of shape `(batch_size, max_num_audio)`):
                The cutoffs of the audio input values relative to its batch index, padded with -1 when no audio.
        Nr!   r   r   r7  rs   r!   .c              3   :   K   | ]  }|j                   d      yw)r   N)r   ).0els     r=   	<genexpr>zQCsmForConditionalGeneration._merge_input_ids_with_input_values.<locals>.<genexpr>  s     "K2288A;"Ks   )r   ru   iTas_tuple)r2  r  )#r  rJ   r   paddiffr8   r@  maxr   r   r  r   ziprU   r   r  encodeaudio_codesr   appendr}  get_audio_codes_maskrG   audio_token_idr  r  rm   rT   longcodebook_eos_token_idsqueezeaudio_eos_token_idrepeatr  nonzero)rX   r0  r  r  r  r2  audio_lengthsinput_values_maskaudio_tokens_listbatch_input_valuesbatch_input_values_cutoffsrZ   	start_idxend_idxaudio_batchcodec_outputscodebook_idsmax_audio_framesr  batched_audio_token_idsaudio_codes_maskr  audio_token_maskaudio_embedsaudio_eos_frame_idsaudio_eos_embedsaudio_eos_token_masklabels_expanded depth_decoder_ignore_frames_idxss                                r=   "_merge_input_ids_with_input_valuesz>CsmForConditionalGeneration._merge_input_ids_with_input_values  sl   * ..y9##%==#4#45I6#R 01E1JKPPRM)-!*;<M %-A-E-E-GP\PcPc d k kM"B! !2M4K4KA4N N
 !#BElThBi >>"$>-GHbfgHg-h*9??BQFG >A :1 =I8Q?G"4S)G:K5K"LK$($4$4$;$;K<Q<QRS<T$UM#0#<#<#F#Fq"#ML%,,\!_=>>  #"K9J"KK&+kk\mnVX""21a1ABHHQK1O'PQn'#  $//DDEVW![[77N(N:..;;<STL.:;K.LM*+ 

Aq$++";";<YEUEU]b]g]gh++334    $22??@ST\\]^_#,0N0N#N 2B2I2IJ^JbJbJdfg2hM./ !"("2"22"6"="=aDKKD]D]"^4KL\4] 014:dN3K3KUY3K3Z0pt @ CEefgEhjkjl lm(!.&AA; os   ;Mr+   r   r2  r   c           	      0   t        	|   d	|||||d|}|}|j                  dk(  rn|j                  d      ]| j	                  ||j                  d      |j                  d      |j                  d            }|j                  |d   |d   d d       |S )
N)r0  r+   r   r2  r   r   r2  r  r  r  )r0  r  r  r  )r2  r  r0  r;   )rj   r  ndimr   r  r   )
rX   r0  r+   r   r2  r   r   r  merged_inputsrq   s
            r=   r  z9CsmForConditionalGeneration.prepare_inputs_for_generation  s     w< 
+)')
 
  Y^^q%8\=M=Mo=^=f CC##ZZ7%+ZZ0F%Gzz(+	 D M "/"@MZbLcrvw r<   r   r  r   r3  r  r   c                 X   |
|
n| j                   j                  }
||n| j                   j                  }|/|j                  dk(  r | j	                  ||||      }|d   }|d   }d} | j
                  d||||||	|
||d	|}|d   }t        |t              rt        | d      n|}| j                  |dd|ddf         }d}d}d}d}||dddddf   } | j                  d||| j                   j                  d|}|ddddddf   d	k(  j                  d
       }||   dd| j                   j                  dz
  f   }t        j                  j!                  |dd      }|j#                  d      }||d   |d   dz
  ddf   }||   }| j%                  |||	|
|d|      }|j&                  }||z   }t)        |||||j*                  |j,                  |j.                  ||j0                  nd||j*                  nd||j,                  nd||j.                        S d      S )a  
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, num_codebooks) or (batch_size, sequence_length)`):
            1. (batch_size, sequence_length): corresponds to the input sequence prepared with the processor from the text prompt. Such input
            requires `input_values` to be provided so that audio can be encoded in codebook tokens and then merged with the text tokens.

            2. (batch_size, sequence_length, num_codebooks): codebook tokens generated during the autoregressive decoding. Such input is not meant to be used by end users.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        input_values_cutoffs (`torch.Tensor` of shape `(batch_size, max_num_audio)`, *optional*):
            Specify the end positions of audio segments within each batch entry, relative to the concatenated audio input.
            If a batch entry has fewer segments than the maximum, it is padded with -1. For example, in a batch of 2 sequences
            where the first contains 2 audio segments of length l1, and the second contains 1 audio segment of length l2,
            the input_values_cutoffs would be: [[l1, 2 * l1], [l2, -1]].
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[config.audio_token_id, -100, -101]`.
            Requires targeted `input_values` to be provided as audio tokens will be infered from it using the `codec_model`.
            - `config.audio_token_id` indicates an audio frames (considering sequence length elements as frames)
            - `-100` will be ignored in the loss computation
            - `-101` indicates the audio frame will be used only for the backbone model (using the first codebook token as labels)

            Such labels can be prepared using `output_labels=True` when calling [`CsmProcessor`].
        logits_to_keep (`int` or `torch.Tensor`, *optional*):
            Kept for compatibility. Does not support another value than:
            1. `0`, which is equivalent to keeping all logits, used in the training regime
            2. `1`, which is equivalent to keeping only the last logit, used in the generation regime

        Example:

        ```python
        >>> import torch
        >>> from transformers import CsmForConditionalGeneration, AutoProcessor
        >>> from datasets import load_dataset, Audio

        >>> model_id = "eustlb/csm-1b"
        >>> torch_device = "cuda" if torch.cuda.is_available() else "cpu"

        >>> processor = AutoProcessor.from_pretrained(model_id)

        >>> ds = load_dataset("hf-internal-testing/dailytalk-dummy", split="train")
        >>> # ensure the audio is 24kHz
        >>> ds = ds.cast_column("audio", Audio(sampling_rate=24000))

        >>> conversation = []
        >>> # prepare a conversation with text and corresponding audio
        >>> for text, audio, speaker_id in zip(ds[:4]["text"], ds[:4]["audio"], ds[:4]["speaker_id"]):
        ...     conversation.append(
        ...         {
        ...             "role": f"{speaker_id}",
        ...             "content": [{"type": "text", "text": text}, {"type": "audio", "path": audio["array"]}],
        ...         }
        ...     )

        >>> inputs = processor.apply_chat_template(
        ...     conversation,
        ...     tokenize=True,
        ...     return_dict=True,
        ...     output_labels=True,
        ... ).to(torch_device)

        >>> model = CsmForConditionalGeneration.from_pretrained(model_id, device_map=torch_device)
        >>> output = model(**inputs)
        >>> output.loss.backward()
        ```Nr   r2  r  )	r0  r   r   r+   r2  r  r   r3  r   r   )r*   r  r  r!   r  rs   r   .r  )r   Tr  )r0  r1  r  r   r3  return_dictr  )r)   r3   r.   r*   r+   r,   r-   r/   r0   r1   r2   r;   )rG   r   r3  r  r  r  rI   r  r  r  r  r  allrT   rJ   r   r  r  r  r)   r(   r+   r,   r-   r*   )rX   r0  r  r   r  r   r+   r2  r  r  r   r3  r   r  r   r  backbone_outputsbackbone_hidden_statesr  backbone_logitsr)   r3   r.   depth_decoder_outputsbackbone_labels
train_maskdepth_decoder_input_ids
train_idxsbackbone_last_hidden_statesdepth_decoder_labelss                                 r=   r|   z#CsmForConditionalGeneration.forward  s   l 2C1N-TXT_T_TqTq$8$D $++JjJj 	  Y^^q%8 CC<)=vM */:M"8,FI.4.. 
)%+'/!5)
 
 "2!!48B>SV8W~ot4]k,,'=aPQ>Q'RS! $$Q1WoO.D.. &4;;KaKaekM "!Q(+t388R8@@J&,Z&8>]@Y@Y\]@]>]9]&^#&(mm&7&78OQW_`&7&a##++T+:J*@APZ[\P]`aPacdAd*e'#)*#5 $($6$61+F#"3%9 + %7 %! "7!;!; #55D '1",<<*88'22AVAb!6!=!=hl$0 +@*O*O$0 )>(K(KI^Ij%:%E%E
 	
 qu
 	
r<   rT  rU  ru   rV  c                    | | j                         dk(  r| }|S t        j                  |      j                  }t        j                  ||f|||j
                        }|dk7  rt        j                  |d      }|t        j                  ||j
                        |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }	|ddddddd|	f   | ddddddf   j                  |j
                        z   }
|
dk(  }
|ddddddd|	f   j                  |
|      |ddddddd|	f<   |S rg  rk  rp  s              r=   r_  zQCsmForConditionalGeneration._prepare_4d_causal_attention_mask_with_cache_position  rs  r<   r  )NNNNNNNNNNNNr   )$r4   r5   r6   r  rk   r*  r.  r  r  r  classmethodr  r  r   r8   r  r  r	  r   r9   r  r   r   r   r   r  r  r   r  r   r(   r|   ru  ru   r_  r   r   s   @r=   r  r  `  s    	@1

01&  41 -1/37;)-NBELL)NB u||,NB 'u||4	NB
 &NB 
%,,	NBf ,0595959## "% !!1!12	
   1 12 !!1!12>  '+/3157;37KO59-1$(,0/35934f
##f
 u||,f
 !.	f

 'u||4f
 u//0f
 "%tE4E4E/F(F"GHf
   1 12f
 ))*f
 D>f
 $D>f
 'tnf
 !!1!12f
 c5<</0f
 *+f
  
u''	(!f
  f
P 444 4 {{	4
 4 4 4r<   r  )r@   r  r  r  r  rx  )rD   )Qdataclassesr   typingr   r   r   r   r   r8   torch.nnrJ   activationsr
   cache_utilsr   r   
generationr   integrationsr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   r   autor    configuration_csmr"   r#   generation_csmr$   !torch.nn.attention.flex_attentionr%   integrations.flex_attentionr&   
get_loggerr4   r   r(   r@   ModulerV   r   r   r   r   r  r  r   r   r   r   rB   r  rS   r  r  r  r  r  __all__r;   r<   r=   <module>r9     s  , " 9 9   ! . ) 7 > B 9 O K F & u u  ? .  !;J 
		H	% 76 76 76t 
 * * *B Y'J J (J(< <DRYY  (6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % %4J)299 J)Z20 2j F- F FRryy . ?,j > |!3_ ||~  {) { {| 
X"46H X
Xvr<   