
    rh֊                        d dl mZ d dl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mZ dd
lmZ ddlmZ ddlmZmZmZmZ ddlmZ ddlm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z,  ejZ                  e.      Z/e ed       G d de                    Z0 G d de%      Z1 G d de&      Z2 G d de#      Z3 G d de       Z4 G d d e!      Z5 ed!      e G d" d#e                    Z6e G d$ d%e$e6             Z7 G d& d'ejp                        Z9 ed(       G d) d*e"e             Z: G d+ d,ejp                        Z;e G d- d.e$             Z< ed/       G d0 d1e6e,             Z=g d2Z>y)3    )	dataclass)OptionalUnionN)check_model_inputs   )CacheDynamicCache)GenerationMixin)create_causal_mask)BaseModelOutputWithPastCausalLMOutputWithPast)PreTrainedModel)Unpack)ModelOutputauto_docstringcan_return_tuplelogging   )	AutoModel)LlamaAttentionLlamaDecoderLayerLlamaForCausalLMLlamaMLP
LlamaModelLlamaRMSNormLlamaRotaryEmbeddingTransformersKwargs   )	CsmConfigCsmDepthDecoderConfig)CsmGenerationMixinz:
    Base class for the model autoregressive outputs.
    )custom_introc                      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)CsmOutputWithPasta	
  
    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 (`Cache`, *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.
    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'   tupler(   r)   r*   r+   r,   r-   r.   r/        v/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/models/csm/modular_csm.pyr$   r$   1   s'   < )-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--.5r9   r$   c                       e Zd Zy)
CsmRMSNormNr0   r1   r2   r8   r9   r:   r<   r<   d       r9   r<   c                       e Zd Zy)CsmRotaryEmbeddingNr=   r8   r9   r:   r@   r@   h   r>   r9   r@   c                       e Zd Zy)CsmMLPNr=   r8   r9   r:   rB   rB   l   r>   r9   rB   c                       e Zd Zy)CsmAttentionNr=   r8   r9   r:   rD   rD   p   r>   r9   rD   c                       e Zd Zy)CsmDecoderLayerNr=   r8   r9   r:   rF   rF   t   r>   r9   rF   z[
    The bare Csm Model outputting raw hidden-states without any specific head on top.
    c                   X     e Zd ZU eed<   dZdZdgZdgZdZ	dZ
dZdZeedZ fdZ xZS )CsmPreTrainedModelconfigmodelTrF   r'   )r(   r)   c                     t         |   |       t        |t              r^|j                  }t        |dz
        D ]@  }|j                  j                  |   j                  d| j                  j                         B y y )Nr   g        )meanstd)super_init_weights
isinstanceCsmCodebooksHeadnum_codebooksrangeweightdatanormal_rI   initializer_range)selfmodulerR   i	__class__s       r:   rO   z CsmPreTrainedModel._init_weights   sr    f%f./"00M=1,- [""1%--3DKK<Y<Y-Z[ 0r9   )r0   r1   r2   r   r6   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_can_compile_fullgraph_supports_attention_backendrF   rD   _can_record_outputsrO   __classcell__r[   s   @r:   rH   rH   x   s\     &*#*+#4"5N ""&("
[ [r9   rH   c                   2    e Zd ZU eed<    f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j                     dee   deeef   fd              Z xZS )CsmDepthDecoderModelrI   c                     t         |   |       t        j                  |j                  |j
                  z  |j                        | _        t        j                  |j                  |j                  d      | _
        y NF)bias)rN   __init__nn	EmbeddingrR   
