


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 							__lowercase     (				__lowerCAmelCase							:       Union[str, Any]      ,					__lowerCAmelCase							:       str      ,					__lowerCAmelCase							:       Optional[Any]      ,					__lowerCAmelCase							:       str=None      ,					__lowerCAmelCase							:       str=None      ,					__lowerCAmelCase							:       str=None      ,					__lowerCAmelCase							:       List[Any]=None      ,					__lowerCAmelCase							:       Tuple=None      ,					):
       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=__lowerCAmelCase     )
       if decoder_head_mask is None:
              a__    =  torch.ones(config.decoder_layers      ,					config.decoder_attention_heads      ,					device=__lowerCAmelCase     )
       if cross_attn_head_mask is None:
              a__    =  torch.ones(config.decoder_layers      ,					config.decoder_attention_heads      ,					device=__lowerCAmelCase     )
       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  snake_case_     :
     def __init__(   self     :List[str]    ,__snake_case     :Optional[Any]    ,__snake_case     :Dict=13    ,__snake_case     :str=7    ,__snake_case     :Tuple=True    ,__snake_case     :Optional[int]=False    ,__snake_case     :List[Any]=99    ,__snake_case     :str=16    ,__snake_case     :Optional[Any]=2    ,__snake_case     :List[str]=4    ,__snake_case     :Optional[Any]=4    ,__snake_case     :int="relu"    ,__snake_case     :Dict=0.1    ,__snake_case     :List[str]=0.1    ,__snake_case     :Union[str, Any]=0.0    ,__snake_case     :Any=0.0    ,__snake_case     :List[str]=20    ,__snake_case     :Tuple=2    ,__snake_case     :Dict=1    ,__snake_case     :Optional[Any]=0    ,)      ->					List[Any]:
            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 				lowerCamelCase__(   self     :Any   )      ->					List[str]:
            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(__snake_case    ,__snake_case    ,__snake_case   )
            return config, inputs_dict
     def 				lowerCamelCase__(   self     :List[str]   )      ->					str:
            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 				lowerCamelCase__(   self     :int   )      ->					str:
            a__   ,      a__    =  self.prepare_config_and_inputs()
            return config, inputs_dict
     def 				lowerCamelCase__(   self     :Optional[int]    ,__snake_case     :Dict    ,__snake_case     :Optional[Any]   )      ->					Union[str, Any]:
            a__    =  MaMaaaModel(config=__snake_case   ).get_decoder().to(__snake_case   ).eval()
            a__    =  inputs_dict['input_ids']
            a__    =  inputs_dict['attention_mask']
            a__    =  inputs_dict['head_mask']

            # first forward pass
            a__    =  model(__snake_case    ,attention_mask=__snake_case    ,head_mask=__snake_case    ,use_cache=__snake_case   )

            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(__snake_case    ,attention_mask=__snake_case   )['last_hidden_state']
            a__    =  model(__snake_case    ,attention_mask=__snake_case    ,past_key_values=__snake_case   )[
                '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(__snake_case    ,__snake_case    ,atol=1E-2   )   )



     def 				lowerCamelCase__(   self     :Tuple    ,__snake_case     :Any    ,__snake_case     :Dict   )      ->					Optional[int]:
            a__    =  MaMaaaModel(config=__snake_case   ).to(__snake_case   ).eval()
            a__    =  model(**__snake_case   )

            a__    =  outputs.encoder_last_hidden_state
            a__    =  outputs.last_hidden_state

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

            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(__snake_case   )
                   a__    =  MaMaaaDecoder.from_pretrained(__snake_case   ).to(__snake_case   )

            a__    =  decoder(
                input_ids=inputs_dict['decoder_input_ids']    ,attention_mask=inputs_dict['decoder_attention_mask']    ,encoder_hidden_states=__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  snake_case_     (lowerCamelCase_			,		lowerCamelCase_			,		lowerCamelCase_			,		unittest.TestCase   ):
     UpperCAmelCase__      :					Optional[int]					   =    (
         (
             MaMaaaModel,
             MaMaaaForConditionalGeneration,
         )
         if is_torch_available()
         else ()
     )
     UpperCAmelCase__      :					int					   =    (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
     UpperCAmelCase__      :					str					   =    (
         {
             '''conversational''': MaMaaaForConditionalGeneration,
             '''feature-extraction''': MaMaaaModel,
             '''summarization''': MaMaaaForConditionalGeneration,
             '''text2text-generation''': MaMaaaForConditionalGeneration,
             '''translation''': MaMaaaForConditionalGeneration,
         }
         if is_torch_available()
         else {}
     )
     UpperCAmelCase__      :					int					   =    True
     UpperCAmelCase__      :					Union[str, Any]					   =    True
     UpperCAmelCase__      :					Union[str, Any]					   =    False
     UpperCAmelCase__      :					Union[str, Any]					   =    False
     def 				lowerCamelCase__(   self     :Dict    ,__snake_case     :int    ,__snake_case     :Any    ,__snake_case     :List[Any]    ,__snake_case     :List[str]    ,__snake_case     :List[Any]   )      ->					Tuple:
            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 				lowerCamelCase__(   self     :List[Any]   )      ->					Dict:
            a__    =  MaMaaaModelTester(self   )
            a__    =  ConfigTester(self    ,config_class=__snake_case   )
     def 				lowerCamelCase__(   self     :int   )      ->					Dict:
            self.config_tester.run_common_tests()
     def 				lowerCamelCase__(   self     :List[str]   )      ->					List[Any]:
            a__   ,      a__    =  self.model_tester.prepare_config_and_inputs()
            for model_class in self.all_model_classes:
                   a__    =  model_class(__snake_case   )

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

            for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
                   a__    =  model_class(__snake_case   )
                   model.to(__snake_case   )
                   model.eval()

                   a__    =  copy.deepcopy(self._prepare_for_class(__snake_case    ,__snake_case   )   )

                   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'    ,__snake_case   )
                          del inputs["input_ids"]
                          inputs.pop('decoder_input_ids'    ,__snake_case   )

                   a__    =  model.get_input_embeddings()
                   if not self.is_encoder_decoder:
                          a__    =  wte(__snake_case   )
                   else:
                          a__    =  wte(__snake_case   )
                          a__    =  wte(__snake_case   )

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



     def 				lowerCamelCase__(   self     :Any   )      ->					Tuple:
            a__   ,      a__    =  self.model_tester.prepare_config_and_inputs()
            a__    =  input_dict['input_ids']
            a__    =  input_ids.ne(1   ).to(__snake_case   )
            a__    =  MaMaaaForConditionalGeneration(__snake_case   ).eval().to(__snake_case   )
            if torch_device == "cuda":
                   model.half()
            model.generate(__snake_case    ,attention_mask=__snake_case   )
            model.generate(num_beams=4    ,do_sample=__snake_case    ,early_stopping=__snake_case    ,num_return_sequences=3   )






def 							__lowercase     (				__lowerCAmelCase							:       Optional[int]     ):
       return torch.tensor(__lowerCAmelCase      ,					dtype=torch.long      ,					device=__lowerCAmelCase     )


snake_case							: Any      =   1e-4







@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class  snake_case_     (unittest.TestCase   ):
     @cached_property
     def 				lowerCamelCase__(   self     :Optional[int]   )      ->					Optional[Any]:
            return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'   )
     def 				lowerCamelCase__(   self     :Union[str, Any]   )      ->					Optional[Any]:
            a__    =  MaMaaaModel.from_pretrained('facebook/m2m100_418M'   ).to(__snake_case   )
            a__    =  _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]   )
            a__    =  _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]   )
            a__    =  prepare_mam_aaa_inputs_dict(model.config    ,__snake_case    ,__snake_case   )
            with torch.no_grad():
                   a__    =  model(**__snake_case   )[0]
            a__    =  torch.Size((1, 11, 10_24)   )
            self.assertEqual(output.shape    ,__snake_case   )
            # change to expected output here
            a__    =  torch.tensor(
                [[-0.77_80, -0.16_76, 0.10_38], [-6.75_56, -1.39_92, 0.05_67], [-7.53_83, -0.59_20, -0.27_79]]    ,device=__snake_case   )
            self.assertTrue(torch.allclose(output[:, :3, :3]    ,__snake_case    ,atol=__snake_case   )   )
     def 				lowerCamelCase__(   self     :Tuple   )      ->					Optional[int]:
            a__    =  MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'   ).to(__snake_case   )

            # change to intended input
            a__    =  _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]   )
            a__    =  _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]   )
            a__    =  prepare_mam_aaa_inputs_dict(model.config    ,__snake_case    ,__snake_case   )
            with torch.no_grad():
                   a__    =  model(**__snake_case   )[0]
            a__    =  torch.Size((1, 11, model.config.vocab_size)   )
            self.assertEqual(output.shape    ,__snake_case   )
            # change to expected output here
            a__    =  torch.tensor(
                [[-1.04_48, -1.04_11, 3.79_92], [-3.21_91, -3.23_86, -1.34_51], [-3.62_10, -3.59_93, 0.49_25]]    ,device=__snake_case   )
            self.assertTrue(torch.allclose(output[:, :3, :3]    ,__snake_case    ,atol=__snake_case   )   )



     def 				lowerCamelCase__(   self     :Dict   )      ->					Union[str, Any]:
            a__    =  MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'   ).to(__snake_case   )
            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(__snake_case    ,padding=__snake_case    ,return_tensors='pt'   )

            a__    =  model.generate(
                input_ids=dct['input_ids'].to(__snake_case   )    ,attention_mask=dct['attention_mask'].to(__snake_case   )    ,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=__snake_case    ,skip_special_tokens=__snake_case   )
            assert generated == expected_en








