






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()
SCREAMING_SNAKE_CASE__		:							Optional[Any] 				=				logging.get_logger(__name__)


SCREAMING_SNAKE_CASE__		:							Optional[Any] 				=				["""model.decoder.embed_positions.weights"""]





def  _lowerCamelCase						(						__lowerCamelCase       ) ->			List[Any]:

     '''simple docstring'''
     if "emb" in name:
          UpperCAmelCase__      :  int				      =			name.replace("""emb""" ,							"""model.decoder.embed_tokens"""       )
     if "transformer" in name:
          UpperCAmelCase__      :  Optional[int]				      =			name.replace("""transformer""" ,							"""model.decoder"""       )
     if "cross_attention" in name:
          UpperCAmelCase__      :  Optional[Any]				      =			name.replace("""cross_attention""" ,							"""encoder_attn"""       )
     if "linear1" in name:
          UpperCAmelCase__      :  List[str]				      =			name.replace("""linear1""" ,							"""fc1"""       )
     if "linear2" in name:
          UpperCAmelCase__      :  str				      =			name.replace("""linear2""" ,							"""fc2"""       )
     if "norm1" in name:
          UpperCAmelCase__      :  Tuple				      =			name.replace("""norm1""" ,							"""self_attn_layer_norm"""       )
     if "norm_cross" in name:
          UpperCAmelCase__      :  str				      =			name.replace("""norm_cross""" ,							"""encoder_attn_layer_norm"""       )
     if "norm2" in name:
          UpperCAmelCase__      :  List[str]				      =			name.replace("""norm2""" ,							"""final_layer_norm"""       )
     if "out_norm" in name:
          UpperCAmelCase__      :  Optional[int]				      =			name.replace("""out_norm""" ,							"""model.decoder.layer_norm"""       )
     if "linears" in name:
          UpperCAmelCase__      :  List[Any]				      =			name.replace("""linears""" ,							"""lm_heads"""       )
     if "condition_provider.conditioners.description.output_proj" in name:
          UpperCAmelCase__      :  Dict				      =			name.replace("""condition_provider.conditioners.description.output_proj""" ,							"""enc_to_dec_proj"""       )
     return name





def  _lowerCamelCase						(						__lowerCamelCase ,							__lowerCamelCase       ) ->			Tuple[Dict, Dict]:

     '''simple docstring'''
     UpperCAmelCase__      :  Optional[Any]				      =			list(state_dict.keys()       )
     UpperCAmelCase__      :  str				      =			{}
     for key in keys:
          UpperCAmelCase__      :  Tuple				      =			state_dict.pop(__lowerCamelCase       )
          UpperCAmelCase__      :  Union[str, Any]				      =			rename_keys(__lowerCamelCase       )
          if "in_proj_weight" in key:
               # split fused qkv proj
               UpperCAmelCase__      :  Optional[int]				      =			val[:hidden_size, :]
               UpperCAmelCase__      :  List[Any]				      =			val[hidden_size : 2 * hidden_size, :]
               UpperCAmelCase__      :  Tuple				      =			val[-hidden_size:, :]
          elif "enc_to_dec_proj" in key:
               UpperCAmelCase__      :  Dict				      =			val
          else:
               UpperCAmelCase__      :  Dict				      =			val
     return state_dict, enc_dec_proj_state_dict





def  _lowerCamelCase						(						__lowerCamelCase       ) ->			MusicgenDecoderConfig:

     '''simple docstring'''
     if checkpoint == "small":
          # default config values
          UpperCAmelCase__      :  Union[str, Any]				      =			1024
          UpperCAmelCase__      :  Union[str, Any]				      =			24
          UpperCAmelCase__      :  Dict				      =			16
     elif checkpoint == "medium":
          UpperCAmelCase__      :  Optional[int]				      =			1536
          UpperCAmelCase__      :  int				      =			48
          UpperCAmelCase__      :  Tuple				      =			24
     elif checkpoint == "large":
          UpperCAmelCase__      :  Any				      =			2048
          UpperCAmelCase__      :  Optional[Any]				      =			48
          UpperCAmelCase__      :  List[Any]				      =			32
     else:
          raise ValueError(F"Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}."       )
     UpperCAmelCase__      :  Any				      =			MusicgenDecoderConfig(
         hidden_size=__lowerCamelCase ,							ffn_dim=hidden_size * 4 ,							num_hidden_layers=__lowerCamelCase ,							num_attention_heads=__lowerCamelCase ,							)
     return config





