
    rh                       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 ddlZddlmZ ddlmZ ddlmZ ddlmZmZ dd	lmZmZmZmZmZ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'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z;  e3       rddl<m=Z= erddl>m?Z?  e4j                  eA      ZBee2 G d de*                    ZCdej                  deEdeEfdZF G d dej                        ZH	 	 	 d;d ej                  d!ej                  d"ej                  d#ej                  d$eej                     d%eeI   d&eId'eej                     fd(ZJ G d) d*ej                        ZK G d+ d,e%      ZLe2 G d- d.e.             ZM G d/ d0eM      ZNe2 G d1 d2eM             ZO e2d34       G d5 d6eMe             ZP e2d74       G d8 d9eMe             ZQg d:ZRy)<zPyTorch Musicgen model.    N)	dataclass)TYPE_CHECKINGAnyCallableOptionalUnion)CrossEntropyLoss   )ACT2FN)CacheEncoderDecoderCache)%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)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsModelOutputSeq2SeqLMOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)auto_docstringis_torch_flex_attn_availablelogging   )
AutoConfig	AutoModel   )MusicgenConfigMusicgenDecoderConfig)make_flex_block_causal_mask)BaseStreamerc                   v    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<   y)MusicgenUnconditionalInputa  
    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__r0   tupletorchFloatTensor__annotations__r1   r   
LongTensorr2   float     /var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/models/musicgen/modeling_musicgen.pyr/   r/   I   sA    	 15OU5,,-415NHU--.5&*NHUO*r>   r/   	input_idspad_token_iddecoder_start_token_idc                    | j                  dd      } | j                  | j                        }| dddf   j                         |dddf<   |t	        d      ||d<   |t	        d      |j                  |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.)	transpose	new_zerosshapeclone
ValueErrormasked_fill_)r@   rA   rB   shifted_input_idss       r?   shift_tokens_rightrN   \   s    
 ##Aq)I!++IOO<!*38!4!:!:!<c12g%noo 6fdee""#4#<lKr>   c                        e Zd ZdZdedef fdZdedefdZededefd       Z e	j                         dde	j                  d	efd
       Z xZS )%MusicgenSinusoidalPositionalEmbeddingzDThis module produces sinusoidal positional embeddings of any length.num_positionsembedding_dimc                 T    t         |           || _        | j                  ||       y N)super__init__rR   make_weights)selfrQ   rR   	__class__s      r?   rV   z.MusicgenSinusoidalPositionalEmbedding.__init__s   s&    *-7r>   num_embeddingsc                     | j                  ||      }t        | d      r;|j                  | j                  j                  | j                  j
                        }| j                  d|d       y )NweightsdtypedeviceF)
persistent)get_embeddinghasattrtor\   r^   r_   register_buffer)rX   rZ   rR   emb_weightss       r?   rW   z2MusicgenSinusoidalPositionalEmbedding.make_weightsx   sY    ((G4#%..t||/A/A$,,J]J].^KYFr>   c                    |dz  }t        j                  d      |dz
  z  }t        j                  t        j                  |t        j
                        j                         | z        }t        j                  | t        j
                        j                         j                  d      |j                  d      z  }t        j                  t        j                  |      t        j                  |      gd      j                  | d      }|dz  dk(  r-t        j                  |t        j                  | d      gd      }|j                  t        j                               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)   r^   r   dimrD   )mathlogr8   exparangeint64r<   	unsqueezecatcossinviewzerosrc   get_default_dtype)rZ   rR   half_dimembs       r?   ra   z3MusicgenSinusoidalPositionalEmbedding.get_embedding   s    !A%hhuoA.iiXU[[AGGISDPQll>=CCEOOPQRUXUbUbcdUeeii338a@EEnVXY1!))S%++na"@AqICvve--/00r>   r@   past_key_values_lengthc                 r   |j                         \  }}}t        j                  |      |z   j                  |j                        }|| j
                  j                  d      kD  r| j                  || j                         | j
                  j                  d|j                  d            j                         S )Nr   rD   )sizer8   rm   rc   r_   r\   rW   rR   index_selectrs   detach)rX   r@   rx   bsz	codebooksseq_lenposition_idss          r?   forwardz-MusicgenSinusoidalPositionalEmbedding.forward   s    "+.."2YW-0FFJJ9K[K[\T\\&&q))gt'9'9:||((L,=,=b,ABIIKKr>   )r   )r3   r4   r5   r6   intrV   rW   staticmethodra   r8   no_gradTensorr   __classcell__rY   s   @r?   rP   rP   p   s    N8c 8# 8
G3 Gs G 1c 1# 1 1 U]]_L Ls L Lr>   rP   modulequerykeyvaluer1   scalingdropout	head_maskc                    ||j                  d      dz  }t        j                  ||j                  dd            |z  }	||	|z   }	t        j
                  j                  |	d      }	||	|j                  dddd      z  }	t        j
                  j                  |	|| j                        }	t        j                  |	|      }
|
j                  dd      j                         }
|
|	fS )NrD         r%   r
   rh   r)   ptraining)rz   r8   matmulrG   nn
functionalsoftmaxrs   r   r   
contiguous)r   r   r   r   r1   r   r   r   kwargsattn_weightsattn_outputs              r?   eager_attention_forwardr      s     **R.D(<<s}}Q':;gEL!#n4==((2(>L#innQAq&AA==((6??([L,,|U3K''1-88:K$$r>   c                       e Zd ZdZ	 	 	 	 	 	 ddededee   dee   dee   dee   dee   d	ee   f fd
Z		 	 	 	 	 	 dde
j                  dee
j                     dee   dee
j                     dee
j                     dee   dee
j                     dee   dee
j                  ee
j                     eee
j                        f   fdZ xZS )MusicgenAttentionz=Multi-headed attention from 'Attention Is All You Need' paper	embed_dim	num_headsr   
is_decoderbias	is_causalconfig	layer_idxc	                    t         	|           || _        || _        || _        ||z  | _        || _        | j
                  |z  | j                  k7  rt        d| j                   d| d      | j
                  dz  | _        || _	        || _
        || _        t        j                  |||      | _        t        j                  |||      | _        t        j                  |||      | _        t        j                  |||      | _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).r   r   )rU   rV   r   r   r   head_dimr   rK   r   r   r   r   r   Lineark_projv_projq_projout_proj)
