

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      A__					(			__A  :						int     ,				__A  :						Tuple     ,				__A  :						List[Any]     ,				__A  :						Dict=None     ,				__A  :						Tuple=None     ,				__A  :						str=None     ,				__A  :						Any=None     ,				__A  :						Tuple=None     ,				)					->int:
      if attention_mask is None:
            __A    =input_ids.ne(config.pad_token_id			)
      if decoder_attention_mask is None:
            __A    =decoder_input_ids.ne(config.pad_token_id			)
      if head_mask is None:
            __A    =torch.ones(config.encoder_layers     ,				config.encoder_attention_heads     ,				device=__A			)
      if decoder_head_mask is None:
            __A    =torch.ones(config.decoder_layers     ,				config.decoder_attention_heads     ,				device=__A			)
      if cross_attn_head_mask is None:
            __A    =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        lowerCAmelCase__  :



       '''simple docstring'''







       def __init__(							self ,   lowercase__ ,   lowercase__=1_3 ,   lowercase__=7 ,   lowercase__=True ,   lowercase__=False ,   lowercase__=9_9 ,   lowercase__=1_6 ,   lowercase__=2 ,   lowercase__=4 ,   lowercase__=4 ,   lowercase__="relu" ,   lowercase__=0.1 ,   lowercase__=0.1 ,   lowercase__=0.0 ,   lowercase__=0.0 ,   lowercase__=2_0 ,   lowercase__=2 ,   lowercase__=1 ,   lowercase__=0 ,   ):







             '''simple docstring'''



             __A    =parent
             __A    =batch_size
             __A    =seq_length
             __A    =is_training
             __A    =use_labels
             __A    =vocab_size
             __A    =hidden_size
             __A    =num_hidden_layers
             __A    =num_attention_heads
             __A    =intermediate_size
             __A    =hidden_act
             __A    =hidden_dropout_prob
             __A    =attention_probs_dropout_prob
             __A    =encoder_layerdrop
             __A    =decoder_layerdrop
             __A    =max_position_embeddings
             __A    =eos_token_id
             __A    =pad_token_id
             __A    =bos_token_id

       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             __A    =ids_tensor([self.batch_size, self.seq_length] ,   self.vocab_size     )
             __A    =self.eos_token_id  # Eos Token
             __A    =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    =input_ids.clamp(self.pad_token_id + 1     )
             __A    =decoder_input_ids.clamp(self.pad_token_id + 1     )

             __A    =self.get_config()
             __A    =prepare_mam_aaa_inputs_dict(lowercase__ ,   lowercase__ ,   lowercase__     )
             return config, inputs_dict

       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



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







             '''simple docstring'''



             __A    ,		__A    =self.prepare_config_and_inputs()
             return config, inputs_dict

       def     __UpperCamelCase     (							self ,   lowercase__ ,   lowercase__     ):







             '''simple docstring'''



             __A    =MaMaaaModel(config=lowercase__     ).get_decoder().to(lowercase__     ).eval()
             __A    =inputs_dict['''input_ids''']
             __A    =inputs_dict['''attention_mask''']
             __A    =inputs_dict['''head_mask''']

             # first forward pass
             __A    =model(lowercase__ ,   attention_mask=lowercase__ ,   head_mask=lowercase__ ,   use_cache=lowercase__     )

             __A    ,		__A    =outputs.to_tuple()

             # create hypothetical multiple next token and extent to next_input_ids
             __A    =ids_tensor((self.batch_size, 3) ,   config.vocab_size     )
             __A    =ids_tensor((self.batch_size, 3) ,   2     )

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

             __A    =model(lowercase__ ,   attention_mask=lowercase__     )['''last_hidden_state''']
             __A    =model(lowercase__ ,   attention_mask=lowercase__ ,   past_key_values=lowercase__     )[
                 '''last_hidden_state'''
             ]

             # select random slice
             __A    =ids_tensor((1,) ,   output_from_past.shape[-1]     ).item()
             __A    =output_from_no_past[:, -3:, random_slice_idx].detach()
             __A    =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(lowercase__ ,   lowercase__ ,   atol=1E-2     )     )


       def     __UpperCamelCase     (							self ,   lowercase__ ,   lowercase__     ):







             '''simple docstring'''



             __A    =MaMaaaModel(config=lowercase__     ).to(lowercase__     ).eval()
             __A    =model(**lowercase__     )

             __A    =outputs.encoder_last_hidden_state
             __A    =outputs.last_hidden_state

             with tempfile.TemporaryDirectory() as tmpdirname:
                   __A    =model.get_encoder()
                   encoder.save_pretrained(lowercase__     )
                   __A    =MaMaaaEncoder.from_pretrained(lowercase__     ).to(lowercase__     )

             __A    =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    =model.get_decoder()
                   decoder.save_pretrained(lowercase__     )
                   __A    =MaMaaaDecoder.from_pretrained(lowercase__     ).to(lowercase__     )

             __A    =decoder(
                 input_ids=inputs_dict['''decoder_input_ids'''] ,   attention_mask=inputs_dict['''decoder_attention_mask'''] ,   encoder_hidden_states=lowercase__ ,   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        lowerCAmelCase__  (					__magic_name__				,							__magic_name__				,							__magic_name__				,							unittest.TestCase			):



       '''simple docstring'''







       lowercase_						=    (
           (
               MaMaaaModel,
               MaMaaaForConditionalGeneration,
           )
           if is_torch_available()
           else ()
       )
       lowercase_						=    (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
       lowercase_						=    (
           {
               """conversational""": MaMaaaForConditionalGeneration,
               """feature-extraction""": MaMaaaModel,
               """summarization""": MaMaaaForConditionalGeneration,
               """text2text-generation""": MaMaaaForConditionalGeneration,
               """translation""": MaMaaaForConditionalGeneration,
           }
           if is_torch_available()
           else {}
       )
       lowercase_						=    True
       lowercase_						=    True
       lowercase_						=    False
       lowercase_						=    False

       def     __UpperCamelCase     (							self ,   lowercase__ ,   lowercase__ ,   lowercase__ ,   lowercase__ ,   lowercase__     ):







             '''simple docstring'''



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







             '''simple docstring'''



             __A    =MaMaaaModelTester(self     )
             __A    =ConfigTester(self ,   config_class=lowercase__     )

       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             self.config_tester.run_common_tests()

       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             __A    ,		__A    =self.model_tester.prepare_config_and_inputs()
             for model_class in self.all_model_classes:
                   __A    =model_class(lowercase__     )

                   with tempfile.TemporaryDirectory() as tmpdirname:
                         model.save_pretrained(lowercase__     )
                         __A    ,		__A    =model_class.from_pretrained(lowercase__ ,   output_loading_info=lowercase__     )
                   self.assertEqual(info['''missing_keys'''] ,   []     )

       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             __A    =self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowercase__     )

       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             __A    =self.model_tester.prepare_config_and_inputs_for_common()
             self.model_tester.check_encoder_decoder_model_standalone(*lowercase__     )

       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             __A    ,		__A    =self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
                   __A    =model_class(lowercase__     )
                   model.to(lowercase__     )
                   model.eval()

                   __A    =copy.deepcopy(self._prepare_for_class(lowercase__ ,   lowercase__     )     )

                   if not self.is_encoder_decoder:
                         __A    =inputs['''input_ids''']
                         del inputs["input_ids"]
                   else:
                         __A    =inputs['''input_ids''']
                         __A    =inputs.get('''decoder_input_ids''' ,   lowercase__     )
                         del inputs["input_ids"]
                         inputs.pop('''decoder_input_ids''' ,   lowercase__     )

                   __A    =model.get_input_embeddings()
                   if not self.is_encoder_decoder:
                         __A    =wte(lowercase__     )
                   else:
                         __A    =wte(lowercase__     )
                         __A    =wte(lowercase__     )

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


       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             __A    ,		__A    =self.model_tester.prepare_config_and_inputs()
             __A    =input_dict['''input_ids''']
             __A    =input_ids.ne(1     ).to(lowercase__     )
             __A    =MaMaaaForConditionalGeneration(lowercase__     ).eval().to(lowercase__     )
             if torch_device == "cuda":
                   model.half()
             model.generate(lowercase__ ,   attention_mask=lowercase__     )
             model.generate(num_beams=4 ,   do_sample=lowercase__ ,   early_stopping=lowercase__ ,   num_return_sequences=3     )





def      A__					(			__A  :						int			)					->List[Any]:
      return torch.tensor(__A     ,				dtype=torch.long     ,				device=__A			)


_lowerCamelCase      :					Any					    =      1e-4





@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class        lowerCAmelCase__  (					unittest.TestCase			):



       '''simple docstring'''







       @cached_property
       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             return MaMaaaTokenizer.from_pretrained('''facebook/m2m100_418M'''     )

       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             __A    =MaMaaaModel.from_pretrained('''facebook/m2m100_418M'''     ).to(lowercase__     )
             __A    =_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    =_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    =prepare_mam_aaa_inputs_dict(model.config ,   lowercase__ ,   lowercase__     )
             with torch.no_grad():
                   __A    =model(**lowercase__     )[0]
             __A    =torch.Size((1, 1_1, 1_0_2_4)     )
             self.assertEqual(output.shape ,   lowercase__     )
             # change to expected output here
             __A    =torch.tensor(
                 [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]] ,   device=lowercase__     )
             self.assertTrue(torch.allclose(output[:, :3, :3] ,   lowercase__ ,   atol=lowercase__     )     )

       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             __A    =MaMaaaForConditionalGeneration.from_pretrained('''facebook/m2m100_418M'''     ).to(lowercase__     )

             # change to intended input
             __A    =_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    =_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    =prepare_mam_aaa_inputs_dict(model.config ,   lowercase__ ,   lowercase__     )
             with torch.no_grad():
                   __A    =model(**lowercase__     )[0]
             __A    =torch.Size((1, 1_1, model.config.vocab_size)     )
             self.assertEqual(output.shape ,   lowercase__     )
             # change to expected output here
             __A    =torch.tensor(
                 [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]] ,   device=lowercase__     )
             self.assertTrue(torch.allclose(output[:, :3, :3] ,   lowercase__ ,   atol=lowercase__     )     )


       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             __A    =MaMaaaForConditionalGeneration.from_pretrained('''facebook/m2m100_418M'''     ).to(lowercase__     )
             __A    =MaMaaaTokenizer.from_pretrained('''facebook/m2m100_418M''' ,   src_lang='''fr''' ,   tgt_lang='''en'''     )

             __A    =[
                 '''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    =tokenizer(lowercase__ ,   padding=lowercase__ ,   return_tensors='''pt'''     )

             __A    =model.generate(
                 input_ids=dct['''input_ids'''].to(lowercase__     ) ,   attention_mask=dct['''attention_mask'''].to(lowercase__     ) ,   num_beams=5 ,   forced_bos_token_id=tokenizer.get_lang_id('''en'''     ) ,   )

             __A    =[
                 '''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    =tokenizer.batch_decode(
                 hypotheses_batch.tolist() ,   clean_up_tokenization_spaces=lowercase__ ,   skip_special_tokens=lowercase__     )
             assert generated == expected_en





# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re

from ..utils import cached_file


# docstyle-ignore
_lowerCamelCase      :					Optional[int]					    =      '''
Human: <<task>>

Assistant: '''


_lowerCamelCase      :					str					    =      '''huggingface-tools/default-prompts'''
_lowerCamelCase      :					Optional[int]					    =      {'''chat''': '''chat_prompt_template.txt''', '''run''': '''run_prompt_template.txt'''}





def      A__					(			__A  :						Dict     ,				__A  :						Dict     ,				__A  :						Optional[Any]="run"			)					->Any:
      if prompt_or_repo_id is None:
            __A    =DEFAULT_PROMPTS_REPO

      # prompt is considered a repo ID when it does not contain any kind of space
      if re.search('''\\s'''     ,				__A			) is not None:
            return prompt_or_repo_id

      __A    =cached_file(
          __A     ,				PROMPT_FILES[mode]     ,				repo_type='''dataset'''     ,				user_agent={'''agent''': agent_name}			)
      with open(__A     ,				'''r'''     ,				encoding='''utf-8'''			) as f:
            return f.read()


