
    gd                    Z   d Z ddlZddlZddlmZ ddlmZmZmZm	Z	 ddl
Z
ddlZ
ddl
mZ ddlmZ ddlmZ dd	lmZmZ dd
lmZmZ ddlmZmZmZmZ ddlmZmZ ddlm Z m!Z! ddl"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)m*Z*m+Z+  e&j,        e-          Z.dZ/de
j0        de
j0        fdZ1de
j0        de
j0        fdZ2d Z3dDdZ4	 	 	 	 	 	 dEdZ5e G d de#                      Z6e G d de#                      Z7 G d  d!ej8                  Z9 G d" d#ej8                  Z: G d$ d%ej8                  Z; G d& d'ej8                  Z< G d( d)ej8                  Z= G d* d+ej8                  Z> G d, d-ej8                  Z? G d. d/ej8                  Z@ G d0 d1ej8                  ZA G d2 d3e          ZBd4ZCd5ZDd6ZE G d7 d8eB          ZF G d9 d:eB          ZG e$d;eC           G d< d=eB                      ZH e$d>eC           G d? d@eBe                      ZI e$dAeC           G dB dCeBe                      ZJdS )FzPyTorch CLVP model.    N)	dataclass)DictOptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)GenerationConfigGenerationMixin)_prepare_4d_attention_mask!_prepare_4d_causal_attention_mask)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsBaseModelOutputWithPooling!CausalLMOutputWithCrossAttentions)PreTrainedModelSequenceSummary)Conv1Disin_mps_friendly)ModelOutputadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )
ClvpConfigClvpDecoderConfigClvpEncoderConfigzsusnato/clvp_devlogitsreturnc                     t           j                            | t          j        t          |           | j                            S )Ndevice)r   
functionalcross_entropytorcharangelenr%   )r!   s    b/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/clvp/modeling_clvp.pycontrastive_lossr,   ;   s3    =&&vu|CKKPVP]/^/^/^___    
similarityc                 r    t          |           }t          |                                           }||z   dz  S )Ng       @)r,   t)r.   caption_lossspeech_losss      r+   	clvp_lossr3   @   s4    #J//L":<<>>22K;&#--r-   c                     | dd| j         d         dz  f         }| d| j         d         dz  df         }t          j        | |fd          S )z*Rotates half the hidden dims of the input..N   dim)shaper(   cat)xx1x2s      r+   rotate_halfr>   G   s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r-   c                    ||                              |          }||                              |          }| |z  t          |           |z  z   }||z  t          |          |z  z   }||z  t          |          |z  z   }	|||	fS )an  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_embrK   N   s    * l

%
%m
4
4C
l

%
%m
4
4C3w;q>>C/0G3w;q>>C/0G3w;q>>C/0GGW$$r-      Tc                 6   |rRt           j        j                            | d|          } |'t           j        j                            |dd          n|}| }|r=t          j        | j        d         | j        d         dz   f| j        | j                  }t          |           D ]\  }}	t          |	|          
                                rut          j        |	|k              d                                         }
t          j        |	d|
         t          j        |g| j                  |	|
d         g          ||<   t           j        j                            |	d|          ||<   |'t           j        j                            |dd          n|}||fS )	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zerosr9   rQ   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_tokensre   k   s     
H'++Iv\+RR	HVHbEH##NF!#DDDhv 	 # 
"[_Q!3a!78	XaXh
 
 
 !*) 4 4 		k 		kA} ==AACC kk-<"?@@CGGII(-(9"4C4(%,~iN^*_*_*_anorososatu) )"1%%
 ).(;(?(?v]i(?(j(j"1%%HVHbEH##NF!#DDDhv 	 ~--r-   c                       e Zd ZU dZdZeej                 ed<   dZ	ej        ed<   dZ
eej                 ed<   dZeeej                          ed<   dZeeej                          ed<   dS )ClvpEncoderOutputak  
    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____doc__rh   r   r(   FloatTensor__annotations__ri   rj   rk   r   rl    r-   r+   rg   rg      s          * +/FHU&'...+/u(///15M8E-.5558<M8E%"345<<<59Ju01299999r-   rg   c                       e Zd ZU dZdZeej                 ed<   dZ	eej
                 ed<   dZej        ed<   dZej        ed<   dZej        ed<   dZej        ed<   dZeed	<   dZeed
<   dZej        ed<   dZej        ed<   dZej        ed<   dS )
ClvpOutputai  
    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_states)rm   rn   ro   rp   rv   r   r(   rq   rr   rw   
LongTensorrx   ry   rz   r{   r|   r   r}   r~   r   r   rs   r-   r+   ru   ru      s          < )-D(5$
%,,,-1J)*111+/u(///)-OU&---%)K")))'+M5$+++4818886:3:::/35,33348 18886: %"3:::::r-   ru   c                   ,     e Zd Zd fd	Zd Zd Z xZS )ClvpRMSNormư>c                     t                                                       t          j        t	          j        |                    | _        || _        dS )z:
        ClvpRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parameterr(   onesweightvariance_epsilon)selfhidden_sizeeps	__class__s      r+   r   zClvpRMSNorm.__init__   sD     	l5:k#:#:;; #r-   c                    |j         }|                    t          j                  }|                    d                              dd          }|t          j        || j        z             z  }| j        |                    |          z  S )Nr6   r5   T)keepdim)	rQ   tor(   float32powmeanrsqrtr   r   )r   rk   input_dtypevariances       r+   forwardzClvpRMSNorm.forward   s|    #)%((77 $$Q'',,R,>>%Ht?T4T(U(UU{]--k::::r-   c                 H    t          | j        j                   d| j         S )Nz, eps=)tupler   r9   r   r   s    r+   
extra_reprzClvpRMSNorm.extra_repr   s&    )**II$2GIIIr-   )r   )rm   rn   ro   r   r   r   __classcell__r   s   @r+   r   r      sb        $ $ $ $ $ $; ; ;J J J J J J Jr-   r   c                   F     e Zd ZdZ fdZdej        dej        fdZ xZS )ClvpRotaryPositionalEmbeddingz
    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                 J   t                                                       t          |j        |j        dz  z  d          }ddt          j        d|dt
          j                                                  |z  z  z  }| 	                    d|           d | _
        d | _        d S )Nr6             ?i'  r   rQ   inv_freq)r   r   maxprojection_dimnum_attention_headsr(   r)   int64floatregister_buffercached_sequence_length"cached_rotary_positional_embedding)r   configr8   r   r   s       r+   r   z&ClvpRotaryPositionalEmbedding.__init__   s    &'F,F,JKRPP%ELC%+$N$N$N$T$T$V$VY\$\]^Z222&*#26///r-   rk   r"   c                 j   |j         d         }|| j        k    r| j        | j        S || _        t          j        ||j                                      | j                  }t          j        d|| j                  }t          j	        ||fd          }|
                    d          | _        | j        S )Nr   r$   zi,j->ijr5   r7   r   )r9   r   r   r(   r)   r%   type_asr   einsumr:   r@   )r   rk   sequence_lengthtime_stampsfreqs
