o
    Zh"                    @   s^  d Z ddlZddl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mZmZmZ ddlZddlmZ ddlmZ ddlmZ ddlmZmZmZmZ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&m'Z'm(Z(m)Z) ddl*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5 e# rddl!m6Z6 erddl7m8Z8 e.9e:Z;eG dd de(Z<dej=de>de>fddZ?G dd dej@ZAG dd dej@ZBG d d! d!eBZCG d"d# d#eBZDeBeDeCd$ZEG d%d& d&ej@ZFe-G d'd( d(e+ZGG d)d* d*eGZHe-G d+d, d,eGZIe-d-d.G d/d0 d0eGeZJe-d1d.G d2d3 d3e+eZKg d4ZLdS )5zPyTorch Musicgen model.    N)	dataclass)TYPE_CHECKINGAnyDictListOptionalTupleUnion)CrossEntropyLoss   )ACT2FN)%ClassifierFreeGuidanceLogitsProcessorGenerationConfigGenerationMixinGenerationModeLogitsProcessorListStoppingCriteriaList)_prepare_4d_attention_mask#_prepare_4d_attention_mask_for_sdpa!_prepare_4d_causal_attention_mask*_prepare_4d_causal_attention_mask_for_sdpa)!flash_attn_supports_top_left_maskis_flash_attn_available)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsModelOutputSeq2SeqLMOutput)PreTrainedModel)auto_docstringlogging   )
AutoConfig	AutoModel   )MusicgenConfigMusicgenDecoderConfig)_flash_attention_forward)BaseStreamerc                   @   sF   e Zd ZU dZdZeej ed< dZ	e
ej ed< dZe
e ed< dS )MusicgenUnconditionalInputa%  
    Args:
        encoder_outputs  (`Tuple[torch.FloatTensor]` of length 1, with tensor shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the text encoder model.
        attention_mask (`torch.LongTensor`)  of shape `(batch_size, sequence_length)`, *optional*):
            Encoder attention 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**.
        guidance_scale (`float`, *optional*):
            Guidance scale for classifier free guidance, setting the balance between the conditional logits (predicted
            from the prompts) and the unconditional logits (predicted without prompts).
    Nencoder_outputsattention_maskguidance_scale)__name__
__module____qualname____doc__r+   r   torchFloatTensor__annotations__r,   r   
LongTensorr-   float r7   r7   ]/var/www/auris/lib/python3.10/site-packages/transformers/models/musicgen/modeling_musicgen.pyr*   C   s
   
 r*   	input_idspad_token_iddecoder_start_token_idc                 C   st   |  dd} | | j}| dddf  |dddf< |du r$td||d< |du r0td||d	k| |S )
z1
    Shift input ids one token to the right.
    r%   r!   .NzSMake sure to set the decoder_start_token_id attribute of the model's configuration..r   zIMake sure to set the pad_token_id attribute of the model's configuration.)	transposeZ	new_zerosshapeclone
ValueErrorZmasked_fill_)r9   r:   r;   Zshifted_input_idsr7   r7   r8   shift_tokens_rightV   s    rC   c                       sp   e Zd ZdZdedef fddZdedefddZededefd	d
Ze	
 dde	jdefddZ  ZS )%MusicgenSinusoidalPositionalEmbeddingzDThis module produces sinusoidal positional embeddings of any length.num_positionsembedding_dimc                    s    t    || _| || d S N)super__init__rF   make_weights)selfrE   rF   	__class__r7   r8   rI   m   s   
z.MusicgenSinusoidalPositionalEmbedding.__init__num_embeddingsc                 C   s@   |  ||}t| dr|j| jj| jjd}| jd|dd d S )NweightsdtypedeviceF)
persistent)get_embeddinghasattrtorO   rQ   rR   Zregister_buffer)rK   rN   rF   Zemb_weightsr7   r7   r8   rJ   r   s   
z2MusicgenSinusoidalPositionalEmbedding.make_weightsc                 C   s   |d }t d|d  }ttj|tjd |  }tj| tjd d|d }tjt	|t
|gdd| d}|d dkrUtj|t| dgdd}|t S )z
        Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the
        description in Section 3.5 of "Attention Is All You Need".
        r!   i'  r%   rQ   r   dimr<   )mathlogr2   exparangeZint64r6   Z	unsqueezecatcossinviewzerosrV   Zget_default_dtype)rN   rF   Zhalf_dimZembr7   r7   r8   rT   z   s    $&z3MusicgenSinusoidalPositionalEmbedding.get_embeddingr   r9   past_key_values_lengthc                 C   s`   |  \}}}t|| |j}|| j dkr$| || j | j | j	d|
d S )Nr   r<   )sizer2   r]   rV   rR   rO   rJ   offsetrF   Zindex_selectra   detach)rK   r9   rc   bsz	codebooksseq_lenZposition_idsr7   r7   r8   forward   s
   z-MusicgenSinusoidalPositionalEmbedding.forward)r   )r.   r/   r0   r1   intrI   rJ   staticmethodrT   r2   no_gradTensorrj   __classcell__r7   r7   rL   r8   rD   j   s     rD   c                       s   e Zd ZdZ					ddededed	ed
ededee f fddZ	de
jdedefddZ					dde
jdee
j deee
j  dee
j dee
j dedee
jee
j eee
j  f fddZ  ZS )MusicgenAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FTN	embed_dim	num_headsdropout
is_decoderbias	is_causalconfigc                    s   t    || _|| _|| _|| | _|| _| j| | jkr*td| j d| d| jd | _|| _	|| _
tj|||d| _tj|||d| _tj|||d| _tj|||d| _d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      ࿩rv   )rH   rI   rr   rs   rt   head_dimrx   rB   scalingru   rw   nnLineark_projv_projq_projout_proj)rK   rr   rs   rt   ru   rv   rw   rx   rL   r7   r8   rI      s&   



zMusicgenAttention.__init__tensorri   rg   c                 C   s    | ||| j| jdd S )Nr%   r!   )ra   rs   rz   r?   
contiguousrK   r   ri   rg   r7   r7   r8   _shape   s    zMusicgenAttention._shapehidden_stateskey_value_statespast_key_valuer,   layer_head_maskoutput_attentionsreturnc                 C   sr  |du}|  \}}	}
| || j }|r.|dur.|d jd |jd kr.|d }|d }nZ|rE| | |d|}| | |d|}nC|durt| | |d|}| | |d|}tj|d |gdd}tj|d |gdd}n| | |d|}| | |d|}| j	r||f}|| j
 d| jf}| ||	|j| }|j| }|j| }| d}t||dd}|  || j
 |	|fkrtd|| j
 |	|f d|   |dur|  |d|	|fkrtd	|d|	|f d|   ||| j
|	|| }||| j
 |	|}tjj|dd}|durL|  | j
fkr1td
| j
f d|   |dddd||| j
|	| }||| j
 |	|}|rc||| j
|	|}||| j
 |	|}nd}tjj|| j| jd}t||}|  || j
 |	| jfkrtd|| j
 |	| jf d|   ||| j
|	| j}|dd}|||	| j}| |}|||fS )#Input shape: Batch x Time x ChannelNr   r!   r%   r<   rX   z$Attention weights should be of size 	, but is z!Attention mask should be of size z/Head mask for a single layer should be of size ptraining `attn_output` should be of size )rd   r   r{   r@   r   r~   r   r2   r^   ru   rs   rz   ra   reshapeZbmmr?   rB   r|   
functionalZsoftmaxrt   r   rr   r   )rK   r   r   r   r,   r   r   is_cross_attentionrg   tgt_len_query_states
key_statesvalue_statesZ
proj_shapeZsrc_lenattn_weightsZattn_weights_reshapedZ
attn_probsattn_outputr7   r7   r8   rj      s   





