


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 	__lowerCamelCase						(							lowerCamelCase__		:						List[str]  ,							lowerCamelCase__		:						Union[str, Any]  ,							lowerCamelCase__		:						List[str]  ,							lowerCamelCase__		:						int=None  ,							lowerCamelCase__		:						Union[str, Any]=None  ,							lowerCamelCase__		:						str=None  ,							lowerCamelCase__		:						List[Any]=None  ,							lowerCamelCase__		:						Tuple=None  ,							):





			'''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=lowerCamelCase__      )
			if decoder_head_mask is None:
						lowerCamelCase    		=  torch.ones(config.decoder_layers  ,							config.decoder_attention_heads  ,							device=lowerCamelCase__      )
			if cross_attn_head_mask is None:
						lowerCamelCase    		=  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        __lowercase       :



		"""simple docstring"""

		def __init__( self		,      A		,      A=13		,      A=7		,      A=True		,      A=False		,      A=99		,      A=16		,      A=2		,      A=4		,      A=4		,      A="relu"		,      A=0.1		,      A=0.1		,      A=0.0		,      A=0.0		,      A=20		,      A=2		,      A=1		,      A=0		,      )  -> Union[str, Any]:







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







					'''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(A		,      A		,      A	)
					return config, inputs_dict







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







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







					'''simple docstring'''







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







		def 					__A   ( self		,      A		,      A	)  -> str:







					'''simple docstring'''







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

					# first forward pass
					lowerCamelCase    		=  model(A		,      attention_mask=A		,      head_mask=A		,      use_cache=A	)

					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(A		,      attention_mask=A	)["""last_hidden_state"""]
					lowerCamelCase    		=  model(A		,      attention_mask=A		,      past_key_values=A	)[
					    """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(A		,      A		,      atol=1e-2	)	)







		def 					__A   ( self		,      A		,      A	)  -> Tuple:







					'''simple docstring'''







					lowerCamelCase    		=  MaMaaaModel(config=A	).to(A	).eval()
					lowerCamelCase    		=  model(**A	)

					lowerCamelCase    		=  outputs.encoder_last_hidden_state
					lowerCamelCase    		=  outputs.last_hidden_state

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

					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(A	)
								lowerCamelCase    		=  MaMaaaDecoder.from_pretrained(A	).to(A	)

					lowerCamelCase    		=  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        __lowercase       (							a_			,							a_			,							a_			,							unittest.TestCase  ):



		"""simple docstring"""

		UpperCamelCase     :					Optional[int]			       =		(
		    (
		        MaMaaaModel,
		        MaMaaaForConditionalGeneration,
		    )
		    if is_torch_available()
		    else ()
		)
		UpperCamelCase     :					Optional[int]			       =		(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     :					int			       =		True
		UpperCamelCase     :					str			       =		True
		UpperCamelCase     :					Any			       =		False
		UpperCamelCase     :					Any			       =		False







		def 					__A   ( self		,      A		,      A		,      A		,      A		,      A	)  -> List[Any]:







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







					'''simple docstring'''







					lowerCamelCase    		=  MaMaaaModelTester(self	)
					lowerCamelCase    		=  ConfigTester(self		,      config_class=A	)







		def 					__A   ( self	)  -> Tuple:







					'''simple docstring'''







					self.config_tester.run_common_tests()







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







					'''simple docstring'''







					lowerCamelCase		,		lowerCamelCase    		=  self.model_tester.prepare_config_and_inputs()
					for model_class in self.all_model_classes:
								lowerCamelCase    		=  model_class(A	)

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







		def 					__A   ( self	)  -> Tuple:







					'''simple docstring'''







					lowerCamelCase    		=  self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_decoder_model_past_large_inputs(*A	)







		def 					__A   ( self	)  -> Tuple:







					'''simple docstring'''







					lowerCamelCase    		=  self.model_tester.prepare_config_and_inputs_for_common()
					self.model_tester.check_encoder_decoder_model_standalone(*A	)







		def 					__A   ( self	)  -> List[Any]:







					'''simple docstring'''







					lowerCamelCase		,		lowerCamelCase    		=  self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
								lowerCamelCase    		=  model_class(A	)
								model.to(A	)
								model.eval()

								lowerCamelCase    		=  copy.deepcopy(self._prepare_for_class(A		,      A	)	)

								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"""		,      A	)
											del inputs["input_ids"]
											inputs.pop("""decoder_input_ids"""		,      A	)

								lowerCamelCase    		=  model.get_input_embeddings()
								if not self.is_encoder_decoder:
											lowerCamelCase    		=  wte(A	)
								else:
											lowerCamelCase    		=  wte(A	)
											lowerCamelCase    		=  wte(A	)

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







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







					'''simple docstring'''







					lowerCamelCase		,		lowerCamelCase    		=  self.model_tester.prepare_config_and_inputs()
					lowerCamelCase    		=  input_dict["""input_ids"""]
					lowerCamelCase    		=  input_ids.ne(1	).to(A	)
					lowerCamelCase    		=  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 	__lowerCamelCase						(							lowerCamelCase__		:						str      ):





			'''simple docstring'''




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