embeddingss         r+   r   z%ClvpRotaryPositionalEmbedding.forward  s    '-a0d999d>e>q::&5#l?=;OPPPXXY]YfggYT]CCYu~2666
2<2F2Fq2I2I/66r-   	rm   rn   ro   rp   r   r(   rq   r   r   r   s   @r+   r   r      sj         
7 7 7 7 77U%6 75;L 7 7 7 7 7 7 7 7r-   r   c                   l    e Zd ZdZ fdZdej        dedefdZ	 	 	 	 	 	 	 dd	ej	        d
e
ej	                 de
ej                 de
ej                 de
eej                          de
e         de
ej	                 de
e         deej	        e
ej	                 e
eej	                          f         fdZ xZS )ClvpSelfAttentionzu
    Multi-headed attention to combine Absolute and Rotary Positional Embeddings into a single Attention module.
    c                    t                                                       || _        |j        | _        |j        | _        | j        | j        z  | _        | j        | j        z  | j        k    r t          d| j         d| j         d          | j        dz  | _	        |j
        | _        t          |d          rk|j        }t          j        t          j        ||ft          j                            }|                    dd||          }|                     d|d	
           t)          j        | j        | j        |j                  | _        t)          j        | j        | j        |j                  | _        t)          j        | j        | j        |j                  | _        t)          j        | j        | j                  | _        d S )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   zClvpSelfAttention.__init__  s   +3$.8=4>)T^;;'dn ' 'N' ' '   ]D(
/6455 	A":M:ej-)GuzZZZ[[D99Q=-@@D  % @@@iVE^___iVE^___iVE^___	$.$.AAr-   rY   seq_lenbszc                     |                     ||| j        | j                                      dd                                          S )Nr   r6   )r   r   r   	transpose
contiguous)r   rY   r   r   s       r+   _shapezClvpSelfAttention._shape3  s<    {{3GGQQRSUVWWbbdddr-   NFrk   rotary_pos_embr[   rF   past_key_value	use_cache	head_maskoutput_attentionsr"   c	                 b   ||t          d          |                                \  }	}
}|                     |                     |          d|	          | j        z  }|                     |                     |          d|	          }|                     |                     |          d|	          }|5|\  }}t          j        ||fd          }t          j        ||fd          }|du r||f}nd }||j	        d         }|dd |f         |d|d f         }}|dd |f         |d|d f         }}|dd |f         |d|d f         }}|
                                                    d          |                                                    d          }}t          ||||||          \  }}}t          j        ||fd          }t          j        ||fd          }t          j        ||fd          }|j	        d         }|j	        d         }t          j        ||                    dd	                    }|L|                                |	d
||fk    r+t          d|	d
||f d|                                           ||z   }t           j                            |d          }|||z  }t           j                            || j        | j                  }t          j        ||          }|                                |	| j        || j        fk    r5t          d|	| j        || j        f d|                                           |                    d
d                                          }|                    |	|| j                  }|                     |          }|sd }|||fS )NzB`position_ids` must be provided when `rotary_pos_emb` is not None.r5   r7   T.r   r6   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(   r:   r9   rD   squeezerE   rK   matmulr   r   r&   softmaxr   r   r   r   r   reshaper   r   ) r   rk   r   r[   rF   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_passrD   rE   tgt_lensrc_lenattn_weights
attn_probsattn_outputs                                    r+   r   zClvpSelfAttention.forward6  s     %,*>abbb)..00Q	 {{4;;}#=#=r3GG$*T[[]!;!;REE
{{4;;}#=#=r3GG%#1 HjHj#9rBBBJ 9j,%?RHHHL!<0GGG%+1"5N S/>/12S.//12 "I
 3/03/0 G
 S/>/12S.//12 "I
 &))++33A668J8J8L8L8T8TUV8W8WC,@GU^`cehjv,w,w)Iw	 !9i%<"EEELGX#6B???J 9i%<"EEEL$Q'"1%|L*2F2Fq!2L2LMM%""$$a'(BBB ta'8Rtt]k]p]p]r]rtt   (.8L},,\r,BB  ')3L]**<4<RVR_*``
l:|<<#t~w!NNN)CRVR_3` ) )$$&&) )  
 "++Aq11<<>>!))#wGGmmK00  	 LG\11r-   )NNNNFNF)rm   rn   ro   rp   r   r(   Tensorintr   rq   r   r   r   r   r   r   r   s   @r+   r   r     sn        B B B B B4eU\ eC ec e e e e 7;59378<$)15,1\2 \2(\2 !!23\2 !!12	\2
 u/0\2 !u|!45\2 D>\2 E-.\2 $D>\2 
