






"""simple docstring"""







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__           =	["\nclass", "\ndef", "\n#", "\n@", "\nprint", "\nif"]




class 				A__ (			lowercase__):

		def __init__(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE=None ,	_SCREAMING_SNAKE_CASE=1				):
			__lowerCAmelCase    :		Dict		    =   tokenizer
			__lowerCAmelCase    :		Optional[int]		    =   dataset
			__lowerCAmelCase    :		Optional[Any]		    =   len(_SCREAMING_SNAKE_CASE				) if n_tasks is None else n_tasks
			__lowerCAmelCase    :		Dict		    =   n_copies







		def __iter__(   self				):
			__lowerCAmelCase    :		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()				)
			__lowerCAmelCase    :		int		    =   self.tokenizer(_SCREAMING_SNAKE_CASE ,	padding=_SCREAMING_SNAKE_CASE ,	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 				A__ (			lowercase__):

		def __init__(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				):
			__lowerCAmelCase    :		Dict		    =   start_length
			__lowerCAmelCase    :		Any		    =   eof_strings
			__lowerCAmelCase    :		Any		    =   tokenizer







		def __call__(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	**_SCREAMING_SNAKE_CASE				):
			__lowerCAmelCase    :		Dict		    =   self.tokenizer.batch_decode(input_ids[:, self.start_length :]				)
			__lowerCAmelCase    :		int		    =   []
			for decoded_generation in decoded_generations:
				done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings				)				)
			return all(_SCREAMING_SNAKE_CASE				)



def 					__lowerCAmelCase       (_UpperCamelCase	):
	__lowerCAmelCase    :		List[Any]		    =   re.split('(%s)' % '|'.join(_lowerCamelCase	) ,						_lowerCamelCase	)
	# last string should be ""
	return "".join(string_list[:-2]	)
def 					__lowerCAmelCase       (_UpperCamelCase ,						_UpperCamelCase ,						_UpperCamelCase ,						_UpperCamelCase ,						_UpperCamelCase ,						_UpperCamelCase=20 ,						**_UpperCamelCase	):
	__lowerCAmelCase    :		int		    =   defaultdict(_lowerCamelCase	)  # dict of list of generated tokens
	for step, batch in tqdm(enumerate(_lowerCamelCase	)	):
		with torch.no_grad():
			__lowerCAmelCase    :		str		    =   batch["ids"].shape[-1]
			__lowerCAmelCase    :		List[Any]		    =   accelerator.unwrap_model(_lowerCamelCase	).generate(
			    input_ids=batch['ids'][:, : batch['input_len']] ,						num_return_sequences=_lowerCamelCase ,						**_lowerCamelCase	)
			# each task is generated batch_size times
			__lowerCAmelCase    :		Dict		    =   batch["task_id"].repeat(_lowerCamelCase	)
			__lowerCAmelCase    :		Dict		    =   accelerator.pad_across_processes(
			    _lowerCamelCase ,						dim=1 ,						pad_index=tokenizer.pad_token_id	)

			__lowerCAmelCase    :		Any		    =   accelerator.gather((generated_tokens, generated_tasks)	)
			__lowerCAmelCase    :		Dict		    =   generated_tokens.cpu().numpy()
			__lowerCAmelCase    :		Any		    =   generated_tasks.cpu().numpy()

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

	__lowerCAmelCase    :		List[Any]		    =   [[] for _ in range(_lowerCamelCase	)]
	for task, generated_tokens in gen_token_dict.items():
		for s in generated_tokens:
			__lowerCAmelCase    :		List[Any]		    =   tokenizer.decode(_lowerCamelCase ,						skip_special_tokens=_lowerCamelCase ,						clean_up_tokenization_spaces=_lowerCamelCase	)
			code_gens[task].append(remove_last_block(_lowerCamelCase	)	)
	return code_gens