rX   r   r   r   r   r   r   r   r   rY   s
            r?   rV   zMusicgenAttention.__init__   s     	""!Y.MMI%$..8MdnnM]$YKr3  }}d*$""ii	94@ii	94@ii	94@		)YTBr>   hidden_stateskey_value_statespast_key_valuer1   layer_head_maskoutput_attentionscache_positionr   returnc                    |du}	|j                   dd \  }
}|	r|j                   d   n|}|
|d| j                  f}|
|d| j                  f} | j                  |      j                  | j	                  dd      }|St        |t              rA|j                  j                  | j                        }|	r|j                  }n|j                  }n|}|	r|n|}|	rK|IrGj                  | j                     j                  }|j                  | j                     j                  }n | j                  |      j                  | j	                  dd      } | j!                  |      j                  | j	                  dd      }|D|	s|nd}j#                  ||| j                  d|i      \  }}|	rd|j                  | j                  <   t$        }| j&                  j(                  dk7  rt*        | j&                  j(                     } || ||||f| j,                  sdn| j.                  | j0                  ||d	|\  }}|j3                  |
|d      j5                         }| j7                  |      }||fS )
z#Input shape: Batch x Time x ChannelNrD   r)   r%   r   Teager        )r   r   r   r   )rI   r   r   rs   rG   
isinstancer   
is_updatedgetr   cross_attention_cacheself_attention_cachelayerskeysvaluesr   r   updater   r   _attn_implementationr   r   r   r   reshaper   r   )rX   r   r   r   r1   r   r   r   r   is_cross_attentionr}   tgt_lensrc_lenq_input_shapekv_input_shapequery_statesr   curr_past_key_valuecurrent_states
key_statesvalue_statesattention_interfacer   r   s                           r?   r   zMusicgenAttention.forward   su   " .T9 %**3B/W/A"((+wgr4==9wDMM: 7t{{=166FPPQRTUV%.*=>+66::4>>J
%*8*N*N'*8*M*M'&4#-?)]."<,33DNNCHHJ.55dnnELLL9^499>JTTUVXYZJ;4;;~6;;^LVVWXZ[\L)7It+>+E+Ednn?OQ_>`,(
L &@DN--dnn=(?;;++w6"9$++:Z:Z"[$7%
  $}}C$,,LL/%%
 %
!\ "))#w;FFHmmK0L((r>   )r   FTFNN)NNNNFN)r3   r4   r5   r6   r   r   r<   boolr*   rV   r8   r   r   r!   r   r7   r   r   r   s   @r?   r   r      sh   G $'%*#$)+/#'CC C %	C
 TNC tnC D>C (C C=CH 48*.1526,115O)||O) #5<<0O) !	O)
 !.O) "%,,/O) $D>O) !.O) -.O) 
u||Xell3XeELL>Q5RR	SO)r>   r   c                   D    e Zd Zddef f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   d
ee	   dee	   deej                     dej                  fdZ
 xZS )MusicgenDecoderLayerr   c           
      *   t         |           |j                  | _        t	        | j                  |j
                  |j                  ddd||      | _        |j                  | _        t        |j                     | _        |j                  | _        t        j                  | j                        | _        t	        | j                  |j
                  |j                  dd||      | _        t        j                  | j                        | _        t        j$                  | j                  |j&                  d      | _        t        j$                  |j&                  | j                  d      | _        t        j                  | j                        | _        y )NTF)r   r   r   r   r   r   r   r   )r   r   r   r   r   r   )rU   rV   hidden_sizer   r   num_attention_headsattention_dropout	self_attnr   r   activation_functionactivation_fnactivation_dropoutr   	LayerNormself_attn_layer_normencoder_attnencoder_attn_layer_normr   ffn_dimfc1fc2final_layer_norm)rX   r   r   rY   s      r?   rV   zMusicgenDecoderLayer.__init__1  s(   ++*nn00,,	
 ~~#F$>$>?"(";";$&LL$@!-NN&&,,
 (*||DNN'C$99T^^V^^%H99V^^T^^%H "T^^ <r>   r   r1   encoder_hidden_statesencoder_attention_maskr   cross_attn_layer_head_maskr   r   	use_cacher   r   c           	      2   |}| j                  |      }| j                  ||||||
      \  }}t        j                  j	                  || j                  | j
                        }||z   }d}|i|}| j                  |      }| j                  |||||||
      \  }}t        j                  j	                  || j                  | j
                        }||z   }|}| j                  |      }| j                  | j                  |            }t        j                  j	                  || j                  | j
                        }| j                  |      }t        j                  j	                  || j                  | j
                        }||z   }|f}|r|||fz  }|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.
        )r   r   r1   r   r   r   r   N)r   r   r1   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   )rX   r   r1   r   r   r   r   r   r   r   r   residualself_attn_weightscross_attn_weightsoutputss                  r?   r   zMusicgenDecoderLayer.forwardT  s   > !11-@ ,0>>'))+/) ,: ,
(( --mt||VZVcVc-d =0 " ,$H 88GM040A0A+!65 :-"3- 1B 1-M- MM11-4<<Z^ZgZg1hM$}4M !--m<**488M+BC--mt?V?Vaeanan-o/--mt||VZVcVc-d =0 ")+=>>Gr>   rT   )	NNNNNNFTN)r3   r4   r5   r+   rV   r8   r   r   r   r   r   r   r   s   @r?   r   r   0  s    =4 =L 268<9=26=A*.,1$(15M||M !.M  (5	M
 !) 6M "%,,/M %-U\\$:M !M $D>M D>M !.M 
Mr>   r   c                   :    e Zd ZU eed<   dZdZddgZdZdZ	dZ
d Zy)MusicgenPreTrainedModelr   modelTr   r   c                    | j                   j                  }t        |t        j                        rY|j
                  j                  j                  d|       |j                  %|j                  j                  j                          y y t        |t        j                        rJ|j
                  j                  j                  d       |j                  j                  j                          y t        |t        j                        rf|j
                  j                  j                  d|       |j                  2|j
                  j                  |j                     j                          y y y )Nr   )meanstd      ?)r   initializer_factorr   r   r   weightdatanormal_r   zero_r   fill_	Embeddingpadding_idx)rX   r   r   s      r?   _init_weightsz%MusicgenPreTrainedModel._init_weights  s    kk,,fbii(MM&&CS&9{{&  &&( '-MM$$S)KK""$-MM&&CS&9!!-""6#5#56<<> . .r>   N)r3   r4   r5   r+   r:   base_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_flash_attn_supports_sdpa_supports_flex_attnr   r=   r>   r?   r   r     s6    !!&*#/1DEN?r>   r   c                        e Zd ZdZdef f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j                     deeef   fd       Zdeej                  df   dej"                  dej                  defdZdeej                  df   deej                  df   dej"                  dej                  fdZ xZS )MusicgenDecoderzw
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MusicgenDecoderLayer`]
    r   c           	         t         |   |       |j                  | _        |j                  | _        |j                  | _        |j                  | _        |j                  | _        |j                  rt        j                  |j                        nd| _        |j                  dz   }t        j                  t!        |j                        D cg c]"  }t        j"                  ||j                        $ c}      | _        t'        |j                  |j                        | _        t        j                  t!        |j*                        D cg c]  }t-        ||       c}      | _        t        j0                  |j                        | _        |j4                  | _        d| _        | j;                          y c c}w c c}w )Nr   r)   )r   F)rU   rV   r   	layerdropmax_position_embeddingsmax_target_positionsr   d_modelnum_codebooksscale_embeddingrj   sqrtembed_scale
vocab_sizer   
ModuleListranger   embed_tokensrP   embed_positionsnum_hidden_layersr   r   r   
layer_normr   attn_implementationgradient_checkpointing	post_init)rX   r   r   _irY   s        r?   rV   zMusicgenDecoder.__init__  sW    ~~))$*$B$B!))#11<B<R<R499V%7%78X[%%)	MMBGH\H\B]^QR\\)V%7%78^
  E** 

 mm@EfF^F^@_`1!&A6`
 ,,v'9'9:#)#>#> &+#! _ as   'F8F=Nr@   r1   r   r   r   cross_attn_head_maskpast_key_valuesinputs_embedsr   r   output_hidden_statesreturn_dictr   r   c                 n   |
|
n| j                   j                  }
||n| j                   j                  }|	|	n| j                   j                  }	||n| j                   j                  }||t        d      |?|j                  d| j                  |j                  d         }|j                  \  }}}||f}n/|"|j                         dd }|ddddddf   }nt        d      | j                  r%| j                  r|	rt        j                  d       d}	d}|	r<t        |t              s,t        j                  d       d}t!        j"                  |      }||j%                         nd	}|<t'        t)              D cg c]  } | j*                  |   |dd|f           c}      }| j-                  ||||      }| j/                  ||||      }| j1                  ||      }||j3                  |j4                        z   }t6        j8                  j;                  || j:                  | j                  
      }|rdnd}|
rdnd}|
r|dnd}t=        ||gddg      D ]j  \  }}|	|j                         d	   t?        | j@                        k7  s3t        d| dt?        | j@                         d|j                         d	    d       tC        | j@                        D ]|  \  }}|r||fz  }tE        jF                  d	d      }| j                  r|| jH                  k  r@ ||||||||   nd|||   nd||
|	|
      } | d	   }|
sh|| d   fz  }|t|| d   fz  }~ | jK                  |      }|r||fz  }|r|jM                         }|stO        d |||||fD              S tQ        |||||      S c c}w )  
        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 timerD   zEYou have to specify either decoder_input_ids or decoder_inputs_embedsz[`use_cache=True` is incompatible with gradient checkpointing`. Setting `use_cache=False`...FzPassing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. You should pass an instance of `EncoderDecoderCache` instead, e.g. `past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`.Tr   r   r=   r   r  zThe `z` should be specified for z layers, but it is for .r)   )r   r   r   r   r   r   r   r%   c              3   $   K   | ]  }|| 
 y wrT   r=   ).0vs     r?   	<genexpr>z*MusicgenDecoder.forward.<locals>.<genexpr>  s      = s   last_hidden_stater  r   
