





'''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


a__			:					Optional[int]       						=						['\nclass', '\ndef', '\n#', '\n@', '\nprint', '\nif']






class     lowerCAmelCase__ (				UpperCAmelCase_    ):

       '''simple docstring'''

       def __init__( self					:				int       ,     a__					:				Dict       ,     a__					:				List[str]       ,     a__					:				Union[str, Any]=None       ,     a__					:				int=1						):
              UpperCAmelCase  =						tokenizer
              UpperCAmelCase  =						dataset
              UpperCAmelCase  =						len(a__						) if n_tasks is None else n_tasks
              UpperCAmelCase  =						n_copies



       def __iter__( self					:				int						):
              UpperCAmelCase  =						[]
              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  =						self.tokenizer(a__       ,     padding=a__       ,     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__ (				UpperCAmelCase_    ):

       '''simple docstring'''

       def __init__( self					:				Any       ,     a__					:				List[Any]       ,     a__					:				List[str]       ,     a__					:				Optional[Any]						):
              UpperCAmelCase  =						start_length
              UpperCAmelCase  =						eof_strings
              UpperCAmelCase  =						tokenizer



       def __call__( self					:				Optional[int]       ,     a__					:				Optional[Any]       ,     a__					:				Dict       ,     **a__					:				List[str]						):
              UpperCAmelCase  =						self.tokenizer.batch_decode(input_ids[:, self.start_length :]						)
              UpperCAmelCase  =						[]
              for decoded_generation in decoded_generations:
                     done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings						)						)
              return all(a__						)


def       __snake_case		( SCREAMING_SNAKE_CASE_ :			List[str] )							->     str:

       """simple docstring"""


       UpperCAmelCase  =						re.split('''(%s)''' % '''|'''.join(SCREAMING_SNAKE_CASE_ )			,	SCREAMING_SNAKE_CASE_ )
       # last string should be ""
       return "".join(string_list[:-2] )
def       __snake_case		( SCREAMING_SNAKE_CASE_ :			Optional[int]			,	SCREAMING_SNAKE_CASE_ :			Tuple			,	SCREAMING_SNAKE_CASE_ :			Tuple			,	SCREAMING_SNAKE_CASE_ :			List[Any]			,	SCREAMING_SNAKE_CASE_ :			Optional[Any]			,	SCREAMING_SNAKE_CASE_ :			Union[str, Any]=20			,	**SCREAMING_SNAKE_CASE_ :			int )							->     Any:

       """simple docstring"""


       UpperCAmelCase  =						defaultdict(SCREAMING_SNAKE_CASE_ )  # dict of list of generated tokens
       for step, batch in tqdm(enumerate(SCREAMING_SNAKE_CASE_ ) ):
              with torch.no_grad():
                     UpperCAmelCase  =						batch['''ids'''].shape[-1]
                     UpperCAmelCase  =						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  =						batch['''task_id'''].repeat(SCREAMING_SNAKE_CASE_ )
                     UpperCAmelCase  =						accelerator.pad_across_processes(
                         SCREAMING_SNAKE_CASE_			,	dim=1			,	pad_index=tokenizer.pad_token_id )

                     UpperCAmelCase,					UpperCAmelCase  =						accelerator.gather((generated_tokens, generated_tasks) )
                     UpperCAmelCase  =						generated_tokens.cpu().numpy()
                     UpperCAmelCase  =						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  =						[[] for _ in range(SCREAMING_SNAKE_CASE_ )]
       for task, generated_tokens in gen_token_dict.items():
              for s in generated_tokens:
                     UpperCAmelCase  =						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       __snake_case		( )							->     Optional[Any]:

       """simple docstring"""


       UpperCAmelCase  =						HfArgumentParser(SCREAMING_SNAKE_CASE_ )
       UpperCAmelCase  =						parser.parse_args()

       transformers.logging.set_verbosity_error()
       # enables code execution in code_eval metric
       UpperCAmelCase  =						args.HF_ALLOW_CODE_EVAL
       # make sure tokenizer plays nice with multiprocessing
       UpperCAmelCase  =						'''false'''

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

       # Use dataset load to feed to accelerate
       UpperCAmelCase  =						Accelerator()
       set_seed(args.seed			,	device_specific=SCREAMING_SNAKE_CASE_ )

       # Load model and tokenizer
       UpperCAmelCase  =						AutoTokenizer.from_pretrained(args.model_ckpt )
       UpperCAmelCase  =						tokenizer.eos_token
       UpperCAmelCase  =						AutoModelForCausalLM.from_pretrained(args.model_ckpt )

       # Generation settings
       UpperCAmelCase  =						{
           '''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  =						load_dataset('''openai_humaneval''' )
       UpperCAmelCase  =						load_metric('''code_eval''' )

       UpperCAmelCase  =						args.num_tasks if args.num_tasks is not None else len(human_eval['''test'''] )
       UpperCAmelCase  =						args.n_samples // args.batch_size

       UpperCAmelCase  =						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  =						DataLoader(SCREAMING_SNAKE_CASE_			,	batch_size=1 )

       # Run a quick test to see if code evaluation is enabled
       try:
              UpperCAmelCase  =						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  =						accelerator.prepare(SCREAMING_SNAKE_CASE_			,	SCREAMING_SNAKE_CASE_ )

       UpperCAmelCase  =						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  =						[]

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

              # Evaluate completions with "code_eval" metric
              UpperCAmelCase,					UpperCAmelCase  =						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()