def 					__lowerCAmelCase       ():
	__lowerCAmelCase    :		Optional[Any]		    =   HfArgumentParser(_lowerCamelCase	)
	__lowerCAmelCase    :		Union[str, Any]		    =   parser.parse_args()

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

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

	# Use dataset load to feed to accelerate
	__lowerCAmelCase    :		Dict		    =   Accelerator()
	set_seed(args.seed ,						device_specific=_lowerCamelCase	)

	# Load model and tokenizer
	__lowerCAmelCase    :		Any		    =   AutoTokenizer.from_pretrained(args.model_ckpt	)
	__lowerCAmelCase    :		Union[str, Any]		    =   tokenizer.eos_token
	__lowerCAmelCase    :		List[str]		    =   AutoModelForCausalLM.from_pretrained(args.model_ckpt	)

	# Generation settings
	__lowerCAmelCase    :		List[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 ,						_lowerCamelCase ,						_lowerCamelCase	)]	),
	}

	# Load evaluation dataset and metric
	__lowerCAmelCase    :		str		    =   load_dataset('openai_humaneval'	)
	__lowerCAmelCase    :		Any		    =   load_metric('code_eval'	)

	__lowerCAmelCase    :		Dict		    =   args.num_tasks if args.num_tasks is not None else len(human_eval['test']	)
	__lowerCAmelCase    :		Union[str, Any]		    =   args.n_samples // args.batch_size

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

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

	__lowerCAmelCase    :		Optional[int]		    =   accelerator.prepare(_lowerCamelCase ,						_lowerCamelCase	)

	__lowerCAmelCase    :		Tuple		    =   complete_code(
	    _lowerCamelCase ,						_lowerCamelCase ,						_lowerCamelCase ,						_lowerCamelCase ,						n_tasks=_lowerCamelCase ,						batch_size=args.batch_size ,						**_lowerCamelCase ,						)

	if accelerator.is_main_process:
		__lowerCAmelCase    :		Optional[Any]		    =   []

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

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


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

"""simple docstring"""







import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
							import torch
							from torch import nn

							from transformers import RegNetForImageClassification, RegNetModel
							from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor




class 				A__ :

		def __init__(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE=3 ,	_SCREAMING_SNAKE_CASE=32 ,	_SCREAMING_SNAKE_CASE=3 ,	_SCREAMING_SNAKE_CASE=10 ,	_SCREAMING_SNAKE_CASE=[10, 20, 30, 40] ,	_SCREAMING_SNAKE_CASE=[1, 1, 2, 1] ,	_SCREAMING_SNAKE_CASE=True ,	_SCREAMING_SNAKE_CASE=True ,	_SCREAMING_SNAKE_CASE="relu" ,	_SCREAMING_SNAKE_CASE=3 ,	_SCREAMING_SNAKE_CASE=None ,	):
			__lowerCAmelCase    :		Optional[Any]		    =   parent
			__lowerCAmelCase    :		int		    =   batch_size
			__lowerCAmelCase    :		Union[str, Any]		    =   image_size
			__lowerCAmelCase    :		Optional[Any]		    =   num_channels
			__lowerCAmelCase    :		List[Any]		    =   embeddings_size
			__lowerCAmelCase    :		Dict		    =   hidden_sizes
			__lowerCAmelCase    :		Optional[int]		    =   depths
			__lowerCAmelCase    :		Optional[Any]		    =   is_training
			__lowerCAmelCase    :		int		    =   use_labels
			__lowerCAmelCase    :		List[Any]		    =   hidden_act
			__lowerCAmelCase    :		Optional[Any]		    =   num_labels
			__lowerCAmelCase    :		List[str]		    =   scope
			__lowerCAmelCase    :		Optional[Any]		    =   len(_SCREAMING_SNAKE_CASE				)

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    :		Optional[Any]		    =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

			__lowerCAmelCase    :		List[str]		    =   None
			if self.use_labels:
				__lowerCAmelCase    :		Tuple		    =   ids_tensor([self.batch_size] ,	self.num_labels				)

			__lowerCAmelCase    :		int		    =   self.get_config()

			return config, pixel_values, labels

		def 							__lowerCamelCase							(   self				):
			return RegNetConfig(
			    num_channels=self.num_channels ,	embeddings_size=self.embeddings_size ,	hidden_sizes=self.hidden_sizes ,	depths=self.depths ,	hidden_act=self.hidden_act ,	num_labels=self.num_labels ,	)

		def 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				):
			__lowerCAmelCase    :		Any		    =   RegNetModel(config=_SCREAMING_SNAKE_CASE				)
			model.to(_SCREAMING_SNAKE_CASE				)
			model.eval()
			__lowerCAmelCase    :		Any		    =   model(_SCREAMING_SNAKE_CASE				)
			# expected last hidden states: B, C, H // 32, W // 32
			self.parent.assertEqual(
			    result.last_hidden_state.shape ,	(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,	)

		def 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				):
			__lowerCAmelCase    :		Optional[Any]		    =   self.num_labels
			__lowerCAmelCase    :		str		    =   RegNetForImageClassification(_SCREAMING_SNAKE_CASE				)
			model.to(_SCREAMING_SNAKE_CASE				)
			model.eval()
			__lowerCAmelCase    :		Any		    =   model(_SCREAMING_SNAKE_CASE ,	labels=_SCREAMING_SNAKE_CASE				)
			self.parent.assertEqual(result.logits.shape ,	(self.batch_size, self.num_labels)				)







		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    :		Optional[Any]		    =   self.prepare_config_and_inputs()
			__lowerCAmelCase    ,     __lowerCAmelCase    ,     __lowerCAmelCase    :		Any		    =   config_and_inputs
			__lowerCAmelCase    :		List[str]		    =   {'pixel_values': pixel_values}
			return config, inputs_dict