attentionscross_attentions))r   r   r  r   use_return_dictrK   r   r  rI   rz   r  r   loggerwarning_oncer   r   r   from_legacy_cacheget_seq_lengthsumr  r  _update_causal_mask_update_cross_attn_maskr  rc   r_   r   r   r   ziplenr   	enumeraterandomuniformr  r  to_legacy_cacher7   r   )!rX   r@   r1   r   r   r   r  r  r  r   r   r  r  r   inputr}   r  r   input_shapereturn_legacy_cacherx   codebook	positionsr   all_hidden_statesall_self_attnsall_cross_attentions	attn_mask	mask_nameidxdecoder_layerdropout_probabilitylayer_outputss!                                    r?   r   zMusicgenDecoder.forward  sW   l 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]  ]%>stt"%%b$*<*<ioob>QRE*/++'C.K&',,.s3K!!Q),Edee&&4==##q "	#Z?\
 #'1CCOTOETE`!?!?!Afg afgtau vU]!<!2!28!<U1h;=O!P vwM11"	
 "&!=!=!"	"
 ((0FG	%	]5I5I(JJ--mt||VZVcVc-d #7BD0d&7<Q<]rdh %(4H(IKYoKp$q 	 Iy$>>#A&#dkk*::$	{*DSEUDV W%NN,Q/03 	 #,DKK"8 	@C#!m%55!"(..A"6}}"5"F)%'=3<3H3dI]Ii,@,Eos."3#-M *!,M =#3"55(4(]1-=,??(3	@6 6  -!11-==?O ':K^]qr  
 9+++%1
 	
W !ws   #N2r6  rx   c                    | j                   j                  dk(  r|d|v r|}|S d }|S | j                   j                  dk(  rt        ||||      }|S | j                   j                  dk(  rUt        |t        j
                        rt        |      }|S |*t        t	        j                  ||j                              }|S t        ||||      }|S )Nflash_attention_2r   sdpaflex_attention)rz   r_   )
r   r   r   r   r8   r   r,   onesr_   r   )rX   r1   r6  r  rx   s        r?   r-  z#MusicgenDecoder._update_causal_mask  s     ;;++/BB0>0JqTbOb^N8 9 jnN8 7 [[--7 H&	N0 % [[--1AA.%,,7!<^!L    '!<JJ),33" 	 ?]<RN r>   c                    ||| j                   j                  dk(  rd|v r|}|S d }|S | j                   j                  dk(  rt        ||j                  |d         }|S | j                   j                  dk(  r-t	        |t
        j                        rt        ||d   d      }|S t        ||j                  |d         }|S )	NrD  r   rE  rD   )r   rF  F)query_lengthr   )	r   r   r   r^   r   r8   r   r,   r   )rX   r   r   r6  r  s        r?   r.  z'MusicgenDecoder._update_cross_attn_mask  s     !,1G1S{{//3FFCDH^C^)?&. &%/ ei&. &%- 11V; *M*!'''O*&$ &% 115EE4ellC-H.%0_"'.* &%	 *D*M,?,?UW*& &%r>   NNNNNNNNNNNNN)r3   r4   r5   r6   r+   rV   r"   r   r8   r;   r   r9   r7   r   r   r   r   Sizer   r-  r.  r   r   s   @r?   r  r    s   4 :  1515=A=A,07;EI59$(,0/3&*15o
E,,-o
 !.o
  ((9(9:	o

 !))9)9 :o
 ELL)o
 'u||4o
 "%e.?.?(@"ABo
   1 12o
 D>o
 $D>o
 'tno
 d^o
 !.o
 
u??	@o
 o
b%ellD01% ZZ% ||	%
 !$%N!&$U\\4%78!& !&ellD&8 9!& ZZ	!&
 ||!&r>   r  c                        e Zd Zdef fdZd Zd Z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
j                     deeef   fd       Z xZS )MusicgenModelr   c                 d    t         |   |       t        |      | _        | j	                          y rT   )rU   rV   r  decoderr  )rX   r   rY   s     r?   rV   zMusicgenModel.__init__  s&     &v.r>   c                 .    | j                   j                  S rT   rO  r  rX   s    r?   get_input_embeddingsz"MusicgenModel.get_input_embeddings  s    ||(((r>   c                 &    || j                   _        y rT   rQ  rX   r   s     r?   set_input_embeddingsz"MusicgenModel.set_input_embeddings  s    $)!r>   c                     | j                   S rT   rO  rR  s    r?   get_decoderzMusicgenModel.get_decoder      ||r>   r@   r1   r   r   r   r  r  r  r   r   r  r  r   r   c                    |
|
n| j                   j                  }
||n| j                   j                  }|	|	n| j                   j                  }	||n| j                   j                  }| j                  |||||||||	|
|||      }|s|S t        |j                  |j                  |j                  |j                  |j                        S )r  )r@   r1   r   r   r   r  r  r  r   r   r  r  r   r#  )r   r   r  r   r'  rO  r   r$  r  r   r%  r&  )rX   r@   r1   r   r   r   r  r  r  r   r   r  r  r   decoder_outputss                  r?   r   zMusicgenModel.forward  s    l 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B] ,,)#9"7!5+'/!5#) ' 
  ""8-??+;;)77&11,==
 	
r>   rJ  )r3   r4   r5   r+   rV   rS  rV  rY  r"   r   r8   r;   r   r9   r7   r   r   r   r   r   r   s   @r?   rM  rM    sv   4 )*  1515=A=A,07;EI59$(,0/3&*15V
E,,-V
 !.V
  ((9(9:	V

 !))9)9 :V
 ELL)V
 'u||4V
 "%e.?.?(@"ABV
   1 12V
 D>V
 $D>V
 'tnV
 d^V
 !.V
 
u??	@V
 V
r>   rM  zK
    The MusicGen decoder model with a language modelling head on top.
    )custom_introc            "           e Zd Zdef fdZd Zd Zd Zd Zd Z	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j                     dee   dee   dee   dee   deej                     deeef   fd       Z	 	 	 	 	 	 	 	 	 d'dZ	 d(d	ej                  dedee   fdZed        Z ej6                         	 	 	 	 	 	 d)deej                     dee   d ee   d!ee   d"ee   d#ed$   fd%       Z xZ S )*MusicgenForCausalLMr   c           
      Z   t         |   |       t        |      | _        |j                  | _        t        j                  t        |j                        D cg c].  }t        j                  |j                  |j                  d      0 c}      | _        | j                          y c c}w )NFr   )rU   rV   rM  r   r  r   r  r  r   r   r  lm_headsr  )rX   r   r  rY   s      r?   rV   zMusicgenForCausalLM.__init__M  s     "6*
