Ë
    ÜÓ^j€” ã                   óÎ  — 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 ddl	m
Z
mZmZ ddlZddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ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# 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/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6 ddl7m8Z8m9Z9 ddl:m;Z;m<Z< ddl=m>Z> ddl?m@Z@ ddlAmBZBmCZC e
rddlDmEZE  e6jŒ                  eG«      ZHe5e G d„ de,«      «       «       ZIdej”                  deKdeKfd „ZL G d!„ d"ejš                  «      ZN	 	 d>d#ejš                  d$ej”                  d%ej”                  d&ej”                  d'ej”                  dz  d(eOdz  d)eOd*e2e4   fd+„ZP G d,„ d-ejš                  «      ZQ G d.„ d/e'«      ZRe5 G d0„ d1e0«      «       ZS G d2„ d3eS«      ZTe5 G d4„ d5eS«      «       ZU e5d6¬7«       G d8„ d9eSe«      «       ZV e5d:¬7«       G d;„ d<eSe«      «       ZWg d=¢ZXy)?zPyTorch Musicgen model.é    N)ÚCallable)Ú	dataclass)ÚTYPE_CHECKINGÚAnyÚOptional)ÚCrossEntropyLossé   )Úinitialization)ÚACT2FN)ÚCacheÚDynamicCacheÚEncoderDecoderCache)Ú%ClassifierFreeGuidanceLogitsProcessorÚGenerationConfigÚGenerationMixinÚGenerationModeÚLogitsProcessorListÚStoppingCriteriaList)Úcreate_bidirectional_maskÚcreate_causal_mask)ÚFlashAttentionKwargs)ÚGradientCheckpointingLayer)ÚBaseModelOutputÚ)BaseModelOutputWithPastAndCrossAttentionsÚ!CausalLMOutputWithCrossAttentionsÚModelOutputÚSeq2SeqLMOutput)ÚALL_ATTENTION_FUNCTIONSÚPreTrainedModel)ÚUnpack)ÚTransformersKwargsÚauto_docstringÚlogging)Úcan_return_tupleÚmerge_with_config_defaults)ÚOutputRecorderÚcapture_outputsé   )Ú
AutoConfig©Ú	AutoModelé   )ÚMusicgenConfigÚMusicgenDecoderConfig)ÚBaseStreamerc                   ó|   — e Zd ZU dZdZeej                     dz  ed<   dZ	ej                  dz  ed<   dZedz  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__r2   ÚtupleÚtorchÚFloatTensorÚ__annotations__r3   Ú
LongTensorr4   Úfloat© ó    úy/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/musicgen/modeling_musicgen.pyr1   r1   C   sF   … ñ	ð 8<€O�U˜5×,Ñ,Ñ-°Ñ4Ó;Ø.2€N�E×$Ñ$ tÑ+Ó2Ø#'€N�E˜D‘LÔ'r@   r1   Ú	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(   .NéÿÿÿÿzSMake sure to set the decoder_start_token_id attribute of the model's configuration.©.r   zIMake sure to set the pad_token_id attribute of the model's configuration.éœÿÿÿ)Ú	transposeÚ	new_zerosÚshapeÚcloneÚ
ValueErrorÚmasked_fill_)rB   rC   rD   Úshifted_input_idss       rA   Úshift_tokens_rightrP   V   s�   € ð
 ×#Ñ# A qÓ)€IØ!×+Ñ+¨I¯O©OÓ<ÐØ!*¨3°°°¨8Ñ!4×!:Ñ!:Ó!<Ð�c˜1™2�gÑØÐ%ÜÐ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                 ób   •— t         ‰| �  «        || _        || _        | j	                  ||«       y ©N)ÚsuperÚ__init__rT   rS   Úmake_weights)ÚselfrS   rT   Ú	__class__s      €rA   rX   z.MusicgenSinusoidalPositionalEmbedding.__init__m   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`   ra   Úregister_buffer)rZ   r\   rT   Úemb_weightss       rA   rY   z2MusicgenSinusoidalPositionalEmbedding.make_weightss   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   ©ÚdimrF   )ÚmathÚlogr:   ÚexpÚarangeÚint64r>   Ú	unsqueezeÚcatÚcosÚsinÚviewÚzerosre   Úget_default_dtype)r\   rT   Úhalf_dimÚembs       rA   rc   z3MusicgenSinusoidalPositionalEmbedding.get_embedding{   s  € ð ! AÑ%ˆÜ�h‰h�u‹o ¨A¡Ñ.ˆÜ�i‰iœŸ™ X´U·[±[ÔA×GÑGÓIÈSÈDÑPÓQˆÜ�l‰l˜>´·±Ô=×CÑCÓE×OÑOÐPQÓRÐUX×UbÑUbÐcdÓUeÑeˆÜ�i‰iœŸ™ 3›¬¯©°3«Ð8¸aÔ@×EÑEÀnÐVXÓYˆØ˜1Ñ Ò!ä—)‘)˜S¤%§+¡+¨n¸aÓ"@ÐAÀqÔIˆCØ�v‰v”e×-Ñ-Ó/Ó0Ð0r@   rB   Ú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   rF   )Úsizer:   ro   re   ra   r^   rY   rT   Úindex_selectru   Údetach)rZ   rB   rz   ÚbszÚ	codebooksÚseq_lenÚposition_idss          rA   Úforwardz-MusicgenSinusoidalPositionalEmbedding.forward‹   s’   € à"+§.¡.Ó"2ÑˆˆY˜äŸ™ WÓ-Ð0FÑF×JÑJÈ9×K[ÑK[Ó\ˆà�T—\‘\×&Ñ& qÓ)Ò)Ø×Ñ˜g t×'9Ñ'9Ô:Ø�|‰|×(Ñ(¨¨L×,=Ñ,=¸bÓ,AÓB×IÑIÓKÐKr@   )r   )r5   r6   r7   r8   ÚintrX   rY   Ústaticmethodrc   r:   Úno_gradÚTensorrƒ   Ú__classcell__©r[   s   @rA   rR   rR   j   sƒ   ø„ ÙNð8 cð 8¸#õ 8ðG¨3ð G¸só Gð ð1 cð 1¸#ò 1ó ð1ð €U‡]�]ƒ_ñL §¡ð LÀsò Ló ôLr@   rR   ÚmoduleÚqueryÚkeyÚvaluer3   ÚscalingÚdropoutÚkwargsc                 óœ  — |€|j                  d«      dz  }t        j                  ||j                  dd«      «      |z  }|�||z   }t        j
                  j                  |d¬«      }t        j
                  j                  ||| j                  ¬«      }t        j                  ||«      }	|	j                  dd«      j                  «       }	|	|fS )NrF   ç      à¿r(   r	   rj   ©ÚpÚtrainingr,   )
r|   r:   ÚmatmulrI   ÚnnÚ
functionalÚsoftmaxr�   r•   Ú
contiguous)
rŠ   r‹   rŒ   r�   r3   rŽ   r�   r�   Úattn_weightsÚattn_outputs
             rA   Úeager_attention_forwardr�   —   s»   € ð €Ø—*‘*˜R“. DÑ(ˆô —<‘<  s§}¡}°Q¸Ó':Ó;¸gÑE€LàÐ!Ø# nÑ4ˆä—=‘=×(Ñ(¨¸2Ð(Ó>€LÜ—=‘=×(Ñ(¨¸È6Ï?É?Ð(Ó[€Lä—,‘,˜|¨UÓ3€KØ×'Ñ'¨¨1Ó-×8Ñ8Ó:€Kà˜Ð$Ð$r@   c                   óX  ‡ — e Zd ZdZ	 	 	 	 	 	 ddedededz  dedz  dedz  dedz  d	edz  d
edz  fˆ fd„Z	 	 	 	 dde	j                  de	j                  dz  dedz  de	j                  dz  dedz  dee   dee	j                  e	j                  dz  ee	j                     dz  f   fd„Zˆ xZS )ÚMusicgenAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNÚ	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£   )rW   rX   r    r¡   r�   Úhead_dimr¥   rM   rŽ   r¢   r¤   r¦   r—   ÚLinearÚk_projÚv_projÚq_projÚout_proj)
rZ   r    r¡   r�   r¢   r£   r¤   r¥   r¦   r[   s
            €rA   rX   zMusicgenAttention.__init__¶   së   ø€ ô 	‰ÑÔØ"ˆŒØ"ˆŒØˆŒØ! YÑ.ˆŒØˆŒà�M‰M˜IÑ%¨$¯.©.Ò8ÜØMÈdÏnÉnÐM]Ø$ Y K¨rð3óð ð —}‘} dÑ*ˆŒØ$ˆŒØ"ˆŒØ"ˆŒä—i‘i 	¨9¸4Ô@ˆŒÜ—i‘i 	¨9¸4Ô@ˆŒÜ—i‘i 	¨9¸4Ô@ˆŒÜŸ	™	 )¨Y¸TÔBˆ�r@   Úhidden_statesÚkey_value_statesÚpast_key_valuesr3   Úoutput_attentionsr�   Úreturnc                 óÒ  — |du}|j                   dd }g |¢d‘| j                  ‘­}	| j                  |«      j                  |	«      j	                  d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Íg |j                   dd ¢d‘| j                  ‘­}| j                  |«      j                  |«      j	                  dd«      }| j!                  |«      j                  |«      j	                  dd«      }|�Kj#                  ||| j                  «      \  }}|r)t        |t        «      rd|j                  | j                  <   t%        j&                  | j(                  j*                  t,        «      } || |