"

zMusicgenAttention.forward)rq   FTFNNNNNF)r.   r/   r0   r1   rk   r6   boolr   r&   rI   r2   rn   r   r   rj   ro   r7   r7   rL   r8   rp      sV    rp   c                       s   e Zd ZdZ fddZdejdedefddZ									
ddejde	ej de	e
ej  de	ej de	ej dede
eje	ej e	e
ej  f fddZ  ZS )MusicgenFlashAttention2aL  
    Musicgen flash attention module. This module inherits from `MusicgenAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                    s   t  j|i | t | _d S rG   )rH   rI   r   _flash_attn_uses_top_left_maskrK   argskwargsrL   r7   r8   rI   <  s   z MusicgenFlashAttention2.__init__r   ri   rg   c                 C   s   | ||| j| jS rG   )ra   rs   rz   r   r7   r7   r8   _reshapeD  s   z MusicgenFlashAttention2._reshapeNFr   r   r   r,   r   r   r   c              
   C   s>  |d u}|  \}}	}
| | |d|}|r8|d ur8|d jd |jd kr8|d dd}|d dd}nb|rO| | |d|}| | |d|}nK|d ur| | |d|}| | |d|}tj|d dd|gdd}tj|d dd|gdd}n| | |d|}| | |d|}| j	r|dd|ddf}|jd }|d ur||d jd 7 }|j
}|tjkrt rt }nt| jdr| jj}n| jjj
}td| d	 ||}||}||}t|||||	| jr| jnd
| j| jd}|||	d}| |}|sd }|||fS )Nr<   r   r!   r%   rX   _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .rq   )rt   rw   Zuse_top_left_mask)rd   r   r   r@   r?   r~   r   r2   r^   ru   rQ   Zfloat32Zis_autocast_enabledZget_autocast_gpu_dtyperU   rx   r   weightloggerwarning_oncerV   r(   r   rt   rw   r   r   r   )rK   r   r   r   r,   r   r   r   rg   Zq_lenr   r   r   r   Z
kv_seq_lenZinput_dtypeZtarget_dtyper   r   r7   r7   r8   rj   G  sl    









zMusicgenFlashAttention2.forwardr   )r.   r/   r0   r1   rI   r2   rn   rk   r   r   r   r   rj   ro   r7   r7   rL   r8   r   5  s0    r   c                       s   e Zd Z					ddejdeej deeej  deej deej ded	eejeej eeej  f f fd
dZ  Z	S )MusicgenSdpaAttentionNFr   r   r   r,   r   r   r   c                    sF  |rt d t j|||||dS |dur7|jg ddt|jjk	 r7t d t j|||||dS |du}|
 \}}	}
| |}|rb|durb|d jd |jd	 krb|d }|d	 }nZ|ry| | |d
|}| | |d
|}nC|dur| | |d
|}| | |d
|}tj|d |gdd}tj|d	 |gdd}n| | |d
|}| | |d
|}| jr||f}| ||	|}| jr|du r|	d	krdnd}tjjj||||| jr| jnd|d}|
 || j|	| jfkrtd|| j|	| jf d|
  |d	d}|||	| j}| |}|d|fS )r   a  MusicgenModel is using MusicgenSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.)r   r   r,   r   N)r%   r!   r   rX   a  `torch.nn.functional.scaled_dot_product_attention` does not support having an empty attention mask. Falling back to the manual attention implementation. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.Note that this probably happens because `guidance_scale>1` or because you used `get_unconditional_inputs`. See https://github.com/huggingface/transformers/issues/31189 for more information.r   r!   r%   r<   TFrq   )	attn_maskZ	dropout_prw   r   r   )r   r   rH   rj   meanr2   ZfinforQ   minanyrd   r   r@   r   r~   r   r^   ru   rw   r|   r   Zscaled_dot_product_attentionr   rt   rs   rz   rB   r?   r   rr   r   )rK   r   r   r   r,   r   r   r   rg   r   r   r   r   r   rw   r   rL   r7   r8   rj     s   	 


	

zMusicgenSdpaAttention.forwardr   )
r.   r/   r0   r2   rn   r   r   r   rj   ro   r7   r7   rL   r8   r     s*    r   )eagersdpaflash_attention_2c                       s   e Zd Zdef fddZ								dd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ej  dee	 dee	 dejfddZ
  ZS )MusicgenDecoderLayerrx   c              	      s   t    |j| _t|j | j|j|jddd|d| _|j	| _	t
|j | _|j| _t| j| _t|j | j|j|jdd|d| _t| j| _tj| j|jdd| _tj|j| jdd| _t| j| _d S )NTF)rr   rs   rt   ru   rv   rw   rx   )rt   ru   rv   rx   ry   )rH   rI   hidden_sizerr   MUSICGEN_ATTENTION_CLASSES_attn_implementationZnum_attention_headsZattention_dropout	self_attnrt   r   Zactivation_functionactivation_fnactivation_dropoutr|   	LayerNormself_attn_layer_normencoder_attnencoder_attn_layer_normr}   Zffn_dimfc1fc2final_layer_normrK   rx   rL   r7   r8   rI   1  s6   
	zMusicgenDecoderLayer.__init__NFTr   r,   encoder_hidden_statesencoder_attention_maskr   cross_attn_layer_head_maskr   r   	use_cacher   c
                 C   sZ  |}
|  |}|dur|dd nd}| j|||||d\}}}tjj|| j| jd}|
| }d}d}|durk|}
| |}|durH|dd nd}| j||||||d\}}}tjj|| j| jd}|
| }|| }|}
| |}| 	| 
|}tjj|| j| jd}| |}tjj|| j| jd}|
| }|f}|r|||f7 }|	r||f7 }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            encoder_hidden_states (`torch.FloatTensor`):
                cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
            encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
                `(encoder_attention_heads,)`.
            cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
                size `(decoder_attention_heads,)`.
            past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        Nr!   )r   r   r,   r   r   r   r   )r   r   r,   r   r   r   )r   r   r|   r   rt   r   r   r   r   r   r   r   r   )rK   r   r,   r   r   r   r   r   r   r   ZresidualZself_attn_past_key_valueZself_attn_weightsZpresent_key_valueZcross_attn_present_key_valueZcross_attn_weightsZcross_attn_past_key_valueoutputsr7   r7   r8   rj   Q  sT   




zMusicgenDecoderLayer.forward)NNNNNNFT)r.   r/   r0   r'   rI   r2   rn   r   r   r   rj   ro   r7   r7   rL   r8   r   0  s>    #	
r   c                   @   s0   e Zd ZeZdZdZddgZdZdZ	dd Z
dS )MusicgenPreTrainedModelmodelTr   rp   c                 C   s   | j j}t|tjtjfr%|jjjd|d |j	d ur#|j	j
  d S d S t|tjrD|jjjd|d |jd urF|jj|j 
  d S d S d S )Nrq   )r   std)rx   Zinitializer_factor
isinstancer|   r}   ZConv1dr   dataZnormal_rv   Zzero_	EmbeddingZpadding_idx)rK   moduler   r7   r7   r8   _init_weights  s   

z%MusicgenPreTrainedModel._init_weightsN)r.   r/   r0   r'   config_classbase_model_prefixsupports_gradient_checkpointingZ_no_split_modules_supports_flash_attn_2_supports_sdpar   r7   r7   r7   r8   r     s    r   c                       s   e Zd ZdZdef fddZdd Zdd Z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
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dZ  ZS )MusicgenDecoderzw
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MusicgenDecoderLayer`]
    rx   c                    s   t     j| _ j| _ j| _ j| _ j| _ j	r#t
 jnd| _ jd t fddt jD | _t j j| _t fddt jD | _t j| _ j| _d| _|   d S )N      ?r%   c                    s   g | ]	}t  jqS r7   )r|   r   r   .0r   rx   rr   r7   r8   