@require_torch
class 				A__ (			_lowerCamelCase ,  _lowerCamelCase ,  unittest.TestCase):
		A_		: List[str]            =			(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
		A_		: List[Any]            =			(
		    {'feature-extraction': RegNetModel, 'image-classification': RegNetForImageClassification}
		    if is_torch_available()
		    else {}
		)

		A_		: Dict            =			False
		A_		: str            =			False
		A_		: int            =			False
		A_		: Union[str, Any]            =			False

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    :		List[str]		    =   RegNetModelTester(self				)
			__lowerCAmelCase    :		int		    =   ConfigTester(self ,	config_class=_SCREAMING_SNAKE_CASE ,	has_text_modality=_SCREAMING_SNAKE_CASE				)

		def 							__lowerCamelCase							(   self				):
			self.create_and_test_config_common_properties()
			self.config_tester.create_and_test_config_to_json_string()
			self.config_tester.create_and_test_config_to_json_file()
			self.config_tester.create_and_test_config_from_and_save_pretrained()
			self.config_tester.create_and_test_config_with_num_labels()
			self.config_tester.check_config_can_be_init_without_params()
			self.config_tester.check_config_arguments_init()

		def 							__lowerCamelCase							(   self				):
			return

		@unittest.skip(reason='RegNet does not use inputs_embeds'				)
		def 							__lowerCamelCase							(   self				):
			pass

		@unittest.skip(reason='RegNet does not support input and output embeddings'				)
		def 							__lowerCamelCase							(   self				):
			pass

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    ,     __lowerCAmelCase    :		List[Any]		    =   self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
				__lowerCAmelCase    :		Optional[int]		    =   model_class(_SCREAMING_SNAKE_CASE				)
				__lowerCAmelCase    :		Dict		    =   inspect.signature(model.forward				)
				# signature.parameters is an OrderedDict => so arg_names order is deterministic
				__lowerCAmelCase    :		Tuple		    =   [*signature.parameters.keys()]

				__lowerCAmelCase    :		Optional[int]		    =   ['pixel_values']
				self.assertListEqual(arg_names[:1] ,	_SCREAMING_SNAKE_CASE				)

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    :		Optional[Any]		    =   self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE				)

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    ,     __lowerCAmelCase    :		List[str]		    =   self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
				__lowerCAmelCase    :		Union[str, Any]		    =   model_class(config=_SCREAMING_SNAKE_CASE				)
				for name, module in model.named_modules():
					if isinstance(_SCREAMING_SNAKE_CASE ,	(nn.BatchNormad, nn.GroupNorm)				):
						self.assertTrue(
						    torch.all(module.weight == 1				) ,	msg=f"Parameter {name} of model {model_class} seems not properly initialized" ,	)
						self.assertTrue(
						    torch.all(module.bias == 0				) ,	msg=f"Parameter {name} of model {model_class} seems not properly initialized" ,	)

		def 							__lowerCamelCase							(   self				):
			def check_hidden_states_output(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				):
				__lowerCAmelCase    :		Any		    =   model_class(_SCREAMING_SNAKE_CASE				)
				model.to(_SCREAMING_SNAKE_CASE				)
				model.eval()

				with torch.no_grad():
					__lowerCAmelCase    :		List[str]		    =   model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				)				)

				__lowerCAmelCase    :		Any		    =   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

				__lowerCAmelCase    :		List[str]		    =   self.model_tester.num_stages
				self.assertEqual(len(_SCREAMING_SNAKE_CASE				) ,	expected_num_stages + 1				)

				# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
				self.assertListEqual(
				    list(hidden_states[0].shape[-2:]				) ,	[self.model_tester.image_size // 2, self.model_tester.image_size // 2] ,	)

			__lowerCAmelCase    ,     __lowerCAmelCase    :		Dict		    =   self.model_tester.prepare_config_and_inputs_for_common()
			__lowerCAmelCase    :		List[Any]		    =   ['basic', 'bottleneck']
			for model_class in self.all_model_classes:
				for layer_type in layers_type:
					__lowerCAmelCase    :		List[Any]		    =   layer_type
					__lowerCAmelCase    :		Tuple		    =   True
					check_hidden_states_output(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				)

					# check that output_hidden_states also work using config
					del inputs_dict["output_hidden_states"]
					__lowerCAmelCase    :		Dict		    =   True

					check_hidden_states_output(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				)

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    :		List[Any]		    =   self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE				)







		@slow
		def 							__lowerCamelCase							(   self				):
			for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				__lowerCAmelCase    :		Dict		    =   RegNetModel.from_pretrained(_SCREAMING_SNAKE_CASE				)
				self.assertIsNotNone(_SCREAMING_SNAKE_CASE				)



def 					__lowerCAmelCase       ():
	__lowerCAmelCase    :		str		    =   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
	return image




@require_torch
@require_vision
class 				A__ (			unittest.TestCase):

		@cached_property
		def 							__lowerCamelCase							(   self				):
			return (
			    AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)
			    if is_vision_available()
			    else None
			)







		@slow
		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase    :		List[str]		    =   RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(_SCREAMING_SNAKE_CASE				)

			__lowerCAmelCase    :		str		    =   self.default_image_processor
			__lowerCAmelCase    :		Any		    =   prepare_img()
			__lowerCAmelCase    :		Any		    =   image_processor(images=_SCREAMING_SNAKE_CASE ,	return_tensors='pt'				).to(_SCREAMING_SNAKE_CASE				)

			# forward pass
			with torch.no_grad():
				__lowerCAmelCase    :		List[str]		    =   model(**_SCREAMING_SNAKE_CASE				)

			# verify the logits
			__lowerCAmelCase    :		Union[str, Any]		    =   torch.Size((1, 10_00)				)
			self.assertEqual(outputs.logits.shape ,	_SCREAMING_SNAKE_CASE				)

			__lowerCAmelCase    :		Optional[int]		    =   torch.tensor([-0.4180, -1.5051, -3.4836]				).to(_SCREAMING_SNAKE_CASE				)

			self.assertTrue(torch.allclose(outputs.logits[0, :3] ,	_SCREAMING_SNAKE_CASE ,	atol=1E-4				)				)