



'''simple docstring'''

from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
							from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor

class       __magic_name__		:







							def __init__(				self   :			Optional[int]      ,_UpperCAmelCase   :			Optional[int]      ,_UpperCAmelCase   :			Union[str, Any]=3      ,_UpperCAmelCase   :			str=32      ,_UpperCAmelCase   :			Tuple=3      ,_UpperCAmelCase   :			Optional[Any]=10      ,_UpperCAmelCase   :			Union[str, Any]=[10, 20, 30, 40]      ,_UpperCAmelCase   :			int=[1, 1, 2, 1]      ,_UpperCAmelCase   :			Tuple=True      ,_UpperCAmelCase   :			Dict=True      ,_UpperCAmelCase   :			str="relu"      ,_UpperCAmelCase   :			Tuple=3      ,_UpperCAmelCase   :			Optional[Any]=None      ,):
									_a	: int								=				parent
									_a	: List[Any]								=				batch_size
									_a	: Optional[int]								=				image_size
									_a	: Optional[Any]								=				num_channels
									_a	: Optional[Any]								=				embeddings_size
									_a	: Union[str, Any]								=				hidden_sizes
									_a	: Any								=				depths
									_a	: Union[str, Any]								=				is_training
									_a	: List[str]								=				use_labels
									_a	: Any								=				hidden_act
									_a	: str								=				num_labels
									_a	: int								=				scope
									_a	: Optional[int]								=				len(_UpperCAmelCase						)







							def 				__lowercase     (				self   :			int						):
									_a	: str								=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

									_a	: str								=				None
									if self.use_labels:
											_a	: Tuple								=				ids_tensor([self.batch_size]      ,self.num_labels						)

									_a	: Optional[Any]								=				self.get_config()

									return config, pixel_values, labels







							def 				__lowercase     (				self   :			List[str]						):
									return ResNetConfig(
									    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      ,image_size=self.image_size      ,)







							def 				__lowercase     (				self   :			Optional[int]      ,_UpperCAmelCase   :			int      ,_UpperCAmelCase   :			str      ,_UpperCAmelCase   :			Any						):
									_a	: Optional[Any]								=				TFResNetModel(config=_UpperCAmelCase						)
									_a	: List[Any]								=				model(_UpperCAmelCase						)
									# 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   :			Any      ,_UpperCAmelCase   :			Dict      ,_UpperCAmelCase   :			Dict      ,_UpperCAmelCase   :			Optional[int]						):
									_a	: int								=				self.num_labels
									_a	: Tuple								=				TFResNetForImageClassification(_UpperCAmelCase						)
									_a	: List[str]								=				model(_UpperCAmelCase      ,labels=_UpperCAmelCase						)
									self.parent.assertEqual(result.logits.shape      ,(self.batch_size, self.num_labels)						)







							def 				__lowercase     (				self   :			Any						):
									_a	: Union[str, Any]								=				self.prepare_config_and_inputs()
									_a			,   _a			,   _a	: List[Any]								=				config_and_inputs
									_a	: Any								=				{'pixel_values': pixel_values}
									return config, inputs_dict

