U
    9%e                    @   sV  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 ddlZddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZ 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'm(Z(m)Z) ddl*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0 er*ddl1m2Z2 e(3e4Z5dZ6dZ7dgZ8eG dd de!Z9d8ej:ej;ej<e=dddZ>d9ej?ej;ee= dddZ@ej?e=e=dd d!ZAG d"d# d#ejBZCG d$d% d%ejBZDG d&d' d'ejBZEG d(d) d)e$ZFd*ZGd+ZHd,ZIG d-d. d.eFZJe&d/eGG d0d1 d1eFZKe&d2eGG d3d4 d4eFZLe&d5eGG d6d7 d7e$ZMdS ):z PyTorch Musicgen model.    N)	dataclass)TYPE_CHECKINGAnyDictOptionalTupleUnion)CrossEntropyLoss)
checkpoint   )ACT2FN)GenerationConfig)%ClassifierFreeGuidanceLogitsProcessorLogitsProcessorList)StoppingCriteriaList)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsModelOutputSeq2SeqLMOutput)PreTrainedModel)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )
AutoConfig	AutoModel   )MusicgenConfigMusicgenDecoderConfig)BaseStreamerr    zfacebook/musicgen-smallc                   @   s>   e Zd ZU dZdZeej ed< dZ	ej
ed< dZ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%   
LongTensorr&   float r0   r0   m/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/musicgen/modeling_musicgen.pyr#   A   s   
r#   )input_ids_shapedtypedevicepast_key_values_lengthc                 C   s   | \}}t j||ft |j|d}t j|d|d}|||d |ddk d ||}|dkrt j	t j
||||d|gdd}|ddddddf |d||| S )zB
    Make causal mask used for bi-directional self-attention.
    )r4   r   r   r3   r4   dimN)r+   fullfinfominarangesizemasked_fill_viewtocatzerosexpand)r2   r3   r4   r5   bsztgt_lenmaskZ	mask_condr0   r0   r1   _make_causal_maskU   s    "
 rH   )rG   r3   rF   c                 C   sj   |   \}}|dk	r|n|}| ddddddf |d|||}d| }||tjt|jS )z_
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    Nr         ?)r>   rD   rA   Zmasked_fillr+   boolr;   r<   )rG   r3   rF   rE   src_lenZexpanded_maskZinverted_maskr0   r0   r1   _expand_maskg   s
    *rL   )	input_idspad_token_iddecoder_start_token_idc                 C   sx   |  | j}| ddddf  |ddddf< |dkrDtd||dddf< |dkrdtd||dk| |S )z1
    Shift input ids one token to the right.
    Nr6   r   zSMake 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.)Z	new_zerosshapeclone
ValueErrorr?   )rM   rN   rO   Zshifted_input_idsr0   r0   r1   shift_tokens_rightv   s    (rT   c                       sh   e Zd ZdZeed fddZeedddZeeeddd	Ze	
 de	jed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__rW   make_weights)selfrV   rW   	__class__r0   r1   rZ      s    