|||f| j.                  sdn| j0                  | j2                  |dœ|¤Ž\  }} |j4                  g |¢d‘­Ž j7                  «       }| j9                  |«      }||fS )	z#Input shape: Batch x Time x ChannelNrF   r,   r(   FTç        )r�   rŽ   r²   )rK   r©   r­   ru   rI   Ú
isinstancer   Ú
is_updatedÚgetr¦   Úcross_attention_cacheÚself_attention_cacheÚlayersÚkeysÚvaluesr«   r¬   Úupdater   Úget_interfacer¥   Ú_attn_implementationr�   r•   r�   rŽ   Úreshaperš   r®   )rZ   r¯   r°   r±   r3   r²   r�   Úis_cross_attentionÚinput_shapeÚhidden_shapeÚquery_statesr·   Úcurr_past_key_valuesÚcurrent_statesÚ
key_statesÚvalue_statesÚkv_shapeÚattention_interfacerœ   r›   s                       rA   rƒ   zMusicgenAttention.forward×   sb  € ð .°TÐ9Ðð $×)Ñ)¨#¨2Ð.ˆà8˜Ð8 bÐ8¨$¯-©-Ñ8ˆð —{‘{ =Ó1×6Ñ6°|ÓD×NÑNÈqÐRSÓTˆàˆ
ØÐ&Ü˜/Ô+>Ô?Ø,×7Ñ7×;Ñ;¸D¿N¹NÓK�
Ù%à+:×+PÑ+PÑ(à+:×+OÑ+OÑ(à'6Ð$á-?Ñ)À]ˆÙ /Ð"=Á*à-×4Ñ4°T·^±^ÑD×IÑIˆJØ/×6Ñ6°t·~±~ÑF×MÑM‰LàF˜×-Ñ-¨c¨rÐ2ÐF°BÐF¸¿¹ÑFˆHØŸ™ ^Ó4×9Ñ9¸(ÓC×MÑMÈaÐQRÓSˆJØŸ;™; ~Ó6×;Ñ;¸HÓE×OÑOÐPQÐSTÓUˆLàÐ*à+?×+FÑ+FÀzÐS_Ðae×aoÑaoÓ+pÑ(�
˜Lá%¬*°_ÔFYÔ*ZØAE�O×.Ñ.¨t¯~©~Ñ>ä(?×(MÑ(MØ�K‰K×,Ñ,Ô.Eó)
Ðñ %8ØØØØØð
%
ð  $Ÿ}š}‘C°$·,±,Ø—L‘LØ/ñ
%
ð ñ
%
Ñ!ˆ�\ð *�k×)Ñ)Ð;¨;Ð;¸Ò;×FÑFÓHˆØ—m‘m KÓ0ˆà˜LÐ(Ð(r@   )rµ   FTFNN)NNNF)r5   r6   r7   r8   r„   r>   Úboolr-   rX   r:   r‡   r   r    r   r9   rƒ   rˆ   r‰   s   @rA   rŸ   rŸ   ³   s:  ø„ ÙGð !$Ø"'Ø Ø!&Ø(,Ø $ñCàðCð ðCð ˜‘ð	Cð
 ˜4‘KðCð �T‰kðCð ˜$‘;ðCð  Ñ%ðCð ˜‘:õCðH 15Ø(,Ø.2Ø).ñI)à—|‘|ðI)ð  Ÿ,™,¨Ñ-ðI)ð  ™ð	I)ð
 Ÿ™ tÑ+ðI)ð   $™;ðI)ð Ð-Ñ.ðI)ð 
ˆu�|‰|˜UŸ\™\¨DÑ0°%¸¿¹Ñ2EÈÑ2LÐLÑ	M÷I)r@   rŸ   c                   óâ   ‡ — e Zd Zddefˆ fd„Z	 	 	 	 	 ddej                  dej                  dz  dej                  dz  dej                  dz  dedz  d	edz  d
e	e
   dej                  fd„Zˆ xZS )ÚMusicgenDecoderLayerNr¥   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¨   )rW   rX   Ú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)rZ   r¥   r¦   r[   s      €rA   rX   zMusicgenDecoderLayer.__init__$  s(  ø€ Ü‰ÑÔØ×+Ñ+ˆŒä*Ø—n‘nØ×0Ñ0Ø×,Ñ,ØØØØØô	
ˆŒð —~‘~ˆŒÜ# F×$>Ñ$>Ñ?ˆÔØ"(×";Ñ";ˆÔä$&§L¡L°·±Ó$@ˆÔ!Ü-Ø�N‰NØ×&Ñ&Ø×,Ñ,ØØØØô
ˆÔô (*§|¡|°D·N±NÓ'CˆÔ$Ü—9‘9˜TŸ^™^¨V¯^©^À%ÔHˆŒÜ—9‘9˜VŸ^™^¨T¯^©^À%ÔHˆŒÜ "§¡¨T¯^©^Ó <ˆÕr@   r¯   r3   Úencoder_hidden_statesÚencoder_attention_maskr±   Ú	use_cacher�   r³   c                 ó  — |}| j                  |«      } | j                  |f||dœ|¤Ž\  }}	t        j                  j	                  || j                  | j
                  ¬«      }||z   }|�h|}| j                  |«      } | j                  |f|||dœ|¤Ž\  }}	t        j                  j	                  || j                  | j
                  ¬«      }||z   }|}| j                  |«      }| j                  | j                  |«      «      }t        j                  j	                  || j                  | j
                  ¬«      }| j                  |«      }t        j                  j	                  || j                  | j
                  ¬«      }||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.
            past_key_values (`Cache`): cached past key and value projection states
        )r±   r3   r“   )r°   r3   r±   )rØ   rÓ   r—   r˜   r�   r•   rÚ   rÙ   rÞ   rÕ   rÜ   rÖ   rÝ   )
rZ   r¯   r3   rß   rà   r±   rá   r�   ÚresidualÚ_s
             rA   rƒ   zMusicgenDecoderLayer.forwardE  s—  € ð* !ˆØ×1Ñ1°-Ó@ˆð *˜4Ÿ>™>Øð
à+Ø)ñ
ð ñ	
Ñˆ�qô Ÿ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-ÓdˆØ  =Ñ0ˆð !Ð,Ø$ˆHØ ×8Ñ8¸ÓGˆMà0˜t×0Ñ0Øð à!6Ø5Ø /ñ	 ð
 ñ ÑˆM˜1ô ŸM™M×1Ñ1°-À4Ç<Á<ÐZ^×ZgÑZgÐ1ÓhˆMØ$ }Ñ4ˆMð !ˆØ×-Ñ-¨mÓ<ˆØ×*Ñ*¨4¯8©8°MÓ+BÓCˆÜŸ™×-Ñ-¨m¸t×?VÑ?VÐae×anÑanÐ-ÓoˆØŸ™ Ó/ˆÜŸ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-ÓdˆØ  =Ñ0ˆàÐr@   rV   )NNNNT)r5   r6   r7   r.   rX   r:   r‡   r   rÌ   r    r!   rƒ   rˆ   r‰   s   @rA   rÎ   rÎ   #  s¦   ø„ ñ=Ð4õ =ðH /3Ø59Ø6:Ø(,Ø!%ñ:à—|‘|ð:ð Ÿ™ tÑ+ð:ð  %Ÿ|™|¨dÑ2ð	:ð
 !&§¡¨tÑ 3ð:ð  ™ð:ð ˜$‘;ð:ð Ð+Ñ,ð:ð 
�‰÷:r@   rÎ   c                   ón   ‡ — e Zd ZU eed<   dZdZddgZdZdZ	dZ
 ej                  «       ˆ fd„«       Zˆ xZS )ÚMusicgenPreTrainedModelr¥   ÚmodelTrÎ   rŸ   c                 óÒ   •— t         ‰| �  |«       t        |t        «      rG|j	                  |j
                  |j                  «      }t        j                  |j                  |«       y y rV   )
