




"""simple docstring"""




import logging

import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.bert.modeling_bert import (
    BERT_INPUTS_DOCSTRING,
    BERT_START_DOCSTRING,
    BertEncoder,
    BertModel,
    BertPreTrainedModel,
)


a_        =       logging.getLogger(__name__)

class   UpperCAmelCase_    (			snake_case		):
		def 	_lowerCamelCase							(						self				,						UpperCamelCase_				,						UpperCamelCase_				,						UpperCamelCase_=None				,						UpperCamelCase_=None       )						->       Optional[Any]:
					__lowercase			:  Tuple								=       self.layer[current_layer](UpperCamelCase_				,						UpperCamelCase_				,						head_mask[current_layer]       )

					__lowercase			:  Any								=       layer_outputs[0]

					return hidden_states


@add_start_docstrings(
    "The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top."   ,					snake_case   ,					)
class   UpperCAmelCase_    (			snake_case		):
		def __init__(						self				,						UpperCamelCase_       )						->       int:
					super().__init__(UpperCamelCase_       )

					__lowercase			:  Optional[Any]								=       BertEncoderWithPabee(UpperCamelCase_       )

					self.init_weights()
					__lowercase			:  str								=       0
					__lowercase			:  Optional[Any]								=       0
					__lowercase			:  Optional[int]								=       0

					__lowercase			:  int								=       0
		def 	_lowerCamelCase							(						self				,						UpperCamelCase_       )						->       Dict:
					__lowercase			:  Tuple								=       threshold
		def 	_lowerCamelCase							(						self				,						UpperCamelCase_       )						->       Union[str, Any]:
					__lowercase			:  Optional[int]								=       patience
		def 	_lowerCamelCase							(						self       )						->       List[str]:
					__lowercase			:  Tuple								=       0
					__lowercase			:  Tuple								=       0
		def 	_lowerCamelCase							(						self       )						->       List[Any]:
					__lowercase			:  Optional[int]								=       self.inference_layers_num / self.inference_instances_num
					__lowercase			:  int								=       (
					    F"""*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up ="""
					    F""" {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***"""
					)
					print(UpperCamelCase_       )
		@add_start_docstrings_to_model_forward(UpperCamelCase_       )
		def 	_lowerCamelCase							(						self				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=False				,						)						->       Union[str, Any]:

					if input_ids is not None and inputs_embeds is not None:
								raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time'''       )
					elif input_ids is not None:
								__lowercase			:  Tuple								=       input_ids.size()
					elif inputs_embeds is not None:
								__lowercase			:  List[Any]								=       inputs_embeds.size()[:-1]
					else:
								raise ValueError('''You have to specify either input_ids or inputs_embeds'''       )

					__lowercase			:  int								=       input_ids.device if input_ids is not None else inputs_embeds.device

					if attention_mask is None:
								__lowercase			:  Dict								=       torch.ones(UpperCamelCase_				,						device=UpperCamelCase_       )
					if token_type_ids is None:
								__lowercase			:  int								=       torch.zeros(UpperCamelCase_				,						dtype=torch.long				,						device=UpperCamelCase_       )

					# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
					# ourselves in which case we just need to make it broadcastable to all heads.
					__lowercase			:  torch.Tensor								=       self.get_extended_attention_mask(UpperCamelCase_				,						UpperCamelCase_				,						UpperCamelCase_       )

					# If a 2D ou 3D attention mask is provided for the cross-attention
					# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
					if self.config.is_decoder and encoder_hidden_states is not None:
								__lowercase			,__lowercase			,__lowercase			:  Optional[int]								=       encoder_hidden_states.size()
								__lowercase			:  Any								=       (encoder_batch_size, encoder_sequence_length)
								if encoder_attention_mask is None:
											__lowercase			:  List[str]								=       torch.ones(UpperCamelCase_				,						device=UpperCamelCase_       )
								__lowercase			:  Tuple								=       self.invert_attention_mask(UpperCamelCase_       )
					else:
								__lowercase			:  Tuple								=       None

					# Prepare head mask if needed
					# 1.0 in head_mask indicate we keep the head
					# attention_probs has shape bsz x n_heads x N x N
					# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
					# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
					__lowercase			:  Optional[int]								=       self.get_head_mask(UpperCamelCase_				,						self.config.num_hidden_layers       )

					__lowercase			:  Optional[int]								=       self.embeddings(
					    input_ids=UpperCamelCase_				,						position_ids=UpperCamelCase_				,						token_type_ids=UpperCamelCase_				,						inputs_embeds=UpperCamelCase_       )
					__lowercase			:  Union[str, Any]								=       embedding_output

					if self.training:
								__lowercase			:  List[Any]								=       []
								for i in range(self.config.num_hidden_layers       ):
											__lowercase			:  str								=       self.encoder.adaptive_forward(
											    UpperCamelCase_				,						current_layer=UpperCamelCase_				,						attention_mask=UpperCamelCase_				,						head_mask=UpperCamelCase_       )

											__lowercase			:  int								=       self.pooler(UpperCamelCase_       )
											__lowercase			:  str								=       output_layers[i](output_dropout(UpperCamelCase_       )       )
											res.append(UpperCamelCase_       )
					elif self.patience == 0:  # Use all layers for inference
								__lowercase			:  int								=       self.encoder(
								    UpperCamelCase_				,						attention_mask=UpperCamelCase_				,						head_mask=UpperCamelCase_				,						encoder_hidden_states=UpperCamelCase_				,						encoder_attention_mask=UpperCamelCase_				,						)
								__lowercase			:  Optional[Any]								=       self.pooler(encoder_outputs[0]       )
								__lowercase			:  int								=       [output_layers[self.config.num_hidden_layers - 1](UpperCamelCase_       )]
					else:
								__lowercase			:  Optional[int]								=       0
								__lowercase			:  Union[str, Any]								=       None
								__lowercase			:  int								=       0
								for i in range(self.config.num_hidden_layers       ):
											calculated_layer_num += 1
											__lowercase			:  Tuple								=       self.encoder.adaptive_forward(
											    UpperCamelCase_				,						current_layer=UpperCamelCase_				,						attention_mask=UpperCamelCase_				,						head_mask=UpperCamelCase_       )

											__lowercase			:  Dict								=       self.pooler(UpperCamelCase_       )
											__lowercase			:  Optional[int]								=       output_layers[i](UpperCamelCase_       )
											if regression:
														__lowercase			:  Any								=       logits.detach()
														if patient_result is not None:
																	__lowercase			:  List[str]								=       patient_result.detach()
														if (patient_result is not None) and torch.abs(patient_result - labels       ) < self.regression_threshold:
																	patient_counter += 1
														else:
																	__lowercase			:  int								=       0
											else:
														__lowercase			:  List[str]								=       logits.detach().argmax(dim=1       )
														if patient_result is not None:
																	__lowercase			:  Optional[Any]								=       patient_result.detach().argmax(dim=1       )
														if (patient_result is not None) and torch.all(labels.eq(UpperCamelCase_       )       ):
																	patient_counter += 1
														else:
																	__lowercase			:  Tuple								=       0

											__lowercase			:  Union[str, Any]								=       logits
											if patient_counter == self.patience:
														break
								__lowercase			:  Optional[int]								=       [patient_result]
								self.inference_layers_num += calculated_layer_num
								self.inference_instances_num += 1

					return res


@add_start_docstrings(
    "Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n    the pooled output) e.g. for GLUE tasks. "   ,					snake_case   ,					)
class   UpperCAmelCase_    (			snake_case		):
		def __init__(						self				,						UpperCamelCase_       )						->       Optional[Any]:
					super().__init__(UpperCamelCase_       )
					__lowercase			:  List[Any]								=       config.num_labels

					__lowercase			:  int								=       BertModelWithPabee(UpperCamelCase_       )
					__lowercase			:  int								=       nn.Dropout(config.hidden_dropout_prob       )
					__lowercase			:  Union[str, Any]								=       nn.ModuleList(
					    [nn.Linear(config.hidden_size				,						self.config.num_labels       ) for _ in range(config.num_hidden_layers       )]       )

					self.init_weights()
		@add_start_docstrings_to_model_forward(UpperCamelCase_       )
		def 	_lowerCamelCase							(						self				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						UpperCamelCase_=None				,						)						->       int:
					__lowercase			:  Union[str, Any]								=       self.bert(
					    input_ids=UpperCamelCase_				,						attention_mask=UpperCamelCase_				,						token_type_ids=UpperCamelCase_				,						position_ids=UpperCamelCase_				,						head_mask=UpperCamelCase_				,						inputs_embeds=UpperCamelCase_				,						output_dropout=self.dropout				,						output_layers=self.classifiers				,						regression=self.num_labels == 1				,						)

					__lowercase			:  List[str]								=       (logits[-1],)

					if labels is not None:
								__lowercase			:  Any								=       None
								__lowercase			:  Optional[int]								=       0
								for ix, logits_item in enumerate(UpperCamelCase_       ):
											if self.num_labels == 1:
														#  We are doing regression
														__lowercase			:  Any								=       MSELoss()
														__lowercase			:  Any								=       loss_fct(logits_item.view(-1       )				,						labels.view(-1       )       )
											else:
														__lowercase			:  str								=       CrossEntropyLoss()
														__lowercase			:  Dict								=       loss_fct(logits_item.view(-1				,						self.num_labels       )				,						labels.view(-1       )       )
											if total_loss is None:
														__lowercase			:  List[str]								=       loss
											else:
														total_loss += loss * (ix + 1)
											total_weights += ix + 1
								__lowercase			:  Union[str, Any]								=       (total_loss / total_weights,) + outputs

					return outputs









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


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

class     __a(	_a  ):






    """simple docstring"""





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





    def __iter__( self    )					->						Any:
         UpperCAmelCase_     :				List[Any]  =     []
         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_     :				Union[str, Any]  =     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(	_a  ):






    """simple docstring"""





    def __init__( self  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )					->						List[Any]:
         UpperCAmelCase_     :				str  =     start_length
         UpperCAmelCase_     :				Optional[int]  =     eof_strings
         UpperCAmelCase_     :				str  =     tokenizer





    def __call__( self  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,**_SCREAMING_SNAKE_CASE    )					->						List[Any]:
         UpperCAmelCase_     :				Optional[Any]  =     self.tokenizer.batch_decode(input_ids[:, self.start_length :]    )
         UpperCAmelCase_     :				Optional[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__  (     _lowercase ):

     '''simple docstring'''


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







def lowerCamelCase__  (     _lowercase					,		_lowercase					,		_lowercase					,		_lowercase					,		_lowercase					,		_lowercase=20					,		**_lowercase ):

     '''simple docstring'''


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

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

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

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







def lowerCamelCase__  (     ):

     '''simple docstring'''


     UpperCAmelCase_     :				Optional[Any]  =     HfArgumentParser(_lowercase )
     UpperCAmelCase_     :				int  =     parser.parse_args()

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

     if args.num_workers is None:
          UpperCAmelCase_     :				Optional[Any]  =     multiprocessing.cpu_count()

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

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

     # Generation settings
     UpperCAmelCase_     :				str  =     {
         '''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					,		_lowercase					,		_lowercase )] ),
     }

     # Load evaluation dataset and metric
     UpperCAmelCase_     :				Tuple  =     load_dataset('''openai_humaneval''' )
     UpperCAmelCase_     :				Dict  =     load_metric('''code_eval''' )

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

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

     # Run a quick test to see if code evaluation is enabled
     try:
          UpperCAmelCase_     :				Any  =     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(_lowercase					,		_lowercase )

     UpperCAmelCase_     :				int  =     complete_code(
         _lowercase					,		_lowercase					,		_lowercase					,		_lowercase					,		n_tasks=_lowercase					,		batch_size=args.batch_size					,		**_lowercase					,		)

     if accelerator.is_main_process:
          UpperCAmelCase_     :				Any  =     []

          for task in tqdm(range(_lowercase ) ):
               UpperCAmelCase_     :				int  =     human_eval['''test'''][task]['''test''']
               UpperCAmelCase_     :				str  =     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=_lowercase					,		predictions=_lowercase					,		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(_lowercase					,		_lowercase )


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