z.MusicgenSinusoidalPositionalEmbedding.__init__)num_embeddingsrW   c                 C   sN   |  ||}t| dr,|j| jj| jjd}t|| _d| j_| j	  d S )Nweightsr7   F)
get_embeddinghasattrrA   r`   r3   r4   nn	ParameterZrequires_gradZdetach_)r\   r_   rW   Zemb_weightsr0   r0   r1   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rt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   r3   r   r8   r6   )mathlogr+   expr=   r/   Z	unsqueezerB   cossinr@   rC   rA   Zget_default_dtype)r_   rW   Zhalf_dimZembr0   r0   r1   ra      s     &z3MusicgenSinusoidalPositionalEmbedding.get_embeddingr   )rM   r5   c                 C   s`   |  \}}}t|| |j}|| j dkrH| || j | j | j	d|
d S )Nr   r6   )r>   r+   r=   rA   r4   r`   r[   offsetrW   Zindex_selectr@   detach)r\   rM   r5   rE   	codebooksseq_lenZposition_idsr0   r0   r1   forward   s
    z-MusicgenSinusoidalPositionalEmbedding.forward)r   )r'   r(   r)   r*   intrZ   r[   staticmethodra   r+   no_gradTensorro   __classcell__r0   r0   r]   r1   rU      s   
rU   c                       s   e Zd ZdZdeeeeed fddZej	eedd	d
Z
dej	eej	 eeej	  eej	 eej	 eeej	eej	 eeej	  f dddZ  ZS )MusicgenAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FT	embed_dim	num_headsdropout
is_decoderbiasc                    s   t    || _|| _|| _|| | _| j| | jkrNt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      ࿩r|   )rY   rZ   rx   ry   rz   head_dimrS   scalingr{   rc   Lineark_projv_projq_projout_proj)r\   rx   ry   rz   r{   r|   r]   r0   r1   rZ      s    

zMusicgenAttention.__init__)tensorrn   rE   c                 C   s    | ||| j| jdd S )Nr   r   )r@   ry   r~   	transpose
contiguous)r\   r   rn   rE   r0   r0   r1   _shape   s    zMusicgenAttention._shapeN)hidden_stateskey_value_statespast_key_valuer%   layer_head_maskoutput_attentionsreturnc                 C   sx  |dk	}|  \}}	}
| || j }|r\|dk	r\|d jd |jd kr\|d }|d }n|r| | |d|}| | |d|}n|dk	r| | |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k	r |  |d|	|fkrtd	|d|	|f d|   ||| j
|	|| }||| j
 |	|}tjj|dd}|dk	r|  | j
fkrhtd
| j
f d|   |dddd||| j
|	| }||| j
 |	|}|r||| j
|	|}||| j
 |	|}nd}tjj|| j| jd}t||}|  || j
 |	| jfkr4td|| j
 |	| jf d|   ||| j
|	| j}|dd}|||	| j}| |}|||fS )z#Input shape: Batch x Time x ChannelNr   r   r   r6   r8   z$Attention weights should be of size z	, but is z!Attention mask should be of size z/Head mask for a single layer should be of size ptrainingz `attn_output` should be of size )r>   r   r   rQ   r   r   r   r+   rB   r{   ry   r~   r@   reshapeZbmmr   rS   rc   
functionalZsoftmaxrz   r   rx   r   )r\   r   r   r   r%   r   r   Zis_cross_attentionrE   rF   _Zquery_statesZ
key_statesZvalue_statesZ
proj_shaperK   Zattn_weightsZattn_weights_reshapedZ
attn_probsZattn_outputr0   r0   r1   ro      s~    





" 
zMusicgenAttention.forward)rv   FT)NNNNF)r'   r(   r)   r*   rp   r/   rJ   rZ   r+   rs   r   r   r   ro   rt   r0   r0   r]   r1   ru      s4           ru   c                       sx   e Zd Zed fddZd
ejeej eej eej eej eej eeej  ee	 ee	 ejd
dd	Z
  ZS )MusicgenDecoderLayerconfigc                    s   t    |j| _t| j|j|jddd| _|j| _t	|j
 | _|j| _t| j| _t| j|j|jddd| _t| j| _tj| j|jdd| _tj|j| jdd| _t| j| _d S )NTFrw   )rz   r{   r|   r}   )rY   rZ   hidden_sizerx   ru   Znum_attention_headsZattention_dropout	self_attnrz   r   Zactivation_functionactivation_fnactivation_dropoutrc   	LayerNormself_attn_layer_normencoder_attnencoder_attn_layer_normr   Zffn_dimfc1fc2final_layer_normr\   r   r]   r0   r1   rZ   Q  s0    
zMusicgenDecoderLayer.__init__NFT)
r   r%   encoder_hidden_statesencoder_attention_maskr   cross_attn_layer_head_maskr   r   	use_cacher   c
                 C   s^  |}
|  |}|dk	r"|dd nd}| j|||||d\}}}tjj|| j| jd}|
| }d}d}|dk	r|}
| |}|dk	r|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}|rJ|||f7 }|	rZ||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   rc   r   rz   r   r   r   r   r   r   r   r   )r\   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outputsr0   r0   r1   ro   n  sT    




zMusicgenDecoderLayer.forward)NNNNNNFT)r'   r(   r)   r!   rZ   r+   rs   r   r   rJ   ro   rt   r0   r0   r]   r1   r   P  s*            r   c                   @   s6   e Zd ZdZeZdZdZddgZdd Z	dd	d
Z
dS )MusicgenPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    modelTr   ru   c                 C   s   | j j}t|tjtjfrD|jjjd|d |j	d k	r~|j	j
  n:t|tjr~|jjjd|d |jd k	r~|jj|j 
  d S )Nrv   )Zmeanstd)r   Zinitializer_factor
isinstancerc   r   ZConv1dweightdataZnormal_r|   Zzero_	EmbeddingZpadding_idx)r\   moduler   r0   r0   r1   _init_weights  s    

z%MusicgenPreTrainedModel._init_weightsFc                 C   s   t |tr||_d S rX   )r   MusicgenDecodergradient_checkpointingr\   r   valuer0   r0   r1   _set_gradient_checkpointing  s    
z3MusicgenPreTrainedModel._set_gradient_checkpointingN)F)r'   r(   r)   r*   r!   config_classbase_model_prefixsupports_gradient_checkpointingZ_no_split_modulesr   r   r0   r0   r0   r1   r     s   r   u  

    The Musicgen model was proposed in [Simple and Controllable Music Generation](https://arxiv.org/abs/2306.05284) by
    Jade Copet, Felix Kreuk, Itai Gat, Tal Remez, David Kant, Gabriel Synnaeve, Yossi Adi, Alexandre Défossez. It is an
    encoder decoder transformer trained on the task of conditional music generation

    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 ([`MusicgenConfig`]): 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.
as  
    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.

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

            [What are input IDs?](../glossary#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)
        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.
        head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:

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

        decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:

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

        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. Mask values selected in `[0,
            1]`:

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

        encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
            Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
            `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
            hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
            `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`. 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.
        decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
            representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
            input (see `past_key_values`). This is useful if you want more control over how to convert
            `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

            If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
            of `inputs_embeds`.
        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.
a  
    Args:
        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>

        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)
        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)
        head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

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

        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**.

        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
            `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`. 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.
        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                       s   e Zd ZdZed fddZdd Zdd Zd	d
 Ze	e
dejeej eej eej eej eej eeeej   eej ee ee ee ee eeef dddZ  ZS )r   zw
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MusicgenDecoderLayer`]
    r   c                    s   t     j| _ j| _ j| _ j| _ j| _ j	rFt
 jnd| _ jd t fddt jD | _t j j| _t fddt jD | _t j| _d| _|   d S )NrI   r   c                    s   g | ]}t  jqS r0   )rc   r   r   .0r   r   rx   r0   r1   