<listcomp>  s    z,MusicgenDecoder.__init__.<locals>.<listcomp>c                    s   g | ]}t  qS r7   )r   r   rx   r7   r8   r         F)rH   rI   rt   	layerdropZmax_position_embeddingsZmax_target_positionsr   Zd_modelnum_codebooksZscale_embeddingrZ   sqrtZembed_scale
vocab_sizer|   
ModuleListrangeembed_tokensrD   embed_positionsZnum_hidden_layerslayersr   
layer_normr   attn_implementationgradient_checkpointing	post_initr   rL   r   r8   rI     s(   
 zMusicgenDecoder.__init__c                 C      | j S rG   r   rK   r7   r7   r8   get_input_embeddings     z$MusicgenDecoder.get_input_embeddingsc                 C   
   || _ d S rG   r   rK   valuer7   r7   r8   set_input_embeddings     
z$MusicgenDecoder.set_input_embeddingsNr9   r,   r   r   	head_maskcross_attn_head_maskpast_key_valuesinputs_embedsr   r   output_hidden_statesreturn_dictr   c                     s  |
dur|
nj j}
|dur|nj j}|	dur|	nj j}	|dur$|nj j}|dur4|dur4td|durN|dj|jd   j\}}}||f}n|durh|	 dd }|ddddddf  ntd|dury|d d jd nd}|du rt
 fddt|D }jd	kr|durd|v r|nd}njd
kr|du r|
st||||}nt||||}|dur|durjd	krd|v r|nd}n jd
kr|du r|
st||j|d d}n
t||j|d d} |}|||j }tjj|jjd}jrjr|	rtd d}	|rdnd}|
r&dnd}|
r2|dur2dnd}|	r9dnd}t||gddgD ]+\}}|durn|	 d tjkrntd| dtj d|	 d  dqDtjD ]\}}|r||f7 }t !dd}jr|j"k rqu|dur|| nd}jrȈjrȈ#|j$|||||dur|| nd|dur|| ndd|
|	
}n||||||dur|| nd|dur|| nd||
|	d	}|d }|	r|||
rdnd f7 }|
r||d f7 }|dur||d f7 }qu%|}|r||f7 }|	r$|nd}|s7t&dd |||||fD S t'|||||dS )  
        input_ids (`torch.LongTensor` of shape `(batch_size * num_codebooks, sequence_length)`):
            Indices of input sequence tokens in the vocabulary, corresponding to the sequence of audio codes.

            Indices can be obtained by encoding an audio prompt with an audio encoder model to predict audio codes,
            such as with the [`EncodecModel`]. See [`EncodecModel.encode`] for details.

            [What are input IDs?](../glossary#input-ids)

            <Tip warning={true}>

            The `input_ids` will automatically be converted from shape `(batch_size * num_codebooks,
            target_sequence_length)` to `(batch_size, num_codebooks, target_sequence_length)` in the forward pass. If
            you obtain audio codes from an audio encoding model, such as [`EncodecModel`], ensure that the number of
            frames is equal to 1, and that you reshape the audio codes from `(frames, batch_size, num_codebooks,
            target_sequence_length)` to `(batch_size * num_codebooks, target_sequence_length)` prior to passing them as
            `input_ids`.

            </Tip>
        encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of
            the decoder.
        encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
            Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. 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)
        cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
            cross-attention on hidden heads. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer<   zEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   r!   c                    s&   g | ]}j |  d d |f qS rG   r   )r   codebookinputrK   r7   r8   r   4  s   & z+MusicgenDecoder.forward.<locals>.<listcomp>r   r   )r   r   z[`use_cache=True` is incompatible with gradient checkpointing`. Setting `use_cache=False`...Fr7   r   r   zThe `z` should be specified for z layers, but it is for r   r%   )r,   r   r   r   r   r   r   r   r   c                 s   s    | ]	}|d ur|V  qd S rG   r7   )r   vr7   r7   r8   	<genexpr>  s    z*MusicgenDecoder.forward.<locals>.<genexpr>last_hidden_stater   r   
attentionscross_attentions)(rx   r   r   r   use_return_dictrB   r   r   r@   rd   sumr   r   r   r   r   rQ   r   r   rV   rR   r|   r   rt   r   r   r   r   ziplenr   	enumeraterandomuniformr   Z_gradient_checkpointing_funcrj   r   tupler   ) rK   r9   r,   r   r   r   r   r   r   r   r   r   r   rg   r   ri   Zinput_shaperc   Z	positionsr   Zall_hidden_statesZall_self_attnsZall_cross_attentionsZnext_decoder_cacher   Z	mask_nameidxZdecoder_layerZdropout_probabilityr   Zlayer_outputsZ
next_cacher7   r   r8   rj     s   5








zMusicgenDecoder.forwardNNNNNNNNNNNN)r.   r/   r0   r1   r'   rI   r   r   r   r   r2   r5   rn   r3   r   r   r	   r   rj   ro   r7   r7   rL   r8   r     sZ    	

r   c                       s   e Zd Zdef fddZdd Zdd Zdd	 Z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
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dZ  ZS )MusicgenModelrx   c                    s"   t  | t|| _|   d S rG   )rH   rI   r   decoderr   r   rL   r7   r8   rI     s   
zMusicgenModel.__init__c                 C      | j jS rG   r  r   r   r7   r7   r8   r        z"MusicgenModel.get_input_embeddingsc                 C      || j _d S rG   r  r   r7   r7   r8   r        z"MusicgenModel.set_input_embeddingsc                 C   r   rG   r  r   r7   r7   r8   get_decoder  r   zMusicgenModel.get_decoderNr9   r,   r   r   r   r   r   r   r   r   r   r   r   c                 C   s   |
dur|
n| j j}
|dur|n| j j}|	dur|	n| j j}	|dur$|n| j j}| j|||||||||	|
||d}|s=|S t|j|j|j	|j
|jdS )r   N)r9   r,   r   r   r   r   r   r   r   r   r   r   r   )rx   r   r   r   r  r  r   r   r   r   r   r  )rK   r9   r,   r   r   r   r   r   r   r   r   r   r   decoder_outputsr7   r7   r8   rj     s8   5zMusicgenModel.forwardr  )r.   r/   r0   r'   rI   r   r   r  r   r   r2   r5   rn   r3   r   r   r	   r   rj   ro   r7   r7   rL   r8   r    sZ    	

r  zK
    The MusicGen decoder model with a language modelling head on top.
    )Zcustom_introc                        s  e Zd Zdef fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
e													d3d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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d Z							!		d4d"d#Z	d5dejd$ed%ee fd&d'Zed(d) Ze 						d6d*eej d+ee d,ee d-ee d.ee d/ed0 fd1d2Z  Z S )7MusicgenForCausalLMrx   c                    sJ   t    t | _ j| _t fddt jD | _| 	  d S )Nc                    s    g | ]}t j j jd dqS )Fry   )r|   r}   r   r   r   r   r7   r8   r   1  s     z0MusicgenForCausalLM.__init__.<locals>.<listcomp>)
rH   rI   r  r   r   r|   r   r   lm_headsr   r   rL   r   r8   rI   *  s   
zMusicgenForCausalLM.__init__c                 C   s
   | j jjS rG   r   r  r   r   r7   r7   r8   r   7  r   z(MusicgenForCausalLM.get_input_embeddingsc                 C   s   || j j_d S rG   r  r   r7   r7   r8   r   :  s   z(MusicgenForCausalLM.set_input_embeddingsc                 C   r   rG   r  r   r7   r7   r8   get_output_embeddings=  r   z)MusicgenForCausalLM.get_output_embeddingsc                 C   r   rG   r  rK   Znew_embeddingsr7   r7   r8   set_output_embeddings@  r   z)MusicgenForCausalLM.set_output_embeddingsc                 C   r  rG   r   r  )rK   r  r7   r7   r8   set_decoderC  r  zMusicgenForCausalLM.set_decoderc                 C   r  rG   r  r   r7   r7   r8   r  F  r  zMusicgenForCausalLM.get_decoderNr9   r,   r   r   r   r   r   r   labelsr   r   r   r   r   c                    s  |dur|n| j j}|	dur |du r |du r t|	| j j| j j}| j|||||||||
|||d}|d  tj fdd| jD dd}d}|	dur|dddd|	j	d  df }t
 }tjg | jd}|	|	| j jkd	}	t| j jD ]%}|dd|f  d
|j	d
 }|	d|f  d
}||||7 }qv|| j j }|jd
g|j	dd R  }|s|f|dd  }|dur|f| S |S t|||j|j|j|jdS )ar
  
        input_ids (`torch.LongTensor` of shape `(batch_size * num_codebooks, sequence_length)`):
            Indices of input sequence tokens in the vocabulary, corresponding to the sequence of audio codes.

            Indices can be obtained by encoding an audio prompt with an audio encoder model to predict audio codes,
            such as with the [`EncodecModel`]. See [`EncodecModel.encode`] for details.

            [What are input IDs?](../glossary#input-ids)

            <Tip warning={true}>

            The `input_ids` will automatically be converted from shape `(batch_size * num_codebooks,
            target_sequence_length)` to `(batch_size, num_codebooks, target_sequence_length)` in the forward pass. If
            you obtain audio codes from an audio encoding model, such as [`EncodecModel`], ensure that the number of
            frames is equal to 1, and that you reshape the audio codes from `(frames, batch_size, num_codebooks,
            target_sequence_length)` to `(batch_size * num_codebooks, target_sequence_length)` prior to passing them as
            `input_ids`.

            </Tip>
        encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of
            the decoder.
        encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
            Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. 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)
        cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
            cross-attention on hidden heads. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length, num_codebooks)`, *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)r,   r   r   r   r   r   r   r   r   r   r   r   c                    s   g | ]}| qS r7   r7   )r   headr   r7   r8   r     r   z/MusicgenForCausalLM.forward.<locals>.<listcomp>r%   rX   rR   r>   r<   .r!   )losslogitsr   r   r   r  )rx   r  rC   r:   bos_token_idr   r2   stackr  r@   r
   rb   rR   Zmasked_fillr   r   r   ra   r   r   r   r   r   r  )rK   r9   r,   r   r   r   r   r   r   r  r   r   r   r   r   r   Z	lm_logitsr#  r$  Zloss_fctr   Zcodebook_logitsZcodebook_labelsoutputr7   r!  r8   rj   I  sT   <""zMusicgenForCausalLM.forwardTc              	   K   s   |	d u r| j || jj| jjd\}}	| ||	}|
