


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


UpperCAmelCase_   :				Optional[Any]						      = '\\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'

UpperCAmelCase_   :				Union[str, Any]						      = '\\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'


UpperCAmelCase_   :				int						      = '\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'


UpperCAmelCase_   :				int						      = '\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'

UpperCAmelCase_   :				Any						      = '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 				SCREAMING_SNAKE_CASE__						(       datasets.Metric    ):
      def  SCREAMING_SNAKE_CASE							( self       : List[Any]  )	->    Dict:
             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  SCREAMING_SNAKE_CASE							( self       : Dict  ,							SCREAMING_SNAKE_CASE__       : List[str]  ,							SCREAMING_SNAKE_CASE__       : List[str]  ,							SCREAMING_SNAKE_CASE__       : Optional[Any]=[1, 1_0, 1_0_0]  ,							SCREAMING_SNAKE_CASE__       : Any=4  ,							SCREAMING_SNAKE_CASE__       : Tuple=3.0  )	->    int:

             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=SCREAMING_SNAKE_CASE__  ) as executor:
                    a_      :	Tuple							=						[]
                    a_      :	Optional[int]							=						Counter()
                    a_      :	Optional[int]							=						0
                    a_      :	Dict							=						defaultdict(SCREAMING_SNAKE_CASE__  )

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

                    for future in as_completed(SCREAMING_SNAKE_CASE__  ):
                           a_      :	List[str]							=						future.result()
                           results[result["task_id"]].append((result['completion_id'], result)  )

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

             a_      :	List[Any]							=						k
             a_      :	List[Any]							=						{F"""pass@{k}""": estimate_pass_at_k(SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  ).mean() for k in ks if (total >= k).all()}

             return pass_at_k, results







def  SCREAMING_SNAKE_CASE_		(    __A				:    Any						,					__A				:    Optional[int]						,					__A				:    str       )			->	List[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       ):
              a_      :	int							=						itertools.repeat(__A						,					len(__A       )       )
       else:
              assert len(__A       ) == len(__A       )
              a_      :	str							=						iter(__A       )

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






import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
   from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder







def  SCREAMING_SNAKE_CASE_		(    __A				:    int						,					__A				:    Tuple						,					__A				:    int						,					__A				:    Any=None						,					__A				:    str=None						,					__A				:    Any=None						,					__A				:    Optional[int]=None						,					__A				:    str=None						,					)			->	List[str]:

       """simple docstring"""

       if attention_mask is None:
              a_      :	List[Any]							=						input_ids.ne(config.pad_token_id       )
       if decoder_attention_mask is None:
              a_      :	str							=						decoder_input_ids.ne(config.pad_token_id       )
       if head_mask is None:
              a_      :	Any							=						torch.ones(config.encoder_layers						,					config.encoder_attention_heads						,					device=__A       )
       if decoder_head_mask is None:
              a_      :	int							=						torch.ones(config.decoder_layers						,					config.decoder_attention_heads						,					device=__A       )
       if cross_attn_head_mask is None:
              a_      :	Union[str, Any]							=						torch.ones(config.decoder_layers						,					config.decoder_attention_heads						,					device=__A       )
       return {
           "input_ids": input_ids,
           "decoder_input_ids": decoder_input_ids,
           "attention_mask": attention_mask,
           "decoder_attention_mask": attention_mask,
           "head_mask": head_mask,
           "decoder_head_mask": decoder_head_mask,
           "cross_attn_head_mask": cross_attn_head_mask,
       }