def 							__lowercase     (				__lowerCAmelCase							:       int     ):
							a__    =  generate_pascal_triangle(__lowerCAmelCase     )
							for row_idx in range(__lowerCAmelCase     ):
														# Print left spaces
														for _ in range(num_rows - row_idx - 1     ):
																					print(end=' '     )
														# Print row values
														for col_idx in range(row_idx + 1     ):
																					if col_idx != row_idx:
																												print(triangle[row_idx][col_idx]      ,					end=' '     )
																					else:
																												print(triangle[row_idx][col_idx]      ,					end=''     )
														print()






def 							__lowercase     (				__lowerCAmelCase							:       int     ):

							if not isinstance(__lowerCAmelCase      ,					__lowerCAmelCase     ):
														raise TypeError('The input value of \'num_rows\' should be \'int\''     )

							if num_rows == 0:
														return []
							elif num_rows < 0:
														raise ValueError(
														    'The input value of \'num_rows\' should be greater than or equal to 0'     )

							a__    =  []
							for current_row_idx in range(__lowerCAmelCase     ):
														a__    =  populate_current_row(__lowerCAmelCase      ,					__lowerCAmelCase     )
														triangle.append(__lowerCAmelCase     )
							return triangle






def 							__lowercase     (				__lowerCAmelCase							:       list[list[int]]      ,					__lowerCAmelCase							:       int     ):
							a__    =  [-1] * (current_row_idx + 1)
							# first and last elements of current row are equal to 1
							a__   ,      a__    =  1, 1
							for current_col_idx in range(1      ,					__lowerCAmelCase     ):
														calculate_current_element(
														    __lowerCAmelCase      ,					__lowerCAmelCase      ,					__lowerCAmelCase      ,					__lowerCAmelCase     )
							return current_row