vocab_sizebackbone_hidden_sizeembed_tokensLinearhidden_sizeinputs_embeds_projectorrX   rI   r[   s     r:   rl   zCsmDepthDecoderModel.__init__   s]     LL&*>*>ARAR*RU[UpUpq')yy1L1LfN`N`gl'm$r9   	input_idsbackbone_last_hidden_stateattention_maskposition_idsr'   inputs_embeds	use_cachecache_positionkwargsreturnc	                    |5t         j                  j                         st        j	                  d       d}|du |duz  rt        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                  |      }t!        | j"                  |||||	      }|}|j%                  d      }| j'                  ||      }| j(                  d| j"                  j*                   D ]  } ||f||||||d
|	} | j-                  |      }t/        ||r|      S 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.r   r   device)minzvWhen the first codebook token is provided, `backbone_last_hidden_state` should also be provided for correct inference.)rI   input_embedsrx   r|   r'   ry   )rx   ry   past_key_valuer{   r|   position_embeddings)last_hidden_stater'   )r4   compileris_compilingloggerwarning_once
ValueErrorr	   get_seq_lengthshaper   arangeclampro   rq   warningrt   r   rI   	unsqueeze
rotary_emblayersnum_hidden_layersnormr   )rX   rv   rw   rx   ry   r'   rz   r{   r|   r}   past_seen_tokensinputs_seq_lengthr   codebook_idxsoffsetinput_ids_are_first_codebookcausal_maskr(   r   decoder_layers                       r:   forwardzCsmDepthDecoderModel.forward   s>   & #ENN,G,G,IM  L-t";<Z[[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(;;&))+%
 & &//2"oom\J![[)H4;;+H+HI 
	M)	*).#-$7	 	M
	 		-0&+/8O
 	
>B
 	
r9   )NNNNNNNN)r0   r1   r2   r    r6   rl   r   r   r4   
LongTensorr   r5   Tensorr   boolr   r   r   r7   r   r   re   rf   s   @r:   rh   rh      s   !!n
  '+BF1537+/59$(59R
##R
 %-U->->$?R
 !.	R

 u//0R
 "%R
   1 12R
 D>R
 !!1!12R
 +,R
 
u--	.R
  R
r9   rh   c                   &     e Zd Z fdZddZ xZS )rQ   c                     t         |           || _        t        j                  t        j                  | j                  dz
  ||            | _        y )Nr   )rN   rl   rR   rm   	Parameterr4   emptyrT   )rX   rs   rR   ro   r[   s       r:   rl   zCsmCodebooksHead.__init__   s?    *ll5;;t/A/AA/E{T^#_`r9   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   dim)
r   rT   r4   r   rS   rm   
functionallinearTstack)rX   r(   r|   
seq_lengthcodebook_weightr   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<Nr0   r1   r2   rl   r   re   rf   s   @r:   rQ   rQ      s    a
r9   rQ   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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e
eej                     f      de	ej                     de	ej                     de	e   de	ej                     deeej                  f   dee   deeef   fd              Z xZS )CsmDepthDecoderForCausalLMNc                     t         |   |       | `t        |j                  |j
                  |j                        | _        t        |      | _	        y r   )
rN   rl   lm_headrQ   rs   rR   ro   codebooks_headrh   rJ   ru   s     r:   rl   z#CsmDepthDecoderForCausalLM.__init__  sE     L.v/A/A6CWCWY_YjYjk)&1
r9   rv   r'   rx   rz   r|   c                     t        	|   |||||fi |}|d   d   dk(  }|s|j                  d       |j                  d       |S )Nr|   r   rw   ry   )rN   prepare_inputs_for_generationpop)
rX   rv   r'   rx   rz   r|   r}   model_inputsis_first_generation_stepr[   s
            r:   r   z8CsmDepthDecoderForCausalLM.prepare_inputs_for_generation!  sg     w<~
Y_
 $00@#A!#D#I '9: 	(r9   rw   ry   labelsr{   logits_to_keepr}   r~   c                     | 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]`.
        )rv   rw   rx   ry   r'   rz   r{   r|   r   r   N.)r&   r   ro   shift_labels)r%   r&   r'   r(   r)   r8   )rJ   rP   intslicer   
contiguousloss_functionrI   ro   r   r'   r(   r)   )rX   rv   rw   rx   ry   r'   rz   r   r{   r|   r   r}   outputsr(   slice_indicesr&   r%   r   s                     r:   r   z"CsmDepthDecoderForCausalLM.forward7  s;   2 $** 

'A)%+')

 

  
nc*" %a %~ot <*M$$!]A-.Q_Qk}0Mqu
 ""$!#qr'?557L%4%% dt{{7M7M\hlrD &#33!//))
 	