d ur.|
dkr.|d}|d ur.|d}|d ur<|d d dd f }||||||||dS )Nr:   
max_lengthr%   r!   r%   r<   )r9   r,   r   r   r   r   r   r   )build_delay_pattern_maskgeneration_configr:   r)  apply_delay_pattern_maskrepeat)rK   r9   r,   r   r   r   r   r   r   delay_pattern_maskr-   r   r7   r7   r8   prepare_inputs_for_generation  s,   


z1MusicgenForCausalLM.prepare_inputs_for_generationr:   r)  c                 C   s>  | d| j|jd }|j\}}}|dur|n| jj}tj|||ftj|jdd }| j	j
dkr4|d n|}|d| d k rN| || d| || dfS t|D ]N}	| j	j
dkrn|dd|	f |dd|	|	||	 f< qR|ddd|	 f |ddd|	 |	||	 f< |ddd|	 d f |ddd|	 d |	||	 f< qRtjtj||ftjd|| d d}
|
ttj||ftjd }
| j	j
dkr|
jddd	}
|
|j }|| | |  }|dddddf }|dk dddf }t|dkrt|}n|}| || d}|d
d|f  || d}||fS )aD  Build a delayed pattern mask to the input_ids. Each codebook is offset by the previous codebook by
        one, giving a delayed pattern mask at the start of sequence and end of sequence. Take the example where there
        are 4 codebooks and a max sequence length of 8, we have the delayed pattern mask of shape `(codebooks,
        seq_len)`:
        - [P, -1, -1, -1, -1, P, P, P]
        - [P, P, -1, -1, -1, -1, P, P]
        - [P, P, P, -1, -1, -1, -1, P]
        - [P, P, P, P, -1, -1, -1, -1]
        where P is the special padding token id and -1 indicates that the token is valid for prediction. If we include
        a prompt (decoder input ids), the -1 positions indicate where new tokens should be predicted. Otherwise, the
        mask is set to the value in the prompt:
        - [P, a, b, -1, -1, P, P, P]
        - [P, P, c, d, -1, -1, P, P]
        - [P, P, P, e, f, -1, -1, P]
        - [P, P, P, P, g, h, -1, -1]
        where a-h indicate the input prompt (decoder input ids) that are offset by 1. Now, we only override the -1
        tokens in our prediction.
        r<   NrP   r!   r%   rW   )Zdiagonalr   rX   .)r   r   r@   r,  r)  r2   oneslongrR   rx   audio_channelsr   Ztriur   Ztrilrepeat_interleaverV   Znonzeror  r   )rK   r9   r:   r)  rg   r   ri   Zinput_ids_shiftedZchannel_codebooksr   Zdelay_patternmaskZfirst_codebook_idsZ	start_idsZfirst_start_idZpattern_maskr7   r7   r8   r+    s:    (.8
z,MusicgenForCausalLM.build_delay_pattern_maskc                 C   s0   | j d }|dd|f }t|dk| |} | S )zApply a delay pattern mask to the decoder input ids, only preserving predictions where
        the mask is set to -1, and otherwise setting to the value detailed in the mask.r<   .N)r@   r2   where)r9   Zdecoder_pad_token_maskri   r7   r7   r8   r-  <  s   