@torch.no_grad()
def  _lowerCamelCase						(						__lowerCamelCase ,							__lowerCamelCase=None ,							__lowerCamelCase=None ,							__lowerCamelCase="cpu"       ) ->			List[Any]:

     '''simple docstring'''
     UpperCAmelCase__      :  List[str]				      =			MusicGen.get_pretrained(__lowerCamelCase ,							device=__lowerCamelCase       )
     UpperCAmelCase__      :  Optional[int]				      =			decoder_config_from_checkpoint(__lowerCamelCase       )

     UpperCAmelCase__      :  List[Any]				      =			fairseq_model.lm.state_dict()
     UpperCAmelCase__      ,		UpperCAmelCase__      :  Dict				      =			rename_state_dict(
         __lowerCamelCase ,							hidden_size=decoder_config.hidden_size       )

     UpperCAmelCase__      :  str				      =			TaEncoderModel.from_pretrained("""t5-base"""       )
     UpperCAmelCase__      :  Tuple				      =			EncodecModel.from_pretrained("""facebook/encodec_32khz"""       )
     UpperCAmelCase__      :  Union[str, Any]				      =			MusicgenForCausalLM(__lowerCamelCase       ).eval()

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

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

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

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

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

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

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

     with torch.no_grad():
          UpperCAmelCase__      :  Any				      =			model(input_ids=__lowerCamelCase ,							decoder_input_ids=__lowerCamelCase       ).logits

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

     # now construct the processor
     UpperCAmelCase__      :  str				      =			AutoTokenizer.from_pretrained("""t5-base"""       )
     UpperCAmelCase__      :  Any				      =			AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" ,							padding_side="""left"""       )

     UpperCAmelCase__      :  Dict				      =			MusicgenProcessor(feature_extractor=__lowerCamelCase ,							tokenizer=__lowerCamelCase       )

     # set the appropriate bos/pad token ids
     UpperCAmelCase__      :  Dict				      =			2048
     UpperCAmelCase__      :  int				      =			2048

     # set other default generation config params
     UpperCAmelCase__      :  Union[str, Any]				      =			int(30 * audio_encoder.config.frame_rate       )
     UpperCAmelCase__      :  Union[str, Any]				      =			True
     UpperCAmelCase__      :  Dict				      =			3.0

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

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


if __name__ == "__main__":
      SCREAMING_SNAKE_CASE__		:							str 				=				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."""
      )

      SCREAMING_SNAKE_CASE__		:							int 				=				parser.parse_args()
      convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)








import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel
from transformers.utils import logging


logging.set_verbosity_info()
lowercase   =	logging.get_logger(__name__)