"""simple docstring"""

import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
   from transformers import WhisperFeatureExtractor

if is_torch_available():
   import torch

SCREAMING_SNAKE_CASE_            =    random.Random()




def      lowercase__    (       lowerCAmelCase					:       int			,					lowerCAmelCase					:       Union[str, Any]=1.0			,					lowerCAmelCase					:       Any=None			,					lowerCAmelCase					:       Optional[Any]=None			)			->   Dict:






    """simple docstring"""




    if rng is None:
        UpperCAmelCase          =       global_rng

    UpperCAmelCase          =       []
    for batch_idx in range(shape[0]			):
        values.append([]			)
        for _ in range(shape[1]			):
            values[-1].append(rng.random() * scale			)

    return values
@require_torch
@require_torchaudio
class   _UpperCAmelCase				(		unittest.TestCase				):




      def __init__(				self ,							lowercase_ ,							lowercase_=7 ,							lowercase_=4_0_0 ,							lowercase_=2_0_0_0 ,							lowercase_=1_0 ,							lowercase_=1_6_0 ,							lowercase_=8 ,							lowercase_=0.0 ,							lowercase_=4_0_0_0 ,							lowercase_=False ,							lowercase_=True ,							)    ->       Optional[int]:
          UpperCAmelCase          =       parent
          UpperCAmelCase          =       batch_size
          UpperCAmelCase          =       min_seq_length
          UpperCAmelCase          =       max_seq_length
          UpperCAmelCase          =       (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
          UpperCAmelCase          =       padding_value
          UpperCAmelCase          =       sampling_rate
          UpperCAmelCase          =       return_attention_mask
          UpperCAmelCase          =       do_normalize
          UpperCAmelCase          =       feature_size
          UpperCAmelCase          =       chunk_length
          UpperCAmelCase          =       hop_length




      def      a_   (				self				)    ->       Dict:
          return {
              "feature_size": self.feature_size,
              "hop_length": self.hop_length,
              "chunk_length": self.chunk_length,
              "padding_value": self.padding_value,
              "sampling_rate": self.sampling_rate,
              "return_attention_mask": self.return_attention_mask,
              "do_normalize": self.do_normalize,
          }




      def      a_   (				self ,							lowercase_=False ,							lowercase_=False				)    ->       Optional[Any]:
          def _flatten(lowercase_				):
              return list(itertools.chain(*lowercase_				)				)

          if equal_length:
              UpperCAmelCase          =       [floats_list((self.max_seq_length, self.feature_size)				) for _ in range(self.batch_size				)]
          else:
              # make sure that inputs increase in size
              UpperCAmelCase          =       [
                  floats_list((x, self.feature_size)				)
                  for x in range(self.min_seq_length ,							self.max_seq_length ,							self.seq_length_diff				)
              ]
          if numpify:
              UpperCAmelCase          =       [np.asarray(lowercase_				) for x in speech_inputs]
          return speech_inputs

@require_torch
@require_torchaudio
class   _UpperCAmelCase				(		SCREAMING_SNAKE_CASE_  ,      unittest.TestCase				):
      __SCREAMING_SNAKE_CASE :				List[Any]				   =						WhisperFeatureExtractor if is_speech_available() else None




      def      a_   (				self				)    ->       Union[str, Any]:
          UpperCAmelCase          =       WhisperFeatureExtractionTester(self				)




      def      a_   (				self				)    ->       List[str]:
          UpperCAmelCase          =       self.feature_extraction_class(**self.feat_extract_dict				)

          with tempfile.TemporaryDirectory() as tmpdirname:
              UpperCAmelCase          =       feat_extract_first.save_pretrained(lowercase_				)[0]
              check_json_file_has_correct_format(lowercase_				)
              UpperCAmelCase          =       self.feature_extraction_class.from_pretrained(lowercase_				)

          UpperCAmelCase          =       feat_extract_first.to_dict()
          UpperCAmelCase          =       feat_extract_second.to_dict()
          UpperCAmelCase          =       feat_extract_first.mel_filters
          UpperCAmelCase          =       feat_extract_second.mel_filters
          self.assertTrue(np.allclose(lowercase_ ,							lowercase_				)				)
          self.assertEqual(lowercase_ ,							lowercase_				)




      def      a_   (				self				)    ->       List[str]:
          UpperCAmelCase          =       self.feature_extraction_class(**self.feat_extract_dict				)

          with tempfile.TemporaryDirectory() as tmpdirname:
              UpperCAmelCase          =       os.path.join(lowercase_ ,							'feat_extract.json'				)
              feat_extract_first.to_json_file(lowercase_				)
              UpperCAmelCase          =       self.feature_extraction_class.from_json_file(lowercase_				)

          UpperCAmelCase          =       feat_extract_first.to_dict()
          UpperCAmelCase          =       feat_extract_second.to_dict()
          UpperCAmelCase          =       feat_extract_first.mel_filters
          UpperCAmelCase          =       feat_extract_second.mel_filters
          self.assertTrue(np.allclose(lowercase_ ,							lowercase_				)				)
          self.assertEqual(lowercase_ ,							lowercase_				)




      def      a_   (				self				)    ->       Tuple:
          # Tests that all call wrap to encode_plus and batch_encode_plus
          UpperCAmelCase          =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()				)
          # create three inputs of length 800, 1000, and 1200
          UpperCAmelCase          =       [floats_list((1, x)				)[0] for x in range(8_0_0 ,							1_4_0_0 ,							2_0_0				)]
          UpperCAmelCase          =       [np.asarray(lowercase_				) for speech_input in speech_inputs]

          # Test feature size
          UpperCAmelCase          =       feature_extractor(lowercase_ ,							padding='max_length' ,							return_tensors='np'				).input_features
          self.assertTrue(input_features.ndim == 3				)
          self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames				)
          self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size				)

          # Test not batched input
          UpperCAmelCase          =       feature_extractor(speech_inputs[0] ,							return_tensors='np'				).input_features
          UpperCAmelCase          =       feature_extractor(np_speech_inputs[0] ,							return_tensors='np'				).input_features
          self.assertTrue(np.allclose(lowercase_ ,							lowercase_ ,							atol=1E-3				)				)

          # Test batched
          UpperCAmelCase          =       feature_extractor(lowercase_ ,							return_tensors='np'				).input_features
          UpperCAmelCase          =       feature_extractor(lowercase_ ,							return_tensors='np'				).input_features
          for enc_seq_a, enc_seq_a in zip(lowercase_ ,							lowercase_				):
              self.assertTrue(np.allclose(lowercase_ ,							lowercase_ ,							atol=1E-3				)				)

          # Test 2-D numpy arrays are batched.
          UpperCAmelCase          =       [floats_list((1, x)				)[0] for x in (8_0_0, 8_0_0, 8_0_0)]
          UpperCAmelCase          =       np.asarray(lowercase_				)
          UpperCAmelCase          =       feature_extractor(lowercase_ ,							return_tensors='np'				).input_features
          UpperCAmelCase          =       feature_extractor(lowercase_ ,							return_tensors='np'				).input_features
          for enc_seq_a, enc_seq_a in zip(lowercase_ ,							lowercase_				):
              self.assertTrue(np.allclose(lowercase_ ,							lowercase_ ,							atol=1E-3				)				)

          # Test truncation required
          UpperCAmelCase          =       [floats_list((1, x)				)[0] for x in range(2_0_0 ,							(feature_extractor.n_samples + 5_0_0) ,							2_0_0				)]
          UpperCAmelCase          =       [np.asarray(lowercase_				) for speech_input in speech_inputs]

          UpperCAmelCase          =       [x[: feature_extractor.n_samples] for x in speech_inputs]
          UpperCAmelCase          =       [np.asarray(lowercase_				) for speech_input in speech_inputs_truncated]

          UpperCAmelCase          =       feature_extractor(lowercase_ ,							return_tensors='np'				).input_features
          UpperCAmelCase          =       feature_extractor(lowercase_ ,							return_tensors='np'				).input_features
          for enc_seq_a, enc_seq_a in zip(lowercase_ ,							lowercase_				):
              self.assertTrue(np.allclose(lowercase_ ,							lowercase_ ,							atol=1E-3				)				)




      def      a_   (				self				)    ->       List[Any]:
          import torch

          UpperCAmelCase          =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()				)
          UpperCAmelCase          =       np.random.rand(1_0_0 ,							3_2				).astype(np.floataa				)
          UpperCAmelCase          =       np_speech_inputs.tolist()

          for inputs in [py_speech_inputs, np_speech_inputs]:
              UpperCAmelCase          =       feature_extractor.pad([{'input_features': inputs}] ,							return_tensors='np'				)
              self.assertTrue(np_processed.input_features.dtype == np.floataa				)
              UpperCAmelCase          =       feature_extractor.pad([{'input_features': inputs}] ,							return_tensors='pt'				)
              self.assertTrue(pt_processed.input_features.dtype == torch.floataa				)




      def      a_   (				self ,							lowercase_				)    ->       Optional[Any]:
          UpperCAmelCase          =       load_dataset('hf-internal-testing/librispeech_asr_dummy' ,							'clean' ,							split='validation'				)
          # automatic decoding with librispeech
          UpperCAmelCase          =       ds.sort('id'				).select(range(lowercase_				)				)[:num_samples]['audio']

          return [x["array"] for x in speech_samples]




      def      a_   (				self				)    ->       Dict:
          # fmt: off
          UpperCAmelCase          =       torch.tensor(
              [
                  0.1_1_9_3, -0.0_9_4_6, -0.1_0_9_8, -0.0_1_9_6, 0.0_2_2_5, -0.0_6_9_0, -0.1_7_3_6, 0.0_9_5_1,
                  0.0_9_7_1, -0.0_8_1_7, -0.0_7_0_2, 0.0_1_6_2, 0.0_2_6_0, 0.0_0_1_7, -0.0_1_9_2, -0.1_6_7_8,
                  0.0_7_0_9, -0.1_8_6_7, -0.0_6_5_5, -0.0_2_7_4, -0.0_2_3_4, -0.1_8_8_4, -0.0_5_1_6, -0.0_5_5_4,
                  -0.0_2_7_4, -0.1_4_2_5, -0.1_4_2_3, 0.0_8_3_7, 0.0_3_7_7, -0.0_8_5_4
              ]				)
          # fmt: on

          UpperCAmelCase          =       self._load_datasamples(1				)
          UpperCAmelCase          =       WhisperFeatureExtractor()
          UpperCAmelCase          =       feature_extractor(lowercase_ ,							return_tensors='pt'				).input_features
          self.assertEqual(input_features.shape ,							(1, 8_0, 3_0_0_0)				)
          self.assertTrue(torch.allclose(input_features[0, 0, :3_0] ,							lowercase_ ,							atol=1E-4				)				)




      def      a_   (				self				)    ->       Optional[Any]:
          UpperCAmelCase          =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()				)
          UpperCAmelCase          =       self._load_datasamples(1				)[0]
          UpperCAmelCase          =       ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5_5_3_5  # Rescale to [0, 65535] to show issue
          UpperCAmelCase          =       feat_extract.zero_mean_unit_var_norm([audio] ,							attention_mask=lowercase_				)[0]

          self.assertTrue(np.all(np.mean(lowercase_				) < 1E-3				)				)
          self.assertTrue(np.all(np.abs(np.var(lowercase_				) - 1				) < 1E-3				)				)