u (5+<"=xeN_H`?aa	b\2 \2 \2 \2 \2 \2 \2 \2r-   r   c                   F     e Zd ZdZ fdZdej        dej        fdZ xZS )ClvpGatedLinearUnitz
    `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                                                       t          |j                 | _        t          j        |j        |j        dz            | _	        d S )Nr6   )
r   r   r   
hidden_actactivation_fnr   r   r   intermediate_sizeprojr   r   r   s     r+   r   zClvpGatedLinearUnit.__init__  sK    #F$56If0&2JQ2NOO			r-   rk   r"   c                     |                      |                              dd          \  }}||                     |          z  S )Nr6   r5   r7   )r  chunkr   )r   rk   gates      r+   r   zClvpGatedLinearUnit.forward  sD    "ii66<<QB<GGtt11$7777r-   r   r   s   @r+   r   r     so         
P P P P P
8U%6 85;L 8 8 8 8 8 8 8 8r-   r   c                   F     e Zd ZdZ fdZdej        dej        fdZ xZS )ClvpEncoderMLPzA
    This MLP is used in CLVP speech or text encoder models.
    c                    t                                                       || _        t          |          | _        t          j        |j        |j                  | _	        t          j
        |j                  | _        d S N)r   r   r   r   fc1r   r   r   r   fc2Dropoutr   dropout_layerr  s     r+   r   zClvpEncoderMLP.__init__  sb    &v..9V5v7IJJZ77r-   rk   r"   c                     |                      |          }|                     |          }|                     |          }|S r	  )r
  r  r  r   rk   s     r+   r   zClvpEncoderMLP.forward  s=    //**=99//r-   r   r   s   @r+   r  r    sj         8 8 8 8 8U%6 5;L        r-   r  c                        e Zd Zdef fdZ	 ddej        dej        dej        dej        dee	         d	e
ej                 fd
Z xZS )ClvpEncoderLayerr   c                 >   t                                                       || _        |j        | _        t          |          | _        t          |          | _        t          | j        |j
                  | _        t          | j        |j
                  | _        d S )Nr   )r   r   r   r   r   r   	self_attnr  mlpr   layer_norm_epsinput_rmsnormpost_attention_rmsnormr  s     r+   r   zClvpEncoderLayer.__init__  s    +*622!&))(V=RSSS&1$.fF[&\&\&\###r-   Frk   r   r[   rF   r   r"   c                    |}|                      |          }|                     |||||          }|d         }||z   }|}|                     |          }|                     |          }||z   }|f}|r||d         fz  }|S )a6  
        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.
        )rk   r   r[   rF   r   r   r5   )r  r  r  r  )	r   rk   r   r[   rF   r   residualattention_outputsoutputss	            r+   r   zClvpEncoderLayer.forward  s    , !**=99 NN'))%/ + 
 
 *!, =0 33MBB// =0 " 	0)"-//Gr-   )F)rm   rn   ro   r   r   r(   rq   r   r   r   r   r   r   r   s   @r+   r  r    s        ]z ] ] ] ] ] ]  -20 0(0 )0 (	0
 &0 $D>0 
u 	!0 0 0 0 0 0 0 0r-   r  c                   Z     e Zd Z fdZdeeej                          dej        fdZ xZ	S )ClvpDecoderMLPc                    t                                                       |j        }t          ||          | _        t          ||          | _        t          |j                 | _        t          j
        |j                  | _        d S r	  )r   r   r   r   c_fcc_projr   activation_functionactr   r  resid_pdropr   )r   r   r   r   r   s       r+   r   zClvpDecoderMLP.__init__  sl    &	,i88	Y(9::&45z&"455r-   rk   r"   c                     |                      |          }|                     |          }|                     |          }|                     |          }|S r	  )r   r#  r!  r   r  s     r+   r   zClvpDecoderMLP.forward  sL    		-00//M22]33r-   )
rm   rn   ro   r   r   r   r(   rq   r   r   r   s   @r+   r  r    sj        6 6 6 6 6XeE4E.F%G EL]        r-   r  c                   X    e Zd Z fdZ	 	 	 	 	 	 ddeeej                          deeej                          deej	                 deej	                 deej                 d	ee
         d
ee
         deeej                 eeej        eej        df         f                  f         fdZ xZS )ClvpDecoderLayerc                 N   t                                                       |j        }|j        |j        nd|z  }t	          j        ||j                  | _        t          |          | _	        t	          j        ||j                  | _
        t          ||          | _        d S )N   r  )r   r   r   n_innerr   	LayerNormlayer_norm_epsiloninput_layernormr   attnpost_attention_layernormr  r  )r   r   r   	inner_dimr   s       r+   r   zClvpDecoderLayer.__init__
  s    (&,n&@FNNa+o	!|KV=VWWW%f--	(*[fF_(`(`(`%!)V44r-   NFrk   r   r[   rF   r   r   r   r"   .c           	      *   |}|                      |          }|                     |||||||          }	|	d         }
|	dd          }|
|z   }|}|                     |          }|                     |          }||z   }|r|f|z   }n|f|dd          z   }|S )Nr   r[   rF   r   r   r   r   r   )r-  r.  r/  r  )r   rk   r   r[   rF   r   r   r   r  attn_outputsr   r  feed_forward_hidden_statess                r+   r   zClvpDecoderLayer.forward  s     !,,];;yy))%/ ! 
 
 #1oqrr"#h. 55mDD%)XXm%<%<" #== 	5$&0GG$&4Gr-   )NNNNFF)rm   rn   ro   r   r   r   r(   rq   r   r   r   r   r   r   r   s   @r+   r'  r'  	  s       	5 	5 	5 	5 	5 9=593715$),1% %e&7 89% !u|!45% !!12	%
 u/0% E-.% D>% $D>% 
uU\"HU5<uGXZ]G]A^3^-_$``	a% % % % % % % %r-   r'  c            
            e Zd ZdZdef fdZddedefdZ	 	 	 dd	ej	        d
e
ej                 de
ej	                 de
ej                 fdZ xZS )ClvpConditioningEncodera  
    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                                                       |j         _        |j         _        t	          j         j        j         j        j                   _        t	          j         j        j	         j        j                   _
        t	          j         j        j         j        j        d           _                              j        j                  t	          j         fdt!           j        j                  D                        _        t	          j         fdt!           j        j                  D                        _        d _        d S )Nr   )kernel_sizec                 T    g | ]$}t          j        j        j        d d          %S )gh㈵>T)r   affine)r   	GroupNormdecoder_configr   ).0r   
num_groupsr   s     r+   
<listcomp>z4ClvpConditioningEncoder.__init__.<locals>.<listcomp>Z  sC        Z)<)Hd[_```  r-   c                 8    g | ]}t          j                  S rs   )r   r<  r=  r   r   s     r+   r?  z4ClvpConditioningEncoder.__init__.<locals>.<listcomp>b  s%    lllt233lllr-   F)r   r   text_configr<  r   	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group_normsmel_attn_blocksgradient_checkpointing)r   r   r>  r   s   ` @r+   r   z ClvpConditioningEncoder.__init__J  sP   !-$3$&L1A1LdNaNm$n$n!')|/1D1P(
 (
$ 	$"5"BDDWDcqrsss 2243F3RSS
=    t2FGG  
 
  "}llllU4CVCj=k=klll 
  
 ',###r-   r   channelsgroupsc                     |dk    rd}n|dk    rd}||z  dk    rt          |dz            }||z  dk    |dk    rt          d| d          |S )a  
        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   r6   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   rR  rS  s      r+   rK  z0ClvpConditioningEncoder.compute_groupnorm_groupsg  s     r>>FF^^F1$$!__F 1$$ Q;;CX^ C C C  
 r-   Ninput_featuresrZ   inputs_embedsr[   c                 $   ||t          d          ||                                \  }}n1| |                                d d         \  }}nt          d          |(t          j        ||gt          j        |j                  }t          ||| j        j        | j        j	                  \  }}| 
                    |          }|                    d          dz
  }|                     |          }||z   }	| j        r| j        rt          j        j                            | j        |          }
t%          | j                  D ]\  }}|
                    dd          }t          j        j                            | j        |         |
                              dd          }
t          j        j                            ||
          d         |z   }
|
                    dd          }
n|                     |          }
t%          | j                  D ]o\  }}|
                    dd          } | j        |         |
                              dd          }
 ||
          d         |z   }
|
                    dd          }
p|
d d d d df         }
|
                    d          }
|	j        d         dk    r4|
j        d         dk    r#|	                    |
j        d         dd          }	n|	j        d         dk    r4|
j        d         dk    r#|
                    |	j        d         dd          }
nH|	j        d         |
j        d         k    r,t          d	|	j        d          d
|
j        d          d          t          j        |
|	gd          S )NDYou cannot specify both input_ids and inputs_embeds at the same timer5   5You have to specify either input_ids or inputs_embedsrP   )r]   r^   r   r6   r   z=The number of texts and number of audios must be same. Found z
 texts vs z audiosr7   )r   r   r(   r   longr%   re   rB  r]   r^   rE  cumsumrG  rQ  r   utils