z,MusicgenForCausalLM.apply_delay_pattern_maskinputsr,  logits_processorstopping_criteriasynced_gpusstreamerr)   c                 K   st  |du r| j }t|}|jdi |}|  | |  |dur%|nt }|dur.|nt }d|v}	|dddu}
| 	||j
|\}}}|jd | j }| j||
|jd |j|d< |j|d< |dddu rv|	rv| ||||d< |jd }|d	du o|jdu}|d
du o|jdu}| j||||||d}| j||j|jd\}}|dur||  ||d< | }|jdur|jdkr|t|j d|_| j|||d||jd}| j||d}|tjtj fv r| j!d||j"d|\}}| j#|f|||||d|}nt$d|j%r|j&}n|}| '||d }|||j(k )|| jd}|j%r8||_&|S |S )5  

        Generates sequences of token ids for models with a language modeling head.

        <Tip warning={true}>

        Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
        model's default generation configuration. You can override any `generation_config` by passing the corresponding
        parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.

        For an overview of generation strategies and code examples, check out the [following
        guide](./generation_strategies).

        </Tip>

        Parameters:
            inputs (`torch.Tensor` of varying shape depending on the modality, *optional*):
                The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the
                method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`
                should be in the format `input_ids`. For encoder-decoder models *inputs* can represent any of
                `input_ids`, `input_values`, `input_features`, or `pixel_values`.
            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.
            logits_processor (`LogitsProcessorList`, *optional*):
                Custom logits processors that complement the default logits processors built from arguments and
                generation config. If a logit processor is passed that is already created with the arguments or a
                generation config an error is thrown. This feature is intended for advanced users.
            stopping_criteria (`StoppingCriteriaList`, *optional*):
                Custom stopping criteria that complement the default stopping criteria built from arguments and a
                generation config. If a stopping criteria is passed that is already created with the arguments or a
                generation config an error is thrown. This feature is intended for advanced users.
            synced_gpus (`bool`, *optional*, defaults to `False`):
                Whether to continue running the while loop until max_length (needed to avoid deadlocking with
                `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
            streamer (`BaseStreamer`, *optional*):
                Streamer object that will be used to stream the generated sequences. Generated tokens are passed
                through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
            kwargs (`Dict[str, Any]`, *optional*):
                Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
                forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
                specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.

        Return:
            [`~utils.ModelOutput`] or `torch.LongTensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True`
            or when `config.return_dict_in_generate=True`) or a `torch.FloatTensor`.

                If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible
                [`~utils.ModelOutput`] types are:

                    - [`~generation.GenerateDecoderOnlyOutput`],
                    - [`~generation.GenerateBeamDecoderOnlyOutput`]

                If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible
                [`~utils.ModelOutput`] types are:

                    - [`~generation.GenerateEncoderDecoderOutput`],
                    - [`~generation.GenerateBeamEncoderDecoderOutput`]
        Nr+   r,   r   r"  r   r-   r<   r)  
min_lengthr,  has_default_max_lengthhas_default_min_lengthmodel_input_nameinputs_tensorinput_ids_lengthr(  r/  r%   r,  Zinput_ids_seq_lengthZencoder_input_idsZprefix_allowed_tokens_fnr8  rR   r,  r9  )r9   expand_sizer8  r9  r,  r:  r;  Got incompatible mode for generation, should be one of greedy or sampling. Ensure that beam search is de-activated by setting `num_beams=1` and `num_beam_groups=1`.r7   )*r,  copydeepcopyupdatevalidate_validate_model_kwargsr   r   get_prepare_model_inputsr%  r@   r   _prepare_special_tokensrR   r   r-   &_prepare_attention_mask_for_generationr)  r=  _prepare_generated_lengthr+  _decoder_start_token_tensorputcpuget_generation_modeappendr   _get_logits_processor_get_stopping_criteriar   SAMPLEGREEDY_SEARCH_expand_inputs_for_generationnum_return_sequences_samplerB   return_dict_in_generate	sequencesr-  _pad_token_tensorr   )rK   r7  r,  r8  r9  r:  r;  r   model_kwargsrequires_attention_maskkwargs_has_attention_maskr9   rA  
batch_sizerC  r?  r@  r/  generation_moder   
output_idsr7   r7   r8   generateE  s   K







zMusicgenForCausalLM.generate)NNNNNNNNNNNNN)	NNNNNNTNNrG   NNNNNN)!r.   r/   r0   r'   rI   r   r   r  r  r  r  r   r   r2   r5   rn   r3   r   r   r	   r   rj   r0  rk   r+  rl   r-  rm   r   r   r   rh  ro   r7   r7   rL   r8   r  $  s    	

|
/
K
r  z_
    The composite MusicGen model with a text encoder, audio encoder and Musicgen decoder,
    c                $       sF  e Zd ZeZdZdZdZdZdZ					dXde
