


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


_A		       =						'\\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'

_A		       =						'\\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'


_A		       =						'\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'


_A		       =						'\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'

_A		       =						'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    )  ->       Union[str, Any]:
         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					,   A_					,   A_					,   A_=[1, 10, 100]					,   A_=4					,   A_=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=A_    ) as executor:
              __UpperCamelCase    							=[]
              __UpperCamelCase    							=Counter()
              __UpperCamelCase    							=0
              __UpperCamelCase    							=defaultdict(A_    )

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

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

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

         __UpperCamelCase    							=k
         __UpperCamelCase    							={f'pass@{k}': estimate_pass_at_k(A_					,   A_					,   A_    ).mean() for k in ks if (total >= k).all()}

         return pass_at_k, results

def 						_UpperCAmelCase				(			SCREAMING_SNAKE_CASE__			:					List[str]			,     SCREAMING_SNAKE_CASE__			:					Optional[Any]			,     SCREAMING_SNAKE_CASE__			:					Tuple				):

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

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









from collections import OrderedDict
from typing import Mapping

from packaging import version

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


_A		       =						logging.get_logger(__name__)

_A		       =						{
    'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json',
    # See all YOLOS models at https://huggingface.co/models?filter=yolos
}






class     UpperCAmelCase__       (					A_		):



    """simple docstring"""






    UpperCAmelCase__						:		Optional[int]      =  "yolos"






    def __init__(			self					,   A_=768					,   A_=12					,   A_=12					,   A_=3072					,   A_="gelu"					,   A_=0.0					,   A_=0.0					,   A_=0.02					,   A_=1E-12					,   A_=[512, 864]					,   A_=16					,   A_=3					,   A_=True					,   A_=100					,   A_=True					,   A_=False					,   A_=1					,   A_=5					,   A_=2					,   A_=5					,   A_=2					,   A_=0.1					,   **A_					,   )  ->       Any:
         super().__init__(**A_    )

         __UpperCamelCase    							=hidden_size
         __UpperCamelCase    							=num_hidden_layers
         __UpperCamelCase    							=num_attention_heads
         __UpperCamelCase    							=intermediate_size
         __UpperCamelCase    							=hidden_act
         __UpperCamelCase    							=hidden_dropout_prob
         __UpperCamelCase    							=attention_probs_dropout_prob
         __UpperCamelCase    							=initializer_range
         __UpperCamelCase    							=layer_norm_eps
         __UpperCamelCase    							=image_size
         __UpperCamelCase    							=patch_size
         __UpperCamelCase    							=num_channels
         __UpperCamelCase    							=qkv_bias
         __UpperCamelCase    							=num_detection_tokens
         __UpperCamelCase    							=use_mid_position_embeddings
         __UpperCamelCase    							=auxiliary_loss
         # Hungarian matcher
         __UpperCamelCase    							=class_cost
         __UpperCamelCase    							=bbox_cost
         __UpperCamelCase    							=giou_cost
         # Loss coefficients
         __UpperCamelCase    							=bbox_loss_coefficient
         __UpperCamelCase    							=giou_loss_coefficient
         __UpperCamelCase    							=eos_coefficient






class     UpperCAmelCase__       (					A_		):



    """simple docstring"""






    UpperCAmelCase__						:		str      =  version.parse("1.11"		)






    @property
    def _a					(			self    )  ->       Mapping[str, Mapping[int, str]]:
         return OrderedDict(
             [
                 ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
             ]    )






    @property
    def _a					(			self    )  ->       float:
         return 1E-4






    @property
    def _a					(			self    )  ->       int:
         return 12