r9   NNNN)
NNNNNNNNNr   )r0   r1   r2   _tied_weights_keys_tp_plan_pp_planrl   r4   r   r   r   r5   r   r   r   r   r   listr   r   r   r   r7   r   r   re   rf   s   @r:   r   r     s    HH2 ,0595959## "% !!1!12	
   1 12 !!1!12,  '+BF1537KO59-1$(5934@
##@
 %-U->->$?@
 !.	@

 u//0@
 "%tE4E4E/F(F"GH@
   1 12@
 ))*@
 D>@
 !!1!12@
 c5<</0@
 +,@
 
u,,	-@
  @
r9   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_offsetsF)
persistent)rN   rl   rm   rn   rR   ro   rs   embed_audio_tokensregister_bufferr4   r   ru   s     r:   rl   z#CsmBackboneModelEmbeddings.__init__}  sn    "$,,0D0DvGXGX0X[a[m[m"n"ELL1E1E$FIZIZ$Zgl 	 	
r9   c                 f    | j                  || j                  z         }|j                  d      }|S )Nr   r   )r   r   sum)rX   rv   r   s      r:   r   z"CsmBackboneModelEmbeddings.forward  s6    ..y4;T;T/TU#''A'.r9   r   rf   s   @r:   r   r   |  s    
r9   r   c                   <     e Zd Z fdZee fd              Z xZS )CsmBackboneModelc                 D    t         |   |       t        |      | _        y r   )rN   rl   r   rq   ru   s     r:   rl   zCsmBackboneModel.__init__  s     6v>r9   c                 "    t        |   di |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)
        r8   )rN   r   )rX   super_kwargsr[   s     r:   r   zCsmBackboneModel.forward  s     w...r9   )r0   r1   r2   rl   r   r   r   re   rf   s   @r:   r   r     s$    ? /  /r9   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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j                     deeej                  f   dee   deeef   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 rj   )rN   rl   ro   rm   rr   rs   r   rn   text_vocab_sizeembed_text_tokensr   _from_configbackbone_modelr   depth_decoder_configdepth_decoderr   from_configcodec_configcodec_model	post_initru   s     r:   rl   z$CsmForConditionalGeneration.__init__  s      ++yy!3!3V5F5FUS!#f.D.DfFXFX!Y.;;FC7DDVE`E`a$001D1DEr9   c                 .    | j                   j                  S r   r   rq   rX   s    r:   get_input_embeddingsz0CsmForConditionalGeneration.get_input_embeddings  s    ""///r9   c                 &    || j                   _        y r   r   )rX   values     r:   set_input_embeddingsz0CsmForConditionalGeneration.set_input_embeddings  s    +0(r9   c                     | j                   j                  rO| j                  | j                  j                  j
                  | j                  j                  j                         y y r   )rI   tie_codebooks_embeddings_tie_or_clone_weightsr   rq   r   r   rJ   r   s    r:   _tie_weightsz(CsmForConditionalGeneration._tie_weights  sL    ;;//&&##00CC""((55 0r9   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)getrN   from_pretrainedlenvarsgeneration_configitems
startswithr   updatedelattr)clsargsr}   rJ   loading_infoprefix
prefix_lenattrr   depth_decoder_attrsr[   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   setattrrN   save_pretrained)rX   r   r}   r   r  r  r   r[   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0r9   rv   input_valuesinput_values_cutoffsr   r~   c                    | j                  |      }|Ut        j                  j                  |d      }||dk\     j	                         }||dkD     }t        j                  |j                         |j                        j                  t        |      d      }||j                  d      k  }t        j                         5  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-                  |      }ddd       | j.                  j0                  }||k(  }| j2                  j5                        }|   ||<   t        j6                  dd| j.                  j8                  f|j                  t
        j:                  	      | j.                  j<                  z  }| j2                  j5                  |      j?                  d      }|| j.                  j@                  k(  }|jC                  |jE                         d      ||<   |j|j                  d      jC                  dd| j.                  j8                        }||   ||<   |||<   |d