e de
e de
e de
e f fd	d
Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Ze			dYde
e de
e de
e defdd Ze															dZd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ej  d'e
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 d.e
e de ee!f f d/d0Z"										d[d1d2Z#			dYd3e$d4ed5e%eej&f d6e
e$ d7e
e$ d8ej'deeje%eej&f f fd9d:Z(d;ej&d4e
e d<e)de%ee*f fd=d>Z+	d\d4e
e fd?d@Z,d*ej&fdAdBZ-dCdD Z.dEdF Z/dGdH Z0			dYdIe
ej& d7e
e$ d5e
e%eej&f  dejfdJdKZ1	d]d6e
e e$e2e$ f  d7e
e$ de$fdLdMZ3e4 						d^dIe
ej& d<e
e) dNe
e5 dOe
e6 dPe
e dQe
dR fdSdTZ7d_dVdWZ8  Z9S )` MusicgenForConditionalGenerationZencoder_decoderr9   TNrx   text_encoderaudio_encoderr  c                    s  |du r|du s|du s|du rt d|du r#t|j|j|j}nt|| js4t d| d| j |jjdurQ|jj|jj	krQt d|jj d|jj	 dt
 | |du rgdd	lm} ||j}|du rwdd
lm} ||j}|du rt|j}|| _|| _|| _| jj | jj krtd| jj d| jj  | jj | jj krtd| jj d| jj  | jj | jj krtd| jj d| jj  | jjj| jj_| jjj| jj_| jjj| jj_| jj| j_| jj| j_| jj| j_| jjj	| jjj	kr%| jjjdu r%t| jjj	| jjj	| _| j dur6t d| j dtt| jjj ! }d|vrKt d| "  dS )a  
        text_encoder (`PreTrainedModel`, *optional*):
            The text encoder model that encodes text into hidden states for conditioning.
        audio_encoder (`PreTrainedModel`, *optional*):
            The audio encoder model that encodes audio into hidden states for conditioning.
        decoder (`MusicgenForCausalLM`, *optional*):
            The decoder model that generates audio tokens based on conditioning signals.
        NzlEither a configuration has to be provided, or all three of text encoder, audio encoder and MusicGen decoder.zConfig: z has to be of type zIf `cross_attention_hidden_size` is specified in the MusicGen decoder's configuration, it has to be equal to the text encoder's `hidden_size`. Got z6 for `config.decoder.cross_attention_hidden_size` and z' for `config.text_encoder.hidden_size`.r!   )AutoModelForTextEncodingr#   zConfig of the text_encoder: z/ is overwritten by shared text_encoder config: zConfig of the audio_encoder: z0 is overwritten by shared audio_encoder config: zConfig of the decoder: z* is overwritten by shared decoder config: zThe encoder zB should not have a LM Head. Please use a model without and LM Headr   zThe selected decoder is not prepared for the encoder hidden states to be passed. Please see the following discussion on GitHub: https://github.com/huggingface/transformers/issues/23350)#rB   r&   from_sub_models_configrx   r   r   r  cross_attention_hidden_sizerk  r   rH   rI   auto.modeling_autorm  Zfrom_configr$   rl  r  Z_from_configto_dictr   warningrM   r   r|   r}   enc_to_dec_projr  setinspect	signaturerj   
parameterskeystie_weights)rK   rx   rk  rl  r  rm  r$   Zdecoder_signaturerL   r7   r8   rI     s    
z)MusicgenForConditionalGeneration.__init__c                 C   s<   | j jr| jj}| | j| jj| | jjd}|| _d S d S )Nrk  )rx   Ztie_encoder_decoderr  r   Z_tie_encoder_decoder_weightsrk  Z_modulesZ_dynamic_tied_weights_keys)rK   Zdecoder_base_model_prefixZtied_weightsr7   r7   r8   ry    s   

	z,MusicgenForConditionalGeneration.tie_weightsc                 C   r   rG   )rl  r   r7   r7   r8   get_audio_encoder  r   z2MusicgenForConditionalGeneration.get_audio_encoderc                 C   r   rG   )rk  r   r7   r7   r8   get_text_encoder  r   z1MusicgenForConditionalGeneration.get_text_encoderc                 C   s   |   S rG   )r{  r   r7   r7   r8   get_encoder  s   z,MusicgenForConditionalGeneration.get_encoderc                 C   r   rG   r  r   r7   r7   r8   r    r   z,MusicgenForConditionalGeneration.get_decoderc                 C   
   | j  S rG   )rk  r   r   r7   r7   r8   r     r   z5MusicgenForConditionalGeneration.get_input_embeddingsc                 C   r}  rG   )r  r  r   r7   r7   r8   r    r   z6MusicgenForConditionalGeneration.get_output_embeddingsc                 C   s   | j |S rG   )r  r  r  r7   r7   r8   r    r  z6MusicgenForConditionalGeneration.set_output_embeddings*text_encoder_pretrained_model_name_or_path+audio_encoder_pretrained_model_name_or_path%decoder_pretrained_model_name_or_pathr   c              	   O   s  dd |  D }dd |  D }dd |  D }| D ]}	|d|	 = q| D ]}	|d|	 = q+| D ]}	|d|	 = q7|dd	}
|
d	u r|d	u rQtd
d|vrtj|fi |ddi\}}|jdu sn|jdu r}t	d| d d|_d|_||d< t
j|g|R i |}
|dd	}|d	u r|d	u rtdd|vrtj|fi |ddi\}}|jdu s|jdu rt	d| d d|_d|_||d< t
j|g|R i |}|dd	}|d	u rU|d	u rtdd|vr0tj|fi |ddi\}}t|tr|j}|jdu s|jdu r,t	d| d| d| d d|_d|_||d< |d jdu s@|d jdu rLtd| d| d tj|fi |}tj|
j|j|jfi |}| |
|||dS )a  
        Instantiate a text encoder, an audio encoder, and a MusicGen decoder from one, two or three base classes of the
        library from pretrained model checkpoints.


        The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
        the model, you need to first set it back in training mode with `model.train()`.

        Params:
            text_encoder_pretrained_model_name_or_path (`str`, *optional*):
                Information necessary to initiate the text encoder. Can be either:

                    - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
                    - A path to a *directory* containing model weights saved using
                      [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.

            audio_encoder_pretrained_model_name_or_path (`str`, *optional*):
                Information necessary to initiate the audio encoder. Can be either:

                    - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
                    - A path to a *directory* containing model weights saved using
                      [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.

            decoder_pretrained_model_name_or_path (`str`, *optional*, defaults to `None`):
                Information necessary to initiate the decoder. Can be either:

                    - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
                    - A path to a *directory* containing model weights saved using
                      [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.

            model_args (remaining positional arguments, *optional*):
                All remaining positional arguments will be passed to the underlying model's `__init__` method.

            kwargs (remaining dictionary of keyword arguments, *optional*):
                Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
                `output_attentions=True`).

                - To update the text encoder configuration, use the prefix *text_encoder_* for each configuration
                  parameter.
                - To update the audio encoder configuration, use the prefix *audio_encoder_* for each configuration
                  parameter.
                - To update the decoder configuration, use the prefix *decoder_* for each configuration parameter.
                - To update the parent model configuration, do not use a prefix for each configuration parameter.

                Behaves differently depending on whether a `config` is provided or automatically loaded.

        Example:

        ```python
        >>> from transformers import MusicgenForConditionalGeneration

        >>> # initialize a musicgen model from a t5 text encoder, encodec audio encoder, and musicgen decoder
        >>> model = MusicgenForConditionalGeneration.from_sub_models_pretrained(
        ...     text_encoder_pretrained_model_name_or_path="google-t5/t5-base",
        ...     audio_encoder_pretrained_model_name_or_path="facebook/encodec_24khz",
        ...     decoder_pretrained_model_name_or_path="facebook/musicgen-small",
        ... )
        >>> # saving model after fine-tuning
        >>> model.save_pretrained("./musicgen-ft")
        >>> # load fine-tuned model
        >>> model = MusicgenForConditionalGeneration.from_pretrained("./musicgen-ft")
        ```c                 S   ,   i | ]\}}| d r|td d |qS )text_encoder_N
startswithr  r   argumentr   r7   r7   r8   
<dictcomp>      zOMusicgenForConditionalGeneration.from_sub_models_pretrained.<locals>.<dictcomp>c                 S   r  )audio_encoder_Nr  r  r7   r7   r8   r    r  c                 S   r  decoder_Nr  r  r7   r7   r8   r    
    r  r  r  r   NzxIf `text_encoder_model` is not defined as an argument, a `text_encoder_pretrained_model_name_or_path` has to be defined.rx   Zreturn_unused_kwargsTzInitializing z\ as a text_encoder model from a decoder model. Cross-attention and casual mask are disabled.Fz{If `audio_encoder_model` is not defined as an argument, an `audio_encoder_pretrained_model_name_or_path` has to be defined.z^ as an audio_encoder model from a decoder model. Cross-attention and casual mask are disabled.znIf `decoder_model` is not defined as an argument, a `decoder_pretrained_model_name_or_path` has to be defined.z9 as a decoder model. Cross attention layers are added to z and randomly initialized if z2's architecture allows for cross attention layers.zDecoder model z9 is not initialized as a decoder. In order to initialize z as a decoder, make sure that the attributes `is_decoder` and `add_cross_attention` of `decoder_config` passed to `.from_sub_models_pretrained(...)` are set to `True` or do not pass a `decoder_config` to `.from_sub_models_pretrained(...)`)rk  rl  r  rx   )itemsrx  poprB   r"   Zfrom_pretrainedru   Zadd_cross_attentionr   infor$   r   r&   r  rr  r  rn  rx   )clsr~  r  r  Z
model_argsr   kwargs_text_encoderkwargs_audio_encoderkwargs_decoderkeyrk  Zencoder_configrl  r  Zdecoder_configrx   r7   r7   r8   from_sub_models_pretrained  s   H



 z;MusicgenForConditionalGeneration.from_sub_models_pretrainedr,   input_valuespadding_maskdecoder_input_idsdecoder_attention_maskr+   r   r   decoder_inputs_embedsr  r   r   r   r   c                 K   s  |dur|n| j j}dd | D }dd | D }dd | D }|du r9| jd|||	|||d|}n	t|trBt| }|d }| jj j| jj jkr\| jj j	du r\| 
|}|durf||d  }|dur|du r|
du rt|| j jj| j jj}nN|du r|
du r| jd||d	|}|j}|j\}}}}|d
krtd| d| j jjdkr|jd | jjd kr|jddd}|d || jj |}| jd|||||
||||||d|}|s|| S t|j|j|j|j|j|j|j|j|jd	S )a  
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size * num_codebooks, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary, corresponding to the sequence of audio codes.

            Indices can be obtained by encoding an audio prompt with an audio encoder model to predict audio codes,
            such as with the [`EncodecModel`]. See [`EncodecModel.encode`] for details.

            [What are decoder input IDs?](../glossary#decoder-input-ids)

            <Tip warning={true}>

            The `decoder_input_ids` will automatically be converted from shape `(batch_size * num_codebooks,
            target_sequence_length)` to `(batch_size, num_codebooks, target_sequence_length)` in the forward pass. If
            you obtain audio codes from an audio encoding model, such as [`EncodecModel`], ensure that the number of
            frames is equal to 1, and that you reshape the audio codes from `(frames, batch_size, num_codebooks,
            target_sequence_length)` to `(batch_size * num_codebooks, target_sequence_length)` prior to passing them as
            `decoder_input_ids`.

            </Tip>
        decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
            be used by default.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length, num_codebooks)`, *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]`
        padding_mask (`torch.BoolTensor` 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)

        Examples:
        ```python
        >>> from transformers import AutoProcessor, MusicgenForConditionalGeneration
        >>> import torch

        >>> processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
        >>> model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")

        >>> inputs = processor(
        ...     text=["80s pop track with bassy drums and synth", "90s rock song with loud guitars and heavy drums"],
        ...     padding=True,
        ...     return_tensors="pt",
        ... )

        >>> pad_token_id = model.generation_config.pad_token_id
        >>> decoder_input_ids = (
        ...     torch.ones((inputs.input_ids.shape[0] * model.decoder.num_codebooks, 1), dtype=torch.long)
        ...     * pad_token_id
        ... )

        >>> logits = model(**inputs, decoder_input_ids=decoder_input_ids).logits
        >>> logits.shape  # (bsz * num_codebooks, tgt_len, vocab_size)
        torch.Size([8, 1, 2048])
        ```Nc                 S   (   i | ]\}}| d r|td  |qS )r  r  r  r7   r7   r8   r        z<MusicgenForConditionalGeneration.forward.<locals>.<dictcomp>c                 S   r  )r  r  r  r7   r7   r8   r    r  c                 S   r  r  r  r  r7   r7   r8   r    r  )r9   r,   r   r   r   r   r   ).N)r  r  r%   0Expected 1 frame in the audio code outputs, got Y frames. Ensure chunking is disabled by setting `chunk_length=None` in the audio encoder.r!   rX   r   .)r9   r,   r   r   r   r   r   r   r   r   r  )	r#  r$  r   Zdecoder_hidden_statesZdecoder_attentionsr  Zencoder_last_hidden_stater   Zencoder_attentionsr7   )rx   r  r  rk  r   r	  r   r   r  ro  rs  rC   r:   r;   rl  audio_codesr@   rB   r3  r   r4  r   r   r#  r$  r   r   r   r  r   )rK   r9   r,   r  r  r  r  r+   r   r   r  r  r   r   r   r   r   r  r  r  r   audio_encoder_outputsr  framesrg   rh   ri   r  r7   r7   r8   rj   k  s   N
	

$z(MusicgenForConditionalGeneration.forwardc                 K   s   |
d u r| j j|| jj| jjd\}}
| j ||
}|d ur0|dkr0|d}|d ur0|d}|d urX|d d jd }|jd |krG|}n|jd d }|d d |d f }d |	||||||||d
S )N)r)  r%   r*  r   r!   )
r9   r+   r   r  r,   r  r   decoder_head_maskr   r   )r  r+  r,  r:   r)  r-  r.  r@   )rK   r  r   r,   r   r  r  r   r   r+   decoder_delay_pattern_maskr-   r   Zpast_lengthZremove_prefix_lengthr7   r7   r8   r0    s8   


z>MusicgenForConditionalGeneration.prepare_inputs_for_generationre  rA  rb  r;   r%  rR   c           
      C   s   |durd|v r| d}nd|v r|dkr| d}nd}| ||}|du r+| j}tj|| jj dftj|d| }|du rF|}||fS |d |k 	 rytj
||gdd}d	|v ry|d	 }	tj
t|	ddddf |	fdd}	|	|d	< ||fS )
zGPrepares `decoder_input_ids` for generation with encoder-decoder modelsNr  r9   r%   rP   r=   r<   rX   r  )r  _get_decoder_start_token_idrR   r2   r1  r  r   r2  allitemr^   Z	ones_like)
rK   re  rA  rb  r;   r%  rR   r  Zdecoder_input_ids_startr  r7   r7   r8   )_prepare_decoder_input_ids_for_generationV  s2   zJMusicgenForConditionalGeneration._prepare_decoder_input_ids_for_generationrB  r,  c           
         s(  |   }t|drd|j_g dfdd| D }tt|jj	 d v p,d v }|s: fdd| D }|j
|d	< |j|d
< |j}|d urM|n| jj}d|d< |||< |di |j}	|d ur|dkrtj|	t|	gdd}	d|v rtj|d t|d gdd|d< t|	d|d< |S )N_hf_hookTr  Z
cross_attnr   c                    ,   i | ]\ }t  fd dD s |qS )c                 3       | ]}  |V  qd S rG   r  r   r   r  r7   r8   r         zjMusicgenForConditionalGeneration._prepare_text_encoder_kwargs_for_generation.<locals>.<dictcomp>.<genexpr>r   r   r   irrelevant_prefixr  r8   r        z`MusicgenForConditionalGeneration._prepare_text_encoder_kwargs_for_generation.<locals>.<dictcomp>r   rb  c                       i | ]\}}| v r||qS r7   r7   r  encoder_signaturer7   r8   r        r   r   r   r%   r   rX   r,   r   r+   r7   )r{  rU   r  io_same_devicer  rt  ru  rv  rj   rw  r   r   r-   rk  main_input_namer   r2   ZconcatenateZ
zeros_liker   )
rK   rB  rb  rA  r,  encoderencoder_kwargsencoder_accepts_wildcardr-   r   r7   r  r  r8   +_prepare_text_encoder_kwargs_for_generation  s8   





