'''simple docstring'''




import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
 import tensorflow as tf





class 							SCREAMING_SNAKE_CASE (					enum.Enum			):
  """simple docstring"""







  __A  =		0
  __A  =		1
  __A  =		2





@add_end_docstrings(__lowerCAmelCase			)
class 							SCREAMING_SNAKE_CASE (					__lowerCAmelCase			):
  """simple docstring"""







  __A  =		"""
    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
    voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
    begging for his blessing. <eod> </s> <eos>
    """



  def __init__(	self :       Tuple       ,       *__lowerCAmelCase :       List[str]       ,       **__lowerCAmelCase :       Union[str, Any]       ):


        """simple docstring"""



        super().__init__(*_SCREAMING_SNAKE_CASE       ,       **_SCREAMING_SNAKE_CASE       )
        self.check_model_type(
            TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_CAUSAL_LM_MAPPING       )
        if "prefix" not in self._preprocess_params:
              # This is very specific. The logic is quite complex and needs to be done
              # as a "default".
              # It also defines both some preprocess_kwargs and generate_kwargs
              # which is why we cannot put them in their respective methods.
              _lowerCAmelCase		 = None
              if self.model.config.prefix is not None:
                    _lowerCAmelCase		 = self.model.config.prefix
              if prefix is None and self.model.__class__.__name__ in [
                  "XLNetLMHeadModel",
                  "TransfoXLLMHeadModel",
                  "TFXLNetLMHeadModel",
                  "TFTransfoXLLMHeadModel",
              ]:
                    # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
                    _lowerCAmelCase		 = self.XL_PREFIX
              if prefix is not None:
                    # Recalculate some generate_kwargs linked to prefix.
                    _lowerCAmelCase ,	_lowerCAmelCase ,	_lowerCAmelCase		 = self._sanitize_parameters(prefix=_SCREAMING_SNAKE_CASE       ,       **self._forward_params       )
                    _lowerCAmelCase		 = {**self._preprocess_params, **preprocess_params}
                    _lowerCAmelCase		 = {**self._forward_params, **forward_params}



  def 	a (	self :       Dict       ,       __lowerCAmelCase :       Optional[Any]=None       ,       __lowerCAmelCase :       List[Any]=None       ,       __lowerCAmelCase :       Any=None       ,       __lowerCAmelCase :       Optional[int]=None       ,       __lowerCAmelCase :       Optional[int]=None       ,       __lowerCAmelCase :       Tuple=None       ,       __lowerCAmelCase :       Any=None       ,       __lowerCAmelCase :       List[Any]=None       ,       **__lowerCAmelCase :       str       ,       ):


        """simple docstring"""



        _lowerCAmelCase		 = {}
        if prefix is not None:
              _lowerCAmelCase		 = prefix
        if prefix:
              _lowerCAmelCase		 = self.tokenizer(
                  _SCREAMING_SNAKE_CASE       ,       padding=_SCREAMING_SNAKE_CASE       ,       add_special_tokens=_SCREAMING_SNAKE_CASE       ,       return_tensors=self.framework       )
              _lowerCAmelCase		 = prefix_inputs['input_ids'].shape[-1]

        if handle_long_generation is not None:
              if handle_long_generation not in {"hole"}:
                    raise ValueError(
                        F"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"
                        ' [None, \'hole\']'       )
              _lowerCAmelCase		 = handle_long_generation

        preprocess_params.update(_SCREAMING_SNAKE_CASE       )
        _lowerCAmelCase		 = generate_kwargs

        _lowerCAmelCase		 = {}
        if return_full_text is not None and return_type is None:
              if return_text is not None:
                    raise ValueError('`return_text` is mutually exclusive with `return_full_text`'       )
              if return_tensors is not None:
                    raise ValueError('`return_full_text` is mutually exclusive with `return_tensors`'       )
              _lowerCAmelCase		 = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
        if return_tensors is not None and return_type is None:
              if return_text is not None:
                    raise ValueError('`return_text` is mutually exclusive with `return_tensors`'       )
              _lowerCAmelCase		 = ReturnType.TENSORS
        if return_type is not None:
              _lowerCAmelCase		 = return_type
        if clean_up_tokenization_spaces is not None:
              _lowerCAmelCase		 = clean_up_tokenization_spaces

        if stop_sequence is not None:
              _lowerCAmelCase		 = self.tokenizer.encode(_SCREAMING_SNAKE_CASE       ,       add_special_tokens=_SCREAMING_SNAKE_CASE       )
              if len(_SCREAMING_SNAKE_CASE       ) > 1:
                    warnings.warn(
                        'Stopping on a multiple token sequence is not yet supported on transformers. The first token of'
                        ' the stop sequence will be used as the stop sequence string in the interim.'       )
              _lowerCAmelCase		 = stop_sequence_ids[0]

        return preprocess_params, forward_params, postprocess_params



  def 	a (	self :       Optional[Any]       ,       *__lowerCAmelCase :       Dict       ,       **__lowerCAmelCase :       Optional[Any]       ):


        """simple docstring"""



        if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
              kwargs.update({'add_space_before_punct_symbol': True}       )

        return super()._parse_and_tokenize(*_SCREAMING_SNAKE_CASE       ,       **_SCREAMING_SNAKE_CASE       )



  def __call__(	self :       Optional[Any]       ,       __lowerCAmelCase :       Dict       ,       **__lowerCAmelCase :       List[Any]       ):


        """simple docstring"""



        return super().__call__(_SCREAMING_SNAKE_CASE       ,       **_SCREAMING_SNAKE_CASE       )



  def 	a (	self :       Union[str, Any]       ,       __lowerCAmelCase :       str       ,       __lowerCAmelCase :       Optional[int]=""       ,       __lowerCAmelCase :       Any=None       ,       **__lowerCAmelCase :       Any       ):


        """simple docstring"""



        _lowerCAmelCase		 = self.tokenizer(
            prefix + prompt_text       ,       padding=_SCREAMING_SNAKE_CASE       ,       add_special_tokens=_SCREAMING_SNAKE_CASE       ,       return_tensors=self.framework       )
        _lowerCAmelCase		 = prompt_text

        if handle_long_generation == "hole":
              _lowerCAmelCase		 = inputs['input_ids'].shape[-1]
              if "max_new_tokens" in generate_kwargs:
                    _lowerCAmelCase		 = generate_kwargs['max_new_tokens']
              else:
                    _lowerCAmelCase		 = generate_kwargs.get('max_length'       ,       self.model.config.max_length       ) - cur_len
                    if new_tokens < 0:
                          raise ValueError('We cannot infer how many new tokens are expected'       )
              if cur_len + new_tokens > self.tokenizer.model_max_length:
                    _lowerCAmelCase		 = self.tokenizer.model_max_length - new_tokens
                    if keep_length <= 0:
                          raise ValueError(
                              'We cannot use `hole` to handle this generation the number of desired tokens exceeds the'
                              ' models max length'       )

                    _lowerCAmelCase		 = inputs['input_ids'][:, -keep_length:]
                    if "attention_mask" in inputs:
                          _lowerCAmelCase		 = inputs['attention_mask'][:, -keep_length:]

        return inputs



  def 	a (	self :       Optional[int]       ,       __lowerCAmelCase :       List[Any]       ,       **__lowerCAmelCase :       List[str]       ):


        """simple docstring"""



        _lowerCAmelCase		 = model_inputs['input_ids']
        _lowerCAmelCase		 = model_inputs.get('attention_mask'       ,       _SCREAMING_SNAKE_CASE       )
        # Allow empty prompts
        if input_ids.shape[1] == 0:
              _lowerCAmelCase		 = None
              _lowerCAmelCase		 = None
              _lowerCAmelCase		 = 1
        else:
              _lowerCAmelCase		 = input_ids.shape[0]
        _lowerCAmelCase		 = model_inputs.pop('prompt_text'       )

        # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
        # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
        _lowerCAmelCase		 = generate_kwargs.pop('prefix_length'       ,       0       )
        if prefix_length > 0:
              _lowerCAmelCase		 = 'max_new_tokens' in generate_kwargs or (
                  'generation_config' in generate_kwargs
                  and generate_kwargs['generation_config'].max_new_tokens is not None
              )
              if not has_max_new_tokens:
                    _lowerCAmelCase		 = generate_kwargs.get('max_length'       ) or self.model.config.max_length
                    generate_kwargs["max_length"] += prefix_length
              _lowerCAmelCase		 = 'min_new_tokens' in generate_kwargs or (
                  'generation_config' in generate_kwargs
                  and generate_kwargs['generation_config'].min_new_tokens is not None
              )
              if not has_min_new_tokens and "min_length" in generate_kwargs:
                    generate_kwargs["min_length"] += prefix_length

        # BS x SL
        _lowerCAmelCase		 = self.model.generate(input_ids=_SCREAMING_SNAKE_CASE       ,       attention_mask=_SCREAMING_SNAKE_CASE       ,       **_SCREAMING_SNAKE_CASE       )
        _lowerCAmelCase		 = generated_sequence.shape[0]
        if self.framework == "pt":
              _lowerCAmelCase		 = generated_sequence.reshape(_SCREAMING_SNAKE_CASE       ,       out_b // in_b       ,       *generated_sequence.shape[1:]       )
        elif self.framework == "tf":
              _lowerCAmelCase		 = tf.reshape(_SCREAMING_SNAKE_CASE       ,       (in_b, out_b // in_b, *generated_sequence.shape[1:])       )
        return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}



  def 	a (	self :       Any       ,       __lowerCAmelCase :       List[Any]       ,       __lowerCAmelCase :       Any=ReturnType.FULL_TEXT       ,       __lowerCAmelCase :       Optional[int]=True       ):


        """simple docstring"""



        _lowerCAmelCase		 = model_outputs['generated_sequence'][0]
        _lowerCAmelCase		 = model_outputs['input_ids']
        _lowerCAmelCase		 = model_outputs['prompt_text']
        _lowerCAmelCase		 = generated_sequence.numpy().tolist()
        _lowerCAmelCase		 = []
        for sequence in generated_sequence:
              if return_type == ReturnType.TENSORS:
                    _lowerCAmelCase		 = {'generated_token_ids': sequence}
              elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
                    # Decode text
                    _lowerCAmelCase		 = self.tokenizer.decode(
                        _SCREAMING_SNAKE_CASE       ,       skip_special_tokens=_SCREAMING_SNAKE_CASE       ,       clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE       ,       )

                    # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
                    if input_ids is None:
                          _lowerCAmelCase		 = 0
                    else:
                          _lowerCAmelCase		 = len(
                              self.tokenizer.decode(
                                  input_ids[0]       ,       skip_special_tokens=_SCREAMING_SNAKE_CASE       ,       clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE       ,       )       )

                    if return_type == ReturnType.FULL_TEXT:
                          _lowerCAmelCase		 = prompt_text + text[prompt_length:]
                    else:
                          _lowerCAmelCase		 = text[prompt_length:]

                    _lowerCAmelCase		 = {'generated_text': all_text}
              records.append(_SCREAMING_SNAKE_CASE       )

        return records











'''simple docstring'''





import itertools
import os
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed

import numpy as np

import datasets

from .execute import check_correctness


UpperCamelCase_		:     Dict          =		'''\
@misc{chen2021evaluating,
      title={Evaluating Large Language Models Trained on Code},
      author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \
and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \
and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \
and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \
and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \
and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \
and Mohammad Bavarian and Clemens Winter and Philippe Tillet \
and Felipe Petroski Such and Dave Cummings and Matthias Plappert \
and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \
and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \
and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \
and William Saunders and Christopher Hesse and Andrew N. Carr \
and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \
and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \
and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \
and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},
      year={2021},
      eprint={2107.03374},
      archivePrefix={arXiv},
      primaryClass={cs.LG}
}
'''

UpperCamelCase_		:     int          =		'''\
This metric implements the evaluation harness for the HumanEval problem solving dataset
described in the paper "Evaluating Large Language Models Trained on Code"
(https://arxiv.org/abs/2107.03374).
'''


UpperCamelCase_		:     Optional[Any]          =		'''
Calculates how good are predictions given some references, using certain scores
Args:
    predictions: list of candidates to evaluate. Each candidates should be a list
        of strings with several code candidates to solve the problem.
    references: a list with a test for each prediction. Each test should evaluate the
        correctness of a code candidate.
    k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])
    num_workers: number of workers used to evaluate the canidate programs (Default: 4).
    timeout:
Returns:
    pass_at_k: dict with pass rates for each k
    results: dict with granular results of each unittest
Examples:
    >>> code_eval = datasets.load_metric("code_eval")
    >>> test_cases = ["assert add(2,3)==5"]
    >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]
    >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])
    >>> print(pass_at_k)
    {\'pass@1\': 0.5, \'pass@2\': 1.0}
'''


UpperCamelCase_		:     Optional[int]          =		'''
################################################################################
                                  !!!WARNING!!!
################################################################################
The "code_eval" metric executes untrusted model-generated code in Python.
Although it is highly unlikely that model-generated code will do something
overtly malicious in response to this test suite, model-generated code may act
destructively due to a lack of model capability or alignment.
Users are strongly encouraged to sandbox this evaluation suite so that it
does not perform destructive actions on their host or network. For more
information on how OpenAI sandboxes its code, see the paper "Evaluating Large
Language Models Trained on Code" (https://arxiv.org/abs/2107.03374).

Once you have read this disclaimer and taken appropriate precautions,
set the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this
with:

>>> import os
>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"

################################################################################\
'''

UpperCamelCase_		:     List[Any]          =		'''The MIT License

Copyright (c) OpenAI (https://openai.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.'''

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






     def 							_lowercase      (					self       )				->     Optional[int]:
          return datasets.MetricInfo(
              # This is the description that will appear on the metrics page.
              description=_DESCRIPTION   ,citation=_CITATION   ,inputs_description=_KWARGS_DESCRIPTION   ,features=datasets.Features(
                  {
                      "predictions": datasets.Sequence(datasets.Value("string"       )       ),
                      "references": datasets.Value("string"       ),
                  }       )   ,homepage="https://github.com/openai/human-eval"   ,codebase_urls=["https://github.com/openai/human-eval"]   ,reference_urls=["https://github.com/openai/human-eval"]   ,license=_LICENSE   ,)






     def 							_lowercase      (					self   ,_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE=[1, 10, 100]   ,_SCREAMING_SNAKE_CASE=4   ,_SCREAMING_SNAKE_CASE=3.0       )				->     Any:

          if os.getenv("HF_ALLOW_CODE_EVAL"   ,0       ) != "1":
               raise ValueError(_WARNING       )

          if os.name == "nt":
               raise NotImplementedError("This metric is currently not supported on Windows."       )

          with ThreadPoolExecutor(max_workers=_SCREAMING_SNAKE_CASE       ) as executor:
               _snake_case				= []
               _snake_case				= Counter()
               _snake_case				= 0
               _snake_case				= defaultdict(_SCREAMING_SNAKE_CASE       )

               for task_id, (candidates, test_case) in enumerate(zip(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE       )       ):
                    for candidate in candidates:
                         _snake_case				= candidate + "\n" + test_case
                         _snake_case				= (test_program, timeout, task_id, completion_id[task_id])
                         _snake_case				= executor.submit(_SCREAMING_SNAKE_CASE   ,*_SCREAMING_SNAKE_CASE       )
                         futures.append(_SCREAMING_SNAKE_CASE       )
                         completion_id[task_id] += 1
                         n_samples += 1

               for future in as_completed(_SCREAMING_SNAKE_CASE       ):
                    _snake_case				= future.result()
                    results[result["task_id"]].append((result["completion_id"], result)       )

          _snake_case				,   _snake_case				= [], []
          for result in results.values():
               result.sort()
               _snake_case				= [r[1]["passed"] for r in result]
               total.append(len(_SCREAMING_SNAKE_CASE       )       )
               correct.append(sum(_SCREAMING_SNAKE_CASE       )       )
          _snake_case				= np.array(_SCREAMING_SNAKE_CASE       )
          _snake_case				= np.array(_SCREAMING_SNAKE_CASE       )

          _snake_case				= k
          _snake_case				= {f"""pass@{k}""": estimate_pass_at_k(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE       ).mean() for k in ks if (total >= k).all()}

          return pass_at_k, results







def       __a      (  _UpperCamelCase:       Optional[int]   ,		_UpperCamelCase:       Any   ,		_UpperCamelCase:       List[str]       )		->					List[Any]:

     """simple docstring"""




     def estimator(_UpperCamelCase:       int   ,		_UpperCamelCase:       int   ,		_UpperCamelCase:       int       ) -> float:
          if n - c < k:
               return 1.0
          return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1   ,		n + 1       )       )

     if isinstance(_UpperCamelCase   ,		_UpperCamelCase       ):
          _snake_case				= itertools.repeat(_UpperCamelCase   ,		len(_UpperCamelCase       )       )
     else:
          assert len(_UpperCamelCase       ) == len(_UpperCamelCase       )
          _snake_case				= iter(_UpperCamelCase       )

     return np.array([estimator(int(_UpperCamelCase       )   ,		int(_UpperCamelCase       )   ,		_UpperCamelCase       ) for n, c in zip(_UpperCamelCase   ,		_UpperCamelCase       )]       )


