
    fTh^                    ^   S r SSKrSSKrSSKJr  SSKJrJrJrJ	r	J
r
  SSKrSSKrSSKJr  SSKJr  SSKJrJr  SS	KJrJr  SS
KJrJr  SSKJrJrJrJr  SSKJr  SSK J!r!J"r"  SSK#J$r$J%r%J&r&  SSK'J(r(J)r)J*r*  \&RV                  " \,5      r-S\R\                  S\R\                  4S jr/S\R\                  S\R\                  4S jr0S r1SAS jr2      SBS jr3\ " S S\$5      5       r4\ " S S\$5      5       r5 " S S\Rl                  5      r7 " S S \Rl                  5      r8 " S! S"\Rl                  5      r9 " S# S$\Rl                  5      r: " S% S&\Rl                  5      r; " S' S(\Rl                  5      r< " S) S*\Rl                  5      r= " S+ S,\Rl                  5      r> " S- S.\Rl                  5      r? " S/ S0\Rl                  5      r@\% " S1 S2\5      5       rA " S3 S4\A5      rB " S5 S6\A5      rC\% " S7 S8\A5      5       rD\%" S9S:9 " S; S<\A\5      5       rE\%" S=S:9 " S> S?\A\5      5       rF/ S@QrGg)CzPyTorch CLVP model.    N)	dataclass)CallableDictOptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FNget_activation)GenerationConfigGenerationMixin)_prepare_4d_attention_mask!_prepare_4d_causal_attention_mask)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsBaseModelOutputWithPooling!CausalLMOutputWithCrossAttentions)PreTrainedModel)Conv1Disin_mps_friendly)ModelOutputauto_docstringlogging   )
ClvpConfigClvpDecoderConfigClvpEncoderConfiglogitsreturnc                     [         R                  R                  U [        R                  " [        U 5      U R                  S95      $ )Ndevice)r	   
functionalcross_entropytorcharangelenr$   )r    s    ^/var/www/auris/envauris/lib/python3.13/site-packages/transformers/models/clvp/modeling_clvp.pycontrastive_lossr+   7   s/    ==&&vu||CKPVP]P]/^__    
similarityc                 X    [        U 5      n[        U R                  5       5      nX-   S-  $ )Ng       @)r+   t)r-   caption_lossspeech_losss      r*   	clvp_lossr2   <   s*    #J/L":<<>2K&#--r,   c                     U SSU R                   S   S-  24   nU SU R                   S   S-  S24   n[        R                  " U* U4SS9$ )z*Rotates half the hidden dims of the input..N   dim)shaper'   cat)xx1x2s      r*   rotate_halfr=   C   sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r,   c                     X5   R                  U5      nXE   R                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nX#-  [        U5      U-  -   n	XxU	4$ )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`):
        The position indices of the tokens corresponding to the query and key tensors. For example, this can be
        used to pass offsetted position ids when working with a KV-cache.
    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kvcossinposition_idsunsqueeze_dimq_embedk_embedv_embeds
             r*   apply_rotary_pos_embrJ   J   st    * 

%
%m
4C


