






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   , _A   , _A   , _A=None   , _A=None   , _A=None   , _A=None   , _A=None   , )      ->      List[str]:







				"""simple docstring"""


				if attention_mask is None:
								snake_case__						=  input_ids.ne(config.pad_token_id	)
				if decoder_attention_mask is None:
								snake_case__						=  decoder_input_ids.ne(config.pad_token_id	)
				if head_mask is None:
								snake_case__						=  torch.ones(config.encoder_layers   , config.encoder_attention_heads   , device=_A	)
				if decoder_head_mask is None:
								snake_case__						=  torch.ones(config.decoder_layers   , config.decoder_attention_heads   , device=_A	)
				if cross_attn_head_mask is None:
								snake_case__						=  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:   Tuple							,						UpperCamelCase:   Optional[int]							,						UpperCamelCase:   Optional[Any]=13							,						UpperCamelCase:   Dict=7							,						UpperCamelCase:   Tuple=True							,						UpperCamelCase:   str=False							,						UpperCamelCase:   str=99							,						UpperCamelCase:   List[Any]=16							,						UpperCamelCase:   List[Any]=2							,						UpperCamelCase:   Any=4							,						UpperCamelCase:   List[Any]=4							,						UpperCamelCase:   List[Any]="relu"							,						UpperCamelCase:   Tuple=0.1							,						UpperCamelCase:   Optional[Any]=0.1							,						UpperCamelCase:   List[str]=0.0							,						UpperCamelCase:   List[str]=0.0							,						UpperCamelCase:   str=20							,						UpperCamelCase:   str=2							,						UpperCamelCase:   Dict=1							,						UpperCamelCase:   Optional[Any]=0							,						)		->		str:
											snake_case__						=  parent
											snake_case__						=  batch_size
											snake_case__						=  seq_length
											snake_case__						=  is_training
											snake_case__						=  use_labels
											snake_case__						=  vocab_size
											snake_case__						=  hidden_size
											snake_case__						=  num_hidden_layers
											snake_case__						=  num_attention_heads
											snake_case__						=  intermediate_size
											snake_case__						=  hidden_act
											snake_case__						=  hidden_dropout_prob
											snake_case__						=  attention_probs_dropout_prob
											snake_case__						=  encoder_layerdrop
											snake_case__						=  decoder_layerdrop
											snake_case__						=  max_position_embeddings
											snake_case__						=  eos_token_id
											snake_case__						=  pad_token_id
											snake_case__						=  bos_token_id
							def lowerCAmelCase_			(  self:   Optional[int]    )		->		Dict:
											snake_case__						=  ids_tensor([self.batch_size, self.seq_length]							,						self.vocab_size    )
											snake_case__						=  self.eos_token_id  # Eos Token
											snake_case__						=  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
											snake_case__						=  input_ids.clamp(self.pad_token_id + 1    )
											snake_case__						=  decoder_input_ids.clamp(self.pad_token_id + 1    )

											snake_case__						=  self.get_config()
											snake_case__						=  prepare_mam_aaa_inputs_dict(UpperCamelCase							,						UpperCamelCase							,						UpperCamelCase    )
											return config, inputs_dict
							def lowerCAmelCase_			(  self:   int    )		->		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:   Optional[Any]    )		->		Optional[Any]:
											snake_case__				,    snake_case__						=  self.prepare_config_and_inputs()
											return config, inputs_dict
							def lowerCAmelCase_			(  self:   Dict							,						UpperCamelCase:   Any							,						UpperCamelCase:   int    )		->		str:
											snake_case__						=  MaMaaaModel(config=UpperCamelCase    ).get_decoder().to(UpperCamelCase    ).eval()
											snake_case__						=  inputs_dict['input_ids']
											snake_case__						=  inputs_dict['attention_mask']
											snake_case__						=  inputs_dict['head_mask']

											# first forward pass
											snake_case__						=  model(UpperCamelCase							,						attention_mask=UpperCamelCase							,						head_mask=UpperCamelCase							,						use_cache=UpperCamelCase    )

											snake_case__				,    snake_case__						=  outputs.to_tuple()

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

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

											snake_case__						=  model(UpperCamelCase							,						attention_mask=UpperCamelCase    )['last_hidden_state']
											snake_case__						=  model(UpperCamelCase							,						attention_mask=UpperCamelCase							,						past_key_values=UpperCamelCase    )[
											    'last_hidden_state'
											]

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


							def lowerCAmelCase_			(  self:   Union[str, Any]							,						UpperCamelCase:   int							,						UpperCamelCase:   Optional[Any]    )		->		Dict:
											snake_case__						=  MaMaaaModel(config=UpperCamelCase    ).to(UpperCamelCase    ).eval()
											snake_case__						=  model(**UpperCamelCase    )

											snake_case__						=  outputs.encoder_last_hidden_state
											snake_case__						=  outputs.last_hidden_state

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

											snake_case__						=  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:
															snake_case__						=  model.get_decoder()
															decoder.save_pretrained(UpperCamelCase    )
															snake_case__						=  MaMaaaDecoder.from_pretrained(UpperCamelCase    ).to(UpperCamelCase    )

											snake_case__						=  decoder(
											    input_ids=inputs_dict['decoder_input_ids']							,						attention_mask=inputs_dict['decoder_attention_mask']							,						encoder_hidden_states=UpperCamelCase							,						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(						__lowerCamelCase     ,	__lowerCamelCase     ,	__lowerCamelCase     ,	unittest.TestCase						):
							_UpperCAmelCase			     =							(
							    (
							        MaMaaaModel,
							        MaMaaaForConditionalGeneration,
							    )
							    if is_torch_available()
							    else ()
							)
							_UpperCAmelCase			     =							(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
							_UpperCAmelCase			     =							(
							    {
							        'conversational': MaMaaaForConditionalGeneration,
							        'feature-extraction': MaMaaaModel,
							        'summarization': MaMaaaForConditionalGeneration,
							        'text2text-generation': MaMaaaForConditionalGeneration,
							        'translation': MaMaaaForConditionalGeneration,
							    }
							    if is_torch_available()
							    else {}
							)
							_UpperCAmelCase			     =							True
							_UpperCAmelCase			     =							True
							_UpperCAmelCase			     =							False
							_UpperCAmelCase			     =							False
							def lowerCAmelCase_			(  self:   int							,						UpperCamelCase:   Optional[Any]							,						UpperCamelCase:   List[str]							,						UpperCamelCase:   List[str]							,						UpperCamelCase:   Optional[int]							,						UpperCamelCase:   List[Any]    )		->		List[str]:






											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:   str    )		->		Optional[Any]:
											snake_case__						=  MaMaaaModelTester(self    )
											snake_case__						=  ConfigTester(self							,						config_class=UpperCamelCase    )
							def lowerCAmelCase_			(  self:   List[Any]    )		->		Union[str, Any]:
											self.config_tester.run_common_tests()
							def lowerCAmelCase_			(  self:   Any    )		->		str:
											snake_case__				,    snake_case__						=  self.model_tester.prepare_config_and_inputs()
											for model_class in self.all_model_classes:
															snake_case__						=  model_class(UpperCamelCase    )

															with tempfile.TemporaryDirectory() as tmpdirname:
																			model.save_pretrained(UpperCamelCase    )
																			snake_case__				,    snake_case__						=  model_class.from_pretrained(UpperCamelCase							,						output_loading_info=UpperCamelCase    )
															self.assertEqual(info['missing_keys']							,						[]    )
							def lowerCAmelCase_			(  self:   Optional[Any]    )		->		int:
											snake_case__						=  self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCamelCase    )
							def lowerCAmelCase_			(  self:   Optional[Any]    )		->		Any:
											snake_case__						=  self.model_tester.prepare_config_and_inputs_for_common()
											self.model_tester.check_encoder_decoder_model_standalone(*UpperCamelCase    )
							def lowerCAmelCase_			(  self:   Any    )		->		int:
											snake_case__				,    snake_case__						=  self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
															snake_case__						=  model_class(UpperCamelCase    )
															model.to(UpperCamelCase    )
															model.eval()

															snake_case__						=  copy.deepcopy(self._prepare_for_class(UpperCamelCase							,						UpperCamelCase    )    )

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

															snake_case__						=  model.get_input_embeddings()
															if not self.is_encoder_decoder:
																			snake_case__						=  wte(UpperCamelCase    )
															else:
																			snake_case__						=  wte(UpperCamelCase    )
																			snake_case__						=  wte(UpperCamelCase    )

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


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