checkpointrJ  rT   rP  r   rO  r@   r9   repeatconcat)r   rX  rZ   rY  r[   
batch_size
seq_lengthrF   position_embedsrz   mel_specrb   mel_attn_blockresidual_mel_specs                 r+   r   zClvpConditioningEncoder.forward|  s     ]%>cddd"%.^^%5%5"J

&%2%7%7%9%9#2#%>"J

TUUU !"ZZ(@
[d[klllN %>)6)6	%
 %
 %
!	> 11)<<%,,R001466|DD#o5& 	44= 	4{-88WWH%.t/C%D%D 4 4!>$,$6$6q!$<$<! ;1<<T=Ma=PRZ[[eefgijkk ;1<<^XVVWXY\mm#--a334 }}^44H%.t/C%D%D 4 4!>$,$6$6q!$<$<!.4+A.x88BB1aHH)>(33A69JJ#--a33AAAqqq!G$%%a(( Q1$$):a)?)?%,,X^A->1EEKKq!Q&&8>!+<+A+A{'8';QBBHHq!X^A%666T$*1-T T9A9JT T T  
 |X{3;;;;r-   )r   NNN)rm   rn   ro   rp   r   r   r   rK  r(   rq   r   r   r   r   r   s   @r+   r6  r6  =  s        
 
,z , , , , , ,:  c    0 155959H< H<)H< E,-H<   12	H<
 !!12H< H< H< H< H< H< H< H<r-   r6  c                   (    e Zd ZdZeZdZdZdZd Z	dS )ClvpPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    clvpTpast_key_valuesc           	      v   | j         j        }t          |t          j                  r&|j        j                            d|dz             nt          |t          j        t          t          j
        f          rK|j        j                            d|dz             |j        |j        j                                         nt          |t                    r| j         j        }|j         j        dz  d|j         j        z  dz  z  |z  }d|j         j        z  dz  |z  }t          j                            t#          |j        d          r|j        j        j        n|j        j        |           t          j                            |j        j        |           nCt          |t*                    rR| j                                         }|j        }|j        j        j                            d||j        dz  z             nt          |t0                    rJ|j        j        j                            d|           |j        j        j                                         n}t          |t4                    rh|                                D ]S\  }}|d	k    rH|j                            d| j         j        t;          j        d| j         j        z            z             Tt          |t          j                  r?|j        j                                         |j        j                             d
           dS dS )zInitialize the weightsg        g{Gz?)r   stdNr   r6   r  )ro  zc_proj.weightr   )!r   initializer_factor
isinstancer   rC  r   datanormal_r   r   rH  r   zero_r  r   num_hidden_layersinitgetattrr
  r  r  ClvpEncoderget_text_config
projectionr6  rJ  ClvpForCausalLMnamed_parametersinitializer_rangemathsqrtr+  fill_)r   modulefactorin_proj_stdfc_stdr   namer   s           r+   _init_weightsz!ClvpPreTrainedModel._init_weights  s   /fbl++ 	M&&CVd]&CCCCFBI >?? 	M&&CVd]&CCC{& &&(((// 	[3F!=4d:FMDc@chl?lmpvvK&-33<vEFGOOgfj&6Q6QhFJO22W]WaWhntOuuuGOOFJ-;O????,, 	[0022F.F$)11s&J\^bJb@c1dddd 788 	O"'//Sf/EEEO %++----00 	!2244  a?**FNN t{'DtyQRUYU`UrQrGsGs's #    fbl++ 	*K""$$$M$$S)))))	* 	*r-   N)
rm   rn   ro   rp   r   config_classbase_model_prefixsupports_gradient_checkpointing_skip_keys_device_placementr  rs   r-   r+   rk  rk    sF         
 L&*#"3* * * * *r-   rk  a=  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`ClvpConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

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

            [What are input IDs?](../glossary#input-ids)
        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`.
        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)
        return_loss (`bool`, *optional*):
            Whether or not to return the contrastive loss.
        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.
a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
            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)
        past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
            Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
            `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
            their past given to this model should not be passed as `input_ids` as they have already been computed.
        attention_mask (`torch.FloatTensor` 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**.

            If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
            `past_key_values`. In other words, the `attention_mask` always has to have the length:
            `len(past_key_values) + len(input_ids)`

            [What are attention masks?](../glossary#attention-mask)
        token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
            1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.

            [What are token type IDs?](../glossary#token-type-ids)
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.

            If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
            `past_key_values`).
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        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.
c                        e Zd ZdZdef fdZd Zd Z	 	 	 	 	 	 	 ddee	j
                 dee	j
                 d	ee	j
                 d
ee	j
                 dee         dee         dee         deeef         fdZ xZS )rx  z
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`ClvpEncoderLayer`].

    Args:
        config: ClvpConfig
    r   c                 >   t                                                     | _        t          j        j        j                  | _        j        rt                    nd | _
        t          j        fdt          j                  D                       | _        t                    | _        t          j        j        j                  | _        t          j        j        j        d          | _        d| _        |                                  d S )Nc                 .    g | ]}t                    S rs   )r  )r=  r   r   s     r+   r?  z(ClvpEncoder.__init__.<locals>.<listcomp>v  s"    $g$g$g!%5f%=%=$g$g$gr-   r  Fr   )r   r   r   r   rC  rD  r   token_embeddinguse_rotary_embeddingr   r   rL  rM  ru  layersr   sequence_summaryr+  r  final_layer_normr   r   rz  rQ  	post_initr  s    `r+   r   zClvpEncoder.__init__p  s       !|F,=v?QRRGMGbl;FCCChlm$g$g$g$guVMeGfGf$g$g$ghh / 7 7 "V-?VEZ [ [ [)F$68MTYZZZ&+#r-   c                     | j         S r	  r  r   s    r+   get_input_embeddingsz ClvpEncoder.get_input_embeddings  s    ##r-   c                     || _         d S r	  r  r   rO   s     r+   set_input_embeddingsz ClvpEncoder.set_input_embeddings  s    $r-   NrZ   rY  r[   rF   r   output_hidden_statesreturn_dictr"   c                    ||n| j         j        }||n| j         j        }||n| j         j        }||t	          d          |\|                     ||           |                                }|                    d|d                   }|                     |          }n.||                                dd         }nt	          d          |t          ||j
                  }|L||j        n|j        }	t          j        |d         t          j        |	          }|                    d          }|rdnd}
|rdnd}| j        |                     |          nd}|}t#          | j                  D ]o\  }}|r|
|fz   }
| j        r5| j        r.t          j        j                            |j        ||||          }n ||||||	          }|d         }|r||d         fz   }p|r|
|fz   }
|}|                     |          }|                     |          }|                     |          }|st7          d
 ||||
