






import itertools
import os
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed

import numpy as np

import datasets

from .execute import check_correctness


_UpperCamelCase			:	Tuple								='\\n@misc{chen2021evaluating,\n      title={Evaluating Large Language Models Trained on Code},\n      author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n      year={2021},\n      eprint={2107.03374},\n      archivePrefix={arXiv},\n      primaryClass={cs.LG}\n}\n'

_UpperCamelCase			:	Tuple								='\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper "Evaluating Large Language Models Trained on Code"\n(https://arxiv.org/abs/2107.03374).\n'


_UpperCamelCase			:	Any								='\nCalculates how good are predictions given some references, using certain scores\nArgs:\n    predictions: list of candidates to evaluate. Each candidates should be a list\n        of strings with several code candidates to solve the problem.\n    references: a list with a test for each prediction. Each test should evaluate the\n        correctness of a code candidate.\n    k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n    num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n    timeout:\nReturns:\n    pass_at_k: dict with pass rates for each k\n    results: dict with granular results of each unittest\nExamples:\n    >>> code_eval = datasets.load_metric("code_eval")\n    >>> test_cases = ["assert add(2,3)==5"]\n    >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]\n    >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n    >>> print(pass_at_k)\n    {\'pass@1\': 0.5, \'pass@2\': 1.0}\n'


_UpperCamelCase			:	Optional[Any]								='\n################################################################################\n                                  !!!WARNING!!!\n################################################################################\nThe "code_eval" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper "Evaluating Large\nLanguage Models Trained on Code" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"\n\n################################################################################\\n'

_UpperCamelCase			:	Tuple								='The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.'






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,				_KWARGS_DESCRIPTION							)
class 						UpperCAmelCase__ (							datasets.Metric							):







		def  A__      (					self		):
						return datasets.MetricInfo(
						    # This is the description that will appear on the metrics page.
						    description=_DESCRIPTION       ,citation=_CITATION       ,inputs_description=_KWARGS_DESCRIPTION       ,features=datasets.Features(
						        {
						            '''predictions''': datasets.Sequence(datasets.Value('''string'''		)		),
						            '''references''': datasets.Value('''string'''		),
						        }		)       ,homepage='''https://github.com/openai/human-eval'''       ,codebase_urls=['''https://github.com/openai/human-eval''']       ,reference_urls=['''https://github.com/openai/human-eval''']       ,license=_LICENSE       ,)







		def  A__      (					self       ,A__       ,A__       ,A__=[1, 10, 100]       ,A__=4       ,A__=3.0		):

						if os.getenv('''HF_ALLOW_CODE_EVAL'''       ,0		) != "1":
										raise ValueError(_WARNING		)

						if os.name == "nt":
										raise NotImplementedError('''This metric is currently not supported on Windows.'''		)

						with ThreadPoolExecutor(max_workers=A__		) as executor:
										_A	:				Any   =      []
										_A	:				List[Any]   =      Counter()
										_A	:				Optional[Any]   =      0
										_A	:				Any   =      defaultdict(A__		)

										for task_id, (candidates, test_case) in enumerate(zip(A__       ,A__		)		):
														for candidate in candidates:
																		_A	:				List[str]   =      candidate + '''\n''' + test_case
																		_A	:				Any   =      (test_program, timeout, task_id, completion_id[task_id])
																		_A	:				Union[str, Any]   =      executor.submit(A__       ,*A__		)
																		futures.append(A__		)
																		completion_id[task_id] += 1
																		n_samples += 1

										for future in as_completed(A__		):
														_A	:				List[str]   =      future.result()
														results[result["task_id"]].append((result['''completion_id'''], result)		)

						_A  ,				_A	:				str   =      [], []
						for result in results.values():
										result.sort()
										_A	:				Optional[Any]   =      [r[1]['''passed'''] for r in result]
										total.append(len(A__		)		)
										correct.append(sum(A__		)		)
						_A	:				int   =      np.array(A__		)
						_A	:				Dict   =      np.array(A__		)

						_A	:				Optional[Any]   =      k
						_A	:				Union[str, Any]   =      {f"""pass@{k}""": estimate_pass_at_k(A__       ,A__       ,A__		).mean() for k in ks if (total >= k).all()}

						return pass_at_k, results