<listcomp>  s     z,MusicgenDecoder.__init__.<locals>.<listcomp>c                    s   g | ]}t  qS r0   )r   r   r   r0   r1   r     s     F)rY   rZ   rz   	layerdropZmax_position_embeddingsZmax_target_positionsr   Zd_modelnum_codebooksZscale_embeddingrf   sqrtZembed_scale
vocab_sizerc   
ModuleListrangeembed_tokensrU   embed_positionsZnum_hidden_layerslayersr   
layer_normr   	post_initr   r]   r   r1   rZ     s&    
 zMusicgenDecoder.__init__c                 C   s   | j S rX   r   r\   r0   r0   r1   get_input_embeddings  s    z$MusicgenDecoder.get_input_embeddingsc                 C   s
   || _ d S rX   r   r\   r   r0   r0   r1   set_input_embeddings  s    z$MusicgenDecoder.set_input_embeddingsc                 C   s`   d }|d dkr$t ||j|j|d}|d k	r\t||j|d d|j}|d krT|n|| }|S )Nr6   r   )r4   r5   rF   )rH   r3   r4   rL   rA   )r\   r%   input_shapeinputs_embedsr5   Zcombined_attention_maskZexpanded_attn_maskr0   r0   r1   _prepare_decoder_attention_mask  s    z/MusicgenDecoder._prepare_decoder_attention_maskNrM   r%   r   r   	head_maskcross_attn_head_maskpast_key_valuesr   r   r   output_hidden_statesreturn_dictr   c           !         s  d k	rnj j|d k	r |nj j}d k	r4nj j|d k	rH|nj j}|d k	rj|d k	rjtdnp|d k	r|dj|jd   j\}}}||f}n<|d k	r|	 d d }|d d d d dd f  ntd|d k	r|d d jd nd}|d krt
 fddt|D }||||}|d k	rV|d k	rVt||j|d d} |}|||j }tjj|jjd	}jrjrrtd
 d|rdnd }rdnd }r|d k	rdnd }rdnd }t||gddgD ]V\}}|d k	r |	 d tjkr td| dtj d|	 d  dq tjD ]B\}}|r|||f7 }tdd}jr|jk rqb|d k	r|| nd }jrjrfdd}t |||||||d k	r|| nd |d k	r
|| nd d }n>||||||d k	r0|| nd |d k	rD|| nd |d	}|d }rx||rndnd f7 }rb||d f7 }|d k	rb||d f7 }qb!|}|r||f7 }r|nd } |st"dd || |||fD S t#|| |||dS )NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer6   zEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   r   c                    s&   g | ]}j |  d d |f qS rX   r   )r   codebook)inputr\   r0   r1   r     s     z+MusicgenDecoder.forward.<locals>.<listcomp>r   r   z[`use_cache=True` is incompatible with gradient checkpointing`. Setting `use_cache=False`...Fr0   r   r   zThe `z` should be specified for z layers, but it is for .r   c                    s    fdd}|S )Nc                     s    | f S rX   r0   )inputs)r   r   r   r0   r1   custom_forward?  s    zNMusicgenDecoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr0   )r   r   )r   r   )r   r1   create_custom_forward>  s    z6MusicgenDecoder.forward.<locals>.create_custom_forward)r%   r   r   r   r   r   r   r   r   c                 s   s   | ]}|d k	r|V  qd S rX   r0   )r   vr0   r0   r1   	<genexpr>p  s   z*MusicgenDecoder.forward.<locals>.<genexpr>last_hidden_stater   r   
attentionscross_attentions)$r   r   r   r   use_return_dictrS   r   r   rQ   r>   sumr   r   rL   r3   r   rA   r4   rc   r   rz   r   r   loggerZwarning_onceziplenr   	enumeraterandomuniformr   r
   r   tupler   )!r\   rM   r%   r   r   r   r   r   r   r   r   r   r   rE   r   rn   r   r5   Z	positionsr   Zall_hidden_statesZall_self_attnsZall_cross_attentionsZnext_decoder_cacheZ	attn_maskZ	mask_nameidxZdecoder_layerZdropout_probabilityr   r   Zlayer_outputsZ
next_cacher0   )r   r   r\   r   r1   ro     s    


   
$



