






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


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

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


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


SCREAMING_SNAKE_CASE							=						'\n################################################################################\n                                  !!!WARNING!!!\n################################################################################\nThe "code_eval" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper "Evaluating Large\nLanguage Models Trained on Code" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"\n\n################################################################################\\n'

SCREAMING_SNAKE_CASE							=						'The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION					,							_KWARGS_DESCRIPTION					)
class UpperCAmelCase_       (     datasets.Metric					):




      """simple docstring"""




      def 					A__   (			self      :		Optional[int]		)	->	Any:


       '''simple docstring'''

       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 					A__   (			self      :		int  ,   UpperCAmelCase      :		Union[str, Any]  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		Optional[Any]=[1, 10, 100]  ,   UpperCAmelCase      :		List[Any]=4  ,   UpperCAmelCase      :		Dict=3.0		)	->	str:


       '''simple docstring'''

       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:
        lowercase       : Dict						=[]
        lowercase       : List[str]						=Counter()
        lowercase       : Optional[int]						=0
        lowercase       : Union[str, Any]						=defaultdict(UpperCAmelCase		)

        for task_id, (candidates, test_case) in enumerate(zip(UpperCAmelCase  ,   UpperCAmelCase		)		):
         for candidate in candidates:
          lowercase       : Union[str, Any]						=candidate + '''\n''' + test_case
          lowercase       : Any						=(test_program, timeout, task_id, completion_id[task_id])
          lowercase       : Optional[Any]						=executor.submit(UpperCAmelCase  ,   *UpperCAmelCase		)
          futures.append(UpperCAmelCase		)
          completion_id[task_id] += 1
          n_samples += 1

        for future in as_completed(UpperCAmelCase		):
         lowercase       : Tuple						=future.result()
         results[result["task_id"]].append((result['''completion_id'''], result)		)

       lowercase	,		lowercase       : Optional[Any]						=[], []
       for result in results.values():
        result.sort()
        lowercase       : List[str]						=[r[1]['''passed'''] for r in result]
        total.append(len(UpperCAmelCase		)		)
        correct.append(sum(UpperCAmelCase		)		)
       lowercase       : int						=np.array(UpperCAmelCase		)
       lowercase       : List[str]						=np.array(UpperCAmelCase		)

       lowercase       : Optional[int]						=k
       lowercase       : Optional[Any]						={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 				lowercase_					(     __A			:							Optional[int]       ,   __A			:							List[str]       ,   __A			:							int      )							->   Union[str, Any]:



 """simple docstring"""




 def estimator(__A			:							int       ,   __A			:							int       ,   __A			:							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(__A       ,   __A      ):
  lowercase       : Tuple						=itertools.repeat(__A       ,   len(__A      )      )
 else:
  assert len(__A      ) == len(__A      )
  lowercase       : Union[str, Any]						=iter(__A      )

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









from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__A								=       logging.get_logger(__name__)

__A								=       {
    "facebook/xlm-roberta-xl": "https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json",
    "facebook/xlm-roberta-xxl": "https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json",
    # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl
}







class        __lowerCAmelCase					(			__magic_name__					):

			"""simple docstring"""







			snake_case_  						=			'''xlm-roberta-xl'''


			def __init__( self     ,		lowerCamelCase__=250_880     ,		lowerCamelCase__=2_560     ,		lowerCamelCase__=36     ,		lowerCamelCase__=32     ,		lowerCamelCase__=10_240     ,		lowerCamelCase__="gelu"     ,		lowerCamelCase__=0.1     ,		lowerCamelCase__=0.1     ,		lowerCamelCase__=514     ,		lowerCamelCase__=1     ,		lowerCamelCase__=0.02     ,		lowerCamelCase__=1e-05     ,		lowerCamelCase__=1     ,		lowerCamelCase__=0     ,		lowerCamelCase__=2     ,		lowerCamelCase__="absolute"     ,		lowerCamelCase__=True     ,		lowerCamelCase__=None     ,		**lowerCamelCase__     ,		)       -> str:



							'''simple docstring'''
							super().__init__(pad_token_id=lowerCamelCase__     ,		bos_token_id=lowerCamelCase__     ,		eos_token_id=lowerCamelCase__     ,		**lowerCamelCase__				)
							__lowerCamelCase									=       vocab_size
							__lowerCamelCase									=       hidden_size
							__lowerCamelCase									=       num_hidden_layers
							__lowerCamelCase									=       num_attention_heads
							__lowerCamelCase									=       hidden_act
							__lowerCamelCase									=       intermediate_size
							__lowerCamelCase									=       hidden_dropout_prob
							__lowerCamelCase									=       attention_probs_dropout_prob
							__lowerCamelCase									=       max_position_embeddings
							__lowerCamelCase									=       type_vocab_size
							__lowerCamelCase									=       initializer_range
							__lowerCamelCase									=       layer_norm_eps
							__lowerCamelCase									=       position_embedding_type
							__lowerCamelCase									=       use_cache
							__lowerCamelCase									=       classifier_dropout







class        __lowerCAmelCase					(			__magic_name__					):

			"""simple docstring"""







			@property
			def  lowercase_       ( self				)       -> Mapping[str, Mapping[int, str]]:



							'''simple docstring'''
							if self.task == "multiple-choice":
											__lowerCamelCase									=       {0: 'batch', 1: 'choice', 2: 'sequence'}
							else:
											__lowerCamelCase									=       {0: 'batch', 1: 'sequence'}
							return OrderedDict(
							    [
							        ('input_ids', dynamic_axis),
							        ('attention_mask', dynamic_axis),
							    ]				)


