






from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
 import tensorflow as tf

 from ..tf_utils import stable_softmax


if is_torch_available():
 import torch


lowerCamelCase      :       Optional[int]    =						logging.get_logger(__name__)



@add_end_docstrings(
    a_				,		R"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """				,		)
class 				_UpperCamelCase      (a_      ):


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase						)->						np.ndarray:
           if self.framework == "tf":
                __lowerCAmelCase             =       tf.where(input_ids == self.tokenizer.mask_token_id						).numpy()
           elif self.framework == "pt":
                __lowerCAmelCase             =       torch.nonzero(input_ids == self.tokenizer.mask_token_id       ,    as_tuple=__UpperCamelCase						)
           else:
                raise ValueError("Unsupported framework"						)
           return masked_index


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase						)->						np.ndarray:
           __lowerCAmelCase             =       self.get_masked_index(__UpperCamelCase						)
           __lowerCAmelCase             =       np.prod(masked_index.shape						)
           if numel < 1:
                raise PipelineException(
                    "fill-mask"       ,    self.model.base_model_prefix       ,    F"""No mask_token ({self.tokenizer.mask_token}) found on the input"""       ,    )


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase						)->						Tuple:
           if isinstance(__UpperCamelCase       ,    __UpperCamelCase						):
                for model_input in model_inputs:
                     self._ensure_exactly_one_mask_token(model_input["input_ids"][0]						)
           else:
                for input_ids in model_inputs["input_ids"]:
                     self._ensure_exactly_one_mask_token(__UpperCamelCase						)


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase=None       ,    **__UpperCamelCase						)->						Dict[str, GenericTensor]:
           if return_tensors is None:
                __lowerCAmelCase             =       self.framework
           __lowerCAmelCase             =       self.tokenizer(__UpperCamelCase       ,    return_tensors=__UpperCamelCase						)
           self.ensure_exactly_one_mask_token(__UpperCamelCase						)
           return model_inputs


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase						)->						str:
           __lowerCAmelCase             =       self.model(**__UpperCamelCase						)
           __lowerCAmelCase             =       model_inputs["input_ids"]
           return model_outputs


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase=5       ,    __UpperCamelCase=None						)->						str:
           # Cap top_k if there are targets
           if target_ids is not None and target_ids.shape[0] < top_k:
                __lowerCAmelCase             =       target_ids.shape[0]
           __lowerCAmelCase             =       model_outputs["input_ids"][0]
           __lowerCAmelCase             =       model_outputs["logits"]

           if self.framework == "tf":
                __lowerCAmelCase             =       tf.where(input_ids == self.tokenizer.mask_token_id						).numpy()[:, 0]

                __lowerCAmelCase             =       outputs.numpy()

                __lowerCAmelCase             =       outputs[0, masked_index, :]
                __lowerCAmelCase             =       stable_softmax(__UpperCamelCase       ,    axis=-1						)
                if target_ids is not None:
                     __lowerCAmelCase             =       tf.gather_nd(tf.squeeze(__UpperCamelCase       ,    0						)       ,    target_ids.reshape(-1       ,    1						)						)
                     __lowerCAmelCase             =       tf.expand_dims(__UpperCamelCase       ,    0						)

                __lowerCAmelCase             =       tf.math.top_k(__UpperCamelCase       ,    k=__UpperCamelCase						)
                __lowerCAmelCase      ,			__lowerCAmelCase             =       topk.values.numpy(), topk.indices.numpy()
           else:
                __lowerCAmelCase             =       torch.nonzero(input_ids == self.tokenizer.mask_token_id       ,    as_tuple=__UpperCamelCase						).squeeze(-1						)
                # Fill mask pipeline supports only one ${mask_token} per sample

                __lowerCAmelCase             =       outputs[0, masked_index, :]
                __lowerCAmelCase             =       logits.softmax(dim=-1						)
                if target_ids is not None:
                     __lowerCAmelCase             =       probs[..., target_ids]

                __lowerCAmelCase      ,			__lowerCAmelCase             =       probs.topk(__UpperCamelCase						)

           __lowerCAmelCase             =       []
           __lowerCAmelCase             =       values.shape[0] == 1
           for i, (_values, _predictions) in enumerate(zip(values.tolist()       ,    predictions.tolist()						)						):
                __lowerCAmelCase             =       []
                for v, p in zip(_values       ,    _predictions						):
                     # Copy is important since we're going to modify this array in place
                     __lowerCAmelCase             =       input_ids.numpy().copy()
                     if target_ids is not None:
                          __lowerCAmelCase             =       target_ids[p].tolist()

                     __lowerCAmelCase             =       p
                     # Filter padding out:
                     __lowerCAmelCase             =       tokens[np.where(tokens != self.tokenizer.pad_token_id						)]
                     # Originally we skip special tokens to give readable output.
                     # For multi masks though, the other [MASK] would be removed otherwise
                     # making the output look odd, so we add them back
                     __lowerCAmelCase             =       self.tokenizer.decode(__UpperCamelCase       ,    skip_special_tokens=__UpperCamelCase						)
                     __lowerCAmelCase             =       {"score": v, "token": p, "token_str": self.tokenizer.decode([p]						), "sequence": sequence}
                     row.append(__UpperCamelCase						)
                result.append(__UpperCamelCase						)
           if single_mask:
                return result[0]
           return result


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase=None						)->						Union[str, Any]:
           if isinstance(__UpperCamelCase       ,    __UpperCamelCase						):
                __lowerCAmelCase             =       [targets]
           try:
                __lowerCAmelCase             =       self.tokenizer.get_vocab()
           except Exception:
                __lowerCAmelCase             =       {}
           __lowerCAmelCase             =       []
           for target in targets:
                __lowerCAmelCase             =       vocab.get(__UpperCamelCase       ,    __UpperCamelCase						)
                if id_ is None:
                     __lowerCAmelCase             =       self.tokenizer(
                         __UpperCamelCase       ,    add_special_tokens=__UpperCamelCase       ,    return_attention_mask=__UpperCamelCase       ,    return_token_type_ids=__UpperCamelCase       ,    max_length=1       ,    truncation=__UpperCamelCase       ,    )["input_ids"]
                     if len(__UpperCamelCase						) == 0:
                          logger.warning(
                              F"""The specified target token `{target}` does not exist in the model vocabulary. """
                              "We cannot replace it with anything meaningful, ignoring it"						)
                          continue
                     __lowerCAmelCase             =       input_ids[0]
                     # XXX: If users encounter this pass
                     # it becomes pretty slow, so let's make sure
                     # The warning enables them to fix the input to
                     # get faster performance.
                     logger.warning(
                         F"""The specified target token `{target}` does not exist in the model vocabulary. """
                         F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_						)}`."""						)
                target_ids.append(id_						)
           __lowerCAmelCase             =       list(set(__UpperCamelCase						)						)
           if len(__UpperCamelCase						) == 0:
                raise ValueError("At least one target must be provided when passed."						)
           __lowerCAmelCase             =       np.array(__UpperCamelCase						)
           return target_ids


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase=None       ,    __UpperCamelCase=None						)->						Optional[int]:
           __lowerCAmelCase             =       {}

           if targets is not None:
                __lowerCAmelCase             =       self.get_target_ids(__UpperCamelCase       ,    __UpperCamelCase						)
                __lowerCAmelCase             =       target_ids

           if top_k is not None:
                __lowerCAmelCase             =       top_k

           if self.tokenizer.mask_token_id is None:
                raise PipelineException(
                    "fill-mask"       ,    self.model.base_model_prefix       ,    "The tokenizer does not define a `mask_token`."						)
           return {}, {}, postprocess_params


      def __call__(						self       ,    __UpperCamelCase       ,    *__UpperCamelCase       ,    **__UpperCamelCase						)->						List[str]:
           __lowerCAmelCase             =       super().__call__(__UpperCamelCase       ,    **__UpperCamelCase						)
           if isinstance(__UpperCamelCase       ,    __UpperCamelCase						) and len(__UpperCamelCase						) == 1:
                return outputs[0]
           return outputs














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


lowerCamelCase      :       Tuple    =						'''\
@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}
}
'''

lowerCamelCase      :       List[str]    =						'''\
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).
'''


lowerCamelCase      :       List[str]    =						'''
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}
'''


lowerCamelCase      :       Optional[Any]    =						'''
################################################################################
                                  !!!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"

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

lowerCamelCase      :       Union[str, 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 				_UpperCamelCase      (datasets.Metric      ):


      def 			__UpperCAmelCase		(						self						)->						str:
           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 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase=[1, 1_0, 1_0_0]       ,    __UpperCamelCase=4       ,    __UpperCamelCase=3.0						)->						str:

           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=__UpperCamelCase						) as executor:
                __lowerCAmelCase             =       []
                __lowerCAmelCase             =       Counter()
                __lowerCAmelCase             =       0
                __lowerCAmelCase             =       defaultdict(__UpperCamelCase						)

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

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

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

           __lowerCAmelCase             =       k
           __lowerCAmelCase             =       {F"""pass@{k}""": estimate_pass_at_k(__UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase						).mean() for k in ks if (total >= k).all()}

           return pass_at_k, results





def    __lowerCAmelCase   (    __snake_case       ,			__snake_case       ,			__snake_case							):

     def estimator(__snake_case       ,			__snake_case       ,			__snake_case							) -> 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(__snake_case       ,			__snake_case							):
          __lowerCAmelCase             =       itertools.repeat(__snake_case       ,			len(__snake_case							)							)
     else:
          assert len(__snake_case							) == len(__snake_case							)
          __lowerCAmelCase             =       iter(__snake_case							)

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






