

import inspect
import unittest

from transformers import ResNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch
					from torch import nn

					from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
					from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor





class       __UpperCAmelCase  :



			def __init__(							self							:  Any,	__A							:  Optional[Any],	__A							:  Union[str, Any]=3,	__A							:  List[str]=3_2,	__A							:  List[str]=3,	__A							:  List[str]=1_0,	__A							:  Tuple=[1_0, 2_0, 3_0, 4_0],	__A							:  Dict=[1, 1, 2, 1],	__A							:  Any=True,	__A							:  int=True,	__A							:  Tuple="relu",	__A							:  Any=3,	__A							:  List[Any]=None,	__A							:  List[Any]=["stage2", "stage3", "stage4"],	__A							:  Tuple=[2, 3, 4],	):
					UpperCAmelCase :							Any								=				parent
					UpperCAmelCase :							str								=				batch_size
					UpperCAmelCase :							Optional[Any]								=				image_size
					UpperCAmelCase :							List[str]								=				num_channels
					UpperCAmelCase :							int								=				embeddings_size
					UpperCAmelCase :							Dict								=				hidden_sizes
					UpperCAmelCase :							Optional[int]								=				depths
					UpperCAmelCase :							Optional[Any]								=				is_training
					UpperCAmelCase :							Optional[Any]								=				use_labels
					UpperCAmelCase :							Tuple								=				hidden_act
					UpperCAmelCase :							Any								=				num_labels
					UpperCAmelCase :							str								=				scope
					UpperCAmelCase :							str								=				len(__A		)
					UpperCAmelCase :							Optional[Any]								=				out_features
					UpperCAmelCase :							Dict								=				out_indices



			def  __magic_name__					(							self							:  Any		):
					UpperCAmelCase :							Any								=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

					UpperCAmelCase :							Optional[Any]								=				None
					if self.use_labels:
							UpperCAmelCase :							Union[str, Any]								=				ids_tensor([self.batch_size],	self.num_labels		)

					UpperCAmelCase :							int								=				self.get_config()

					return config, pixel_values, labels



			def  __magic_name__					(							self							:  int		):
					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,	out_features=self.out_features,	out_indices=self.out_indices,	)



			def  __magic_name__					(							self							:  Optional[Any],	__A							:  int,	__A							:  List[str],	__A							:  Optional[Any]		):
					UpperCAmelCase :							Tuple								=				ResNetModel(config=__A		)
					model.to(__A		)
					model.eval()
					UpperCAmelCase :							str								=				model(__A		)
					# 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 // 3_2, self.image_size // 3_2),	)



			def  __magic_name__					(							self							:  str,	__A							:  str,	__A							:  List[Any],	__A							:  Any		):
					UpperCAmelCase :							Any								=				self.num_labels
					UpperCAmelCase :							int								=				ResNetForImageClassification(__A		)
					model.to(__A		)
					model.eval()
					UpperCAmelCase :							int								=				model(__A,	labels=__A		)
					self.parent.assertEqual(result.logits.shape,	(self.batch_size, self.num_labels)		)



			def  __magic_name__					(							self							:  Optional[int],	__A							:  Optional[int],	__A							:  Union[str, Any],	__A							:  Any		):
					UpperCAmelCase :							Dict								=				ResNetBackbone(config=__A		)
					model.to(__A		)
					model.eval()
					UpperCAmelCase :							Any								=				model(__A		)

					# verify feature maps
					self.parent.assertEqual(len(result.feature_maps		),	len(config.out_features		)		)
					self.parent.assertListEqual(list(result.feature_maps[0].shape		),	[self.batch_size, self.hidden_sizes[1], 4, 4]		)

					# verify channels
					self.parent.assertEqual(len(model.channels		),	len(config.out_features		)		)
					self.parent.assertListEqual(model.channels,	config.hidden_sizes[1:]		)

					# verify backbone works with out_features=None
					UpperCAmelCase :							List[str]								=				None
					UpperCAmelCase :							Tuple								=				ResNetBackbone(config=__A		)
					model.to(__A		)
					model.eval()
					UpperCAmelCase :							Union[str, Any]								=				model(__A		)

					# verify feature maps
					self.parent.assertEqual(len(result.feature_maps		),	1		)
					self.parent.assertListEqual(list(result.feature_maps[0].shape		),	[self.batch_size, self.hidden_sizes[-1], 1, 1]		)

					# verify channels
					self.parent.assertEqual(len(model.channels		),	1		)
					self.parent.assertListEqual(model.channels,	[config.hidden_sizes[-1]]		)





			def  __magic_name__					(							self							:  Any		):
					UpperCAmelCase :							Any								=				self.prepare_config_and_inputs()
					UpperCAmelCase :							Any								=				config_and_inputs
					UpperCAmelCase :							Tuple								=				{'''pixel_values''': pixel_values}
					return config, inputs_dict