zLMusicgenForConditionalGeneration._prepare_text_encoder_kwargs_for_generationc                    sJ  |   }t|drd|j_g dfdd| D }tt|jj	 d v p,d v }|s: fdd| D }|d ur@|n| j
j}d|d	< | jjjd
kri|||< |jdi |}|j}|j}	|j\}
}}}n|jd
 dkr{td|jd
  d|d d d d
d d f ||< |jdi |}|j}|j}|d d d
d d d f ||< |jdi |}|j}|j}|j\}
}}}||
|d| |f}||d d d d d d dd d f< ||d d d d d
d dd d f< |d gks|d gkrtj||gd
d}	nd g| }	|
d
krtd|
 d|d || jj |}||d< |	|d< |S )Nr  Tr  c                    r  )c                 3   r  rG   r  r  r  r7   r8   r     r  zkMusicgenForConditionalGeneration._prepare_audio_encoder_kwargs_for_generation.<locals>.<dictcomp>.<genexpr>r  r  r  r  r8   r    r  zaMusicgenForConditionalGeneration._prepare_audio_encoder_kwargs_for_generation.<locals>.<dictcomp>r   rb  c                    r  r7   r7   r  r  r7   r8   r    r  r   r%   r!   z3Expected stereo audio (2-channels) but example has z	 channel.rX   r  r  r  r  audio_scalesr7   )rz  rU   r  r  r  rt  ru  rv  rj   rw  rl  r  r  rx   r3  encoder  r  r@   rB   Znew_onesr2   r&  r   r   )rK   r  rb  rA  r  r  r  r  r  r  r  rg   rh   ri   Zaudio_encoder_outputs_leftZaudio_codes_leftZaudio_scales_leftZaudio_encoder_outputs_rightZaudio_codes_rightZaudio_scales_rightr  r7   r  r8   ,_prepare_audio_encoder_kwargs_for_generation  s`   


""


zMMusicgenForConditionalGeneration._prepare_audio_encoder_kwargs_for_generationc                 C   s   t || jjj| jjjS rG   )rC   rx   r  r:   r%  )rK   r  r7   r7   r8   %prepare_decoder_input_ids_from_labels	  s   zFMusicgenForConditionalGeneration.prepare_decoder_input_ids_from_labelsc                 O   s   t d)NzResizing the embedding layers via the EncoderDecoderModel directly is not supported. Please use the respective methods of the wrapped objects (model.encoder.resize_token_embeddings(...) or model.decoder.resize_token_embeddings(...)))NotImplementedErrorr   r7   r7   r8   resize_token_embeddings	  s   z8MusicgenForConditionalGeneration.resize_token_embeddingsc                 C   "   | j  D ]}d|_qd| j _dS )z3
        Freeze the audio encoder weights.
        FN)rl  rw  requires_grad_requires_gradrK   paramr7   r7   r8   freeze_audio_encoder	     z5MusicgenForConditionalGeneration.freeze_audio_encoderc                 C   r  )z2
        Freeze the text encoder weights.
        FN)rk  rw  r  r  r  r7   r7   r8   freeze_text_encoder	  r  z4MusicgenForConditionalGeneration.freeze_text_encoderr7  c                 C   s   |dur|S | d}|dur%|d  dd }tj|tj| jdd S |du r-tdd}| D ]}t|tj	rB|j
d } nq3tj|dftj| jd| S )	z3Initializes input ids for generation, if necessary.Nr+   r   r<   rP   r>   zB`bos_token_id` has to be defined when no `input_ids` are provided.r%   )rN  rd   r2   r1  r2  rR   rB   valuesr   rn   r@   )rK   r7  r%  rb  r+   r@   re  r   r7   r7   r8   *_maybe_initialize_input_ids_for_generation	  s   

zKMusicgenForConditionalGeneration._maybe_initialize_input_ids_for_generationc                 C   sH   |d ur|n| j j}|d ur|n| j j}|d ur|S |d ur |S td)Nz\`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation.)r,  r;   r%  rB   )rK   r;   r%  r7   r7   r8   r  8	  s   z<MusicgenForConditionalGeneration._get_decoder_start_token_idr8  r9  r:  r;  r)   c                 K   s  |du r| j }t|}|jdi |}|  | |  |ddur9t|d tu r9t	|d d d|d< |dur?|nt
 }|durH|nt }d|v}	|dddu}
| ||j|\}}}|jd }| j||
|jd |j|d< |j|d< |dddu r|	r| ||||d< d|vr| ||||}d	|vrd
|v r| |d
 |}| j||||j|j|jd\}}|jd }|ddu o|jdu}|ddu o|jdu}| j||||||d}| jj||j|jd\}}||d< |dur||  |  }|jdur|jdkr|!t"|j d|_| j#|||d||jd}| j$||d}|t%j&t%j'fv rU| j(d||j)| j*j+d|\}}| j,|f|||||d|}nt-d|j.ra|j/}n|}| j0||d }|||j1k 2|| jj3d}|d }|d}|du rdg| }| jj*j4dkr| j5j6||dj7}n=| j5j6|dddddddddf |d}|j7}| j5j6|dddddddddf |d}|j7}t8j9||gdd}|j.r||_/|S |S )r<  Nr+   r   r  r,   r"  r   r-   r  r  )re  rA  rb  r;   r%  rR   r<   r)  r=  r>  r(  r  r%   rD  rE  )r9   rF  is_encoder_decoderrG  rH  )N.r  )r  r!   rX   r7   ):r,  rI  rJ  rK  rL  rM  rN  typer	  r   r   r   rO  r%  r@   rP  rR   r   r-   rQ  r  r  r  rS  Z_bos_token_tensorr)  r=  rR  r  r+  rT  rU  rV  rW  r   rX  rY  r   rZ  r[  r\  r]  rx   r  r^  rB   r_  r`  r-  ra  r   r   r3  rl  decodeZaudio_valuesr2   r^   )rK   r7  r,  r8  r9  r:  r;  r   rb  rc  rd  rB  rA  re  r9   rC  r?  r@  r  rf  r   rg  r  Zoutput_valuesZcodec_outputs_leftZoutput_values_leftZcodec_outputs_rightZoutput_values_rightr7   r7   r8   rh  J	  s   K