#11SXY_YmYmSnoaRYYv))6+<+<5Io

 		 ps   3B(c                 B    | j                   j                  j                  S rT   r   rO  r  rR  s    r?   rS  z(MusicgenForCausalLM.get_input_embeddingsZ  s    zz!!...r>   c                 :    || j                   j                  _        y rT   rc  rU  s     r?   rV  z(MusicgenForCausalLM.set_input_embeddings]  s    */

'r>   c                     | j                   S rT   ra  rR  s    r?   get_output_embeddingsz)MusicgenForCausalLM.get_output_embeddings`  s    }}r>   c                     || _         y rT   rf  rX   new_embeddingss     r?   set_output_embeddingsz)MusicgenForCausalLM.set_output_embeddingsc  s	    &r>   c                 &    || j                   _        y rT   r   rO  )rX   rO  s     r?   set_decoderzMusicgenForCausalLM.set_decoderf  s    $

r>   c                 .    | j                   j                  S rT   rm  rR  s    r?   rY  zMusicgenForCausalLM.get_decoderi  s    zz!!!r>   r@   r1   r   r   r   r  r  r  labelsr   r   r  r  r   r   c                 n   ||n| j                   j                  }|	9|7|5t        |	| j                   j                  | j                   j                        }| j                  |||||||||
||||      }|d   }t        j                  | j                  D cg c]
  } ||       c}d      }d}|	|dddd|	j                  d    df   }t               }t        j                  g | j                        }|	j                  |	| j                   j                  k(  d      }	t        | j                   j                        D ]f  }|dd|f   j!                         j#                  d|j                  d         }|	d	|f   j!                         j#                  d      }| |||      z  }h || j                   j                  z  } |j$                  dg|j                  d
d  }|s|f|dd z   }||f|z   S |S t'        |||j(                  |j*                  |j,                  |j.                        S c c}w )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)r1   r   r   r   r  r  r  r   r   r  r  r   r   r)   rh   r_   rF   rD   .r%   )losslogitsr  r   r%  r&  )r   r'  rN   rA   bos_token_idr   r8   stackra  rI   r	   rt   r_   masked_fillr  r  r   rs   r   r   r  r   r%  r&  )rX   r@   r1   r   r   r   r  r  r  rp  r   r   r  r  r   r   r   r   head	lm_logitsrs  rt  loss_fctr8  codebook_logitscodebook_labelsoutputs                              r?   r   zMusicgenForCausalLM.forwardl  sH   z &1%<k$++B]B]Y%6=;P*64;;3K3KT[[MeMefI**)"7#9!5+'/!5#)  
   
KK Om!4 OUVW	 q!fll1o%5%778F')H;;r$++6D ''$++2J2J(JDQF "$++";";< C"(H"5"@"@"B"G"GFLLY[L\"]"(h"7"B"B"D"I"I""M/BBC
 $++333D &I%%b?9??12+>?	\GABK/F)-)9TGf$EvE0#33!//))$55
 	
? !Ps   H2c           	      .   |	?| j                  || j                  j                  | j                  j                        \  }}	| j	                  ||	      }|
)|
dkD  r$|j                  d      }||j                  d      }||d d dd f   }||||||||dS )NrA   
max_lengthr)   r%   r)   rD   )r@   r1   r   r   r   r  r  r   )build_delay_pattern_maskgeneration_configrA   r  apply_delay_pattern_maskrepeat)rX   r@   r1   r   r   r   r  r  r   delay_pattern_maskr2   r   s               r?   prepare_inputs_for_generationz1MusicgenForCausalLM.prepare_inputs_for_generation  s     %,0,I,I!33@@11<< -J -)I) 11)=OP	%.1*< "((0I)!/!6!6v!>&!!RS&)I #,%:&<"$8."	
 		
r>   rA   r  c                 P   |j                  d| j                  |j                  d         }|j                  \  }}}||n| j                  j                  }t        j                  |||ft
        j                  |j                        dz  }| j                  j                  dk(  r|dz  n|}|d|z  dz
  k  r*|j                  ||z  d      |j                  ||z  d      fS t        |      D ]p  }	| j                  j                  dk(  r|dd|	f   |dd|	|	||	z   f<   3|ddd|	z  f   |ddd|	z  |	||	z   f<   |ddd|	z  dz   f   |ddd|	z  dz   |	||	z   f<   r t        j                  t        j                  ||ft
        j                        ||z
  dz         }
|
t        j                  t        j                  ||ft
        j                              z   }
| j                  j                  dk(  r|
j                  dd	      }
|
j!                  |j                         }||z  | |z  z   }|dddddf   }|dk(  j#                         dddf   }t%        |      dkD  rt'        |      }n|}|j                  ||z  d      }|d
d|f   j                  ||z  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.
        rD   Nr]   r%   r)   rg   )diagonalr   rh   .)r   r  rI   r  r  r8   rG  longr_   r   audio_channelsr  triur   trilrepeat_interleaverc   nonzeror0  min)rX   r@   rA   r  r}   r  r   input_ids_shiftedchannel_codebooksr8  delay_patternmaskfirst_codebook_ids	start_idsfirst_start_idpattern_masks                   r?   r  z,MusicgenForCausalLM.build_delay_pattern_mask  s   , %%b$*<*<ioob>QR	&/oo#]G#-#9Zt?U?U?`?`
JJ]J7uzzR[RbRbcfhh 	 37++2L2LPQ2QMQ.Wd--11$$S=%8"=?P?X?XY\_lYlnp?qqq /0 	wH{{))Q.PYZ[]eZePf!!Xx'H:L/L"LM U^^_abemam^mTn!!Q\8g>P3P"PQXabcefiqeqtueubuXv!!Q\A%5x'HBT7T"TU	w 

JJ):6ejjIT^arTruvTv
 &