@require_tf
class       __magic_name__		(       _UpperCamelCase     ,		_UpperCamelCase     ,		unittest.TestCase  ):
							lowerCAmelCase			:       str  							=   (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
							lowerCAmelCase			:       int  							=   (
							    {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
							    if is_tf_available()
							    else {}
							)

							lowerCAmelCase			:       Dict  							=   False
							lowerCAmelCase			:       List[Any]  							=   False
							lowerCAmelCase			:       Optional[Any]  							=   False
							lowerCAmelCase			:       Union[str, Any]  							=   False
							lowerCAmelCase			:       Dict  							=   False







							def 				__lowercase     (				self   :			Any						):
									_a	: Dict								=				TFResNetModelTester(self						)
									_a	: Tuple								=				ConfigTester(self      ,config_class=_UpperCAmelCase      ,has_text_modality=_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Optional[int]						):
									self.create_and_test_config_common_properties()
									self.config_tester.create_and_test_config_to_json_string()
									self.config_tester.create_and_test_config_to_json_file()
									self.config_tester.create_and_test_config_from_and_save_pretrained()
									self.config_tester.create_and_test_config_with_num_labels()
									self.config_tester.check_config_can_be_init_without_params()
									self.config_tester.check_config_arguments_init()







							def 				__lowercase     (				self   :			Optional[Any]						):
									return







							@unittest.skip(reason='ResNet does not use inputs_embeds'						)
							def 				__lowercase     (				self   :			Tuple						):
									pass







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







							def 				__lowercase     (				self   :			List[Any]						):
									_a			,   _a	: Dict								=				self.model_tester.prepare_config_and_inputs_for_common()

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

											_a	: Optional[int]								=				['pixel_values']
											self.assertListEqual(arg_names[:1]      ,_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Tuple						):
									_a	: Tuple								=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_UpperCAmelCase						)







							def 				__lowercase     (				self   :			List[str]						):
									def check_hidden_states_output(_UpperCAmelCase   :			Optional[Any]      ,_UpperCAmelCase   :			Optional[int]      ,_UpperCAmelCase   :			str						):
											_a	: Optional[Any]								=				model_class(_UpperCAmelCase						)
											_a	: str								=				model(**self._prepare_for_class(_UpperCAmelCase      ,_UpperCAmelCase						)						)

											_a	: Union[str, Any]								=				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

											_a	: Tuple								=				self.model_tester.num_stages
											self.assertEqual(len(_UpperCAmelCase						)      ,expected_num_stages + 1						)

											# ResNet'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 // 4, self.model_tester.image_size // 4]      ,)

									_a			,   _a	: Optional[Any]								=				self.model_tester.prepare_config_and_inputs_for_common()
									_a	: Union[str, Any]								=				['basic', 'bottleneck']
									for model_class in self.all_model_classes:
											for layer_type in layers_type:
													_a	: str								=				layer_type
													_a	: List[Any]								=				True
													check_hidden_states_output(_UpperCAmelCase      ,_UpperCAmelCase      ,_UpperCAmelCase						)

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													_a	: Any								=				True

													check_hidden_states_output(_UpperCAmelCase      ,_UpperCAmelCase      ,_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Optional[Any]						):
									_a	: Optional[int]								=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase						)







							@slow
							def 				__lowercase     (				self   :			Union[str, Any]						):
									for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											_a	: int								=				TFResNetModel.from_pretrained(_UpperCAmelCase						)
											self.assertIsNotNone(_UpperCAmelCase						)



def 	__lowerCamelCase	( )     -> List[Any]:
		_a	: Optional[Any]								=				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
		return image

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







							@cached_property
							def 				__lowercase     (				self   :			Union[str, Any]						):
									return (
									    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
									    if is_vision_available()
									    else None
									)







							@slow
							def 				__lowercase     (				self   :			Optional[int]						):
									_a	: int								=				TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)

									_a	: str								=				self.default_image_processor
									_a	: Union[str, Any]								=				prepare_img()
									_a	: Optional[int]								=				image_processor(images=_UpperCAmelCase      ,return_tensors='tf'						)

									# forward pass
									_a	: Union[str, Any]								=				model(**_UpperCAmelCase						)

									# verify the logits
									_a	: Union[str, Any]								=				tf.TensorShape((1, 1000)						)
									self.assertEqual(outputs.logits.shape      ,_UpperCAmelCase						)

									_a	: Optional[Any]								=				tf.constant([-11.10_69, -9.78_77, -8.37_77]						)

									self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()      ,_UpperCAmelCase      ,atol=1E-4						)						)









'''simple docstring'''

from __future__ import annotations

import unittest

from transformers import AutoTokenizer, MBartConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

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


if is_tf_available():
							import tensorflow as tf

							from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel

