"""simple docstring"""




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


__lowerCAmelCase    :							str													=						"\\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"

__lowerCAmelCase    :							Dict													=						"\\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"


__lowerCAmelCase    :							List[str]													=						"\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"


__lowerCAmelCase    :							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"

__lowerCAmelCase    :							Any													=						"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       a_      (     datasets.Metric			):




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Union[str, Any]     ):
							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 						_SCREAMING_SNAKE_CASE						(	self						:     Optional[int]  ,						snake_case__						:     List[str]  ,						snake_case__						:     List[str]  ,						snake_case__						:     Union[str, Any]=[1, 10, 100]  ,						snake_case__						:     List[Any]=4  ,						snake_case__						:     List[Any]=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:
									lowerCAmelCase__        =   []
									lowerCAmelCase__        =   Counter()
									lowerCAmelCase__        =   0
									lowerCAmelCase__        =   defaultdict(a_     )

									for task_id, (candidates, test_case) in enumerate(zip(a_  ,						a_     )     ):
											for candidate in candidates:
													lowerCAmelCase__        =   candidate + "\n" + test_case
													lowerCAmelCase__        =   (test_program, timeout, task_id, completion_id[task_id])
													lowerCAmelCase__        =   executor.submit(a_  ,						*a_     )
													futures.append(a_     )
													completion_id[task_id] += 1
													n_samples += 1

									for future in as_completed(a_     ):
											lowerCAmelCase__        =   future.result()
											results[result["task_id"]].append((result["""completion_id"""], result)     )

							lowerCAmelCase__        =   [], []
							for result in results.values():
									result.sort()
									lowerCAmelCase__        =   [r[1]["passed"] for r in result]
									total.append(len(a_     )     )
									correct.append(sum(a_     )     )
							lowerCAmelCase__        =   np.array(a_     )
							lowerCAmelCase__        =   np.array(a_     )

							lowerCAmelCase__        =   k
							lowerCAmelCase__        =   {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 							_UpperCAmelCase		(       lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__     ):





		"""simple docstring"""




		def estimator(lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__     ) -> 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(lowerCAmelCase_			,  lowerCAmelCase_     ):
				lowerCAmelCase__        =   itertools.repeat(lowerCAmelCase_			,  len(lowerCAmelCase_     )     )
		else:
				assert len(lowerCAmelCase_     ) == len(lowerCAmelCase_     )
				lowerCAmelCase__        =   iter(lowerCAmelCase_     )

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





"""simple docstring"""




import argparse
import os

import gluonnlp as nlp
import mxnet as mx
import numpy as np
import torch
from gluonnlp.base import get_home_dir
from gluonnlp.model.bert import BERTEncoder
from gluonnlp.model.utils import _load_vocab
from gluonnlp.vocab import Vocab
from packaging import version
from torch import nn

from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)
from transformers.utils import logging


if version.parse(nlp.__version__) != version.parse("0.8.3"):
			raise Exception("requires gluonnlp == 0.8.3")

if version.parse(mx.__version__) != version.parse("1.5.0"):
			raise Exception("requires mxnet == 1.5.0")

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

__lowerCAmelCase    :							Any													=						"The Nymphenburg Palace is a beautiful palace in Munich!"







def 							_UpperCAmelCase		(       lowerCamelCase__			,  lowerCamelCase__     ):





		"""simple docstring"""




		lowerCAmelCase__        =   {
		    """attention_cell""": """multi_head""",
		    """num_layers""": 4,
		    """units""": 1024,
		    """hidden_size""": 768,
		    """max_length""": 512,
		    """num_heads""": 8,
		    """scaled""": True,
		    """dropout""": 0.1,
		    """use_residual""": True,
		    """embed_size""": 1024,
		    """embed_dropout""": 0.1,
		    """word_embed""": None,
		    """layer_norm_eps""": 1e-5,
		    """token_type_vocab_size""": 2,
		}

		lowerCAmelCase__        =   bort_4_8_768_1024_hparams

		# Let's construct the original Bort model here
		# Taken from official BERT implementation, see:
		# https://github.com/alexa/bort/blob/master/bort/bort.py
		lowerCAmelCase__        =   BERTEncoder(
		    attention_cell=predefined_args["""attention_cell"""]			,  num_layers=predefined_args["""num_layers"""]			,  units=predefined_args["""units"""]			,  hidden_size=predefined_args["""hidden_size"""]			,  max_length=predefined_args["""max_length"""]			,  num_heads=predefined_args["""num_heads"""]			,  scaled=predefined_args["""scaled"""]			,  dropout=predefined_args["""dropout"""]			,  output_attention=lowerCamelCase__			,  output_all_encodings=lowerCamelCase__			,  use_residual=predefined_args["""use_residual"""]			,  activation=predefined_args.get("""activation"""			,  """gelu"""     )			,  layer_norm_eps=predefined_args.get("""layer_norm_eps"""			,  lowerCamelCase__     )			,  )

		# Vocab information needs to be fetched first
		# It's the same as RoBERTa, so RobertaTokenizer can be used later
		lowerCAmelCase__        =   """openwebtext_ccnews_stories_books_cased"""

		# Specify download folder to Gluonnlp's vocab
		lowerCAmelCase__        =   os.path.join(get_home_dir()			,  """models"""     )
		lowerCAmelCase__        =   _load_vocab(lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__			,  cls=lowerCamelCase__     )

		lowerCAmelCase__        =   nlp.model.BERTModel(
		    lowerCamelCase__			,  len(lowerCamelCase__     )			,  units=predefined_args["""units"""]			,  embed_size=predefined_args["""embed_size"""]			,  embed_dropout=predefined_args["""embed_dropout"""]			,  word_embed=predefined_args["""word_embed"""]			,  use_pooler=lowerCamelCase__			,  use_token_type_embed=lowerCamelCase__			,  token_type_vocab_size=predefined_args["""token_type_vocab_size"""]			,  use_classifier=lowerCamelCase__			,  use_decoder=lowerCamelCase__			,  )

		original_bort.load_parameters(lowerCamelCase__			,  cast_dtype=lowerCamelCase__			,  ignore_extra=lowerCamelCase__     )
		lowerCAmelCase__        =   original_bort._collect_params_with_prefix()

		# Build our config 🤗
		lowerCAmelCase__        =   {
		    """architectures""": ["""BertForMaskedLM"""],
		    """attention_probs_dropout_prob""": predefined_args["""dropout"""],
		    """hidden_act""": """gelu""",
		    """hidden_dropout_prob""": predefined_args["""dropout"""],
		    """hidden_size""": predefined_args["""embed_size"""],
		    """initializer_range""": 0.02,
		    """intermediate_size""": predefined_args["""hidden_size"""],
		    """layer_norm_eps""": predefined_args["""layer_norm_eps"""],
		    """max_position_embeddings""": predefined_args["""max_length"""],
		    """model_type""": """bort""",
		    """num_attention_heads""": predefined_args["""num_heads"""],
		    """num_hidden_layers""": predefined_args["""num_layers"""],
		    """pad_token_id""": 1,  # 2 = BERT, 1 = RoBERTa
		    """type_vocab_size""": 1,  # 2 = BERT, 1 = RoBERTa
		    """vocab_size""": len(lowerCamelCase__     ),
		}

		lowerCAmelCase__        =   BertConfig.from_dict(lowerCamelCase__     )
		lowerCAmelCase__        =   BertForMaskedLM(lowerCamelCase__     )
		hf_bort_model.eval()

		# Parameter mapping table (Gluonnlp to Transformers)
		# * denotes layer index
		#
		# | Gluon Parameter                                                | Transformers Parameter
		# | -------------------------------------------------------------- | ----------------------
		# | `encoder.layer_norm.beta`                                      | `bert.embeddings.LayerNorm.bias`
		# | `encoder.layer_norm.gamma`                                     | `bert.embeddings.LayerNorm.weight`
		# | `encoder.position_weight`                                      | `bert.embeddings.position_embeddings.weight`
		# | `word_embed.0.weight`                                          | `bert.embeddings.word_embeddings.weight`
		# | `encoder.transformer_cells.*.attention_cell.proj_key.bias`     | `bert.encoder.layer.*.attention.self.key.bias`
		# | `encoder.transformer_cells.*.attention_cell.proj_key.weight`   | `bert.encoder.layer.*.attention.self.key.weight`
		# | `encoder.transformer_cells.*.attention_cell.proj_query.bias`   | `bert.encoder.layer.*.attention.self.query.bias`
		# | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight`
		# | `encoder.transformer_cells.*.attention_cell.proj_value.bias`   | `bert.encoder.layer.*.attention.self.value.bias`
		# | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight`
		# | `encoder.transformer_cells.*.ffn.ffn_2.bias`                   | `bert.encoder.layer.*.attention.output.dense.bias`
		# | `encoder.transformer_cells.*.ffn.ffn_2.weight`                 | `bert.encoder.layer.*.attention.output.dense.weight`
		# | `encoder.transformer_cells.*.layer_norm.beta`                  | `bert.encoder.layer.*.attention.output.LayerNorm.bias`
		# | `encoder.transformer_cells.*.layer_norm.gamma`                 | `bert.encoder.layer.*.attention.output.LayerNorm.weight`
		# | `encoder.transformer_cells.*.ffn.ffn_1.bias`                   | `bert.encoder.layer.*.intermediate.dense.bias`
		# | `encoder.transformer_cells.*.ffn.ffn_1.weight`                 | `bert.encoder.layer.*.intermediate.dense.weight`
		# | `encoder.transformer_cells.*.ffn.layer_norm.beta`              | `bert.encoder.layer.*.output.LayerNorm.bias`
		# | `encoder.transformer_cells.*.ffn.layer_norm.gamma`             | `bert.encoder.layer.*.output.LayerNorm.weight`
		# | `encoder.transformer_cells.*.proj.bias`                        | `bert.encoder.layer.*.output.dense.bias`
		# | `encoder.transformer_cells.*.proj.weight`                      | `bert.encoder.layer.*.output.dense.weight`

		# Helper function to convert MXNET Arrays to PyTorch
		def to_torch(lowerCamelCase__     ) -> nn.Parameter:
				return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy()     )     )

		# Check param shapes and map new HF param back
		def check_and_map_params(lowerCamelCase__			,  lowerCamelCase__     ):
				lowerCAmelCase__        =   hf_param.shape

				lowerCAmelCase__        =   to_torch(params[gluon_param]     )
				lowerCAmelCase__        =   gluon_param.shape

				assert (
				    shape_hf == shape_gluon
				), f"""The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers"""

				return gluon_param

		lowerCAmelCase__        =   check_and_map_params(
		    hf_bort_model.bert.embeddings.word_embeddings.weight			,  """word_embed.0.weight"""     )
		lowerCAmelCase__        =   check_and_map_params(
		    hf_bort_model.bert.embeddings.position_embeddings.weight			,  """encoder.position_weight"""     )
		lowerCAmelCase__        =   check_and_map_params(
		    hf_bort_model.bert.embeddings.LayerNorm.bias			,  """encoder.layer_norm.beta"""     )
		lowerCAmelCase__        =   check_and_map_params(
		    hf_bort_model.bert.embeddings.LayerNorm.weight			,  """encoder.layer_norm.gamma"""     )

		# Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them)
		lowerCAmelCase__        =   torch.zeros_like(
		    hf_bort_model.bert.embeddings.token_type_embeddings.weight.data     )

		for i in range(hf_bort_config.num_hidden_layers     ):
				lowerCAmelCase__        =   hf_bort_model.bert.encoder.layer[i]

				# self attention
				lowerCAmelCase__        =   layer.attention.self

				lowerCAmelCase__        =   check_and_map_params(
				    self_attn.key.bias.data			,  f"""encoder.transformer_cells.{i}.attention_cell.proj_key.bias"""     )

				lowerCAmelCase__        =   check_and_map_params(
				    self_attn.key.weight.data			,  f"""encoder.transformer_cells.{i}.attention_cell.proj_key.weight"""     )
				lowerCAmelCase__        =   check_and_map_params(
				    self_attn.query.bias.data			,  f"""encoder.transformer_cells.{i}.attention_cell.proj_query.bias"""     )
				lowerCAmelCase__        =   check_and_map_params(
				    self_attn.query.weight.data			,  f"""encoder.transformer_cells.{i}.attention_cell.proj_query.weight"""     )
				lowerCAmelCase__        =   check_and_map_params(
				    self_attn.value.bias.data			,  f"""encoder.transformer_cells.{i}.attention_cell.proj_value.bias"""     )
				lowerCAmelCase__        =   check_and_map_params(
				    self_attn.value.weight.data			,  f"""encoder.transformer_cells.{i}.attention_cell.proj_value.weight"""     )

				# self attention output
				lowerCAmelCase__        =   layer.attention.output

				lowerCAmelCase__        =   check_and_map_params(
				    self_output.dense.bias			,  f"""encoder.transformer_cells.{i}.proj.bias"""     )
				lowerCAmelCase__        =   check_and_map_params(
				    self_output.dense.weight			,  f"""encoder.transformer_cells.{i}.proj.weight"""     )
				lowerCAmelCase__        =   check_and_map_params(
				    self_output.LayerNorm.bias			,  f"""encoder.transformer_cells.{i}.layer_norm.beta"""     )
				lowerCAmelCase__        =   check_and_map_params(
				    self_output.LayerNorm.weight			,  f"""encoder.transformer_cells.{i}.layer_norm.gamma"""     )

				# intermediate
				lowerCAmelCase__        =   layer.intermediate

				lowerCAmelCase__        =   check_and_map_params(
				    intermediate.dense.bias			,  f"""encoder.transformer_cells.{i}.ffn.ffn_1.bias"""     )
				lowerCAmelCase__        =   check_and_map_params(
				    intermediate.dense.weight			,  f"""encoder.transformer_cells.{i}.ffn.ffn_1.weight"""     )

				# output
				lowerCAmelCase__        =   layer.output

				lowerCAmelCase__        =   check_and_map_params(
				    bert_output.dense.bias			,  f"""encoder.transformer_cells.{i}.ffn.ffn_2.bias"""     )
				lowerCAmelCase__        =   check_and_map_params(
				    bert_output.dense.weight			,  f"""encoder.transformer_cells.{i}.ffn.ffn_2.weight"""     )
				lowerCAmelCase__        =   check_and_map_params(
				    bert_output.LayerNorm.bias			,  f"""encoder.transformer_cells.{i}.ffn.layer_norm.beta"""     )
				lowerCAmelCase__        =   check_and_map_params(
				    bert_output.LayerNorm.weight			,  f"""encoder.transformer_cells.{i}.ffn.layer_norm.gamma"""     )

		# Save space and energy 🎄
		hf_bort_model.half()

		# Compare output of both models
		lowerCAmelCase__        =   RobertaTokenizer.from_pretrained("""roberta-base"""     )

		lowerCAmelCase__        =   tokenizer.encode_plus(lowerCamelCase__     )["""input_ids"""]

		# Get gluon output
		lowerCAmelCase__        =   mx.nd.array([input_ids]     )
		lowerCAmelCase__        =   original_bort(inputs=lowerCamelCase__			,  token_types=[]     )

		# Get Transformer output (save and reload model again)
		hf_bort_model.save_pretrained(lowerCamelCase__     )
		lowerCAmelCase__        =   BertModel.from_pretrained(lowerCamelCase__     )
		hf_bort_model.eval()

		lowerCAmelCase__        =   tokenizer.encode_plus(lowerCamelCase__			,  return_tensors="""pt"""     )
		lowerCAmelCase__        =   hf_bort_model(**lowerCamelCase__     )[0]

		lowerCAmelCase__        =   output_gluon[0].asnumpy()
		lowerCAmelCase__        =   output_hf[0].detach().numpy()

		lowerCAmelCase__        =   np.max(np.abs(hf_layer - gluon_layer     )     ).item()
		lowerCAmelCase__        =   np.allclose(lowerCamelCase__			,  lowerCamelCase__			,  atol=1e-3     )

		if success:
				print("""✔️ Both model do output the same tensors"""     )
		else:
				print("""❌ Both model do **NOT** output the same tensors"""     )
				print("""Absolute difference is:"""			,  lowerCamelCase__     )


if __name__ == "__main__":
			__lowerCAmelCase    :							Union[str, Any]													=						argparse.ArgumentParser()
			# Required parameters
			parser.add_argument(
			    "--bort_checkpoint_path", default=None, type=str, required=True, help="Path the official Bort params file."
			)
			parser.add_argument(
			    "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
			)
			__lowerCAmelCase    :							str													=						parser.parse_args()
			convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)