def 							__lowercase     (				__lowerCAmelCase							:       list[list[int]]      ,					__lowerCAmelCase							:       list[int]      ,					__lowerCAmelCase							:       int      ,					__lowerCAmelCase							:       int      ,					):
							a__    =  triangle[current_row_idx - 1][current_col_idx - 1]
							a__    =  triangle[current_row_idx - 1][current_col_idx]
							a__    =  above_to_left_elt + above_to_right_elt






def 							__lowercase     (				__lowerCAmelCase							:       int     ):

							if not isinstance(__lowerCAmelCase      ,					__lowerCAmelCase     ):
														raise TypeError('The input value of \'num_rows\' should be \'int\''     )

							if num_rows == 0:
														return []
							elif num_rows < 0:
														raise ValueError(
														    'The input value of \'num_rows\' should be greater than or equal to 0'     )

							a__    =  [[1]]

							for row_index in range(1      ,					__lowerCAmelCase     ):
														a__    =  [0] + result[-1] + [0]
														a__    =  row_index + 1
														# Calculate the number of distinct elements in a row
														a__    =  sum(divmod(__lowerCAmelCase      ,					2     )     )
														a__    =  [
														    temp_row[i - 1] + temp_row[i] for i in range(1      ,					distinct_elements + 1     )
														]
														a__    =  row_first_half[: (row_index + 1) // 2]
														row_second_half.reverse()
														a__    =  row_first_half + row_second_half
														result.append(__lowerCAmelCase     )

							return result






def 							__lowercase     (				):
							from collections.abc import Callable
							from timeit import timeit

							def benchmark_a_function(__lowerCAmelCase							:       Callable      ,					__lowerCAmelCase							:       int     ) -> None:
														a__    =  F'{func.__name__}({value})'
														a__    =  timeit(F'__main__.{call}'      ,					setup='import __main__'     )
														# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
														print(F'{call:38} -- {timing:.4f} seconds'     )

							for value in range(1_5     ):  # (1, 7, 14):
														for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
																					benchmark_a_function(__lowerCAmelCase      ,					__lowerCAmelCase     )
														print()


if __name__ == "__main__":
						import doctest

						doctest.testmod()
						benchmark()