rW   Ú_init_weightsr¶   rR   rc   rS   rT   ÚinitÚcopy_r^   )rZ   rŠ   rg   r[   s      €rA   ré   z%MusicgenPreTrainedModel._init_weightsŒ  sQ   ø€ ä‰Ñ˜fÔ%Ü�fÔCÔDØ ×.Ñ.¨v×/CÑ/CÀV×EYÑEYÓZˆKÜ�J‰J�v—~‘~ {Õ3ð Er@   )r5   r6   r7   r.   r<   Úbase_model_prefixÚsupports_gradient_checkpointingÚ_no_split_modulesÚ_supports_flash_attnÚ_supports_sdpaÚ_supports_flex_attnr:   r†   ré   rˆ   r‰   s   @rA   ræ   ræ   ‚  sL   ø… à!Ó!ØÐØ&*Ð#Ø/Ð1DÐEÐØÐØ€NØÐà€U‡]�]ƒ_ó4ó ô4r@   ræ   c                   óL  ‡ — e Zd ZdZe eedd¬«       eedd¬«      dœZdefˆ fd„Z	e
ee	 	 	 	 	 	 	 dd
ej                  d	z  dej                  d	z  dej                   d	z  dej                  d	z  ded	z  dej                   d	z  ded	z  dee   deez  fd„«       «       «       Zˆ xZS )ÚMusicgenDecoderzw
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MusicgenDecoderLayer`]
    r,   rÓ   )ÚindexÚ
layer_namerÙ   )r¯   Ú
attentionsÚcross_attentionsr¥   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 )Nç      ð?r,   )r¦   F)rW   rX   r�   Ú	layerdropÚmax_position_embeddingsÚmax_target_positionsrÐ   Úd_modelÚnum_codebooksÚscale_embeddingrl   ÚsqrtÚembed_scaleÚ
vocab_sizer—   Ú
ModuleListÚrangeÚ	EmbeddingÚembed_tokensrR   Úembed_positionsÚnum_hidden_layersrÎ   r»   r×   Ú
layer_normrÀ   Úattn_implementationÚgradient_checkpointingÚ	post_init)rZ   r¥   r    rä   Úir[   s        €rA   rX   zMusicgenDecoder.__init__Ÿ  sW  ø€ Ü‰Ñ˜Ô Ø—~‘~ˆŒØ×)Ñ)ˆŒØ$*×$BÑ$BˆÔ!Ø×)Ñ)ˆŒØ#×1Ñ1ˆÔØ<B×<RÒ<Rœ4Ÿ9™9 V×%7Ñ%7Ô8ÐX[ˆÔà×%Ñ%¨Ñ)ˆ	ÜŸM™MÜBGÈ×H\ÑH\ÓB]Ö^¸QŒR�\‰\˜) V×%7Ñ%7Õ8Ò^ó
ˆÔô  EØ×*Ñ*Ø×Ñó 
ˆÔô
 —m‘mÜ@EÀf×F^ÑF^Ó@_Ö`¸1Ô! &°AÖ6Ò`ó
ˆŒô Ÿ,™, v×'9Ñ'9Ó:ˆŒØ#)×#>Ñ#>ˆÔ à&+ˆÔ#à�‰Õùò! _ùò as   Ã'F8ÅF=NrB   r3   rß   rà   r±   Úinputs_embedsrá   r�   r³   c                 óÖ  ‡ ‡— |�|�t        d«      ‚|�;|j                  d‰ j                  |j                  d   «      Š‰j                  \  }	}
}n|�|dd…dd…dd…f   Šnt        d«      ‚|r6|€4t	        t        ‰ j                  ¬«      t        ‰ j                  ¬«      «      }|�|j                  «       nd}|€t        ˆˆ fd„t        
«      D «       «      }t        ‰ j                  |||¬«      }t        ‰ j                  |||¬	«      }‰ j                  ‰|«      }||j                  |j                  «      z   }t        j                   j#                  |‰ j"                  ‰ j$                  ¬
«      }t'        ‰ j(                  «      D ]F  \  }}t+        j,                  dd«      }‰ j$                  r|‰ j.                  k  rŒ8 ||||f|||dœ|¤Ž}ŒH ‰ j1                  |«      }t3        ||¬«      S )á$  
        input_ids (`torch.LongTensor` of shape `(batch_size * num_codebooks, sequence_length)`):
            Indices of input sequence tokens in the vocabulary, corresponding to the sequence of audio codes.

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

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

            <Tip warning={true}>

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

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

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

            [What are attention masks?](../glossary#attention-mask)
        NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timerF   zEYou have to specify either decoder_input_ids or decoder_inputs_embeds)r¥   r   c              3   óV   •K  — | ]   } ‰j                   |   ‰d d …|f   «      –— Œ" y ­wrV   )r  )Ú.0ÚcodebookÚinputrZ   s     €€rA   ú	<genexpr>z*MusicgenDecoder.forward.<locals>.<genexpr>ú  s.   øè ø€ ÒuÐT\Ð ; × 1Ñ 1°(Ñ ;¸EÂ!ÀXÀ+Ñ<N× OÑuùs   ƒ&))r¥   r  r3   r±   )r¥   r  r3   rß   r“   r,   )rà   r±   rá   )Úlast_hidden_stater±   )rM   rÁ   rþ   rK   r   r   r¥   Úget_seq_lengthÚsumr  r   r   r  re   ra   r—   r˜   r�   r•   Ú	enumerater»   ÚrandomÚuniformrú   r	  r   )rZ   rB   r3   rß   rà   r±   r  rá   r�   r   rþ   r�   rz   Ú	positionsr¯   ÚidxÚdecoder_layerÚdropout_probabilityr  s   `                 @rA   rƒ   zMusicgenDecoder.forward¼  s÷  ù€ ðZ Ð  ]Ð%>ÜÐsÓtÐtØÐ"à×%Ñ% b¨$×*<Ñ*<¸i¿o¹oÈbÑ>QÓRˆEØ*/¯+©+Ñ'ˆC�¡ØÐ&Ø!¢!¢Q¨© )Ñ,‰EäÐdÓeÐeá˜Ð0Ü1´,ÀdÇkÁkÔ2RÔT`Ðhl×hsÑhsÔTtÓuˆOàETÐE` ×!?Ñ!?Ô!AÐfgÐàÐ ÜÔuÔ`eÐfsÓ`tÔuÓuˆMä+Ø—;‘;Ø'Ø)Ø+ô	