zMusicgenDecoder.forward)NNNNNNNNNNNN)r'   r(   r)   r*   r!   rZ   r   r   r   r   !MUSICGEN_DECODER_INPUTS_DOCSTRINGr+   r.   r   rs   r,   r   rJ   r   r   ro   rt   r0   r0   r]   r1   r     sB               
r   z^The bare Musicgen decoder model outputting raw hidden-states without any specific head on top.c                       s   e Zd Zed fddZdd Zdd Zdd	 Zee	de
jee
j ee
j ee
j ee
j ee
j eeee
j   ee
j ee ee ee ee eeef dddZ  ZS )MusicgenModelr   c                    s"   t  | t|| _|   d S rX   )rY   rZ   r   decoderr   r   r]   r0   r1   rZ     s    
zMusicgenModel.__init__c                 C   s   | j jS rX   r   r   r   r0   r0   r1   r     s    z"MusicgenModel.get_input_embeddingsc                 C   s   || j _d S rX   r   r   r0   r0   r1   r     s    z"MusicgenModel.set_input_embeddingsc                 C   s   | j S rX   r   r   r0   r0   r1   get_decoder  s    zMusicgenModel.get_decoderNr   c                 C   s   |
d k	r|
n| j j}
|d k	r |n| j j}|	d k	r4|	n| j j}	|d k	rH|n| j j}| j|||||||||	|
||d}|sz|S t|j|j|j	|j
|jdS )N)rM   r%   r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   )r\   rM   r%   r   r   r   r   r   r   r   r   r   r   decoder_outputsr0   r0   r1   ro     s8    zMusicgenModel.forward)NNNNNNNNNNNN)r'   r(   r)   r!   rZ   r   r   r   r   r   r+   r.   r   rs   r,   r   rJ   r   r   ro   rt   r0   r0   r]   r1   r   ~  s@               
r   zAThe MusicGen decoder model with a language modelling head on top.c                       sJ  e Zd Zed fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
eeeeedd!ejeej eej eej eej eej eeeej   eej eej ee ee ee ee eeef dddZd"ddZd#ejeedddZedd Ze d$eej ee  ee! ee" ee ed ddd Z#  Z$S )%MusicgenForCausalLMr   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 )Fr}   )rc   r   r   r   r   r   r0   r1   r     s     z0MusicgenForCausalLM.__init__.<locals>.<listcomp>)
rY   rZ   r   r   r   rc   r   r   lm_headsr   r   r]   r   r1   rZ     s    
zMusicgenForCausalLM.__init__c                 C   s
   | j jjS rX   r   r   r   r   r0   r0   r1   r     s    z(MusicgenForCausalLM.get_input_embeddingsc                 C   s   || j j_d S rX   r   r   r0   r0   r1   r     s    z(MusicgenForCausalLM.set_input_embeddingsc                 C   s   | j S rX   r   r   r0   r0   r1   get_output_embeddings  s    z)MusicgenForCausalLM.get_output_embeddingsc                 C   s
   || _ d S rX   r   r\   Znew_embeddingsr0   r0   r1   set_output_embeddings  s    z)MusicgenForCausalLM.set_output_embeddingsc                 C   s   || j _d S rX   r   r   )r\   r   r0   r0   r1   set_decoder  s    zMusicgenForCausalLM.set_decoderc                 C   s   | j jS rX   r   r   r0   r0   r1   r     s    zMusicgenForCausalLM.get_decoderoutput_typer   N)rM   r%   r   r   r   r   r   r   labelsr   r   r   r   r   c                    s   |dk	r|n| j j}| j|||||||||