class 				SCREAMING_SNAKE_CASE__						:
      def __init__( self       : List[str]  ,							SCREAMING_SNAKE_CASE__       : str  ,							SCREAMING_SNAKE_CASE__       : Dict=1_3  ,							SCREAMING_SNAKE_CASE__       : int=7  ,							SCREAMING_SNAKE_CASE__       : Optional[Any]=True  ,							SCREAMING_SNAKE_CASE__       : Any=False  ,							SCREAMING_SNAKE_CASE__       : int=9_9  ,							SCREAMING_SNAKE_CASE__       : int=1_6  ,							SCREAMING_SNAKE_CASE__       : str=2  ,							SCREAMING_SNAKE_CASE__       : Any=4  ,							SCREAMING_SNAKE_CASE__       : Union[str, Any]=4  ,							SCREAMING_SNAKE_CASE__       : Union[str, Any]="relu"  ,							SCREAMING_SNAKE_CASE__       : Tuple=0.1  ,							SCREAMING_SNAKE_CASE__       : Any=0.1  ,							SCREAMING_SNAKE_CASE__       : Dict=0.0  ,							SCREAMING_SNAKE_CASE__       : Optional[int]=0.0  ,							SCREAMING_SNAKE_CASE__       : Optional[int]=2_0  ,							SCREAMING_SNAKE_CASE__       : List[str]=2  ,							SCREAMING_SNAKE_CASE__       : Union[str, Any]=1  ,							SCREAMING_SNAKE_CASE__       : Tuple=0  ,							)	->    Dict:
             a_      :	Dict							=						parent
             a_      :	List[str]							=						batch_size
             a_      :	Optional[int]							=						seq_length
             a_      :	str							=						is_training
             a_      :	List[str]							=						use_labels
             a_      :	Optional[Any]							=						vocab_size
             a_      :	str							=						hidden_size
             a_      :	Optional[int]							=						num_hidden_layers
             a_      :	Any							=						num_attention_heads
             a_      :	Tuple							=						intermediate_size
             a_      :	int							=						hidden_act
             a_      :	List[Any]							=						hidden_dropout_prob
             a_      :	Tuple							=						attention_probs_dropout_prob
             a_      :	Dict							=						encoder_layerdrop
             a_      :	Union[str, Any]							=						decoder_layerdrop
             a_      :	Tuple							=						max_position_embeddings
             a_      :	Tuple							=						eos_token_id
             a_      :	Optional[int]							=						pad_token_id
             a_      :	Union[str, Any]							=						bos_token_id
      def  SCREAMING_SNAKE_CASE							( self       : List[str]  )	->    Any:
             a_      :	List[Any]							=						ids_tensor([self.batch_size, self.seq_length]  ,							self.vocab_size  )
             a_      :	List[str]							=						self.eos_token_id  # Eos Token
             a_      :	str							=						ids_tensor([self.batch_size, self.seq_length]  ,							self.vocab_size  )

             # we need to clamp the input ids here to avoid having pad token in between
             # this is because for M2M100 the position_ids are prepared such that
             # all pad tokens have pos id = 2 and rest are between 2..seq_length
             # and the seq_length here is seq_length - num_pad_tokens
             # but when using past, there is no way of knowing if the past input ids had
             # pad tokens in them, which results in incorrect seq_lenth and which in turn results in
             # position_ids being off by num_pad_tokens in past input
             a_      :	Optional[int]							=						input_ids.clamp(self.pad_token_id + 1  )
             a_      :	Union[str, Any]							=						decoder_input_ids.clamp(self.pad_token_id + 1  )

             a_      :	Any							=						self.get_config()
             a_      :	List[str]							=						prepare_mam_aaa_inputs_dict(SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  )
             return config, inputs_dict
      def  SCREAMING_SNAKE_CASE							( self       : int  )	->    Any:
             return MaMaaaConfig(
                 vocab_size=self.vocab_size  ,							d_model=self.hidden_size  ,							encoder_layers=self.num_hidden_layers  ,							decoder_layers=self.num_hidden_layers  ,							encoder_attention_heads=self.num_attention_heads  ,							decoder_attention_heads=self.num_attention_heads  ,							encoder_ffn_dim=self.intermediate_size  ,							decoder_ffn_dim=self.intermediate_size  ,							dropout=self.hidden_dropout_prob  ,							attention_dropout=self.attention_probs_dropout_prob  ,							encoder_layerdrop=self.encoder_layerdrop  ,							decoder_layerdrop=self.decoder_layerdrop  ,							max_position_embeddings=self.max_position_embeddings  ,							eos_token_id=self.eos_token_id  ,							bos_token_id=self.bos_token_id  ,							pad_token_id=self.pad_token_id  ,							)
      def  SCREAMING_SNAKE_CASE							( self       : Union[str, Any]  )	->    int:
             a_							,	a_      :	List[Any]							=						self.prepare_config_and_inputs()
             return config, inputs_dict
      def  SCREAMING_SNAKE_CASE							( self       : Optional[Any]  ,							SCREAMING_SNAKE_CASE__       : Optional[int]  ,							SCREAMING_SNAKE_CASE__       : Optional[int]  )	->    Tuple:
             a_      :	Tuple							=						MaMaaaModel(config=SCREAMING_SNAKE_CASE__  ).get_decoder().to(SCREAMING_SNAKE_CASE__  ).eval()
             a_      :	List[str]							=						inputs_dict['input_ids']
             a_      :	List[str]							=						inputs_dict['attention_mask']
             a_      :	int							=						inputs_dict['head_mask']

             # first forward pass
             a_      :	List[Any]							=						model(SCREAMING_SNAKE_CASE__  ,							attention_mask=SCREAMING_SNAKE_CASE__  ,							head_mask=SCREAMING_SNAKE_CASE__  ,							use_cache=SCREAMING_SNAKE_CASE__  )

             a_							,	a_      :	Optional[Any]							=						outputs.to_tuple()

             # create hypothetical multiple next token and extent to next_input_ids
             a_      :	Union[str, Any]							=						ids_tensor((self.batch_size, 3)  ,							config.vocab_size  )
             a_      :	Any							=						ids_tensor((self.batch_size, 3)  ,							2  )

             # append to next input_ids and
             a_      :	Tuple							=						torch.cat([input_ids, next_tokens]  ,							dim=-1  )
             a_      :	str							=						torch.cat([attention_mask, next_attn_mask]  ,							dim=-1  )

             a_      :	Optional[int]							=						model(SCREAMING_SNAKE_CASE__  ,							attention_mask=SCREAMING_SNAKE_CASE__  )['last_hidden_state']
             a_      :	int							=						model(SCREAMING_SNAKE_CASE__  ,							attention_mask=SCREAMING_SNAKE_CASE__  ,							past_key_values=SCREAMING_SNAKE_CASE__  )[
                 'last_hidden_state'
             ]

             # select random slice
             a_      :	str							=						ids_tensor((1,)  ,							output_from_past.shape[-1]  ).item()
             a_      :	Optional[int]							=						output_from_no_past[:, -3:, random_slice_idx].detach()
             a_      :	Optional[int]							=						output_from_past[:, :, random_slice_idx].detach()

             self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]  )

             # test that outputs are equal for slice
             self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  ,							atol=1E-2  )  )

      def  SCREAMING_SNAKE_CASE							( self       : int  ,							SCREAMING_SNAKE_CASE__       : int  ,							SCREAMING_SNAKE_CASE__       : Any  )	->    Any:
             a_      :	int							=						MaMaaaModel(config=SCREAMING_SNAKE_CASE__  ).to(SCREAMING_SNAKE_CASE__  ).eval()
             a_      :	Dict							=						model(**SCREAMING_SNAKE_CASE__  )

             a_      :	str							=						outputs.encoder_last_hidden_state
             a_      :	int							=						outputs.last_hidden_state

             with tempfile.TemporaryDirectory() as tmpdirname:
                    a_      :	Dict							=						model.get_encoder()
                    encoder.save_pretrained(SCREAMING_SNAKE_CASE__  )
                    a_      :	Tuple							=						MaMaaaEncoder.from_pretrained(SCREAMING_SNAKE_CASE__  ).to(SCREAMING_SNAKE_CASE__  )

             a_      :	int							=						encoder(inputs_dict['input_ids']  ,							attention_mask=inputs_dict['attention_mask']  )[
                 0
             ]

             self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3  )

             with tempfile.TemporaryDirectory() as tmpdirname:
                    a_      :	Tuple							=						model.get_decoder()
                    decoder.save_pretrained(SCREAMING_SNAKE_CASE__  )
                    a_      :	int							=						MaMaaaDecoder.from_pretrained(SCREAMING_SNAKE_CASE__  ).to(SCREAMING_SNAKE_CASE__  )

             a_      :	Union[str, Any]							=						decoder(
                 input_ids=inputs_dict['decoder_input_ids']  ,							attention_mask=inputs_dict['decoder_attention_mask']  ,							encoder_hidden_states=SCREAMING_SNAKE_CASE__  ,							encoder_attention_mask=inputs_dict['attention_mask']  ,							)[0]

             self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3  )