def   __lowerCAmelCase    (				UpperCAmelCase__					:   int      ,					UpperCAmelCase__					:   Tuple=False							)	->     Optional[Any]:
							lowerCamelCase_					=       []
							for i in range(config.num_hidden_layers							):
														# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
														rename_keys.append((F'''blocks.{i}.norm1.weight''', F'''vit.encoder.layer.{i}.layernorm_before.weight''')							)
														rename_keys.append((F'''blocks.{i}.norm1.bias''', F'''vit.encoder.layer.{i}.layernorm_before.bias''')							)
														rename_keys.append((F'''blocks.{i}.attn.proj.weight''', F'''vit.encoder.layer.{i}.attention.output.dense.weight''')							)
														rename_keys.append((F'''blocks.{i}.attn.proj.bias''', F'''vit.encoder.layer.{i}.attention.output.dense.bias''')							)
														rename_keys.append((F'''blocks.{i}.norm2.weight''', F'''vit.encoder.layer.{i}.layernorm_after.weight''')							)
														rename_keys.append((F'''blocks.{i}.norm2.bias''', F'''vit.encoder.layer.{i}.layernorm_after.bias''')							)
														rename_keys.append((F'''blocks.{i}.mlp.fc1.weight''', F'''vit.encoder.layer.{i}.intermediate.dense.weight''')							)
														rename_keys.append((F'''blocks.{i}.mlp.fc1.bias''', F'''vit.encoder.layer.{i}.intermediate.dense.bias''')							)
														rename_keys.append((F'''blocks.{i}.mlp.fc2.weight''', F'''vit.encoder.layer.{i}.output.dense.weight''')							)
														rename_keys.append((F'''blocks.{i}.mlp.fc2.bias''', F'''vit.encoder.layer.{i}.output.dense.bias''')							)

							# projection layer + position embeddings
							rename_keys.extend(
							    [
							        ("""cls_token""", """vit.embeddings.cls_token"""),
							        ("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""),
							        ("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""),
							        ("""pos_embed""", """vit.embeddings.position_embeddings"""),
							    ]							)

							if base_model:
														# layernorm + pooler
														rename_keys.extend(
														    [
														        ("""norm.weight""", """layernorm.weight"""),
														        ("""norm.bias""", """layernorm.bias"""),
														    ]							)

														# if just the base model, we should remove "vit" from all keys that start with "vit"
														lowerCamelCase_					=       [(pair[0], pair[1][4:]) if pair[1].startswith("""vit"""							) else pair for pair in rename_keys]
							else:
														# layernorm + classification head
														rename_keys.extend(
														    [
														        ("""norm.weight""", """vit.layernorm.weight"""),
														        ("""norm.bias""", """vit.layernorm.bias"""),
														        ("""head.weight""", """classifier.weight"""),
														        ("""head.bias""", """classifier.bias"""),
														    ]							)

							return rename_keys



def   __lowerCAmelCase    (				UpperCAmelCase__					:   List[str]      ,					UpperCAmelCase__					:   Optional[Any]      ,					UpperCAmelCase__					:   Any=False							)	->     int:
							for i in range(config.num_hidden_layers							):
														if base_model:
																					lowerCamelCase_					=       """"""
														else:
																					lowerCamelCase_					=       """vit."""
														# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
														lowerCamelCase_					=       state_dict.pop(F'''blocks.{i}.attn.qkv.weight'''							)
														lowerCamelCase_					=       state_dict.pop(F'''blocks.{i}.attn.qkv.bias'''							)
														# next, add query, keys and values (in that order) to the state dict
														lowerCamelCase_					=       in_proj_weight[
														    : config.hidden_size, :
														]
														lowerCamelCase_					=       in_proj_bias[: config.hidden_size]
														lowerCamelCase_					=       in_proj_weight[
														    config.hidden_size : config.hidden_size * 2, :
														]
														lowerCamelCase_					=       in_proj_bias[
														    config.hidden_size : config.hidden_size * 2
														]
														lowerCamelCase_					=       in_proj_weight[
														    -config.hidden_size :, :
														]
														lowerCamelCase_					=       in_proj_bias[-config.hidden_size :]



def   __lowerCAmelCase    (				UpperCAmelCase__					:   str							)	->     str:
							lowerCamelCase_					=       ["""head.weight""", """head.bias"""]
							for k in ignore_keys:
														state_dict.pop(UpperCAmelCase__      ,					UpperCAmelCase__							)



def   __lowerCAmelCase    (				UpperCAmelCase__					:   Dict      ,					UpperCAmelCase__					:   int      ,					UpperCAmelCase__					:   int							)	->     Tuple:
							lowerCamelCase_					=       dct.pop(UpperCAmelCase__							)
							lowerCamelCase_					=       val



def   __lowerCAmelCase    (				)	->     Any:
							lowerCamelCase_					=       """http://images.cocodataset.org/val2017/000000039769.jpg"""
							lowerCamelCase_					=       Image.open(requests.get(UpperCAmelCase__      ,					stream=UpperCAmelCase__							).raw							)
							return im



@torch.no_grad()
def   __lowerCAmelCase    (				UpperCAmelCase__					:   str      ,					UpperCAmelCase__					:   Optional[int]      ,					UpperCAmelCase__					:   Tuple=True							)	->     Dict:
							lowerCamelCase_					=       ViTConfig()
							# patch_size
							if model_name[-1] == "8":
														lowerCamelCase_					=       8
							# set labels if required
							if not base_model:
														lowerCamelCase_					=       1_0_0_0
														lowerCamelCase_					=       """huggingface/label-files"""
														lowerCamelCase_					=       """imagenet-1k-id2label.json"""
														lowerCamelCase_					=       json.load(open(hf_hub_download(UpperCAmelCase__      ,					UpperCAmelCase__      ,					repo_type="""dataset"""							)      ,					"""r"""							)							)
														lowerCamelCase_					=       {int(UpperCAmelCase__							): v for k, v in idalabel.items()}
														lowerCamelCase_					=       idalabel
														lowerCamelCase_					=       {v: k for k, v in idalabel.items()}
							# size of the architecture
							if model_name in ["dino_vits8", "dino_vits16"]:
														lowerCamelCase_					=       3_8_4
														lowerCamelCase_					=       1_5_3_6
														lowerCamelCase_					=       1_2
														lowerCamelCase_					=       6

							# load original model from torch hub
							lowerCamelCase_					=       torch.hub.load("""facebookresearch/dino:main"""      ,					UpperCAmelCase__							)
							original_model.eval()

							# load state_dict of original model, remove and rename some keys
							lowerCamelCase_					=       original_model.state_dict()
							if base_model:
														remove_classification_head_(UpperCAmelCase__							)
							lowerCamelCase_					=       create_rename_keys(UpperCAmelCase__      ,					base_model=UpperCAmelCase__							)
							for src, dest in rename_keys:
														rename_key(UpperCAmelCase__      ,					UpperCAmelCase__      ,					UpperCAmelCase__							)
							read_in_q_k_v(UpperCAmelCase__      ,					UpperCAmelCase__      ,					UpperCAmelCase__							)

							# load HuggingFace model
							if base_model:
														lowerCamelCase_					=       ViTModel(UpperCAmelCase__      ,					add_pooling_layer=UpperCAmelCase__							).eval()
							else:
														lowerCamelCase_					=       ViTForImageClassification(UpperCAmelCase__							).eval()
							model.load_state_dict(UpperCAmelCase__							)

							# Check outputs on an image, prepared by ViTImageProcessor
							lowerCamelCase_					=       ViTImageProcessor()
							lowerCamelCase_					=       image_processor(images=prepare_img()      ,					return_tensors="""pt"""							)
							lowerCamelCase_					=       encoding["""pixel_values"""]
							lowerCamelCase_					=       model(UpperCAmelCase__							)

							if base_model:
														lowerCamelCase_					=       original_model(UpperCAmelCase__							)
														assert torch.allclose(UpperCAmelCase__      ,					outputs.last_hidden_state[:, 0, :]      ,					atol=1e-1							)
							else:
														lowerCamelCase_					=       original_model(UpperCAmelCase__							)
														assert logits.shape == outputs.logits.shape
														assert torch.allclose(UpperCAmelCase__      ,					outputs.logits      ,					atol=1e-3							)

							Path(UpperCAmelCase__							).mkdir(exist_ok=UpperCAmelCase__							)
							print(F'''Saving model {model_name} to {pytorch_dump_folder_path}'''							)
							model.save_pretrained(UpperCAmelCase__							)
							print(F'''Saving image processor to {pytorch_dump_folder_path}'''							)
							image_processor.save_pretrained(UpperCAmelCase__							)


if __name__ == "__main__":
		lowercase   =	argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    '''--model_name''',
		    default='''dino_vitb16''',
		    type=str,
		    help='''Name of the model trained with DINO you\'d like to convert.''',
		)
		parser.add_argument(
		    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
		)
		parser.add_argument(
		    '''--base_model''',
		    action='''store_true''',
		    help='''Whether to only convert the base model (no projection head weights).''',
		)

		parser.set_defaults(base_model=True)
		lowercase   =	parser.parse_args()
		convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)





