





'''simple docstring'''







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  _lowerCamelCase				( lowercase						:      str    ,							lowercase						:      Dict    ,							lowercase						:      Tuple    ,							lowercase						:      Optional[Any]=None    ,							lowercase						:      Union[str, Any]=None    ,							lowercase						:      Any=None    ,							lowercase						:      str=None    ,							lowercase						:      Optional[int]=None    ,							)	->	str:
				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=lowercase						)
				if decoder_head_mask is None:
								_a								= torch.ones(config.decoder_layers    ,							config.decoder_attention_heads    ,							device=lowercase						)
				if cross_attn_head_mask is None:
								_a								= torch.ones(config.decoder_layers    ,							config.decoder_attention_heads    ,							device=lowercase						)
				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  :






				"""simple docstring"""







				def __init__(  self     :					List[Any]					,				__a     :					List[str]					,				__a     :					Tuple=13					,				__a     :					str=7					,				__a     :					Any=True					,				__a     :					Union[str, Any]=False					,				__a     :					int=99					,				__a     :					Tuple=16					,				__a     :					Any=2					,				__a     :					Tuple=4					,				__a     :					int=4					,				__a     :					Tuple="relu"					,				__a     :					List[Any]=0.1					,				__a     :					Union[str, Any]=0.1					,				__a     :					Any=0.0					,				__a     :					Union[str, Any]=0.0					,				__a     :					List[Any]=20					,				__a     :					List[Any]=2					,				__a     :					Optional[Any]=1					,				__a     :					int=0					,				):
								_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     :					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(__a					,				__a					,				__a					)
								return config, inputs_dict




				def   UpperCamelCase__   (  self     :					List[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   UpperCamelCase__   (  self     :					List[Any]					):
								_a	,					_a								= self.prepare_config_and_inputs()
								return config, inputs_dict




				def   UpperCamelCase__   (  self     :					int					,				__a     :					Dict					,				__a     :					Dict					):
								_a								= MaMaaaModel(config=__a					).get_decoder().to(__a					).eval()
								_a								= inputs_dict["input_ids"]
								_a								= inputs_dict["attention_mask"]
								_a								= inputs_dict["head_mask"]

								# first forward pass
								_a								= model(__a					,				attention_mask=__a					,				head_mask=__a					,				use_cache=__a					)

								_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(__a					,				attention_mask=__a					)["last_hidden_state"]
								_a								= model(__a					,				attention_mask=__a					,				past_key_values=__a					)[
								    "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(__a					,				__a					,				atol=1e-2					)					)




				def   UpperCamelCase__   (  self     :					List[str]					,				__a     :					str					,				__a     :					Optional[int]					):
								_a								= MaMaaaModel(config=__a					).to(__a					).eval()
								_a								= model(**__a					)

								_a								= outputs.encoder_last_hidden_state
								_a								= outputs.last_hidden_state

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

								_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(__a					)
												_a								= MaMaaaDecoder.from_pretrained(__a					).to(__a					)

								_a								= decoder(
								    input_ids=inputs_dict["decoder_input_ids"]					,				attention_mask=inputs_dict["decoder_attention_mask"]					,				encoder_hidden_states=__a					,				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      ):






				"""simple docstring"""







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




				def   UpperCamelCase__   (  self     :					int					,				__a     :					str					,				__a     :					str					,				__a     :					List[str]					,				__a     :					str					,				__a     :					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   UpperCamelCase__   (  self     :					Dict					):
								_a								= MaMaaaModelTester(self					)
								_a								= ConfigTester(self					,				config_class=__a					)




				def   UpperCamelCase__   (  self     :					str					):
								self.config_tester.run_common_tests()




				def   UpperCamelCase__   (  self     :					Dict					):
								_a	,					_a								= self.model_tester.prepare_config_and_inputs()
								for model_class in self.all_model_classes:
												_a								= model_class(__a					)

												with tempfile.TemporaryDirectory() as tmpdirname:
																model.save_pretrained(__a					)
																_a	,					_a								= model_class.from_pretrained(__a					,				output_loading_info=__a					)
												self.assertEqual(info["missing_keys"]					,				[]					)




				def   UpperCamelCase__   (  self     :					List[str]					):
								_a								= self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_decoder_model_past_large_inputs(*__a					)




				def   UpperCamelCase__   (  self     :					List[str]					):
								_a								= self.model_tester.prepare_config_and_inputs_for_common()
								self.model_tester.check_encoder_decoder_model_standalone(*__a					)




				def   UpperCamelCase__   (  self     :					Optional[int]					):
								_a	,					_a								= self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
												_a								= model_class(__a					)
												model.to(__a					)
												model.eval()

												_a								= copy.deepcopy(self._prepare_for_class(__a					,				__a					)					)

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

												_a								= model.get_input_embeddings()
												if not self.is_encoder_decoder:
																_a								= wte(__a					)
												else:
																_a								= wte(__a					)
																_a								= wte(__a					)

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




				def   UpperCamelCase__   (  self     :					List[str]					):
								_a	,					_a								= self.model_tester.prepare_config_and_inputs()
								_a								= input_dict["input_ids"]
								_a								= input_ids.ne(1					).to(__a					)
								_a								= MaMaaaForConditionalGeneration(__a					).eval().to(__a					)
								if torch_device == "cuda":
												model.half()
								model.generate(__a					,				attention_mask=__a					)
								model.generate(num_beams=4					,				do_sample=__a					,				early_stopping=__a					,				num_return_sequences=3					)






def  _lowerCamelCase				( lowercase						:      Any						)	->	List[Any]:
				return torch.tensor(lowercase    ,							dtype=torch.long    ,							device=lowercase						)


lowerCAmelCase_					:    List[str]      	=			1e-4



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






				"""simple docstring"""







				@cached_property
				def   UpperCamelCase__   (  self     :					Union[str, Any]					):
								return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"					)




				def   UpperCamelCase__   (  self     :					Optional[Any]					):
								_a								= MaMaaaModel.from_pretrained("facebook/m2m100_418M"					).to(__a					)
								_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					,				__a					,				__a					)
								with torch.no_grad():
												_a								= model(**__a					)[0]
								_a								= torch.Size((1, 11, 10_24)					)
								self.assertEqual(output.shape					,				__a					)
								# 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=__a					)
								self.assertTrue(torch.allclose(output[:, :3, :3]					,				__a					,				atol=__a					)					)




				def   UpperCamelCase__   (  self     :					Optional[Any]					):
								_a								= MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"					).to(__a					)

								# 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					,				__a					,				__a					)
								with torch.no_grad():
												_a								= model(**__a					)[0]
								_a								= torch.Size((1, 11, model.config.vocab_size)					)
								self.assertEqual(output.shape					,				__a					)
								# 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=__a					)
								self.assertTrue(torch.allclose(output[:, :3, :3]					,				__a					,				atol=__a					)					)




				def   UpperCamelCase__   (  self     :					List[str]					):
								_a								= MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"					).to(__a					)
								_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(__a					,				padding=__a					,				return_tensors="pt"					)

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







'''simple docstring'''







import unittest

from diffusers.pipelines.pipeline_utils import is_safetensors_compatible
class 				__SCREAMING_SNAKE_CASE  (unittest.TestCase      ):






				"""simple docstring"""







				def   UpperCamelCase__   (  self     :					str					):
								_a								= [
								    "safety_checker/pytorch_model.bin",
								    "safety_checker/model.safetensors",
								    "vae/diffusion_pytorch_model.bin",
								    "vae/diffusion_pytorch_model.safetensors",
								    "text_encoder/pytorch_model.bin",
								    "text_encoder/model.safetensors",
								    "unet/diffusion_pytorch_model.bin",
								    "unet/diffusion_pytorch_model.safetensors",
								]
								self.assertTrue(is_safetensors_compatible(__a					)					)




				def   UpperCamelCase__   (  self     :					List[str]					):
								_a								= [
								    "unet/diffusion_pytorch_model.bin",
								    "unet/diffusion_pytorch_model.safetensors",
								]
								self.assertTrue(is_safetensors_compatible(__a					)					)




				def   UpperCamelCase__   (  self     :					List[str]					):
								_a								= [
								    "safety_checker/pytorch_model.bin",
								    "safety_checker/model.safetensors",
								    "vae/diffusion_pytorch_model.bin",
								    "vae/diffusion_pytorch_model.safetensors",
								    "text_encoder/pytorch_model.bin",
								    "text_encoder/model.safetensors",
								    "unet/diffusion_pytorch_model.bin",
								    # Removed: 'unet/diffusion_pytorch_model.safetensors',
								]
								self.assertFalse(is_safetensors_compatible(__a					)					)




				def   UpperCamelCase__   (  self     :					List[str]					):
								_a								= [
								    "text_encoder/pytorch_model.bin",
								    "text_encoder/model.safetensors",
								]
								self.assertTrue(is_safetensors_compatible(__a					)					)




				def   UpperCamelCase__   (  self     :					Optional[Any]					):
								_a								= [
								    "safety_checker/pytorch_model.bin",
								    "safety_checker/model.safetensors",
								    "vae/diffusion_pytorch_model.bin",
								    "vae/diffusion_pytorch_model.safetensors",
								    "text_encoder/pytorch_model.bin",
								    # Removed: 'text_encoder/model.safetensors',
								    "unet/diffusion_pytorch_model.bin",
								    "unet/diffusion_pytorch_model.safetensors",
								]
								self.assertFalse(is_safetensors_compatible(__a					)					)




				def   UpperCamelCase__   (  self     :					str					):
								_a								= [
								    "safety_checker/pytorch_model.fp16.bin",
								    "safety_checker/model.fp16.safetensors",
								    "vae/diffusion_pytorch_model.fp16.bin",
								    "vae/diffusion_pytorch_model.fp16.safetensors",
								    "text_encoder/pytorch_model.fp16.bin",
								    "text_encoder/model.fp16.safetensors",
								    "unet/diffusion_pytorch_model.fp16.bin",
								    "unet/diffusion_pytorch_model.fp16.safetensors",
								]
								_a								= "fp16"
								self.assertTrue(is_safetensors_compatible(__a					,				variant=__a					)					)




				def   UpperCamelCase__   (  self     :					Any					):
								_a								= [
								    "unet/diffusion_pytorch_model.fp16.bin",
								    "unet/diffusion_pytorch_model.fp16.safetensors",
								]
								_a								= "fp16"
								self.assertTrue(is_safetensors_compatible(__a					,				variant=__a					)					)




				def   UpperCamelCase__   (  self     :					Any					):
								# pass variant but use the non-variant filenames
								_a								= [
								    "unet/diffusion_pytorch_model.bin",
								    "unet/diffusion_pytorch_model.safetensors",
								]
								_a								= "fp16"
								self.assertTrue(is_safetensors_compatible(__a					,				variant=__a					)					)




				def   UpperCamelCase__   (  self     :					Optional[Any]					):
								_a								= [
								    "safety_checker/pytorch_model.fp16.bin",
								    "safety_checker/model.fp16.safetensors",
								    "vae/diffusion_pytorch_model.fp16.bin",
								    "vae/diffusion_pytorch_model.fp16.safetensors",
								    "text_encoder/pytorch_model.fp16.bin",
								    "text_encoder/model.fp16.safetensors",
								    "unet/diffusion_pytorch_model.fp16.bin",
								    # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors',
								]
								_a								= "fp16"
								self.assertFalse(is_safetensors_compatible(__a					,				variant=__a					)					)




				def   UpperCamelCase__   (  self     :					Dict					):
								_a								= [
								    "text_encoder/pytorch_model.fp16.bin",
								    "text_encoder/model.fp16.safetensors",
								]
								_a								= "fp16"
								self.assertTrue(is_safetensors_compatible(__a					,				variant=__a					)					)




				def   UpperCamelCase__   (  self     :					List[str]					):
								# pass variant but use the non-variant filenames
								_a								= [
								    "text_encoder/pytorch_model.bin",
								    "text_encoder/model.safetensors",
								]
								_a								= "fp16"
								self.assertTrue(is_safetensors_compatible(__a					,				variant=__a					)					)




				def   UpperCamelCase__   (  self     :					Optional[int]					):
								_a								= [
								    "safety_checker/pytorch_model.fp16.bin",
								    "safety_checker/model.fp16.safetensors",
								    "vae/diffusion_pytorch_model.fp16.bin",
								    "vae/diffusion_pytorch_model.fp16.safetensors",
								    "text_encoder/pytorch_model.fp16.bin",
								    # 'text_encoder/model.fp16.safetensors',
								    "unet/diffusion_pytorch_model.fp16.bin",
								    "unet/diffusion_pytorch_model.fp16.safetensors",
								]
								_a								= "fp16"
								self.assertFalse(is_safetensors_compatible(__a					,				variant=__a					)					)