k(  jG                  d      }d||d   |d   ddf<   |}||dS c c}w # 1 sw Y   xY 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   r   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     &Orrxx{&Os   )r   dtypeiTas_tuple)rz   r   )$r   rm   r   paddiffr4   r   maxr   expandr   r   no_gradziprS   r   r   encodeaudio_codes	transposeappendr   get_audio_codes_maskrI   audio_token_idr   rq   onesrR   longcodebook_eos_token_idsqueezeaudio_eos_token_idrepeatr   nonzero)rX   rv   r	  r
  r   rz   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  s   * ..y9##%==#4#45I6#R 01E1JKPPRM)-!*;<M %-A-E-E-GP\PcPc d k kM"B! !2M4K4KA4N N
  \$&!FI,XlFm BB&(B1KLfjkLk1l."#=#C#CA#F#JK B$>q$A	"<QU"C&8i>O9O&P(,(8(8(?(?@U@UVW@X(Y'4'@'@'J'J1b'Q)00aABB $'&O=N&O#O */++`qrZ\R]]&&rAq!5EQR5S+TUr+' $(#3#3#H#HIZ#[ !\$ "[[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18K 454:dN3K3KUY3K3Z0pt @ CEefgEhjkjl lm(!.&AA= s\ \s   CM4;M/
"M4/M44M>r'   rx   rz   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)rv   r'   rx   rz   r|   r   rz   r	  r
  r   )rv   r	  r
  r   )rz   r   rv   r8   )rN   r   ndimr   r=  r   )
rX   rv   r'   rx   rz   r|   r}   r   merged_inputsr[   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 r9   ry   r{   r   r}   c                    |/|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|||	d|d|}|j"                  }||z   }t%        |||||j&                  |j(                  |j*                  ||j,                  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 = "sesame/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   rz   r   )rv   rx   ry   r'   rz   r{   r|   r   )r&   r   ro   r   r  r  r   .r  )r   Tr  )rv   rw   r{   return_dictr   )r%   r/   r*   r&   r'   r(   r)   r+   r,   r-   r.   r8   )r?  r=  r   rP   r   r   r   r   rI   ro   allrR   rm   r   r  r(  r   r%   r$   r'   r(   r)   r&   )rX   rv   r	  rx   r
  ry   r'   rz   r   r{   r|   r   r}   r@  backbone_outputsbackbone_hidden_statesr   backbone_logitsr%   r/   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.forwardZ  s   f  Y^^q%8 CC<)=vM */:M"8,FI.4.. 	
)%+')	
 	
 "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 $6D$6$6 %1+F# +% %! "7!;!; #55D '1",<<*88'22AVAb!6!=!=hl$0 +@*O*O$0 )>(K(KI^Ij%:%E%E
 	
 qu
 	
r9   r   )NNNNNNNNNNr   )r0   r1   r2   r   rl   r   r   r   classmethodr   r  r   r4   r   r=  r   r   r5   r   r   r   r   r   r   r   r   r   r7   r$   r   re   rf   s   @r:   r   r     s    	@1
01  41 -1/37;)-PBELL)PB u||,PB 'u||4	PB
 &PB 
%,,	PBj ,0595959## "% !!1!12	
   1 12 !!1!12>  '+/3157;37KO59-1$(5934[
##[
 u||,[
 !.	[

 'u||4[
 u//0[
 "%tE4E4E/F(F"GH[
   1 12[
 ))*[
 D>[
 !!1!12[
 c5<</0[
 +,[
 
u''	([
  [
r9   r   )rH   r   rh   r   r   )?dataclassesr   typingr   r   r4   torch.nnrm   transformers.utils.genericr   cache_utilsr   r	   
generationr
   masking_utilsr   modeling_outputsr   r   modeling_utilsr   processing_utilsr   utilsr   r   r   r   autor   llama.modeling_llamar   r   r   r   r   r   r   r   configuration_csmr   r    generation_csmr!   
get_loggerr0   r   r$   r<   r@   rB   rD   rF   rH   rh   ModulerQ   r   r   r   r   __all__r8   r9   r:   <module>ra     s    " "   9 . ) / O - & K K 	 	 	 @ . 
		H	% 
)6 )6 )6Z	 		- 		X 		> 		' 	 
 [ [ [4 \
:'9 \
 \
~ryy . c
!1? c
c
L  /z / /. 
P
"46H P

P
f
r9   