




import json
import multiprocessing
import os
import re
from collections import defaultdict

import torch
from accelerate import Accelerator
from accelerate.utils import set_seed
from arguments import HumanEvalArguments
from datasets import load_dataset, load_metric
from torch.utils.data import IterableDataset
from torch.utils.data.dataloader import DataLoader
from tqdm import tqdm

import transformers
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList


__lowerCAmelCase	:       Union[str, Any]     =	['\nclass', '\ndef', '\n#', '\n@', '\nprint', '\nif']




class 					snake_case__							(_UpperCamelCase     ):
				"""simple docstring"""



				def __init__(   self       :  Any      ,   __lowerCamelCase       :  List[str]      ,   __lowerCamelCase       :  Union[str, Any]      ,   __lowerCamelCase       :  Union[str, Any]=None      ,   __lowerCamelCase       :  Any=1							)      ->  Union[str, Any]:
							a					=    tokenizer
							a					=    dataset
							a					=    len(__lowerCamelCase							) if n_tasks is None else n_tasks
							a					=    n_copies





				def __iter__(   self       :  Tuple							)      ->  str:
							a					=    []
							for task in range(self.n_tasks							):
										# without strip, the model generate commented codes ...
										prompts.append(self.tokenizer.eos_token + self.dataset[task]["prompt"].strip()							)
							a					=    self.tokenizer(__lowerCamelCase      ,   padding=__lowerCamelCase      ,   return_tensors="pt"							)
							for task in range(self.n_tasks							):
										for _ in range(self.n_copies							):
													yield {
													    "ids": outputs.input_ids[task],
													    "task_id": task,
													    "input_len": outputs.attention_mask[task].sum(),
													}




class 					snake_case__							(_UpperCamelCase     ):
				"""simple docstring"""



				def __init__(   self       :  int      ,   __lowerCamelCase       :  Dict      ,   __lowerCamelCase       :  Dict      ,   __lowerCamelCase       :  Tuple							)      ->  Optional[Any]:
							a					=    start_length
							a					=    eof_strings
							a					=    tokenizer





				def __call__(   self       :  int      ,   __lowerCamelCase       :  Dict      ,   __lowerCamelCase       :  List[str]      ,   **__lowerCamelCase       :  Optional[int]							)      ->  Optional[Any]:
							a					=    self.tokenizer.batch_decode(input_ids[:, self.start_length :]							)
							a					=    []
							for decoded_generation in decoded_generations:
										done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings							)							)
							return all(__lowerCamelCase							)




def     __magic_name__       (				A	:      List[Any]     ):






			'''simple docstring'''







			a					=    re.split("(%s)" % "|".join(A     ),						A     )
			# last string should be ""
			return "".join(string_list[:-2]     )




def     __magic_name__       (				A	:      Union[str, Any],						A	:      Optional[Any],						A	:      List[Any],						A	:      Optional[Any],						A	:      List[str],						A	:      List[Any]=20,						**A	:      Union[str, Any]     ):






			'''simple docstring'''







			a					=    defaultdict(A     )  # dict of list of generated tokens
			for step, batch in tqdm(enumerate(A     )     ):
						with torch.no_grad():
									a					=    batch["ids"].shape[-1]
									a					=    accelerator.unwrap_model(A     ).generate(
									    input_ids=batch["ids"][:, : batch["input_len"]],						num_return_sequences=A,						**A     )
									# each task is generated batch_size times
									a					=    batch["task_id"].repeat(A     )
									a					=    accelerator.pad_across_processes(
									    A,						dim=1,						pad_index=tokenizer.pad_token_id     )

									a					,	a					=    accelerator.gather((generated_tokens, generated_tasks)     )
									a					=    generated_tokens.cpu().numpy()
									a					=    generated_tasks.cpu().numpy()

									for task, generated_tokens in zip(A,						A     ):
												gen_token_dict[task].append(A     )

			a					=    [[] for _ in range(A     )]
			for task, generated_tokens in gen_token_dict.items():
						for s in generated_tokens:
									a					=    tokenizer.decode(A,						skip_special_tokens=A,						clean_up_tokenization_spaces=A     )
									code_gens[task].append(remove_last_block(A     )     )
			return code_gens




