




'''simple docstring'''

import argparse
import glob
import logging
import os
from argparse import Namespace
from importlib import import_module

import numpy as np
import torch
from lightning_base import BaseTransformer, add_generic_args, generic_train
from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader, TensorDataset
from utils_ner import TokenClassificationTask


a       :						Optional[Any]								=		logging.getLogger(__name__)



class 		SCREAMING_SNAKE_CASE__  (			_UpperCamelCase	):
			__SCREAMING_SNAKE_CASE    =			"""token-classification"""





			def __init__(      self						:    str      ,		a_						:    Tuple							):



						"""simple docstring"""




						if type(a_							) == dict:
									__snake_case			=		Namespace(**a_							)
						__snake_case			=		import_module("tasks"							)
						try:
									__snake_case			=		getattr(a_      ,		hparams.task_type							)
									__snake_case			=		token_classification_task_clazz()
						except AttributeError:
									raise ValueError(
									    f'''Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. '''
									    f'''Available tasks classes are: {TokenClassificationTask.__subclasses__()}'''							)
						__snake_case			=		self.token_classification_task.get_labels(hparams.labels							)
						__snake_case			=		CrossEntropyLoss().ignore_index
						super().__init__(a_      ,		len(self.labels							)      ,		self.mode							)





			def 							A (      self						:    int      ,		**a_						:    List[str]							):



						"""simple docstring"""




						return self.model(**a_							)





			def 							A (      self						:    str      ,		a_						:    List[str]      ,		a_						:    Dict							):



						"""simple docstring"""




						__snake_case			=		{"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}
						if self.config.model_type != "distilbert":
									__snake_case			=		(
									    batch[2] if self.config.model_type in ["bert", "xlnet"] else None
									)  # XLM and RoBERTa don"t use token_type_ids

						__snake_case			=		self(**a_							)
						__snake_case			=		outputs[0]
						# tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]}
						return {"loss": loss}





			def 							A (      self						:    List[Any]							):



						"""simple docstring"""




						__snake_case			=		self.hparams
						for mode in ["train", "dev", "test"]:
									__snake_case			=		self._feature_file(a_							)
									if os.path.exists(a_							) and not args.overwrite_cache:
												logger.info("Loading features from cached file %s"      ,		a_							)
												__snake_case			=		torch.load(a_							)
									else:
												logger.info("Creating features from dataset file at %s"      ,		args.data_dir							)
												__snake_case			=		self.token_classification_task.read_examples_from_file(args.data_dir      ,		a_							)
												__snake_case			=		self.token_classification_task.convert_examples_to_features(
												    a_      ,		self.labels      ,		args.max_seq_length      ,		self.tokenizer      ,		cls_token_at_end=bool(self.config.model_type in ["xlnet"]							)      ,		cls_token=self.tokenizer.cls_token      ,		cls_token_segment_id=2 if self.config.model_type in ["xlnet"] else 0      ,		sep_token=self.tokenizer.sep_token      ,		sep_token_extra=a_      ,		pad_on_left=bool(self.config.model_type in ["xlnet"]							)      ,		pad_token=self.tokenizer.pad_token_id      ,		pad_token_segment_id=self.tokenizer.pad_token_type_id      ,		pad_token_label_id=self.pad_token_label_id      ,		)
												logger.info("Saving features into cached file %s"      ,		a_							)
												torch.save(a_      ,		a_							)





			def 							A (      self						:    List[Any]      ,		a_						:    int      ,		a_						:    int      ,		a_						:    bool = False							):



						"""simple docstring"""




						__snake_case			=		self._feature_file(a_							)
						logger.info("Loading features from cached file %s"      ,		a_							)
						__snake_case			=		torch.load(a_							)
						__snake_case			=		torch.tensor([f.input_ids for f in features]      ,		dtype=torch.long							)
						__snake_case			=		torch.tensor([f.attention_mask for f in features]      ,		dtype=torch.long							)
						if features[0].token_type_ids is not None:
									__snake_case			=		torch.tensor([f.token_type_ids for f in features]      ,		dtype=torch.long							)
						else:
									__snake_case			=		torch.tensor([0 for f in features]      ,		dtype=torch.long							)
									# HACK(we will not use this anymore soon)
						__snake_case			=		torch.tensor([f.label_ids for f in features]      ,		dtype=torch.long							)
						return DataLoader(
						    TensorDataset(a_      ,		a_      ,		a_      ,		a_							)      ,		batch_size=a_							)





			def 							A (      self						:    Tuple      ,		a_						:    Tuple      ,		a_						:    Optional[Any]							):



						"""simple docstring"""




						"""Compute validation""" ""
						__snake_case			=		{"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}
						if self.config.model_type != "distilbert":
									__snake_case			=		(
									    batch[2] if self.config.model_type in ["bert", "xlnet"] else None
									)  # XLM and RoBERTa don"t use token_type_ids
						__snake_case			=		self(**a_							)
						__snake_case		,     __snake_case			=		outputs[:2]
						__snake_case			=		logits.detach().cpu().numpy()
						__snake_case			=		inputs["labels"].detach().cpu().numpy()
						return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}





			def 							A (      self						:    Dict      ,		a_						:    Tuple							):



						"""simple docstring"""




						__snake_case			=		torch.stack([x["val_loss"] for x in outputs]							).mean()
						__snake_case			=		np.concatenate([x["pred"] for x in outputs]      ,		axis=0							)
						__snake_case			=		np.argmax(a_      ,		axis=2							)
						__snake_case			=		np.concatenate([x["target"] for x in outputs]      ,		axis=0							)

						__snake_case			=		dict(enumerate(self.labels							)							)
						__snake_case			=		[[] for _ in range(out_label_ids.shape[0]							)]
						__snake_case			=		[[] for _ in range(out_label_ids.shape[0]							)]

						for i in range(out_label_ids.shape[0]							):
									for j in range(out_label_ids.shape[1]							):
												if out_label_ids[i, j] != self.pad_token_label_id:
															out_label_list[i].append(label_map[out_label_ids[i][j]]							)
															preds_list[i].append(label_map[preds[i][j]]							)

						__snake_case			=		{
						    "val_loss": val_loss_mean,
						    "accuracy_score": accuracy_score(a_      ,		a_							),
						    "precision": precision_score(a_      ,		a_							),
						    "recall": recall_score(a_      ,		a_							),
						    "f1": fa_score(a_      ,		a_							),
						}

						__snake_case			=		dict(results.items()							)
						__snake_case			=		results
						return ret, preds_list, out_label_list





			def 							A (      self						:    List[str]      ,		a_						:    List[Any]							):



						"""simple docstring"""




						__snake_case		,     __snake_case		,     __snake_case			=		self._eval_end(a_							)
						__snake_case			=		ret["log"]
						return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}





			def 							A (      self						:    Optional[int]      ,		a_						:    Optional[Any]							):



						"""simple docstring"""




						__snake_case		,     __snake_case		,     __snake_case			=		self._eval_end(a_							)

						# Converting to the dict required by pl
						# https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\
						# pytorch_lightning/trainer/logging.py#L139
						__snake_case			=		ret["log"]
						# `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss`
						return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs}






			@staticmethod
			def 							A (      a_						:    int      ,		a_						:    List[str]							):



						"""simple docstring"""




						BaseTransformer.add_model_specific_args(a_      ,		a_							)
						parser.add_argument(
						    "--task_type"      ,		default="NER"      ,		type=a_      ,		help="Task type to fine tune in training (e.g. NER, POS, etc)"							)
						parser.add_argument(
						    "--max_seq_length"      ,		default=128      ,		type=a_      ,		help=(
						        "The maximum total input sequence length after tokenization. Sequences longer "
						        "than this will be truncated, sequences shorter will be padded."
						    )      ,		)

						parser.add_argument(
						    "--labels"      ,		default=""      ,		type=a_      ,		help="Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."      ,		)
						parser.add_argument(
						    "--gpus"      ,		default=0      ,		type=a_      ,		help="The number of GPUs allocated for this, it is by default 0 meaning none"      ,		)

						parser.add_argument(
						    "--overwrite_cache"      ,		action="store_true"      ,		help="Overwrite the cached training and evaluation sets"							)

						return parser


if __name__ == "__main__":
						a       :						Union[str, Any]								=		argparse.ArgumentParser()
						add_generic_args(parser, os.getcwd())
						a       :						List[str]								=		NERTransformer.add_model_specific_args(parser, os.getcwd())
						a       :						List[Any]								=		parser.parse_args()
						a       :						str								=		NERTransformer(args)
						a       :						List[Any]								=		generic_train(model, args)

						if args.do_predict:
												# See https://github.com/huggingface/transformers/issues/3159
												# pl use this default format to create a checkpoint:
												# https://github.com/PyTorchLightning/pytorch-lightning/blob/master\
												# /pytorch_lightning/callbacks/model_checkpoint.py#L322
												a       :						Tuple								=		sorted(glob.glob(os.path.join(args.output_dir, '''checkpoint-epoch=*.ckpt'''), recursive=True))
												a       :						Optional[int]								=		model.load_from_checkpoint(checkpoints[-1])
												trainer.test(model)













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   )]   )