ˆô ";Ø—;‘;Ø'Ø1Ø"7ô	"
Ðð ×(Ñ(¨Ð0FÓGˆ	Ø%¨	¯©°]×5IÑ5IÓ(JÑJˆÜŸ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-Ódˆä"+¨D¯K©KÓ"8ò 	ÑˆC�ä"(§.¡.°°AÓ"6ÐØ�}Š}Ð"5¸¿¹Ò"FØá)ØØØ%ðð (>Ø /Ø#ñð ñ‰Mð	ð  Ÿ™¨Ó6ˆä8Ø+Ø+ô
ð 	
r@   ©NNNNNNN)r5   r6   r7   r8   rÎ   r&   rŸ   Ú_can_record_outputsr.   rX   r%   r'   r"   r:   r=   r‡   r;   r   rÌ   r    r!   r9   r   rƒ   rˆ   r‰   s   @rA   ró   ró   ”  s$  ø„ ñð
 .Ù$Ð%6¸aÈKÔXÙ*Ð+<ÀAÐR`ÔañÐðÐ4õ ð:  ØØð .2Ø.2Ø:>Ø:>Ø(,Ø26Ø!%ñd
à×#Ñ# dÑ*ðd
ð Ÿ™ tÑ+ðd
ð  %×0Ñ0°4Ñ7ð	d
ð
 !&× 0Ñ 0°4Ñ 7ðd
ð  ™ðd
ð ×(Ñ(¨4Ñ/ðd
ð ˜$‘;ðd
ð Ð+Ñ,ðd
ð 
Ð:Ñ	:òd
ó ó ó  ôd
r@   ró   c                   ó$  ‡ — e Zd Zdefˆ fd„Zd„ Zd„ Zeee		 	 	 	 	 	 	 dde
j                  dz  de
j                  dz  de
j                  dz  d	e
j                  dz  d
edz  de
j                  dz  dedz  dee   deez  fd„«       «       «       Zˆ xZS )ÚMusicgenModelr¥   c                 ód   •— t         ‰| �  |«       t        |«      | _        | j	                  «        y rV   )rW   rX   ró   Údecoderr  )rZ   r¥   r[   s     €rA   rX   zMusicgenModel.__init__(  s&   ø€ Ü‰Ñ˜Ô Ü& vÓ.ˆŒà�‰Õr@   c                 ó.   — | j                   j                  S rV   ©r%  r  ©rZ   s    rA   Úget_input_embeddingsz"MusicgenModel.get_input_embeddings.  s   € Ø�|‰|×(Ñ(Ð(r@   c                 ó&   — || j                   _        y rV   r'  ©rZ   r�   s     rA   Úset_input_embeddingsz"MusicgenModel.set_input_embeddings1  s   € Ø$)ˆ�‰Õ!r@   NrB   r3   rß   rà   r±   r  rá   r�   r³   c                 ó:   —  | j                   d|||||||dœ|¤Ž}	|	S )r  )rB   r3   rà   rß   r±   r  rá   r?   )r%  )
rZ   rB   r3   rß   rà   r±   r  rá   r�   Údecoder_outputss
             rA   rƒ   zMusicgenModel.forward4  sF   € ðZ FRÀTÇ\Á\ð 	F
ØØ)Ø#9Ø"7Ø+Ø'Øñ	F
ð ñ	F
ˆð Ðr@   r   )r5   r6   r7   r.   rX   r)  r,  r%   r'   r"   r:   r=   r‡   r;   r   rÌ   r    r!   r9   r   rƒ   rˆ   r‰   s   @rA   r#  r#  &  sö   ø„ ðÐ4õ ò)ò*ð  ØØð .2Ø.2Ø:>Ø:>Ø(,Ø26Ø!%ñ5à×#Ñ# dÑ*ð5ð Ÿ™ tÑ+ð5ð  %×0Ñ0°4Ñ7ð	5ð
 !&× 0Ñ 0°4Ñ 7ð5ð  ™ð5ð ×(Ñ(¨4Ñ/ð5ð ˜$‘;ð5ð Ð+Ñ,ð5ð 
Ð:Ñ	:ò5ó ó ó  ô5r@   r#  zK
    The MusicGen decoder model with a language modelling head on top.
    )Úcustom_introc                   ó8  ‡ — e Zd ZdZdefˆ fd„Zd„ Zd„ Zd„ Zd„ Z	e
ee	 	 	 	 	 	 	 	 d!d	ej                  dz  d
ej                  dz  dej                   dz  dej                  dz  dedz  dej                   dz  dej                  dz  dedz  dee   deez  fd„«       «       «       Z	 	 	 	 	 	 	 d"d„Zd#d	ej                  dededz  fd„Zed„ «       Z ej:                  «       	 	 	 	 	 	 d$dej                  dz  dedz  dedz  de dz  dedz  de!d   fd „«       Z"ˆ xZ#S )%ÚMusicgenForCausalLM©Úaudior¥   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¨   )rW   rX   r#  rç   rþ   r—   r  r  rª   rÐ   r  Úlm_headsr  )rZ   r¥   rä   r[   s      €rA   rX   zMusicgenForCausalLM.__init__w  s   ø€ Ü‰Ñ˜Ô ä" 6Ó*ˆŒ
à#×1Ñ1ˆÔÜŸ™ÜSXÐY_×YmÑYmÓSnÖoÈaŒR�Y‰Y�v×)Ñ)¨6×+<Ñ+<À5ÖIÒoó
ˆŒð
 	�‰Õùò	 ps   Á3B(c                 óB   — | j                   j                  j                  S rV   ©rç   r%  r  r(  s    rA   r)  z(MusicgenForCausalLM.get_input_embeddings„  s   € Ø�z‰z×!Ñ!×.Ñ.Ð.r@   c                 ó:   — || j                   j                  _        y rV   r7  r+  s     rA   r,  z(MusicgenForCausalLM.set_input_embeddings‡  s   € Ø*/ˆ�
‰
×ÑÕ'r@   c                 ó   — | j                   S rV   ©r5  r(  s    rA   Úget_output_embeddingsz)MusicgenForCausalLM.get_output_embeddingsŠ  s   € Ø�}‰}Ðr@   c                 ó   — || _         y rV   r:  ©rZ   Únew_embeddingss     rA   Úset_output_embeddingsz)MusicgenForCausalLM.set_output_embeddings�  s	   € Ø&ˆ�r@   NrB   r3   rß   rà   r±   r  Úlabelsrá   r�   r³   c	           
      ó  — |�9|€7|€5t        || j                  j                  | j                  j                  «      } | j                  |f||||||dœ|	¤Ž}
|
j
                  }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 ¢­Ž }t'        |||
j(                  |
j*                  |
j,                  |
j.                  ¬
«      S c c}w )aÝ  
        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)
        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)r3   rß   rà   r±   r  rá   r,   rj   ©ra   rH   rF   .r(   )ÚlossÚlogitsr±   r¯   rö   r÷   )rP   r¥   rC   Úbos_token_idrç   r  r:   Ústackr5  rK   r   rv   ra   Úmasked_fillr  rþ   rš   ru   rÁ   r   r±   r¯   rö   r÷   )rZ   rB   r3   rß   rà   r±   r  r@  rá   r�   Úoutputsr¯   ÚheadÚ	lm_logitsrC  rD  Úloss_fctr  Úcodebook_logitsÚcodebook_labelss                       rA   rƒ   zMusicgenForCausalLM.forward�  s  € ðf Ð YÐ%6¸=Ð;PÜ*¨6°4·;±;×3KÑ3KÈTÏ[É[×MeÑMeÓfˆIà=G¸T¿Z¹ZØð	>
à)Ø"7Ø#9Ø+Ø'Øñ	>
ð ñ	>
ˆð  ×1Ñ1ˆä—K‘KÀÇÁÖ O¸¡ mÕ!4Ò OÐUVÔWˆ	àˆØÑð šq¢! f§l¡l°1¡oÐ%5Ñ%7Ð7Ñ8ˆFä'Ó)ˆHÜ—;‘;˜r¨$¯+©+Ô6ˆDð ×'Ñ'¨°$·+±+×2JÑ2JÑ(JÈDÓQˆFô " $§+¡+×";Ñ";Ó<ò C�Ø"(ª¨H¨Ñ"5×"@Ñ"@Ó"B×"GÑ"GÈÈFÏLÉLÐY[ÑL\Ó"]�Ø"(¨¨h¨Ñ"7×"BÑ"BÓ"D×"IÑ"IÈ"Ó"M�Ø™ °/ÓBÑB‘ðCð
 ˜$Ÿ+™+×3Ñ3Ñ3ˆDð &�I×%Ñ% bÐ?¨9¯?©?¸1¸2Ð+>Ò?ˆ	ä0ØØØ#×3Ñ3Ø!×/Ñ/Ø×)Ñ)Ø$×5Ñ5ô
ð 	
ùò7 !Ps   Á?Hc	                 ó*  — |€?| j                  || j                  j                  | j                  j                  ¬«      \  }}| j	                  ||«      }|�)|dkD  r$|j                  d«      }|�|j                  d«      }|�|d d …dd …f   }||||||dœS )N©rC   Ú
max_lengthr,   ©r(   r,   rF   )rB   r3   rß   rà   r±   rá   )Úbuild_delay_pattern_maskÚgeneration_configrC   rP  Úapply_delay_pattern_maskÚrepeat)
rZ   rB   r3   rß   rà   r±   rá   Údelay_pattern_maskr4   r�   s
             rA   Úprepare_inputs_for_generationz1MusicgenForCausalLM.prepare_inputs_for_generation÷  sÅ   € ð Ð%Ø,0×,IÑ,IØØ!×3Ñ3×@Ñ@Ø×1Ñ1×<Ñ<ð -Jó -Ñ)ˆIÐ)ð ×1Ñ1°)Ð=OÓPˆ	àÐ%¨.¸1Ò*<ð "×(Ñ(¨Ó0ˆIØÐ)Ø!/×!6Ñ!6°vÓ!>�àÐ&Ø!¢! R¡S &Ñ)ˆIð #Ø,Ø%:Ø&<Ø.Ø"ñ
ð 	
r@   rC   rP  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.
        rF   Nr_   r(   r,   ri   )Údiagonalr   rj   .)rÁ   rþ   rK   rS  rP  r:   ÚonesÚlongra   r¥   Úaudio_channelsr  ÚtriurÌ   ÚtrilÚrepeat_interleavere   ÚnonzeroÚlenÚmin)rZ   rB   rC   rP  r   rþ   r�   Úinput_ids_shiftedÚchannel_codebooksr  Údelay_patternÚmaskÚfirst_codebook_idsÚ	start_idsÚfirst_start_idÚpattern_masks                   rA   rR  z,MusicgenForCausalLM.build_delay_pattern_mask!  sû  € ð( ×%Ñ% b¨$×*<Ñ*<¸i¿o¹oÈbÑ>QÓRˆ	Ø&/§o¡oÑ#ˆˆ]˜Gà#-Ð#9‘Z¸t×?UÑ?U×?`Ñ?`ˆ
ä�J‰J˜˜]¨JÐ7¼u¿z¹zÐR[×RbÑRbÔcÐfhÑhð 	ð 37·+±+×2LÑ2LÐPQÒ2Q˜M¨QÒ.ÐWdÐà˜Ð-Ñ-°Ñ1Ò1Ø×$Ñ$ S¨=Ñ%8¸"Ó=Ð?P×?XÑ?XÐY\Ð_lÑYlÐnpÓ?qÐqÐqô Ð/Ó0ò 	wˆHØ�{‰{×)Ñ)¨QÒ.àPYÒZ[Ð]eÐZeÑPfÐ!¢! X¨x¸'ÀHÑ:LÐ/LÐ"LÒMð U^Ò^_ÐabÐemÑamÐ^mÑTnÐ!¢! Q¨¡\°8¸gÈÑ>PÐ3PÐ"PÑQØXaÒbcÐefÐiqÑeqÐtuÑeuÐbuÑXvÐ!¢! Q¨¡\°AÑ%5°xÀ'ÈHÑBTÐ7TÐ"TÒUð	wô Ÿ
™
Ü�J‰JÐ)¨:Ð6¼e¿j¹jÔIÐT^ÐarÑTrÐuvÑTvô
ˆð &¬¯
©
´5·:±:Ð?PÐR\Ð>]Ôej×eoÑeoÔ3pÓ(qÑqˆà�;‰;×%Ñ%¨Ò*à)×;Ñ;¸AÀ1Ð;ÓEˆMà× Ñ  ×!1Ñ!1Ó2Ð2ˆØÐ,Ñ,°¨u°|Ñ/CÑCˆ	ð '¢q¨!ªQ wÑ/ÐØ'¨2Ñ-×6Ñ6Ó8º¸A¸Ñ>ˆ	Üˆy‹>˜AÒÜ  ›^‰Nð %ˆNð !×(Ñ(¨¨}Ñ)<¸bÓAˆØ˜c ? N ?Ð2Ñ3×;Ñ;¸CÀ-Ñ<OÐQSÓTˆ	Ø˜,Ð&Ð&r@   c                 ój   — | j                   d   }|dd|…f   }t        j                  |dk(  | |«      } | S )z®Apply 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.rF   .N)rK   r:   Úwhere)rB   Údecoder_pad_token_maskr�   s      rA   rT  z,MusicgenForCausalLM.apply_delay_pattern_maskj  sD   € ð —/‘/ "Ñ%ˆØ!7¸¸X¸g¸X¸Ñ!FÐÜ—K‘KÐ 6¸"Ñ <¸iÐI_Ó`ˆ	ØÐr@   ÚinputsrS  Ú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||¬«       | 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`]
        Nr2   r3   r   rB  rá   r4   rF   rP  Ú
min_length©rS  Úhas_default_max_lengthÚhas_default_min_lengthÚmodel_input_nameÚinputs_tensorÚinput_ids_lengthr,   r  )Úgeneration_modeÚ
batch_sizeÚmax_cache_lengthrO  rV  ©rS  Úinput_ids_seq_lengthÚencoder_input_idsÚprefix_allowed_tokens_fnro  ra   ©rS  rp  )rB   Úexpand_size)ro  rp  rS  rq  rr  úŒGot incompatible mode for generation, should be one of greedy or sampling. Ensure that beam search is de-activated by setting `num_beams=1`.r?   ).rS  ÚcopyÚdeepcopyr¾   ÚvalidateÚ_validate_model_kwargsr   r   r¸   Ú_prepare_model_inputsrE  rK   rþ   Ú_prepare_special_tokensra   rá   r4   Ú&_prepare_attention_mask_for_generationrP  ru  Ú_prepare_generated_lengthÚ_validate_generated_lengthr¥   Úis_encoder_decoderÚ_prepare_cache_for_generationrR  Ú_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Ú_samplerM   Úreturn_dict_in_generateÚ	sequencesrT  Ú_pad_token_tensorrÁ   )rZ   rn  rS  ro  rp  rq  rr  r�   Úmodel_kwargsÚrequires_attention_maskÚkwargs_has_attention_maskrB   ry  r}  r{  rw  rx  r~  rV  r|  rH  Ú
output_idss                         rA   ÚgeneratezMusicgenForCausalLM.generates  sˆ  € ðV Ð$Ø $× 6Ñ 6Ðä ŸM™MÐ*;Ó<ÐØ/Ð(×/Ñ/Ñ9°&Ñ9ˆØ×"Ñ"Ô$Ø×#Ñ# L×$5Ñ$5Ó$7Ô8ð 0@Ð/KÑ+ÔQdÓQfÐØ1BÐ1NÑ-ÔThÓTjÐà"3¸<Ð"GÐØ$0×$4Ñ$4Ð5EÀtÓ$LÐTXÐ$XÐ!ð 59×4NÑ4NØÐ%×2Ñ2°Ló5
Ñ1ˆ	Ð# \ð —_‘_ QÑ'¨4×+=Ñ+=Ñ=ˆ
Ø×$Ñ$Ð%6Ð8QÐZc×ZjÑZjÐ$Ôkð %6×$?Ñ$?ˆ�[Ñ!Ø):×)IÑ)IˆÐ%Ñ&à×ÑÐ,¨dÓ3Ð;Ñ@WØ-1×-XÑ-XØÐ,¨ló.ˆLÐ)Ñ*ð
 %Ÿ?™?¨2Ñ.ÐØ!'§¡¨LÓ!9¸TÐ!AÒ!nÐFW×FbÑFbÐjnÐFnÐØ!'§¡¨LÓ!9¸TÐ!AÒ!nÐFW×FbÑFbÐjnÐFnÐØ ×:Ñ:Ø/Ø#9Ø#9Ø-Ø#Ø-ð ;ó 
Ðð 	×'Ñ'Ð(9Ð;KÐMcÔdð -×7Ñ7¸!Ñ;Ðà×"Ñ" 1Ñ%Ð)9Ò9Ø  OÒ3Ø—K‘K×2Ò2àÐ 0× 6Ñ 6°qÑ 9Ñ9ÐØ×*Ñ*ØØØ Ø!Ø-ð 	+ô 	
ð )-×(EÑ(EØØ*×FÑFØ(×3Ñ3ð )Fó )
Ñ%ˆ	Ð%ð ÐØ�L‰L˜Ÿ™›Ô)ð .@ˆÐ)Ñ*ð ,×?Ñ?ÓAˆð ×+Ñ+Ð7Ð<M×<\Ñ<\Ð_`Ò<`Ø×#Ñ#Ô$IÐJ[×JjÑJjÓ$kÔlØ/3ÐÔ,ð  ×5Ñ5Ø/Ø!1Ø'Ø%)Ø-Ø×#Ñ#ð 6ó 
Ðð !×7Ñ7Ø/ÐCTð 8ó 
Ðð œ~×4Ñ4´n×6RÑ6RÐSÑSà&H d×&HÑ&Hð 'Ø#Ø-×BÑBñ'ð ñ'Ñ#ˆI�|ð #�d—l‘lØðà!1Ø"3Ø"3Ø'Ø!ñð ñ‰Gô ðTóð ð
 ×4Ò4Ø ×*Ñ*‰Jà ˆJð ×2Ñ2°:¸|ÐL`Ñ?aÓbˆ
