


"""simple docstring"""
import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
__SCREAMING_SNAKE_CASE							:      Union[str, Any]						=      {'LayoutLMv2Config', 'LayoutLMv3Config'}





@is_pipeline_test
class        __A       (unittest.TestCase):





							'''simple docstring'''

							__lowercase:						Optional[Any]							 =      MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
							__lowercase:						int							 =      TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

							if model_mapping is not None:
														__lowercase:						Dict							 =      {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
							if tf_model_mapping is not None:
														__lowercase:						List[Any]							 =      {
														    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
														}



							@require_torch
							def 						lowerCAmelCase    (			self							: Union[str, Any]    ):



														"""simple docstring"""



														snake_case_          =						pipeline(
														    task="""text-classification"""						,    model="""hf-internal-testing/tiny-random-distilbert"""						,    framework="""pt"""    )

														snake_case_          =						text_classifier("""This is great !"""    )
														self.assertEqual(nested_simplify(_UpperCAmelCase    )						,    [{"""label""": """LABEL_0""", """score""": 0.504}]    )

														snake_case_          =						text_classifier("""This is great !"""						,    top_k=2    )
														self.assertEqual(
														    nested_simplify(_UpperCAmelCase    )						,    [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]    )

														snake_case_          =						text_classifier(["""This is great !""", """This is bad"""]						,    top_k=2    )
														self.assertEqual(
														    nested_simplify(_UpperCAmelCase    )						,    [
														        [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}],
														        [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}],
														    ]						,    )

														snake_case_          =						text_classifier("""This is great !"""						,    top_k=1    )
														self.assertEqual(nested_simplify(_UpperCAmelCase    )						,    [{"""label""": """LABEL_0""", """score""": 0.504}]    )

														# Legacy behavior
														snake_case_          =						text_classifier("""This is great !"""						,    return_all_scores=_UpperCAmelCase    )
														self.assertEqual(nested_simplify(_UpperCAmelCase    )						,    [{"""label""": """LABEL_0""", """score""": 0.504}]    )

														snake_case_          =						text_classifier("""This is great !"""						,    return_all_scores=_UpperCAmelCase    )
														self.assertEqual(
														    nested_simplify(_UpperCAmelCase    )						,    [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]]    )

														snake_case_          =						text_classifier(["""This is great !""", """Something else"""]						,    return_all_scores=_UpperCAmelCase    )
														self.assertEqual(
														    nested_simplify(_UpperCAmelCase    )						,    [
														        [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}],
														        [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}],
														    ]						,    )

														snake_case_          =						text_classifier(["""This is great !""", """Something else"""]						,    return_all_scores=_UpperCAmelCase    )
														self.assertEqual(
														    nested_simplify(_UpperCAmelCase    )						,    [
														        {"""label""": """LABEL_0""", """score""": 0.504},
														        {"""label""": """LABEL_0""", """score""": 0.504},
														    ]						,    )



							@require_torch
							def 						lowerCAmelCase    (			self							: Any    ):



														"""simple docstring"""



														import torch

														snake_case_          =						pipeline(
														    task="""text-classification"""						,    model="""hf-internal-testing/tiny-random-distilbert"""						,    framework="""pt"""						,    device=torch.device("""cpu"""    )						,    )

														snake_case_          =						text_classifier("""This is great !"""    )
														self.assertEqual(nested_simplify(_UpperCAmelCase    )						,    [{"""label""": """LABEL_0""", """score""": 0.504}]    )



							@require_tf
							def 						lowerCAmelCase    (			self							: Optional[int]    ):



														"""simple docstring"""



														snake_case_          =						pipeline(
														    task="""text-classification"""						,    model="""hf-internal-testing/tiny-random-distilbert"""						,    framework="""tf"""    )

														snake_case_          =						text_classifier("""This is great !"""    )
														self.assertEqual(nested_simplify(_UpperCAmelCase    )						,    [{"""label""": """LABEL_0""", """score""": 0.504}]    )



							@slow
							@require_torch
							def 						lowerCAmelCase    (			self							: Union[str, Any]    ):



														"""simple docstring"""



														snake_case_          =						pipeline("""text-classification"""    )

														snake_case_          =						text_classifier("""This is great !"""    )
														self.assertEqual(nested_simplify(_UpperCAmelCase    )						,    [{"""label""": """POSITIVE""", """score""": 1.0}]    )
														snake_case_          =						text_classifier("""This is bad !"""    )
														self.assertEqual(nested_simplify(_UpperCAmelCase    )						,    [{"""label""": """NEGATIVE""", """score""": 1.0}]    )
														snake_case_          =						text_classifier("""Birds are a type of animal"""    )
														self.assertEqual(nested_simplify(_UpperCAmelCase    )						,    [{"""label""": """POSITIVE""", """score""": 0.988}]    )



							@slow
							@require_tf
							def 						lowerCAmelCase    (			self							: Tuple    ):



														"""simple docstring"""



														snake_case_          =						pipeline("""text-classification"""						,    framework="""tf"""    )

														snake_case_          =						text_classifier("""This is great !"""    )
														self.assertEqual(nested_simplify(_UpperCAmelCase    )						,    [{"""label""": """POSITIVE""", """score""": 1.0}]    )
														snake_case_          =						text_classifier("""This is bad !"""    )
														self.assertEqual(nested_simplify(_UpperCAmelCase    )						,    [{"""label""": """NEGATIVE""", """score""": 1.0}]    )
														snake_case_          =						text_classifier("""Birds are a type of animal"""    )
														self.assertEqual(nested_simplify(_UpperCAmelCase    )						,    [{"""label""": """POSITIVE""", """score""": 0.988}]    )



							def 						lowerCAmelCase    (			self							: Dict						,    UpperCAmelCase_							: Any						,    UpperCAmelCase_							: str						,    UpperCAmelCase_							: Tuple    ):



														"""simple docstring"""



														snake_case_          =						TextClassificationPipeline(model=_UpperCAmelCase						,    tokenizer=_UpperCAmelCase    )
														return text_classifier, ["HuggingFace is in", "This is another test"]



							def 						lowerCAmelCase    (			self							: Optional[int]						,    UpperCAmelCase_							: List[str]						,    UpperCAmelCase_							: Tuple    ):



														"""simple docstring"""



														snake_case_          =						text_classifier.model
														# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
														snake_case_          =						"""HuggingFace is in"""
														snake_case_          =						text_classifier(_UpperCAmelCase    )

														self.assertEqual(nested_simplify(_UpperCAmelCase    )						,    [{"""label""": ANY(_UpperCAmelCase    ), """score""": ANY(_UpperCAmelCase    )}]    )
														self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values()    )

														snake_case_          =						["""HuggingFace is in """, """Paris is in France"""]
														snake_case_          =						text_classifier(_UpperCAmelCase    )
														self.assertEqual(
														    nested_simplify(_UpperCAmelCase    )						,    [{"""label""": ANY(_UpperCAmelCase    ), """score""": ANY(_UpperCAmelCase    )}, {"""label""": ANY(_UpperCAmelCase    ), """score""": ANY(_UpperCAmelCase    )}]						,    )
														self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values()    )
														self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values()    )

														# Forcing to get all results with `top_k=None`
														# This is NOT the legacy format
														snake_case_          =						text_classifier(_UpperCAmelCase						,    top_k=_UpperCAmelCase    )
														snake_case_          =						len(model.config.idalabel.values()    )
														self.assertEqual(
														    nested_simplify(_UpperCAmelCase    )						,    [[{"""label""": ANY(_UpperCAmelCase    ), """score""": ANY(_UpperCAmelCase    )}] * N, [{"""label""": ANY(_UpperCAmelCase    ), """score""": ANY(_UpperCAmelCase    )}] * N]						,    )

														snake_case_          =						{"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""}
														snake_case_          =						text_classifier(_UpperCAmelCase    )
														self.assertEqual(
														    nested_simplify(_UpperCAmelCase    )						,    {"""label""": ANY(_UpperCAmelCase    ), """score""": ANY(_UpperCAmelCase    )}						,    )
														self.assertTrue(outputs["""label"""] in model.config.idalabel.values()    )

														# This might be used a text pair, but tokenizer + pipe interaction
														# makes it hard to understand that it's not using the pair properly
														# https://github.com/huggingface/transformers/issues/17305
														# We disabled this usage instead as it was outputting wrong outputs.
														snake_case_          =						[["""HuggingFace is in """, """Paris is in France"""]]
														with self.assertRaises(_UpperCAmelCase    ):
																					text_classifier(_UpperCAmelCase    )

														# This used to be valid for doing text pairs
														# We're keeping it working because of backward compatibility
														snake_case_          =						text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]]    )
														self.assertEqual(
														    nested_simplify(_UpperCAmelCase    )						,    [{"""label""": ANY(_UpperCAmelCase    ), """score""": ANY(_UpperCAmelCase    )}]						,    )
														self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values()    )