|fD                       S t9          ||||
|          S )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[  r5   r\  r   rP   r   rs   )r   c              3      K   | ]}||V  	d S r	  rs   r=  rC   s     r+   	<genexpr>z&ClvpEncoder.forward.<locals>.<genexpr>  s1        ijiviviviviv r-   )rh   ri   rj   rk   rl   )r   r   r  use_return_dictr   %warn_if_padding_and_no_attention_maskr   r   r  r   rQ   r%   r(   r)   r]  r@   r   rT   r  rQ  r   r_  r`  __call__r  r  rz  r   rg   )r   rZ   rY  r[   rF   r   r  r  input_shaper%   encoder_statesall_attentionsr   rk   idxencoder_layerlayer_outputsri   pooled_outputrh   s                       r+   r   zClvpEncoder.forward  s   N 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B] ]%>cddd"66y.QQQ#..**K!r;r?;;I 00;;MM&',,..ss3KKTUUU %7H[\\N)2)>Y%%MDXF <AejQWXXXL'11!44L3=0:d?C?R?^,,];;;dh%"+DK"8"8 	F 	FC# C!/=2B!B* t}  % 6 A A!*!"" ! ! !.!"" &7! ! ! *!,M  F!/=3C2E!E 	?+}.>>N) 112CDD --.?@@ // 	  "$5}nVde      !/'(%
 
 
 	
r-   )NNNNNNN)rm   rn   ro   rp   r   r   r  r  r   r(   r   r   r   r   r   r   r   r   s   @r+   rx  rx  g  s1        z      "$ $ $% % %
 15485937,0/3&*y
 y
E,-y
   01y
 !!12	y

 u/0y
 $D>y
 'tny
 d^y
 
uo%	&y
 y
 y
 y
 y
 y
 y
 y
r-   rx  c                       e Zd ZdZ fdZd Zd Zd Z ee	          	 	 	 	 	 	 	 	 	 	 	 dde
ej                 de
ej                 d	e
ej                 d
e
ej                 de
ej                 de
eeej                                   de
ej                 de
e         de
e         de
e         de
e         deeef         fd            Z xZS )ClvpDecoderzs
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ClvpDecoderLayer`]
    c                 d    t                                          |           | _        t          j         j        j         j        j                   _        t          j         j        j         j        j                   _	        t          j
         j        j                   _        t          j         fdt           j        j                  D                        _        t          j         j        j         j        j                   _        d _                                          d S )Nc                 8    g | ]}t          j                  S rs   )r'  r   rA  s     r+   r?  z(ClvpDecoder.__init__.<locals>.<listcomp>  s$    $q$q$qq%5dk%B%B$q$q$qr-   r  F)r   r   r   r   rC  rD  r   input_embeds_layerr   position_embeds_layerr  
embd_pdropdroprL  rM  ru  r  r+  r,  
layer_normrQ  r  r  s   ` r+   r   zClvpDecoder.__init__  s       "$,t{/Et{G^"_"_%'\$+2UW[WbWn%o%o"Jt{566	m$q$q$q$qERVR]RoLpLp$q$q$qrr,t{'>DKDbccc&+# 	r-   c                     | j         S r	  r  r   s    r+   r  z ClvpDecoder.get_input_embeddings  s    &&r-   c                     || _         d S r	  r  r   new_embeddingss     r+   r  z ClvpDecoder.set_input_embeddings  s    "0r-   c                     |                                 D ]*\  }}| j        |         j                            |           +dS )zv
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
        N)itemsr  r.  prune_heads)r   heads_to_prunelayerheadss       r+   _prune_headszClvpDecoder._prune_heads  sN     +0022 	7 	7LE5K#//6666	7 	7r-   NrZ   r[   token_type_idsrF   r   rm  rY  r   r   r  r  r"   c           
         |	|	n| j         j        }	|
|
n| j         j        }
||n| j         j        }||n| j         j        }||t          d          |T|                     ||           |                                }|                    d|d                   }|j	        d          n;|*|                                d d         }|j	        d          nt          d          ||j
        n|j
        }||                    d|d                   }|(d}t          d gt          | j                  z            }n!|d         d                             d          }|Zt          j        ||d         |z   t          j        |          }|                    d                              d|d                   }||                     |          }|                     |          }||z   }t)          ||||          }|                     || j         j                  }|}||                     |          }||z   }|                     |          }d|dd          z   |                    d          fz   }| j        r%| j        r|rt4                              d	           d
}|rdnd }|	rdnd }|	r| j         j        rdnd }|
rdnd }t;          t=          | j        |                    D ]\  }\  }}|
r||fz   }| j        r<| j        r5t          j        j                              |j!        |d ||||                   }n |||||||         ||	          }|d         }|du r||d         fz   }|	r,|||rdnd         fz   }| j         j        r|||rdnd         fz   }| "                    |          }|                    |          }|
r||fz   }|st          d |||||fD                       S tG          |||||          S )Nr[  r5   r   r\  r   rP   )r5   r   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Frs   r2  Tr6   r
   c              3      K   | ]}||V  	d S r	  rs   r  s     r+   r  z&ClvpDecoder.forward.<locals>.<genexpr>  s0        =  === r-   ri   rm  rk   rl   cross_attentions)$r   r   r  r   r  r   r  r   r   r9   r%   r   r*   r  r(   r)   r]  r@   r  r  r   get_head_maskru  r  rQ  r   loggerwarning_onceadd_cross_attentionrT   zipr_  r`  r  r  r   )r   rZ   r[   r  rF   r   rm  rY  r   r   r  r  r  r%   past_key_values_lengthre  rk   token_type_embedsoutput_shapepresentsall_self_attentionsall_cross_attentionsall_hidden_statesrb   blockr   r  s                              r+   r   zClvpDecoder.forward&  s    2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B] ]%>cddd"66y.QQQ#..**K!r;r?;;IOA&',,..ss3K"""TUUU%.%:!!@T%+00[_EEN"%&"#TFS-=-=$=>>OO%4Q%7%:%?%?%C%C" <&B:P(PX]Xbkq  L (11!4499"k"oNNL  33I>>M44\BB%7:K8N
 
 &&y$+2OPP	%% $ 7 7 G G),==M		-00{122.-2D2DR2H2H1JJ& 	"4= 	" "##p   "	",22$5?bb4%6d4;;Zdrr`d"6@BBD*3C_4U4U*V*V 	d 	d&A&~# I$58H$H!* t} +0;;N!" aL   %!#1#1!-'l'&7   $AJMD  #wqzm3  d&9W)EZQQYZ=[<]&]#;2 d+?7PYK`11_`CaBc+c(66%**<88   	E 1]4D D 	  '3DFY[op      9+$+*1
 
 
 	
r-   NNNNNNNNNNN)rm   rn   ro   rp   r   r  r  r  r   CLVP_DECODER_INPUTS_DOCSTRINGr   r(   r   rq   r   r   r   r   r   r   r   r   s   @r+   r  r    s            "' ' '1 1 17 7 7 +*+HII 156:593715@D59$(,0/3&*L
 L
E,-L
 !!23L
 !!12	L

 u/0L
 E-.L
 "%el(;"<=L
   12L
 D>L
 $D>L
 'tnL
 d^L
 
u??	@L
 L
 L
 JIL
 L
 L
 L
 L
r-   r  zZThe bare Clvp decoder model outputting raw hidden-states without any specific head on top.c                       e Zd Zdef fdZd Zd Zd Z ee	          	 	 	 	 	 	 	 	 	 	 	 dde
ej                 de
ej                 d	e
ej                 d
e
ej                 de
ej                 de
eeej                                   de
ej                 de
e         de
e         de
e         de
e         deeef         fd            Z xZS )	ClvpModelr   c                     t                                          |           || _        t          | j                  | _        |                                  d S r	  )r   r   r   r  decoderr  r  s     r+   r   zClvpModel.__init__  sK       "4;// 	r-   c                     | j         j        S r	  r  r  r   s    r+   r  zClvpModel.get_input_embeddings  s    |..r-   c                     || j         _        d S r	  r  r  s     r+   r  zClvpModel.set_input_embeddings  s    */'''r-   c                     | j         S r	  )r  r   s    r+   get_decoderzClvpModel.get_decoder  s
    |r-   NrZ   r[   r  rF   r   rm  rY  r   r   r  r  r"   c                 $   |	|	n| j         j        }	|
|
n| j         j        }
||n| j         j        }||n| j         j        }|                     |||||||||	|
|          }|s|S t          |j        |j        |j	        |j
        |j                  S )N)rZ   r[   r  rF   r   rm  rY  r   r   r  r  r  )r   r   r  r   r  r  r   ri   rm  rk   rl   r  )r   rZ   r[   r  rF   r   rm  rY  r   r   r  r  decoder_outputss                r+   r   zClvpModel.forward  s     2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B] ,,))%+'/!5# ' 
 
  	#""8-?+;)7&1,=
 
 
 	