ð   
Ð.?×.QÑ.QÑ QÑR×ZÑZØ˜×*Ñ*¨Bó
ˆ
ð ×4Ò4Ø *ˆGÔØˆNàÐr@   ©NNNNNNNN)NNNNTNNrV   ©NNNNNN)$r5   r6   r7   Úoutput_modalitiesr.   rX   r)  r,  r;  r?  r%   r'   r"   r:   r=   r‡   r;   r   rÌ   r    r!   r9   r   rƒ   rW  r„   rR  r…   rT  r†   r   r   r   r   r¤  rˆ   r‰   s   @rA   r1  r1  o  s  ø„ ð #ÐðÐ4õ ò/ò0òò'ð  ØØð .2Ø.2Ø:>Ø:>Ø(,Ø26Ø*.Ø!%ñb
à×#Ñ# dÑ*ðb
ð Ÿ™ tÑ+ðb
ð  %×0Ñ0°4Ñ7ð	b
ð
 !&× 0Ñ 0°4Ñ 7ðb
ð  ™ðb
ð ×(Ñ(¨4Ñ/ðb
ð × Ñ  4Ñ'ðb
ð ˜$‘;ðb
ð Ð+Ñ,ðb
ð 
Ð2Ñ	2òb
ó ó ó  ðb
ðN Ø"Ø#ØØØØó(
ñTG'°%×2BÑ2Bð G'ÐRUð G'ÐcfÐimÑcmó G'ðR ñó ðð €U‡]�]ƒ_ð '+Ø59Ø7;Ø9=Ø#'Ø-1ñZà—‘˜tÑ#ðZð ,¨dÑ2ðZð .°Ñ4ð	Zð
 0°$Ñ6ðZð ˜D‘[ðZð ˜>Ñ*òZó ôZr@   r1  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Z	 	 	 	 d;dedz  de	dz  de	dz  d	e
dz  fˆ fd
„Zd„ Zd„ Zd„ Ze	 	 	 d<dedz  dedz  dedz  de	fd„«       Zee	 	 	 	 	 	 	 	 	 	 	 	 d=dej*                  dz  dej,                  dz  dej.                  dz  dej,                  dz  dej*                  dz  dej,                  dz  deej.                     dz  dedz  dej.                  dz  dej.                  dz  dej*                  dz  dedz  dee   deez  fd„«       «       Z	 	 	 	 	 	 	 	 d>d edz  fd!„Z 	 	 	 d<d"ed#ed$e!eejD                  f   d%edz  d&edz  d'ejF                  dz  deej*                  e!eejD                  f   f   fd(„Z$d)ejD                  d#edz  d*e%de!ee&f   fd+„Z'	 d?d#edz  fd,„Z(dejD                  fd-„Z)d.„ Z*d/„ Z+d0„ Z,d1ejD                  dz  d&edz  d$e!eejD                  f   dej*                  fd2„Z-	 d@d%ee.e   z  dz  d&edz  defd3„Z/ ej`                  «       	 	 	 	 	 	 dAd1ejD                  dz  d*e%dz  d4e1dz  d5e2dz  d6edz  d7e3d8   fd9„«       Z4dBd:„Z5ˆ xZ6S )CÚ MusicgenForConditionalGenerationr¥   r2  Úencoder_decoderrB   TNÚtext_encoderÚaudio_encoderr%  c                 ó"  •— |€|�|�|€t        d«      ‚|€-t        |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                  €Wt/        j0                  | j                  j                  j                  | j
                  j                  j                  «      | _        | j                  j5                  «       �t        d| j                  › d�«      ‚t7        t9        j:                  | j
                  j<                  «      j>                  jA                  «       «      }d|vrt        d«      ‚| jC                  «        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.©r«  r¬  r%  zConfig: z has to be of type z“If `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ß   z¸The 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)"rM   r-   r¥   r¶   Úconfig_classr%  Úcross_attention_hidden_sizer«  rÐ   rW   rX   Úauto.modeling_autor¯  Úfrom_configr+   r¬  r1  Ú_from_configÚto_dictÚloggerÚwarningr[   rÀ   r—   rª   Úenc_to_dec_projr;  ÚsetÚinspectÚ	signaturerƒ   Ú
parametersr¼   r  )	rZ   r¥   r«  r¬  r%  r¯  r+   Údecoder_signaturer[   s	           €rA   rX   z)MusicgenForConditionalGeneration.__init__]  sw  ø€ ð ˆ>˜|Ð3°}Ð7LÐPWÐP_ÜØ~óð ð ˆ>Ü#Ø)×0Ñ0À×@TÑ@TÐ^e×^lÑ^lô‰Fô ˜f d×&7Ñ&7Ô8Ü  8¨F¨8Ð3FÀt×GXÑGXÐFYÐ!ZÓ[Ð[à�>‰>×5Ñ5ÐAØ�~‰~×9Ñ9¸V×=PÑ=P×=\Ñ=\Ò\Ü ðAØAGÇÁ×AkÑAkÐ@lð mIØIO×I\ÑI\×IhÑIhÐHið j:ð:óð ô 	‰Ñ˜Ô àÐÝEà3×?Ñ?À×@SÑ@SÓTˆLàÐ Ý6à1˜I×1Ñ1°&×2FÑ2FÓGˆMàˆ?Ü)×6Ñ6°v·~±~ÓFˆGà(ˆÔØ*ˆÔØˆŒà×Ñ×#Ñ#×+Ñ+Ó-°·±×1IÑ1I×1QÑ1QÓ1SÒSÜ�N‰NØ.¨t×/@Ñ/@×/JÑ/JÐ.Kð LØ—K‘K×,Ñ,Ð-ð/ôð ×Ñ×$Ñ$×,Ñ,Ó.°$·+±+×2KÑ2K×2SÑ2SÓ2UÒUÜ�N‰NØ/°×0BÑ0B×0LÑ0LÐ/Mð NØ—K‘K×-Ñ-Ð.ð0ôð �<‰<×Ñ×&Ñ&Ó(¨D¯K©K×,?Ñ,?×,GÑ,GÓ,IÒIÜ�N‰NØ)¨$¯,©,×*@Ñ*@Ð)Að BØ—K‘K×'Ñ'Ð(ð*ôð 9=×8IÑ8I×8PÑ8P×8eÑ8eˆ�‰× Ñ Ô5Ø9=×9KÑ9K×9RÑ9R×9gÑ9gˆ�‰×!Ñ!Ô6Ø37·<±<×3FÑ3F×3[Ñ3[ˆ�‰×ÑÔ0Ø#'§;¡;×#;Ñ#;ˆ×ÑÔ Ø$(§K¡K×$=Ñ$=ˆ×ÑÔ!Ø"Ÿk™k×1Ñ1ˆ�‰Ôð ×Ñ×$Ñ$×0Ñ0°D·L±L×4GÑ4G×4SÑ4SÒSØ—‘×#Ñ#×?Ñ?ÐGä#%§9¡9¨T×->Ñ->×-EÑ-E×-QÑ-QÐSW×S_ÑS_×SfÑSf×SrÑSrÓ#sˆDÔ à×Ñ×2Ñ2Ó4Ð@ÜØ˜t×0Ñ0Ð1Ð1sÐtóð ô  ¤× 1Ñ 1°$·,±,×2FÑ2FÓ G× RÑ R× WÑ WÓ YÓZÐØ"Ð*;Ñ;Üðkóð ð 	�‰Õr@   c                 ó6   — | j                   j                  «       S rV   )r«  r)  r(  s    rA   r)  z5MusicgenForConditionalGeneration.get_input_embeddingsÄ  s   € Ø× Ñ ×5Ñ5Ó7Ð7r@   c                 ó6   — | j                   j                  «       S rV   )r%  r;  r(  s    rA   r;  z6MusicgenForConditionalGeneration.get_output_embeddingsÇ  s   € Ø�|‰|×1Ñ1Ó3Ð3r@   c                 ó8   — | j                   j                  |«      S rV   )r%  r?  r=  s     rA   r?  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r‡t        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        d|j"                  |j"                  |j"                  dœ|¤Ž} | ||||¬«      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 causal 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 causal mask are disabled.znIf `decoder_model` is not defined as an argument, a `decoder_pretrained_model_name_or_path` has to be defined.z9 as a decoder model. Cross attention layers are added to z and randomly initialized if z2's architecture allows for cross attention layers.zDecoder model z9 is not initialized as a decoder. In order to initialize zî as a decoder, make sure that the attributes `is_decoder` and `add_cross_attention` of `decoder_config` passed to `.from_sub_models_pretrained(...)` are set to `True` or do not pass a `decoder_config` to `.from_sub_models_pretrained(...)`r®  )r«  r¬  r%  r¥   r?   )ÚitemsÚ
startswithra  ÚpoprM   r)   Úfrom_pretrainedr¢   Úadd_cross_attentionr¶  Úinfor+   r¶   r-   r%  r·  r1  r¥   )ÚclsrÁ  rÂ  rÃ  Ú
model_argsr�   Úargumentr�   Úkwargs_text_encoderÚkwargs_audio_encoderÚkwargs_decoderrŒ   r«  Úencoder_configr¬  r%  Údecoder_configr¥   s                     rA   Úfrom_sub_models_pretrainedz;MusicgenForConditionalGeneration.from_sub_models_pretrainedÍ  s±  € ðT $*§<¡<£>÷
á�˜%Ø×"Ñ" ?Ô3ð ”S˜Ó)Ð+Ð,¨eÑ3ð
Ðñ 
ð $*§<¡<£>÷ 
á�˜%Ø×"Ñ"Ð#3Ô4ð ”SÐ)Ó*Ð,Ð-¨uÑ4ð 
Ðñ  
ð GMÇlÁlÃn÷
Ù3B°8¸UÐX`×XkÑXkÐlvÕXwˆH”S˜“_Ð&Ð'¨Ñ.ð
ˆñ 
ð
 'ò 	.ˆCØ�¨Ñ,Ñ-ð	.à'ò 	/ˆCØÐ'¨#Ñ-Ñ.ð	/à!ò 	)ˆCØ�z CÑ'Ñ(ð	)ð +×.Ñ.¨w¸Ó=ˆØÐØ9ÐAÜ ð%óð ð
 Ð2Ñ2Ü6@×6PÑ6PØ>ñ7ØBUñ7Ølpò7Ñ3�Ð 3ð "×,Ñ,°Ñ4¸×8ZÑ8ZÐ^bÑ8bÜ—K‘KØ'Ð(RÐ'Sð T^ð ^ôð 16�NÔ-Ø9>�NÔ6à0>Ð# HÑ-ä$×4Ñ4Ø:ðØ=GòØK^ñˆLð -×0Ñ0°¸$Ó?ˆØÐ Ø:ÐBÜ ð%óð ð
 Ð3Ñ3Ü7A×7QÑ7QØ?ñ8ØCWñ8Ønrò8Ñ4�Ð 4ð "×,Ñ,°Ñ4¸×8ZÑ8ZÐ^bÑ8bÜ—K‘KØ'Ð(SÐ'Tð U^ð ^ôð 16�NÔ-Ø9>�NÔ6à1?Ð$ XÑ.ä%×5Ñ5Ø;ðØ>HòØL`ñˆMð !×$Ñ$ W¨dÓ3ˆØˆ?Ø4Ð<Ü ð%óð ð
 ˜~Ñ-Ü1;×1KÑ1KØ9ñ2Ø=Kñ2Øbfò2Ñ.� ô ˜n¬nÔ=Ø%3×%;Ñ%;�Nà!×,Ñ,°Ñ5¸×9[Ñ9[Ð_dÑ9dÜ—K‘KØ'Ð(MÐ'Nð O0Ø0UÐ/Vð WØAÐBÐBtðvôð
 15�NÔ-Ø9=�NÔ6à+9�˜xÑ(à˜hÑ'×2Ñ2°eÑ;¸~ÈhÑ?W×?kÑ?kÐotÑ?tÜ—‘Ø$Ð%JÐ$Kð L.Ø.SÐ-Tð UMðMôô *×9Ñ9Ð:_ÑrÐcqÑrˆGô  ð 
Ø%×,Ñ,¸M×<PÑ<PÐZa×ZhÑZhñ
Ølrñ
ˆñ  ¸MÐSZÐciÔjÐjùów
ùó 
ùó
s   ”*M(Á*M.ÂM4Â.M4r3   Úinput_valuesÚpadding_maskÚdecoder_input_idsÚdecoder_attention_maskr2   r±   r  Údecoder_inputs_embedsr@  rá   r�   c                 óæ  — i }i }i }i }|j                  «       D ]s  \  }}|j                  d«      r|||t        d«      d <   Œ)|j                  d«      r|||t        d«      d <   ŒL|j                  d«      r|||t        d«      d <   Œo|||<   Œu |€ | 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œ|¤|¤Ž}t/        |j0                  |j2                  |j4                  |j6                  |j8                  |j:                  |j<                  |j6                  |j8                  ¬«	      S )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])
        ```rÅ  NrÆ  rÇ  )rB   r3   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(   rj   ©r   .)rB   r3   rß   rà   r  rá   r±   r@  )	rC  rD  r±   Údecoder_hidden_statesÚdecoder_attentionsr÷   Úencoder_last_hidden_staterß   Úencoder_attentionsr?   )rÉ  rÊ  ra  r«  r¶   r9   r   r¥   rÐ   r%  r±  r¸  rP   rC   rD   r¬  Úaudio_codesrK   rM   r\  rþ   r_  rÁ   r   rC  rD  r±   r¯   rö   r÷   r  )rZ   rB   r3   rØ  rÙ  rÚ  rÛ  r2   r±   r  rÜ  r@  rá   r�   rÒ  rÓ  rÔ  Úcommon_kwargsrŒ   r�   rß   Úaudio_encoder_outputsrå  Úframesr   r€   r�   r.  s                               rA   rƒ   z(MusicgenForConditionalGeneration.forward’  sT  € ðX !ÐØ!ÐØˆØˆØ Ÿ,™,›.ò 	+‰JˆC�Ø�~‰~˜oÔ.ØCHÐ# C¬¨OÓ(<Ð(>Ð$?Ò@Ø—‘Ð 0Ô1ØEJÐ$ S¬Ð-=Ó)>Ð)@Ð%AÒBØ—‘ 
Ô+Ø9>�˜s¤3 z£?Ð#4Ð5Ò6à%*�˜cÒ"ð	+ð Ð"Ø/˜d×/Ñ/ð Ø#Ø-Ø+ñð &ð	ð
  ñ‰Oô ˜¬Ô/Ü-¨Ð?ˆOà /°Ñ 2Ðð ×Ñ×$Ñ$×0Ñ0°D·L±L×4GÑ4G×4SÑ4SÒSØ—‘×#Ñ#×?Ñ?ÐGà$(×$8Ñ$8Ð9NÓ$OÐ!àÐ%Ø$9¸NÈ9Ñ<UÑ$UÐ!àÐÐ%6Ð%>ÐCXÐC`Ü 2Ø˜Ÿ™×+Ñ+×8Ñ8¸$¿+¹+×:MÑ:M×:dÑ:dó!Ñð Ð&Ð+@Ð+HØ$6 D×$6Ñ$6ð %Ø)Ø)ñ%ð 'ñ%Ð!ð
 0×;Ñ;ˆKØ.9×.?Ñ.?Ñ+ˆF�C˜ GØ˜Š{Ü ØFÀvÀhð OTð Tóð ð
 �{‰{×"Ñ"×1Ñ1°QÒ6¸;×;LÑ;LÈQÑ;OÐSW×S_ÑS_×SmÑSmÐqrÑSrÒ;rà)×;Ñ;¸AÀ1Ð;ÓE�à +¨FÑ 3× ;Ñ ;¸CÀ$Ç,Á,×B\ÑB\Ñ<\Ð^eÓ fÐð >J¸T¿\¹\ð >
Ø'Ø1Ø"7Ø#1Ø/ØØ+Øñ>
ð ð>
ð ñ>
ˆô Ø ×%Ñ%Ø"×)Ñ)Ø+×;Ñ;Ø"1×"?Ñ"?Ø.×9Ñ9Ø,×=Ñ=Ø&5×&GÑ&GØ"1×"?Ñ"?Ø.×9Ñ9ô

ð 
	
r@   Únext_sequence_lengthc
                 ó^  — |€I| j                   j                  || j                  j                  | j                  j                  ¬«      \  }}| j                   j                  ||«      }|	�)|	dkD  r$|j                  d«      }|�|j                  d«      }|�|�|d d …| d …f   n|}d ||||||dœS )N)rP  r,   rQ  )rB   r2   r±   rÚ  r3   rÛ  rá   )r%  rR  rS  rC   rP  rT  rU  )rZ   rÚ  ré  r±   r3   rÛ  rá   r2   Údecoder_delay_pattern_maskr4   r�   s              rA   rW  z>MusicgenForConditionalGeneration.prepare_inputs_for_generation6  sç   € ð &Ð-Ø<@¿L¹L×<aÑ<aØ!Ø×&Ñ&×3Ñ3Ø×1Ñ1×<Ñ<ð =bó =Ñ9ÐÐ9ð !ŸL™L×AÑAÐBSÐUoÓpÐàÐ%¨.¸1Ò*<ð !2× 8Ñ 8¸Ó @ÐØ%Ð1Ø)?×)FÑ)FÀvÓ)NÐ&àÐ&à@TÐ@`Ð!¢!Ð&:Ð%:Ñ%;Ð";Ò<Ðfwð ð
 Ø.Ø.Ø!2Ø,Ø&<Ø"ñ
ð 	
r@   r}  ry  r   rD   rE  ra   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Ú  rB   r,   r_   rG   rF   rj   rÛ  )rË  Ú_get_decoder_start_token_idra   r:   rZ  r%  rþ   r[  ÚallÚitemrr   Ú	ones_like)
rZ   r}  ry  r   rD   rE  ra   rÚ  Údecoder_input_ids_startrÛ  s
             rA   Ú)_prepare_decoder_input_ids_for_generationzJMusicgenForConditionalGeneration._prepare_decoder_input_ids_for_generationd  s[  € ð Ð#Ð(;¸|Ñ(KØ ,× 0Ñ 0Ð1DÓ EÑØ˜LÑ(Ð-=ÀÒ-LØ ,× 0Ñ 0°Ó =Ñà $Ðð "&×!AÑ!AÐBXÐZfÓ!gÐØˆ>Ø—[‘[ˆFä�J‰J˜
 T§\¡\×%?Ñ%?Ñ?ÀÐCÌ5Ï:É:Ð^dÔeØ$ñ%ð 	 ð Ð$Ø 7Ðð ! ,Ð.Ð.ð   Ñ'Ð+AÑA×FÑFÓH×MÑMÔOÜ %§	¡	Ð+BÐDUÐ*VÐ\^Ô _ÐØ'¨<Ñ7Ø)5Ð6NÑ)OÐ&Ü).¯©Ü—_‘_Ð%;Ó<ºQÀÀÀ¸UÑCÐE[Ð\Øô*Ð&ð :P�Ð5Ñ6à  ,Ð.Ð.r@   rz  rS  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rV   ©rÊ  ©r  r”   rÑ  s     €rA   r  z_MusicgenForConditionalGeneration._prepare_text_encoder_kwargs_for_generation.<locals>.<genexpr>¦  ó   øè ø€ ÒI°!�x×*Ñ*¨1×-ÑIùó   ƒr�   r   r²   Úoutput_hidden_statesÚreturn_dictr,   r   rj   r3   ©r  r2   r?   )Úget_encoderrd   rô  Úio_same_devicerÉ  Úanyr¹  rº  r»  rƒ   r¼  r²   rü  r4   r«  Úmain_input_namer  r:   ÚconcatenateÚ
zeros_liker   )rZ   rz  r   ry  rS  ÚencoderÚirrelevant_prefixrÑ  r�   Úencoder_kwargsÚencoder_signatureÚencoder_accepts_wildcardr4   r  s          `      rA   Ú+_prepare_text_encoder_kwargs_for_generationzLMusicgenForConditionalGeneration._prepare_text_encoder_kwargs_for_generation“  sù  ø€ ð ×"Ñ"Ó$ˆô �7˜JÔ'Ø.2ˆG×ÑÔ+ò DÐð $0×#5Ñ#5Ó#7÷
ð 
á�˜%ÜÓIÐ7HÔIÔIð �e‰Oð
ˆñ 
ô
  ¤× 1Ñ 1°'·/±/Ó B× MÑ MÓNÐØ#+Ð/@Ð#@Ò#gÀNÐVgÐDgÐ Ù'à7E×7KÑ7KÓ7M÷Ù$3 H¨eÐQYÐ]nÒQn�˜%‘ðˆNñ ð /@×.QÑ.QˆÐ*Ñ+Ø1B×1WÑ1WˆÐ-Ñ.Ø*×9Ñ9ˆð 0@Ð/KÑ+ÐQU×QbÑQb×QrÑQrÐØ(,ˆ�}Ñ%Ø+8ˆÐ'Ñ(Ù#Ñ5 nÑ5×GÑGÐð Ð%¨.¸1Ò*<Ü %× 1Ñ 1Ð3DÄe×FVÑFVÐWhÓFiÐ2jÐpqÔ rÐØ <Ñ/Ü16×1BÑ1BØ!Ð"2Ñ3´U×5EÑ5EÀlÐScÑFdÓ5eÐfÐlmô2�Ð-Ñ.ô +:ÐL]Ô*^ˆÐ&Ñ'àÐùó?