@require_torch
class 				SCREAMING_SNAKE_CASE__						(       lowercase__		,					lowercase__		,					lowercase__		,					unittest.TestCase    ):
      snake_case__       :  Optional[int]       =		(
          (
              MaMaaaModel,
              MaMaaaForConditionalGeneration,
          )
          if is_torch_available()
          else ()
      )
      snake_case__       :  Optional[int]       =		(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
      snake_case__       :  Union[str, Any]       =		(
          {
              '''conversational''': MaMaaaForConditionalGeneration,
              '''feature-extraction''': MaMaaaModel,
              '''summarization''': MaMaaaForConditionalGeneration,
              '''text2text-generation''': MaMaaaForConditionalGeneration,
              '''translation''': MaMaaaForConditionalGeneration,
          }
          if is_torch_available()
          else {}
      )
      snake_case__       :  str       =		True
      snake_case__       :  Dict       =		True
      snake_case__       :  Dict       =		False
      snake_case__       :  Any       =		False
      def  SCREAMING_SNAKE_CASE							( self       : Optional[int]  ,							SCREAMING_SNAKE_CASE__       : int  ,							SCREAMING_SNAKE_CASE__       : Any  ,							SCREAMING_SNAKE_CASE__       : str  ,							SCREAMING_SNAKE_CASE__       : Optional[int]  ,							SCREAMING_SNAKE_CASE__       : List[Any]  )	->    int:
             if pipeline_test_casse_name == "TranslationPipelineTests":
                    # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
                    # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
                    return True

             return False
      def  SCREAMING_SNAKE_CASE							( self       : Tuple  )	->    List[str]:
             a_      :	Optional[int]							=						MaMaaaModelTester(self  )
             a_      :	Optional[int]							=						ConfigTester(self  ,							config_class=SCREAMING_SNAKE_CASE__  )
      def  SCREAMING_SNAKE_CASE							( self       : int  )	->    str:
             self.config_tester.run_common_tests()
      def  SCREAMING_SNAKE_CASE							( self       : Optional[Any]  )	->    Optional[Any]:
             a_							,	a_      :	Optional[int]							=						self.model_tester.prepare_config_and_inputs()
             for model_class in self.all_model_classes:
                    a_      :	List[Any]							=						model_class(SCREAMING_SNAKE_CASE__  )

                    with tempfile.TemporaryDirectory() as tmpdirname:
                           model.save_pretrained(SCREAMING_SNAKE_CASE__  )
                           a_							,	a_      :	Optional[Any]							=						model_class.from_pretrained(SCREAMING_SNAKE_CASE__  ,							output_loading_info=SCREAMING_SNAKE_CASE__  )
                    self.assertEqual(info['missing_keys']  ,							[]  )
      def  SCREAMING_SNAKE_CASE							( self       : str  )	->    Tuple:
             a_      :	Dict							=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_decoder_model_past_large_inputs(*SCREAMING_SNAKE_CASE__  )
      def  SCREAMING_SNAKE_CASE							( self       : List[str]  )	->    Any:
             a_      :	Optional[Any]							=						self.model_tester.prepare_config_and_inputs_for_common()
             self.model_tester.check_encoder_decoder_model_standalone(*SCREAMING_SNAKE_CASE__  )
      def  SCREAMING_SNAKE_CASE							( self       : Tuple  )	->    List[Any]:
             a_							,	a_      :	int							=						self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
                    a_      :	str							=						model_class(SCREAMING_SNAKE_CASE__  )
                    model.to(SCREAMING_SNAKE_CASE__  )
                    model.eval()

                    a_      :	List[str]							=						copy.deepcopy(self._prepare_for_class(SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  )  )

                    if not self.is_encoder_decoder:
                           a_      :	int							=						inputs['input_ids']
                           del inputs["input_ids"]
                    else:
                           a_      :	str							=						inputs['input_ids']
                           a_      :	str							=						inputs.get('decoder_input_ids'  ,							SCREAMING_SNAKE_CASE__  )
                           del inputs["input_ids"]
                           inputs.pop('decoder_input_ids'  ,							SCREAMING_SNAKE_CASE__  )

                    a_      :	List[str]							=						model.get_input_embeddings()
                    if not self.is_encoder_decoder:
                           a_      :	Any							=						wte(SCREAMING_SNAKE_CASE__  )
                    else:
                           a_      :	Optional[int]							=						wte(SCREAMING_SNAKE_CASE__  )
                           a_      :	Any							=						wte(SCREAMING_SNAKE_CASE__  )

                    with torch.no_grad():
                           model(**SCREAMING_SNAKE_CASE__  )[0]

      def  SCREAMING_SNAKE_CASE							( self       : Tuple  )	->    Dict:
             a_							,	a_      :	Dict							=						self.model_tester.prepare_config_and_inputs()
             a_      :	Union[str, Any]							=						input_dict['input_ids']
             a_      :	List[Any]							=						input_ids.ne(1  ).to(SCREAMING_SNAKE_CASE__  )
             a_      :	List[str]							=						MaMaaaForConditionalGeneration(SCREAMING_SNAKE_CASE__  ).eval().to(SCREAMING_SNAKE_CASE__  )
             if torch_device == "cuda":
                    model.half()
             model.generate(SCREAMING_SNAKE_CASE__  ,							attention_mask=SCREAMING_SNAKE_CASE__  )
             model.generate(num_beams=4  ,							do_sample=SCREAMING_SNAKE_CASE__  ,							early_stopping=SCREAMING_SNAKE_CASE__  ,							num_return_sequences=3  )







def  SCREAMING_SNAKE_CASE_		(    __A				:    Any       )			->	Optional[int]:

       """simple docstring"""

       return torch.tensor(__A						,					dtype=torch.long						,					device=__A       )


UpperCAmelCase_   :				int						      = 1e-4
@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class 				SCREAMING_SNAKE_CASE__						(       unittest.TestCase    ):
      @cached_property
      def  SCREAMING_SNAKE_CASE							( self       : List[str]  )	->    Tuple:
             return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'  )
      def  SCREAMING_SNAKE_CASE							( self       : List[Any]  )	->    Union[str, Any]:
             a_      :	Union[str, Any]							=						MaMaaaModel.from_pretrained('facebook/m2m100_418M'  ).to(SCREAMING_SNAKE_CASE__  )
             a_      :	List[Any]							=						_long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]]  )
             a_      :	List[Any]							=						_long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]]  )
             a_      :	List[Any]							=						prepare_mam_aaa_inputs_dict(model.config  ,							SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  )
             with torch.no_grad():
                    a_      :	Tuple							=						model(**SCREAMING_SNAKE_CASE__  )[0]
             a_      :	int							=						torch.Size((1, 1_1, 1_0_2_4)  )
             self.assertEqual(output.shape  ,							SCREAMING_SNAKE_CASE__  )
             # change to expected output here
             a_      :	Optional[Any]							=						torch.tensor(
                 [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]  ,							device=SCREAMING_SNAKE_CASE__  )
             self.assertTrue(torch.allclose(output[:, :3, :3]  ,							SCREAMING_SNAKE_CASE__  ,							atol=SCREAMING_SNAKE_CASE__  )  )
      def  SCREAMING_SNAKE_CASE							( self       : Optional[int]  )	->    List[Any]:
             a_      :	int							=						MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'  ).to(SCREAMING_SNAKE_CASE__  )

             # change to intended input
             a_      :	List[str]							=						_long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]]  )
             a_      :	Optional[int]							=						_long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]]  )
             a_      :	int							=						prepare_mam_aaa_inputs_dict(model.config  ,							SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  )
             with torch.no_grad():
                    a_      :	List[str]							=						model(**SCREAMING_SNAKE_CASE__  )[0]
             a_      :	int							=						torch.Size((1, 1_1, model.config.vocab_size)  )
             self.assertEqual(output.shape  ,							SCREAMING_SNAKE_CASE__  )
             # change to expected output here
             a_      :	Dict							=						torch.tensor(
                 [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]  ,							device=SCREAMING_SNAKE_CASE__  )
             self.assertTrue(torch.allclose(output[:, :3, :3]  ,							SCREAMING_SNAKE_CASE__  ,							atol=SCREAMING_SNAKE_CASE__  )  )

      def  SCREAMING_SNAKE_CASE							( self       : int  )	->    Tuple:
             a_      :	Dict							=						MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'  ).to(SCREAMING_SNAKE_CASE__  )
             a_      :	str							=						MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'  ,							src_lang='fr'  ,							tgt_lang='en'  )

             a_      :	List[str]							=						[
                 'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement',
                 'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.',
                 'Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent'
                 ' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de'
                 ' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.',
             ]

             # The below article tests that we don't add any hypotheses outside of the top n_beams
             a_      :	Any							=						tokenizer(SCREAMING_SNAKE_CASE__  ,							padding=SCREAMING_SNAKE_CASE__  ,							return_tensors='pt'  )

             a_      :	Optional[int]							=						model.generate(
                 input_ids=dct['input_ids'].to(SCREAMING_SNAKE_CASE__  )  ,							attention_mask=dct['attention_mask'].to(SCREAMING_SNAKE_CASE__  )  ,							num_beams=5  ,							forced_bos_token_id=tokenizer.get_lang_id('en'  )  ,							)

             a_      :	Any							=						[
                 'The NSA case highlights the total absence of intelligence debate',
                 'I think there are two levels of response from the French government.',
                 'When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.'
                 ' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all'
                 ' communications in France.',
             ]

             a_      :	int							=						tokenizer.batch_decode(
                 hypotheses_batch.tolist()  ,							clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__  ,							skip_special_tokens=SCREAMING_SNAKE_CASE__  )
             assert generated == expected_en