5::?PR\>]ejeoeo3p(qq;;%%*);;A1;EM  !1!122,,u|/CC	 'q!Qw/'2-668A>	y>A ^N %N !((})<bAc?N?23;;C-<OQST	,&&r>   c                 j    | j                   d   }|dd|f   }t        j                  |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.rD   .N)rI   r8   where)r@   decoder_pad_token_maskr   s      r?   r  z,MusicgenForCausalLM.apply_delay_pattern_maska  sD     //"%!7XgX!FKK 6" <iI_`	r>   inputsr  logits_processorstopping_criteriasynced_gpusstreamerr-   c           	         || j                   }t        j                  |      } |j                  di |}|j	                          | j                  |j                                ||n	t               }||n	t               }d|v}	|j                  dd      du}
| j                  ||j                  |      \  }}}|j                  d   | j                  z  }| j                  ||
|j                         |j                  |d<   |j                   |d<   |j                  dd      |	r| j#                  |||      |d<   |j                  d   }|j                  d	      du xr |j$                  du}|j                  d
      du xr |j&                  du}| j)                  ||||||      }| j+                  |||       |j$                  dz
  }|j                  d   |k7  r-|dk(  r(| j,                  j.                  s||j                  d   z  }| j1                  ||d|||j                         | j3                  ||j4                  |j$                        \  }}||j7                  |j9                                ||d<   |j;                         }|j                   :|j                   dkD  r+|j=                  t?        |j                                d|_        | jA                  |||d||j                        }| jC                  ||      }|tD        jF                  tD        jH                  fv r< | jJ                  d||jL                  d|\  }} | jN                  |f|||||d|}ntQ        d      |jR                  r|jT                  }n|}| jW                  ||d         }|||jX                  k7     j[                  || j                  d      }|jR                  r	||_*        |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`]
        Nr0   r1   r   rr  r   r2   rD   r  
min_lengthr  has_default_max_lengthhas_default_min_lengthmodel_input_nameinputs_tensorinput_ids_lengthr)   r  )assistant_model
batch_sizemax_cache_lengthr_   r  r  r  input_ids_seq_lengthencoder_input_idsprefix_allowed_tokens_fnr  r_   r  r  )r@   expand_sizer  r  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`.r=   ).r  copydeepcopyr   validate_validate_model_kwargsr   r   r   _prepare_model_inputsru  rI   r  _prepare_special_tokensr_   r   r2   &_prepare_attention_mask_for_generationr  r  _prepare_generated_length_validate_generated_lengthr   is_encoder_decoder_prepare_cache_for_generationr  _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_samplerK   return_dict_in_generate	sequencesr  _pad_token_tensorr   )rX   r  r  r  r  r  r  r   model_kwargsrequires_attention_maskkwargs_has_attention_maskr@   r  r  r  r  r  r  r  generation_moder   
output_idss                         r?   generatezMusicgenForCausalLM.generatej  s   V $ $ 6 6 MM*;</(//9&9""$##L$5$5$78 0@/K+QdQf1B1N-ThTj"3<"G$0$4$45Et$LTX$X! 594N4N%22L5
1	#\ __Q'4+=+==
$$%68QZcZjZj$k %6$?$?[!):)I)I%&,d3;@W-1-X-X,l.L)*
 %??2.!'L!9T!A!nFWFbFbjnFn!'L!9T!A!nFWFbFbjnFn ::/#9#9-#- ; 
 	''(9;KMcd -77!;""1%)99 O3KK22 0 6 6q 99** !-#** 	+ 	
 )-(E(E*FF(33 )F )
%	% LL) .@)* ,??A ++7<M<\<\_`<`##$IJ[JjJj$kl/3,  55/!1'%)-## 6 
 !77/CT 8 
 ~44n6R6RSS&Hd&H&H '#-BB' '#I| #dll!1"3"3'! G l 
 44 **J J 22:|L`?ab
  
.?.Q.Q QRZZ**B

 44 *GNr>   )NNNNNNNNNNNNNN)	NNNNNNTNNrT   NNNNNN)!r3   r4   r5   r+   rV   rS  rV  rg  rk  rn  rY  r"   r   r8   r;   r   r9   r7   r   r   r   r   r  r   r  r   r  r   r   r   r   r  r   r   s   @r?   r_  r_  G  s   4 /0'%"  1515=A=A,07;EI59-1$(,0/3&*15y
E,,-y
 !.y
  ((9(9:	y

 !))9)9 :y
 ELL)y
 'u||4y
 "%e.?.?(@"ABy
   1 12y
 ))*y
 D>y
 $D>y
 'tny
 d^y
 !.y
" 
u77	8#y
 y
| "#!,
^ [_I'))I'9<I'JRSV-I'V   U]]_ *.8<:><@&*-1[&[ $$45[ ##67	[
 $$89[ d^[ >*[ [r>   r_  z_
    The composite MusicGen model with a text encoder, audio encoder and Musicgen decoder,
    c            $       $    e Zd ZU eed<   dZdZdZ	 	 	 	 d?dee   dee	   dee	   dee
   f fdZd	 Zd
 Zd Zd Zd Zd Zd Zd Ze	 	 	 d@dee   dee   dee   de	fd       Ze	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dAdeej2                     deej4                     deej6                     deej4                     deej2                     deej4                     deeej6                        deeeej6                           deej6                     deej6                     deej2                     d ee   d!ee   d"ee   d#ee   deeef   f d$       Z 	 	 	 	 	 	 	 	 	 	 	 dBd%Z!	 	 	 d@d&e"d'ed(e#eejH                  f   d)ee"   d*ee"   d+ejJ                  deej2                  e#eejH                  f   f   fd,Z&d-ejH                  d'ee   d.e'de#ee(f   fd/Z)	 dCd'ee   fd0Z*dejH                  fd1Z+d2 Z,d3 Z-d4 Z.	 	 	 d@d5eejH                     d*ee"   d(ee#eejH                  f      dej2                  fd6Z/	 dDd)eee"e0e"   f      d*ee"   de"fd7Z1 ejd                         	 	 	 	 	 	 dEd5eejH                     d.ee'   d8ee3   d9ee4   d:ee   d;ed<   fd=       Z5dFd>Z6 xZ7S )G MusicgenForConditionalGenerationr   encoder_decoderr@   Ttext_encoderaudio_encoderrO  c                 4   ||||t        d      |6t        j                  |j                  |j                  |j                        }n1t	        || j
                        st        d| d| j
                         |j                  j                  g|j                  j                  |j                  j                  k7  r:t        d|j                  j                   d|j                  j                   d      t        | -  |       |!dd	lm} |j                  |j                        }|"dd
lm}  |j                  |j                         }|t"        j%                  |j                        }|| _        || _        || _        | j                  j                  j'                         | j                  j                  j'                         k7  rCt(        j+                  d| j                  j,                   d| j                  j                          | j                   j                  j'                         | j                  j                   j'                         k7  rCt(        j+                  d| j                   j,                   d| j                  j                           | j                  j                  j'                         | j                  j                  j'                         k7  rCt(        j+                  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                  k7  rw| j                  j                  j                  Wt1        j2                  | j                  j                  j                  | j                  j                  j                        | _        | j                  j7                         t        d| j                   d      t9        t;        j<                  | j                  j>                        j@                  jC                               }d|vrt        d      | jE                          y)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)#rK   r*   from_sub_models_configr   r   config_classrO  cross_attention_hidden_sizer  r   rU   rV   auto.modeling_autor  from_configr(   r  r_  _from_configto_dictr(  warningrY   r   r   r   enc_to_dec_projrg  setinspect	signaturer   
parametersr   tie_weights)	rX   r   r  r  rO  r  r(   decoder_signaturerY   s	           r?   rV   z)MusicgenForConditionalGeneration.__init__T  s{    >|3}7LPWP_~  >#::<;N;NP]PdPdfmftftuFfd&7&78 8F83FtGXGXFY!Z[[>>55A~~99V=P=P=\=\\ AAGAkAk@l mIIOI\I\IhIhHi j::  	 E3??@S@STL 61I11&2F2FGM?)66v~~FG(*##++-1I1I1Q1Q1SSNN.t/@/@/J/J.K LKK,,-/ $$,,.$++2K2K2S2S2UUNN/0B0B0L0L/M NKK--.0 <<&&(DKK,?,?,G,G,IINN)$,,*@*@)A BKK''(* 9=8I8I8P8P8e8e  59=9K9K9R9R9g9g!!637<<3F3F3[3[0#';;#;#; $(KK$=$=!"kk11 $$00DLL4G4G4S4SS##??G#%99T->->-E-E-Q-QSWS_S_SfSfSrSr#sD 224@t0011st    1 1$,,2F2F G R R W W YZ"*;;k  	r>   c                     | j                   j                  rg| j                  j                  }| j	                  | j
                  | j                  j                  |   | j                  j                  d      }|| _        y y )Nr  )r   tie_encoder_decoderrO  r   _tie_encoder_decoder_weightsr  _modules_dynamic_tied_weights_keys)rX   decoder_base_model_prefixtied_weightss      r?   r  z,MusicgenForConditionalGeneration.tie_weights  sj    ;;**(,(F(F%<<!!%%&?@..	L /;D+ +r>   c                     | j                   S rT   )r  rR  s    r?   get_audio_encoderz2MusicgenForConditionalGeneration.get_audio_encoder  s    !!!r>   c                     | j                   S rT   )r  rR  s    r?   get_text_encoderz1MusicgenForConditionalGeneration.get_text_encoder  s       r>   c                 "    | j                         S rT   )r  rR  s    r?   get_encoderz,MusicgenForConditionalGeneration.get_encoder  s    $$&&r>   c                     | j                   S rT   rX  rR  s    r?   rY  z,MusicgenForConditionalGeneration.get_decoder  rZ  r>   c                 6    | j                   j                         S rT   )r  rS  rR  s    r?   rS  z5MusicgenForConditionalGeneration.get_input_embeddings  s      5577r>   c                 6    | j                   j                         S rT   )rO  rg  rR  s    r?   rg  z6MusicgenForConditionalGeneration.get_output_embeddings  s    ||1133r>   c                 8    | j                   j                  |      S rT   )rO  rk  ri  s     r?   rk  z6MusicgenForConditionalGeneration.set_output_embeddings  s    ||11.AAr>   *text_encoder_pretrained_model_name_or_path+audio_encoder_pretrained_model_name_or_path%decoder_pretrained_model_name_or_pathr   c           	         |j                         D ci c]%  \  }}|j                  d      r|t        d      d |' }}}|j                         D ci c]%  \  }}|j                  d      r|t        d      d |' }	}}|j                         D ci c]&  \  }}|j                  d      s|t        d      d |( }
}}|D ]  }|d|z   = 
 |	D ]  }|d|z   = 
 |
D ]  }|d|z   = 
 |j                  dd      }||t	        d      d|vret        j                  |fi |dd	i\  }}|j                  d	u s|j                  d	u r't        j                  d
| d       d|_        d|_        ||d<   t        j                  |g|i |}|	j                  dd      }||t	        d      d|	vret        j                  |fi |	dd	i\  }}	|j                  d	u s|j                  d	u r't        j                  d
| d       d|_        d|_        ||	d<   t        j                  |g|i |	}|
j                  dd      }||t	        d      d|
vrt        j                  |fi |
dd	i\  }}
t        |t              r|j                  }|j                  du s|j                  du r-t        j                  d
| d| d| d       d	|_        d	|_        ||
d<   |
d   j                  du s|
d   j                  du rt        j                  d| d| d       t!        j                  |fi |
}t        j"                  |j$                  |j$                  |j$                  fi |} | ||||      S c c}}w c c}}w c c}}w )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")
        ```text_encoder_Naudio_encoder_decoder_r   zxIf `text_encoder_model` is not defined as an argument, a `text_encoder_pretrained_model_name_or_path` has to be defined.r   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  rO  r   )items
