


"""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 						lowercase__(A ,		A ,		A ,		A=None ,		A=None ,		A=None ,		A=None ,		A=None ,		)    ->Optional[int]:




						"""simple docstring"""



						if attention_mask is None:
												lowercase__    :				int=	input_ids.ne(config.pad_token_id						)
						if decoder_attention_mask is None:
												lowercase__    :				Optional[Any]=	decoder_input_ids.ne(config.pad_token_id						)
						if head_mask is None:
												lowercase__    :				Union[str, Any]=	torch.ones(config.encoder_layers ,		config.encoder_attention_heads ,		device=_UpperCAmelCase						)
						if decoder_head_mask is None:
												lowercase__    :				Any=	torch.ones(config.decoder_layers ,		config.decoder_attention_heads ,		device=_UpperCAmelCase						)
						if cross_attn_head_mask is None:
												lowercase__    :				Union[str, Any]=	torch.ones(config.decoder_layers ,		config.decoder_attention_heads ,		device=_UpperCAmelCase						)
						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    __UpperCAmelCase:




						"""simple docstring"""




						def __init__(       self	,  snake_case__	,  snake_case__=13	,  snake_case__=7	,  snake_case__=True	,  snake_case__=False	,  snake_case__=99	,  snake_case__=16	,  snake_case__=2	,  snake_case__=4	,  snake_case__=4	,  snake_case__="relu"	,  snake_case__=0.1	,  snake_case__=0.1	,  snake_case__=0.0	,  snake_case__=0.0	,  snake_case__=20	,  snake_case__=2	,  snake_case__=1	,  snake_case__=0	,  ):
												'''simple docstring'''
												lowercase__    :				List[str]=	parent
												lowercase__    :				Union[str, Any]=	batch_size
												lowercase__    :				Union[str, Any]=	seq_length
												lowercase__    :				str=	is_training
												lowercase__    :				Optional[Any]=	use_labels
												lowercase__    :				Dict=	vocab_size
												lowercase__    :				int=	hidden_size
												lowercase__    :				Dict=	num_hidden_layers
												lowercase__    :				List[str]=	num_attention_heads
												lowercase__    :				Dict=	intermediate_size
												lowercase__    :				Dict=	hidden_act
												lowercase__    :				Optional[int]=	hidden_dropout_prob
												lowercase__    :				Union[str, Any]=	attention_probs_dropout_prob
												lowercase__    :				str=	encoder_layerdrop
												lowercase__    :				Union[str, Any]=	decoder_layerdrop
												lowercase__    :				List[Any]=	max_position_embeddings
												lowercase__    :				str=	eos_token_id
												lowercase__    :				List[Any]=	pad_token_id
												lowercase__    :				str=	bos_token_id




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Any=	ids_tensor([self.batch_size, self.seq_length]	,  self.vocab_size      )
												lowercase__    :				Any=	self.eos_token_id  # Eos Token
												lowercase__    :				Dict=	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
												lowercase__    :				List[Any]=	input_ids.clamp(self.pad_token_id + 1      )
												lowercase__    :				Tuple=	decoder_input_ids.clamp(self.pad_token_id + 1      )

												lowercase__    :				Any=	self.get_config()
												lowercase__    :				int=	prepare_mam_aaa_inputs_dict(snake_case__	,  snake_case__	,  snake_case__      )
												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'''
												lowercase__    :				str=	self.prepare_config_and_inputs()
												return config, inputs_dict




						def 		UpperCAmelCase_	(       self	,  snake_case__	,  snake_case__      ):
												'''simple docstring'''
												lowercase__    :				int=	MaMaaaModel(config=snake_case__      ).get_decoder().to(snake_case__      ).eval()
												lowercase__    :				Tuple=	inputs_dict['input_ids']
												lowercase__    :				str=	inputs_dict['attention_mask']
												lowercase__    :				Tuple=	inputs_dict['head_mask']

												# first forward pass
												lowercase__    :				int=	model(snake_case__	,  attention_mask=snake_case__	,  head_mask=snake_case__	,  use_cache=snake_case__      )

												lowercase__    :				str=	outputs.to_tuple()

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

												# append to next input_ids and
												lowercase__    :				Optional[Any]=	torch.cat([input_ids, next_tokens]	,  dim=-1      )
												lowercase__    :				List[Any]=	torch.cat([attention_mask, next_attn_mask]	,  dim=-1      )

												lowercase__    :				str=	model(snake_case__	,  attention_mask=snake_case__      )['last_hidden_state']
												lowercase__    :				Any=	model(snake_case__	,  attention_mask=snake_case__	,  past_key_values=snake_case__      )[
												    'last_hidden_state'
												]

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




						def 		UpperCAmelCase_	(       self	,  snake_case__	,  snake_case__      ):
												'''simple docstring'''
												lowercase__    :				Union[str, Any]=	MaMaaaModel(config=snake_case__      ).to(snake_case__      ).eval()
												lowercase__    :				Any=	model(**snake_case__      )

												lowercase__    :				Optional[Any]=	outputs.encoder_last_hidden_state
												lowercase__    :				List[str]=	outputs.last_hidden_state

												with tempfile.TemporaryDirectory() as tmpdirname:
																		lowercase__    :				List[Any]=	model.get_encoder()
																		encoder.save_pretrained(snake_case__      )
																		lowercase__    :				Optional[int]=	MaMaaaEncoder.from_pretrained(snake_case__      ).to(snake_case__      )

												lowercase__    :				List[Any]=	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:
																		lowercase__    :				int=	model.get_decoder()
																		decoder.save_pretrained(snake_case__      )
																		lowercase__    :				Dict=	MaMaaaDecoder.from_pretrained(snake_case__      ).to(snake_case__      )

												lowercase__    :				List[Any]=	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    __UpperCAmelCase(       __UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase  ,  unittest.TestCase							):




						"""simple docstring"""




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




						def 		UpperCAmelCase_	(       self	,  snake_case__	,  snake_case__	,  snake_case__	,  snake_case__	,  snake_case__      ):
												'''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'''
												lowercase__    :				List[str]=	MaMaaaModelTester(self      )
												lowercase__    :				Optional[Any]=	ConfigTester(self	,  config_class=snake_case__      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												self.config_tester.run_common_tests()




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				int=	self.model_tester.prepare_config_and_inputs()
												for model_class in self.all_model_classes:
																		lowercase__    :				Optional[Any]=	model_class(snake_case__      )

																		with tempfile.TemporaryDirectory() as tmpdirname:
																								model.save_pretrained(snake_case__      )
																								lowercase__    :				Optional[Any]=	model_class.from_pretrained(snake_case__	,  output_loading_info=snake_case__      )
																		self.assertEqual(info["missing_keys"]	,  []      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Optional[Any]=	self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_decoder_model_past_large_inputs(*snake_case__      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				int=	self.model_tester.prepare_config_and_inputs_for_common()
												self.model_tester.check_encoder_decoder_model_standalone(*snake_case__      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Tuple=	self.model_tester.prepare_config_and_inputs_for_common()

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

																		lowercase__    :				List[Any]=	copy.deepcopy(self._prepare_for_class(snake_case__	,  snake_case__      )      )

																		if not self.is_encoder_decoder:
																								lowercase__    :				Union[str, Any]=	inputs['input_ids']
																								del inputs["input_ids"]
																		else:
																								lowercase__    :				Optional[int]=	inputs['input_ids']
																								lowercase__    :				Any=	inputs.get("decoder_input_ids"	,  snake_case__      )
																								del inputs["input_ids"]
																								inputs.pop("decoder_input_ids"	,  snake_case__      )

																		lowercase__    :				Any=	model.get_input_embeddings()
																		if not self.is_encoder_decoder:
																								lowercase__    :				List[str]=	wte(snake_case__      )
																		else:
																								lowercase__    :				Optional[Any]=	wte(snake_case__      )
																								lowercase__    :				Any=	wte(snake_case__      )

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




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Optional[Any]=	self.model_tester.prepare_config_and_inputs()
												lowercase__    :				Optional[Any]=	input_dict['input_ids']
												lowercase__    :				Optional[int]=	input_ids.ne(1      ).to(snake_case__      )
												lowercase__    :				List[Any]=	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__(A						)    ->Optional[Any]:




						"""simple docstring"""



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


a			:    Optional[int]				 =		1e-4







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




						"""simple docstring"""




						@cached_property
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				str=	MaMaaaModel.from_pretrained("facebook/m2m100_418M"      ).to(snake_case__      )
												lowercase__    :				List[str]=	_long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]      )
												lowercase__    :				Dict=	_long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]      )
												lowercase__    :				str=	prepare_mam_aaa_inputs_dict(model.config	,  snake_case__	,  snake_case__      )
												with torch.no_grad():
																		lowercase__    :				Union[str, Any]=	model(**snake_case__      )[0]
												lowercase__    :				str=	torch.Size((1, 11, 1024)      )
												self.assertEqual(output.shape	,  snake_case__      )
												# change to expected output here
												lowercase__    :				int=	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 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Any=	MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"      ).to(snake_case__      )

												# change to intended input
												lowercase__    :				List[Any]=	_long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]      )
												lowercase__    :				Tuple=	_long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]      )
												lowercase__    :				Tuple=	prepare_mam_aaa_inputs_dict(model.config	,  snake_case__	,  snake_case__      )
												with torch.no_grad():
																		lowercase__    :				Optional[int]=	model(**snake_case__      )[0]
												lowercase__    :				List[str]=	torch.Size((1, 11, model.config.vocab_size)      )
												self.assertEqual(output.shape	,  snake_case__      )
												# change to expected output here
												lowercase__    :				Dict=	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 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Union[str, Any]=	MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"      ).to(snake_case__      )
												lowercase__    :				Dict=	MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"	,  src_lang="fr"	,  tgt_lang="en"      )

												lowercase__    :				int=	[
												    '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
												lowercase__    :				Dict=	tokenizer(snake_case__	,  padding=snake_case__	,  return_tensors="pt"      )

												lowercase__    :				Optional[Any]=	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"      )	,  )

												lowercase__    :				Optional[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.',
												]

												lowercase__    :				str=	tokenizer.batch_decode(
												    hypotheses_batch.tolist()	,  clean_up_tokenization_spaces=snake_case__	,  skip_special_tokens=snake_case__      )
												assert generated == expected_en














"""simple docstring"""







import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device


a			:    Union[str, Any]				 =		False


class    __UpperCAmelCase(       unittest.TestCase							):




						"""simple docstring"""




						pass


@nightly
@require_torch_gpu
class    __UpperCAmelCase(       unittest.TestCase							):




						"""simple docstring"""




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												# clean up the VRAM after each test
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Dict=	VersatileDiffusionTextToImagePipeline.from_pretrained("shi-labs/versatile-diffusion"      )
												# remove text_unet
												pipe.remove_unused_weights()
												pipe.to(snake_case__      )
												pipe.set_progress_bar_config(disable=snake_case__      )

												lowercase__    :				Any=	"A painting of a squirrel eating a burger "
												lowercase__    :				Optional[Any]=	torch.manual_seed(0      )
												lowercase__    :				List[str]=	pipe(
												    prompt=snake_case__	,  generator=snake_case__	,  guidance_scale=7.5	,  num_inference_steps=2	,  output_type="numpy"      ).images

												with tempfile.TemporaryDirectory() as tmpdirname:
																		pipe.save_pretrained(snake_case__      )
																		lowercase__    :				Optional[Any]=	VersatileDiffusionTextToImagePipeline.from_pretrained(snake_case__      )
												pipe.to(snake_case__      )
												pipe.set_progress_bar_config(disable=snake_case__      )

												lowercase__    :				Any=	generator.manual_seed(0      )
												lowercase__    :				Tuple=	pipe(
												    prompt=snake_case__	,  generator=snake_case__	,  guidance_scale=7.5	,  num_inference_steps=2	,  output_type="numpy"      ).images

												assert np.abs(image - new_image      ).sum() < 1e-5, "Models don't have the same forward pass"




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Tuple=	VersatileDiffusionTextToImagePipeline.from_pretrained(
												    "shi-labs/versatile-diffusion"	,  torch_dtype=torch.floataa      )
												pipe.to(snake_case__      )
												pipe.set_progress_bar_config(disable=snake_case__      )

												lowercase__    :				List[str]=	"A painting of a squirrel eating a burger "
												lowercase__    :				Union[str, Any]=	torch.manual_seed(0      )
												lowercase__    :				Optional[Any]=	pipe(
												    prompt=snake_case__	,  generator=snake_case__	,  guidance_scale=7.5	,  num_inference_steps=50	,  output_type="numpy"      ).images

												lowercase__    :				List[str]=	image[0, 253:256, 253:256, -1]

												assert image.shape == (1, 512, 512, 3)
												lowercase__    :				Optional[int]=	np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78]      )

												assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-2






