





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


a__							:							List[str] ='''\
@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__							:							Optional[Any] ='''\
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__							:							Optional[int] ='''
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__							:							Dict ='''
################################################################################
                                  !!!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__							:							Optional[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      snake_case     (    datasets.Metric       ):




 """simple docstring"""



 def        _lowerCamelCase					(       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        _lowerCamelCase					(       self       :							Union[str, Any]							,	__A       :							Dict							,	__A       :							Tuple							,	__A       :							List[str]=[1, 1_0, 1_0_0]							,	__A       :							Dict=4							,	__A       :							List[str]=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:
               __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 				lowercase__   (   __lowercase						:  Optional[Any]				,  __lowercase						:  int				,  __lowercase						:  Union[str, Any]     ) ->      Optional[int]:



       """simple docstring"""






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

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







'''simple docstring'''
import argparse

import torch
from torch import nn

from transformers import MBartConfig, MBartForConditionalGeneration
def 				lowercase__   (   __lowercase						:  Any     ) ->      Union[str, Any]:



       """simple docstring"""






       __UpperCamelCase       =  [
           'encoder.version',
           'decoder.version',
           'model.encoder.version',
           'model.decoder.version',
           '_float_tensor',
           'decoder.output_projection.weight',
       ]
       for k in ignore_keys:
              state_dict.pop(__lowercase				,  __lowercase     )
def 				lowercase__   (   __lowercase						:  Tuple     ) ->      int:



       """simple docstring"""






       __UpperCamelCase       ,						__UpperCamelCase       =  emb.weight.shape
       __UpperCamelCase       =  nn.Linear(__lowercase				,  __lowercase				,  bias=__lowercase     )
       __UpperCamelCase       =  emb.weight.data
       return lin_layer
def 				lowercase__   (   __lowercase						:  int				,  __lowercase						:  List[str]="facebook/mbart-large-en-ro"				,  __lowercase						:  str=False				,  __lowercase						:  List[Any]=False     ) ->      int:



       """simple docstring"""






       __UpperCamelCase       =  torch.load(__lowercase				,  map_location='cpu'     )['model']
       remove_ignore_keys_(__lowercase     )
       __UpperCamelCase       =  state_dict['encoder.embed_tokens.weight'].shape[0]

       __UpperCamelCase       =  MBartConfig.from_pretrained(__lowercase				,  vocab_size=__lowercase     )
       if mbart_aa and finetuned:
              __UpperCamelCase       =  'relu'

       __UpperCamelCase       =  state_dict['decoder.embed_tokens.weight']
       __UpperCamelCase       =  MBartForConditionalGeneration(__lowercase     )
       model.model.load_state_dict(__lowercase     )

       if finetuned:
              __UpperCamelCase       =  make_linear_from_emb(model.model.shared     )

       return model


if __name__ == "__main__":
    a__							:							Dict =argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.'''
    )
    parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
    parser.add_argument(
        '''--hf_config''',
        default='''facebook/mbart-large-cc25''',
        type=str,
        help='''Which huggingface architecture to use: mbart-large''',
    )
    parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''')
    parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''')
    a__							:							Union[str, Any] =parser.parse_args()
    a__							:							str =convert_fairseq_mbart_checkpoint_from_disk(
        args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa
    )
    model.save_pretrained(args.pytorch_dump_folder_path)