UpperCAmelCase   :    List[Any]     =		1e-4







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



		"""simple docstring"""

		@cached_property
		def 					__A   ( self	)  -> Optional[Any]:







					'''simple docstring'''







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







		def 					__A   ( self	)  -> Any:







					'''simple docstring'''







					lowerCamelCase    		=  MaMaaaModel.from_pretrained("""facebook/m2m100_418M"""	).to(A	)
					lowerCamelCase    		=  _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]	)
					lowerCamelCase    		=  _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]	)
					lowerCamelCase    		=  prepare_mam_aaa_inputs_dict(model.config		,      A		,      A	)
					with torch.no_grad():
								lowerCamelCase    		=  model(**A	)[0]
					lowerCamelCase    		=  torch.Size((1, 11, 10_24)	)
					self.assertEqual(output.shape		,      A	)
					# 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=A	)
					self.assertTrue(torch.allclose(output[:, :3, :3]		,      A		,      atol=A	)	)







		def 					__A   ( self	)  -> str:







					'''simple docstring'''







					lowerCamelCase    		=  MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""	).to(A	)

					# change to intended input
					lowerCamelCase    		=  _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]	)
					lowerCamelCase    		=  _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]	)
					lowerCamelCase    		=  prepare_mam_aaa_inputs_dict(model.config		,      A		,      A	)
					with torch.no_grad():
								lowerCamelCase    		=  model(**A	)[0]
					lowerCamelCase    		=  torch.Size((1, 11, model.config.vocab_size)	)
					self.assertEqual(output.shape		,      A	)
					# 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=A	)
					self.assertTrue(torch.allclose(output[:, :3, :3]		,      A		,      atol=A	)	)







		def 					__A   ( self	)  -> int:







					'''simple docstring'''







					lowerCamelCase    		=  MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""	).to(A	)
					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(A		,      padding=A		,      return_tensors="""pt"""	)

					lowerCamelCase    		=  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"""	)		,      )

					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=A		,      skip_special_tokens=A	)
					assert generated == expected_en





import os
import unittest

from huggingface_hub.utils import are_progress_bars_disabled

import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar







class        __lowercase       (							unittest.TestCase  ):



		"""simple docstring"""

		def 					__A   ( self	)  -> Dict:







					'''simple docstring'''







					lowerCamelCase    		=  logging.get_logger()

					# the current default level is logging.WARNING
					lowerCamelCase    		=  logging.get_verbosity()

					logging.set_verbosity_error()
					self.assertEqual(logger.getEffectiveLevel()		,      logging.get_verbosity()	)

					logging.set_verbosity_warning()
					self.assertEqual(logger.getEffectiveLevel()		,      logging.get_verbosity()	)

					logging.set_verbosity_info()
					self.assertEqual(logger.getEffectiveLevel()		,      logging.get_verbosity()	)

					logging.set_verbosity_debug()
					self.assertEqual(logger.getEffectiveLevel()		,      logging.get_verbosity()	)

					# restore to the original level
					logging.set_verbosity(A	)







		def 					__A   ( self	)  -> Tuple:







					'''simple docstring'''







					lowerCamelCase    		=  logging.get_verbosity()

					lowerCamelCase    		=  logging.get_logger("""transformers.models.bart.tokenization_bart"""	)
					lowerCamelCase    		=  """Testing 1, 2, 3"""

					# should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
					if level_origin <= logging.WARNING:
								with CaptureLogger(A	) as cl:
											logger.warning(A	)
								self.assertEqual(cl.out		,      msg + """\n"""	)

					# this is setting the level for all of `transformers.*` loggers
					logging.set_verbosity_error()

					# should not be able to log warnings
					with CaptureLogger(A	) as cl:
								logger.warning(A	)
					self.assertEqual(cl.out		,      """"""	)

					# should be able to log warnings again
					logging.set_verbosity_warning()
					with CaptureLogger(A	) as cl:
								logger.warning(A	)
					self.assertEqual(cl.out		,      msg + """\n"""	)

					# restore to the original level
					logging.set_verbosity(A	)







		@mockenv(TRANSFORMERS_VERBOSITY="""error"""	)
		def 					__A   ( self	)  -> Union[str, Any]:







					'''simple docstring'''







					transformers.utils.logging._reset_library_root_logger()
					# this action activates the env var
					lowerCamelCase    		=  logging.get_logger("""transformers.models.bart.tokenization_bart"""	)

					lowerCamelCase    		=  os.getenv("""TRANSFORMERS_VERBOSITY"""		,      A	)
					lowerCamelCase    		=  logging.log_levels[env_level_str]

					lowerCamelCase    		=  logging.get_verbosity()
					self.assertEqual(
					    A		,      A		,      F'TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}'		,      )

					# restore to the original level
					lowerCamelCase    		=  """"""
					transformers.utils.logging._reset_library_root_logger()







		@mockenv(TRANSFORMERS_VERBOSITY="""super-error"""	)
		def 					__A   ( self	)  -> Union[str, Any]:







					'''simple docstring'''







					transformers.utils.logging._reset_library_root_logger()
					lowerCamelCase    		=  logging.logging.getLogger()
					with CaptureLogger(A	) as cl:
								# this action activates the env var
								logging.get_logger("""transformers.models.bart.tokenization_bart"""	)
					self.assertIn("""Unknown option TRANSFORMERS_VERBOSITY=super-error"""		,      cl.out	)

					# no need to restore as nothing was changed







		def 					__A   ( self	)  -> Optional[Any]:







					'''simple docstring'''







					transformers.utils.logging._reset_library_root_logger()

					lowerCamelCase    		=  logging.get_logger("""transformers.models.bart.tokenization_bart"""	)
					lowerCamelCase    		=  """Testing 1, 2, 3"""

					with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="""1"""	):
								# nothing should be logged as env var disables this method
								with CaptureLogger(A	) as cl:
											logger.warning_advice(A	)
								self.assertEqual(cl.out		,      """"""	)

					with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=""""""	):
								# should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
								with CaptureLogger(A	) as cl:
											logger.warning_advice(A	)
								self.assertEqual(cl.out		,      msg + """\n"""	)






def 	__lowerCamelCase						(							):





			'''simple docstring'''




			disable_progress_bar()
			assert are_progress_bars_disabled()

			enable_progress_bar()
			assert not are_progress_bars_disabled()