def  a__ (__lowercase							:List[Any]					,  __lowercase							:Union[str, Any]					,  __lowercase							:Any   )		-> List[Any]:

				def estimator(__lowercase							:int					,  __lowercase							:int					,  __lowercase							:int   ) -> float:
								if n - c < k:
												return 1.0
								return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1					,  n + 1   )   )

				if isinstance(__lowercase					,  __lowercase   ):
								_A	:				Optional[Any]   =      itertools.repeat(__lowercase					,  len(__lowercase   )   )
				else:
								assert len(__lowercase   ) == len(__lowercase   )
								_A	:				Dict   =      iter(__lowercase   )

				return np.array([estimator(int(__lowercase   )					,  int(__lowercase   )					,  __lowercase   ) for n, c in zip(__lowercase					,  __lowercase   )]   )











import argparse
import os
from pathlib import Path

import torch
from bark.generation import _load_model as _bark_load_model
from huggingface_hub import hf_hub_download

from transformers import EncodecConfig, EncodecModel, set_seed
from transformers.models.bark.configuration_bark import (
    BarkCoarseConfig,
    BarkConfig,
    BarkFineConfig,
    BarkSemanticConfig,
)
from transformers.models.bark.generation_configuration_bark import (
    BarkCoarseGenerationConfig,
    BarkFineGenerationConfig,
    BarkGenerationConfig,
    BarkSemanticGenerationConfig,
)
from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel
from transformers.utils import logging


logging.set_verbosity_info()
_UpperCamelCase			:	Any								=logging.get_logger(__name__)

set_seed(770)


_UpperCamelCase			:	List[Any]								={
    'c_attn': 'att_proj',
    'c_proj': 'out_proj',
    'c_fc': 'in_proj',
    'transformer.': '',
    'h.': 'layers.',
    'ln_1': 'layernorm_1',
    'ln_2': 'layernorm_2',
    'ln_f': 'layernorm_final',
    'wpe': 'position_embeds_layer',
    'wte': 'input_embeds_layer',
}


_UpperCamelCase			:	Tuple								={
    'text_small': {
        'repo_id': 'suno/bark',
        'file_name': 'text.pt',
    },
    'coarse_small': {
        'repo_id': 'suno/bark',
        'file_name': 'coarse.pt',
    },
    'fine_small': {
        'repo_id': 'suno/bark',
        'file_name': 'fine.pt',
    },
    'text': {
        'repo_id': 'suno/bark',
        'file_name': 'text_2.pt',
    },
    'coarse': {
        'repo_id': 'suno/bark',
        'file_name': 'coarse_2.pt',
    },
    'fine': {
        'repo_id': 'suno/bark',
        'file_name': 'fine_2.pt',
    },
}

_UpperCamelCase			:	Any								=os.path.dirname(os.path.abspath(__file__))
_UpperCamelCase			:	Tuple								=os.path.join(os.path.expanduser('~'), '.cache')
_UpperCamelCase			:	Dict								=os.path.join(os.getenv('XDG_CACHE_HOME', default_cache_dir), 'suno', 'bark_v0')



def  a__ (__lowercase							:int					,  __lowercase							:Any=False   )		-> Union[str, Any]:
				_A	:				str   =      model_type
				if use_small:
								key += "_small"
				return os.path.join(__lowercase					,  REMOTE_MODEL_PATHS[key]['''file_name''']   )



def  a__ (__lowercase							:str					,  __lowercase							:Optional[Any]   )		-> Dict:
				os.makedirs(__lowercase					,  exist_ok=__lowercase   )
				hf_hub_download(repo_id=__lowercase					,  filename=__lowercase					,  local_dir=__lowercase   )



