



"""simple docstring"""





import argparse
from pathlib import Path
from typing import Dict, OrderedDict, Tuple

import torch
from audiocraft.models import MusicGen

from transformers import (
    AutoFeatureExtractor,
    AutoTokenizer,
    EncodecModel,
    MusicgenDecoderConfig,
    MusicgenForConditionalGeneration,
    MusicgenProcessor,
    TaEncoderModel,
)
from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM
from transformers.utils import logging


logging.set_verbosity_info()
__lowerCAmelCase       :					Union[str, Any]      					=					logging.get_logger(__name__)


__lowerCAmelCase       :					str      					=					['''model.decoder.embed_positions.weights''']
def 	__lowerCAmelCase						(		__UpperCamelCase      :			Optional[Any]    ):


						'''simple docstring'''






						if "emb" in name:
												snake_case_   : int						=			name.replace("""emb"""					, """model.decoder.embed_tokens"""    )
						if "transformer" in name:
												snake_case_   : Union[str, Any]						=			name.replace("""transformer"""					, """model.decoder"""    )
						if "cross_attention" in name:
												snake_case_   : Union[str, Any]						=			name.replace("""cross_attention"""					, """encoder_attn"""    )
						if "linear1" in name:
												snake_case_   : List[str]						=			name.replace("""linear1"""					, """fc1"""    )
						if "linear2" in name:
												snake_case_   : Any						=			name.replace("""linear2"""					, """fc2"""    )
						if "norm1" in name:
												snake_case_   : Optional[Any]						=			name.replace("""norm1"""					, """self_attn_layer_norm"""    )
						if "norm_cross" in name:
												snake_case_   : Union[str, Any]						=			name.replace("""norm_cross"""					, """encoder_attn_layer_norm"""    )
						if "norm2" in name:
												snake_case_   : Optional[int]						=			name.replace("""norm2"""					, """final_layer_norm"""    )
						if "out_norm" in name:
												snake_case_   : List[Any]						=			name.replace("""out_norm"""					, """model.decoder.layer_norm"""    )
						if "linears" in name:
												snake_case_   : Optional[Any]						=			name.replace("""linears"""					, """lm_heads"""    )
						if "condition_provider.conditioners.description.output_proj" in name:
												snake_case_   : List[str]						=			name.replace("""condition_provider.conditioners.description.output_proj"""					, """enc_to_dec_proj"""    )
						return name
def 	__lowerCAmelCase						(		__UpperCamelCase      :			OrderedDict					, __UpperCamelCase      :			int    ):


						'''simple docstring'''






						snake_case_   : List[str]						=			list(state_dict.keys()    )
						snake_case_   : int						=			{}
						for key in keys:
												snake_case_   : Optional[int]						=			state_dict.pop(__UpperCamelCase    )
												snake_case_   : int						=			rename_keys(__UpperCamelCase    )
												if "in_proj_weight" in key:
																		# split fused qkv proj
																		snake_case_   : int						=			val[:hidden_size, :]
																		snake_case_   : int						=			val[hidden_size : 2 * hidden_size, :]
																		snake_case_   : Optional[Any]						=			val[-hidden_size:, :]
												elif "enc_to_dec_proj" in key:
																		snake_case_   : Union[str, Any]						=			val
												else:
																		snake_case_   : Optional[Any]						=			val
						return state_dict, enc_dec_proj_state_dict
def 	__lowerCAmelCase						(		__UpperCamelCase      :			str    ):


						'''simple docstring'''






						if checkpoint == "small":
												# default config values
												snake_case_   : str						=			1_0_2_4
												snake_case_   : List[str]						=			2_4
												snake_case_   : List[Any]						=			1_6
						elif checkpoint == "medium":
												snake_case_   : List[str]						=			1_5_3_6
												snake_case_   : str						=			4_8
												snake_case_   : List[Any]						=			2_4
						elif checkpoint == "large":
												snake_case_   : Any						=			2_0_4_8
												snake_case_   : Dict						=			4_8
												snake_case_   : str						=			3_2
						else:
												raise ValueError(F'Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.'    )
						snake_case_   : Dict						=			MusicgenDecoderConfig(
						    hidden_size=__UpperCamelCase					, ffn_dim=hidden_size * 4					, num_hidden_layers=__UpperCamelCase					, num_attention_heads=__UpperCamelCase					, )
						return config