startswithr0  poprK   r&   from_pretrainedr   add_cross_attentionr(  infor(   r   r*   rO  r  r_  r  r   )clsr  r  r  
model_argsr   argumentr   kwargs_text_encoderkwargs_audio_encoderkwargs_decoderr   r  encoder_configr  rO  decoder_configr   s                     r?   from_sub_models_pretrainedz;MusicgenForConditionalGeneration.from_sub_models_pretrained  s   T $*<<>
%""?3 S)+,e3
 
 $*<<> 
%""#34 S)*,-u4 
  
 GMlln
3B8UX`XkXklvXwHS_&'.
 

 ' 	.C,-	.' 	/C'#-.	/! 	)CzC'(	) +..w=9A % 
 226@6P6P>7BU7lp73 3 ",,48Z8Z^b8bKK'(R'S T^ ^ 16N-9>N60>#H-$44:=GK^L -00$? :B % 
 337A7Q7Q?8CW8nr84 4 ",,48Z8Z^b8bKK'(S'T U^ ^ 16N-9>N61?$X.%55;>HL`M !$$Wd3?4< % 
 ~-1;1K1K92=K2bf2. nn=%3%;%;N!,,59[9[_d9dKK'(M'N O00U/V WABBtv
 15N-9=N6+9x(h'22e;~h?W?k?kot?t$%J$K L..S-T UMM *99:_rcqrG  66!5!5w~~
IO
 MSZcijjw
 

s   *M1*M7M=.M=r1   input_valuespadding_maskdecoder_input_idsdecoder_attention_maskr0   r  r  decoder_inputs_embedsrp  r   r   r  r  c                    ||n| j                   j                  }|j                         D ci c]%  \  }}|j                  d      r|t	        d         |' }}}|j                         D ci c]%  \  }}|j                  d      r|t	        d         |' }}}|j                         D ci c]&  \  }}|j                  d      s|t	        d      d |( }}}| | j
                  d|||	|||d|}nt        |t              rt        | }|d   }| j
                  j                   j                  | j                  j                   j                  k7  r1| j                  j                   j                  | j                  |      }|||d   z  }|N|L|
Jt        || j                   j                  j                  | j                   j                  j                        }n||
 | j                   d||d|}|j"                  }|j$                  \  }}}}|d	k7  rt'        d
| d      | j                   j                  j(                  dk(  r<|j$                  d   | j                  j*                  dz  k(  r|j-                  dd      }|d   j/                  || j                  j*                  z  |      } | j                  d|||||
||||||d|}|s||z   S t1        |j2                  |j4                  |j6                  |j8                  |j:                  |j<                  |j>                  |j8                  |j:                  	      S c c}}w c c}}w c c}}w )a  
        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)
        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]`

        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])
        ```Nr  r  r  )r@   r1   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%   rh   r   .)r@   r1   r   r   r  r   r  r   r  r  rp  )	rs  rt  r  decoder_hidden_statesdecoder_attentionsr&  encoder_last_hidden_stater   encoder_attentionsr=   ) r   r'  r  r  r0  r  r   r7   r   r   rO  r  r  rN   rA   rB   r  audio_codesrI   rK   r  r  r  r   r   rs  rt  r  r   r%  r&  r$  )rX   r@   r1   r  r  r  r  r0   r  r  r  rp  r   r   r  r  r   r  r   r  r  r  r   audio_encoder_outputsr!  framesr}   r~   r   r\  s                                 r?   r   z(MusicgenForConditionalGeneration.forward  s   \ &1%<k$++B]B] $*<<>
%""?3 S)*E1
 
 $*<<> 
%""#34 S)*+U2 
  
 GMlln
3B8UX`XkXklvXwHS_&'.
 
 "/d// #-+"3%9' &O /-?O / 2 $$00DLL4G4G4S4SS##??G$($8$89N$O!%$9N9<U$U!%6%>CXC` 2++88$++:M:M:d:d! &+@+H$6D$6$6 %))% '%!
 0;;K.9.?.?+FCG{ Fvh OT T 
 {{""11Q6;;L;LQ;OSWS_S_SmSmqrSr;r);;A1;E +F 3 ; ;C$,,B\B\<\^e f '$,, 
'1"7#1//!5+#
 
 "_44 %%"))+;;"1"?"?.99,==&5&G&G"1"?"?.99

 
	
k
 

s   *M	.*M.MMc                 
   |
I| j                   j                  || j                  j                  | j                  j                        \  }}
| j                   j                  ||
      }|)|dkD  r$|j                  d      }||j                  d      }|c|d   |j                  d   k\  r|d d |j                  d    d f   }n4|j                  d   |j                  d   k7  r
|d d |f   }n|d d dd f   }d |	||||||||d
S )N)r  r)   r  rD   r   )
r@   r0   r  r  r1   r  r   decoder_head_maskr  r   )rO  r  r  rA   r  r  r  rI   )rX   r  r  r1   r   r  r%  r  r   r0   decoder_delay_pattern_maskr2   r   r   s                 r?   r  z>MusicgenForConditionalGeneration.prepare_inputs_for_generationU  sI   " &-<@LL<a<a!&&3311<< =b =99 !LLAABSUop%.1*< !2 8 8 @%1)?)F)Fv)N&&b!%6%<%<Q%??$5a.:N:Nq:Q9Q9S6S$T!!''*n.B.B1.EE$5a6G$H! %6af$=! ..!2,&<"!2$8"
 	