def  a__ (__lowercase							:Union[str, Any]					,  __lowercase							:List[str]					,  __lowercase							:str=False					,  __lowercase							:int="text"   )		-> int:
				if model_type == "text":
								_A	:				Optional[Any]   =      BarkSemanticModel
								_A	:				Any   =      BarkSemanticConfig
								_A	:				Dict   =      BarkSemanticGenerationConfig
				elif model_type == "coarse":
								_A	:				Dict   =      BarkCoarseModel
								_A	:				str   =      BarkCoarseConfig
								_A	:				int   =      BarkCoarseGenerationConfig
				elif model_type == "fine":
								_A	:				str   =      BarkFineModel
								_A	:				Optional[Any]   =      BarkFineConfig
								_A	:				int   =      BarkFineGenerationConfig
				else:
								raise NotImplementedError()
				_A	:				Dict   =      f"""{model_type}_small""" if use_small else model_type
				_A	:				Tuple   =      REMOTE_MODEL_PATHS[model_key]
				if not os.path.exists(__lowercase   ):
								logger.info(f"""{model_type} model not found, downloading into `{CACHE_DIR}`."""   )
								_download(model_info['''repo_id''']					,  model_info['''file_name''']   )
				_A	:				Optional[int]   =      torch.load(__lowercase					,  map_location=__lowercase   )
				# this is a hack
				_A	:				Any   =      checkpoint['''model_args''']
				if "input_vocab_size" not in model_args:
								_A	:				Optional[Any]   =      model_args['''vocab_size''']
								_A	:				Dict   =      model_args['''vocab_size''']
								del model_args["vocab_size"]

				# convert Bark model arguments to HF Bark model arguments
				_A	:				List[str]   =      model_args.pop('''n_head'''   )
				_A	:				int   =      model_args.pop('''n_embd'''   )
				_A	:				Tuple   =      model_args.pop('''n_layer'''   )

				_A	:				Dict   =      ConfigClass(**checkpoint['''model_args''']   )
				_A	:				Optional[Any]   =      ModelClass(config=__lowercase   )
				_A	:				Optional[Any]   =      GenerationConfigClass()

				_A	:				Dict   =      model_generation_config
				_A	:				int   =      checkpoint['''model''']
				# fixup checkpoint
				_A	:				str   =      '''_orig_mod.'''
				for k, v in list(state_dict.items()   ):
								if k.startswith(__lowercase   ):
												# replace part of the key with corresponding layer name in HF implementation
												_A	:				Optional[Any]   =      k[len(__lowercase   ) :]
												for old_layer_name in new_layer_name_dict:
																_A	:				Any   =      new_k.replace(__lowercase					,  new_layer_name_dict[old_layer_name]   )

												_A	:				str   =      state_dict.pop(__lowercase   )

				_A	:				List[str]   =      set(state_dict.keys()   ) - set(model.state_dict().keys()   )
				_A	:				List[Any]   =      {k for k in extra_keys if not k.endswith('''.attn.bias'''   )}
				_A	:				Union[str, Any]   =      set(model.state_dict().keys()   ) - set(state_dict.keys()   )
				_A	:				Any   =      {k for k in missing_keys if not k.endswith('''.attn.bias'''   )}
				if len(__lowercase   ) != 0:
								raise ValueError(f"""extra keys found: {extra_keys}"""   )
				if len(__lowercase   ) != 0:
								raise ValueError(f"""missing keys: {missing_keys}"""   )
				model.load_state_dict(__lowercase					,  strict=__lowercase   )
				_A	:				int   =      model.num_parameters(exclude_embeddings=__lowercase   )
				_A	:				Tuple   =      checkpoint['''best_val_loss'''].item()
				logger.info(f"""model loaded: {round(n_params/1e6					,  1   )}M params, {round(__lowercase					,  3   )} loss"""   )
				model.eval()
				model.to(__lowercase   )
				del checkpoint, state_dict

				return model



