

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_       : Optional[int]         =			'''\
@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}
}
'''

A_       : Tuple         =			'''\
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).
'''


A_       : Dict         =			'''
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}
'''


A_       : 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"

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

A_       : 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				):


					'''simple docstring'''






					def   __A			( self			):
						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			):

						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:
							A__							:    Any        =		[]
							A__							:    Optional[int]        =		Counter()
							A__							:    Dict        =		0
							A__							:    Dict        =		defaultdict(A__			)

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

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

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

						A__							:    Any        =		k
						A__							:    Tuple        =		{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					(lowercase_: Any    ,      lowercase_: Tuple    ,      lowercase_: int					)     ->      Optional[int]:

	def estimator(lowercase_: int    ,      lowercase_: int    ,      lowercase_: 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					):
		A__							:    Tuple        =		itertools.repeat(_UpperCAmelCase    ,      len(_UpperCAmelCase					)					)
	else:
		assert len(_UpperCAmelCase					) == len(_UpperCAmelCase					)
		A__							:    List[Any]        =		iter(_UpperCAmelCase					)

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







'''simple docstring'''







import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
   import bitsandbytes as bnb
   import torch
   import torch.nn as nn

   from ..pytorch_utils import ConvaD

if is_accelerate_available():
   from accelerate import init_empty_weights
   from accelerate.utils import find_tied_parameters

A__:    str					    =       logging.get_logger(__name__)


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	List[Any]    ,_UpperCAmelCase	:	List[str]    ,_UpperCAmelCase	:	int    ,_UpperCAmelCase	:	int=None    ,_UpperCAmelCase	:	Optional[Any]=None  )  ->			Optional[Any]:
       # Recurse if needed
       if "." in tensor_name:
              _a    : Union[str, Any]     					=tensor_name.split("""."""  )
              for split in splits[:-1]:
                     _a    : Optional[Any]     					=getattr(_UpperCAmelCase    ,_UpperCAmelCase  )
                     if new_module is None:
                            raise ValueError(F"{module} has no attribute {split}."  )
                     _a    : Optional[int]     					=new_module
              _a    : Optional[int]     					=splits[-1]

       if tensor_name not in module._parameters and tensor_name not in module._buffers:
              raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}."  )
       _a    : Optional[Any]     					=tensor_name in module._buffers
       _a    : str     					=getattr(_UpperCAmelCase    ,_UpperCAmelCase  )

       if old_value.device == torch.device("""meta"""  ) and device not in ["meta", torch.device("""meta"""  )] and value is None:
              raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}."  )

       _a    : int     					=False
       _a    : Tuple     					=False
       if is_buffer or not is_bitsandbytes_available():
              _a    : str     					=False
              _a    : Optional[Any]     					=False
       else:
              _a    : int     					=hasattr(bnb.nn    ,"""Params4bit"""  ) and isinstance(module._parameters[tensor_name]    ,bnb.nn.Paramsabit  )
              _a    : int     					=isinstance(module._parameters[tensor_name]    ,bnb.nn.IntaParams  )

       if is_abit or is_abit:
              _a    : Any     					=module._parameters[tensor_name]
              if param.device.type != "cuda":
                     if value is None:
                            _a    : int     					=old_value.to(_UpperCAmelCase  )
                     elif isinstance(_UpperCAmelCase    ,torch.Tensor  ):
                            _a    : str     					=value.to("""cpu"""  )
                            if value.dtype == torch.inta:
                                   _a    : int     					=version.parse(importlib.metadata.version("""bitsandbytes"""  )  ) > version.parse(
                                       """0.37.2"""  )
                                   if not is_abit_serializable:
                                          raise ValueError(
                                              """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """
                                              """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."""  )
                     else:
                            _a    : Dict     					=torch.tensor(_UpperCAmelCase    ,device="""cpu"""  )

                     # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
                     # Since weights are saved in the correct "orientation", we skip transposing when loading.
                     if issubclass(module.source_cls    ,_UpperCAmelCase  ) and fpaa_statistics is None:
                            _a    : int     					=new_value.T

                     _a    : Any     					=old_value.__dict__
                     if is_abit:
                            _a    : Any     					=bnb.nn.IntaParams(_UpperCAmelCase    ,requires_grad=_UpperCAmelCase    ,**_UpperCAmelCase  ).to(_UpperCAmelCase  )
                     elif is_abit:
                            _a    : Union[str, Any]     					=bnb.nn.Paramsabit(_UpperCAmelCase    ,requires_grad=_UpperCAmelCase    ,**_UpperCAmelCase  ).to(_UpperCAmelCase  )

                     _a    : List[Any]     					=new_value
                     if fpaa_statistics is not None:
                            setattr(module.weight    ,"""SCB"""    ,fpaa_statistics.to(_UpperCAmelCase  )  )

       else:
              if value is None:
                     _a    : str     					=old_value.to(_UpperCAmelCase  )
              elif isinstance(_UpperCAmelCase    ,torch.Tensor  ):
                     _a    : Any     					=value.to(_UpperCAmelCase  )
              else:
                     _a    : str     					=torch.tensor(_UpperCAmelCase    ,device=_UpperCAmelCase  )

              if is_buffer:
                     _a    : Optional[int]     					=new_value
              else:
                     _a    : Optional[Any]     					=nn.Parameter(_UpperCAmelCase    ,requires_grad=old_value.requires_grad  )
                     _a    : Tuple     					=new_value


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	Tuple    ,_UpperCAmelCase	:	Union[str, Any]=None    ,_UpperCAmelCase	:	List[Any]=None    ,_UpperCAmelCase	:	str=None    ,_UpperCAmelCase	:	Union[str, Any]=False  )  ->			Dict:
       for name, module in model.named_children():
              if current_key_name is None:
                     _a    : Optional[int]     					=[]
              current_key_name.append(_UpperCAmelCase  )

              if (isinstance(_UpperCAmelCase    ,nn.Linear  ) or isinstance(_UpperCAmelCase    ,_UpperCAmelCase  )) and name not in modules_to_not_convert:
                     # Check if the current key is not in the `modules_to_not_convert`
                     if not any(key in """.""".join(_UpperCAmelCase  ) for key in modules_to_not_convert  ):
                            with init_empty_weights():
                                   if isinstance(_UpperCAmelCase    ,_UpperCAmelCase  ):
                                          _a					,    _a    : int     					=module.weight.shape
                                   else:
                                          _a    : List[str]     					=module.in_features
                                          _a    : Tuple     					=module.out_features

                                   if quantization_config.quantization_method() == "llm_int8":
                                          _a    : Optional[Any]     					=bnb.nn.LinearabitLt(
                                              _UpperCAmelCase    ,_UpperCAmelCase    ,module.bias is not None    ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight    ,threshold=quantization_config.llm_inta_threshold    ,)
                                          _a    : Optional[Any]     					=True
                                   else:
                                          if (
                                              quantization_config.llm_inta_skip_modules is not None
                                              and name in quantization_config.llm_inta_skip_modules
                                          ):
                                                 pass
                                          else:
                                                 _a    : Dict     					=bnb.nn.Linearabit(
                                                     _UpperCAmelCase    ,_UpperCAmelCase    ,module.bias is not None    ,quantization_config.bnb_abit_compute_dtype    ,compress_statistics=quantization_config.bnb_abit_use_double_quant    ,quant_type=quantization_config.bnb_abit_quant_type    ,)
                                                 _a    : List[Any]     					=True
                    # Store the module class in case we need to transpose the weight later
                                   _a    : int     					=type(_UpperCAmelCase  )
                                   # Force requires grad to False to avoid unexpected errors
                                   model._modules[name].requires_grad_(_UpperCAmelCase  )
              if len(list(module.children()  )  ) > 0:
                     _a					,    _a    : List[Any]     					=_replace_with_bnb_linear(
                         _UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase    ,has_been_replaced=_UpperCAmelCase    ,)
              # Remove the last key for recursion
              current_key_name.pop(-1  )
       return model, has_been_replaced


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	Tuple    ,_UpperCAmelCase	:	int=None    ,_UpperCAmelCase	:	Union[str, Any]=None    ,_UpperCAmelCase	:	Any=None  )  ->			Tuple:
       _a    : Dict     					=["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert
       _a					,    _a    : List[Any]     					=_replace_with_bnb_linear(
           _UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase  )

       if not has_been_replaced:
              logger.warning(
                  """You are loading your model in 8bit or 4bit but no linear modules were found in your model."""
                  """ Please double check your model architecture, or submit an issue on github if you think this is"""
                  """ a bug."""  )

       return model


def 	SCREAMING_SNAKE_CASE_					(  *_UpperCAmelCase	:	Any    ,**_UpperCAmelCase	:	Any  )  ->			str:
       warnings.warn(
           """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead"""    ,_UpperCAmelCase    ,)
       return replace_with_bnb_linear(*_UpperCAmelCase    ,**_UpperCAmelCase  )


def 	SCREAMING_SNAKE_CASE_					(  *_UpperCAmelCase	:	str    ,**_UpperCAmelCase	:	Optional[int]  )  ->			Optional[int]:
       warnings.warn(
           """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead"""    ,_UpperCAmelCase    ,)
       return set_module_quantized_tensor_to_device(*_UpperCAmelCase    ,**_UpperCAmelCase  )


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	int  )  ->			Union[str, Any]:
       _a    : Any     					=deepcopy(_UpperCAmelCase  )  # this has 0 cost since it is done inside `init_empty_weights` context manager`
       tied_model.tie_weights()

       _a    : List[Any]     					=find_tied_parameters(_UpperCAmelCase  )
       # For compatibility with Accelerate < 0.18
       if isinstance(_UpperCAmelCase    ,_UpperCAmelCase  ):
              _a    : str     					=sum(list(tied_params.values()  )    ,[]  ) + list(tied_params.keys()  )
       else:
              _a    : Optional[int]     					=sum(_UpperCAmelCase    ,[]  )
       _a    : List[Any]     					=len(_UpperCAmelCase  ) > 0

       # Check if it is a base model
       _a    : Tuple     					=not hasattr(_UpperCAmelCase    ,model.base_model_prefix  )

       # Ignore this for base models (BertModel, GPT2Model, etc.)
       if (not has_tied_params) and is_base_model:
              return []

       # otherwise they have an attached head
       _a    : List[Any]     					=list(model.named_children()  )
       _a    : Dict     					=[list_modules[-1][0]]

       # add last module together with tied weights
       _a    : List[str]     					=set(_UpperCAmelCase  ) - set(_UpperCAmelCase  )
       _a    : str     					=list(set(_UpperCAmelCase  )  ) + list(_UpperCAmelCase  )

       # remove ".weight" from the keys
       _a    : List[Any]     					=[""".weight""", """.bias"""]
       _a    : Any     					=[]
       for name in list_untouched:
              for name_to_remove in names_to_remove:
                     if name_to_remove in name:
                            _a    : Any     					=name.replace(_UpperCAmelCase    ,""""""  )
              filtered_module_names.append(_UpperCAmelCase  )

       return filtered_module_names