def     __magic_name__       (				):






			'''simple docstring'''







			a					=    HfArgumentParser(A     )
			a					=    parser.parse_args()

			transformers.logging.set_verbosity_error()
			# enables code execution in code_eval metric
			a					=    args.HF_ALLOW_CODE_EVAL
			# make sure tokenizer plays nice with multiprocessing
			a					=    "false"

			if args.num_workers is None:
						a					=    multiprocessing.cpu_count()

			# Use dataset load to feed to accelerate
			a					=    Accelerator()
			set_seed(args.seed,						device_specific=A     )

			# Load model and tokenizer
			a					=    AutoTokenizer.from_pretrained(args.model_ckpt     )
			a					=    tokenizer.eos_token
			a					=    AutoModelForCausalLM.from_pretrained(args.model_ckpt     )

			# Generation settings
			a					=    {
			    "do_sample": args.do_sample,
			    "temperature": args.temperature,
			    "max_new_tokens": args.max_new_tokens,
			    "top_p": args.top_p,
			    "top_k": args.top_k,
			    "stopping_criteria": StoppingCriteriaList([EndOfFunctionCriteria(0,						A,						A     )]     ),
			}

			# Load evaluation dataset and metric
			a					=    load_dataset("openai_humaneval"     )
			a					=    load_metric("code_eval"     )

			a					=    args.num_tasks if args.num_tasks is not None else len(human_eval["test"]     )
			a					=    args.n_samples // args.batch_size

			a					=    TokenizedDataset(A,						human_eval["test"],						n_copies=A,						n_tasks=A     )
			# do not confuse args.batch_size, which is actually the num_return_sequences
			a					=    DataLoader(A,						batch_size=1     )

			# Run a quick test to see if code evaluation is enabled
			try:
						a					=    code_eval_metric.compute(references=[""],						predictions=[[""]]     )
			except ValueError as exception:
						print(
						    "Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL=\"1\"`"
						    " flag to enable code evaluation."     )
						raise exception

			a					,	a					=    accelerator.prepare(A,						A     )

			a					=    complete_code(
			    A,						A,						A,						A,						n_tasks=A,						batch_size=args.batch_size,						**A,						)

			if accelerator.is_main_process:
						a					=    []

						for task in tqdm(range(A     )     ):
									a					=    human_eval["test"][task]["test"]
									a					=    F"""check({human_eval["test"][task]["entry_point"]})"""
									references.append("\n" + test_func + "\n" + entry_point     )

						# Evaluate completions with "code_eval" metric
						a					,	a					=    code_eval_metric.compute(
						    references=A,						predictions=A,						num_workers=args.num_workers     )
						print(F"""Results: {pass_at_k}"""     )

						# Save results to json file
						with open(args.output_file,						"w"     ) as fp:
									json.dump(A,						A     )


# For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing
# https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script
if __name__ == "__main__":
		main()












from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


__lowerCAmelCase	:       Optional[Any]     =	'\\n@misc{wu2016googles,\n      title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n              and Jeffrey Dean},\n      year={2016},\n      eprint={1609.08144},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n'

__lowerCAmelCase	:       str     =	'\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n'

__lowerCAmelCase	:       List[Any]     =	'\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n    predictions (list of str): list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references (list of list of str): list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n    \'google_bleu\': google_bleu score\n\nExamples:\n    Example 1:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results["google_bleu"], 2))\n        0.44\n\n    Example 2:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results["google_bleu"], 2))\n        0.61\n\n    Example 3:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n        >>> print(round(results["google_bleu"], 2))\n        0.53\n\n    Example 4:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n        >>> print(round(results["google_bleu"], 2))\n        0.4\n'




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION					, _KWARGS_DESCRIPTION     )
class 					snake_case__							(datasets.Metric     ):
				"""simple docstring"""



				def 							__UpperCAmelCase							(   self       :  int							)      ->  MetricInfo:
							return datasets.MetricInfo(
							    description=_DESCRIPTION      ,   citation=_CITATION      ,   inputs_description=_KWARGS_DESCRIPTION      ,   features=datasets.Features(
							        {
							            "predictions": datasets.Sequence(datasets.Value("string"      ,   id="token"							)      ,   id="sequence"							),
							            "references": datasets.Sequence(
							                datasets.Sequence(datasets.Value("string"      ,   id="token"							)      ,   id="sequence"							)      ,   id="references"							),
							        }							)      ,   )





				def 							__UpperCAmelCase							(   self       :  List[str]      ,   __lowerCamelCase       :  List[List[List[str]]]      ,   __lowerCamelCase       :  List[List[str]]      ,   __lowerCamelCase       :  int = 1      ,   __lowerCamelCase       :  int = 4      ,   )      ->  Dict[str, float]:
							return {
							    "google_bleu": gleu_score.corpus_gleu(
							        list_of_references=__lowerCamelCase      ,   hypotheses=__lowerCamelCase      ,   min_len=__lowerCamelCase      ,   max_len=__lowerCamelCase							)
							}