def  a__ (__lowercase							:Union[str, Any]					,  __lowercase							:Any=False					,  __lowercase							:Optional[int]="text"   )		-> Dict:
				if model_type not in ("text", "coarse", "fine"):
								raise NotImplementedError()

				_A	:				List[str]   =      '''cpu'''  # do conversion on cpu

				_A	:				Tuple   =      _get_ckpt_path(__lowercase					,  use_small=__lowercase   )
				_A	:				Any   =      _load_model(__lowercase					,  __lowercase					,  model_type=__lowercase					,  use_small=__lowercase   )

				# load bark initial model
				_A	:				Union[str, Any]   =      _bark_load_model(__lowercase					,  '''cpu'''					,  model_type=__lowercase					,  use_small=__lowercase   )

				if model_type == "text":
								_A	:				Any   =      bark_model['''model''']

				if model.num_parameters(exclude_embeddings=__lowercase   ) != bark_model.get_num_params():
								raise ValueError('''initial and new models don\'t have the same number of parameters'''   )

				# check if same output as the bark model
				_A	:				List[str]   =      5
				_A	:				List[str]   =      10

				if model_type in ["text", "coarse"]:
								_A	:				str   =      torch.randint(256					,  (batch_size, sequence_length)					,  dtype=torch.int   )
								_A	:				Any   =      bark_model(__lowercase   )[0]

								_A	:				Optional[Any]   =      model(__lowercase   )

								# take last logits
								_A	:				Dict   =      output_new_model_total.logits[:, [-1], :]

				else:
								_A	:				str   =      3
								_A	:				List[str]   =      8
								_A	:				List[Any]   =      torch.randint(256					,  (batch_size, sequence_length, n_codes_total)					,  dtype=torch.int   )

								_A	:				List[str]   =      model(__lowercase					,  __lowercase   )
								_A	:				Dict   =      bark_model(__lowercase					,  __lowercase   )

								_A	:				Optional[Any]   =      output_new_model_total.logits

				# output difference should come from the difference of self-attention implementation design
				if output_new_model.shape != output_old_model.shape:
								raise ValueError('''initial and new outputs don\'t have the same shape'''   )
				if (output_new_model - output_old_model).abs().max().item() > 1e-3:
								raise ValueError('''initial and new outputs are not equal'''   )

				Path(__lowercase   ).mkdir(exist_ok=__lowercase   )
				model.save_pretrained(__lowercase   )



def  a__ (__lowercase							:Dict					,  __lowercase							:List[str]					,  __lowercase							:Union[str, Any]					,  __lowercase							:Dict					,  __lowercase							:List[Any]					,  __lowercase							:Optional[int]					,  )		-> Union[str, Any]:
				_A	:				List[Any]   =      os.path.join(__lowercase					,  __lowercase   )

				_A	:				List[str]   =      BarkSemanticConfig.from_pretrained(os.path.join(__lowercase					,  '''config.json'''   )   )
				_A	:				List[Any]   =      BarkCoarseConfig.from_pretrained(os.path.join(__lowercase					,  '''config.json'''   )   )
				_A	:				Optional[int]   =      BarkFineConfig.from_pretrained(os.path.join(__lowercase					,  '''config.json'''   )   )
				_A	:				Any   =      EncodecConfig.from_pretrained('''facebook/encodec_24khz'''   )

				_A	:				str   =      BarkSemanticModel.from_pretrained(__lowercase   )
				_A	:				Tuple   =      BarkCoarseModel.from_pretrained(__lowercase   )
				_A	:				List[str]   =      BarkFineModel.from_pretrained(__lowercase   )
				_A	:				Union[str, Any]   =      EncodecModel.from_pretrained('''facebook/encodec_24khz'''   )

				_A	:				Tuple   =      BarkConfig.from_sub_model_configs(
				    __lowercase					,  __lowercase					,  __lowercase					,  __lowercase   )

				_A	:				Tuple   =      BarkGenerationConfig.from_sub_model_configs(
				    semantic.generation_config					,  coarseAcoustic.generation_config					,  fineAcoustic.generation_config   )

				_A	:				Tuple   =      BarkModel(__lowercase   )

				_A	:				Optional[Any]   =      semantic
				_A	:				List[Any]   =      coarseAcoustic
				_A	:				int   =      fineAcoustic
				_A	:				List[Any]   =      codec

				_A	:				Optional[Any]   =      bark_generation_config

				Path(__lowercase   ).mkdir(exist_ok=__lowercase   )
				bark.save_pretrained(__lowercase					,  repo_id=__lowercase					,  push_to_hub=__lowercase   )


if __name__ == "__main__":
	_UpperCamelCase			:	str								=argparse.ArgumentParser()
	# Required parameters

	parser.add_argument('model_type', type=str, help='text, coarse or fine.')
	parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
	parser.add_argument('--is_small', action='store_true', help='convert the small version instead of the large.')

	_UpperCamelCase			:	Dict								=parser.parse_args()

	load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)