@require_tf
class       __magic_name__		:
							lowerCAmelCase			:       Optional[Any]  							=   MBartConfig
							lowerCAmelCase			:       str  							=   {}
							lowerCAmelCase			:       Dict  							=   'gelu'







							def __init__(				self   :			List[str]      ,_UpperCAmelCase   :			List[str]      ,_UpperCAmelCase   :			Tuple=13      ,_UpperCAmelCase   :			str=7      ,_UpperCAmelCase   :			Dict=True      ,_UpperCAmelCase   :			Optional[int]=False      ,_UpperCAmelCase   :			List[str]=99      ,_UpperCAmelCase   :			str=32      ,_UpperCAmelCase   :			List[str]=2      ,_UpperCAmelCase   :			Optional[int]=4      ,_UpperCAmelCase   :			str=37      ,_UpperCAmelCase   :			Union[str, Any]=0.1      ,_UpperCAmelCase   :			str=0.1      ,_UpperCAmelCase   :			Dict=20      ,_UpperCAmelCase   :			Optional[Any]=2      ,_UpperCAmelCase   :			Union[str, Any]=1      ,_UpperCAmelCase   :			List[str]=0      ,):
									_a	: Any								=				parent
									_a	: List[Any]								=				batch_size
									_a	: Any								=				seq_length
									_a	: List[str]								=				is_training
									_a	: str								=				use_labels
									_a	: List[Any]								=				vocab_size
									_a	: List[str]								=				hidden_size
									_a	: Union[str, Any]								=				num_hidden_layers
									_a	: Optional[Any]								=				num_attention_heads
									_a	: Optional[int]								=				intermediate_size
									_a	: Any								=				hidden_dropout_prob
									_a	: int								=				attention_probs_dropout_prob
									_a	: Union[str, Any]								=				max_position_embeddings
									_a	: Union[str, Any]								=				eos_token_id
									_a	: int								=				pad_token_id
									_a	: Union[str, Any]								=				bos_token_id







							def 				__lowercase     (				self   :			Optional[Any]						):
									_a	: str								=				ids_tensor([self.batch_size, self.seq_length - 1]      ,self.vocab_size						)
									_a	: List[str]								=				tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size						)      ,1						)
									_a	: str								=				tf.concat([input_ids, eos_tensor]      ,axis=1						)

									_a	: Dict								=				ids_tensor([self.batch_size, self.seq_length]      ,self.vocab_size						)

									_a	: List[str]								=				self.config_cls(
									    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      ,max_position_embeddings=self.max_position_embeddings      ,eos_token_ids=[2]      ,bos_token_id=self.bos_token_id      ,pad_token_id=self.pad_token_id      ,decoder_start_token_id=self.pad_token_id      ,**self.config_updates      ,)
									_a	: Optional[int]								=				prepare_mbart_inputs_dict(_UpperCAmelCase      ,_UpperCAmelCase      ,_UpperCAmelCase						)
									return config, inputs_dict







							def 				__lowercase     (				self   :			Optional[Any]      ,_UpperCAmelCase   :			Union[str, Any]      ,_UpperCAmelCase   :			Optional[int]						):
									_a	: str								=				TFMBartModel(config=_UpperCAmelCase						).get_decoder()
									_a	: List[Any]								=				inputs_dict['input_ids']

									_a	: Optional[Any]								=				input_ids[:1, :]
									_a	: Tuple								=				inputs_dict['attention_mask'][:1, :]
									_a	: List[Any]								=				inputs_dict['head_mask']
									_a	: str								=				1

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

									_a			,   _a	: Optional[int]								=				outputs.to_tuple()
									_a	: Union[str, Any]								=				past_key_values[1]



def 	__lowerCamelCase	( lowerCAmelCase_		,     lowerCAmelCase_		,     lowerCAmelCase_		,     lowerCAmelCase_=None		,     lowerCAmelCase_=None		,     lowerCAmelCase_=None		,     lowerCAmelCase_=None		,     lowerCAmelCase_=None		,     )     -> Union[str, Any]:
		if attention_mask is None:
				_a	: List[Any]								=				tf.cast(tf.math.not_equal(lowerCAmelCase_		,     config.pad_token_id    )		,     tf.inta    )
		if decoder_attention_mask is None:
				_a	: Any								=				tf.concat(
				    [
				        tf.ones(decoder_input_ids[:, :1].shape		,     dtype=tf.inta    ),
				        tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]		,     config.pad_token_id    )		,     tf.inta    ),
				    ]		,     axis=-1		,     )
		if head_mask is None:
				_a	: int								=				tf.ones((config.encoder_layers, config.encoder_attention_heads)    )
		if decoder_head_mask is None:
				_a	: Any								=				tf.ones((config.decoder_layers, config.decoder_attention_heads)    )
		if cross_attn_head_mask is None:
				_a	: int								=				tf.ones((config.decoder_layers, config.decoder_attention_heads)    )
		return {
		    "input_ids": input_ids,
		    "decoder_input_ids": decoder_input_ids,
		    "attention_mask": attention_mask,
		    "decoder_attention_mask": decoder_attention_mask,
		    "head_mask": head_mask,
		    "decoder_head_mask": decoder_head_mask,
		    "cross_attn_head_mask": cross_attn_head_mask,
		}

