


'''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 (     __a					,   __a					,   __a					,   __a=None					,   __a=None					,   __a=None					,   __a=None					,   __a=None					,   )    ->      Dict:



					'''simple docstring'''






					if attention_mask is None:
										UpperCamelCase__  :Optional[int]				   =					input_ids.ne(config.pad_token_id  )
					if decoder_attention_mask is None:
										UpperCamelCase__  :Tuple				   =					decoder_input_ids.ne(config.pad_token_id  )
					if head_mask is None:
										UpperCamelCase__  :str				   =					torch.ones(config.encoder_layers					,   config.encoder_attention_heads					,   device=__a  )
					if decoder_head_mask is None:
										UpperCamelCase__  :int				   =					torch.ones(config.decoder_layers					,   config.decoder_attention_heads					,   device=__a  )
					if cross_attn_head_mask is None:
										UpperCamelCase__  :Dict				   =					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   lowercase      :

		"""simple docstring"""

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

							'''simple docstring'''


							UpperCamelCase__  :Optional[Any]				   =					parent
							UpperCamelCase__  :Union[str, Any]				   =					batch_size
							UpperCamelCase__  :Dict				   =					seq_length
							UpperCamelCase__  :Dict				   =					is_training
							UpperCamelCase__  :List[str]				   =					use_labels
							UpperCamelCase__  :str				   =					vocab_size
							UpperCamelCase__  :Union[str, Any]				   =					hidden_size
							UpperCamelCase__  :Optional[Any]				   =					num_hidden_layers
							UpperCamelCase__  :int				   =					num_attention_heads
							UpperCamelCase__  :int				   =					intermediate_size
							UpperCamelCase__  :Optional[int]				   =					hidden_act
							UpperCamelCase__  :Optional[int]				   =					hidden_dropout_prob
							UpperCamelCase__  :Union[str, Any]				   =					attention_probs_dropout_prob
							UpperCamelCase__  :List[Any]				   =					encoder_layerdrop
							UpperCamelCase__  :Optional[Any]				   =					decoder_layerdrop
							UpperCamelCase__  :Optional[int]				   =					max_position_embeddings
							UpperCamelCase__  :List[str]				   =					eos_token_id
							UpperCamelCase__  :Dict				   =					pad_token_id
							UpperCamelCase__  :Optional[int]				   =					bos_token_id




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


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

							UpperCamelCase__  :int				   =					self.get_config()
							UpperCamelCase__  :Any				   =					prepare_mam_aaa_inputs_dict(UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_				)
							return config, inputs_dict




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

							'''simple docstring'''


							UpperCamelCase__   ,							UpperCamelCase__  :List[Any]				   =					self.prepare_config_and_inputs()
							return config, inputs_dict




		def        lowerCAmelCase__							(						self       ,  UpperCamelCase_       ,  UpperCamelCase_				):

							'''simple docstring'''


							UpperCamelCase__  :str				   =					MaMaaaModel(config=UpperCamelCase_				).get_decoder().to(UpperCamelCase_				).eval()
							UpperCamelCase__  :Tuple				   =					inputs_dict['''input_ids''']
							UpperCamelCase__  :List[Any]				   =					inputs_dict['''attention_mask''']
							UpperCamelCase__  :Tuple				   =					inputs_dict['''head_mask''']

							# first forward pass
							UpperCamelCase__  :str				   =					model(UpperCamelCase_       ,  attention_mask=UpperCamelCase_       ,  head_mask=UpperCamelCase_       ,  use_cache=UpperCamelCase_				)

							UpperCamelCase__   ,							UpperCamelCase__  :str				   =					outputs.to_tuple()

							# create hypothetical multiple next token and extent to next_input_ids
							UpperCamelCase__  :Optional[Any]				   =					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__  :Optional[int]				   =					torch.cat([input_ids, next_tokens]       ,  dim=-1				)
							UpperCamelCase__  :Any				   =					torch.cat([attention_mask, next_attn_mask]       ,  dim=-1				)

							UpperCamelCase__  :Optional[Any]				   =					model(UpperCamelCase_       ,  attention_mask=UpperCamelCase_				)['''last_hidden_state''']
							UpperCamelCase__  :Tuple				   =					model(UpperCamelCase_       ,  attention_mask=UpperCamelCase_       ,  past_key_values=UpperCamelCase_				)[
							    '''last_hidden_state'''
							]

							# select random slice
							UpperCamelCase__  :Optional[int]				   =					ids_tensor((1,)       ,  output_from_past.shape[-1]				).item()
							UpperCamelCase__  :List[Any]				   =					output_from_no_past[:, -3:, random_slice_idx].detach()
							UpperCamelCase__  :List[Any]				   =					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       ,  UpperCamelCase_       ,  UpperCamelCase_				):

							'''simple docstring'''


							UpperCamelCase__  :Optional[int]				   =					MaMaaaModel(config=UpperCamelCase_				).to(UpperCamelCase_				).eval()
							UpperCamelCase__  :Optional[Any]				   =					model(**UpperCamelCase_				)

							UpperCamelCase__  :Optional[int]				   =					outputs.encoder_last_hidden_state
							UpperCamelCase__  :Any				   =					outputs.last_hidden_state

							with tempfile.TemporaryDirectory() as tmpdirname:
												UpperCamelCase__  :str				   =					model.get_encoder()
												encoder.save_pretrained(UpperCamelCase_				)
												UpperCamelCase__  :Any				   =					MaMaaaEncoder.from_pretrained(UpperCamelCase_				).to(UpperCamelCase_				)

							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__  :Optional[int]				   =					model.get_decoder()
												decoder.save_pretrained(UpperCamelCase_				)
												UpperCamelCase__  :str				   =					MaMaaaDecoder.from_pretrained(UpperCamelCase_				).to(UpperCamelCase_				)

							UpperCamelCase__  :Union[str, Any]				   =					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   lowercase      (				A__      ,						A__      ,						A__      ,						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       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_				):

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

							'''simple docstring'''


							UpperCamelCase__  :Any				   =					MaMaaaModelTester(self				)
							UpperCamelCase__  :Union[str, Any]				   =					ConfigTester(self       ,  config_class=UpperCamelCase_				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							self.config_tester.run_common_tests()




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__   ,							UpperCamelCase__  :str				   =					self.model_tester.prepare_config_and_inputs()
							for model_class in self.all_model_classes:
												UpperCamelCase__  :str				   =					model_class(UpperCamelCase_				)

												with tempfile.TemporaryDirectory() as tmpdirname:
																	model.save_pretrained(UpperCamelCase_				)
																	UpperCamelCase__   ,							UpperCamelCase__  :List[Any]				   =					model_class.from_pretrained(UpperCamelCase_       ,  output_loading_info=UpperCamelCase_				)
												self.assertEqual(info['''missing_keys''']       ,  []				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :int				   =					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCamelCase_				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :List[Any]				   =					self.model_tester.prepare_config_and_inputs_for_common()
							self.model_tester.check_encoder_decoder_model_standalone(*UpperCamelCase_				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__   ,							UpperCamelCase__  :Union[str, Any]				   =					self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
												UpperCamelCase__  :Optional[Any]				   =					model_class(UpperCamelCase_				)
												model.to(UpperCamelCase_				)
												model.eval()

												UpperCamelCase__  :Tuple				   =					copy.deepcopy(self._prepare_for_class(UpperCamelCase_       ,  UpperCamelCase_				)				)

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

												UpperCamelCase__  :Optional[int]				   =					model.get_input_embeddings()
												if not self.is_encoder_decoder:
																	UpperCamelCase__  :List[str]				   =					wte(UpperCamelCase_				)
												else:
																	UpperCamelCase__  :Any				   =					wte(UpperCamelCase_				)
																	UpperCamelCase__  :int				   =					wte(UpperCamelCase_				)

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




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__   ,							UpperCamelCase__  :Optional[int]				   =					self.model_tester.prepare_config_and_inputs()
							UpperCamelCase__  :Optional[int]				   =					input_dict['''input_ids''']
							UpperCamelCase__  :Optional[Any]				   =					input_ids.ne(1				).to(UpperCamelCase_				)
							UpperCamelCase__  :Dict				   =					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 (     __a  )    ->      List[Any]:



					'''simple docstring'''






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


__snake_case				 =	1e-4







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

		"""simple docstring"""

		@cached_property
		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


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




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


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




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :int				   =					MaMaaaForConditionalGeneration.from_pretrained('''facebook/m2m100_418M'''				).to(UpperCamelCase_				)

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




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :Optional[int]				   =					MaMaaaForConditionalGeneration.from_pretrained('''facebook/m2m100_418M'''				).to(UpperCamelCase_				)
							UpperCamelCase__  :List[str]				   =					MaMaaaTokenizer.from_pretrained('''facebook/m2m100_418M'''       ,  src_lang='''fr'''       ,  tgt_lang='''en'''				)

							UpperCamelCase__  :Any				   =					[
							    '''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__  :Union[str, Any]				   =					tokenizer(UpperCamelCase_       ,  padding=UpperCamelCase_       ,  return_tensors='''pt'''				)

							UpperCamelCase__  :Union[str, Any]				   =					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'''				)       ,  )

							UpperCamelCase__  :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.''',
							]

							UpperCamelCase__  :int				   =					tokenizer.batch_decode(
							    hypotheses_batch.tolist()       ,  clean_up_tokenization_spaces=UpperCamelCase_       ,  skip_special_tokens=UpperCamelCase_				)
							assert generated == expected_en



'''simple docstring'''
from __future__ import annotations

from math import pi, sqrt


def      a (     __a					,   __a  )    ->      tuple:



					'''simple docstring'''






					if inductance <= 0:
										raise ValueError('''Inductance cannot be 0 or negative'''  )

					elif capacitance <= 0:
										raise ValueError('''Capacitance cannot be 0 or negative'''  )

					else:
										return (
										    "Resonant frequency",
										    float(1 / (2 * pi * (sqrt(inductance * capacitance  )))  ),
										)


if __name__ == "__main__":
		import doctest

		doctest.testmod()