@require_torch
class       __UpperCAmelCase  ( lowerCamelCase__    ,						lowerCamelCase__    ,						unittest.TestCase		):
			UpperCamelCase       =  (
			    (
			        ResNetModel,
			        ResNetForImageClassification,
			        ResNetBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			UpperCamelCase       =  (
			    {"""feature-extraction""": ResNetModel, """image-classification""": ResNetForImageClassification}
			    if is_torch_available()
			    else {}
			)

			UpperCamelCase       =  True
			UpperCamelCase       =  False
			UpperCamelCase       =  False
			UpperCamelCase       =  False
			UpperCamelCase       =  False



			def  __magic_name__					(							self							:  Optional[Any]		):
					UpperCAmelCase :							Optional[Any]								=				ResNetModelTester(self		)
					UpperCAmelCase :							Tuple								=				ConfigTester(self,	config_class=__A,	has_text_modality=__A		)



			def  __magic_name__					(							self							:  List[str]		):
					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  __magic_name__					(							self							:  Dict		):
					return



			@unittest.skip(reason='''ResNet does not use inputs_embeds'''		)
			def  __magic_name__					(							self							:  List[str]		):
					pass



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



			def  __magic_name__					(							self							:  Tuple		):
					UpperCAmelCase :							List[str]								=				self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							UpperCAmelCase :							Dict								=				model_class(__A		)
							UpperCAmelCase :							str								=				inspect.signature(model.forward		)
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							UpperCAmelCase :							Any								=				[*signature.parameters.keys()]

							UpperCAmelCase :							List[Any]								=				['''pixel_values''']
							self.assertListEqual(arg_names[:1],	__A		)



			def  __magic_name__					(							self							:  Optional[int]		):
					UpperCAmelCase :							Any								=				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*__A		)



			def  __magic_name__					(							self							:  Optional[int]		):
					UpperCAmelCase :							Optional[Any]								=				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_backbone(*__A		)



			def  __magic_name__					(							self							:  List[Any]		):
					UpperCAmelCase :							str								=				self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							UpperCAmelCase :							Any								=				model_class(config=__A		)
							for name, module in model.named_modules():
									if isinstance(__A,	(nn.BatchNormad, nn.GroupNorm)		):
											self.assertTrue(
											    torch.all(module.weight == 1		),	msg=F'''Parameter {name} of model {model_class} seems not properly initialized''',	)
											self.assertTrue(
											    torch.all(module.bias == 0		),	msg=F'''Parameter {name} of model {model_class} seems not properly initialized''',	)



			def  __magic_name__					(							self							:  Optional[int]		):
					def check_hidden_states_output(__A							:  Optional[Any],	__A							:  Tuple,	__A							:  Optional[Any]		):
							UpperCAmelCase :							Any								=				model_class(__A		)
							model.to(__A		)
							model.eval()

							with torch.no_grad():
									UpperCAmelCase :							List[Any]								=				model(**self._prepare_for_class(__A,	__A		)		)

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

							UpperCAmelCase :							List[Any]								=				self.model_tester.num_stages
							self.assertEqual(len(__A		),	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],	)

					UpperCAmelCase :							List[str]								=				self.model_tester.prepare_config_and_inputs_for_common()
					UpperCAmelCase :							int								=				['''basic''', '''bottleneck''']
					for model_class in self.all_model_classes:
							for layer_type in layers_type:
									UpperCAmelCase :							List[str]								=				layer_type
									UpperCAmelCase :							Dict								=				True
									check_hidden_states_output(__A,	__A,	__A		)

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

									check_hidden_states_output(__A,	__A,	__A		)



			@unittest.skip(reason='''ResNet does not use feedforward chunking'''		)
			def  __magic_name__					(							self							:  Optional[Any]		):
					pass



			def  __magic_name__					(							self							:  Optional[Any]		):
					UpperCAmelCase :							List[Any]								=				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*__A		)





			@slow
			def  __magic_name__					(							self							:  Optional[int]		):
					for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							UpperCAmelCase :							List[str]								=				ResNetModel.from_pretrained(__A		)
							self.assertIsNotNone(__A		)






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





@require_torch
@require_vision
class       __UpperCAmelCase  ( unittest.TestCase		):



			@cached_property
			def  __magic_name__					(							self							:  Tuple		):
					return (
					    AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
					    if is_vision_available()
					    else None
					)





			@slow
			def  __magic_name__					(							self							:  Dict		):
					UpperCAmelCase :							Optional[Any]								=				ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(__A		)

					UpperCAmelCase :							Tuple								=				self.default_image_processor
					UpperCAmelCase :							int								=				prepare_img()
					UpperCAmelCase :							str								=				image_processor(images=__A,	return_tensors='''pt'''		).to(__A		)

					# forward pass
					with torch.no_grad():
							UpperCAmelCase :							Any								=				model(**__A		)

					# verify the logits
					UpperCAmelCase :							Tuple								=				torch.Size((1, 1_0_0_0)		)
					self.assertEqual(outputs.logits.shape,	__A		)

					UpperCAmelCase :							Any								=				torch.tensor([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]		).to(__A		)

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






@require_torch
class       __UpperCAmelCase  ( lowerCamelCase__    ,						unittest.TestCase		):
			UpperCamelCase       =  (ResNetBackbone,) if is_torch_available() else ()
			UpperCamelCase       =  False
			UpperCamelCase       =  ResNetConfig



			def  __magic_name__					(							self							:  Tuple		):
					UpperCAmelCase :							List[Any]								=				ResNetModelTester(self		)








from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available


_lowerCamelCase       :     int           =							{}

try:
     if not is_sentencepiece_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     _lowerCamelCase       :     Tuple           =							["MBart50Tokenizer"]

try:
     if not is_tokenizers_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     _lowerCamelCase       :     List[Any]           =							["MBart50TokenizerFast"]


if TYPE_CHECKING:
     try:
          if not is_sentencepiece_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .tokenization_mbartaa import MBartaaTokenizer

     try:
          if not is_tokenizers_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .tokenization_mbartaa_fast import MBartaaTokenizerFast

else:
     import sys

     _lowerCamelCase       :     Optional[int]           =							_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)