ùós   Á!F.Â<F4Ã	F4c                 ó˜  ‡— | j                  d¬«      }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 )Nr3  )Úmodalityrô  Trõ  c              3   ó@   •K  — | ]  }‰j                  |«      –— Œ y ­wrV   rø  rù  s     €rA   r  z`MusicgenForConditionalGeneration._prepare_audio_encoder_kwargs_for_generation.<locals>.<genexpr>Ó  rú  rû  r�   r   rý  r,   r(   z3Expected stereo audio (2-channels) but example has z	 channel.rj   rÞ  rß  rà  rÚ  Úaudio_scalesr?   )rÿ  rd   rô  r   rÉ  r  r¹  rº  r»  rƒ   r¼  r¬  r  r%  r¥   r\  Úencoderå  r  rK   rM   Únew_onesr:   rF  rÁ   rþ   )rZ   rØ  r   ry  r  r  rÑ  r�   r  r  r	  rç  rå  r  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         `                  rA   Ú,_prepare_audio_encoder_kwargs_for_generationzMMusicgenForConditionalGeneration._prepare_audio_encoder_kwargs_for_generationÄ  sO  ø€ ð ×"Ñ"¨GÐ"Ó4ˆô �7˜JÔ'Ø.2ˆG×ÑÔ+ò DÐð $0×#5Ñ#5Ó#7÷
ð 
á�˜%ÜÓIÐ7HÔIÔIð �e‰Oð
ˆñ 
ô
  ¤× 1Ñ 1°'·/±/Ó B× MÑ MÓNÐØ#+Ð/@Ð#@Ò#gÀNÐVgÐDgÐ Ù'à7E×7KÑ7KÓ7M÷Ù$3 H¨eÐQYÐ]nÒQn�˜%‘ðˆNñ ð
 0@Ð/KÑ+ÐQU×QcÑQc×QsÑQsÐØ(,ˆ�}Ñ%à�<‰<×Ñ×-Ñ-°Ò2Ø/;ˆNÐ+Ñ,Ø$2 G§N¡NÑ$D°^Ñ$DÐ!Ø/×;Ñ;ˆKØ0×=Ñ=ˆLà.9×.?Ñ.?Ñ+ˆF�C˜¢Gð ×!Ñ! !Ñ$¨Ò)Ü ØIÈ,×J\ÑJ\Ð]^ÑJ_ÐI`Ð`iÐjóð ð 0<ºA¸rÀ¸rÂ1¸HÑ/EˆNÐ+Ñ,Ø)7¨¯©Ñ)I¸.Ñ)IÐ&Ø9×EÑEÐØ :× GÑ GÐà/;ºA¸q¹rÂ1¸HÑ/EˆNÐ+Ñ,Ø*8¨'¯.©.Ñ*J¸>Ñ*JÐ'Ø ;× GÑ GÐØ!<×!IÑ!IÐà.>×.DÑ.DÑ+ˆF�C˜ Gà*×3Ñ3°V¸SÀ!ÀiÁ-ÐQXÐ4YÓZˆKà(8ˆKšš1™c ˜c¢1˜Ñ%Ø):ˆKšš1˜a˜d ˜d¢A˜Ñ&à  T FÒ*Ð.@ÀTÀFÒ.JÜ$Ÿ{™{Ð,=Ð?QÐ+RÐXYÔZ‘à $˜v¨™|�à�QŠ;ÜØBÀ6À(ð KPð Póð ð
 (¨Ñ/×7Ñ7¸¸d¿l¹l×>XÑ>XÑ8XÐZaÓbÐà,=ˆÐ(Ñ)Ø'3ˆ�^Ñ$ØÐùó}
ùós   Á	!K Â>KÃKc                 ó”   — t        || j                  j                  j                  | j                  j                  j                  «      S rV   )rP   r¥   r%  rC   rE  )rZ   r@  s     rA   Ú%prepare_decoder_input_ids_from_labelszFMusicgenForConditionalGeneration.prepare_decoder_input_ids_from_labels  s1   € Ü! &¨$¯+©+×*=Ñ*=×*JÑ*JÈDÏKÉK×L_ÑL_×LlÑLlÓmÐmr@   c                 ó   — t        d«      ‚)NzèResizing 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)rZ   Úargsr�   s      rA   Ú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©rZ   Úparams     rA   Úfreeze_audio_encoderz5MusicgenForConditionalGeneration.freeze_audio_encoder  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¼  r  r   r!  s     rA   Úfreeze_text_encoderz4MusicgenForConditionalGeneration.freeze_text_encoder"  s8   € ð ×&Ñ&×1Ñ1Ó3ò 	(ˆEØ"'ˆEÕð	(à+0ˆ×ÑÕ(r@   rn  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.Nr2   r   rF   r_   rH   zB`bos_token_id` has to be defined when no `input_ids` are provided.r,   )r¸   r|   r:   rZ  r[  ra   rM   r½   r¶   r‡   rK   )rZ   rn  rE  r   r2   rK   r}  r�   s           rA   Ú*_maybe_initialize_input_ids_for_generationzKMusicgenForConditionalGeneration._maybe_initialize_input_ids_for_generation*  sÖ   € ð ÐØˆMà&×*Ñ*Ð+<Ó=ˆØÐ&à# AÑ&×+Ñ+Ó-¨c¨rÐ2ˆEÜ—:‘:˜e¬5¯:©:¸d¿k¹kÔJÈTÑQÐQàÐÜÐaÓbÐbð ˆ
Ø!×(Ñ(Ó*ò 	ˆEÜ˜%¤§¡Õ.Ø"Ÿ[™[¨™^�
Ùð	ô �z‰z˜: q˜/´·±ÀDÇKÁKÔPÐS_Ñ_Ð_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.)rS  rD   rE  rM   )rZ   rD   rE  s      rA   rí  z<MusicgenForConditionalGeneration._get_decoder_start_token_idF  se   € ð
 &Ð1ñ #à×'Ñ'×>Ñ>ð 	ð
 (4Ð'?‘|ÀT×E[ÑE[×EhÑEhˆà!Ð-Ø)Ð)ØÐ%ØÐÜØjó
ð 	
r@   ro  rp  rq  rr  r/   c                 ó~
  — | j                  d|ddd«      } | j                  |fi |¤Ž\  }}	|j                  «       }