|||d}|d  tj fdd| jD dd}d}|	dk	rptd|jd|jd
d  }|s|f|dd  }|dk	r|f| S |S t	|||j
|j|j|jd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]`
                Returns:
        N)r%   r   r   r   r   r   r   r   r   r   r   r   c                    s   g | ]}| qS r0   r0   )r   headr   r0   r1   r     s     z/MusicgenForCausalLM.forward.<locals>.<listcomp>r   r8   z)Training is not implemented for Musicgen.r6   r   )losslogitsr   r   r   r   )r6   )r   r   r   r+   stackr   NotImplementedErrorr   rQ   r   r   r   r   r   )r\   rM   r%   r   r   r   r   r   r   r  r   r   r   r   r   Z	lm_logitsr  outputr0   r  r1   ro     s@    zMusicgenForCausalLM.forwardTc              	   K   s   |	d kr$| j || jj| jjd\}}	| ||	}|
d k	r\|
dkr\|d}|d k	r\|d}|d k	rx|d d dd f }||||||||dS )NrN   
max_lengthr   r   r   r6   )rM   r%   r   r   r   r   r   r   )build_delay_pattern_maskgeneration_configrN   r
  apply_delay_pattern_maskrepeat)r\   rM   r%   r   r   r   r   r   r   delay_pattern_maskr&   kwargsr0   r0   r1   prepare_inputs_for_generation,  s,    


z1MusicgenForCausalLM.prepare_inputs_for_generation)rM   rN   r
  c                 C   s  | d| j|jd }|j\}}}|dk	r.|n| jj}tj|||ftj|jdd }|d| d k r| || d| || dfS t	|D ]*}|dd|f |dd|||| f< qtj
tj||ftjd|| d d}	|	ttj||ftjd }	|	|j }
|
| |
 |  }|dddddf }|dk dddf }t|dkrbt|}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.
        r6   Nr7   r   r   re   )Zdiagonalr   .)r   r   rQ   r  r
  r+   oneslongr4   r   ZtriurJ   ZtrilrA   Znonzeror   r<   )r\   rM   rN   r
  rE   r   rn   Zinput_ids_shiftedr   Zdelay_patternrG   Zfirst_codebook_idsZ	start_idsZfirst_start_idZpattern_maskr0   r0   r1   r  Y  s0     ( 

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.r6   .N)rQ   r+   where)rM   Zdecoder_pad_token_maskrn   r0   r0   r1   r    s    
z,MusicgenForCausalLM.apply_delay_pattern_maskr"   r   r  logits_processorstopping_criteriasynced_gpusstreamerc                 K   s  |dkr| j }t|}|jf |}|  | |  |dk	rF|nt }|dk	rX|nt }|jdkr|j	dk	r|
dddkrtd |j	}	t|	tr|	d }	td|	 d |	|_| ||j|\}
}}|
jd | j }|j|d< |j|d< |j|d	< |j|d
< d|k}|
dddkr@|r@| |
|j|j	|d< |
jd }|
ddkob|jdk	}|r|jdkr|jdkrtd|j d n:|jdk	r|std|j d|j d |j| |_|jdk	r|j|jkrtd|j d|j d||jkr,td| d|j d | j|
|j|jd\}
}|dk	r\||
  ||d< |j dko|j!dko|j"dk}|j dko|j!dko|j"dk}|jdk	r|jdkr|#t$|j d|_| j%|||
d|d}| j&||d }|rJ|j'dkrtd!|j' d"| j(|
f|||j|j	|j)|j*||d#|}nd|r| +|}| j,f |
|j'd$|\}
}| j-|
f||||j|j	|j)|j*||d%	|}ntd&|j*r|j.}n|}| /||d }|||jk 0|| jd}|j*r||_.|S |S dS )'  

        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 for 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.GreedySearchDecoderOnlyOutput`],
                    - [`~generation.SampleDecoderOnlyOutput`],
                    - [`~generation.BeamSearchDecoderOnlyOutput`],
                    - [`~generation.BeamSampleDecoderOnlyOutput`]

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

                    - [`~generation.GreedySearchEncoderDecoderOutput`],
                    - [`~generation.SampleEncoderDecoderOutput`],
                    - [`~generation.BeamSearchEncoderDecoderOutput`],
                    - [`~generation.BeamSampleEncoderDecoderOutput`]
        Nr%   The attention mask and the pad token id were not set. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.r   )Setting `pad_token_id` to `eos_token_id`: for open-end generation.r   r   r   r&   r$   r6   r
     0Using the model-agnostic default `max_length` (=zx) to control the generation length.  recommend setting `max_new_tokens` to control the maximum length of the generation.Both `max_new_tokens` (=) and `max_length`(=) seem to have been set. `max_new_tokens` will take precedence. Please refer to the documentation for more information. (https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)3Unfeasible length constraints: the minimum length (%) is larger than the maximum length ()%Input length of decoder_input_ids is , but `max_length` is set to X. This can lead to unexpected behavior. You should consider increasing `max_new_tokens`.r	  r  r   FTr  input_ids_seq_lengthZencoder_input_idsZprefix_allowed_tokens_fnr  r  r  Bnum_return_sequences has to be 1 when doing greedy search, but is r   r  r  rN   eos_token_idoutput_scoresreturn_dict_in_generater  r  )rM   expand_size	r  logits_warperr  rN   r/  r0  r1  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`.)1r  copydeepcopyupdatevalidate_validate_model_kwargsr   r   rN   r/  getr   warningr   list_prepare_model_inputsbos_token_idrQ   r   r   r   r   r&   &_prepare_attention_mask_for_generationr
  max_new_tokens
min_lengthrS   r  rO   putcpu	num_beamsnum_beam_groups	do_sampleappendr   _get_logits_processor_get_stopping_criterianum_return_sequencesgreedy_searchr0  r1  _get_logits_warper_expand_inputs_for_generationsample	sequencesr  r   )r\   r   r  r  r  r  r  r  model_kwargsr/  rM   model_input_name
batch_sizerequires_attention_maskr+  has_default_max_lengthr  is_greedy_gen_modeis_sample_gen_moder   r4  
output_idsr0   r0   r1   generate  s"   N

  




  


	 


  zMusicgenForCausalLM.generate)NNNNNNNNNNNNN)	NNNNNNTNN)N)NNNNNN)%r'   r(   r)   r!   rZ   r   r   r   r   r   r   r   r   r   r   _CONFIG_FOR_DOCr+   r.   r   rs   r,   r   rJ   r   r   ro   r  rp   r  rq   r  rr   r   r   r   rY  rt   r0   r0   r]   r1   r     s   
             
D         
-=
      r   zThe composite MusicGen model with a text encoder, audio encoder and Musicgen decoder,for music generation tasks with one or both of text and audio prompts.c                       sr  e Zd ZeZdZdZdZd>ee ee	 ee	 ee
 d fddZdd	 Zd?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 fddZed@eeee	dddZeeeeed dAeej eej  eej! eej  eej eej  ee"ej!  e"e"ej!  eej! eej! eej ee# ee# ee# ee# e$e"ef d!d"d#Z%dBd$d%Z&dCe'ee(eej)f e'e'ej*e"eje(eej)f f d&d'd(Z+dDej)ee ee, e(ee-f d)d*d+Z.dEee d,d-d.Z/ej)d/d0d1Z0d2d3 Z1dFeej) ee' ee(eej)f  ejd4d5d6Z2e3 dGeej) ee4 ee5 ee6 ee# ed7 d8d9d:Z7dHd<d=Z8  Z9S )I MusicgenForConditionalGenerationZencoder_decoderrM   TN)r   text_encoderaudio_encoderr   c                    sx  |d kr(|d ks |d ks |d kr(t d|d krFt|j|j|j}n"t|| jsht d| d| j |jjd k	r|jj|jj	krt d|jj d|jj	 dt
 | |d krddlm} ||j}|d krdd	lm} ||j}|d krt|j}|| _|| _|| _| jj | jj krLt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	kr | jjjd kr t| jjj	| jjj	| _| j d k	rBt d| j dtt| jjj }d|krlt d|    d S )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)!rS   r    from_sub_models_configr   r   r   r   cross_attention_hidden_sizer\  r   rY   rZ   auto.modeling_autor^  from_configr   r]  r   to_dictr   r<  r^   rc   r   enc_to_dec_projr   setinspect	signaturero   
parameterskeystie_weights)r\   r   r\  r]  r   r^  r   Zdecoder_signaturer]   r0   r1   rZ     sn     


z)MusicgenForConditionalGeneration.__init__c                 C   s0   | j jr,| jj}| | j| jj| | jj d S rX   )r   Ztie_encoder_decoderr   r   Z_tie_encoder_decoder_weightsr\  Z_modules)r\   Zdecoder_base_model_prefixr0   r0   r1   rj    s     
 z,MusicgenForConditionalGeneration.tie_weightsFc                 C   s$   | j j||d | jj||d d S )N)r   )r\  r   r   r   r0   r0   r1   r     s    z<MusicgenForConditionalGeneration._set_gradient_checkpointingc                 C   s   | j S rX   )r]  r   r0   r0   r1   get_audio_encoder"  s    z2MusicgenForConditionalGeneration.get_audio_encoderc                 C   s   | j S rX   )r\  r   r0   r0   r1   get_text_encoder%  s    z1MusicgenForConditionalGeneration.get_text_encoderc                 C   s   |   S rX   )rl  r   r0   r0   r1   get_encoder(  s    z,MusicgenForConditionalGeneration.get_encoderc                 C   s   | j S rX   r   r   r0   r0   r1   r   ,  s    z,MusicgenForConditionalGeneration.get_decoderc                 C   s
   | j  S rX   )r\  r   r   r0   r0   r1   r   /  s    z5MusicgenForConditionalGeneration.get_input_embeddingsc                 C   s
   | j  S rX   )r   r   r   r0   r0   r1   r   2  s    z6MusicgenForConditionalGeneration.get_output_embeddingsc                 C   s   | j |S rX   )r   r   r   r0   r0   r1   r   5  s    z6MusicgenForConditionalGeneration.set_output_embeddingsc                    s2   | ddrtd d|d< t j|f||S )z
        Example:

        ```python
        >>> from transformers import MusicgenForConditionalGeneration

        >>> model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")
        ```Z
_fast_initFz{Fast initialization is currently not supported for MusicgenForConditionalGeneration. Falling back to slow initialization...)r;  r   r<  rY   from_pretrained)clsZpretrained_model_name_or_path
model_argsr  r]   r0   r1   rn  8  s    z0MusicgenForConditionalGeneration.from_pretrained)*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|	 = qV| D ]}	|d|	 = qn|dd	}
|
d	kr|d	krtd
d|krtj|f|ddi\}}|jdks|jdkrt	d| d d|_d|_||d< t
j|f||}
|dd	}|d	kr|d	kr<tdd|krtj|f|ddi\}}|jdksx|jdkrt	d| d d|_d|_||d< t
j|f||}|dd	}|d	kr|d	krtdd|krXtj|f|ddi\}}t|tr|j}|jdks&|jdkrPt	d| d| d| d d|_d|_||d< |d jdksx|d jdkrtd| d| d tj|f|}tj|
j|j|jf|}| |
|||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.
                      Valid model ids can be located at the root-level, like `t5-base`, or namespaced under a user or
                      organization name, like `google/flan-t5-base.
                    - 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.
                      Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
                      user or organization name, like `facebook/encodec_24khz`.
                    - 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.
                      Valid model ids can be located at the root-level, like `gpt2`, or namespaced under a user or
                      organization name, like `facebook/musicgen-small`.
                    - 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="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   s,   i | ]$\}}| d r|td d |qS )text_encoder_N