%
%m
4Cw;q>C/0Gw;q>C/0Gw;q>C/0GW$$r,   c           	      R   U(       aW  [         R                  R                  R                  U SUS9n Ub)  [         R                  R                  R                  USSS9OUnU nU(       Ga=  [         R                  " U R
                  S   U R
                  S   S-   4U R                  U R                  S9n[        U 5       H  u  p[        X5      R                  5       (       ai  [         R                  " X:H  5      S   R                  5       n
[         R                  " U	SU
 [         R                  " U/U R                  S9XS /5      Xx'   M  [         R                  R                  R                  U	SUS9Xx'   M     Ub)  [         R                  R                  R                  USSS9OUnXq4$ )	z
This method adds extra bos and eos tokens to input_ids and accordingly modifies the attention_mask which is used in
`ClvpConditioningEncoder` and the generation loop of the `ClvpModelForConditionalGeneration`.
)r   r   valueNr   r   dtyper$   r#   )r   r   )r'   r	   r%   padzerosr8   rO   r$   	enumerater   sumwhereminconcatenatetensor)	input_idsattention_maskpad_token_idbos_token_ideos_token_idadd_bos_tokenadd_eos_tokenmodified_input_idsieach_input_idposs              r*   _pad_extra_bos_eos_tokensrc   g   s    HH''++Iv\+R	HVHbEHH##NF!#Dhv 	 #"[[__Q!3a!78	XaXhXh
 !*) 4A =AACCkk-"?@CGGI(-(9(9"4C(%,,~iN^N^*_anosatu)"%
 ).(;(;(?(?v]i(?(j"% !5 IWHbEHH##NF!#Dhv 	 --r,   c                       \ rS rSr% SrSr\\R                     \	S'   Sr
\\R                     \	S'   Sr\\R                     \	S'   Sr\\\R                        \	S'   Sr\\\R                        \	S'   S	rg)
ClvpEncoderOutput   a#  
Base class for CLVP encoder's outputs that contains a pooling of the last hidden states as well as a projection
output (a linear layer on top of the pooled output).

Args:
    embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when model is initialized with `with_projection=True`):
        The embeddings obtained by applying the projection layer to the pooler_output.
    last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
        The hidden state of the last layer of the model.
    pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
        Pooled output of the `last_hidden_state`.
    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.
Nembedslast_hidden_statepooler_outputhidden_states
attentions )__name__
__module____qualname____firstlineno____doc__rg   r   r'   FloatTensor__annotations__rh   ri   rj   r   rk   __static_attributes__rl   r,   r*   re   re      s}    * +/FHU&&'.59x 1 12915M8E--.58<M8E%"3"345<59Ju00129r,   re   c                      \ rS rSr% SrSr\\R                     \	S'   Sr
\\R                     \	S'   Sr\\R                     \	S'   Sr\\R                     \	S'   Sr\\R                     \	S'   Sr\\R                     \	S	'   Sr\\	S
'   Sr\\	S'   Sr\\R                     \	S'   Sr\\R                     \	S'   Sr\\R                     \	S'   Srg)
ClvpOutput   a  
Args:
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
        Contrastive loss for speech-text similarity.
    speech_ids (`torch.LongTensor`, *optional*):
        speech_ids (or speech candidates) generated by the `ClvpForCausalLM` model.
    logits_per_speech (`torch.FloatTensor` of shape `(speech_batch_size, text_batch_size)`):
        The scaled dot product scores between `speech_embeds` and `text_embeds`. This represents the speech-text
        similarity scores.
    logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, speech_batch_size)`):
        The scaled dot product scores between `text_embeds` and `speech_embeds`. This represents the text-speech
        similarity scores.
    text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
        The text embeddings obtained by applying the projection layer to the pooled output of the text encoder
        model.
    speech_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
        The speech embeddings obtained by applying the projection layer to the pooled output of the speech encoder
        model.
    text_model_output (`BaseModelOutputWithPooling`):
        The pooled output of the `last_hidden_state` of the text encoder Model.
    speech_model_output (`BaseModelOutputWithPooling`):
        The pooled output of the `last_hidden_state` of the speech encoder Model.
    decoder_hidden_states (`torch.FloatTensor`, *optional*):
        The hidden states of the decoder model.
    text_encoder_hidden_states (`torch.FloatTensor`, *optional*):
        The hidden states of the text encoder model.
    speech_encoder_hidden_states (`torch.FloatTensor`, *optional*):
        The hidden states of the speech encoder model.
Nloss
speech_idslogits_per_speechlogits_per_texttext_embedsspeech_embedstext_model_outputspeech_model_outputdecoder_hidden_statestext_encoder_hidden_statesspeech_encoder_hidden_statesrl   )rm   rn   ro   rp   rq   rx   r   r'   rr   rs   ry   
LongTensorrz   r{   r|   r}   r~   r   r   r   r   r   rt   rl   r,   r*   rv   rv      s    < )-D(5$$
%,-1J))*159x 1 12937OXe//07/3K%++,315M8E--.548186:3:9=8E$5$56=>B):): ;B@D (5+<+<"=Dr,   rv   c                   8   ^  \ rS rSrSU 4S jjrS rS rSrU =r$ )ClvpRMSNorm   c                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z*
ClvpRMSNorm is equivalent to T5LayerNorm
N)super__init__r	   	Parameterr'   onesweightvariance_epsilon)selfhidden_sizeeps	__class__s      r*   r   ClvpRMSNorm.__init__   s/     	ll5::k#:; #r,   c                    UR                   nUR                  [        R                  5      nUR	                  S5      R                  SSS9nU[        R                  " X0R                  -   5      -  nU R                  UR                  U5      -  $ )Nr5   r4   T)keepdim)	rO   tor'   float32powmeanrsqrtr   r   )r   rj   input_dtypevariances       r*   forwardClvpRMSNorm.forward   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::r,   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)tupler   r8   r   r   s    r*   
extra_reprClvpRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIr,   )r   r   )gư>)	rm   rn   ro   rp   r   r   r   rt   __classcell__r   s   @r*   r   r      s    $;J Jr,   r   c                   f   ^  \ rS rSrSrU 4S jrS\R                  S\R                  4S jrSr	U =r
$ )ClvpRotaryPositionalEmbedding   z
Rotary Position Embedding Class for CLVP. It was proposed in the paper 'ROFORMER: ENHANCED TRANSFORMER WITH ROTARY
POSITION EMBEDDING', Please see https://arxiv.org/pdf/2104.09864v1.pdf .
c           	      &  > [         TU ]  5         [        UR                  UR                  S-  -  S5      nSS[
        R                  " SUS[
        R                  S9R                  5       U-  -  -  nU R                  SU5        S U l
        S U l        g )Nr5             ?i'  r   rO   inv_freq)r   r   maxprojection_dimnum_attention_headsr'   r(   int64floatregister_buffercached_sequence_length"cached_rotary_positional_embedding)r   configr7   r   r   s       r*   r   &ClvpRotaryPositionalEmbedding.__init__   s    &''F,F,F,JKRP%ELLC%++$N$T$T$VY\$\]^Z2&*#26/r,   rj   r!   c                    UR                   S   nX R                  :X  a  U R                  b  U R                  $ X l        [        R                  " X!R
                  S9R                  U R                  5      n[        R                  " SX0R                  5      n[        R                  " XD4SS9nUR                  S5      U l        U R                  $ )Nr   r#   zi,j->ijr4   r6   r   )r8   r   r   r'   r(   r$   type_asr   einsumr9   r?   )r   rj   sequence_lengthtime_stampsfreqs
embeddingss         r*   r   %ClvpRotaryPositionalEmbedding.forward  s    '--a0999d>e>e>q:::&5#ll?;O;OPXXY]YfYfgY]]CYY~26
2<2F2Fq2I/666r,   )r   r   rm   rn   ro   rp   rq   r   r'   rr   r   rt   r   r   s   @r*   r   r      s1    
77U%6%6 75;L;L 7 7r,   r   c                     ^  \ rS rSrSrU 4S jrS\R                  S\S\4S jr	       SS\R                  S	\\R                     S
\\R                     S\\R                     S\\\R                        S\\   S\\R                     S\\   S\\R                  \\R                     \\\R                        4   4S jjrSrU =r$ )ClvpSelfAttentioni  zm
Multi-headed attention to combine Absolute and Rotary Positional Embeddings into a single Attention module.
c                 :  > [         TU ]  5         Xl        UR                  U l        UR
                  U l        U R                  U R                  -  U l        U R                  U R                  -  U R                  :w  a&  [        SU R                   SU R                   S35      eU R                  S-  U l	        UR                  U l        [        US5      (       ah  UR                  n[        R                  " [        R                   " X"4[        R"                  S95      nUR%                  SSX"5      nU R'                  SUS	S
9  [(        R*                  " U R                  U R                  UR,                  S9U l        [(        R*                  " U R                  U R                  UR,                  S9U l        [(        R*                  " U R                  U R                  UR,                  S9U l        [(        R*                  " U R                  U R                  5      U l        g )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).      max_position_embeddingsr   r   biasF)
persistentr   )r   r   r   r   	embed_dimr   	num_headshead_dim
ValueErrorscaleattention_dropoutdropouthasattrr   r'   trilr   boolviewr   r	   Linearuse_attention_biask_projv_projq_projout_proj)r   r   max_positionsr   r   s       r*   r   ClvpSelfAttention.__init__  s   ++33$..8==4>>)T^^;MdnnM] ^NN#2'  ]]D(
//6455"::M::ejj-)GuzzZ[D99Q=@D  % @iiVE^E^_iiVE^E^_iiVE^E^_		$..$..Ar,   rW   seq_lenbszc                     UR                  X2U R                  U R                  5      R                  SS5      R	                  5       $ )Nr   r5   )r   r   r   	transpose
contiguous)r   rW   r   r   s       r*   _shapeClvpSelfAttention._shape.  s5    {{3GQQRSUVWbbddr,   rj   rotary_pos_embrY   rE   past_key_value	use_cache	head_maskoutput_attentionsr!   c	                    Ub  Uc  [        S5      eUR                  5       u  pnU R                  U R                  U5      SU	5      U R                  -  nU R                  U R                  U5      SU	5      nU R                  U R                  U5      SU	5      nUb2  Uu  nn[        R                  " X4SS9n[        R                  " UU4SS9nUSL a  X4nOS nUb  UR                  S   nUSS U24   USUS 24   nnUSS U24   USUS 24   nnUSS U24   USUS 24   nnUR                  5       R                  S5      UR                  5       R                  S5      nn[        UUUUUU5      u  nnn[        R                  " UU4SS9n[        R                  " UU4SS9n[        R                  " UU4SS9nUR                  S   nUR                  S   n[        R                  " XR                  SS	5      5      nUb@  UR                  5       U	S
UU4:w  a#  [        SU	S
UU4 SUR                  5        35      eUU-   n[         R"                  R%                  USS9nUb  UU-  n[         R"                  R'                  UU R&                  U R(                  S9n[        R                  " UU5      nUR                  5       XR*                  UU R,                  4:w  a6  [        SXR*                  UU R,                  4 SUR                  5        35      eUR                  S
S5      R/                  5       nUR1                  U	UU R2                  5      nU R5                  U5      nU(       d  S nUUU4$ )NzB`position_ids` must be provided when `rotary_pos_emb` is not None.r4   r6   T.r   r5   r   r   z!Attention mask should be of size z	, but is )ptrainingz `attn_output` should be of size )r   sizer   r   r   r   r   r'   r9   r8   rC   squeezerD   rJ   matmulr   r	   r%   softmaxr   r   r   r   r   reshaper   r   ) r   rj   r   rY   rE   r   r   r   r   r   _r   query_states
key_statesvalue_statespast_key
past_valuepresentrotary_emb_dim	query_rot
query_passkey_rotkey_pass	value_rot
value_passrC   rD   tgt_lensrc_lenattn_weights
attn_probsattn_outputs                                    r*   r   ClvpSelfAttention.forward1  s    %,*>abb)..0	 {{4;;}#=r3G$**T[[]!;RE
{{4;;}#=r3G%#1 HjH#9rBJ 99j,%?RHL!0GG%+11"5N S/>/12S./12 "I
 3/03/0 G
 S/>/12S./12 "I
 &))+33A68J8J8L8T8TUV8WC,@GU^`cehjv,w)Iw	 !99i%<"ELGX#6B?J 99i%<"EL$$Q'""1%||L2F2Fq!2LM%""$a'(BB 7a'8R7SS\]k]p]p]r\st  (.8L}},,\r,B  ')3L]]**<4<<RVR_R_*`
ll:|<#~~w!NN2CRVR_R_3`2a b$$&') 
 "++Aq1<<>!))#wGmmK0 LG\11r,   )
r   r   r   r   r   r   r   r   r   r   )NNNNFNF)rm   rn   ro   rp   rq   r   r'   Tensorintr   rr   r   r   r   r   r   rt   r   r   s   @r*   r   r     s)   B2eU\\ eC ec e 7;59378<$)15,1\2((\2 !!2!23\2 !!1!12	\2
 u//0\2 !u||!45\2 D>\2 E--.\2 $D>\2 
u  (5+<+<"=xeN_N_H`?aa	b\2 \2r,   r   c                   f   ^  \ rS rSrSrU 4S jrS\R                  S\R                  4S jrSr	U =r
$ )ClvpGatedLinearUniti  z
`ClvpGatedLinearUnit` uses the second half of the `hidden_states` to act as a gate for the first half of the
`hidden_states` which controls the flow of data from the first of the tensor.
c                    > [         TU ]  5         [        UR                     U l        [
        R                  " UR                  UR                  S-  5      U l	        g )Nr5   )
r   r   r   
hidden_actactivation_fnr	   r   r   intermediate_sizeprojr   r   r   s     r*   r   ClvpGatedLinearUnit.__init__  sD    #F$5$56IIf00&2J2JQ2NO	r,   rj   r!   c                 j    U R                  U5      R                  SSS9u  pXR                  U5      -  $ )Nr5   r4   r6   )r  chunkr
  )r   rj   gates      r*   r   ClvpGatedLinearUnit.forward  s7    "ii6<<QB<G11$777r,   )r
  r  r   r   s   @r*   r  r    s2    
P
8U%6%6 85;L;L 8 8r,   r  c                   f   ^  \ rS rSrSrU 4S jrS\R                  S\R                  4S jrSr	U =r
$ )ClvpEncoderMLPi  z9
This MLP is used in CLVP speech or text encoder models.
c                    > [         TU ]  5         Xl        [        U5      U l        [
        R                  " UR                  UR                  5      U l	        [
        R                  " UR                  5      U l        g N)r   r   r   r  fc1r	   r   r  r   fc2Dropoutr   dropout_layerr  s     r*   r   ClvpEncoderMLP.__init__  sR    &v.99V55v7I7IJZZ7r,   rj   r!   c                 l    U R                  U5      nU R                  U5      nU R                  U5      nU$ r  )r  r  r  r   rj   s     r*   r   ClvpEncoderMLP.forward  s4    /**=9/r,   )r   r  r  r  r   r   s   @r*   r  r    s1    8U%6%6 5;L;L  r,   r  c                      ^  \ rS rSrS\4U 4S jjr SS\R                  S\R                  S\R                  S\R                  S\	\
   S	\\R                     4S
 jjrSrU =r$ )ClvpEncoderLayeri  r   c                   > [         TU ]  5         Xl        UR                  U l        [        U5      U l        [        U5      U l        [        U R                  UR                  S9U l        [        U R                  UR                  S9U l        g )Nr   )r   r   r   r   r   r   	self_attnr  mlpr   layer_norm_epsinput_rmsnormpost_attention_rmsnormr  s     r*   r   ClvpEncoderLayer.__init__  sj    ++*62!&)(V=R=RS&1$..fF[F[&\#r,   rj   r   rY   rE   r   r!   c                     UnU R                  U5      nU R                  UUUUUS9nUS   nXa-   nUnU R                  U5      nU R                  U5      nXa-   nU4nU(       a  XS   4-  nU$ )a  
Args:
    hidden_states (`torch.FloatTensor` of shape `(batch, seq_len, embed_dim)`):
        input to the layer.
    rotary_pos_emb (`torch.FloatTensor`):
        rotary position embeddings generated by `ClvpRotaryPositionalEmbedding` module.
    attention_mask (`torch.FloatTensor` of shape `(batch, 1, tgt_len, src_len)`):
        attention mask where padding elements are indicated by very large negative values.
    position_ids (`torch.LongTensor`):
        Denotes position ids of the input tokens.
    output_attentions (`bool`, *optional*, defaults to `False`):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
)rj   r   rY   rE   r   r   r4   )r&  r#  r'  r$  )	r   rj   r   rY   rE   r   residualattention_outputsoutputss	            r*   r   ClvpEncoderLayer.forward  s    , !**=9 NN'))%/ + 
 *!, 0 33MB/ 0 ""-//Gr,   )r   r   r&  r$  r'  r#  )F)rm   rn   ro   rp   r   r   r'   rr   r   r   r   r   r   rt   r   r   s   @r*   r   r     s    ]z ]  -20((0 ))0 ((	0
 &&0 $D>0 
u  	!0 0r,   r   c                      ^  \ rS rSrSrS\4U 4S jjr S
S\R                  S\	\R                     S\R                  4S jjrS	rU =r$ )ClvpSequenceSummaryi  a  
Compute a single vector summary of a sequence hidden states.

Args:
    config ([`ClvpConfig`]):
        The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
        config class of your model for the default values it uses):

        - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:

            - `"last"` -- Take the last token hidden state (like XLNet)
            - `"first"` -- Take the first token hidden state (like Bert)
            - `"mean"` -- Take the mean of all tokens hidden states
            - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
            - `"attn"` -- Not implemented now, use multi-head attention

        - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
        - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
          (otherwise to `config.hidden_size`).
        - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
          another string or `None` will add no activation.
        - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
        - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
r   c                   > [         TU ]  5         [        USS5      U l        U R                  S:X  a  [        e[
        R                  " 5       U l        [        US5      (       a  UR                  (       aq  [        US5      (       a.  UR                  (       a  UR                  S:  a  UR                  nOUR                  n[
        R                  " UR                  U5      U l        [        USS 5      nU(       a  [        U5      O[
        R                  " 5       U l        [
        R                  " 5       U l        [        US5      (       a5  UR"                  S:  a%  [
        R$                  " UR"                  5      U l        [
        R                  " 5       U l        [        US	5      (       a7  UR(                  S:  a&  [
        R$                  " UR(                  5      U l        g g g )
Nsummary_typelastattnsummary_use_projsummary_proj_to_labelsr   summary_activationsummary_first_dropoutsummary_last_dropout)r   r   getattrr1  NotImplementedErrorr	   Identitysummaryr   r4  r5  
num_labelsr   r   r   
activationfirst_dropoutr7  r  last_dropoutr8  )r   r   num_classesactivation_stringr   s       r*   r   ClvpSequenceSummary.__init__  sa   #FNFC& &%{{}6-..63J3Jv788V=Z=Z_e_p_pst_t$//$0099V%7%7EDL#F,@$GIZN3D$E`b`k`k`m[[]62338T8TWX8X!#F,H,H!IDKKM6122v7R7RUV7V "

6+F+F GD 8W2r,   rj   	cls_indexr!   c                    U R                   S:X  a  USS2S4   nGOU R                   S:X  a  USS2S4   nGOU R                   S:X  a  UR                  SS9nOU R                   S	:X  a  Uc?  [        R                  " US
SS2SS24   UR                  S   S-
  [        R
                  S9nOXUR                  S5      R                  S5      nUR                  SUR                  5       S-
  -  UR                  S5      4-   5      nUR                  SU5      R                  S5      nOU R                   S:X  a  [        eU R                  W5      nU R                  U5      nU R                  U5      nU R!                  U5      nU$ )a#  
Compute a single vector summary of a sequence hidden states.

Args:
    hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
        The hidden states of the last layer.
    cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
        Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.

Returns:
    `torch.FloatTensor`: The summary of the sequence hidden states.
r2  Nr4   firstr   r   r   r6   rD  .r   r   r4   r3  )r1  r   r'   	full_liker8   longr?   expandr7   r   gatherr   r:  r?  r<  r>  r@  )r   rj   rD  outputs       r*   r   ClvpSequenceSummary.forward*  sn    &"1b5)F')"1a4(F&("''A'.F+- !OO!#rr1*-!''+a/**	 &//3==bA	%,,Uimmo6I-JmN`N`acNdMf-fg	"))"i8@@DF&(%%##F+f%(""6*r,   )r>  r?  r@  r<  r1  r  )rm   rn   ro   rp   rq   r   r   r'   rr   r   r   r   rt   r   r   s   @r*   r/  r/    sV    2Hz H< Y])"..);CEDTDT;U)			) )r,   r/  c                   n   ^  \ rS rSrU 4S jrS\\\R                        S\R                  4S jr	Sr
U =r$ )ClvpDecoderMLPiW  c                    > [         TU ]  5         UR                  n[        X5      U l        [        X15      U l        [        UR                     U l        [        R                  " UR                  5      U l        g r  )r   r   r   r   c_fcc_projr   activation_functionactr	   r  resid_pdropr   )r   r  r   r   r   s       r*   r   ClvpDecoderMLP.__init__X  sZ    &&	,8	Y:&445zz&"4"45r,   rj   r!   c                     U R                  U5      nU R                  U5      nU R                  U5      nU R                  U5      nU$ r  )rQ  rT  rR  r   r  s     r*   r   ClvpDecoderMLP.forward`  s@    		-0/M2]3r,   )rT  rQ  rR  r   )rm   rn   ro   rp   r   r   r   r'   rr   r   rt   r   r   s   @r*   rO  rO  W  s6    6XeE4E4E.F%G EL]L]  r,   rO  c                   b  ^  \ rS rSrU 4S jr      SS\\\R                        S\\\R                        S\\R                     S\\R                     S\\R                     S\\   S	\\   S
\\\R                     \\\R                  \\R                  S4   4      4   4S jjrSrU =r$ )ClvpDecoderLayerih  c                 B  > [         TU ]  5         UR                  nUR                  b  UR                  OSU-  n[        R
                  " X!R                  S9U l        [        U5      U l	        [        R
                  " X!R                  S9U l
        [        X15      U l        g )N   r"  )r   r   r   n_innerr	   	LayerNormlayer_norm_epsiloninput_layernormr   r3  post_attention_layernormrO  r$  )r   r   r   	inner_dimr   s       r*   r   ClvpDecoderLayer.__init__i  sw    ((&,nn&@FNNa+o	!||K=V=VW%f-	(*[F_F_(`%!)4r,   rj   r   rY   rE   r   r   r   r!   .c           
          UnU R                  U5      nU R                  UUUUUUUS9n	U	S   n
U	SS  nX-   nUnU R                  U5      nU R                  U5      nX-   nU(       a  U4U-   nU$ U4USS  -   nU$ )Nr   rY   rE   r   r   r   r   r   )r`  r3  ra  r$  )r   rj   r   rY   rE   r   r   r   r*  attn_outputsr  r,  feed_forward_hidden_statess                r*   r   ClvpDecoderLayer.forwardt  s     !,,];yy))%/ ! 
 #1oqr"#. 55mD%)XXm%<" =$&0G  %&4Gr,   )r3  r`  r$  ra  )NNNNFF)rm   rn   ro   rp   r   r   r   r'   rr   r  r   r   r   r   rt   r   r   s   @r*   rZ  rZ  h  s    	5 9=593715$),1%e&7&7 89% !u||!45% !!1!12	%
 u//0% E--.% D>% $D>% 
uU\\"HU5<<uGXGXZ]G]A^3^-_$``	a% %r,   rZ  c            
          ^  \ rS rSrSrS\4U 4S jjrSS\S\4S jjr   SS\	R                  S	\\	R                     S
\\	R                     S\\	R                     4S jjrSrU =r$ )ClvpConditioningEncoderi  aw  
This class processes the log-mel spectrograms(extracted by the Feature Extractor) and text tokens(produced by the
tokenizer) as inputs for the decoder model.

First each log-mel spectrogram is processed into a single vector which captures valuable characteristics from each
of them, then the text tokens are converted into token embeddings and position embeddings are added afterwards.
Both of these vectors are concatenated and then passed to the decoder model.

The text tokens helps to incorporate the "text information" and the log-mel spectrogram is used to specify the
"voice characteristics" into the generated mel tokens.
r   c                   > [         TU ]  5         UR                  U l        UR                  U l        [        R
                  " U R                  R                  U R                  R                  5      U l        [        R
                  " U R                  R                  U R                  R                  5      U l
        [        R                  " U R                  R                  U R                  R                  SS9U l        U R                  U R                  R                  5      n[        R                  " [!        U R                  R"                  5       Vs/ s H-  n[        R$                  " X R                  R                  SSS9PM/     sn5      U l        [        R                  " [!        U R                  R"                  5       Vs/ s H  n[)        U R                  5      PM     sn5      U l        SU l        g s  snf s  snf )Nr   )kernel_sizegh㈵>T)r   affineF)r   r   text_configdecoder_configr	   	Embedding
vocab_sizer   text_token_embeddingmax_text_tokenstext_position_embeddingConv1dfeature_sizemel_convcompute_groupnorm_groups
ModuleListrangenum_mel_attn_blocks	GroupNormgroup_normsr   mel_attn_blocksgradient_checkpointing)r   r   
num_groupsr   r   s       r*   r    ClvpConditioningEncoder.__init__  s   !--$33$&LL1A1A1L1LdNaNaNmNm$n!')||//1D1D1P1P(
$ 		$"5"5"B"BDDWDWDcDcqrs 2243F3F3R3RS
== t22FFGGA Z)<)<)H)Hd[_`G
  "}}=B4CVCVCjCj=kl=kt223=kl 
 ',# ms   4G7G<channelsgroupsc                     US::  a  SnOUS::  a  SnX-  S:w  a  [        US-  5      nX-  S:w  a  M  US::  a  [        SU S35      eU$ )z
Calculates the value of `num_groups` for nn.GroupNorm. This logic is taken from the official tortoise
repository. link :
https://github.com/neonbjb/tortoise-tts/blob/4003544b6ff4b68c09856e04d3eff9da26d023c2/tortoise/models/arch_util.py#L26
      @   r   r5   zENumber of groups for the GroupNorm must be greater than 2, but it is z0.Please consider using a different `hidden_size`)r  r   )r   r  r  s      r*   rx  0ClvpConditioningEncoder.compute_groupnorm_groups  st     r>F^F1$!_F 1$ Q;WX^W_ `B C 
 r,   input_featuresrX   inputs_embedsrY   c                     Ub  Ub  [        S5      eUb  UR                  5       u  pVO$Ub  UR                  5       S S u  pVO[        S5      eUc/  [        R                  " XV/[        R                  UR
                  S9n[        UUU R                  R                  U R                  R                  S9u  p$U R                  U5      nUR                  S5      S-
  nU R                  U5      nX8-   n	U R                  (       a  U R                  (       a  [        R                  R                   R!                  U R"                  U5      n
[%        U R&                  5       H  u  pU
R)                  SS5      n[        R                  R                   R!                  U R*                  U   U
5      R)                  SS5      n
[        R                  R                   R!                  X5      S   U-   n
U
R)                  SS5      n
M     OU R#                  U5      n
[%        U R&                  5       H\  u  pU
R)                  SS5      nU R*                  U   " U
5      R)                  SS5      n
U" U
5      S   U-   n
U
R)                  SS5      n
M^     U
S S 2S S 2S4   n
U
R-                  S5      n
U	R.                  S   S:X  a4  U
R.                  S   S:w  a!  U	R1                  U
R.                  S   SS5      n	OU	R.                  S   S:w  a4  U
R.                  S   S:X  a!  U
R1                  U	R.                  S   SS5      n
OLU	R.                  S   U
R.                  S   :w  a,  [        S	U	R.                  S    S
U
R.                  S    S35      e[        R2                  " X/SS9$ )NDYou cannot specify both input_ids and inputs_embeds at the same timer4   5You have to specify either input_ids or inputs_embedsrN   )r[   r\   r   r5   r   z=The number of texts and number of audios must be same. Found z
 texts vs z audiosr6   )r   r   r'   r   rI  r$   rc   rn  r[   r\   rr  cumsumrt  r  r   utils
checkpointrw  rR   r~  r   r}  r?   r8   repeatconcat)r   r  rX   r  rY   
batch_size
seq_lengthrE   position_embedsr|   mel_specr`   mel_attn_blockresidual_mel_specs                 r*   r   ClvpConditioningEncoder.forward  sX     ]%>cdd"%.^^%5"J
&%2%7%7%9#2%>"J
TUU !"ZZ(@

[d[k[klN %>))66))66	%
!	 11)<%,,R01466|D#5&&4=={{--88WH%.t/C/C%D!$,$6$6q!$<! ;;11<<T=M=Ma=PRZ[eefgijk ;;11<<^VWXY\mm#--a3 &E }}^4H%.t/C/C%D!$,$6$6q!$<!++A.x8BB1aH)(3A69JJ#--a3 &E Aq!G$%%a( Q1$):a)?%,,X^^A->1EKq!Q&8>>!+<+A{'8'8';QBHq!X^^A%66$**1-.j9J8K7T 
 ||X3;;r,   )ro  r  r}  r~  rw  rn  rt  rr  )r   NNN)rm   rn   ro   rp   rq   r   r   r  rx  r'   rr   r   r   r   rt   r   r   s   @r*   rj  rj    s    
,z ,: c 0 155959H<))H< E,,-H<   1 12	H<
 !!1!12H< H<r,   rj  c                   *    \ rS rSr\rSrSrSrS r	Sr
g)ClvpPreTrainedModeli&  clvpTpast_key_valuesc           	         U R                   R                  n[        U[        R                  5      (       a)  UR
                  R                  R                  SUS-  S9  GO1[        U[        R                  [        [        R                  45      (       aZ  UR
                  R                  R                  SUS-  S9  UR                  b$  UR                  R                  R                  5         GO[        U[        5      (       Ga  U R                   R                  nUR                   R                  S-  SUR                   R                  -  S-  -  U-  nSUR                   R                  -  S-  U-  n[        R                   R                  [#        UR$                  S5      (       a   UR$                  R&                  R
                  OUR$                  R
                  US9  [        R                   R                  UR(                  R
                  US9  GO~[        U[*        5      (       ae  U R                   R-                  5       nUR                  nUR.                  R
                  R                  R                  SX%R                  S-  -  S9  GO[        U[0        5      (       a]  UR2                  R
                  R                  R                  SUS9  UR2                  R                  R                  R                  5         O[        U[4        5      (       a}  UR7                  5        Hi  u  pgUS	:X  d  M  UR                  R                  SU R                   R8                  [:        R<                  " SU R                   R                  -  5      -  S9  Mk     [        U[        R>                  5      (       aJ  UR                  R                  R                  5         UR
                  R                  RA                  S
5        gg)zInitialize the weightsg        g{Gz?)r   stdNr   r5   r  )r  zc_proj.weightr   )!r   initializer_factor
isinstancer	   rp  r   datanormal_r   r   ru  r   zero_r  r   num_hidden_layersinitr9  r  r  r  ClvpEncoderget_text_config
projectionrj  rw  ClvpForCausalLMnamed_parametersinitializer_rangemathsqrtr^  fill_)r   modulefactorin_proj_stdfc_stdr   namer   s           r*   _init_weights!ClvpPreTrainedModel._init_weights-  s   //fbll++MM&&CVd]&CFBII >??MM&&CVd]&C{{&  &&(//[[33F!==44d:FMMDcDc@chl?lmpvvK&--333<vEFGGOOgfjj&6Q6QFJJOO22W]WaWaWhWhntOuGGOOFJJ--;O?,,[[002F..F$$))11sJ\J\^bJb@c1d 788OO""''//Sf/EOO  %%++-00!224?*FFNN t{{'D'DtyyQRUYU`U`UrUrQrGs's #  5
 fbll++KK""$MM$$S) ,r,   rl   N)rm   rn   ro   rp   r   config_classbase_model_prefixsupports_gradient_checkpointing_skip_keys_device_placementr  rt   rl   r,   r*   r  r  &  s    L&*#"3*r,   r  c                      ^  \ rS rSrSrS\4U 4S jjrS rS r       SS\	\
R                     S\	\
R                     S	\	\
R                     S
\	\
R                     S\	\   S\	\   S\	\   S\\\4   4S jjrSrU =r$ )r  iN  z
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`ClvpEncoderLayer`].

Args:
    config: ClvpConfig
r   c                 x  > [         TU ]  U5        Xl        [        R                  " UR
                  UR                  5      U l        UR                  (       a  [        U5      OS U l
        [        R                  " [        UR                  5       Vs/ s H  n[        U5      PM     sn5      U l        [!        U5      U l        [        R$                  " UR                  UR&                  S9U l        [        R*                  " UR                  UR,                  SS9U l        SU l        U R3                  5         g s  snf )Nr"  Fr   )r   r   r   r	   rp  rq  r   token_embeddinguse_rotary_embeddingr   r   ry  rz  r  r   layersr/  sequence_summaryr^  r%  final_layer_normr   r   r  r  	post_initr   r   r   r   s      r*   r   ClvpEncoder.__init__W  s     !||F,=,=v?Q?QRGMGbGb;FChlmmuVMeMeGf$gGf!%5f%=Gf$gh 3F ; "V-?-?VEZEZ [))F$6$68M8MTYZ&+# %hs   D7c                     U R                   $ r  r  r   s    r*   get_input_embeddings ClvpEncoder.get_input_embeddingsh  s    ###r,   c                     Xl         g r  r  r   rM   s     r*   set_input_embeddings ClvpEncoder.set_input_embeddingsk  s    $r,   rX   r  rY   rE   r   output_hidden_statesreturn_dictr!   c           	         Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUb  Ub  [	        S5      eUbH  U R                  X5        UR                  5       nUR                  SUS   5      nU R                  U5      nO"Ub  UR                  5       SS nO[	        S5      eUb  [        X2R                  5      nUcS  Ub  UR                  OUR                  n	[        R                  " US   [        R                  U	S9nUR                  S5      nU(       a  SOSn
U(       a  SOSnU R                   b  U R!                  U5      OSnUn[#        U R$                  5       H  u  pU(       a  X4-   n
U R&                  (       aI  U R(                  (       a8  [        R*                  R,                  R-                  UR.                  UUUU5      nO
U" UUUUUS	9nUS   nU(       d  M  UUS   4-   nM     U(       a  X4-   n
UnU R1                  U5      nU R3                  U5      nU R5                  U5      nU(       d  [7        S
 UUUX4 5       5      $ [9        UUUU
US9$ )a  
Args:
    input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
        Indices of input sequence tokens in the vocabulary.

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

        [What are input IDs?](../glossary#input-ids)
    inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
        input embeddings for the model. This bypasses the model's internal embedding lookup matrix.
    attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
        Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

        - 1 for tokens that are **not masked**,
        - 0 for tokens that are **masked**.

        [What are attention masks?](../glossary#attention-mask)
    position_ids (`torch.LongTensor`, *optional*):
        Denotes the position ids of `input_ids`.
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
    output_hidden_states (`bool`, *optional*):
        Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
        for more detail.
    return_dict (`bool`, *optional*):
        Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
Nr  r4   r  r   rN   r   rl   )r   c              3   .   #    U  H  oc  M  Uv   M     g 7fr  rl   .0rB   s     r*   	<genexpr>&ClvpEncoder.forward.<locals>.<genexpr>  s      eaes   	)rg   rh   ri   rj   rk   )r   r   r  use_return_dictr   %warn_if_padding_and_no_attention_maskr   r   r  r   rO   r$   r'   r(   rI  r?   r   rR   r  r  r   r  r  __call__r  r  r  r   re   )r   rX   r  rY   rE   r   r  r  input_shaper$   encoder_statesall_attentionsr   rj   idxencoder_layerlayer_outputsrh   pooled_outputrg   s                       r*   r   ClvpEncoder.forwardn  s   N 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] ]%>cdd"66yQ#..*K!r;r?;I 00;M&',,.s3KTUU %7H[H[\N)2)>Y%%MDXDXF <<AejjQWXL'11!4L30d?C?R?R?^,,];dh%"+DKK"8C#!/2B!B**t}} % 6 6 A A!**!"" ! !.!"" &7! *!,M  !/=3C2E!E/ #92  +.>>N) 112CD --.?@ / "$5}ne   !/'(%
 	
r,   )r   r  r  r  r  r   r  r  )NNNNNNN)rm   rn   ro   rp   rq   r   r   r  r  r   r'   r   r   r   r   r   r   rt   r   r   s   @r*   r  r  N  s    z "$%
 15485937,0/3&*y
E,,-y
   0 01y
 !!1!12	y

 u//0y
 $D>y
 'tny
 d^y
 
uo%	&y
 y
r,   r  c                     ^  \ rS rSrSrU 4S jrS rS rS r\	           SS\
\R                     S\
\R                     S	\
\R                     S
\
\R                     S\
\R                     S\
\\\R                           S\
\R                     S\
\   S\
\   S\
\   S\
\   S\\\4   4S jj5       rSrU =r$ )ClvpDecoderi  zk
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ClvpDecoderLayer`]
c                   > [         TU ]  U5        Xl        [        R                  " U R                  R
                  U R                  R                  5      U l        [        R                  " U R                  R                  U R                  R                  5      U l	        [        R                  " U R                  R                  5      U l        [        R                  " [        U R                  R                  5       Vs/ s H  n[!        U R                  5      PM     sn5      U l        [        R$                  " U R                  R                  U R                  R&                  S9U l        SU l        U R-                  5         g s  snf )Nr"  F)r   r   r   r	   rp  rq  r   input_embeds_layerr   position_embeds_layerr  
embd_pdropdropry  rz  r  rZ  r  r^  r_  
layer_normr  r  r  s      r*   r   ClvpDecoder.__init__  s     "$,,t{{/E/Et{{G^G^"_%'\\$++2U2UW[WbWbWnWn%o"JJt{{556	mmERVR]R]RoRoLp$qLpq%5dkk%BLp$qr,,t{{'>'>DKKDbDbc&+# 	 %rs   ?Fc                     U R                   $ r  r  r   s    r*   r   ClvpDecoder.get_input_embeddings   s    &&&r,   c                     Xl         g r  r  r   new_embeddingss     r*   r   ClvpDecoder.set_input_embeddings  s    "0r,   c                     UR                  5        H-  u  p#U R                  U   R                  R                  U5        M/     g)zf
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
N)itemsr  r3  prune_heads)r   heads_to_prunelayerheadss       r*   _prune_headsClvpDecoder._prune_heads  s6     +002LEKK##//6 3r,   rX   rY   token_type_idsrE   r   r  r  r   r   r  r  r!   c                    U	b  U	OU R                   R                  n	U
b  U
OU R                   R                  n
Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  Ub  [        S5      eUbF  U R                  X5        UR                  5       nUR                  SUS   5      nUR                  S     O1Ub#  UR                  5       S S nUR                  S     O[        S5      eUb  UR                  OUR                  nUb  UR                  SUS   5      nUc%  Sn[        S /[        U R                  5      -  5      nOUS   S   R                  S5      nUcN  [        R                  " XS   U-   [        R                   US9nUR#                  S5      R                  SUS   5      nUc  U R%                  U5      nU R'                  U5      nX-   n[)        X,X~5      nU R+                  XPR                   R,                  5      nUnUb  U R%                  U5      nUU-   nU R/                  U5      nSUSS  -   UR                  S5      4-   nU R0                  (       a/  U R2                  (       a  U(       a  [4        R7                  S	5        S
nU(       a  SOS nU	(       a  SOS nU	(       a  U R                   R8                  (       a  SOS nU
(       a  SOS n[;        [=        U R                  U5      5       H  u  nu  nnU
(       a  UU4-   nU R0                  (       aM  U R2                  (       a<  [        R>                  R@                  RA                  URB                  US UUUU   5      nOU" UUUUUU   UU	S9nUS   nUSL a	  UUS   4-   nU	(       d  M  UUU(       a  SOS   4-   nU R                   R8                  (       d  M  UUU(       a  SOS   4-   nM     U RE                  U5      nUR                  U5      nU
(       a  UU4-   nU(       d  [        S UUUUU4 5       5      $ [G        UUUUUS9$ )Nr  r4   r   r  r   rN   rG  r   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Frl   re  Tr5   r   c              3   0   #    U  H  nUc  M  Uv   M     g 7fr  rl   r  s     r*   r  &ClvpDecoder.forward.<locals>.<genexpr>  s      pA ps   	rh   r  rj   rk   cross_attentions)$r   r   r  r   r  r   r  r   r   r8   r$   r   r)   r  r'   r(   rI  r?   r  r  r   get_head_maskr  r  r  r   loggerwarning_onceadd_cross_attentionrR   zipr  r  r  r  r   )r   rX   rY   r  rE   r   r  r  r   r   r  r  r  r$   past_key_values_lengthr  rj   token_type_embedsoutput_shapepresentsall_self_attentionsall_cross_attentionsall_hidden_statesr`   blockr   r,  s                              r*   r   ClvpDecoder.forward  sM    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B] ]%>cdd"66yQ#..*K!r;r?;IOOA&',,.s3K"TUU%.%:!!@T@T%+00[_EN"%&"#TFS-=$=>O%4Q%7%:%?%?%C" <<&B:P(PX]XbXbkqL (11!499"k"oNL  33I>M44\B%7:
 &&y++2O2OP	%% $ 7 7 G),==M		-0{12.-2D2DR2H1JJ&&4==##p "	"2$5b4%64;;;Z;Zr`d"6BD*3C_4U*V&A&~#$58H$H!**t}}++00;;NN!" aL  !#1#1!-'l'&7 $AJMD #wqzm3  &9W)QYZ=[<]&]#;;222+?7PY1_`CaBc+c(? +WB 6%**<8   1]4D D '3DFY[op   9+$+*1
 	
r,   )r   r  r  r  r  r  r  NNNNNNNNNNN)rm   rn   ro   rp   rq   r   r  r  r  r   r   r'   r   rr   r   r  r   r   r   r   rt   r   r   s   @r*   r  r    sG   "'17  156:593715@D59$(,0/3&*L
E,,-L
 !!2!23L
 !!1!12	L

 u//0L
 E--.L
 "%ell(;"<=L
   1 12L
 D>L
 $D>L
 'tnL
 d^L
 
u??	@L
 L
r,   r  c                     ^  \ rS rSrS\4U 4S jjrS rS rS r\	           SS\
\R                     S\
\R                     S	\
\R                     S
\
\R                     S\
\R                     S\
\\\R                           S\
\R                     S\
\   S\
\   S\
\   S\
\   S\\\4   4S jj5       rSrU =r$ )	ClvpModeli  r   c                    > [         TU ]  U5        Xl        [        U R                  5      U l        U R                  5         g r  )r   r   r   r  decoderr  r  s     r*   r   ClvpModel.__init__  s1     "4;;/ 	r,   c                 .    U R                   R                  $ r  r  r  r   s    r*   r  ClvpModel.get_input_embeddings  s    ||...r,   c                 $    XR                   l        g r  r  r  s     r*   r  ClvpModel.set_input_embeddings  s    */'r,   c                     U R                   $ r  )r  r   s    r*   get_decoderClvpModel.get_decoder  s    ||r,   rX   rY   r  rE   r   r  r  r   r   r  r  r!   c                    U	b  U	OU R                   R                  n	U
b  U
OU R                   R                  n
Ub  UOU R                   R                  nUb  UOU R                   R                  nU R                  UUUUUUUUU	U
US9nU(       d  U$ [        UR                  UR                  UR                  UR                  UR                  S9$ )N)rX   rY   r  rE   r   r  r  r   r   r  r  r  )r   r   r  r   r  r  r   rh   r  rj   rk   r  )r   rX   rY   r  rE   r   r  r  r   r   r  r  decoder_outputss                r*   r   ClvpModel.forward  s     2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B] ,,))%+'/!5# ' 
 ""8-??+;;)77&11,==
 	
r,   )r   r  r  )rm   rn   ro   rp   r   r   r  r  r  r   r   r'   r   rr   r   r  r   r   r   r   rt   r   r   s   @r*   r  r    s<   0 /0  156:593715@D59$(,0/3&*-
E,,--
 !!2!23-
 !!1!12	-

 u//0-
 E--.-
 "%ell(;"<=-
   1 12-
 D>-
 $D>-
 'tn-
 d^-
 
u??	@-
 -
r,   r  zG
    The CLVP decoder model with a language modelling head on top.
    )custom_introc                     ^  \ rS rSrU 4S jrS rS r   SS\\R                     S\\
   S\\\\R                  4      S\\R                  \\   \\\R                  4   4   4S	 jjr SS
 jr\            SS\\R"                     S\\\\R                           S\\R$                     S\\R"                     S\\R"                     S\\R$                     S\\R$                     S\\R"                     S\\   S\\   S\\   S\\   S\\\4   4S jj5       r\S\\\R                        S\R                  S\\\R                        4S j5       rSrU =r$ )r  i  c                 h  > [         TU ]  U5        Xl        [        U R                  5      U l        [
        R                  " U R                  R                  5      U l        [
        R                  " U R                  R                  U R                  R                  SS9U l        U R                  5         g )NTr   )r   r   r   r  modelr	   r^  r   
final_normr   rq  lm_headr  r  s     r*   r   ClvpForCausalLM.__init__  st     t{{+
,,t{{'>'>?yy!8!8$++:P:PW[\ 	r,   c                 B    U R                   R                  R                  $ r  r!  r  r  r   s    r*   r  $ClvpForCausalLM.get_input_embeddings  s    zz!!444r,   c                 8    XR                   R                  l        g r  r&  r  s     r*   r  $ClvpForCausalLM.set_input_embeddings  s    0>

-r,   inputsr[   model_kwargsr!   c                 ~   U R                   nUR                  5        VVs0 s H  u  pVUc  M
  XV_M     nnnUR                  US5      nUb  Ub  [        SU SU SU SU S3	5      eUb  UnUS:X  a  SU;   a  U R	                  XUS	9US'   US   SpAUR                  S
S5      nUGb  U R                  R                  R                  [        R                  " UR                  S   S4U R                  R                  UR                  S95      n	XR                  R                  R                  [        R                  " UR                  S   S4SUR                  S95      -  n	[        R                   " X/SS9n[#        US5      (       a&  US   R%                  5       R'                  S5      S-
  n
O<[        R(                  " SUR                  S   [        R$                  UR                  S9n
U
R+                  S5      R-                  UR                  S   S5      n
XR                  R                  R                  U
5      -
  US'   [        R.                  " US   R                  S   S4[        R$                  U R                  S9U R                  R                  -  US'   US   SU4$ U R	                  XU5      nXU4$ s  snnf )zD
This function extracts the model-specific `inputs` for generation.
Nz
`inputs`: z` were passed alongside z/ which is not allowed.Make sure to either pass z or z=...rX   r  )r+  conditioning_embedsr   r   )
fill_valuer$   r6   rY   r4   rN   )main_input_namer  popr   *_maybe_initialize_input_ids_for_generationgetr!  r  r  r'   fullr8   r   r[   r$   r  r  r   rI  r  r(   r?   r  r   )r   r*  r[   r+  
input_namerA   rB   inputs_kwargr-  mel_start_token_embeddingrE   s              r*   _prepare_model_inputs%ClvpForCausalLM._prepare_model_inputs  s    ))
)5););)=O)=)=O#''
D9#(:VH$<ZL I,,284
|4I  %!F$L)H(,(W(W< )X )L% ".o!>J +../DdK*(,

(:(:(M(M

(..q115#{{77.55)% &););)Q)Q

/55a8!<SfSmSmn* % #(,,0C/_ef"g |%566+,<=BBDKKBORSS$||*0035::NaNhNh  (11!4;;<O<U<UVW<XZ[\L,?**BTBTBjBjC -L) 

L9??BAFejjaealalm++**+ %
  0/<OO@@Wcd<//m Ps
   	J9J9c                    UR                   S   nUR                  SS 5      nU(       ad  US   S   R                   S   nUR                   S   U:  a  Un	OUR                   S   S-
  n	US S 2U	S 24   nUb  US S 2UR                   S   * S 24   nUR                  SS 5      n
UR                  SS 5      nU
bZ  UcW  U
R                  5       R                  S5      S-
  nUR	                  U
S:H  S5        U(       a  US S 2S4   R                  S5      nOS nUb2  Ub/  [        R                  " U/[        R                  UR                  S9nUb  Uc  S	U0nOS
U0nUR                  UUR                  S5      UUS.5        U$ )Nr4   r  r   r5   r   rY   rE   rN   r  rX   r   )r  r   rE   r  )
r8   r2  rI  r  masked_fill_r?   r'   rW   r$   update)r   rX   r  r  r-  kwargsinput_ids_lengthr  past_lengthremove_prefix_lengthrY   rE   model_inputss                r*   prepare_inputs_for_generation-ClvpForCausalLM.prepare_inputs_for_generation<  s   
 %??2.$4d;)!,Q/55a8K q!K/'2$ (1q'9A'=$!!%9%:":;I)!/IOOA4F3F3H0H!I$4d;zz.$7%,*>)..077;a?L%%n&91=+ArE2<<R@L*/J <<)9(:%**U^UeUefL $)@+];L'3L#2#ZZ4 ,"0		
 r,   rX   r  rY   r  rE   r   r  labelsr   r   r  r  c                     U
b  U
OU R                   R                  n
Ub  UOU R                   R                  nU	b  U	OU R                   R                  n	Ub  UOU R                   R                  nU R                  UUUUUUUU	U
UUS9nUS   nU R                  U5      nU R                  U5      nSnUb  UR                  UR                  5      nUSSS2SS24   R                  5       nUSSS24   R                  5       n[        5       nU" UR                  SUR                  S5      5      UR                  S5      5      nU(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                   UR"                  UR$                  S9$ )a  
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
    Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
    `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
    are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
N)rX   r  rY   r  rE   r   r  r   r   r  r  r   .r4   r   )rx   r    r  rj   rk   r  )r   r   r  r   r  r!  r"  r#  r   r$   r   r
   r   r   r   r  rj   rk   r  )r   rX   r  rY   r  rE   r   r  rC  r   r   r  r  r,  rj   	lm_logitsrx   shift_logitsshift_labelsloss_fctrL  s                        r*   r   ClvpForCausalLM.forwardq  s   . 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]**+))%'/!5#  
  
OOM2	LL+	YYy//0F$S#2#q[1<<>L!#qr'?557L')HL--b,2C2CB2GH,J[J[\^J_`D\GABK/F)-)9TGf$EvE0#33!//))$55
 	
r,   beam_idxc                 .   ^ [        U4S jU  5       5      $ )z
This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
[`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
beam_idx at every generation step.
c              3   N   >#    U  H  n[        U4S  jU 5       5      v   M     g7f)c              3   x   >#    U  H/  oR                  S TR                  UR                  5      5      v   M1     g7f)r   N)index_selectr   r$   )r  
past_staterJ  s     r*   r  ;ClvpForCausalLM._reorder_cache.<locals>.<genexpr>.<genexpr>  s1     j_iQ[))!X[[9J9J-KLL_is   7:Nr   )r  
layer_pastrJ  s     r*   r  1ClvpForCausalLM._reorder_cache.<locals>.<genexpr>  s'      
-
 j_ijjj-s   "%rQ  )r  rJ  s    `r*   _reorder_cacheClvpForCausalLM._reorder_cache  s      
-
 
 	
r,   )r   r"  r#  r!  r  )NNNNNNNNNNNN)rm   rn   ro   rp   r   r  r  r   r'   r  r  r   strr   r7  rA  r   r   rr   r   r   r   r   staticmethodrT  rt   r   r   s   @r*   r  r    s.   
5?
 *.&*:>	A0&A0 smA0 tC$567	A0
 
u||Xc]Dell1B,CC	DA0H X\3j  15@D6:59371559-1$(,0/3&*E
E,,-E
 "%ell(;"<=E
 !!2!23	E

 !!1!12E
 u//0E
 E--.E
   1 12E
 ))*E
 D>E
 $D>E
 'tnE
 d^E
 
u77	8E
 E
N 
uU\\23
?D||
	uU\\"	#
 
r,   r  z`
    The composite CLVP model with a text encoder, speech encoder and speech decoder model.
    c                   v  ^  \ rS rSr\rS\4U 4S jjrS\R                  S\R                  4S jr	   SS\
\R                     S\
\R                     S	\
\R                     S\R                  4S
 jjr      SS\
\R                     S\
\R                     S\
\R                     S\
\R                     S	\
\R                     S\
\   S\R                  4S jjr\         SS\
\R                     S\
\R                     S\
\R                     S\
\R                     S	\
\R                     S\
\   S\
\   S\
\   S\
\   S\\\4   4S jj5       r\R,                  " 5             SS\
\R                     S\
\R                     S	\
\R                     S\
\   S\
\   S\
\   4S jj5       rSrU =r$ )!ClvpModelForConditionalGenerationi  r   c                   > [         TU ]  U5        [        UR                  [        5      (       d"  [        S[        UR                  5       S35      e[        UR                  [        5      (       d"  [        S[        UR                  5       S35      e[        UR                  [        5      (       d"  [        S[        UR                  5       S35      e[        U5      U l        [        UR                  5      U l        [        UR                  5      U l        [        UR                  5      U l        ["        R$                  " [&        R(                  " U R*                  R,                  5      5      U l        U R1                  5         g )NzPconfig.text_config is expected to be of type `ClvpEncoderConfig` but is of type .zRconfig.speech_config is expected to be of type `ClvpEncoderConfig` but is of type zSconfig.decoder_config is expected to be of type `ClvpDecoderConfig` but is of type )r   r   r  rn  r   	TypeErrortypespeech_configro  r   rj  conditioning_encoderr  speech_decoder_modelr  text_encoder_modelspeech_encoder_modelr	   r   r'   rW   r   logit_scale_init_valuelogit_scaler  r  s     r*   r   *ClvpModelForConditionalGeneration.__init__  sF    &,,.?@@++,-Q0 
 &..0ABB--./q2 
 &//1BCC../03 
 %<F$C!$3F4I4I$J!"-f.@.@"A$/0D0D$E!<<T[[5W5W(XY 	r,   ry   r!   c                 B   U R                   R                  R                  nUSS2SS24   n[        R                  " XR
                  R                   R                  :H  SS5      n[        R                  " XR                  5       US   S9n[        U5       H  u  pEUR                  5       S:X  a  M  UR                  5       nUS   XUS24'   US-
  UR                  S   :  d  MN  [        R                  " USS /UR                  [        R                  S9XSS24'   M     U$ )z
This method modifies the output of the decoder model, such as replacing the `eos_token_id` and changing the
last few tokens of each sequence.

Args:
    speech_ids (`torch.LongTensor`):
        This refers to the output of the decoder model.
Nr   r   )maskrM   r   )r$   rO   )r   ro  decoder_fixing_codesr'   rT   r`  r\   masked_fillr   rR   rS   argmaxr8   rW   r$   rI  )r   ry   ri  stop_token_indicesr`   each_seq_stop_token_indexstms          r*   fix_speech_decoder_output;ClvpModelForConditionalGeneration.fix_speech_decoder_output  s     ${{99NN12&
"[[7P7P7W7W7d7d)dfgijk&&z8O8O8QYmnoYpq
,56H,I(A ),,.!3+224C"6q"9J#$wQw))!,,%*\\)!"-.z7H7HPUPZPZ&
bc6" -J r,   rX   text_encoder_inputs_embedsrY   c                 .    U R                  UUUS9nUS   $ )a  
This method can be used to extract text_embeds from a text. The text embeddings obtained by applying the
projection layer to the pooled output of the CLVP text encoder model.

Args:
    input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
        Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
        provide it.

        [What are input IDs?](../glossary#input-ids)
    text_encoder_inputs_embeds (`torch.FloatTensor`, *optional*):
        inputs_embeds for the text encoder model passed in place of `input_ids`.
    attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
        Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

        - 1 for tokens that are **not masked**,
        - 0 for tokens that are **masked**.

        [What are attention masks?](../glossary#attention-mask)

Returns:
    `torch.FloatTensor` of shape `(batch_size, output_dim)`:
        The text embeddings obtained by applying the projection layer to the pooled output of the CLVP Text
        Model.

Examples:

```python
>>> from transformers import ClvpProcessor, ClvpModelForConditionalGeneration

>>> # Define the Text
>>> text = "This is an example text."

>>> # Define processor and model
>>> processor = ClvpProcessor.from_pretrained("susnato/clvp_dev")
>>> model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev")

>>> # Generate processor output and text embeds
>>> processor_output = processor(text=text, return_tensors="pt")
>>> text_embeds = model.get_text_features(input_ids=processor_output["input_ids"])
```
)rX   r  rY   r   )ra  )r   rX   rq  rY   r,  s        r*   get_text_features3ClvpModelForConditionalGeneration.get_text_features  s/    b ))4) * 
 qzr,   r  "conditioning_encoder_inputs_embedsgeneration_configc                    Ucu  Uc  Ub  Uc  [        S5      eUc  U R                  nUR                  " S0 UD6  U R                  UUUUS9nU R                  R                  UUS9nU R                  US   5      nU R                  UUS9n	U	S   $ )a  
This method can be used to extract speech_embeds. The speech embeddings are obtained by applying the speech
model on speech_ids. If speech_ids is not present but both input_ids and input_features are given then the
decoder model will be used to first generate the speech_ids and then applying the speech model.

Args:
    speech_ids (`torch.LongTensor` of shape `(batch_size, num_speech_ids)`, *optional*):
        Speech Tokens. Padding will be ignored by default should you provide it. If speech_ids are provided
        then input_ids and input_features will be automatically ignored.
    input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
        Input text Tokens. Processed from the [`ClvpTokenizer`]. If speech_ids is not provided, then input_ids
        and input_features will be used.
    input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, time_dim)`, *optional*):
        Indicates log-melspectrogram representations for audio returned by [`ClvpFeatureExtractor`]. If
        speech_ids is not provided, then input_ids and input_features will be used.
    conditioning_encoder_inputs_embeds (`torch.FloatTensor`, *optional*):
        inputs_embeds for `ClvpConditioningEncoder`. Can be used in place of `input_ids`.
    attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
        Mask to avoid performing attention on padding speech token indices. Mask values selected in `[0, 1]`:

        - 1 for tokens that are **not masked**,
        - 0 for tokens that are **masked**.

        [What are attention masks?](../glossary#attention-mask)
    generation_config (`GenerationConfig`, *optional*):
        generation config to control the generation of speech_ids if they are not provided.

Returns:
    `torch.FloatTensor` of shape `(batch_size, output_dim)`:
        The speech embeddings obtained by applying the projection layer to the pooled output of the CLVP Speech
        Model.

Examples:

```python
>>> import datasets
>>> from transformers import ClvpProcessor, ClvpModelForConditionalGeneration

>>> # Define the Text and Load the Audio (We are taking an audio example from HuggingFace Hub using `datasets` library)
>>> text = "This is an example text."
>>> ds = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", datasets.Audio(sampling_rate=22050))
>>> _, audio, sr = ds.sort("id").select(range(1))[:1]["audio"][0].values()

>>> # Define processor and model
>>> processor = ClvpProcessor.from_pretrained("susnato/clvp_dev")
>>> model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev")

>>> # Generate processor output and model output
>>> processor_output = processor(raw_speech=audio, sampling_rate=sr, text=text, return_tensors="pt")
>>> speech_embeds = model.get_speech_features(
...     input_ids=processor_output["input_ids"], input_features=processor_output["input_features"]
... )
```
zfEither speech_ids or input_ids/conditioning_encoder_inputs_embeds and input_features must be provided.r  rX   r  rY   )r-  rv  r   )rX   rY   rl   )r   rv  r;  r_  r`  generatero  rb  )
r   ry   rX   r  ru  rY   rv  r<  r-  r,  s
             r*   get_speech_features5ClvpModelForConditionalGeneration.get_speech_featuresJ  s    D !&H&PUcUk |  !($($:$:!$$.v."&";";-#@-	 #< # 22;;$7"3 < J
 77
1FJ++ ) , 

 qzr,   return_lossr  r   r  c
                 t   Ub  UOU R                   R                  nU	b  U	OU R                   R                  n	U R                  UUUUS9n
U R	                  U
UU	S9nUS   nUR
                  S:X  a  UR                  S5      nU R                  U5      nU R                  UUU	S9nU R                  UUUUU	S9nUS   nUS   nXR                  SS	S
S9-  nUUR                  SS	S
S9-  nU R                  R                  5       n[        R                  " UUR                  5       5      U-  nUR                  5       nSnU(       a  [!        U5      nU	(       d1  UUUUUS   US   4nU(       a  UUS	   US	   US	   4-  nUb  U4U-   $ U$ [#        UUUUUUS   US   UR$                  UR$                  UR$                  S9
$ )a2  
input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, time_dim)`):
    Indicates log mel-spectrogram representations for audio returned by [`ClvpFeatureExtractor`].
conditioning_encoder_inputs_embeds (`torch.FloatTensor`, *optional*):
    inputs_embeds for `ClvpConditioningEncoder`. Can be used in place of `input_ids`.
text_encoder_inputs_embeds (`torch.FloatTensor`, *optional*):
    inputs_embeds for the text encoder model passed in place of `input_ids`.
return_loss (`bool`, *optional*):
    Whether or not to return the contrastive loss.

Examples:

```python
>>> import datasets
>>> from transformers import ClvpProcessor, ClvpModelForConditionalGeneration

>>> # Define the Text and Load the Audio (We are taking an audio example from HuggingFace Hub using `datasets` library)
>>> text = "This is an example text."

>>> ds = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", datasets.Audio(sampling_rate=22050))
>>> _, audio, sr = ds.sort("id").select(range(1))[:1]["audio"][0].values()

>>> # Define processor and model
>>> processor = ClvpProcessor.from_pretrained("susnato/clvp_dev")
>>> model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev")

>>> # processor outputs and model outputs
>>> processor_output = processor(raw_speech=audio, sampling_rate=sr, text=text, return_tensors="pt")
>>> outputs = model(
...     input_ids=processor_output["input_ids"],
...     input_features=processor_output["input_features"],
...     return_dict=True,
... )
```
Nrx  )r  r  r  r   r   r5   rX   r  r  )rX   r  rY   r  r  r4   Tr   r7   r   )
rx   rz   r{   r|   r}   r~   r   r   r   r   )r   r  r  r_  r`  ndimrk  ro  rb  ra  normrd  expr'   r   r/   r2   rv   rj   )r   rX   r  ru  rq  rY   r|  r  r   r  r-  r  ry   speech_outputstext_outputsr}   r|   rd  r{   rz   rx   rL  s                         r*   r   )ClvpModelForConditionalGeneration.forward  sH   h %9$D $++JjJj 	 &1%<k$++B]B]"77)<)	 8 
 33-!5# 4 
 %Q'
 ??a#**1-J33J?
22 !5# 3 
 ..4)!5# / 
 'q)"1o &(:(:QBPT(:(UU!K$4$4qb$$4$OO &&**,,,{MOO4EFT+--/_-D!Qq!F $#B' $"2&  *.)9TGf$EvE/+#'*1o .q 1"1"?"?'3'A'A)7)E)E
 	
r,   pad_to_max_mel_tokensc                    UR                   S   nXR                  R                  R                  S-
  :  a2  [	        SU SU R                  R                  R                  S-
   35      eUc  U R
                  n[        R                  " U5      nUR                  " S0 UD6n	UR                  5         U R                  U	R                  5       5        [        UUSU R                  R                  R                  U R                  R                  R                  S9u  pU R                  UUUS9n
U R                   R#                  U
UUUR$                  S9n['        U[(        5      (       a  UR*                  nUbQ  UWR                   S   -
  n[,        R.                  R0                  R3                  US	U4U R
                  R                  S
9nU R5                  W5      nU R7                  UUUR$                  S9nU R9                  UUUUR$                  S9nUS	   nUS	   nUUR;                  SSSS9-  nUUR;                  SSSS9-  nU R<                  R?                  5       n[,        R@                  " UURC                  5       5      U-  nURC                  5       nUR$                  (       d)  UUUUUUS   US   4nU(       a  UUS   US   US   4-  nU$ [E        UUUUUUS   US   URF                  URF                  URF                  S9
$ )aE	  
Generate method for `ClvpModelForConditionalGeneration`, this method calls the `generate` method of
`ClvpForCausalLM` and then uses those generated `speech_ids` to process `text_embeds` and `speech_embeds` using
`ClvpEncoder`.

Args:
    input_ids (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
        Input text Tokens. Processed from the [`ClvpTokenizer`].
    input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, time_dim)`, *optional*):
        Indicates log-melspectrogram representations for audio returned by [`ClvpFeatureExtractor`].
    attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
        Mask to avoid performing attention on padding text token indices. Mask values selected in `[0, 1]`:

        - 1 for tokens that are **not masked**,
        - 0 for tokens that are **masked**.

        [What are attention masks?](../glossary#attention-mask)
    generation_config (`~generation.GenerationConfig`, *optional*):
        The generation configuration to be used as base parametrization for the generation call. `**kwargs`
        passed to generate matching the attributes of `generation_config` will override them. If
        `generation_config` is not provided, the default will be used, which had the following loading
        priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
        configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
        default values, whose documentation should be checked to parameterize generation.
    pad_to_max_mel_tokens (`int`, *optional*):
        Pads generated speech_ids to the specified value. This is to implement the same logic from the official
        repo, link: https://github.com/neonbjb/tortoise-tts/blob/80f89987a5abda5e2b082618cd74f9c7411141dc/tortoise/api.py#L430
        and to make sure the logits are same.
        This does not affect generation quality so please don't consider using it since it is less efficient.
    output_hidden_states (`bool`, *optional*):
        Whether or not to return the hidden states of decoder model, text encoder and speech encoder models.

Returns:
    `ClvpOutput` or tuple: A `ClvpOutput` (if `return_dict_in_generate=True` or when
    `config.return_dict_in_generate=True`) or a tuple.
r4   r   z;Maximum sequence length reached! Found input_ids of length z:.Please make sure that the maximum length of input_ids is F)r]   r[   r\   )r  rX   rY   )r-  rv  r  r  r   rL   r~  )rX   rY   r  r  r5   Tr  )
ry   rz   r{   r|   r}   r~   r   r   r   r   rl   )$r8   r   ro  rs  r   rv  copydeepcopyr;  validate_validate_model_kwargsrc   rn  r[   r\   r_  r`  ry  return_dict_in_generater  r   	sequencesr'   r	   r%   rP   ro  rb  ra  r  rd  r  r   r/   rv   rj   )r   rX   r  rY   rv  r  r  r<  r   r+  r-  r  ry   padding_neededr  r  r}   r|   rd  r{   rz   rL  s                         r*   ry  *ClvpModelForConditionalGeneration.generate5  sY   f $//"-kk88HH1LMMoM^ _LLPKKLfLfLvLvyzLzK{} 
 $ $ 6 6 MM*;<(//9&9""$##L$5$5$78 %>00==00==%
!	 #77)) 8 
 33<< 3/!5)AA	 = 
 o{33(22J !,2Z5E5Eb5IIN,,00Q/t7M7M7Z7Z 1 J 33J?
22 !5)AA 3 

 ..)!5)AA	 / 
 'q)"1o &(:(:QBPT(:(UU!K$4$4qb$$4$OO &&**,,,{MOO4EFT+--/ 88!Qq!F $#B' $"2&  M!/+#'*1o .q 1"1"?"?'3'A'A)7)E)E
 	
r,   )r_  rd  r`  rb  ra  r  )NNNNNN)	NNNNNNNFN)rm   rn   ro   rp   r   r  r   r'   r   ro  r   rr   rs  r  r   rz  r   r   r   r   rv   r   no_gradr  ry  rt   r   r   s   @r*   rY  rY    s    Lz FE4D4D IYIY @ 15BF59	7E,,-7 %-U->->$?7 !!1!12	7
 
		7v 26046:JN158<_U--._ E,,-_ !!2!23	_
 -5U5F5F,G_ !._ $$45_ 
		_B  156:JNBF59&*/3,1&*G