|
t        j                  t        j
                  fvrt        d«      ‚| 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| j1                  ||	||«      }	d|	vrd|	v r| j3                  |	d   |	«      }	| j5                  |||	|j6                  |j8                  |j(                  ¬«      \  }}	|j$                  d   }|j                  d«      du xr |j:                  du}|j                  d«      du xr |j<                  du}| j?                  ||||||¬«      }| j@                  jC                  ||j6                  |j:                  ¬«      \  }}||	d<   |�|jE                  |jG                  «       «       |j                  «       }
|j,                  �:|j,                  dkD  r+|jI                  tK        |j,                  «      «       d|_        | jM                  |||d||j(                  ¬«      }| jO                  ||¬«      } | jP                  d||jR                  | jT                  jV                  dœ|	¤Ž\  }}	| jY                  |||	«      |d<    | jZ                  |f|||dœ|¤|	¤Ž}|j\                  r|j^                  }n|}| j@                  ja                  ||	d   «      }|||jb                  k7     je                  || j@                  jf                  d«      }|d   }|	j                  d«      }|€dg|z  }| j@                  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 ) rt  NFr…  r2   r   rþ  r3   rB  rá   r4   rÚ  rØ  )r}  ry  r   rD   rE  ra   rF   rP  ru  rv  rO  rë  r,   r  rƒ  )rB   r„  r�  Úprefill_outputs)ro  rp  rS  )N.r  )r  r(   rj   r?   ):Ú_extract_generation_mode_kwargsÚ_prepare_generation_configr”  r   r˜  r™  rM   r‰  r†  Ú_validate_generation_moder¸   Útyper9   r   r   r   rŠ  rE  rK   r‹  ra   rá   r4   rŒ  r
  r  rò  r‘  Ú_bos_token_tensorrP  ru  r�  r%  rR  r’  r“  r•  r   r–  r—  rš  r›  r¥   r�  Ú_prefillrœ  r�  rž  rT  rŸ  rÁ   rþ   r\  r¬  ÚdecodeÚaudio_valuesr:   rr   )rZ   rn  rS  ro  rp  rq  rr  r�   Úgeneration_mode_kwargsr   r|  r¡  r¢  rz  ry  r}  rB   r{  rw  rx  rë  rH  r£  r  Úoutput_valuesÚcodec_outputs_leftÚoutput_values_leftÚcodec_outputs_rightÚoutput_values_rights                                rA   r¤  z)MusicgenForConditionalGeneration.generateX  s  € ðV "&×!EÑ!EÀdÈFÐTYÐ[_ÐaeÓ!fÐØ*I¨$×*IÑ*IÐJ[Ñ*fÐ_eÑ*fÑ'Ð˜<Ø+×?Ñ?ÓAˆØ¤>×#8Ñ#8¼.×:VÑ:VÐ"WÑWÜðTóð ð
 	×#Ñ# L×$5Ñ$5Ó$7Ô8Ø×&Ñ& Ð8IÐKaÔbà×ÑÐ-Ó.Ð:¼tÀLÐQbÑDcÓ?dÔhmÑ?mä.=ÐP\Ð]nÑPoÐpqÑPrÔ.sˆLÐ*Ñ+ð 0@Ð/KÑ+ÔQdÓQfÐØ1BÐ1NÑ-ÔThÓTjÐà"3¸<Ð"GÐØ$0×$4Ñ$4Ð5EÀtÓ$LÐTXÐ$XÐ!ð 9=×8RÑ8RØÐ%×2Ñ2°Ló9
