





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




class 					UpperCAmelCase	(     snake_case_  ):




      def __init__(     self     :					Optional[Any]     ,     __snake_case     :					Tuple     ,     __snake_case     :					Any     ,     __snake_case     :					Dict=None     ,     __snake_case     :					List[Any]=1    )							-> Union[str, Any]:
            _lowerCAmelCase					=				tokenizer
            _lowerCAmelCase					=				dataset
            _lowerCAmelCase					=				len(__snake_case    ) if n_tasks is None else n_tasks
            _lowerCAmelCase					=				n_copies




      def __iter__(     self     :					Optional[int]    )							-> str:
            _lowerCAmelCase					=				[]
            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					=				self.tokenizer(__snake_case     ,     padding=__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 					UpperCAmelCase	(     snake_case_  ):




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




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




def   UpperCamelCase__ (						lowerCAmelCase    ):





      """simple docstring"""


      _lowerCAmelCase					=				re.split("""(%s)""" % """|""".join(lowerCAmelCase    )				,      lowerCAmelCase    )
      # last string should be ""
      return "".join(string_list[:-2]    )
def   UpperCamelCase__ (						lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase=20				,      **lowerCAmelCase    ):





      """simple docstring"""


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

                  _lowerCAmelCase	,				_lowerCAmelCase					=				accelerator.gather((generated_tokens, generated_tasks)    )
                  _lowerCAmelCase					=				generated_tokens.cpu().numpy()
                  _lowerCAmelCase					=				generated_tasks.cpu().numpy()

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

      _lowerCAmelCase					=				[[] for _ in range(lowerCAmelCase    )]
      for task, generated_tokens in gen_token_dict.items():
            for s in generated_tokens:
                  _lowerCAmelCase					=				tokenizer.decode(lowerCAmelCase				,      skip_special_tokens=lowerCAmelCase				,      clean_up_tokenization_spaces=lowerCAmelCase    )
                  code_gens[task].append(remove_last_block(lowerCAmelCase    )    )
      return code_gens
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				HfArgumentParser(lowerCAmelCase    )
      _lowerCAmelCase					=				parser.parse_args()

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

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

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

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

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

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

      _lowerCAmelCase					=				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					=				DataLoader(lowerCAmelCase				,      batch_size=1    )

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

      _lowerCAmelCase					=				complete_code(
          lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase				,      n_tasks=lowerCAmelCase				,      batch_size=args.batch_size				,      **lowerCAmelCase				,      )

      if accelerator.is_main_process:
            _lowerCAmelCase					=				[]

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

            # Evaluate completions with "code_eval" metric
            _lowerCAmelCase	,				_lowerCAmelCase					=				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'''






from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse('''3.8'''):
      import importlib_metadata
else:
      import importlib.metadata as importlib_metadata


A__							:  Dict    =''''''


if version.parse(importlib_metadata.version('''jiwer''')) < version.parse('''2.3.0'''):




      class 					UpperCAmelCase	(     tr.AbstractTransform  ):




            def __init__(     self     :					Any     ,     __snake_case     :					str = " "    )							-> Any:
                  _lowerCAmelCase					=				sentence_delimiter




            def 							lowercase__       (     self     :					str     ,     __snake_case     :					str    )							-> Optional[int]:
                  return list(__snake_case    )




            def 							lowercase__       (     self     :					Tuple     ,     __snake_case     :					List[str]    )							-> Union[str, Any]:
                  _lowerCAmelCase					=				[]
                  for sent_idx, sentence in enumerate(__snake_case    ):
                        chars.extend(self.process_string(__snake_case    )    )
                        if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__snake_case    ) - 1:
                              chars.append(self.sentence_delimiter    )
                  return chars




      A__							:  Optional[Any]    =tr.Compose(
          [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
      )
else:
      A__							:  Tuple    =tr.Compose(
          [
              tr.RemoveMultipleSpaces(),
              tr.Strip(),
              tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
              tr.ReduceToListOfListOfChars(),
          ]
      )


A__							:  List[str]    ='''\
@inproceedings{inproceedings,
    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
    year = {2004},
    month = {01},
    pages = {},
    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
'''

A__							:  Optional[int]    ='''\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.

CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.

Character error rate can be computed as:

CER = (S + D + I) / N = (S + D + I) / (S + D + C)

where

S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).

CER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
'''

A__							:  List[str]    ='''
Computes CER score of transcribed segments against references.
Args:
    references: list of references for each speech input.
    predictions: list of transcribtions to score.
    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
    (float): the character error rate

Examples:

    >>> predictions = ["this is the prediction", "there is an other sample"]
    >>> references = ["this is the reference", "there is another one"]
    >>> cer = datasets.load_metric("cer")
    >>> cer_score = cer.compute(predictions=predictions, references=references)
    >>> print(cer_score)
    0.34146341463414637
'''




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION				,						_KWARGS_DESCRIPTION  )
class 					UpperCAmelCase	(     datasets.Metric  ):




      def 							lowercase__       (     self     :					Any    )							-> Dict:
            return datasets.MetricInfo(
                description=_DESCRIPTION     ,     citation=_CITATION     ,     inputs_description=_KWARGS_DESCRIPTION     ,     features=datasets.Features(
                    {
                        """predictions""": datasets.Value("""string"""     ,     id="""sequence"""    ),
                        """references""": datasets.Value("""string"""     ,     id="""sequence"""    ),
                    }    )     ,     codebase_urls=["""https://github.com/jitsi/jiwer/"""]     ,     reference_urls=[
                    """https://en.wikipedia.org/wiki/Word_error_rate""",
                    """https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates""",
                ]     ,     )




      def 							lowercase__       (     self     :					Optional[Any]     ,     __snake_case     :					Optional[Any]     ,     __snake_case     :					List[str]     ,     __snake_case     :					Tuple=False    )							-> List[Any]:
            if concatenate_texts:
                  return jiwer.compute_measures(
                      __snake_case     ,     __snake_case     ,     truth_transform=__snake_case     ,     hypothesis_transform=__snake_case     ,     )["wer"]

            _lowerCAmelCase					=				0
            _lowerCAmelCase					=				0
            for prediction, reference in zip(__snake_case     ,     __snake_case    ):
                  _lowerCAmelCase					=				jiwer.compute_measures(
                      __snake_case     ,     __snake_case     ,     truth_transform=__snake_case     ,     hypothesis_transform=__snake_case     ,     )
                  incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
                  total += measures["substitutions"] + measures["deletions"] + measures["hits"]

            return incorrect / total