def   a_			(   _A	)      ->      Dict:







				"""simple docstring"""
				return torch.tensor(_A   , dtype=torch.long   , device=_A	)


__UpperCamelCase       :		Tuple							=    1E-4


@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class 	__SCREAMING_SNAKE_CASE(						unittest.TestCase						):
							@cached_property
							def lowerCAmelCase_			(  self:   int    )		->		str:
											return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'    )
							def lowerCAmelCase_			(  self:   Tuple    )		->		Union[str, Any]:
											snake_case__						=  MaMaaaModel.from_pretrained('facebook/m2m100_418M'    ).to(UpperCamelCase    )
											snake_case__						=  _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]    )
											snake_case__						=  _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]    )
											snake_case__						=  prepare_mam_aaa_inputs_dict(model.config							,						UpperCamelCase							,						UpperCamelCase    )
											with torch.no_grad():
															snake_case__						=  model(**UpperCamelCase    )[0]
											snake_case__						=  torch.Size((1, 11, 10_24)    )
											self.assertEqual(output.shape							,						UpperCamelCase    )
											# change to expected output here
											snake_case__						=  torch.tensor(
											    [[-0.7_780, -0.1_676, 0.1_038], [-6.7_556, -1.3_992, 0.0_567], [-7.5_383, -0.5_920, -0.2_779]]							,						device=UpperCamelCase    )
											self.assertTrue(torch.allclose(output[:, :3, :3]							,						UpperCamelCase							,						atol=UpperCamelCase    )    )
							def lowerCAmelCase_			(  self:   int    )		->		Any:
											snake_case__						=  MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'    ).to(UpperCamelCase    )

											# change to intended input
											snake_case__						=  _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]    )
											snake_case__						=  _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]    )
											snake_case__						=  prepare_mam_aaa_inputs_dict(model.config							,						UpperCamelCase							,						UpperCamelCase    )
											with torch.no_grad():
															snake_case__						=  model(**UpperCamelCase    )[0]
											snake_case__						=  torch.Size((1, 11, model.config.vocab_size)    )
											self.assertEqual(output.shape							,						UpperCamelCase    )
											# change to expected output here
											snake_case__						=  torch.tensor(
											    [[-1.0_448, -1.0_411, 3.7_992], [-3.2_191, -3.2_386, -1.3_451], [-3.6_210, -3.5_993, 0.4_925]]							,						device=UpperCamelCase    )
											self.assertTrue(torch.allclose(output[:, :3, :3]							,						UpperCamelCase							,						atol=UpperCamelCase    )    )


							def lowerCAmelCase_			(  self:   Tuple    )		->		str:
											snake_case__						=  MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'    ).to(UpperCamelCase    )
											snake_case__						=  MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'							,						src_lang='fr'							,						tgt_lang='en'    )

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

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

											snake_case__						=  [
											    '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.',
											]

											snake_case__						=  tokenizer.batch_decode(
											    hypotheses_batch.tolist()							,						clean_up_tokenization_spaces=UpperCamelCase							,						skip_special_tokens=UpperCamelCase    )
											assert generated == expected_en