startswithr   r   argumentr   r0   r0   r1   
<dictcomp>  s   
 zOMusicgenForConditionalGeneration.from_sub_models_pretrained.<locals>.<dictcomp>c                 S   s,   i | ]$\}}| d r|td d |qS )audio_encoder_Nru  rw  r0   r0   r1   ry    s   
 c                 S   s,   i | ]$\}}| d r|td d |qS decoder_Nru  rw  r0   r0   r1   ry    s    
  rt  rz  r|  r   NzxIf `text_encoder_model` is not defined as an argument, a `text_encoder_pretrained_model_name_or_path` has to be defined.r   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(...)`)r\  r]  r   r   )itemsri  poprS   r   rn  r{   Zadd_cross_attentionr   infor   r   r    r   r<  r   r_  r   )ro  rq  rr  rs  rp  r  kwargs_text_encoderkwargs_audio_encoderkwargs_decoderkeyr\  Zencoder_configr]  r   Zdecoder_configr   r0   r0   r1   from_sub_models_pretrainedM  s    N









   z;MusicgenForConditionalGeneration.from_sub_models_pretrainedr   )rM   r%   input_valuespadding_maskdecoder_input_idsdecoder_attention_maskr$   r   r   decoder_inputs_embedsr  r   r   r   r   r   c                 K   s$  |dk	r|n| j j}dd | D }dd | D }dd | D }|dkrr| jf |||	|||d|}nt|trt| }|d }| jj j| jj jkr| jj j	dkr| 
|}|dk	r||d  }|dk	r|dkr|
dkrt|| j j| j j}np|dkrj|
dkrj| jf ||d	|}|j}|j\}}}}|d
krRtd| d|d || jj |}| jf |||||
|||||d
|}d}|dk	r|r|jn|d }t }||d| j j|d}|s|dk	r|f| | S || S t||j|j|j|j|j|j|j|jd	S )a  
        Returns:

        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   s(   i | ] \}}| d r|td  |qS )rt  ru  rw  r0   r0   r1   ry  J  s   

 z<MusicgenForConditionalGeneration.forward.<locals>.<dictcomp>c                 S   s(   i | ] \}}| d r|td  |qS )rz  ru  rw  r0   r0   r1   ry  P  s   

 c                 S   s,   i | ]$\}}| d r|td d |qS r{  ru  rw  r0   r0   r1   ry  V  s    
  )rM   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   .)
rM   r%   r   r   r   r   r   r   r   r   r6   )	r  r  r   Zdecoder_hidden_statesZdecoder_attentionsr   Zencoder_last_hidden_stater   Zencoder_attentions)r   r   r}  r\  r   r   r   r   r   r`  rd  rT   rN   rO   r]  audio_codesrQ   rS   r   r   r  r	   r@   r   r   r   r   r   r   r   )r\   rM   r%   r  r  r  r  r$   r   r   r  r  r   r   r   r   r  r  r  r  r   audio_encoder_outputsr  framesrE   rm   rn   r   r  r  Zloss_fctr0   r0   r1   ro     s    0	

  