r>   r  r  r  rB   ru  r_   c                 H   |d|v r|j                  d      }nd|v r|dk7  r|j                  d      }nd}| j                  ||      }|| j                  }t        j                  || j
                  j                  z  dft        j                  |      |z  }||}||fS |d   |k7  j                         j                         r\t        j                  ||gd      }d	|v r?|d	   }	t        j                  t        j                  |	      ddddf   |	fd      }	|	|d	<   ||fS )
zGPrepares `decoder_input_ids` for generation with encoder-decoder modelsNr  r@   r)   r]   rE   rD   rh   r  )r  _get_decoder_start_token_idr_   r8   rG  rO  r  r  allitemrp   	ones_like)
rX   r  r  r  rB   ru  r_   r  decoder_input_ids_startr  s
             r?   )_prepare_decoder_input_ids_for_generationzJMusicgenForConditionalGeneration._prepare_decoder_input_ids_for_generation  s[    #(;|(K , 0 01D EL(-=-L , 0 0 = $ "&!A!ABXZf!g>[[FJJ
T\\%?%??C5::^de$% 	  $ 7 !,..  '+AAFFHMMO %		+BDU*V\^ _'<7)56N)O&).__%;<QUCE[\*& :P56 ,..r>   r  r  c                 t   | j                         }t        |d      rd|j                  _        g d}|j	                         D ci c]  \  }t        fd|D              s| }	}}t        t        j                  |j                        j                        }
d|
v xs d|
v }|s(|	j	                         D ci c]  \  }}||
v s|| }	}}|j                  |	d<   |j                  |	d<   |j                  }||n| j                  j                  }d|	d	<   ||	|<    |di |	j                   }|j|d
kD  ret#        j$                  |t#        j&                  |      gd      }d|v r5t#        j$                  |d   t#        j&                  |d         gd      |d<   t)        |      |d<   |S c c}}w c c}}w )N_hf_hookTr  
cross_attnr   c              3   @   K   | ]  }j                  |        y wrT   r  r   r   r  s     r?   r"  z_MusicgenForConditionalGeneration._prepare_text_encoder_kwargs_for_generation.<locals>.<genexpr>       I!x**1-I   r   r  r   r  r  r)   r   rh   r1   r$  r0   r=   )r  rb   r/  io_same_devicer  anyr  r  r  r   r  r   r  r2   r  main_input_namer$  r8   concatenate
zeros_liker   )rX   r  r  r  r  encoderirrelevant_prefixr  r   encoder_kwargsencoder_signatureencoder_accepts_wildcardr2   r$  s          `      r?   +_prepare_text_encoder_kwargs_for_generationzLMusicgenForConditionalGeneration._prepare_text_encoder_kwargs_for_generation  s    '') 7J'.2G+ D $0#5#5#7
 
%I7HII eO
 

   1 1'// B M MN#+/@#@#gNVgDg '7E7K7K7M$3HeQY]nQn%N  /@.Q.Q*+1B1W1W-.*99 0@/K+QUQbQbQrQr(,}%+8'(#5n5GG %.1*< % 1 13DeFVFVWhFi2jpq r</161B1B!"23U5E5ElScFd5eflm2-. +:L]*^&'?
s   !F.<F4	F4c                    | j                         }t        |d      rd|j                  _        g d}|j	                         D ci c]  \  }t        fd|D              s| }}}t        t        j                  |j                        j                        }	d|	v xs d|	v }
|
s(|j	                         D ci c]  \  }}||	v s|| }}}||n| j                  j                  }d|d<   | j                  j                  j                  dk(  rB|||<    |j                   di |}|j"                  }|j$                  }|j&                  \  }}}}n|j&                  d   d	k7  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&                  \  }}}}|j+                  ||d	|z  |f      }||d d d d d d d	d d f<   ||d d d d dd d	d d f<   |d gk7  s|d gk7  rt-        j.                  ||gd      }nd g|z  }|dk7  rt)        d| d      |d   j1                  || j                  j2                  z  |      }||d<   ||d<   |S c c}}w c c}}w )Nr/  Tr0  c              3   @   K   | ]  }j                  |        y wrT   r3  r4  s     r?   r"  z`MusicgenForConditionalGeneration._prepare_audio_encoder_kwargs_for_generation.<locals>.<genexpr>  r5  r6  r   r  r  r)   r%   z3Expected stereo audio (2-channels) but example has z	 channel.rh   r  r  r  r  audio_scalesr=   )r  rb   r/  r8  r  r9  r  r  r  r   r  r  r:  rO  r   r  encoder!  rE  rI   rK   new_onesr8   rv  r   r  )rX   r  r  r  r=  r>  r  r   r?  r@  rA  r"  r!  rE  r#  r}   r~   r   audio_encoder_outputs_leftaudio_codes_leftaudio_scales_leftaudio_encoder_outputs_rightaudio_codes_rightaudio_scales_rightr  s         `                  r?   ,_prepare_audio_encoder_kwargs_for_generationzMMusicgenForConditionalGeneration._prepare_audio_encoder_kwargs_for_generation  sJ    ((* 7J'.2G+ D $0#5#5#7
 
%I7HII eO
 

   1 1'// B M MN#+/@#@#gNVgDg '7E7K7K7M$3HeQY]nQn%N 
 0@/K+QUQcQcQsQs(,}%<<--2/;N+,$2GNN$D^$D!/;;K0==L.9.?.?+FCG !!!$) I,J\J\]^J_I``ij  0<Arr1H/EN+,)7)I.)I&9EE : G G/;Aqr1H/EN+,*8'..*J>*J' ; G G!<!I!I.>.D.D+FCG*33VS!i-QX4YZK(8K1cc1%):K1addA& TF*.@TF.J${{,=?Q+RXYZ $v|Q;B6( KP P 
 (/77dll>X>X8XZab,=()'3^$}
s   !J><K	Kc                     t        || j                  j                  j                  | j                  j                  j                        S rT   )rN   r   rO  rA   ru  )rX   rp  s     r?   %prepare_decoder_input_ids_from_labelszFMusicgenForConditionalGeneration.prepare_decoder_input_ids_from_labels;  s1    !&$++*=*=*J*JDKKL_L_LlLlmmr>   c                     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(...)))NotImplementedError)rX   argsr   s      r?   resize_token_embeddingsz8MusicgenForConditionalGeneration.resize_token_embeddings>  s    !;
 	
r>   c                 r    | j                   j                         D ]	  }d|_         d| j                   _        y)z3
        Freeze the audio encoder weights.
        FN)r  r  requires_grad_requires_gradrX   params     r?   freeze_audio_encoderz5MusicgenForConditionalGeneration.freeze_audio_encoderE  s8     ''224 	(E"'E	(,1)r>   c                 r    | j                   j                         D ]	  }d|_         d| j                   _        y)z2
        Freeze the text encoder weights.
        FN)r  r  rV  rW  rX  s     r?   freeze_text_encoderz4MusicgenForConditionalGeneration.freeze_text_encoderM  s8     &&113 	(E"'E	(+0(r>   r  c                    ||S |j                  d      }|I|d   j                         dd }t        j                  |t        j                  | j
                        dz  S |t        d      d}|j                         D ]-  }t        |t        j                        s|j                  d   } n t        j                  |dft        j                  | j
                        |z  S )	z3Initializes input ids for generation, if necessary.Nr0   r   rD   r]   rF   zB`bos_token_id` has to be defined when no `input_ids` are provided.r)   )r   rz   r8   rG  r  r_   rK   r   r   r   rI   )rX   r  ru  r  r0   rI   r  r   s           r?   *_maybe_initialize_input_ids_for_generationzKMusicgenForConditionalGeneration._maybe_initialize_input_ids_for_generationU  s     M&**+<=&#A&++-cr2E::e5::dkkJTQQabb 