r-   r  )rm   rn   ro   r   r   r  r  r  r   r  r   r(   r   rq   r   r   r   r   r   r   r   r   s   @r+   r  r    s       
0      / / /0 0 0   +*+HII 156:593715@D59$(,0/3&*-
 -
E,--
 !!23-
 !!12	-

 u/0-
 E-.-
 "%el(;"<=-
   12-
 D>-
 $D>-
 'tn-
 d^-
 
u??	@-
 -
 -
 JI-
 -
 -
 -
 -
r-   r  z=The CLVP decoder model with a language modelling head on top.c                       e Zd Z fdZd Zd Z	 	 	 ddeej                 dee	         dee
eej        f                  deej        ee         e
eej        f         f         fd	Z	 dd
Z ee          	 	 	 	 	 	 	 	 	 	 	 	 ddeej                 deeeej                                   deej                 deej                 deej                 deej                 deej                 deej                 dee         dee         dee         dee         deeef         fd            Zedeeej                          dej        deeej                          fd            Z xZS )r{  c                 X   t                                          |           || _        t          | j                  | _        t          j        | j        j                  | _        t          j	        | j        j        | j        j
        d          | _        |                                  d S )NTr   )r   r   r   r  modelr   r+  r   
final_normr   rD  lm_headr  r  s     r+   r   zClvpForCausalLM.__init__  s       t{++
,t{'>??y!8$+:PW[\\\ 	r-   c                 $    | j         j        j        S r	  r  r  r  r   s    r+   r  z$ClvpForCausalLM.get_input_embeddings  s    z!44r-   c                 (    || j         j        _        d S r	  r  r  s     r+   r  z$ClvpForCausalLM.set_input_embeddings  s    0>
---r-   Ninputsr]   model_kwargsr"   c                 0   | j         }d |                                D             }|                    |d          }||t          d| d| d| d| d	          ||}|dk    r)d	|v r%|                     |||
          |d<   |d	         d	}}|                    dd          }|| j        j                            t          j
        |j        d         df| j        j        |j                            }|| j        j                            t          j
        |j        d         dfd|j                            z  }t          j        ||gd          }t#          |d          r1|d                                                             d          dz
  }n5t          j        d|j        d         dz
  t          j        |j                  }|                    d                              |j        d         d          }|| j        j                            |          z
  |d	<   t          j        |d	         j        d         dft          j        | j                  | j        j        z  |d<   |d	         d	|fS |                     |||          }|||fS )zT
        This function extracts the model-specific `inputs` for generation.
        c                     i | ]
\  }}|||S r	  rs   )r=  rB   rC   s      r+   
<dictcomp>z9ClvpForCausalLM._prepare_model_inputs.<locals>.<dictcomp>  s    OOOA1r-   Nz
`inputs`: z` were passed alongside z/ which is not allowed.Make sure to either pass z or z=...rZ   rY  )r  conditioning_embedsr   r   )
fill_valuer%   r7   r[   r5   rP   )main_input_namer  popr   *_maybe_initialize_input_ids_for_generationgetr  r  r  r(   fullr9   r   r]   r%   r  rb  r   r]  r^  rM  r@   ra  r   )	r   r  r]   r  
input_nameinputs_kwargr  mel_start_token_embeddingrF   s	            r+   _prepare_model_inputsz%ClvpForCausalLM._prepare_model_inputs  s    )
OO););)=)=OOO#''
D99#(:IV I IZ I I,2I I8BI I I   %!F$$L)H)H(,(W(W< )X ) )L% ".o!>JF +../DdKK*(,
(:(M(M
(.q115#{7.5  ) )% &);)Q)Q
/5a8!<SfSmnnn* * % #(,0CE^/_ef"g"g"g |%566 +,<=BBDDKKBOORSS${*03a7uzReRl      (11!44;;<O<UVW<XZ[\\L,?$*BTBjBjC C -L) 
L9?BAFejaealmmm+*+ %
  0/<OO@@Wcddz<//r-   c                    |j         d         }|                    dd           }|rg|d         d         j         d         }|j         d         |k    r|}	n|j         d         dz
  }	|d d |	d f         }||d d |j         d          d f         }|                    dd           }
|                    dd           }|
h|f|
                                                    d          dz
  }|                    |
dk    d           |r|d d df                             d          }nd }|)|'t          j        |gt          j        |j                  }||d	|i}nd
|i}|	                    ||                    d          ||d           |S )Nr5   r  r   r6   r   r[   rF   rP   rY  rZ   r   )rm  r   rF   r  )
r9   r  r]  r^  masked_fill_r@   r(   rY   r%   update)r   rZ   rm  rY  r  kwargsinput_ids_lengthr  past_lengthremove_prefix_lengthr[   rF   model_inputss                r+   prepare_inputs_for_generationz-ClvpForCausalLM.prepare_inputs_for_generationW  s   
 %?2.$4d;; 	J)!,Q/5a8K q!K//'2$$ (1q'9A'=$!!!!%9%:%:":;I)!/IOA4F3F3H3H0H!I$4d;;zz.$77%,*>)..0077;;a?L%%n&91=== A+AAArE2<<R@@L*/J <)9(:%*U^UefffL $)@+];LL'3L#2#ZZ44 ,"0	 	
 	
 	
 r-   rZ   rm  r[   r  rF   r   rY  labelsr   r   r  r  c                    |
|
n| j         j        }
||n| j         j        }|	|	n| j         j        }	||n| j         j        }|                     ||||||||	|
||          }|d         }|                     |          }|                     |          }d}||                    |j	                  }|dddddf         
                                }|dddf         
                                }t                      } ||                    d|                    d                    |                    d                    }|s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        |j                  S )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)rZ   rm  r[   r  rF   r   rY  r   r   r  r  r   .r5   r   )rv   r!   rm  rk   rl   r  )r   r   r  r   r  r  r  r  r   r%   r   r	   r   r   r   rm  rk   rl   r  )r   rZ   rm  r[   r  rF   r   rY  r  r   r   r  r  r  rk   	lm_logitsrv   shift_logitsshift_labelsloss_fctoutputs                        r+   r   zClvpForCausalLM.forward  s   . 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]**+))%'/!5#  
 
  
OOM22	LL++	YYy/00F$S#2#qqq[1<<>>L!#qrr'?5577L'))H8L--b,2C2CB2G2GHH,J[J[\^J_J_``D 	F\GABBK/F)-)9TGf$$vE0#3!/)$5
 
 
 	
r-   beam_idxc                 :    t          fd| D                       S )a  
        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   K   | ]}t          fd |D                       V   dS )c              3   t   K   | ]2}|                     d                     |j                            V  3dS )r   N)index_selectr   r%   )r=  
past_stater  s     r+   r  z;ClvpForCausalLM._reorder_cache.<locals>.<genexpr>.<genexpr>  sC      jjQ[*))!X[[9J-K-KLLjjjjjjr-   Nr   )r=  
layer_pastr  s     r+   r  z1ClvpForCausalLM._reorder_cache.<locals>.<genexpr>  sU       
 
 jjjj_ijjjjj
 
 
 
 
 
r-   r  )rm  r  s    `r+   _reorder_cachezClvpForCausalLM._reorder_cache  s=      
 
 
 