z(MusicgenForConditionalGeneration.forwardc                 K   s   |
d kr&| j j|| jj| jjd\}}
| j ||
}|d k	r`|dkr`|d}|d k	r`|d}|d k	r||d d dd f }d |	||||||||d
S )N)r
  r   r  r6   )
rM   r$   r   r  r%   r  r   decoder_head_maskr   r   )r   r  r  rN   r
  r  r  )r\   r  r   r%   r   r  r  r   r   r$   decoder_delay_pattern_maskr&   r  r0   r0   r1   r    s0    


z>MusicgenForConditionalGeneration.prepare_inputs_for_generation)rS  rR  rQ  rO   r?  r4   r   c           
      C   s   |dk	rd|kr| d}n d|kr8|dkr8| d}nd}| ||}|dkrV| j}tj|| jj dftj|d| }|dkr|}nf|d |k 	 rtj
||gdd}d	|kr|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  rM   r   r7   ).r   r6   r8   r  )r~  Z_get_decoder_start_token_idr4   r+   r  r   r   r  allitemrB   Z	ones_like)
r\   rS  rR  rQ  rO   r?  r4   r  Zdecoder_input_ids_startr  r0   r0   r1   )_prepare_decoder_input_ids_for_generation  s0    zJMusicgenForConditionalGeneration._prepare_decoder_input_ids_for_generation)inputs_tensorrR  r&   r   c           	         s  |   }t|drd|j_dddgfdd| D }tt|jj	 d kpZd	 k}|sv fd
d| D }|d k	r|n| j
j}d|d< |||< |f |j}|d k	r|dkrtj|t|gdd}d|krtj|d t|d gdd|d< t|d|d< |S )N_hf_hookTr|  
cross_attnr   c                    s,   i | ]$\ }t  fd dD s |qS )c                 3   s   | ]}  |V  qd S rX   rv  r   r   rx  r0   r1   r   !  s     zjMusicgenForConditionalGeneration._prepare_text_encoder_kwargs_for_generation.<locals>.<dictcomp>.<genexpr>anyr   r   irrelevant_prefixr  r1   ry    s    z`MusicgenForConditionalGeneration._prepare_text_encoder_kwargs_for_generation.<locals>.<dictcomp>r  rQ  c                    s   i | ]\}}| kr||qS r0   r0   rw  encoder_signaturer0   r1   ry  &  s      r   r   r   r8   r%   r   r$   )rl  rb   r  io_same_devicer}  re  rf  rg  ro   rh  r\  main_input_namer   r+   ZconcatenateZ
zeros_liker   )	r\   r  rQ  rR  r&   encoderencoder_kwargsencoder_accepts_wildcardr   r0   r  r  r1   +_prepare_text_encoder_kwargs_for_generation  s4    



 
zLMusicgenForConditionalGeneration._prepare_text_encoder_kwargs_for_generation)rR  c                    s   |   }t|drd|j_dddgfdd| D }tt|jj	 d kpZd	 k}|sv fd
d| D }|d k	r|n| j
j}d|d< |||< |jf |}|j}|j\}	}
}}|	dkrtd|	 d|d |
| jj |}||d< |j|d< |S )Nr  Tr|  r  r   c                    s,   i | ]$\ }t  fd dD s |qS )c                 3   s   | ]}  |V  qd S rX   r  r  r  r0   r1   r   K  s     zkMusicgenForConditionalGeneration._prepare_audio_encoder_kwargs_for_generation.<locals>.<dictcomp>.<genexpr>r  r  r  r  r1   ry  H  s    zaMusicgenForConditionalGeneration._prepare_audio_encoder_kwargs_for_generation.<locals>.<dictcomp>r  rQ  c                    s   i | ]\}}| kr||qS r0   r0   rw  r  r0   r1   ry  P  s      r   r   r  r  r  r  audio_scales)rk  rb   r  r  r}  re  rf  rg  ro   rh  r]  r  encoder  rQ   rS   r   r   r   r  )r\   r  rQ  rR  r  r  r  r  r  r  rE   rm   rn   r  r0   r  r1   ,_prepare_audio_encoder_kwargs_for_generation<  s6    