@require_tf
class       __magic_name__		(       _UpperCamelCase     ,		_UpperCamelCase     ,		unittest.TestCase  ):
							lowerCAmelCase			:       List[str]  							=   (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
							lowerCAmelCase			:       Optional[Any]  							=   (TFMBartForConditionalGeneration,) if is_tf_available() else ()
							lowerCAmelCase			:       Dict  							=   (
							    {
							        'conversational': TFMBartForConditionalGeneration,
							        'feature-extraction': TFMBartModel,
							        'summarization': TFMBartForConditionalGeneration,
							        'text2text-generation': TFMBartForConditionalGeneration,
							        'translation': TFMBartForConditionalGeneration,
							    }
							    if is_tf_available()
							    else {}
							)
							lowerCAmelCase			:       Dict  							=   True
							lowerCAmelCase			:       List[str]  							=   False
							lowerCAmelCase			:       str  							=   False







							def 				__lowercase     (				self   :			int      ,_UpperCAmelCase   :			Dict      ,_UpperCAmelCase   :			str      ,_UpperCAmelCase   :			Union[str, Any]      ,_UpperCAmelCase   :			Union[str, Any]      ,_UpperCAmelCase   :			int						):
									if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
											# Exception encountered when calling layer '...'
											return True

									return False







							def 				__lowercase     (				self   :			Optional[Any]						):
									_a	: Optional[int]								=				TFMBartModelTester(self						)
									_a	: Dict								=				ConfigTester(self      ,config_class=_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Optional[int]						):
									self.config_tester.run_common_tests()







							def 				__lowercase     (				self   :			Optional[int]						):
									_a	: List[Any]								=				self.model_tester.prepare_config_and_inputs_for_common()
									self.model_tester.check_decoder_model_past_large_inputs(*_UpperCAmelCase						)

@require_sentencepiece
@require_tokenizers
@require_tf
class       __magic_name__		(       unittest.TestCase  ):
							lowerCAmelCase			:       List[Any]  							=   [
							    ' UN Chief Says There Is No Military Solution in Syria',
							]
							lowerCAmelCase			:       Dict  							=   [
							    'Şeful ONU declară că nu există o soluţie militară în Siria',
							]
							lowerCAmelCase			:       Tuple  							=   'facebook/mbart-large-en-ro'







							@cached_property
							def 				__lowercase     (				self   :			Optional[int]						):
									return AutoTokenizer.from_pretrained(self.model_name						)







							@cached_property
							def 				__lowercase     (				self   :			Optional[int]						):
									_a	: Any								=				TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name						)
									return model







							def 				__lowercase     (				self   :			Optional[int]      ,**_UpperCAmelCase   :			Dict						):
									_a	: List[Any]								=				self.translate_src_text(**_UpperCAmelCase						)
									self.assertListEqual(self.expected_text      ,_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Tuple      ,**_UpperCAmelCase   :			str						):
									_a	: List[Any]								=				self.tokenizer(self.src_text      ,**_UpperCAmelCase      ,return_tensors='tf'						)
									_a	: Any								=				self.model.generate(
									    model_inputs.input_ids      ,attention_mask=model_inputs.attention_mask      ,num_beams=2						)
									_a	: Tuple								=				self.tokenizer.batch_decode(_UpperCAmelCase      ,skip_special_tokens=_UpperCAmelCase						)
									return generated_words







							@slow
							def 				__lowercase     (				self   :			Tuple						):
									self._assert_generated_batch_equal_expected()