-
 
 
 
 
 	
r-   ri  )NNNNNNNNNNNN)rm   rn   ro   r   r  r  r   r(   r   r   r   strr   r  r  r   r  r   rq   r   r   r   r   staticmethodr  r   r   s   @r+   r{  r{    s       

 
 
 
 
5 5 5? ? ?
 *.&*:>	A0 A0&A0 smA0 tC$567	A0
 
u|Xc]Del1B,CC	DA0 A0 A0 A0H X\3 3 3 3j +*+HII 15@D6:59371559-1$(,0/3&*E
 E
E,-E
 "%el(;"<=E
 !!23	E

 !!12E
 u/0E
 E-.E
   12E
 )*E
 D>E
 $D>E
 'tnE
 d^E
 
u77	8E
 E
 E
 JIE
N 
uU\23
?D|
	uU\"	#
 
 
 \
 
 
 
 
r-   r{  zThe composite CLVP model with a text encoder, speech encoder and speech decoder model.The speech decoder model generates the speech_ids from the text and the text encoder and speech encoder workstogether to filter out the best speech_ids.c                   6    e Zd ZeZdef fdZdej        dej        fdZ	 	 	 dde	ej                 de	ej
                 d	e	ej                 dej
        fd
Z	 	 	 	 	 	 dde	ej                 de	ej                 de	ej
                 de	ej
                 d	e	ej                 de	e         dej
        fdZ ee           eee          	 	 	 	 	 	 	 	 	 ddej        dej
        de	ej
                 de	ej
                 d	e	ej                 de	e         de	e         de	e         de	e         deeef         fd                        Z ej                    	 	 	 	 	 	 ddej        dej
        d	e	ej                 de	e         de	e         de	e         fd            Z xZS )!ClvpModelForConditionalGenerationr   c                    t                                          |           t          |j        t                    s%t          dt          |j                   d          t          |j        t                    s%t          dt          |j                   d          t          |j        t                    s%t          dt          |j                   d          t          |          | _        t          |j                  | _        t          |j                  | _        t          |j                  | _        t#          j        t'          j        | j        j                            | _        |                                  d S )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   rq  rB  r    	TypeErrortypespeech_configr<  r   r6  conditioning_encoderr{  speech_decoder_modelrx  text_encoder_modelspeech_encoder_modelr   r   r(   rY   r   logit_scale_init_valuelogit_scaler  r  s     r+   r   z*ClvpModelForConditionalGeneration.__init__  s      &,.?@@ 	0+,,0 0 0  
 &.0ABB 	2-..2 2 2  
 &/1BCC 	3.//3 3 3  
 %<F$C$C!$3F4I$J$J!"-f.@"A"A$/0D$E$E!<T[5W(X(XYY 	r-   rw   r"   c                 *   | j         j        j        }|ddddf         }t          j        || j        j         j        k    dd          }t          j        ||                                |d                   }t          |          D ]\  }}|
                                dk    r|                                }|d         |||df<   |dz
  |j        d         k     r6t          j        |dd         g|j        t          j                  ||ddf<   |S )a#  
        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   )maskrO   r
   )r%   rQ   )r   r<  decoder_fixing_codesr(   rV   r  r^   masked_fillr   rT   rU   argmaxr9   rY   r%   r]  )r   rw   r!  stop_token_indicesrb   each_seq_stop_token_indexstms          r+   fix_speech_decoder_outputz;ClvpModelForConditionalGeneration.fix_speech_decoder_output  s6     ${9N122&
"[t7P7W7d)dfgijkk&z8J8O8O8Q8QYmnoYpqqq
,56H,I,I 	 	(A( ),,..!33+2244C"6q"9Jq#$$wQw)!,,,%*\)!""-.z7HPUPZ& & &
1bcc6" r-   NrZ   text_encoder_inputs_embedsr[   c                 B    |                      |||          }|d         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"])
        ```
        )rZ   rY  r[   r   )r  )r   rZ   r(  r[   r  s        r+   get_text_featuresz3ClvpModelForConditionalGeneration.get_text_features.  s4    b ))4) * 
 
 qzr-   rX  "conditioning_encoder_inputs_embedsgeneration_configc                 :   |{|||t          d          || j        } |j        di | |                     ||||          }| j                            ||          }|                     |d                   }|                     ||          }	|	d         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"]
        ... )
        ```
        NzfEither speech_ids or input_ids/conditioning_encoder_inputs_embeds and input_features must be provided.rX  rZ   rY  r[   )r  r,  r   )rZ   r[   rs   )r   r,  r  r  r  generater'  r  )
r   rw   rZ   rX  r+  r[   r,  r  r  r  s
             r+   get_speech_featuresz5ClvpModelForConditionalGeneration.get_speech_featuresg  s    D !&H&PUcUk |   !($($:!$$..v..."&";";-#@-	 #< # # 2;;$7"3 <  J
 77
1FFJ++ ) , 
 

 qzr-   )output_typer  Freturn_lossr  r   r  c
                    ||n| j         j        }|	|	n| j         j        }	|                     ||||          }