E,,-G
 !!2!23G
 -5U5F5F,G	G

 %-U->->$?G
 !!1!12G
 d^G
 'tnG
 $D>G
 d^G
 
uj 	!G
 G
R ]]_ 156:598</3/3Z
E,,-Z
 !!2!23Z
 !!1!12	Z

 $$45Z
  (}Z
 'tnZ
 Z
r,   rY  )rY  r  r  r  r  r  )r   )Nr      r   TT)Hrq   r  r  dataclassesr   typingr   r   r   r   r   r'   torch.utils.checkpointr	   torch.nnr
   activationsr   r   
generationr   r   modeling_attn_mask_utilsr   r   modeling_outputsr   r   r   r   modeling_utilsr   pytorch_utilsr   r   r  r   r   r   configuration_clvpr   r   r   
get_loggerrm   r   r  r+   r2   r=   rJ   rc   re   rv   Moduler   r   r   r  r  r   r/  rO  rZ  rj  r  r  r  r  r  rY  __all__rl   r,   r*   <module>r     se       ! 9 9    % 1 ; e  . 6 
  
		H	%`U\\ `ell `
.%,, .5<< .(%> (.V : : :: )E )E )EZJ")) J(7BII 7<}2		 }2@8")) 8 RYY (;ryy ;~`")) `HRYY "1ryy 1hG<bii G<T $*/ $* $*NY
% Y
xp
% p
f @
# @
 @
F 
_
)? _

_
D 
C
(;_ C

C
Lr,   