'''simple docstring'''

from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


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

UpperCamelCase__  :						List[Any]					=      "\\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"

UpperCamelCase__  :						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 					_lowercase						(   datasets.Metric ):
      '''simple docstring'''


      def 		lowerCAmelCase__       (					self				)      ->      MetricInfo:



         '''simple docstring'''



         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 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_       ,lowerCamelCase_ = 1       ,lowerCamelCase_ = 4       ,)      ->      Dict[str, float]:



         '''simple docstring'''



         return {
             "google_bleu": gleu_score.corpus_gleu(
                 list_of_references=__UpperCamelCase       ,hypotheses=__UpperCamelCase       ,min_len=__UpperCamelCase       ,max_len=__UpperCamelCase				)
         }





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


SCREAMING_SNAKE_CASE		:     Optional[int]         =	["\nclass", "\ndef", "\n#", "\n@", "\nprint", "\nif"]

class        UpperCamelCase						(				__a				):





						def __init__(self			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase=None			,     __UpperCamelCase=1						)				->				List[str]:
												UpperCamelCase_		:							Dict  =		tokenizer
												UpperCamelCase_		:							Dict  =		dataset
												UpperCamelCase_		:							str  =		len(__UpperCamelCase						) if n_tasks is None else n_tasks
												UpperCamelCase_		:							int  =		n_copies





						def __iter__(self						)				->				Any:
												UpperCamelCase_		:							int  =		[]
												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()						)
												UpperCamelCase_		:							Any  =		self.tokenizer(__UpperCamelCase			,     padding=__UpperCamelCase			,     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        UpperCamelCase						(				__a				):





						def __init__(self			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase						)				->				Dict:
												UpperCamelCase_		:							List[Any]  =		start_length
												UpperCamelCase_		:							List[str]  =		eof_strings
												UpperCamelCase_		:							str  =		tokenizer





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






def     lowerCAmelCase_			(   _SCREAMING_SNAKE_CASE     :				Dict			):
						UpperCamelCase_		:							int  =		re.split("""(%s)""" % """|""".join(_SCREAMING_SNAKE_CASE			)		, _SCREAMING_SNAKE_CASE			)
						# last string should be ""
						return "".join(string_list[:-2]			)






def     lowerCAmelCase_			(   _SCREAMING_SNAKE_CASE     :				Optional[int]		, _SCREAMING_SNAKE_CASE     :				Optional[Any]		, _SCREAMING_SNAKE_CASE     :				Optional[Any]		, _SCREAMING_SNAKE_CASE     :				int		, _SCREAMING_SNAKE_CASE     :				List[str]		, _SCREAMING_SNAKE_CASE     :				Optional[Any]=20		, **_SCREAMING_SNAKE_CASE     :				List[str]			):
						UpperCamelCase_		:							Union[str, Any]  =		defaultdict(_SCREAMING_SNAKE_CASE			)  # dict of list of generated tokens
						for step, batch in tqdm(enumerate(_SCREAMING_SNAKE_CASE			)			):
												with torch.no_grad():
																		UpperCamelCase_		:							str  =		batch["""ids"""].shape[-1]
																		UpperCamelCase_		:							List[str]  =		accelerator.unwrap_model(_SCREAMING_SNAKE_CASE			).generate(
																		    input_ids=batch["""ids"""][:, : batch["""input_len"""]]		, num_return_sequences=_SCREAMING_SNAKE_CASE		, **_SCREAMING_SNAKE_CASE			)
																		# each task is generated batch_size times
																		UpperCamelCase_		:							List[str]  =		batch["""task_id"""].repeat(_SCREAMING_SNAKE_CASE			)
																		UpperCamelCase_		:							Union[str, Any]  =		accelerator.pad_across_processes(
																		    _SCREAMING_SNAKE_CASE		, dim=1		, pad_index=tokenizer.pad_token_id			)

																		UpperCamelCase_,UpperCamelCase_		:							Any  =		accelerator.gather((generated_tokens, generated_tasks)			)
																		UpperCamelCase_		:							str  =		generated_tokens.cpu().numpy()
																		UpperCamelCase_		:							List[Any]  =		generated_tasks.cpu().numpy()

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

						UpperCamelCase_		:							List[str]  =		[[] for _ in range(_SCREAMING_SNAKE_CASE			)]
						for task, generated_tokens in gen_token_dict.items():
												for s in generated_tokens:
																		UpperCamelCase_		:							List[Any]  =		tokenizer.decode(_SCREAMING_SNAKE_CASE		, skip_special_tokens=_SCREAMING_SNAKE_CASE		, clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE			)
																		code_gens[task].append(remove_last_block(_SCREAMING_SNAKE_CASE			)			)
						return code_gens






def     lowerCAmelCase_			(   ):
						# Setup configuration
						UpperCamelCase_		:							List[Any]  =		HfArgumentParser(_SCREAMING_SNAKE_CASE			)
						UpperCamelCase_		:							Optional[Any]  =		parser.parse_args()

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

						if args.num_workers is None:
												UpperCamelCase_		:							List[str]  =		multiprocessing.cpu_count()

						# Use dataset load to feed to accelerate
						UpperCamelCase_		:							Optional[Any]  =		Accelerator()
						set_seed(args.seed		, device_specific=_SCREAMING_SNAKE_CASE			)

						# Load model and tokenizer
						UpperCamelCase_		:							str  =		AutoTokenizer.from_pretrained(args.model_ckpt			)
						UpperCamelCase_		:							Any  =		tokenizer.eos_token
						UpperCamelCase_		:							Tuple  =		AutoModelForCausalLM.from_pretrained(args.model_ckpt			)

						# Generation settings
						UpperCamelCase_		:							Union[str, Any]  =		{
						    """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		, _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE			)]			),
						}

						# Load evaluation dataset and metric
						UpperCamelCase_		:							Optional[int]  =		load_dataset("""openai_humaneval"""			)
						UpperCamelCase_		:							Any  =		load_metric("""code_eval"""			)

						UpperCamelCase_		:							int  =		args.num_tasks if args.num_tasks is not None else len(human_eval["""test"""]			)
						UpperCamelCase_		:							List[str]  =		args.n_samples // args.batch_size

						UpperCamelCase_		:							Tuple  =		TokenizedDataset(_SCREAMING_SNAKE_CASE		, human_eval["""test"""]		, n_copies=_SCREAMING_SNAKE_CASE		, n_tasks=_SCREAMING_SNAKE_CASE			)
						# do not confuse args.batch_size, which is actually the num_return_sequences
						UpperCamelCase_		:							List[str]  =		DataLoader(_SCREAMING_SNAKE_CASE		, batch_size=1			)

						# Run a quick test to see if code evaluation is enabled
						try:
												UpperCamelCase_		:							str  =		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

						UpperCamelCase_,UpperCamelCase_		:							int  =		accelerator.prepare(_SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE			)

						UpperCamelCase_		:							Optional[int]  =		complete_code(
						    _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, n_tasks=_SCREAMING_SNAKE_CASE		, batch_size=args.batch_size		, **_SCREAMING_SNAKE_CASE		, )

						if accelerator.is_main_process:
												UpperCamelCase_		:							List[str]  =		[]

												for task in tqdm(range(_SCREAMING_SNAKE_CASE			)			):
																		UpperCamelCase_		:							int  =		human_eval["""test"""][task]["""test"""]
																		UpperCamelCase_		:							Tuple  =		f'''check({human_eval["test"][task]["entry_point"]})'''
																		references.append("""\n""" + test_func + """\n""" + entry_point			)

												# Evaluate completions with "code_eval" metric
												UpperCamelCase_,UpperCamelCase_		:							Any  =		code_eval_metric.compute(
												    references=_SCREAMING_SNAKE_CASE		, predictions=_SCREAMING_SNAKE_CASE		, 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(_SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE			)


# 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()