|                     |
||	          }|d         }|j        dk    r|                    d          }|                     |          }|                     |||	          }| 	                    |||||	          }|d         }|d         }||
                    dd	d
          z  }||
                    dd	d
          z  }| j                                        }t          j        ||                                          |z  }|                                }d}|rt!          |          }|	s:|||||d         |d         f}|r||d	         |d	         |d	         fz  }||f|z   n|S t#          ||||||d         |d         |j        |j        |j        
  
        S )a  
        Returns:

        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,
        ... )
        ```
        Nr.  )rY  r  r  r   r
   r6   rZ   r  r  )rZ   rY  r[   r  r  r5   Tr   r8   r   )
rv   rx   ry   rz   r{   r|   r}   r~   r   r   )r   r  r  r  r  ndimr#  r'  r  r  normr  expr(   r   r0   r3   ru   rk   )r   rZ   rX  r+  r(  r[   r2  r  r   r  r  r  rw   speech_outputstext_outputsr{   rz   r  ry   rx   rv   r  s                         r+   r   z)ClvpModelForConditionalGeneration.forward  s   \ %9$D  $+Jj 	 &1%<kk$+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U!K$4$4qb$$4$O$OO &**,,,{MOO4E4EFFT+--// 	._--D 	F!Qq!F $ #B' $"2&  *.)9TGf$$vE/+#'*1o .q 1"1"?'3'A)7)E
 
 
 	
r-   pad_to_max_mel_tokensc                    |j         d         }|| j        j        j        dz
  k    r't	          d| d| j        j        j        dz
             || j        }t          j        |          } |j        di |}	|	                                 | 
                    |	                                           t          ||d| j        j        j        | j        j        j                  \  }}|                     |||          }
| j                            |
|||j        	          }t'          |t(                    r|j        }|C||j         d         z
  }t,          j        j                            |d
|f| j        j                  }|                     |          }|                     |||j                  }|                     ||||j                  }|d
         }|d
         }||                    ddd          z  }||                    ddd          z  }| j                                        }t-          j         ||!                                          |z  }|!                                }|j        s3||||||d         |d         f}|r||d         |d         |d         fz  }|S tE          ||||||d         |d         |j#        |j#        |j#        
  
        S )a=
  
        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.
        r5   r
   z;Maximum sequence length reached! Found input_ids of length z:.Please make sure that the maximum length of input_ids is NF)r_   r]   r^   )rX  rZ   r[   )r  r,  r  r  r   rN   r4  )rZ   r[   r  r  r6   Tr5  )
rw   rx   ry   rz   r{   r|   r}   r~   r   r   rs   )$r9   r   r<  rF  r   r,  copydeepcopyr  validate_validate_model_kwargsre   rB  r]   r^   r  r  r/  return_dict_in_generaterq  r   	sequencesr(   r   r&   rR   r'  r  r  r7  r  r8  r   r0   ru   rk   )r   rZ   rX  r[   r,  r;  r  r  r   r  r  r  rw   padding_neededr9  r:  r{   rz   r  ry   rx   r  s                         r+   r/  z*ClvpModelForConditionalGeneration.generateL  s   f $/"-dk8H1LMM}o } }LPKLfLvyzLz} }  
 $ $ 6 M*;<</(/99&99""$$$##L$5$5$7$7888 %>0=0=%
 %
 %
!	> #77)) 8 
 
 3<< 3/!5)A	 = 
 
 o{33 	3(2J !,2Z5Eb5IIN,00Q/t7M7Z 1  J 33J??
22 !5)A 3 
 

 ..)!5)A	 / 
 
 'q)"1o &(:(:QBPT(:(U(UU!K$4$4qb$$4$O$OO &**,,,{MOO4E4EFFT+--// 8 	!Qq!F $ #B' $"2&  M!/+#'*1o .q 1"1"?'3'A)7)E
 
 
 	
r-   ri  )NNNNNN)	NNNNNNNFN)rm   rn   ro   r   r  r   r(   r   r'  r   rq   r*  r   r   r0  r   CLVP_INPUTS_DOCSTRINGr   ru   r   r   r   r   no_gradr   r/  r   r   s   @r+   r  r    sE        Lz      FE4D IY    @ 15BF59	7 7E,-7 %-U->$?7 !!12	7
 
	7 7 7 7v 26046:JN158<_ _U-._ E,-_ !!23	_
 -5U5F,G_ !._ $$45_ 
	_ _ _ _B +*+@AA:JOOO '+,0JNBF59&*/3,1&*@
 @
#@
 )@
 -5U5F,G	@

 %-U->$?@
 !!12@
 d^@
 'tn@
 $D>@
 d^@
 
uj 	!@
 @
 @
 PO BA@
D U]__ '+,0598</3/3Z
 Z
#Z
 )Z
 !!12	Z

 $$45Z
  (}Z
 'tnZ
 Z
 Z
 _Z
 Z
 Z
 Z
 Z
r-   r  )r   )Nr   rL   r   TT)Krp   r=  r~  dataclassesr   typingr   r   r   r   r(   torch.utils.checkpointr   torch.nnr	   activationsr   
generationr   r   modeling_attn_mask_utilsr   r   modeling_outputsr   r   r   r   modeling_utilsr   r   pytorch_utilsr   r   r_  r   r   r   r   r   configuration_clvpr   r   r    
get_loggerrm   r  _CHECKPOINT_FOR_DOCr   r,   r3   r>   rK   re   rg   ru   Moduler   r   r   r   r  r  r  r'  r6  rk  CLVP_START_DOCSTRINGrD  r  rx  r  r  r{  r  rs   r-   r+   <module>rU     sE        ! ! ! ! ! ! / / / / / / / / / / / /            % % % % % % ! ! ! ! ! ! ; ; ; ; ; ; ; ; e e e e e e e e            ? > > > > > > > 6 6 6 6 6 6 6 6                       
	H	%	%( `U\ `el ` ` ` `
.%, .5< . . . .( ( (% % % %> (. (. (. (.V : : : : : : : :: ); ); ); ); ); ); ); );ZJ J J J J") J J J(7 7 7 7 7BI 7 7 7<~2 ~2 ~2 ~2 ~2	 ~2 ~2 ~2B8 8 8 8 8") 8 8 8     RY   (; ; ; ; ;ry ; ; ;~    RY   "1 1 1 1 1ry 1 1 1hG< G< G< G< G<bi G< G< G<T)* )* )* )* )*/ )* )* )*X  ! H=! @Y
 Y
 Y
 Y
 Y
% Y
 Y
 Y
xp
 p
 p
 p
 p
% p
 p
 p
f ` @
 @
 @
 @
 @
# @
 @
	 @
F C `
 `
 `
 `
 `
)? `
 `
	 `
F 2 	 }
 }
 }
 }
 }
(;_ }
 }
 }
 }
 }
r-   