"""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   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=None			,	)      ->			Optional[Any]:
							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=_SCREAMING_SNAKE_CASE			)
							if decoder_head_mask is None:
														snake_case_          =						torch.ones(config.decoder_layers			,	config.decoder_attention_heads			,	device=_SCREAMING_SNAKE_CASE			)
							if cross_attn_head_mask is None:
														snake_case_          =						torch.ones(config.decoder_layers			,	config.decoder_attention_heads			,	device=_SCREAMING_SNAKE_CASE			)
							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							: str						,    UpperCAmelCase_							: int						,    UpperCAmelCase_							: str=13						,    UpperCAmelCase_							: Optional[int]=7						,    UpperCAmelCase_							: Optional[int]=True						,    UpperCAmelCase_							: Optional[Any]=False						,    UpperCAmelCase_							: int=99						,    UpperCAmelCase_							: Union[str, Any]=16						,    UpperCAmelCase_							: str=2						,    UpperCAmelCase_							: List[Any]=4						,    UpperCAmelCase_							: int=4						,    UpperCAmelCase_							: Optional[Any]="relu"						,    UpperCAmelCase_							: int=0.1						,    UpperCAmelCase_							: List[Any]=0.1						,    UpperCAmelCase_							: List[Any]=0.0						,    UpperCAmelCase_							: List[str]=0.0						,    UpperCAmelCase_							: List[str]=20						,    UpperCAmelCase_							: Dict=2						,    UpperCAmelCase_							: List[Any]=1						,    UpperCAmelCase_							: Optional[Any]=0						,    )   ->Dict:



														"""simple docstring"""



														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							: Tuple    )   ->List[str]:



														"""simple docstring"""



														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							: Optional[int]    )   ->Union[str, Any]:



														"""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 						lowerCAmelCase    (			self							: int    )   ->Optional[int]:



														"""simple docstring"""



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



							def 						lowerCAmelCase    (			self							: Dict						,    UpperCAmelCase_							: Optional[Any]						,    UpperCAmelCase_							: Dict    )   ->Dict:



														"""simple docstring"""



														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							: Dict						,    UpperCAmelCase_							: Union[str, Any]						,    UpperCAmelCase_							: Dict    )   ->int:



														"""simple docstring"""



														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        __A       (snake_case__  ,						snake_case__  ,						snake_case__  ,						unittest.TestCase):





							'''simple docstring'''

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



							def 						lowerCAmelCase    (			self							: Union[str, Any]						,    UpperCAmelCase_							: List[str]						,    UpperCAmelCase_							: int						,    UpperCAmelCase_							: Optional[int]						,    UpperCAmelCase_							: Optional[int]						,    UpperCAmelCase_							: int    )   ->str:



														"""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 						lowerCAmelCase    (			self							: int    )   ->Dict:



														"""simple docstring"""



														snake_case_          =						MaMaaaModelTester(self    )
														snake_case_          =						ConfigTester(self						,    config_class=UpperCAmelCase_    )



							def 						lowerCAmelCase    (			self							: Optional[Any]    )   ->Tuple:



														"""simple docstring"""



														self.config_tester.run_common_tests()



							def 						lowerCAmelCase    (			self							: Union[str, Any]    )   ->Optional[Any]:



														"""simple docstring"""



														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[int]    )   ->List[Any]:



														"""simple docstring"""



														snake_case_          =						self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCAmelCase_    )



							def 						lowerCAmelCase    (			self							: str    )   ->List[str]:



														"""simple docstring"""



														snake_case_          =						self.model_tester.prepare_config_and_inputs_for_common()
														self.model_tester.check_encoder_decoder_model_standalone(*UpperCAmelCase_    )



							def 						lowerCAmelCase    (			self							: str    )   ->List[str]:



														"""simple docstring"""



														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							: Any    )   ->Any:



														"""simple docstring"""



														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			( _SCREAMING_SNAKE_CASE			)      ->			Optional[int]:
							return torch.tensor(_SCREAMING_SNAKE_CASE			,	dtype=torch.long			,	device=_SCREAMING_SNAKE_CASE			)


__SCREAMING_SNAKE_CASE							:      Tuple						=      1E-4





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





							'''simple docstring'''

							@cached_property
							def 						lowerCAmelCase    (			self							: Dict    )   ->str:



														"""simple docstring"""



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



							def 						lowerCAmelCase    (			self							: str    )   ->Any:



														"""simple docstring"""



														snake_case_          =						MaMaaaModel.from_pretrained("""facebook/m2m100_418M"""    ).to(UpperCAmelCase_    )
														snake_case_          =						_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]    )
														snake_case_          =						_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 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, 1_024)    )
														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							: Optional[int]    )   ->Any:



														"""simple docstring"""



														snake_case_          =						MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""    ).to(UpperCAmelCase_    )

														# change to intended input
														snake_case_          =						_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]    )
														snake_case_          =						_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 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							: Dict    )   ->str:



														"""simple docstring"""



														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