@torch.no_grad()
def 	__lowerCAmelCase						(		__UpperCamelCase      :			str					, __UpperCamelCase      :			Tuple=None					, __UpperCamelCase      :			str=None					, __UpperCamelCase      :			Optional[Any]="cpu"    ):


						'''simple docstring'''






						snake_case_   : Any						=			MusicGen.get_pretrained(__UpperCamelCase					, device=__UpperCamelCase    )
						snake_case_   : List[Any]						=			decoder_config_from_checkpoint(__UpperCamelCase    )

						snake_case_   : Optional[Any]						=			fairseq_model.lm.state_dict()
						snake_case_   : int						=			rename_state_dict(
						    __UpperCamelCase					, hidden_size=decoder_config.hidden_size    )

						snake_case_   : Union[str, Any]						=			TaEncoderModel.from_pretrained("""t5-base"""    )
						snake_case_   : List[str]						=			EncodecModel.from_pretrained("""facebook/encodec_32khz"""    )
						snake_case_   : Dict						=			MusicgenForCausalLM(__UpperCamelCase    ).eval()

						# load all decoder weights - expect that we'll be missing embeddings and enc-dec projection
						snake_case_   : List[Any]						=			decoder.load_state_dict(__UpperCamelCase					, strict=__UpperCamelCase    )

						for key in missing_keys.copy():
												if key.startswith(("""text_encoder""", """audio_encoder""")    ) or key in EXPECTED_MISSING_KEYS:
																		missing_keys.remove(__UpperCamelCase    )

						if len(__UpperCamelCase    ) > 0:
												raise ValueError(F'Missing key(s) in state_dict: {missing_keys}'    )

						if len(__UpperCamelCase    ) > 0:
												raise ValueError(F'Unexpected key(s) in state_dict: {unexpected_keys}'    )

						# init the composite model
						snake_case_   : Optional[int]						=			MusicgenForConditionalGeneration(text_encoder=__UpperCamelCase					, audio_encoder=__UpperCamelCase					, decoder=__UpperCamelCase    )

						# load the pre-trained enc-dec projection (from the decoder state dict)
						model.enc_to_dec_proj.load_state_dict(__UpperCamelCase    )

						# check we can do a forward pass
						snake_case_   : Any						=			torch.arange(0					, 8					, dtype=torch.long    ).reshape(2					, -1    )
						snake_case_   : Any						=			input_ids.reshape(2 * 4					, -1    )

						with torch.no_grad():
												snake_case_   : Any						=			model(input_ids=__UpperCamelCase					, decoder_input_ids=__UpperCamelCase    ).logits

						if logits.shape != (8, 1, 2_0_4_8):
												raise ValueError("""Incorrect shape for logits"""    )

						# now construct the processor
						snake_case_   : List[Any]						=			AutoTokenizer.from_pretrained("""t5-base"""    )
						snake_case_   : Dict						=			AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz"""					, padding_side="""left"""    )

						snake_case_   : Dict						=			MusicgenProcessor(feature_extractor=__UpperCamelCase					, tokenizer=__UpperCamelCase    )

						# set the appropriate bos/pad token ids
						snake_case_   : Union[str, Any]						=			2_0_4_8
						snake_case_   : Optional[int]						=			2_0_4_8

						# set other default generation config params
						snake_case_   : Dict						=			int(3_0 * audio_encoder.config.frame_rate    )
						snake_case_   : Optional[Any]						=			True
						snake_case_   : Any						=			3.0

						if pytorch_dump_folder is not None:
												Path(__UpperCamelCase    ).mkdir(exist_ok=__UpperCamelCase    )
												logger.info(F'Saving model {checkpoint} to {pytorch_dump_folder}'    )
												model.save_pretrained(__UpperCamelCase    )
												processor.save_pretrained(__UpperCamelCase    )

						if repo_id:
												logger.info(F'Pushing model {checkpoint} to {repo_id}'    )
												model.push_to_hub(__UpperCamelCase    )
												processor.push_to_hub(__UpperCamelCase    )


if __name__ == "__main__":
					__lowerCAmelCase       :					Dict      					=					argparse.ArgumentParser()
					# Required parameters
					parser.add_argument(
					    '''--checkpoint''',
					    default='''small''',
					    type=str,
					    help='''Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.''',
					)
					parser.add_argument(
					    '''--pytorch_dump_folder''',
					    required=True,
					    default=None,
					    type=str,
					    help='''Path to the output PyTorch model directory.''',
					)
					parser.add_argument(
					    '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.'''
					)
					parser.add_argument(
					    '''--device''', default='''cpu''', type=str, help='''Torch device to run the conversion, either cpu or cuda.'''
					)

					__lowerCAmelCase       :					List[str]      					=					parser.parse_args()
					convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)










"""simple docstring"""





import argparse
import json
from collections import OrderedDict

import torch
from huggingface_hub import cached_download, hf_hub_url

from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification
def 	__lowerCAmelCase						(		__UpperCamelCase      :			List[Any]    ):


						'''simple docstring'''






						snake_case_   : List[str]						=			[]
						embed.append(
						    (
						        F'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight',
						        F'stage{idx}.patch_embed.proj.weight',
						    )    )
						embed.append(
						    (
						        F'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias',
						        F'stage{idx}.patch_embed.proj.bias',
						    )    )
						embed.append(
						    (
						        F'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight',
						        F'stage{idx}.patch_embed.norm.weight',
						    )    )
						embed.append(
						    (
						        F'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias',
						        F'stage{idx}.patch_embed.norm.bias',
						    )    )
						return embed
def 	__lowerCAmelCase						(		__UpperCamelCase      :			str					, __UpperCamelCase      :			int    ):


						'''simple docstring'''






						snake_case_   : str						=			[]
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked',
						        F'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight',
						        F'stage{idx}.blocks.{cnt}.attn.proj_q.weight',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias',
						        F'stage{idx}.blocks.{cnt}.attn.proj_q.bias',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight',
						        F'stage{idx}.blocks.{cnt}.attn.proj_k.weight',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias',
						        F'stage{idx}.blocks.{cnt}.attn.proj_k.bias',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight',
						        F'stage{idx}.blocks.{cnt}.attn.proj_v.weight',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias',
						        F'stage{idx}.blocks.{cnt}.attn.proj_v.bias',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight',
						        F'stage{idx}.blocks.{cnt}.attn.proj.weight',
						    )    )
						attention_weights.append(
						    (
						        F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias',
						        F'stage{idx}.blocks.{cnt}.attn.proj.bias',
						    )    )
						attention_weights.append(
						    (F'cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight', F'stage{idx}.blocks.{cnt}.mlp.fc1.weight')    )
						attention_weights.append(
						    (F'cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias', F'stage{idx}.blocks.{cnt}.mlp.fc1.bias')    )
						attention_weights.append(
						    (F'cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight', F'stage{idx}.blocks.{cnt}.mlp.fc2.weight')    )
						attention_weights.append(
						    (F'cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias', F'stage{idx}.blocks.{cnt}.mlp.fc2.bias')    )
						attention_weights.append(
						    (F'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight', F'stage{idx}.blocks.{cnt}.norm1.weight')    )
						attention_weights.append(
						    (F'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias', F'stage{idx}.blocks.{cnt}.norm1.bias')    )
						attention_weights.append(
						    (F'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight', F'stage{idx}.blocks.{cnt}.norm2.weight')    )
						attention_weights.append(
						    (F'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias', F'stage{idx}.blocks.{cnt}.norm2.bias')    )
						return attention_weights
def 	__lowerCAmelCase						(		__UpperCamelCase      :			Tuple    ):


						'''simple docstring'''






						snake_case_   : int						=			[]
						token.append((F'cvt.encoder.stages.{idx}.cls_token', """stage2.cls_token""")    )
						return token
def 	__lowerCAmelCase						(		):


						'''simple docstring'''






						snake_case_   : Union[str, Any]						=			[]
						head.append(("""layernorm.weight""", """norm.weight""")    )
						head.append(("""layernorm.bias""", """norm.bias""")    )
						head.append(("""classifier.weight""", """head.weight""")    )
						head.append(("""classifier.bias""", """head.bias""")    )
						return head
def 	__lowerCAmelCase						(		__UpperCamelCase      :			Union[str, Any]					, __UpperCamelCase      :			Union[str, Any]					, __UpperCamelCase      :			Optional[Any]					, __UpperCamelCase      :			List[Any]    ):


						'''simple docstring'''






						snake_case_   : Union[str, Any]						=			"""imagenet-1k-id2label.json"""
						snake_case_   : Optional[Any]						=			1_0_0_0

						snake_case_   : Any						=			"""huggingface/label-files"""
						snake_case_   : Tuple						=			num_labels
						snake_case_   : Dict						=			json.load(open(cached_download(hf_hub_url(__UpperCamelCase					, __UpperCamelCase					, repo_type="""dataset"""    )    )					, """r"""    )    )
						snake_case_   : str						=			{int(__UpperCamelCase    ): v for k, v in idalabel.items()}

						snake_case_   : List[str]						=			idalabel
						snake_case_   : Any						=			{v: k for k, v in idalabel.items()}

						snake_case_   : Dict						=			CvtConfig(num_labels=__UpperCamelCase					, idalabel=__UpperCamelCase					, labelaid=__UpperCamelCase    )

						# For depth size 13 (13 = 1+2+10)
						if cvt_model.rsplit("""/"""					, 1    )[-1][4:6] == "13":
												snake_case_   : Any						=			[1, 2, 1_0]

						# For depth size 21 (21 = 1+4+16)
						elif cvt_model.rsplit("""/"""					, 1    )[-1][4:6] == "21":
												snake_case_   : Any						=			[1, 4, 1_6]

						# For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20)
						else:
												snake_case_   : Optional[int]						=			[2, 2, 2_0]
												snake_case_   : str						=			[3, 1_2, 1_6]
												snake_case_   : Any						=			[1_9_2, 7_6_8, 1_0_2_4]

						snake_case_   : Union[str, Any]						=			CvtForImageClassification(__UpperCamelCase    )
						snake_case_   : str						=			AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k"""    )
						snake_case_   : List[Any]						=			image_size
						snake_case_   : str						=			torch.load(__UpperCamelCase					, map_location=torch.device("""cpu"""    )    )

						snake_case_   : Any						=			OrderedDict()
						snake_case_   : Tuple						=			[]

						for idx in range(len(config.depth    )    ):
												if config.cls_token[idx]:
																		snake_case_   : Optional[Any]						=			list_of_state_dict + cls_token(__UpperCamelCase    )
												snake_case_   : str						=			list_of_state_dict + embeddings(__UpperCamelCase    )
												for cnt in range(config.depth[idx]    ):
																		snake_case_   : List[str]						=			list_of_state_dict + attention(__UpperCamelCase					, __UpperCamelCase    )

						snake_case_   : str						=			list_of_state_dict + final()
						for gg in list_of_state_dict:
												print(__UpperCamelCase    )
						for i in range(len(__UpperCamelCase    )    ):
												snake_case_   : Union[str, Any]						=			original_weights[list_of_state_dict[i][1]]

						model.load_state_dict(__UpperCamelCase    )
						model.save_pretrained(__UpperCamelCase    )
						image_processor.save_pretrained(__UpperCamelCase    )


# Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al

if __name__ == "__main__":
					__lowerCAmelCase       :					Optional[int]      					=					argparse.ArgumentParser()
					parser.add_argument(
					    '''--cvt_model''',
					    default='''cvt-w24''',
					    type=str,
					    help='''Name of the cvt model you\'d like to convert.''',
					)
					parser.add_argument(
					    '''--image_size''',
					    default=384,
					    type=int,
					    help='''Input Image Size''',
					)
					parser.add_argument(
					    '''--cvt_file_name''',
					    default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''',
					    type=str,
					    help='''Input Image Size''',
					)
					parser.add_argument(
					    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
					)

					__lowerCAmelCase       :					Dict      					=					parser.parse_args()
					convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)