zMMusicgenForConditionalGeneration._prepare_audio_encoder_kwargs_for_generation)r  c                 C   s   t || jj| jjS rX   )rT   r   rN   rO   )r\   r  r0   r0   r1   %prepare_decoder_input_ids_from_labelsj  s    zFMusicgenForConditionalGeneration.prepare_decoder_input_ids_from_labelsc                 O   s   t dd S )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(...)))r  )r\   argsr  r0   r0   r1   resize_token_embeddingsm  s    z8MusicgenForConditionalGeneration.resize_token_embeddings)r   r?  rQ  r   c                 C   s   |dk	r|S | d}|dk	rJ|d  dd }tj|tj| jdd S |dkrZtdd}| D ]}t|tj	rf|j
d } qqftj|dftj| jd| S )	z3Initializes input ids for generation, if necessary.Nr$   r   r6   r7   rP   zB`bos_token_id` has to be defined when no `input_ids` are provided.r   )r;  r>   r+   r  r  r4   rS   valuesr   rs   rQ   )r\   r   r?  rQ  r$   rQ   rS  r   r0   r0   r1   *_maybe_initialize_input_ids_for_generationt  s    

zKMusicgenForConditionalGeneration._maybe_initialize_input_ids_for_generationr"   r  c                 K   s  |dkr| j }t|}|jf |}|  | |  |ddk	rnt|d tkrnt	|d d d|d< |dk	rz|nt
 }|dk	r|nt }|jdkr|jdk	r|dddkrtd |j}	t|	tr|	d }	td|	 d |	|_| ||j|\}
}}|
jd }|j|d	< |j|d
< |j|d< |j|d< d|k}|dddkrn|rn| |
|j|j|d< d|kr| j|
|||jd}d|krd|kr| |d |}| j||||j|j|
jd\}}|jd }|ddko|jdk	}|r|j dkrtd|j d n:|j dk	rV|sJtd|j  d|j d |j | |_|j!dk	r|j!|jkrt"d|j! d|j d||jkrtd| d|j d | j#j$||j|jd\}}||d< |dk	r|%|&  |j'd ko
|j(d ko
|j)d!k}|j'd ko,|j(d ko,|j)d"k}|jdk	r\|jd kr\|*t+|j d|_| j,|||
d|d#}| j-||d$}|r|j.d krt"d%|j. d&| j/|f|||j|j|j0|j1||d'|}nj|r2| 2|}| j3f ||j.| j4j5d(|\}}| j6|f||||j|j|j0|j1||d)	|}nt"d*|j1rJ|j7}n|}| j#8||d }|||jk 9|| j#j:d}|d+ }|d,}|dkrdg| }| j;j<||d-}|j1r|j=|_7|S |j=S dS ).r  Nr$   r   r  r%   r  r  r  r   r   r   r&   )r&   r  r  )rS  rR  rQ  rO   r?  r4   r6   r
  r   zz) to control the generation length. We recommend setting `max_new_tokens` to control the maximum length of the generation.r!  r"  r#  r$  r%  r&  r'  r(  r)  r	  r  r   FTr*  r,  r-  r   r.  )rM   r2  is_encoder_decoderr3  r5  )N.r  )r  )>r  r6  r7  r8  r9  r:  r;  typer   r   r   r   rN   r/  r   r<  r   r=  r>  r?  rQ   r   r   r   r&   r@  r  r  r  rO   r4   r
  rA  rB  rS   r   r  rC  rD  rE  rF  rG  rH  r   rI  rJ  rK  rL  r0  r1  rM  rN  r   r  rO  rP  r  r   r   r]  decodeZaudio_values)r\   r   r  r  r  r  r  r  rQ  r/  r  rR  rS  rT  rM   r+  rU  r  rV  rW  r   r4  rX  r  Zoutput_valuesr0   r0   r1   rY    s`   N

  





  





	 


  


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   )r4   r3   rI   )r$   r%   r&   )	r+   rC   r   r\  r   r4   r3   r  r#   )r\   Znum_samplesr   r%   r0   r0   r1   get_unconditional_inputs	  s      z9MusicgenForConditionalGeneration.get_unconditional_inputs)NNNN)F)NNN)NNNNNNNNNNNNNNN)
NNNNNNNNNN)NNN)NN)N)NNN)NNNNNN)r   ):r'   r(   r)   r    r   r   r  r   r   r   r   rZ   rj  r   rk  rl  rm  r   r   r   r   classmethodrn  strr  r   MUSICGEN_INPUTS_DOCSTRINGr   r   rZ  r+   r.   Z
BoolTensorr,   r   rJ   r   ro   r  rp   r   rs   r4   r  r/   r   r  r  r  r  r  rr   r   r   r   rY  r  rt   r0   r0   r]   r1   r[    s      Z	
    K
               
           
6   3  
/ .	           :r[  )r   )N)Nr*   r6  rf  rf   r   dataclassesr   typingr   r   r   r   r   r   r+   Ztorch.nnrc   r	   Ztorch.utils.checkpointr
   Zactivationsr   Zgeneration.configuration_utilsr   Zgeneration.logits_processr   r   Zgeneration.stopping_criteriar   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   utilsr   r   r   r   Zauto.configuration_autor   ra  r   Zconfiguration_musicgenr    r!   Zgeneration.streamersr"   Z
get_loggerr'   r   rZ  Z_CHECKPOINT_FOR_DOCZ&MUSICGEN_PRETRAINED_MODEL_ARCHIVE_LISTr#   Sizer3   r4   rp   rH   rs   rL   rT   ModulerU   ru   r   r   ZMUSICGEN_START_DOCSTRINGr  r   r   r   r   r[  r0   r0   r0   r1   <module>   s    
    . xaM ZC   i