..z)MusicgenForConditionalGeneration.generater%   c                 C   sH   t j|d| jjjf| j| jd}t j|df| jt jd}t|f|ddS )a  
        Helper function to get null inputs for unconditional generation, enabling the model to be used without the
        feature extractor or tokenizer.

        Args:
            num_samples (int, *optional*):
                Number of audio samples to unconditionally generate.
            max_new_tokens (int, *optional*):
                Number of tokens to generate for each sample. More tokens means longer audio samples, at the expense of
                longer inference (since more audio tokens need to be generated per sample).

        Example:
        ```python
        >>> from transformers import MusicgenForConditionalGeneration

        >>> model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")

        >>> # get the unconditional (or 'null') inputs for the model
        >>> unconditional_inputs = model.get_unconditional_inputs(num_samples=1)
        >>> audio_samples = model.generate(**unconditional_inputs, max_new_tokens=256)
        ```r%   )rR   rQ   r   )r+   r,   r-   )	r2   rb   rx   rk  r   rR   rQ   r2  r*   )rK   Znum_samplesr   r,   r7   r7   r8   get_unconditional_inputsA
  s   z9MusicgenForConditionalGeneration.get_unconditional_inputs)NNNN)NNN)NNNNNNNNNNNNNNN)
NNNNNNNNNNrG   )NNri  )r%   ):r.   r/   r0   r&   r   r   r  r   r   r   r   r   r  rI   ry  rz  r{  r|  r  r   r  r  classmethodstrr  r   r2   r5   Z
BoolTensorr3   r   r   r	   r   rj   r0  rk   r   rn   rR   r  r   r   r  r  r  r  r  r  r  r   r  rm   r   r   rh  r  ro   r7   r7   rL   r8   rj    sh   e E	

 4
?
/

2
L


 wrj  )rj  r  r  r   )Mr1   rI  ru  rZ   r  dataclassesr   typingr   r   r   r   r   r   r	   r2   Ztorch.nnr|   r
   Zactivationsr   Z
generationr   r   r   r   r   r   Zmodeling_attn_mask_utilsr   r   r   r   Zmodeling_flash_attention_utilsr   r   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   utilsr   r    Zauto.configuration_autor"   rp  r$   Zconfiguration_musicgenr&   r'   r(   Zgeneration.streamersr)   Z
get_loggerr.   r   r*   rn   rk   rC   ModulerD   rp   r   r   r   r   r   r   r  r  rj  __all__r7   r7   r7   r8   <module>   s   $ 
,  z{{ |h   h        Y