



'''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 					UpperCAmelCase   (						A  :				Dict					,		A  :				Union[str, Any]					,		A  :				Tuple					,		A  :				Optional[int]=None					,		A  :				List[str]=None					,		A  :				int=None					,		A  :				Dict=None					,		A  :				List[Any]=None					,		):
							if attention_mask is None:
														SCREAMING_SNAKE_CASE					:      List[str]     					=			input_ids.ne(config.pad_token_id				)
							if decoder_attention_mask is None:
														SCREAMING_SNAKE_CASE					:      List[str]     					=			decoder_input_ids.ne(config.pad_token_id				)
							if head_mask is None:
														SCREAMING_SNAKE_CASE					:      Optional[int]     					=			torch.ones(config.encoder_layers					,		config.encoder_attention_heads					,		device=A				)
							if decoder_head_mask is None:
														SCREAMING_SNAKE_CASE					:      Tuple     					=			torch.ones(config.decoder_layers					,		config.decoder_attention_heads					,		device=A				)
							if cross_attn_head_mask is None:
														SCREAMING_SNAKE_CASE					:      Optional[int]     					=			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 	lowerCamelCase_							:







						def __init__(  self   :      Dict				,    lowerCAmelCase__   :      Any				,    lowerCAmelCase__   :      Tuple=13				,    lowerCAmelCase__   :      List[Any]=7				,    lowerCAmelCase__   :      Optional[int]=True				,    lowerCAmelCase__   :      Tuple=False				,    lowerCAmelCase__   :      List[Any]=99				,    lowerCAmelCase__   :      List[Any]=16				,    lowerCAmelCase__   :      Optional[int]=2				,    lowerCAmelCase__   :      Optional[Any]=4				,    lowerCAmelCase__   :      str=4				,    lowerCAmelCase__   :      List[Any]="relu"				,    lowerCAmelCase__   :      Dict=0.1				,    lowerCAmelCase__   :      Tuple=0.1				,    lowerCAmelCase__   :      List[Any]=0.0				,    lowerCAmelCase__   :      str=0.0				,    lowerCAmelCase__   :      List[Any]=20				,    lowerCAmelCase__   :      Any=2				,    lowerCAmelCase__   :      Union[str, Any]=1				,    lowerCAmelCase__   :      Union[str, Any]=0				,    ):

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







						def 					__lowercase    (  self   :      Optional[int]				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      Dict     					=			ids_tensor([self.batch_size, self.seq_length]				,    self.vocab_size				)
													SCREAMING_SNAKE_CASE					:      str     					=			self.eos_token_id  # Eos Token
													SCREAMING_SNAKE_CASE					:      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
													SCREAMING_SNAKE_CASE					:      int     					=			input_ids.clamp(self.pad_token_id + 1				)
													SCREAMING_SNAKE_CASE					:      Optional[int]     					=			decoder_input_ids.clamp(self.pad_token_id + 1				)

													SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			self.get_config()
													SCREAMING_SNAKE_CASE					:      Dict     					=			prepare_mam_aaa_inputs_dict(lowerCAmelCase__				,    lowerCAmelCase__				,    lowerCAmelCase__				)
													return config, inputs_dict







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

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					,SCREAMING_SNAKE_CASE					:      Optional[int]     					=			self.prepare_config_and_inputs()
													return config, inputs_dict







						def 					__lowercase    (  self   :      Dict				,    lowerCAmelCase__   :      Union[str, Any]				,    lowerCAmelCase__   :      Tuple				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      List[str]     					=			MaMaaaModel(config=lowerCAmelCase__				).get_decoder().to(lowerCAmelCase__				).eval()
													SCREAMING_SNAKE_CASE					:      str     					=			inputs_dict['''input_ids''']
													SCREAMING_SNAKE_CASE					:      Tuple     					=			inputs_dict['''attention_mask''']
													SCREAMING_SNAKE_CASE					:      int     					=			inputs_dict['''head_mask''']

													# first forward pass
													SCREAMING_SNAKE_CASE					:      Any     					=			model(lowerCAmelCase__				,    attention_mask=lowerCAmelCase__				,    head_mask=lowerCAmelCase__				,    use_cache=lowerCAmelCase__				)

													SCREAMING_SNAKE_CASE					,SCREAMING_SNAKE_CASE					:      Tuple     					=			outputs.to_tuple()

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

													# append to next input_ids and
													SCREAMING_SNAKE_CASE					:      str     					=			torch.cat([input_ids, next_tokens]				,    dim=-1				)
													SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			torch.cat([attention_mask, next_attn_mask]				,    dim=-1				)

													SCREAMING_SNAKE_CASE					:      Dict     					=			model(lowerCAmelCase__				,    attention_mask=lowerCAmelCase__				)['''last_hidden_state''']
													SCREAMING_SNAKE_CASE					:      str     					=			model(lowerCAmelCase__				,    attention_mask=lowerCAmelCase__				,    past_key_values=lowerCAmelCase__				)[
													    '''last_hidden_state'''
													]

													# select random slice
													SCREAMING_SNAKE_CASE					:      Any     					=			ids_tensor((1,)				,    output_from_past.shape[-1]				).item()
													SCREAMING_SNAKE_CASE					:      Optional[int]     					=			output_from_no_past[:, -3:, random_slice_idx].detach()
													SCREAMING_SNAKE_CASE					:      str     					=			output_from_past[:, :, random_slice_idx].detach()

													self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]				)

													# test that outputs are equal for slice
													self.parent.assertTrue(torch.allclose(lowerCAmelCase__				,    lowerCAmelCase__				,    atol=1e-2				)				)







						def 					__lowercase    (  self   :      List[str]				,    lowerCAmelCase__   :      Tuple				,    lowerCAmelCase__   :      Optional[int]				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      str     					=			MaMaaaModel(config=lowerCAmelCase__				).to(lowerCAmelCase__				).eval()
													SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			model(**lowerCAmelCase__				)

													SCREAMING_SNAKE_CASE					:      Optional[int]     					=			outputs.encoder_last_hidden_state
													SCREAMING_SNAKE_CASE					:      int     					=			outputs.last_hidden_state

													with tempfile.TemporaryDirectory() as tmpdirname:
																				SCREAMING_SNAKE_CASE					:      List[Any]     					=			model.get_encoder()
																				encoder.save_pretrained(lowerCAmelCase__				)
																				SCREAMING_SNAKE_CASE					:      Tuple     					=			MaMaaaEncoder.from_pretrained(lowerCAmelCase__				).to(lowerCAmelCase__				)

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

													SCREAMING_SNAKE_CASE					:      List[Any]     					=			decoder(
													    input_ids=inputs_dict['''decoder_input_ids''']				,    attention_mask=inputs_dict['''decoder_attention_mask''']				,    encoder_hidden_states=lowerCAmelCase__				,    encoder_attention_mask=inputs_dict['''attention_mask''']				,    )[0]

													self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3				)


@require_torch
class 	lowerCamelCase_							(					snake_case_    ,				snake_case_    ,				snake_case_    ,				unittest.TestCase			):
						_lowerCAmelCase     :   Union[str, Any]	     =				(
						    (
						        MaMaaaModel,
						        MaMaaaForConditionalGeneration,
						    )
						    if is_torch_available()
						    else ()
						)
						_lowerCAmelCase     :   List[Any]	     =				(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
						_lowerCAmelCase     :   str	     =				(
						    {
						        'conversational': MaMaaaForConditionalGeneration,
						        'feature-extraction': MaMaaaModel,
						        'summarization': MaMaaaForConditionalGeneration,
						        'text2text-generation': MaMaaaForConditionalGeneration,
						        'translation': MaMaaaForConditionalGeneration,
						    }
						    if is_torch_available()
						    else {}
						)
						_lowerCAmelCase     :   Optional[int]	     =				True
						_lowerCAmelCase     :   Any	     =				True
						_lowerCAmelCase     :   Tuple	     =				False
						_lowerCAmelCase     :   str	     =				False







						def 					__lowercase    (  self   :      Union[str, Any]				,    lowerCAmelCase__   :      Dict				,    lowerCAmelCase__   :      List[Any]				,    lowerCAmelCase__   :      Dict				,    lowerCAmelCase__   :      str				,    lowerCAmelCase__   :      Dict				):

													"""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 					__lowercase    (  self   :      List[str]				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      Dict     					=			MaMaaaModelTester(self				)
													SCREAMING_SNAKE_CASE					:      int     					=			ConfigTester(self				,    config_class=lowerCAmelCase__				)







						def 					__lowercase    (  self   :      Optional[int]				):

													"""simple docstring"""
													self.config_tester.run_common_tests()







						def 					__lowercase    (  self   :      Optional[Any]				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					,SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			self.model_tester.prepare_config_and_inputs()
													for model_class in self.all_model_classes:
																				SCREAMING_SNAKE_CASE					:      Optional[int]     					=			model_class(lowerCAmelCase__				)

																				with tempfile.TemporaryDirectory() as tmpdirname:
																											model.save_pretrained(lowerCAmelCase__				)
																											SCREAMING_SNAKE_CASE					,SCREAMING_SNAKE_CASE					:      str     					=			model_class.from_pretrained(lowerCAmelCase__				,    output_loading_info=lowerCAmelCase__				)
																				self.assertEqual(info['''missing_keys''']				,    []				)







						def 					__lowercase    (  self   :      int				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      Optional[int]     					=			self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowerCAmelCase__				)







						def 					__lowercase    (  self   :      Union[str, Any]				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      List[str]     					=			self.model_tester.prepare_config_and_inputs_for_common()
													self.model_tester.check_encoder_decoder_model_standalone(*lowerCAmelCase__				)







						def 					__lowercase    (  self   :      str				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					,SCREAMING_SNAKE_CASE					:      List[Any]     					=			self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
																				SCREAMING_SNAKE_CASE					:      Tuple     					=			model_class(lowerCAmelCase__				)
																				model.to(lowerCAmelCase__				)
																				model.eval()

																				SCREAMING_SNAKE_CASE					:      List[Any]     					=			copy.deepcopy(self._prepare_for_class(lowerCAmelCase__				,    lowerCAmelCase__				)				)

																				if not self.is_encoder_decoder:
																											SCREAMING_SNAKE_CASE					:      Tuple     					=			inputs['''input_ids''']
																											del inputs["input_ids"]
																				else:
																											SCREAMING_SNAKE_CASE					:      str     					=			inputs['''input_ids''']
																											SCREAMING_SNAKE_CASE					:      Tuple     					=			inputs.get('''decoder_input_ids'''				,    lowerCAmelCase__				)
																											del inputs["input_ids"]
																											inputs.pop('''decoder_input_ids'''				,    lowerCAmelCase__				)

																				SCREAMING_SNAKE_CASE					:      Optional[int]     					=			model.get_input_embeddings()
																				if not self.is_encoder_decoder:
																											SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			wte(lowerCAmelCase__				)
																				else:
																											SCREAMING_SNAKE_CASE					:      int     					=			wte(lowerCAmelCase__				)
																											SCREAMING_SNAKE_CASE					:      Tuple     					=			wte(lowerCAmelCase__				)

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







						def 					__lowercase    (  self   :      Tuple				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					,SCREAMING_SNAKE_CASE					:      int     					=			self.model_tester.prepare_config_and_inputs()
													SCREAMING_SNAKE_CASE					:      Any     					=			input_dict['''input_ids''']
													SCREAMING_SNAKE_CASE					:      List[str]     					=			input_ids.ne(1				).to(lowerCAmelCase__				)
													SCREAMING_SNAKE_CASE					:      str     					=			MaMaaaForConditionalGeneration(lowerCAmelCase__				).eval().to(lowerCAmelCase__				)
													if torch_device == "cuda":
																				model.half()
													model.generate(lowerCAmelCase__				,    attention_mask=lowerCAmelCase__				)
													model.generate(num_beams=4				,    do_sample=lowerCAmelCase__				,    early_stopping=lowerCAmelCase__				,    num_return_sequences=3				)


def 					UpperCAmelCase   (						A  :				Optional[Any]				):
							return torch.tensor(A					,		dtype=torch.long					,		device=A				)


lowerCAmelCase_     :       Union[str, Any]								=						1E-4






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







						@cached_property
						def 					__lowercase    (  self   :      Any				):

													"""simple docstring"""
													return MaMaaaTokenizer.from_pretrained('''facebook/m2m100_418M'''				)







						def 					__lowercase    (  self   :      List[str]				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      Any     					=			MaMaaaModel.from_pretrained('''facebook/m2m100_418M'''				).to(lowerCAmelCase__				)
													SCREAMING_SNAKE_CASE					:      Any     					=			_long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]				)
													SCREAMING_SNAKE_CASE					:      int     					=			_long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]				)
													SCREAMING_SNAKE_CASE					:      int     					=			prepare_mam_aaa_inputs_dict(model.config				,    lowerCAmelCase__				,    lowerCAmelCase__				)
													with torch.no_grad():
																				SCREAMING_SNAKE_CASE					:      List[Any]     					=			model(**lowerCAmelCase__				)[0]
													SCREAMING_SNAKE_CASE					:      Optional[int]     					=			torch.Size((1, 11, 10_24)				)
													self.assertEqual(output.shape				,    lowerCAmelCase__				)
													# change to expected output here
													SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			torch.tensor(
													    [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]				,    device=lowerCAmelCase__				)
													self.assertTrue(torch.allclose(output[:, :3, :3]				,    lowerCAmelCase__				,    atol=lowerCAmelCase__				)				)







						def 					__lowercase    (  self   :      Optional[Any]				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      Any     					=			MaMaaaForConditionalGeneration.from_pretrained('''facebook/m2m100_418M'''				).to(lowerCAmelCase__				)

													# change to intended input
													SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			_long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]				)
													SCREAMING_SNAKE_CASE					:      Dict     					=			_long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]				)
													SCREAMING_SNAKE_CASE					:      str     					=			prepare_mam_aaa_inputs_dict(model.config				,    lowerCAmelCase__				,    lowerCAmelCase__				)
													with torch.no_grad():
																				SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			model(**lowerCAmelCase__				)[0]
													SCREAMING_SNAKE_CASE					:      str     					=			torch.Size((1, 11, model.config.vocab_size)				)
													self.assertEqual(output.shape				,    lowerCAmelCase__				)
													# change to expected output here
													SCREAMING_SNAKE_CASE					:      List[str]     					=			torch.tensor(
													    [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]				,    device=lowerCAmelCase__				)
													self.assertTrue(torch.allclose(output[:, :3, :3]				,    lowerCAmelCase__				,    atol=lowerCAmelCase__				)				)







						def 					__lowercase    (  self   :      Tuple				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      List[str]     					=			MaMaaaForConditionalGeneration.from_pretrained('''facebook/m2m100_418M'''				).to(lowerCAmelCase__				)
													SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			MaMaaaTokenizer.from_pretrained('''facebook/m2m100_418M'''				,    src_lang='''fr'''				,    tgt_lang='''en'''				)

													SCREAMING_SNAKE_CASE					:      Union[str, 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
													SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			tokenizer(lowerCAmelCase__				,    padding=lowerCAmelCase__				,    return_tensors='''pt'''				)

													SCREAMING_SNAKE_CASE					:      Optional[int]     					=			model.generate(
													    input_ids=dct['''input_ids'''].to(lowerCAmelCase__				)				,    attention_mask=dct['''attention_mask'''].to(lowerCAmelCase__				)				,    num_beams=5				,    forced_bos_token_id=tokenizer.get_lang_id('''en'''				)				,    )

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

													SCREAMING_SNAKE_CASE					:      Tuple     					=			tokenizer.batch_decode(
													    hypotheses_batch.tolist()				,    clean_up_tokenization_spaces=lowerCAmelCase__				,    skip_special_tokens=lowerCAmelCase__				)
													assert generated == expected_en









'''simple docstring'''



from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
							import tensorflow as tf

							from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor
class 	lowerCamelCase_							:







						def __init__(  self   :      Optional[Any]				,    lowerCAmelCase__   :      Tuple				,    lowerCAmelCase__   :      int=3				,    lowerCAmelCase__   :      Tuple=32				,    lowerCAmelCase__   :      Union[str, Any]=3				,    lowerCAmelCase__   :      Dict=10				,    lowerCAmelCase__   :      List[Any]=[10, 20, 30, 40]				,    lowerCAmelCase__   :      List[Any]=[1, 1, 2, 1]				,    lowerCAmelCase__   :      Optional[int]=True				,    lowerCAmelCase__   :      Any=True				,    lowerCAmelCase__   :      List[str]="relu"				,    lowerCAmelCase__   :      int=3				,    lowerCAmelCase__   :      Tuple=None				,    ):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      Tuple     					=			parent
													SCREAMING_SNAKE_CASE					:      Optional[int]     					=			batch_size
													SCREAMING_SNAKE_CASE					:      List[Any]     					=			image_size
													SCREAMING_SNAKE_CASE					:      Optional[int]     					=			num_channels
													SCREAMING_SNAKE_CASE					:      str     					=			embeddings_size
													SCREAMING_SNAKE_CASE					:      str     					=			hidden_sizes
													SCREAMING_SNAKE_CASE					:      Tuple     					=			depths
													SCREAMING_SNAKE_CASE					:      Dict     					=			is_training
													SCREAMING_SNAKE_CASE					:      Optional[int]     					=			use_labels
													SCREAMING_SNAKE_CASE					:      Optional[int]     					=			hidden_act
													SCREAMING_SNAKE_CASE					:      str     					=			num_labels
													SCREAMING_SNAKE_CASE					:      List[Any]     					=			scope
													SCREAMING_SNAKE_CASE					:      List[Any]     					=			len(lowerCAmelCase__				)







						def 					__lowercase    (  self   :      str				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      Optional[int]     					=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

													SCREAMING_SNAKE_CASE					:      List[Any]     					=			None
													if self.use_labels:
																				SCREAMING_SNAKE_CASE					:      List[Any]     					=			ids_tensor([self.batch_size]				,    self.num_labels				)

													SCREAMING_SNAKE_CASE					:      Optional[int]     					=			self.get_config()
													return config, pixel_values, labels







						def 					__lowercase    (  self   :      Any				):

													"""simple docstring"""
													return RegNetConfig(
													    num_channels=self.num_channels				,    embeddings_size=self.embeddings_size				,    hidden_sizes=self.hidden_sizes				,    depths=self.depths				,    hidden_act=self.hidden_act				,    num_labels=self.num_labels				,    )







						def 					__lowercase    (  self   :      Dict				,    lowerCAmelCase__   :      Tuple				,    lowerCAmelCase__   :      Union[str, Any]				,    lowerCAmelCase__   :      Optional[int]				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      int     					=			TFRegNetModel(config=lowerCAmelCase__				)
													SCREAMING_SNAKE_CASE					:      int     					=			model(lowerCAmelCase__				,    training=lowerCAmelCase__				)
													# expected last hidden states: B, C, H // 32, W // 32
													self.parent.assertEqual(
													    result.last_hidden_state.shape				,    (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)				,    )







						def 					__lowercase    (  self   :      int				,    lowerCAmelCase__   :      str				,    lowerCAmelCase__   :      int				,    lowerCAmelCase__   :      List[str]				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			self.num_labels
													SCREAMING_SNAKE_CASE					:      Any     					=			TFRegNetForImageClassification(lowerCAmelCase__				)
													SCREAMING_SNAKE_CASE					:      Dict     					=			model(lowerCAmelCase__				,    labels=lowerCAmelCase__				,    training=lowerCAmelCase__				)
													self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.num_labels)				)







						def 					__lowercase    (  self   :      List[Any]				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      int     					=			self.prepare_config_and_inputs()
													SCREAMING_SNAKE_CASE					,SCREAMING_SNAKE_CASE					,SCREAMING_SNAKE_CASE					:      List[str]     					=			config_and_inputs
													SCREAMING_SNAKE_CASE					:      Tuple     					=			{'''pixel_values''': pixel_values}
													return config, inputs_dict


@require_tf
class 	lowerCamelCase_							(					snake_case_    ,				snake_case_    ,				unittest.TestCase			):
						_lowerCAmelCase     :   str	     =				(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
						_lowerCAmelCase     :   str	     =				(
						    {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification}
						    if is_tf_available()
						    else {}
						)

						_lowerCAmelCase     :   Tuple	     =				False
						_lowerCAmelCase     :   List[Any]	     =				False
						_lowerCAmelCase     :   List[str]	     =				False
						_lowerCAmelCase     :   str	     =				False
						_lowerCAmelCase     :   str	     =				False







						def 					__lowercase    (  self   :      Union[str, Any]				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      Tuple     					=			TFRegNetModelTester(self				)
													SCREAMING_SNAKE_CASE					:      Dict     					=			ConfigTester(self				,    config_class=lowerCAmelCase__				,    has_text_modality=lowerCAmelCase__				)







						def 					__lowercase    (  self   :      List[str]				):

													"""simple docstring"""
													return







						@unittest.skip(reason='''RegNet does not use inputs_embeds'''				)
						def 					__lowercase    (  self   :      Optional[int]				):

													"""simple docstring"""
													pass







						@unittest.skipIf(
						    not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''				)				) == 0				,    reason='''TF does not support backprop for grouped convolutions on CPU.'''				,    )
						@slow
						def 					__lowercase    (  self   :      int				):

													"""simple docstring"""
													super().test_keras_fit()







						@unittest.skip(reason='''RegNet does not support input and output embeddings'''				)
						def 					__lowercase    (  self   :      Dict				):

													"""simple docstring"""
													pass







						def 					__lowercase    (  self   :      int				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					,SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				SCREAMING_SNAKE_CASE					:      int     					=			model_class(lowerCAmelCase__				)
																				SCREAMING_SNAKE_CASE					:      Any     					=			inspect.signature(model.call				)
																				# signature.parameters is an OrderedDict => so arg_names order is deterministic
																				SCREAMING_SNAKE_CASE					:      Tuple     					=			[*signature.parameters.keys()]

																				SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			['''pixel_values''']
																				self.assertListEqual(arg_names[:1]				,    lowerCAmelCase__				)







						def 					__lowercase    (  self   :      Any				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*lowerCAmelCase__				)







						def 					__lowercase    (  self   :      Dict				):

													"""simple docstring"""
													def check_hidden_states_output(lowerCAmelCase__   :      Any				,    lowerCAmelCase__   :      int				,    lowerCAmelCase__   :      Tuple				):
																				SCREAMING_SNAKE_CASE					:      List[Any]     					=			model_class(lowerCAmelCase__				)
																				SCREAMING_SNAKE_CASE					:      Dict     					=			model(**self._prepare_for_class(lowerCAmelCase__				,    lowerCAmelCase__				)				,    training=lowerCAmelCase__				)

																				SCREAMING_SNAKE_CASE					:      int     					=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																				SCREAMING_SNAKE_CASE					:      int     					=			self.model_tester.num_stages
																				self.assertEqual(len(lowerCAmelCase__				)				,    expected_num_stages + 1				)

																				# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
																				self.assertListEqual(
																				    list(hidden_states[0].shape[-2:]				)				,    [self.model_tester.image_size // 2, self.model_tester.image_size // 2]				,    )

													SCREAMING_SNAKE_CASE					,SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			self.model_tester.prepare_config_and_inputs_for_common()
													SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			['''basic''', '''bottleneck''']
													for model_class in self.all_model_classes:
																				for layer_type in layers_type:
																											SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			layer_type
																											SCREAMING_SNAKE_CASE					:      Tuple     					=			True
																											check_hidden_states_output(lowerCAmelCase__				,    lowerCAmelCase__				,    lowerCAmelCase__				)

																											# check that output_hidden_states also work using config
																											del inputs_dict["output_hidden_states"]
																											SCREAMING_SNAKE_CASE					:      Optional[int]     					=			True

																											check_hidden_states_output(lowerCAmelCase__				,    lowerCAmelCase__				,    lowerCAmelCase__				)







						def 					__lowercase    (  self   :      Union[str, Any]				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					,SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			self.model_tester.prepare_config_and_inputs_for_common()

													def check_equivalence(lowerCAmelCase__   :      Tuple				,    lowerCAmelCase__   :      int				,    lowerCAmelCase__   :      Dict				,    lowerCAmelCase__   :      str={}				):
																				SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			model(lowerCAmelCase__				,    return_dict=lowerCAmelCase__				,    **lowerCAmelCase__				)
																				SCREAMING_SNAKE_CASE					:      Any     					=			model(lowerCAmelCase__				,    return_dict=lowerCAmelCase__				,    **lowerCAmelCase__				).to_tuple()

																				def recursive_check(lowerCAmelCase__   :      Dict				,    lowerCAmelCase__   :      str				):
																											if isinstance(lowerCAmelCase__				,    (List, Tuple)				):
																																		for tuple_iterable_value, dict_iterable_value in zip(lowerCAmelCase__				,    lowerCAmelCase__				):
																																									recursive_check(lowerCAmelCase__				,    lowerCAmelCase__				)
																											elif tuple_object is None:
																																		return
																											else:
																																		self.assertTrue(
																																		    all(tf.equal(lowerCAmelCase__				,    lowerCAmelCase__				)				)				,    msg=(
																																		        '''Tuple and dict output are not equal. Difference:'''
																																		        F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object				)				)}"""
																																		    )				,    )

																											recursive_check(lowerCAmelCase__				,    lowerCAmelCase__				)

													for model_class in self.all_model_classes:
																				SCREAMING_SNAKE_CASE					:      List[Any]     					=			model_class(lowerCAmelCase__				)

																				SCREAMING_SNAKE_CASE					:      int     					=			self._prepare_for_class(lowerCAmelCase__				,    lowerCAmelCase__				)
																				SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			self._prepare_for_class(lowerCAmelCase__				,    lowerCAmelCase__				)
																				check_equivalence(lowerCAmelCase__				,    lowerCAmelCase__				,    lowerCAmelCase__				)

																				SCREAMING_SNAKE_CASE					:      Optional[int]     					=			self._prepare_for_class(lowerCAmelCase__				,    lowerCAmelCase__				,    return_labels=lowerCAmelCase__				)
																				SCREAMING_SNAKE_CASE					:      str     					=			self._prepare_for_class(lowerCAmelCase__				,    lowerCAmelCase__				,    return_labels=lowerCAmelCase__				)
																				check_equivalence(lowerCAmelCase__				,    lowerCAmelCase__				,    lowerCAmelCase__				)

																				SCREAMING_SNAKE_CASE					:      Tuple     					=			self._prepare_for_class(lowerCAmelCase__				,    lowerCAmelCase__				)
																				SCREAMING_SNAKE_CASE					:      Dict     					=			self._prepare_for_class(lowerCAmelCase__				,    lowerCAmelCase__				)
																				check_equivalence(lowerCAmelCase__				,    lowerCAmelCase__				,    lowerCAmelCase__				,    {'''output_hidden_states''': True}				)

																				SCREAMING_SNAKE_CASE					:      Any     					=			self._prepare_for_class(lowerCAmelCase__				,    lowerCAmelCase__				,    return_labels=lowerCAmelCase__				)
																				SCREAMING_SNAKE_CASE					:      List[Any]     					=			self._prepare_for_class(lowerCAmelCase__				,    lowerCAmelCase__				,    return_labels=lowerCAmelCase__				)
																				check_equivalence(lowerCAmelCase__				,    lowerCAmelCase__				,    lowerCAmelCase__				,    {'''output_hidden_states''': True}				)







						def 					__lowercase    (  self   :      List[Any]				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      Dict     					=			self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__				)







						@slow
						def 					__lowercase    (  self   :      Any				):

													"""simple docstring"""
													for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			TFRegNetModel.from_pretrained(lowerCAmelCase__				)
																				self.assertIsNotNone(lowerCAmelCase__				)


def 					UpperCAmelCase   (						):
							SCREAMING_SNAKE_CASE					:      List[Any]     					=			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
							return image






@require_tf
@require_vision
class 	lowerCamelCase_							(					unittest.TestCase			):







						@cached_property
						def 					__lowercase    (  self   :      List[str]				):

													"""simple docstring"""
													return (
													    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)
													    if is_vision_available()
													    else None
													)







						@slow
						def 					__lowercase    (  self   :      str				):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE					:      str     					=			TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)

													SCREAMING_SNAKE_CASE					:      Dict     					=			self.default_image_processor
													SCREAMING_SNAKE_CASE					:      int     					=			prepare_img()
													SCREAMING_SNAKE_CASE					:      List[str]     					=			image_processor(images=lowerCAmelCase__				,    return_tensors='''tf'''				)

													# forward pass
													SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			model(**lowerCAmelCase__				,    training=lowerCAmelCase__				)

													# verify the logits
													SCREAMING_SNAKE_CASE					:      List[str]     					=			tf.TensorShape((1, 10_00)				)
													self.assertEqual(outputs.logits.shape				,    lowerCAmelCase__				)

													SCREAMING_SNAKE_CASE					:      List[str]     					=			tf.constant([-0.4180, -1.5051, -3.4836]				)

													tf.debugging.assert_near(outputs.logits[0, :3]				,    lowerCAmelCase__				,    atol=1e-4				)




