






import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')

require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/text-classification/requirements.txt''')

UpperCAmelCase__      			=						logging.getLogger(__name__)




@dataclass
class 							snake_case_       :

						"""simple docstring"""



						snake_case__        =      field(
						    default=128		,							metadata={
						        """help""": (
						            """The maximum total input sequence length after tokenization. Sequences longer """
						            """than this will be truncated, sequences shorter will be padded."""
						        )
						    }		,							)
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}      )
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={
						        """help""": (
						            """Whether to pad all samples to `max_seq_length`. """
						            """If False, will pad the samples dynamically when batching to the maximum length in the batch."""
						        )
						    }		,							)
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={
						        """help""": (
						            """For debugging purposes or quicker training, truncate the number of training examples to this """
						            """value if set."""
						        )
						    }		,							)
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={
						        """help""": (
						            """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
						            """value if set."""
						        )
						    }		,							)
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={
						        """help""": (
						            """For debugging purposes or quicker training, truncate the number of prediction examples to this """
						            """value if set."""
						        )
						    }		,							)




@dataclass
class 							snake_case_       :

						"""simple docstring"""



						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}      )
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={"""help""": """Evaluation language. Also train language if `train_language` is set to None."""}      )
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={"""help""": """Train language if it is different from the evaluation language."""}      )
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}      )
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}      )
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}		,							)
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={"""help""": """arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"""}		,							)
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""}		,							)
						snake_case__        =      field(
						    default="""main"""		,							metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}		,							)
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={
						        """help""": (
						            """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
						            """with private models)."""
						        )
						    }		,							)
						snake_case__        =      field(
						    default=_UpperCamelCase		,							metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""}		,							)







def     a_   ()				->						Dict:



					"""simple docstring"""
					__a					:						Tuple      =					HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)      )
					__a					:						str      =					parser.parse_args_into_dataclasses()

					# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
					# information sent is the one passed as arguments along with your Python/PyTorch versions.
					send_example_telemetry("run_xnli"				,       lowercase_      )

					# Setup logging
					logging.basicConfig(
					    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"				,       datefmt="%m/%d/%Y %H:%M:%S"				,       handlers=[logging.StreamHandler(sys.stdout      )]				,       )

					if training_args.should_log:
										# The default of training_args.log_level is passive, so we set log level at info here to have that default.
										transformers.utils.logging.set_verbosity_info()

					__a					:						str      =					training_args.get_process_log_level()
					logger.setLevel(lowercase_      )
					datasets.utils.logging.set_verbosity(lowercase_      )
					transformers.utils.logging.set_verbosity(lowercase_      )
					transformers.utils.logging.enable_default_handler()
					transformers.utils.logging.enable_explicit_format()

					# Log on each process the small summary:
					logger.warning(
					    f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'
					    + f'distributed training: {bool(training_args.local_rank != -1      )}, 16-bits training: {training_args.fpaa}'      )
					logger.info(f'Training/evaluation parameters {training_args}'      )

					# Detecting last checkpoint.
					__a					:						Optional[Any]      =					None
					if os.path.isdir(training_args.output_dir      ) and training_args.do_train and not training_args.overwrite_output_dir:
										__a					:						List[str]      =					get_last_checkpoint(training_args.output_dir      )
										if last_checkpoint is None and len(os.listdir(training_args.output_dir      )      ) > 0:
															raise ValueError(
															    f'Output directory ({training_args.output_dir}) already exists and is not empty. '
															    "Use --overwrite_output_dir to overcome."      )
										elif last_checkpoint is not None:
															logger.info(
															    f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '
															    "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."      )

    # Set seed before initializing model.
					set_seed(training_args.seed      )

					# In distributed training, the load_dataset function guarantees that only one local process can concurrently
					# download the dataset.
					# Downloading and loading xnli dataset from the hub.
					if training_args.do_train:
										if model_args.train_language is None:
															__a					:						List[Any]      =					load_dataset(
															    "xnli"				,       model_args.language				,       split="train"				,       cache_dir=model_args.cache_dir				,       use_auth_token=True if model_args.use_auth_token else None				,       )
										else:
															__a					:						Optional[int]      =					load_dataset(
															    "xnli"				,       model_args.train_language				,       split="train"				,       cache_dir=model_args.cache_dir				,       use_auth_token=True if model_args.use_auth_token else None				,       )
										__a					:						str      =					train_dataset.features["label"].names

					if training_args.do_eval:
										__a					:						int      =					load_dataset(
										    "xnli"				,       model_args.language				,       split="validation"				,       cache_dir=model_args.cache_dir				,       use_auth_token=True if model_args.use_auth_token else None				,       )
										__a					:						List[Any]      =					eval_dataset.features["label"].names

					if training_args.do_predict:
										__a					:						int      =					load_dataset(
										    "xnli"				,       model_args.language				,       split="test"				,       cache_dir=model_args.cache_dir				,       use_auth_token=True if model_args.use_auth_token else None				,       )
										__a					:						List[str]      =					predict_dataset.features["label"].names

					# Labels
					__a					:						List[Any]      =					len(lowercase_      )

					# Load pretrained model and tokenizer
					# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
					# download model & vocab.
					__a					:						Any      =					AutoConfig.from_pretrained(
					    model_args.config_name if model_args.config_name else model_args.model_name_or_path				,       num_labels=lowercase_				,       idalabel={str(lowercase_      ): label for i, label in enumerate(lowercase_      )}				,       labelaid={label: i for i, label in enumerate(lowercase_      )}				,       finetuning_task="xnli"				,       cache_dir=model_args.cache_dir				,       revision=model_args.model_revision				,       use_auth_token=True if model_args.use_auth_token else None				,       )
					__a					:						Optional[Any]      =					AutoTokenizer.from_pretrained(
					    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path				,       do_lower_case=model_args.do_lower_case				,       cache_dir=model_args.cache_dir				,       use_fast=model_args.use_fast_tokenizer				,       revision=model_args.model_revision				,       use_auth_token=True if model_args.use_auth_token else None				,       )
					__a					:						List[str]      =					AutoModelForSequenceClassification.from_pretrained(
					    model_args.model_name_or_path				,       from_tf=bool(".ckpt" in model_args.model_name_or_path      )				,       config=lowercase_				,       cache_dir=model_args.cache_dir				,       revision=model_args.model_revision				,       use_auth_token=True if model_args.use_auth_token else None				,       ignore_mismatched_sizes=model_args.ignore_mismatched_sizes				,       )

					# Preprocessing the datasets
					# Padding strategy
					if data_args.pad_to_max_length:
										__a					:						Any      =					"max_length"
					else:
										# We will pad later, dynamically at batch creation, to the max sequence length in each batch
										__a					:						Optional[Any]      =					False

					def preprocess_function(__A      ):
										# Tokenize the texts
										return tokenizer(
										    examples["premise"]				,       examples["hypothesis"]				,       padding=lowercase_				,       max_length=data_args.max_seq_length				,       truncation=lowercase_				,       )

					if training_args.do_train:
										if data_args.max_train_samples is not None:
															__a					:						Optional[Any]      =					min(len(lowercase_      )				,       data_args.max_train_samples      )
															__a					:						Optional[Any]      =					train_dataset.select(range(lowercase_      )      )
										with training_args.main_process_first(desc="train dataset map pre-processing"      ):
															__a					:						Union[str, Any]      =					train_dataset.map(
															    lowercase_				,       batched=lowercase_				,       load_from_cache_file=not data_args.overwrite_cache				,       desc="Running tokenizer on train dataset"				,       )
										# Log a few random samples from the training set:
										for index in random.sample(range(len(lowercase_      )      )				,       3      ):
															logger.info(f'Sample {index} of the training set: {train_dataset[index]}.'      )

					if training_args.do_eval:
										if data_args.max_eval_samples is not None:
															__a					:						List[Any]      =					min(len(lowercase_      )				,       data_args.max_eval_samples      )
															__a					:						str      =					eval_dataset.select(range(lowercase_      )      )
										with training_args.main_process_first(desc="validation dataset map pre-processing"      ):
															__a					:						Dict      =					eval_dataset.map(
															    lowercase_				,       batched=lowercase_				,       load_from_cache_file=not data_args.overwrite_cache				,       desc="Running tokenizer on validation dataset"				,       )

					if training_args.do_predict:
										if data_args.max_predict_samples is not None:
															__a					:						Optional[int]      =					min(len(lowercase_      )				,       data_args.max_predict_samples      )
															__a					:						int      =					predict_dataset.select(range(lowercase_      )      )
										with training_args.main_process_first(desc="prediction dataset map pre-processing"      ):
															__a					:						Union[str, Any]      =					predict_dataset.map(
															    lowercase_				,       batched=lowercase_				,       load_from_cache_file=not data_args.overwrite_cache				,       desc="Running tokenizer on prediction dataset"				,       )

    # Get the metric function
					__a					:						Union[str, Any]      =					evaluate.load("xnli"      )

					# You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
					# predictions and label_ids field) and has to return a dictionary string to float.
					def compute_metrics(__A      ):
										__a					:						int      =					p.predictions[0] if isinstance(p.predictions				,       lowercase_      ) else p.predictions
										__a					:						Union[str, Any]      =					np.argmax(lowercase_				,       axis=1      )
										return metric.compute(predictions=lowercase_				,       references=p.label_ids      )

					# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
					if data_args.pad_to_max_length:
										__a					:						str      =					default_data_collator
					elif training_args.fpaa:
										__a					:						Tuple      =					DataCollatorWithPadding(lowercase_				,       pad_to_multiple_of=8      )
					else:
										__a					:						List[Any]      =					None

					# Initialize our Trainer
					__a					:						List[str]      =					Trainer(
					    model=lowercase_				,       args=lowercase_				,       train_dataset=train_dataset if training_args.do_train else None				,       eval_dataset=eval_dataset if training_args.do_eval else None				,       compute_metrics=lowercase_				,       tokenizer=lowercase_				,       data_collator=lowercase_				,       )

					# Training
					if training_args.do_train:
										__a					:						str      =					None
										if training_args.resume_from_checkpoint is not None:
															__a					:						Optional[Any]      =					training_args.resume_from_checkpoint
										elif last_checkpoint is not None:
															__a					:						Optional[Any]      =					last_checkpoint
										__a					:						Optional[Any]      =					trainer.train(resume_from_checkpoint=lowercase_      )
										__a					:						Tuple      =					train_result.metrics
										__a					:						Optional[Any]      =					(
										    data_args.max_train_samples if data_args.max_train_samples is not None else len(lowercase_      )
										)
										__a					:						Tuple      =					min(lowercase_				,       len(lowercase_      )      )

										trainer.save_model()  # Saves the tokenizer too for easy upload

										trainer.log_metrics("train"				,       lowercase_      )
										trainer.save_metrics("train"				,       lowercase_      )
										trainer.save_state()

					# Evaluation
					if training_args.do_eval:
										logger.info("*** Evaluate ***"      )
										__a					:						Union[str, Any]      =					trainer.evaluate(eval_dataset=lowercase_      )

										__a					:						Optional[Any]      =					data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowercase_      )
										__a					:						Dict      =					min(lowercase_				,       len(lowercase_      )      )

										trainer.log_metrics("eval"				,       lowercase_      )
										trainer.save_metrics("eval"				,       lowercase_      )

					# Prediction
					if training_args.do_predict:
										logger.info("*** Predict ***"      )
										__a					:						Tuple      =					trainer.predict(lowercase_				,       metric_key_prefix="predict"      )

										__a					:						Tuple      =					(
										    data_args.max_predict_samples if data_args.max_predict_samples is not None else len(lowercase_      )
										)
										__a					:						Dict      =					min(lowercase_				,       len(lowercase_      )      )

										trainer.log_metrics("predict"				,       lowercase_      )
										trainer.save_metrics("predict"				,       lowercase_      )

										__a					:						Dict      =					np.argmax(lowercase_				,       axis=1      )
										__a					:						List[Any]      =					os.path.join(training_args.output_dir				,       "predictions.txt"      )
										if trainer.is_world_process_zero():
															with open(lowercase_				,       "w"      ) as writer:
																				writer.write("index\tprediction\n"      )
																				for index, item in enumerate(lowercase_      ):
																									__a					:						int      =					label_list[item]
																									writer.write(f'{index}\t{item}\n'      )


if __name__ == "__main__":
			main()












"""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__						= logging.get_logger(__name__)


lowerCamelCase__						= ["model.decoder.embed_positions.weights"]




def        lowercase__     (       lowercase_      )       ->		Dict:




      """simple docstring"""

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




def        lowercase__     (       lowercase_		,lowercase_      )       ->		Tuple[Dict, Dict]:




      """simple docstring"""

      _UpperCamelCase   :						List[Any]    =							list(state_dict.keys()      )
      _UpperCamelCase   :						int    =							{}
      for key in keys:
            _UpperCamelCase   :						List[str]    =							state_dict.pop(lowercase_      )
            _UpperCamelCase   :						List[Any]    =							rename_keys(lowercase_      )
            if "in_proj_weight" in key:
                  # split fused qkv proj
                  _UpperCamelCase   :						List[Any]    =							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   :						Optional[Any]    =							val
            else:
                  _UpperCamelCase   :						str    =							val
      return state_dict, enc_dec_proj_state_dict




def        lowercase__     (       lowercase_      )       ->		MusicgenDecoderConfig:




      """simple docstring"""

      if checkpoint == "small":
            # default config values
            _UpperCamelCase   :						Optional[Any]    =							1_024
            _UpperCamelCase   :						List[str]    =							24
            _UpperCamelCase   :						Optional[int]    =							16
      elif checkpoint == "medium":
            _UpperCamelCase   :						int    =							1_536
            _UpperCamelCase   :						Any    =							48
            _UpperCamelCase   :						Optional[Any]    =							24
      elif checkpoint == "large":
            _UpperCamelCase   :						int    =							2_048
            _UpperCamelCase   :						Dict    =							48
            _UpperCamelCase   :						Dict    =							32
      else:
            raise ValueError(F'''Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.'''      )
      _UpperCamelCase   :						List[Any]    =							MusicgenDecoderConfig(
          hidden_size=lowercase_		,ffn_dim=hidden_size * 4		,num_hidden_layers=lowercase_		,num_attention_heads=lowercase_		,)
      return config




@torch.no_grad()
def        lowercase__     (       lowercase_		,lowercase_=None		,lowercase_=None		,lowercase_="cpu"      )       ->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase   :						int    =							MusicGen.get_pretrained(lowercase_		,device=lowercase_      )
      _UpperCamelCase   :						int    =							decoder_config_from_checkpoint(lowercase_      )

      _UpperCamelCase   :						int    =							fairseq_model.lm.state_dict()
      _UpperCamelCase,	_UpperCamelCase   :						Tuple    =							rename_state_dict(
          lowercase_		,hidden_size=decoder_config.hidden_size      )

      _UpperCamelCase   :						int    =							TaEncoderModel.from_pretrained("t5-base"      )
      _UpperCamelCase   :						str    =							EncodecModel.from_pretrained("facebook/encodec_32khz"      )
      _UpperCamelCase   :						Dict    =							MusicgenForCausalLM(lowercase_      ).eval()

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

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

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

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

      # init the composite model
      _UpperCamelCase   :						Tuple    =							MusicgenForConditionalGeneration(text_encoder=lowercase_		,audio_encoder=lowercase_		,decoder=lowercase_      )

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

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

      with torch.no_grad():
            _UpperCamelCase   :						List[str]    =							model(input_ids=lowercase_		,decoder_input_ids=lowercase_      ).logits

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

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

      _UpperCamelCase   :						Any    =							MusicgenProcessor(feature_extractor=lowercase_		,tokenizer=lowercase_      )

      # set the appropriate bos/pad token ids
      _UpperCamelCase   :						Optional[Any]    =							2_048
      _UpperCamelCase   :						str    =							2_048

      # set other default generation config params
      _UpperCamelCase   :						Optional[int]    =							int(30 * audio_encoder.config.frame_rate      )
      _UpperCamelCase   :						Optional[Any]    =							True
      _UpperCamelCase   :						Any    =							3.0

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

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


if __name__ == "__main__":
  lowerCamelCase__						= 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__						= parser.parse_args()
  convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