from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCAmelCase					   =       logging.get_logger(__name__)

__lowerCAmelCase					   =       {
    'microsoft/biogpt': 'https://huggingface.co/microsoft/biogpt/resolve/main/config.json',
    # See all BioGPT models at https://huggingface.co/models?filter=biogpt
}





class     lowerCamelCase      (       __lowerCamelCase					):
	UpperCamelCase_  :					Union[str, Any]    		=	'biogpt'







	def __init__(     self      :Tuple   ,     lowercase      :Union[str, Any]=4_2_3_8_4   ,     lowercase      :str=1_0_2_4   ,     lowercase      :Any=2_4   ,     lowercase      :List[str]=1_6   ,     lowercase      :List[str]=4_0_9_6   ,     lowercase      :int="gelu"   ,     lowercase      :List[Any]=0.1   ,     lowercase      :int=0.1   ,     lowercase      :int=1_0_2_4   ,     lowercase      :Optional[Any]=0.02   ,     lowercase      :Union[str, Any]=1e-12   ,     lowercase      :Tuple=True   ,     lowercase      :int=True   ,     lowercase      :Optional[int]=0.0   ,     lowercase      :Any=0.0   ,     lowercase      :str=1   ,     lowercase      :Any=0   ,     lowercase      :int=2   ,     **lowercase      :Tuple   ,     )		->      Optional[int]:







				"""simple docstring"""






				SCREAMING_SNAKE_CASE     						= vocab_size
				SCREAMING_SNAKE_CASE     						= max_position_embeddings
				SCREAMING_SNAKE_CASE     						= hidden_size
				SCREAMING_SNAKE_CASE     						= num_hidden_layers
				SCREAMING_SNAKE_CASE     						= num_attention_heads
				SCREAMING_SNAKE_CASE     						= intermediate_size
				SCREAMING_SNAKE_CASE     						= hidden_act
				SCREAMING_SNAKE_CASE     						= hidden_dropout_prob
				SCREAMING_SNAKE_CASE     						= attention_probs_dropout_prob
				SCREAMING_SNAKE_CASE     						= initializer_range
				SCREAMING_SNAKE_CASE     						= layer_norm_eps
				SCREAMING_SNAKE_CASE     						= scale_embedding
				SCREAMING_SNAKE_CASE     						= use_cache
				SCREAMING_SNAKE_CASE     						= layerdrop
				SCREAMING_SNAKE_CASE     						= activation_dropout
				super().__init__(pad_token_id=lowercase   ,     bos_token_id=lowercase   ,     eos_token_id=lowercase   ,     **lowercase			)