Ñ5ˆÐ'¨ð #×(Ñ(¨Ñ+ˆ
Ø×$Ñ$Ð%6Ð8QÐZg×ZnÑZnÐ$Ô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Ó!9¸TÐ!AÒ!nÐFW×FbÑFbÐjnÐFnÐØ!'§¡¨LÓ!9¸TÐ!AÒ!nÐFW×FbÑFbÐjnÐFnÐØ ×:Ñ:Ø/Ø#9Ø#9Ø-Ø'Ø-ð ;ó 
Ðð 15·±×0UÑ0UØØ*×FÑFØ(×3Ñ3ð 1Vó 1
Ñ-ˆ	Ð-ð 6PˆÐ1Ñ2ð ÐØ�L‰L˜Ÿ™›Ô)ð ,×?Ñ?ÓAˆð ×+Ñ+Ð7Ð<M×<\Ñ<\Ð_`Ò<`Ø×#Ñ#Ô$IÐJ[×JjÑJjÓ$kÔlØ/3ÐÔ,ð  ×5Ñ5Ø/Ø!1Ø+Ø%)Ø-Ø×#Ñ#ð 6ó 
Ðð !×7Ñ7Ø/ÐCTð 8ó 
Ðð
 #E $×"DÑ"Dð #
ØØ)×>Ñ>Ø#Ÿ{™{×=Ñ=ñ#
ð ñ	#
Ñˆ	�<ð 59·M±MÀ)ÐM^Ð`lÓ4mÐÐ0Ñ1ð �$—,‘,Øð
à-Ø/Ø/ñ	
ð
 %ð
ð ñ
ˆð ×4Ò4Ø ×*Ñ*‰Jà ˆJð —\‘\×:Ñ:¸:À|ÐTpÑGqÓrˆ
ð   
Ð.?×.QÑ.QÑ QÑR×ZÑZØ˜Ÿ™×2Ñ2°Bó
ˆ
ð
   	Ñ*ˆ
à#×'Ñ'¨Ó7ˆØÐØ ˜6 JÑ.ˆLà�<‰<×Ñ×-Ñ-°Ò2Ø ×.Ñ.×5Ñ5ØØ)ð 6ó ÷ ‰lñ ð
 "&×!3Ñ!3×!:Ñ!:¸:ÂaÊÉCÈaÈCÒQRÀlÑ;SÐbnÐ!:Ó!oÐØ!3×!@Ñ!@Ðà"&×"4Ñ"4×";Ñ";¸JÂqÊ!ÈQÈTÐPQÈTÒSTÀ}Ñ<UÐdpÐ";Ó"qÐØ"5×"BÑ"BÐä!ŸI™IÐ'9Ð;NÐ&OÐUVÔWˆMà×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,   )ra   r`   rù   )r2   r3   r4   )	r:   rv   r¥   r«  rÐ   ra   r`   r[  r1   )rZ   Únum_samplesr  r3   s       rA   Úget_unconditional_inputsz9MusicgenForConditionalGeneration.get_unconditional_inputsN  sy   € ô, "ŸK™KØ˜!˜TŸ[™[×5Ñ5×AÑAÐBÈ4Ï;É;Ð^b×^hÑ^hô
Ðô Ÿ™ k°1Ð%5¸d¿k¹kÔQV×Q[ÑQ[Ô\ˆä)Ø.Ð0Ø)Øô
ð 	
r@   )NNNN)NNN)NNNNNNNNNNNNr¥  rV   )NNr¦  )r,   )7r5   r6   r7   r-   r<   r§  rì   r  rí   r   r1  rX   r)  r;  r?  ÚclassmethodÚstrr×  r$   r"   r:   r=   Ú
BoolTensorr;   r9   r   rÌ   r    r!   r   rƒ   r„   rW  Údictr‡   ra   rò  r   r   r
  r  r  r  r#  r%  r'  Úlistrí  r†   r   r   r   r¤  r;  rˆ   r‰   s   @rA   r©  r©  Q  s¡  ø… ð ÓØ"ÐØ)ÐØ!€OØ&*Ð#ð )-Ø/3Ø04Ø.2ñeà Ñ%ðeð &¨Ñ,ðeð '¨Ñ-ð	eð
 % tÑ+õeòN8ò4òBð ð BFØBFØ<@ñ	Bkà47¸$±JðBkð 69¸4±ZðBkð 03°T©zð	Bkð 
òBkó ðBkðH Øð .2Ø26Ø15Ø04Ø59Ø:>Ø;?Ø(,Ø26Ø:>Ø*.Ø!%ñ`
à×#Ñ# dÑ*ð`
ð ×(Ñ(¨4Ñ/ð`
ð ×'Ñ'¨$Ñ.ð	`
ð
 ×&Ñ&¨Ñ-ð`
ð !×+Ñ+¨dÑ2ð`
ð !&× 0Ñ 0°4Ñ 7ð`
ð ˜u×0Ñ0Ñ1°DÑ8ð`
ð  ™ð`
ð ×(Ñ(¨4Ñ/ð`
ð  %×0Ñ0°4Ñ7ð`
ð × Ñ  4Ñ'ð`
ð ˜$‘;ð`
ð Ð+Ñ,ð`
ð 
�Ñ	 ò`
ó ó ð`
ðJ ,0ØØØ#ØØØ#'Øñ,
ð " D™jó,
ðf .2Ø#'Ø&*ñ-/àð-/ð ð-/ð ˜3 §¡Ð,Ñ-ð	-/ð
 !$ d¡
ð-/ð ˜D‘jð-/ð —‘˜tÑ#ð-/ð 
ˆu×Ñ  c¨5¯<©<Ð&7Ñ!8Ð8Ñ	9ó-/ð^/à—|‘|ð/ð  ™*ð	/ð
 ,ð/ð 
ˆc�3ˆh‰ó/ðd JNñJØ<?À$¹JóJðXn¸E¿L¹Ló nò
ò2ò1ð`à—‘˜tÑ#ð`ð ˜D‘jð`ð ˜3 §¡Ð,Ñ-ð	`ð
 
×	Ñ	ó`ð: aeñ
Ø&)¨D°©I¡o¸Ñ&<ð
ØSVÐY]ÑS]ð
à	ó
ð$ €U‡]�]ƒ_ð '+Ø59Ø7;Ø9=Ø#'Ø-1ñs!à—‘˜tÑ#ðs!ð ,¨dÑ2ðs!ð .°Ñ4ð	s!ð
 0°$Ñ6ðs!ð ˜D‘[ðs!ð ˜>Ñ*òs!ó ðs!÷j 
r@   r©  )r©  r1  r#  ræ   )Nrµ   )Yr8   r†  rº  rl   r  Úcollections.abcr   Údataclassesr   Útypingr   r   r   r:   Útorch.nnr—   r   Ú r
   rê   Úactivationsr   Úcache_utilsr   r   r   Ú
generationr   r   r   r   r   r   Úmasking_utilsr   r   Úmodeling_flash_attention_utilsr   Úmodeling_layersr   Úmodeling_outputsr   r   r   r   r   Úmodeling_utilsr   r   Úprocessing_utilsr    Úutilsr!   r"   r#   Úutils.genericr$   r%   Úutils.output_capturingr&   r'   Úauto.configuration_autor)   r²  r+   Úconfiguration_musicgenr-   r.   Úgeneration.streamersr/   Ú
get_loggerr5   r¶  r1   r‡   r„   rP   ÚModulerR   r>   r�   rŸ   rÎ   ræ   ró   r#  r1  r©  Ú__all__r?   r@   rA   ú<module>rX     s2  ðñ ã Û Û Û Ý $Ý !ß /Ñ /ã Ý Ý %å &Ý !ß CÑ C÷÷ ÷ Kõõ :÷õ ÷ GÝ &ß @Ñ @ß Iß EÝ 0Ý *ß Iñ Ý4à	ˆ×	Ñ	˜HÓ	%€ð Ø
ô( ó (ó ó ð(ð" %§,¡,ð ¸cð Ð[^ó ô()L¨B¯I©Iô )Lðf !Øñ%Ø�I‰Ið%à�<‰<ð%ð 
�‰ð%ð �<‰<ð	%ð
 —L‘L 4Ñ'ð%ð �T‰\ð%ð ð%ð Ð'Ñ(ó%ô8m)˜Ÿ	™	ô m)ô`\Ð5ô \ð~ ô4˜oó 4ó ð4ô"O
Ð-ô O
ðd ôEÐ+ó Eó ðEñP ðôô
ZÐ1°?ó Zóð
Zñz ðôô
X
Ð'>Àó X
óð
X
òv  r�r@   