'''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 							snake_case__				(     _A:   int ,  _A:   List[str] ,  _A:   Dict ,  _A:   Union[str, Any]=None ,  _A:   Tuple=None ,  _A:   Dict=None ,  _A:   List[Any]=None ,  _A:   Optional[Any]=None ,  )       ->      Any:

		'''simple docstring'''


		if attention_mask is None:
				lowerCAmelCase     =    input_ids.ne(config.pad_token_id					)
		if decoder_attention_mask is None:
				lowerCAmelCase     =    decoder_input_ids.ne(config.pad_token_id					)
		if head_mask is None:
				lowerCAmelCase     =    torch.ones(config.encoder_layers ,  config.encoder_attention_heads ,  device=_A					)
		if decoder_head_mask is None:
				lowerCAmelCase     =    torch.ones(config.decoder_layers ,  config.decoder_attention_heads ,  device=_A					)
		if cross_attn_head_mask is None:
				lowerCAmelCase     =    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 							a__:


			'''simple docstring'''






			def __init__(  self			,       __lowerCAmelCase			,       __lowerCAmelCase=13			,       __lowerCAmelCase=7			,       __lowerCAmelCase=True			,       __lowerCAmelCase=False			,       __lowerCAmelCase=99			,       __lowerCAmelCase=16			,       __lowerCAmelCase=2			,       __lowerCAmelCase=4			,       __lowerCAmelCase=4			,       __lowerCAmelCase="relu"			,       __lowerCAmelCase=0.1			,       __lowerCAmelCase=0.1			,       __lowerCAmelCase=0.0			,       __lowerCAmelCase=0.0			,       __lowerCAmelCase=20			,       __lowerCAmelCase=2			,       __lowerCAmelCase=1			,       __lowerCAmelCase=0			,       ):




					"""simple docstring"""


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



			def 				a_			(  self):




					"""simple docstring"""


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

					lowerCAmelCase     =    self.get_config()
					lowerCAmelCase     =    prepare_mam_aaa_inputs_dict(__lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase)
					return config, inputs_dict



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




					"""simple docstring"""


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



			def 				a_			(  self			,       __lowerCAmelCase			,       __lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase     =    MaMaaaModel(config=__lowerCAmelCase).get_decoder().to(__lowerCAmelCase).eval()
					lowerCAmelCase     =    inputs_dict["""input_ids"""]
					lowerCAmelCase     =    inputs_dict["""attention_mask"""]
					lowerCAmelCase     =    inputs_dict["""head_mask"""]

					# first forward pass
					lowerCAmelCase     =    model(__lowerCAmelCase			,       attention_mask=__lowerCAmelCase			,       head_mask=__lowerCAmelCase			,       use_cache=__lowerCAmelCase)

					lowerCAmelCase   ,	lowerCAmelCase     =    outputs.to_tuple()

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

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

					lowerCAmelCase     =    model(__lowerCAmelCase			,       attention_mask=__lowerCAmelCase)["""last_hidden_state"""]
					lowerCAmelCase     =    model(__lowerCAmelCase			,       attention_mask=__lowerCAmelCase			,       past_key_values=__lowerCAmelCase)[
					    """last_hidden_state"""
					]

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







			def 				a_			(  self			,       __lowerCAmelCase			,       __lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase     =    MaMaaaModel(config=__lowerCAmelCase).to(__lowerCAmelCase).eval()
					lowerCAmelCase     =    model(**__lowerCAmelCase)

					lowerCAmelCase     =    outputs.encoder_last_hidden_state
					lowerCAmelCase     =    outputs.last_hidden_state

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

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

					lowerCAmelCase     =    decoder(
					    input_ids=inputs_dict["""decoder_input_ids"""]			,       attention_mask=inputs_dict["""decoder_attention_mask"""]			,       encoder_hidden_states=__lowerCAmelCase			,       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 							a__(   lowerCAmelCase__					,		lowerCAmelCase__					,		lowerCAmelCase__					,		unittest.TestCase      ):


			'''simple docstring'''






			UpperCAmelCase_     :	Tuple						=			(
			    (
			        MaMaaaModel,
			        MaMaaaForConditionalGeneration,
			    )
			    if is_torch_available()
			    else ()
			)
			UpperCAmelCase_     :	str						=			(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
			UpperCAmelCase_     :	Tuple						=			(
			    {
			        '''conversational''': MaMaaaForConditionalGeneration,
			        '''feature-extraction''': MaMaaaModel,
			        '''summarization''': MaMaaaForConditionalGeneration,
			        '''text2text-generation''': MaMaaaForConditionalGeneration,
			        '''translation''': MaMaaaForConditionalGeneration,
			    }
			    if is_torch_available()
			    else {}
			)
			UpperCAmelCase_     :	str						=			True
			UpperCAmelCase_     :	int						=			True
			UpperCAmelCase_     :	Dict						=			False
			UpperCAmelCase_     :	List[Any]						=			False



			def 				a_			(  self			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase):




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




					"""simple docstring"""


					lowerCAmelCase     =    MaMaaaModelTester(self)
					lowerCAmelCase     =    ConfigTester(self			,       config_class=__lowerCAmelCase)



			def 				a_			(  self):




					"""simple docstring"""


					self.config_tester.run_common_tests()



			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase   ,	lowerCAmelCase     =    self.model_tester.prepare_config_and_inputs()
					for model_class in self.all_model_classes:
							lowerCAmelCase     =    model_class(__lowerCAmelCase)

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



			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_decoder_model_past_large_inputs(*__lowerCAmelCase)



			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    self.model_tester.prepare_config_and_inputs_for_common()
					self.model_tester.check_encoder_decoder_model_standalone(*__lowerCAmelCase)



			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase   ,	lowerCAmelCase     =    self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
							lowerCAmelCase     =    model_class(__lowerCAmelCase)
							model.to(__lowerCAmelCase)
							model.eval()

							lowerCAmelCase     =    copy.deepcopy(self._prepare_for_class(__lowerCAmelCase			,       __lowerCAmelCase))

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

							lowerCAmelCase     =    model.get_input_embeddings()
							if not self.is_encoder_decoder:
									lowerCAmelCase     =    wte(__lowerCAmelCase)
							else:
									lowerCAmelCase     =    wte(__lowerCAmelCase)
									lowerCAmelCase     =    wte(__lowerCAmelCase)

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







			def 				a_			(  self):




					"""simple docstring"""


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







def 							snake_case__				(     _A:   Dict					)       ->      List[str]:

		'''simple docstring'''


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


__lowercase        =    1e-4






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


			'''simple docstring'''






			@cached_property
			def 				a_			(  self):




					"""simple docstring"""


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



			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    MaMaaaModel.from_pretrained("""facebook/m2m100_418M""").to(__lowerCAmelCase)
					lowerCAmelCase     =    _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]])
					lowerCAmelCase     =    _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]])
					lowerCAmelCase     =    prepare_mam_aaa_inputs_dict(model.config			,       __lowerCAmelCase			,       __lowerCAmelCase)
					with torch.no_grad():
							lowerCAmelCase     =    model(**__lowerCAmelCase)[0]
					lowerCAmelCase     =    torch.Size((1, 11, 1024))
					self.assertEqual(output.shape			,       __lowerCAmelCase)
					# change to expected output here
					lowerCAmelCase     =    torch.tensor(
					    [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]			,       device=__lowerCAmelCase)
					self.assertTrue(torch.allclose(output[:, :3, :3]			,       __lowerCAmelCase			,       atol=__lowerCAmelCase))



			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""").to(__lowerCAmelCase)

					# change to intended input
					lowerCAmelCase     =    _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]])
					lowerCAmelCase     =    _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]])
					lowerCAmelCase     =    prepare_mam_aaa_inputs_dict(model.config			,       __lowerCAmelCase			,       __lowerCAmelCase)
					with torch.no_grad():
							lowerCAmelCase     =    model(**__lowerCAmelCase)[0]
					lowerCAmelCase     =    torch.Size((1, 11, model.config.vocab_size))
					self.assertEqual(output.shape			,       __lowerCAmelCase)
					# change to expected output here
					lowerCAmelCase     =    torch.tensor(
					    [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]			,       device=__lowerCAmelCase)
					self.assertTrue(torch.allclose(output[:, :3, :3]			,       __lowerCAmelCase			,       atol=__lowerCAmelCase))







			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""").to(__lowerCAmelCase)
					lowerCAmelCase     =    MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""			,       src_lang="""fr"""			,       tgt_lang="""en""")

					lowerCAmelCase     =    [
					    """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
					lowerCAmelCase     =    tokenizer(__lowerCAmelCase			,       padding=__lowerCAmelCase			,       return_tensors="""pt""")

					lowerCAmelCase     =    model.generate(
					    input_ids=dct["""input_ids"""].to(__lowerCAmelCase)			,       attention_mask=dct["""attention_mask"""].to(__lowerCAmelCase)			,       num_beams=5			,       forced_bos_token_id=tokenizer.get_lang_id("""en""")			,       )

					lowerCAmelCase     =    [
					    """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.""",
					]

					lowerCAmelCase     =    tokenizer.batch_decode(
					    hypotheses_batch.tolist()			,       clean_up_tokenization_spaces=__lowerCAmelCase			,       skip_special_tokens=__lowerCAmelCase)
					assert generated == expected_en





'''simple docstring'''




from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


__lowercase        =    {
    '''configuration_chinese_clip''': [
        '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''ChineseCLIPConfig''',
        '''ChineseCLIPOnnxConfig''',
        '''ChineseCLIPTextConfig''',
        '''ChineseCLIPVisionConfig''',
    ],
    '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''],
}

try:
						if not is_vision_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						__lowercase        =    ['''ChineseCLIPFeatureExtractor''']
						__lowercase        =    ['''ChineseCLIPImageProcessor''']

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						__lowercase        =    [
						    '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
						    '''ChineseCLIPModel''',
						    '''ChineseCLIPPreTrainedModel''',
						    '''ChineseCLIPTextModel''',
						    '''ChineseCLIPVisionModel''',
						]

if TYPE_CHECKING:
						from .configuration_chinese_clip import (
						    CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
						    ChineseCLIPConfig,
						    ChineseCLIPOnnxConfig,
						    ChineseCLIPTextConfig,
						    ChineseCLIPVisionConfig,
						)
						from .processing_chinese_clip import ChineseCLIPProcessor

						try:
												if not is_vision_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_chinese_clip import (
												    CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
												    ChineseCLIPModel,
												    ChineseCLIPPreTrainedModel,
												    ChineseCLIPTextModel,
												    ChineseCLIPVisionModel,
												)

else:
						import sys

						__lowercase        =    _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)




