






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


__UpperCAmelCase     							=						['\nclass', '\ndef', '\n#', '\n@', '\nprint', '\nif']



class   lowerCamelCase				(_snake_case      ):







		'''simple docstring'''



		def __init__(							self    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase=None    ,		_UpperCamelCase=1       )     ->							Optional[int]:
							UpperCAmelCase_   :				Any						=						tokenizer
							UpperCAmelCase_   :				Any						=						dataset
							UpperCAmelCase_   :				List[Any]						=						len(_UpperCamelCase       ) if n_tasks is None else n_tasks
							UpperCAmelCase_   :				Dict						=						n_copies



		def __iter__(							self       )     ->							str:
							UpperCAmelCase_   :				List[str]						=						[]
							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_   :				List[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   lowerCamelCase				(_snake_case      ):







		'''simple docstring'''



		def __init__(							self    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase       )     ->							Optional[Any]:
							UpperCAmelCase_   :				Optional[int]						=						start_length
							UpperCAmelCase_   :				Tuple						=						eof_strings
							UpperCAmelCase_   :				Tuple						=						tokenizer



		def __call__(							self    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		**_UpperCamelCase       )     ->							Tuple:
							UpperCAmelCase_   :				Dict						=						self.tokenizer.batch_decode(input_ids[:, self.start_length :]       )
							UpperCAmelCase_   :				Tuple						=						[]
							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 					lowercase__				(					__snake_case   :							Any  ):


					'''simple docstring'''


					UpperCAmelCase_   :				List[str]						=						re.split('(%s)' % '|'.join(__snake_case  )					,	__snake_case  )
					# last string should be ""
					return "".join(string_list[:-2]  )




def 					lowercase__				(					__snake_case   :							Any					,	__snake_case   :							Union[str, Any]					,	__snake_case   :							Optional[int]					,	__snake_case   :							int					,	__snake_case   :							Union[str, Any]					,	__snake_case   :							List[str]=20					,	**__snake_case   :							Optional[int]  ):


					'''simple docstring'''


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

															UpperCAmelCase_	,  UpperCAmelCase_   :				Tuple						=						accelerator.gather((generated_tokens, generated_tasks)  )
															UpperCAmelCase_   :				Tuple						=						generated_tokens.cpu().numpy()
															UpperCAmelCase_   :				Any						=						generated_tasks.cpu().numpy()

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

					UpperCAmelCase_   :				Union[str, Any]						=						[[] for _ in range(__snake_case  )]
					for task, generated_tokens in gen_token_dict.items():
										for s in generated_tokens:
															UpperCAmelCase_   :				Dict						=						tokenizer.decode(__snake_case					,	skip_special_tokens=__snake_case					,	clean_up_tokenization_spaces=__snake_case  )
															code_gens[task].append(remove_last_block(__snake_case  )  )
					return code_gens




def 					lowercase__				(					):


					'''simple docstring'''


					UpperCAmelCase_   :				List[Any]						=						HfArgumentParser(__snake_case  )
					UpperCAmelCase_   :				str						=						parser.parse_args()

					transformers.logging.set_verbosity_error()
					# enables code execution in code_eval metric
					UpperCAmelCase_   :				Optional[int]						=						args.HF_ALLOW_CODE_EVAL
					# make sure tokenizer plays nice with multiprocessing
					UpperCAmelCase_   :				int						=						'false'

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

					# Use dataset load to feed to accelerate
					UpperCAmelCase_   :				Tuple						=						Accelerator()
					set_seed(args.seed					,	device_specific=__snake_case  )

					# Load model and tokenizer
					UpperCAmelCase_   :				str						=						AutoTokenizer.from_pretrained(args.model_ckpt  )
					UpperCAmelCase_   :				Dict						=						tokenizer.eos_token
					UpperCAmelCase_   :				int						=						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					,	__snake_case					,	__snake_case  )]  ),
					}

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

					UpperCAmelCase_   :				List[Any]						=						args.num_tasks if args.num_tasks is not None else len(human_eval['test']  )
					UpperCAmelCase_   :				Optional[int]						=						args.n_samples // args.batch_size

					UpperCAmelCase_   :				List[str]						=						TokenizedDataset(__snake_case					,	human_eval['test']					,	n_copies=__snake_case					,	n_tasks=__snake_case  )
					# do not confuse args.batch_size, which is actually the num_return_sequences
					UpperCAmelCase_   :				Optional[int]						=						DataLoader(__snake_case					,	batch_size=1  )

					# Run a quick test to see if code evaluation is enabled
					try:
										UpperCAmelCase_   :				int						=						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_   :				Union[str, Any]						=						accelerator.prepare(__snake_case					,	__snake_case  )

					UpperCAmelCase_   :				str						=						complete_code(
					    __snake_case					,	__snake_case					,	__snake_case					,	__snake_case					,	n_tasks=__snake_case					,	batch_size=args.batch_size					,	**__snake_case					,	)

					if accelerator.is_main_process:
										UpperCAmelCase_   :				Tuple						=						[]

										for task in tqdm(range(__snake_case  )  ):
															UpperCAmelCase_   :				List[Any]						=						human_eval['test'][task]['test']
															UpperCAmelCase_   :				int						=						F"check({human_eval['test'][task]['entry_point']})"
															references.append('\n' + test_func + '\n' + entry_point  )

										# Evaluate completions with "code_eval" metric
										UpperCAmelCase_	,  UpperCAmelCase_   :				Union[str, Any]						=						code_eval_metric.compute(
										    references=__snake_case					,	predictions=__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(__snake_case					,	__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()














from __future__ import annotations

from collections.abc import Callable

__UpperCAmelCase     							=						list[list[float | int]]




def 					lowercase__				(					__snake_case   :							Matrix					,	__snake_case   :							Matrix  ):


					'''simple docstring'''


					UpperCAmelCase_   :				int						=						len(__snake_case  )
					UpperCAmelCase_   :				Matrix						=						[[0 for _ in range(size + 1  )] for _ in range(__snake_case  )]
					UpperCAmelCase_   :				int
					UpperCAmelCase_   :				int
					UpperCAmelCase_   :				int
					UpperCAmelCase_   :				int
					UpperCAmelCase_   :				int
					UpperCAmelCase_   :				float

					for row in range(__snake_case  ):
										for col in range(__snake_case  ):
															UpperCAmelCase_   :				Dict						=						matrix[row][col]

										UpperCAmelCase_   :				Union[str, Any]						=						vector[row][0]

					UpperCAmelCase_   :				Union[str, Any]						=						0
					UpperCAmelCase_   :				Union[str, Any]						=						0
					while row < size and col < size:
										# pivoting
										UpperCAmelCase_   :				Optional[Any]						=						max((abs(augmented[rowa][col]  ), rowa) for rowa in range(__snake_case					,	__snake_case  )  )[
										    1
										]
										if augmented[pivot_row][col] == 0:
															col += 1
															continue
										else:
															UpperCAmelCase_	,  UpperCAmelCase_   :				Tuple						=						augmented[pivot_row], augmented[row]

										for rowa in range(row + 1					,	__snake_case  ):
															UpperCAmelCase_   :				Optional[int]						=						augmented[rowa][col] / augmented[row][col]
															UpperCAmelCase_   :				List[str]						=						0
															for cola in range(col + 1					,	size + 1  ):
																				augmented[rowa][cola] -= augmented[row][cola] * ratio

										row += 1
										col += 1

					# back substitution
					for col in range(1					,	__snake_case  ):
										for row in range(__snake_case  ):
															UpperCAmelCase_   :				Union[str, Any]						=						augmented[row][col] / augmented[col][col]
															for cola in range(__snake_case					,	size + 1  ):
																				augmented[row][cola] -= augmented[col][cola] * ratio

    # round to get rid of numbers like 2.000000000000004
					return [
					    [round(augmented[row][size] / augmented[row][row]					,	10  )] for row in range(__snake_case  )
					]




def 					lowercase__				(					__snake_case   :							list[int]  ):


					'''simple docstring'''


					UpperCAmelCase_   :				int						=						len(__snake_case  )
					UpperCAmelCase_   :				Matrix						=						[[0 for _ in range(__snake_case  )] for _ in range(__snake_case  )]
					UpperCAmelCase_   :				Matrix						=						[[0] for _ in range(__snake_case  )]
					UpperCAmelCase_   :				Matrix
					UpperCAmelCase_   :				int
					UpperCAmelCase_   :				int
					UpperCAmelCase_   :				int

					for x_val, y_val in enumerate(__snake_case  ):
										for col in range(__snake_case  ):
															UpperCAmelCase_   :				int						=						(x_val + 1) ** (size - col - 1)
										UpperCAmelCase_   :				int						=						y_val

					UpperCAmelCase_   :				List[str]						=						solve(__snake_case					,	__snake_case  )

					def interpolated_func(__snake_case   :							int  ) -> int:
										return sum(
										    round(coeffs[x_val][0]  ) * (var ** (size - x_val - 1))
										    for x_val in range(__snake_case  )  )

					return interpolated_func




def 					lowercase__				(					__snake_case   :							int  ):


					'''simple docstring'''


					return (
					    1
					    - variable
					    + variable**2
					    - variable**3
					    + variable**4
					    - variable**5
					    + variable**6
					    - variable**7
					    + variable**8
					    - variable**9
					    + variable**10
					)




def 					lowercase__				(					__snake_case   :							Callable[[int], int] = question_function					,	__snake_case   :							int = 10  ):


					'''simple docstring'''


					UpperCAmelCase_   :				list[int]						=						[func(__snake_case  ) for x_val in range(1					,	order + 1  )]

					UpperCAmelCase_   :				list[Callable[[int], int]]						=						[
					    interpolate(data_points[:max_coeff]  ) for max_coeff in range(1					,	order + 1  )
					]

					UpperCAmelCase_   :				int						=						0
					UpperCAmelCase_   :				Callable[[int], int]
					UpperCAmelCase_   :				int

					for poly in polynomials:
										UpperCAmelCase_   :				Optional[int]						=						1
										while func(__snake_case  ) == poly(__snake_case  ):
															x_val += 1

										ret += poly(__snake_case  )

					return ret


if __name__ == "__main__":
		print(F'{solution() = }')






