
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 	_SCREAMING_SNAKE_CASE					(		_lowerCamelCase :			Dict						,  _lowerCamelCase :			int						,  _lowerCamelCase :			Dict						,  _lowerCamelCase :			Optional[Any]=None						,  _lowerCamelCase :			str=None						,  _lowerCamelCase :			str=None						,  _lowerCamelCase :			Optional[int]=None						,  _lowerCamelCase :			int=None						,  )					->    List[Any]:






							'''simple docstring'''





							if attention_mask is None:
														__UpperCamelCase	:   List[Any]			   =					input_ids.ne(config.pad_token_id)
							if decoder_attention_mask is None:
														__UpperCamelCase	:   Union[str, Any]			   =					decoder_input_ids.ne(config.pad_token_id)
							if head_mask is None:
														__UpperCamelCase	:   List[Any]			   =					torch.ones(config.encoder_layers						,  config.encoder_attention_heads						,  device=_lowerCamelCase)
							if decoder_head_mask is None:
														__UpperCamelCase	:   List[str]			   =					torch.ones(config.decoder_layers						,  config.decoder_attention_heads						,  device=_lowerCamelCase)
							if cross_attn_head_mask is None:
														__UpperCamelCase	:   Dict			   =					torch.ones(config.decoder_layers						,  config.decoder_attention_heads						,  device=_lowerCamelCase)
							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  lowerCamelCase__							:




	'''simple docstring'''




	def __init__(					self		:Optional[int]     ,   a		:Tuple     ,   a		:Optional[int]=1_3     ,   a		:Union[str, Any]=7     ,   a		:List[str]=True     ,   a		:Dict=False     ,   a		:str=9_9     ,   a		:Optional[Any]=1_6     ,   a		:Union[str, Any]=2     ,   a		:int=4     ,   a		:Dict=4     ,   a		:Tuple="relu"     ,   a		:Optional[Any]=0.1     ,   a		:List[str]=0.1     ,   a		:Union[str, Any]=0.0     ,   a		:Optional[int]=0.0     ,   a		:Any=2_0     ,   a		:int=2     ,   a		:Union[str, Any]=1     ,   a		:List[Any]=0     ,   )		-> Dict:
								__UpperCamelCase	:   List[str]			   =					parent
								__UpperCamelCase	:   Union[str, Any]			   =					batch_size
								__UpperCamelCase	:   List[Any]			   =					seq_length
								__UpperCamelCase	:   int			   =					is_training
								__UpperCamelCase	:   int			   =					use_labels
								__UpperCamelCase	:   Any			   =					vocab_size
								__UpperCamelCase	:   Any			   =					hidden_size
								__UpperCamelCase	:   Optional[int]			   =					num_hidden_layers
								__UpperCamelCase	:   Tuple			   =					num_attention_heads
								__UpperCamelCase	:   List[str]			   =					intermediate_size
								__UpperCamelCase	:   Any			   =					hidden_act
								__UpperCamelCase	:   Tuple			   =					hidden_dropout_prob
								__UpperCamelCase	:   str			   =					attention_probs_dropout_prob
								__UpperCamelCase	:   Tuple			   =					encoder_layerdrop
								__UpperCamelCase	:   List[str]			   =					decoder_layerdrop
								__UpperCamelCase	:   List[Any]			   =					max_position_embeddings
								__UpperCamelCase	:   List[Any]			   =					eos_token_id
								__UpperCamelCase	:   Optional[int]			   =					pad_token_id
								__UpperCamelCase	:   Union[str, Any]			   =					bos_token_id







	def    _lowerCamelCase				(					self		:str						)		-> Optional[int]:
								__UpperCamelCase	:   Optional[Any]			   =					ids_tensor([self.batch_size, self.seq_length]     ,   self.vocab_size						)
								__UpperCamelCase	:   List[Any]			   =					self.eos_token_id  # Eos Token
								__UpperCamelCase	:   int			   =					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
								__UpperCamelCase	:   int			   =					input_ids.clamp(self.pad_token_id + 1						)
								__UpperCamelCase	:   int			   =					decoder_input_ids.clamp(self.pad_token_id + 1						)

								__UpperCamelCase	:   List[Any]			   =					self.get_config()
								__UpperCamelCase	:   int			   =					prepare_mam_aaa_inputs_dict(a     ,   a     ,   a						)
								return config, inputs_dict







	def    _lowerCamelCase				(					self		:Tuple						)		-> int:
								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		:List[str]						)		-> str:
								__UpperCamelCase   ,						__UpperCamelCase	:   int			   =					self.prepare_config_and_inputs()
								return config, inputs_dict







	def    _lowerCamelCase				(					self		:Union[str, Any]     ,   a		:Optional[int]     ,   a		:Tuple						)		-> Dict:
								__UpperCamelCase	:   List[str]			   =					MaMaaaModel(config=a						).get_decoder().to(a						).eval()
								__UpperCamelCase	:   List[str]			   =					inputs_dict["input_ids"]
								__UpperCamelCase	:   int			   =					inputs_dict["attention_mask"]
								__UpperCamelCase	:   str			   =					inputs_dict["head_mask"]

								# first forward pass
								__UpperCamelCase	:   Union[str, Any]			   =					model(a     ,   attention_mask=a     ,   head_mask=a     ,   use_cache=a						)

								__UpperCamelCase   ,						__UpperCamelCase	:   Tuple			   =					outputs.to_tuple()

								# create hypothetical multiple next token and extent to next_input_ids
								__UpperCamelCase	:   List[str]			   =					ids_tensor((self.batch_size, 3)     ,   config.vocab_size						)
								__UpperCamelCase	:   Union[str, Any]			   =					ids_tensor((self.batch_size, 3)     ,   2						)

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

								__UpperCamelCase	:   str			   =					model(a     ,   attention_mask=a						)["last_hidden_state"]
								__UpperCamelCase	:   List[Any]			   =					model(a     ,   attention_mask=a     ,   past_key_values=a						)[
								    "last_hidden_state"
								]

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







	def    _lowerCamelCase				(					self		:Optional[Any]     ,   a		:int     ,   a		:int						)		-> str:
								__UpperCamelCase	:   Tuple			   =					MaMaaaModel(config=a						).to(a						).eval()
								__UpperCamelCase	:   int			   =					model(**a						)

								__UpperCamelCase	:   Tuple			   =					outputs.encoder_last_hidden_state
								__UpperCamelCase	:   str			   =					outputs.last_hidden_state

								with tempfile.TemporaryDirectory() as tmpdirname:
															__UpperCamelCase	:   Union[str, Any]			   =					model.get_encoder()
															encoder.save_pretrained(a						)
															__UpperCamelCase	:   int			   =					MaMaaaEncoder.from_pretrained(a						).to(a						)

								__UpperCamelCase	:   Optional[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:
															__UpperCamelCase	:   List[Any]			   =					model.get_decoder()
															decoder.save_pretrained(a						)
															__UpperCamelCase	:   List[Any]			   =					MaMaaaDecoder.from_pretrained(a						).to(a						)

								__UpperCamelCase	:   Union[str, Any]			   =					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  lowerCamelCase__							(				__lowercase     ,						__lowercase     ,						__lowercase     ,						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    _lowerCamelCase				(					self		:Optional[int]     ,   a		:List[str]     ,   a		:Tuple     ,   a		:Optional[int]     ,   a		:Union[str, Any]     ,   a		:Any						)		-> List[Any]:
								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		:Optional[int]						)		-> int:
								__UpperCamelCase	:   str			   =					MaMaaaModelTester(self						)
								__UpperCamelCase	:   Dict			   =					ConfigTester(self     ,   config_class=a						)







	def    _lowerCamelCase				(					self		:List[str]						)		-> Union[str, Any]:
								self.config_tester.run_common_tests()







	def    _lowerCamelCase				(					self		:Any						)		-> str:
								__UpperCamelCase   ,						__UpperCamelCase	:   Dict			   =					self.model_tester.prepare_config_and_inputs()
								for model_class in self.all_model_classes:
															__UpperCamelCase	:   Optional[Any]			   =					model_class(a						)

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







	def    _lowerCamelCase				(					self		:List[str]						)		-> Dict:
								__UpperCamelCase	:   Optional[Any]			   =					self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_decoder_model_past_large_inputs(*a						)







	def    _lowerCamelCase				(					self		:str						)		-> List[str]:
								__UpperCamelCase	:   Optional[Any]			   =					self.model_tester.prepare_config_and_inputs_for_common()
								self.model_tester.check_encoder_decoder_model_standalone(*a						)







	def    _lowerCamelCase				(					self		:Any						)		-> List[Any]:
								__UpperCamelCase   ,						__UpperCamelCase	:   List[Any]			   =					self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
															__UpperCamelCase	:   Dict			   =					model_class(a						)
															model.to(a						)
															model.eval()

															__UpperCamelCase	:   Union[str, Any]			   =					copy.deepcopy(self._prepare_for_class(a     ,   a						)						)

															if not self.is_encoder_decoder:
																						__UpperCamelCase	:   Tuple			   =					inputs["input_ids"]
																						del inputs["input_ids"]
															else:
																						__UpperCamelCase	:   Dict			   =					inputs["input_ids"]
																						__UpperCamelCase	:   Tuple			   =					inputs.get("decoder_input_ids"     ,   a						)
																						del inputs["input_ids"]
																						inputs.pop("decoder_input_ids"     ,   a						)

															__UpperCamelCase	:   Optional[int]			   =					model.get_input_embeddings()
															if not self.is_encoder_decoder:
																						__UpperCamelCase	:   Tuple			   =					wte(a						)
															else:
																						__UpperCamelCase	:   List[str]			   =					wte(a						)
																						__UpperCamelCase	:   Optional[int]			   =					wte(a						)

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







	def    _lowerCamelCase				(					self		:List[Any]						)		-> int:
								__UpperCamelCase   ,						__UpperCamelCase	:   str			   =					self.model_tester.prepare_config_and_inputs()
								__UpperCamelCase	:   Dict			   =					input_dict["input_ids"]
								__UpperCamelCase	:   Optional[Any]			   =					input_ids.ne(1						).to(a						)
								__UpperCamelCase	:   List[str]			   =					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 	_SCREAMING_SNAKE_CASE					(		_lowerCamelCase :			List[str])					->    Optional[int]:






							'''simple docstring'''





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


lowercase  :					str													=       1E-4




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




	'''simple docstring'''




	@cached_property
	def    _lowerCamelCase				(					self		:List[str]						)		-> Optional[Any]:
								return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"						)







	def    _lowerCamelCase				(					self		:Any						)		-> str:
								__UpperCamelCase	:   List[str]			   =					MaMaaaModel.from_pretrained("facebook/m2m100_418M"						).to(a						)
								__UpperCamelCase	:   List[Any]			   =					_long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]]						)
								__UpperCamelCase	:   Any			   =					_long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]]						)
								__UpperCamelCase	:   Any			   =					prepare_mam_aaa_inputs_dict(model.config     ,   a     ,   a						)
								with torch.no_grad():
															__UpperCamelCase	:   Tuple			   =					model(**a						)[0]
								__UpperCamelCase	:   int			   =					torch.Size((1, 1_1, 1_0_2_4)						)
								self.assertEqual(output.shape     ,   a						)
								# change to expected output here
								__UpperCamelCase	:   Union[str, Any]			   =					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    _lowerCamelCase				(					self		:List[Any]						)		-> Tuple:
								__UpperCamelCase	:   Any			   =					MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"						).to(a						)

								# change to intended input
								__UpperCamelCase	:   str			   =					_long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]]						)
								__UpperCamelCase	:   Any			   =					_long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]]						)
								__UpperCamelCase	:   str			   =					prepare_mam_aaa_inputs_dict(model.config     ,   a     ,   a						)
								with torch.no_grad():
															__UpperCamelCase	:   int			   =					model(**a						)[0]
								__UpperCamelCase	:   List[Any]			   =					torch.Size((1, 1_1, model.config.vocab_size)						)
								self.assertEqual(output.shape     ,   a						)
								# change to expected output here
								__UpperCamelCase	:   Union[str, Any]			   =					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    _lowerCamelCase				(					self		:List[Any]						)		-> Dict:
								__UpperCamelCase	:   Optional[Any]			   =					MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"						).to(a						)
								__UpperCamelCase	:   Any			   =					MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"     ,   src_lang="fr"     ,   tgt_lang="en"						)

								__UpperCamelCase	:   List[str]			   =					[
								    "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
								__UpperCamelCase	:   List[Any]			   =					tokenizer(a     ,   padding=a     ,   return_tensors="pt"						)

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

								__UpperCamelCase	:   Tuple			   =					[
								    "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.",
								]

								__UpperCamelCase	:   Optional[Any]			   =					tokenizer.batch_decode(
								    hypotheses_batch.tolist()     ,   clean_up_tokenization_spaces=a     ,   skip_special_tokens=a						)
								assert generated == expected_en

import unittest
from dataclasses import dataclass

import pytest

from accelerate.commands.config.config_args import SageMakerConfig
from accelerate.utils import ComputeEnvironment
from accelerate.utils.launch import _convert_nargs_to_dict




@dataclass
class  lowerCamelCase__							(				__lowercase):




	'''simple docstring'''




	_A								=     ComputeEnvironment.AMAZON_SAGEMAKER
	_A								=     True
	_A								=     'ml.p3.2xlarge'
	_A								=     'accelerate_sagemaker_execution_role'
	_A								=     'hf-sm'
	_A								=     'us-east-1'
	_A								=     1
	_A								=     'accelerate-sagemaker-1'
	_A								=     '1.6'
	_A								=     '4.4'
	_A								=     'train.py'
	_A								=     [
	    '--model_name_or_path',
	    'bert',
	    '--do_train',
	    'False',
	    '--epochs',
	    '3',
	    '--learning_rate',
	    '5e-5',
	    '--max_steps',
	    '50.5',
	]
	_A								=     [
	    '--model_name_or_path',
	    'bert',
	    '--do_train',
	    '--do_test',
	    'False',
	    '--do_predict',
	    '--epochs',
	    '3',
	    '--learning_rate',
	    '5e-5',
	    '--max_steps',
	    '50.5',
	]




class  lowerCamelCase__							(				unittest.TestCase):




	'''simple docstring'''




	def    _lowerCamelCase				(					self		:Any						)		-> Optional[int]:
								# If no defaults are changed, `to_kwargs` returns an empty dict.
								__UpperCamelCase	:   Optional[int]			   =					_convert_nargs_to_dict(MockLaunchConfig.success_training_script_args						)
								assert isinstance(converted_args["model_name_or_path"]     ,   a						)
								assert isinstance(converted_args["do_train"]     ,   a						)
								assert isinstance(converted_args["epochs"]     ,   a						)
								assert isinstance(converted_args["learning_rate"]     ,   a						)
								assert isinstance(converted_args["max_steps"]     ,   a						)

								with pytest.raises(a						):
															_convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args						)