!((* 	E%."[[^
	 zz:q/DKKPS___r>   c                     ||n| j                   j                  }||n| j                   j                  }||S ||S t        d      )Nz\`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation.)r  rB   ru  rK   )rX   rB   ru  s      r?   r(  z<MusicgenForConditionalGeneration._get_decoder_start_token_idq  se    
 &1 #''>> 	
 (4'?|TE[E[EhEh!-))%j
 	
r>   r  r  r  r  r-   c           	      B
   || j                   }t        j                  |      } |j                  di |}|j	                          | j                  |j                                |j                  d      )t        |d         t        u rt        |d   d         |d<   ||n	t               }||n	t               }d|v}	|j                  dd      du}
| j                  ||j                  |      \  }}}|j                  d   }| j                  ||
|j                          |j"                  |d<   |j$                  |d<   |j                  dd      |	r| j'                  |||      |d<   d|vr| j)                  ||||      }d	|vrd
|v r| j+                  |d
   |      }| j-                  ||||j.                  |j0                  |j                         \  }}|j                  d   }|j                  d      du xr |j2                  du}|j                  d      du xr |j4                  du}| j7                  ||||||      }| j8                  j;                  ||j.                  |j2                        \  }}||d<   ||j=                  |j?                                |jA                         }|j$                  :|j$                  dkD  r+|jC                  tE        |j$                               d|_        | jG                  |||d||j                         }| jI                  ||      }|tJ        jL                  tJ        jN                  fv rQ | jP                  d||jR                  | jT                  jV                  d|\  }} | jX                  |f|||||d|}nt[        d      |j\                  r|j^                  }n|}| j8                  ja                  ||d         }|||jb                  k7     je                  || j8                  jf                  d      }|d   }|j                  d      }|dg|z  }| j8                  jT                  jh                  dk(  r(| jj                  jm                  ||      jn                  }n| jj                  jm                  |dddddddddf   |      }|jn                  }| jj                  jm                  |dddddddddf   |      }|jn                  }tq        jr                  ||gd      }|j\                  r	||_/        |S |S )r  Nr0   r   r7  r1   rr  r   r2   r  r  )r  r  r  rB   ru  r_   rD   r  r  r  r  r&  r)   r  r  )r@   r  r  r  r  )N.rE  )rE  r%   rh   r=   ):r  r  r  r   r  r  r   typer7   r   r   r   r  ru  rI   r  r_   r   r2   r  rB  rN  r-  r  _bos_token_tensorr  r  r  rO  r  r  r  r  r  r   r  r  r   r  r  r  r  r   r  r  rK   r  r  r  r  r   r  r  r  decodeaudio_valuesr8   rp   )rX   r  r  r  r  r  r  r   r  r  r  r  r  r  r@   r  r  r  r&  r  r   r  rE  output_valuescodec_outputs_leftoutput_values_leftcodec_outputs_rightoutput_values_rights                               r?   r  z)MusicgenForConditionalGeneration.generate  s   V $ $ 6 6 MM*;</(//9&9""$##L$5$5$78-.:tLQbDc?dhm?m.=P\]nPopqPr.sL*+ 0@/K+QdQf1B1N-ThTj"3<"G$0$4$45Et$LTX$X! 9=8R8R%22L9
5' #((+
$$%68QZgZnZn$o %6$?$?[!):)I)I%&,d3;@W-1-X-X0,.L)* L0KK|-=?PL l2~7ULL^,L #'"P"P!-%#4#P#P*<< '' #Q #
	< %??2.!'L!9T!A!nFWFbFbjnFn!'L!9T!A!nFWFbFbjnFn ::/#9#9-'- ; 
 150U0U*FF(33 1V 1
-	- 6P12 LL) ,??A ++7<M<\<\_`<`##$IJ[JjJj$kl/3,  55/!1+%)-## 6 
 !77/CT 8 
 ~44n6R6RSS&Hd&H&H '#-BB#';;#A#A' 	'#I| #dll!1"3"3'! G l 
 44 **J J \\:::|TpGqr
  
.?.Q.Q QRZZ22B


  	*
#''7 6J.L<<--2 ..55) 6  l 
 "&!3!3!:!::aCaCQRl;Sbn!:!o!3!@!@"&"4"4";";Jq!QTPQTST}<Udp";"q"5"B"B!II'9;N&OUVWM44 -GN  r>   c                    t        j                  |d| j                  j                  j                  f| j
                  | j                        }t        j                  |df| j
                  t         j                        }t        |f|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)   )r_   r^   r   )r0   r1   r2   )	r8   rt   r   r  r   r_   r^   r  r/   )rX   num_samplesr$  r1   s       r?   get_unconditional_inputsz9MusicgenForConditionalGeneration.get_unconditional_inputsz	  sy    , "KK!T[[55AAB4;;^b^h^h
 k1%5dkkQVQ[Q[\).0)
 	
r>   )NNNN)NNN)NNNNNNNNNNNNNNN)NNNNNNNNNNNrT   )NNr  )r)   )8r3   r4   r5   r*   r:   r   r:  r   r   r    r_  rV   r  r  r  r  rY  rS  rg  rk  classmethodstrr  r"   r8   r;   
BoolTensorr9   r7   r   r   r   r   r  r   dictr   r_   r-  r   r   rB  rN  rP  rT  rZ  r\  r^  listr(  r   r   r   r  rl  r   r   s   @r?   r  r  I  s    )!O&*# ,0263715c(c /c  0	c
 -.cJ; "!'84B  EIEI?C	Bk4<SMBk 6>c]Bk 08}	Bk 
Bk BkH  155948378<=A>BEI59=A-1$(,0/3&*!n
E,,-n
 !!1!12n
 u001	n

 u//0n
 $E$4$45n
 !))9)9 :n
 "%(9(9":;n
 "%e.?.?(@"ABn
   1 12n
  ((9(9:n
 ))*n
 D>n
 $D>n
 'tnn
  d^!n
$ 
uo%	&%n
 n
f #!#'8
~ 15&*#-/-/ -/ 3,-	-/
 !)-/ sm-/ -/ 
uc5<<&7!88	9-/^/||/ #3-	/
 ,/ 
c3h/d MQJ<DSMJXnELL n
21 *.&*:>	`&` sm` tC$567	`
 
		`: mq
&.uS$s)^/D&E
\deh\i
	
$ U]]_ *.8<:><@&*-1t!&t! $$45t! ##67	t!
 $$89t! d^t! >*t! t!l 
r>   r  )r  r_  rM  r   )Nr   N)Sr6   r  r  rj   r2  dataclassesr   typingr   r   r   r   r   r8   torch.nnr   r	   activationsr   cache_utilsr   r   
generationr   r   r   r   r   r   modeling_attn_mask_utilsr   r   r   r   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   r   r   modeling_utilsr   r    processing_utilsr!   utilsr"   r#   r$   auto.configuration_autor&   r  r(   configuration_musicgenr*   r+   integrations.flex_attentionr,   generation.streamersr-   
get_loggerr3   r(  r/   r   r   rN   ModulerP   r<   r   r   r   r   r  rM  r_  r  __all__r=   r>   r?   <module>r     s8        ! @ @   % ! 5   :  G & J J 0 * I  !J 4			H	% + +  +"%,, c [^ ((LBII (Ld  $(,%II%<<% 
% <<	%
 U\\*% e_% % %%<s)		 s)lq5 qh ?o ? ?0\&- \&~ g
+ g
 g
T 
z1? z
zz 
L
'> L

L
^" rr>   