
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


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

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


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


lowercase__							:							int									=			"\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"

lowercase__							:							List[str]									=			"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        SCREAMING_SNAKE_CASE__    (							datasets.Metric    ):

							"""simple docstring"""






							def     A__		(  self			)->   int:





													'''simple docstring'''






													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     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=[1, 10, 100]     ,	SCREAMING_SNAKE_CASE_=4     ,	SCREAMING_SNAKE_CASE_=3.0			)->   Tuple:





													'''simple docstring'''






													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=SCREAMING_SNAKE_CASE_			) as executor:
																			__UpperCamelCase       =			[]
																			__UpperCamelCase       =			Counter()
																			__UpperCamelCase       =			0
																			__UpperCamelCase       =			defaultdict(SCREAMING_SNAKE_CASE_			)

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

																			for future in as_completed(SCREAMING_SNAKE_CASE_			):
																									__UpperCamelCase       =			future.result()
																									results[result["task_id"]].append((result['''completion_id'''], result)			)

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

													__UpperCamelCase       =			k
													__UpperCamelCase       =			{F"pass@{k}": estimate_pass_at_k(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			).mean() for k in ks if (total >= k).all()}

													return pass_at_k, results





def 	A_ (							snake_case							:   List[str] ,      snake_case							:   Optional[int] ,      snake_case							:   str )      ->    Optional[int]:



						'''simple docstring'''

						def estimator(snake_case							:   int ,      snake_case							:   int ,      snake_case							:   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(snake_case ,      snake_case ):
												__UpperCamelCase       =			itertools.repeat(snake_case ,      len(snake_case ) )
						else:
												assert len(snake_case ) == len(snake_case )
												__UpperCamelCase       =			iter(snake_case )

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






import argparse
import shutil
import time
from json import JSONDecodeError
from logging import getLogger
from pathlib import Path
from typing import Dict, List

import torch
from torch.utils.data import DataLoader
from tqdm import tqdm

from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
from utils import (
    SeqaSeqDataset,
    calculate_bleu,
    calculate_rouge,
    chunks,
    lmap,
    load_json,
    parse_numeric_n_bool_cl_kwargs,
    save_json,
    use_task_specific_params,
    write_txt_file,
)


lowercase__							:							Union[str, Any]									=			getLogger(__name__)




def 	A_ (							snake_case							:   str ,      snake_case							:   str ,      snake_case							:   str ,      snake_case							:   int = 8 ,      snake_case							:   int = 1024 ,      snake_case							:   Dict="val" ,      snake_case							:   Tuple=None ,      snake_case							:   int=False ,      snake_case							:   Union[str, Any]="summarization" ,      snake_case							:   Optional[Any]=None ,      snake_case							:   List[str]=1 ,      snake_case							:   Dict = None ,      snake_case							:   Optional[Any]="" ,      **snake_case							:   Tuple ,      )      ->    Dict:



						'''simple docstring'''

						__UpperCamelCase       =			str(snake_case )
						assert local_rank is not None
						torch.distributed.init_process_group(backend='''nccl''' ,      rank=snake_case )

						__UpperCamelCase       =			Path(snake_case )
						__UpperCamelCase       =			save_dir.joinpath(f"rank_{local_rank}_output.json" )
						torch.cuda.set_device(snake_case )
						__UpperCamelCase       =			AutoModelForSeqaSeqLM.from_pretrained(snake_case ).cuda()
						if fpaa:
												__UpperCamelCase       =			model.half()
						# determine if we need to increase num_beams
						use_task_specific_params(snake_case ,      snake_case )  # update config with task specific params
						__UpperCamelCase       =			generate_kwargs.pop('''num_beams''' ,      model.config.num_beams )  # AttributeError risk?
						if num_return_sequences > num_beams:
												__UpperCamelCase       =			num_return_sequences

						__UpperCamelCase       =			AutoTokenizer.from_pretrained(snake_case )
						logger.info(f"Inferred tokenizer type: {tokenizer.__class__}" )  # if this is wrong, check config.model_type.

						if max_source_length is None:
												__UpperCamelCase       =			tokenizer.model_max_length
						if prefix is None:
												__UpperCamelCase       =			prefix or getattr(model.config ,      '''prefix''' ,      '''''' ) or ''''''
						__UpperCamelCase       =			SeqaSeqDataset(
						    snake_case ,      snake_case ,      snake_case ,      max_target_length=1024 ,      type_path=snake_case ,      n_obs=snake_case ,      prefix=snake_case ,      **snake_case ,      )
						# I set shuffle=True for a more accurate progress bar.
						# If all the longest samples are first, the prog bar estimate is too high at the beginning.
						__UpperCamelCase       =			ds.make_sortish_sampler(snake_case ,      distributed=snake_case ,      add_extra_examples=snake_case ,      shuffle=snake_case )
						__UpperCamelCase       =			DataLoader(snake_case ,      sampler=snake_case ,      batch_size=snake_case ,      collate_fn=ds.collate_fn )
						__UpperCamelCase       =			[]
						for batch in tqdm(snake_case ):
												__UpperCamelCase       =			model.generate(
												    input_ids=batch['''input_ids'''].to(model.device ) ,      attention_mask=batch['''attention_mask'''].to(model.device ) ,      num_return_sequences=snake_case ,      num_beams=snake_case ,      **snake_case ,      )
												__UpperCamelCase       =			tokenizer.batch_decode(snake_case ,      skip_special_tokens=snake_case ,      clean_up_tokenization_spaces=snake_case )
												__UpperCamelCase       =			batch['''ids''']
												if num_return_sequences > 1:
																		__UpperCamelCase       =			chunks(snake_case ,      snake_case )  # batch size chunks, each of size num_return_seq
												for i, pred in enumerate(snake_case ):
																		results.append({'''pred''': pred, '''id''': ids[i].item()} )
						save_json(snake_case ,      snake_case )
						return results, sampler.num_replicas




def 	A_ (							)      ->    int:



						'''simple docstring'''

						__UpperCamelCase       =			argparse.ArgumentParser(
						    epilog='''Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate''' )
						parser.add_argument('''--data_dir''' ,      type=snake_case ,      help='''like cnn_dm/test.source''' )
						parser.add_argument(
						    '''--model_name''' ,      type=snake_case ,      help='''like facebook/bart-large-cnn,t5-base, etc.''' ,      default='''sshleifer/distilbart-xsum-12-3''' ,      )
						parser.add_argument('''--save_dir''' ,      type=snake_case ,      help='''where to save''' ,      default='''tmp_gen''' )
						parser.add_argument('''--max_source_length''' ,      type=snake_case ,      default=snake_case )
						parser.add_argument(
						    '''--type_path''' ,      type=snake_case ,      default='''test''' ,      help='''which subset to evaluate typically train/val/test''' )
						parser.add_argument('''--task''' ,      type=snake_case ,      default='''summarization''' ,      help='''used for task_specific_params + metrics''' )
						parser.add_argument('''--bs''' ,      type=snake_case ,      default=8 ,      required=snake_case ,      help='''batch size''' )
						parser.add_argument(
						    '''--local_rank''' ,      type=snake_case ,      default=-1 ,      required=snake_case ,      help='''should be passed by distributed.launch''' )

						parser.add_argument(
						    '''--n_obs''' ,      type=snake_case ,      default=snake_case ,      required=snake_case ,      help='''How many observations. Defaults to all.''' )
						parser.add_argument(
						    '''--num_return_sequences''' ,      type=snake_case ,      default=1 ,      required=snake_case ,      help='''How many sequences to return''' )
						parser.add_argument(
						    '''--sync_timeout''' ,      type=snake_case ,      default=600 ,      required=snake_case ,      help='''How long should master process wait for other processes to finish.''' ,      )
						parser.add_argument('''--src_lang''' ,      type=snake_case ,      default=snake_case ,      required=snake_case )
						parser.add_argument('''--tgt_lang''' ,      type=snake_case ,      default=snake_case ,      required=snake_case )
						parser.add_argument(
						    '''--prefix''' ,      type=snake_case ,      required=snake_case ,      default=snake_case ,      help='''will be added to the begininng of src examples''' )
						parser.add_argument('''--fp16''' ,      action='''store_true''' )
						parser.add_argument('''--debug''' ,      action='''store_true''' )
						__UpperCamelCase       =			time.time()
						__UpperCamelCase  ,							__UpperCamelCase       =			parser.parse_known_args()
						__UpperCamelCase       =			parse_numeric_n_bool_cl_kwargs(snake_case )
						if generate_kwargs and args.local_rank <= 0:
												print(f"parsed the following generate kwargs: {generate_kwargs}" )
						__UpperCamelCase       =			Path(args.save_dir + '''_tmp''' )
						Path(snake_case ).mkdir(exist_ok=snake_case )  # this handles locking.
						__UpperCamelCase       =			list(json_save_dir.glob('''rank_*.json''' ) )
						if intermediate_files:
												raise ValueError(f"Found files at {json_save_dir} please move or remove them." )
												# In theory, a node could finish and save before another node hits this. If this happens, we can address later.
						__UpperCamelCase       =			{}
						if args.src_lang is not None:
												__UpperCamelCase       =			args.src_lang
						if args.tgt_lang is not None:
												__UpperCamelCase       =			args.tgt_lang

						Path(args.save_dir ).mkdir(exist_ok=snake_case )
						__UpperCamelCase  ,							__UpperCamelCase       =			eval_data_dir(
						    args.data_dir ,      snake_case ,      args.model_name ,      type_path=args.type_path ,      bs=args.bs ,      fpaa=args.fpaa ,      task=args.task ,      local_rank=args.local_rank ,      n_obs=args.n_obs ,      max_source_length=args.max_source_length ,      num_return_sequences=args.num_return_sequences ,      prefix=args.prefix ,      dataset_kwargs=snake_case ,      **snake_case ,      )

						if args.local_rank <= 0:
												__UpperCamelCase       =			Path(args.save_dir )
												save_dir.mkdir(exist_ok=snake_case )
												__UpperCamelCase       =			gather_results_from_each_node(snake_case ,      snake_case ,      args.sync_timeout )
												__UpperCamelCase       =			combine_partial_results(snake_case )
												if args.num_return_sequences > 1:
																		__UpperCamelCase       =			save_dir.joinpath('''pseudolabel_results.json''' )
																		print(f"Saving aggregated results at {save_path}, intermediate in {json_save_dir}/" )
																		save_json(snake_case ,      snake_case )
																		return
												__UpperCamelCase       =			Path(args.data_dir ).joinpath(args.type_path + '''.target''' )
												with open(snake_case ) as f:
																		__UpperCamelCase       =			[x.rstrip() for x in f.readlines()][: len(snake_case )]

												# Calculate metrics, save metrics,  and save _generations.txt
												__UpperCamelCase       =			'''translation''' in args.task
												__UpperCamelCase       =			calculate_bleu if calc_bleu else calculate_rouge
												__UpperCamelCase       =			'''bleu''' if calc_bleu else '''rouge'''
												__UpperCamelCase       =			score_fn(snake_case ,      snake_case )
												__UpperCamelCase       =			len(snake_case )
												__UpperCamelCase       =			time.time() - start_time
												__UpperCamelCase       =			round(runtime / metrics['''n_obs'''] ,      4 )
												__UpperCamelCase       =			num_replicas
												# TODO(@stas00): add whatever metadata to metrics
												__UpperCamelCase       =			save_dir.joinpath(f"{args.type_path}_{metric_name}.json" )
												save_json(snake_case ,      snake_case ,      indent=snake_case )
												print(snake_case )
												write_txt_file(snake_case ,      save_dir.joinpath(f"{args.type_path}_generations.txt" ) )
												if args.debug:
																		write_txt_file(snake_case ,      save_dir.joinpath(f"{args.type_path}.target" ) )
												else:
																		shutil.rmtree(snake_case )




def 	A_ (							snake_case							:   Optional[int] )      ->    List:



						'''simple docstring'''

						__UpperCamelCase       =			[]
						for partial_result in partial_results:
												records.extend(snake_case )
						__UpperCamelCase       =			sorted(snake_case ,      key=lambda snake_case : x["id"] )
						__UpperCamelCase       =			[x['''pred'''] for x in records]
						return preds




def 	A_ (							snake_case							:   List[str] ,      snake_case							:   int ,      snake_case							:   str )      ->    List[Dict[str, List]]:



						'''simple docstring'''

						__UpperCamelCase       =			time.time()
						logger.info('''waiting for all nodes to finish''' )
						__UpperCamelCase       =			None
						while (time.time() - start_wait) < timeout:
												__UpperCamelCase       =			list(save_dir.glob('''rank_*.json''' ) )
												if len(snake_case ) < num_replicas:
																		continue
												try:
																		# make sure all json files are fully saved
																		__UpperCamelCase       =			lmap(snake_case ,      snake_case )
																		return json_data
												except JSONDecodeError:
																		continue
						else:
												raise TimeoutError('''Rank 0 gave up on waiting for other processes''' )
						# Unreachable


if __name__ == "__main__":
				# Usage for MT:
				run_generate()




