






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





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







							'''simple docstring'''
							_UpperCamelCase :		Optional[Any]			    =       parent
							_UpperCamelCase :		List[Any]			    =       batch_size
							_UpperCamelCase :		Optional[int]			    =       image_size
							_UpperCamelCase :		Dict			    =       num_channels
							_UpperCamelCase :		Optional[Any]			    =       embeddings_size
							_UpperCamelCase :		Union[str, Any]			    =       hidden_sizes
							_UpperCamelCase :		List[Any]			    =       depths
							_UpperCamelCase :		Any			    =       is_training
							_UpperCamelCase :		Any			    =       use_labels
							_UpperCamelCase :		Optional[int]			    =       hidden_act
							_UpperCamelCase :		Optional[int]			    =       num_labels
							_UpperCamelCase :		int			    =       scope
							_UpperCamelCase :		Any			    =       len(__A			)





	def      UpperCamelCase_  (			self :    int			):







							'''simple docstring'''
							_UpperCamelCase :		int			    =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

							_UpperCamelCase :		Optional[Any]			    =       None
							if self.use_labels:
													_UpperCamelCase :		Tuple			    =       ids_tensor([self.batch_size]			,self.num_labels			)

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

							return config, pixel_values, labels





	def      UpperCamelCase_  (			self :    Optional[Any]			):







							'''simple docstring'''
							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      UpperCamelCase_  (			self :    Optional[Any]			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    Union[str, Any]			,lowerCamelCase__ :    int			):







							'''simple docstring'''
							_UpperCamelCase :		Union[str, Any]			    =       TFResNetModel(config=__A			)
							_UpperCamelCase :		Optional[int]			    =       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 // 32, self.image_size // 32)			,)





	def      UpperCamelCase_  (			self :    int			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    Dict			,lowerCamelCase__ :    List[Any]			):







							'''simple docstring'''
							_UpperCamelCase :		List[Any]			    =       self.num_labels
							_UpperCamelCase :		Optional[int]			    =       TFResNetForImageClassification(__A			)
							_UpperCamelCase :		int			    =       model(__A			,labels=__A			)
							self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.num_labels)			)





	def      UpperCamelCase_  (			self :    Dict			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[Any]			    =       self.prepare_config_and_inputs()
							_UpperCamelCase :		Union[str, Any]			    =       config_and_inputs
							_UpperCamelCase :		Tuple			    =       {"""pixel_values""": pixel_values}
							return config, inputs_dict






@require_tf
class 							lowercase__     (							A__						, A__						, unittest.TestCase       ):
	lowercase__      =      (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
	lowercase__      =      (
	    {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
	    if is_tf_available()
	    else {}
	)

	lowercase__      =      False
	lowercase__      =      False
	lowercase__      =      False
	lowercase__      =      False
	lowercase__      =      False





	def      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''
							_UpperCamelCase :		Dict			    =       TFResNetModelTester(self			)
							_UpperCamelCase :		Union[str, Any]			    =       ConfigTester(self			,config_class=__A			,has_text_modality=__A			)





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







							'''simple docstring'''
							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      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''
							return





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







							'''simple docstring'''
							pass





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







							'''simple docstring'''
							pass





	def      UpperCamelCase_  (			self :    Optional[int]			):







							'''simple docstring'''
							_UpperCamelCase :		Dict			    =       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_UpperCamelCase :		Union[str, Any]			    =       model_class(__A			)
													_UpperCamelCase :		Tuple			    =       inspect.signature(model.call			)
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													_UpperCamelCase :		Optional[int]			    =       [*signature.parameters.keys()]

													_UpperCamelCase :		Union[str, Any]			    =       ["""pixel_values"""]
													self.assertListEqual(arg_names[:1]			,__A			)





	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							_UpperCamelCase :		List[Any]			    =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__A			)





	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							def check_hidden_states_output(lowerCamelCase__ :    int			,lowerCamelCase__ :    str			,lowerCamelCase__ :    List[Any]			):
													_UpperCamelCase :		Any			    =       model_class(__A			)
													_UpperCamelCase :		List[str]			    =       model(**self._prepare_for_class(__A			,__A			)			)

													_UpperCamelCase :		Optional[int]			    =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

													_UpperCamelCase :		Optional[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 :		Dict			    =       self.model_tester.prepare_config_and_inputs_for_common()
							_UpperCamelCase :		Any			    =       ["""basic""", """bottleneck"""]
							for model_class in self.all_model_classes:
													for layer_type in layers_type:
																			_UpperCamelCase :		List[Any]			    =       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 :		int			    =       True

																			check_hidden_states_output(__A			,__A			,__A			)





	def      UpperCamelCase_  (			self :    Optional[int]			):







							'''simple docstring'''
							_UpperCamelCase :		Union[str, Any]			    =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__A			)





	@slow
	def      UpperCamelCase_  (			self :    Any			):







							'''simple docstring'''
							for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_UpperCamelCase :		List[Any]			    =       TFResNetModel.from_pretrained(__A			)
													self.assertIsNotNone(__A			)






def A__   (					):
						_UpperCamelCase :		Dict			    =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
						return image






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





	@cached_property
	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							return (
							    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)
							    if is_vision_available()
							    else None
							)





	@slow
	def      UpperCamelCase_  (			self :    int			):







							'''simple docstring'''
							_UpperCamelCase :		List[str]			    =       TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)

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

							# forward pass
							_UpperCamelCase :		Union[str, Any]			    =       model(**__A			)

							# verify the logits
							_UpperCamelCase :		Tuple			    =       tf.TensorShape((1, 1000)			)
							self.assertEqual(outputs.logits.shape			,__A			)

							_UpperCamelCase :		List[Any]			    =       tf.constant([-11.1069, -9.7_8_7_7, -8.3_7_7_7]			)

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







'''simple docstring'''
import tempfile
import unittest

from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
from transformers.testing_utils import (
    is_torch_available,
    require_optimum,
    require_torch,
    slow,
)


if is_torch_available():
					import torch






@require_torch
@require_optimum
@slow
class 							lowercase__     (							unittest.TestCase       ):





	def      UpperCamelCase_  (			self :    str			):







							'''simple docstring'''
							_UpperCamelCase :		Any			    =       'hf-internal-testing/tiny-random-t5'
							_UpperCamelCase :		str			    =       AutoTokenizer.from_pretrained(lowerCamelCase__			)
							_UpperCamelCase :		int			    =       AutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase__			)

							_UpperCamelCase :		List[str]			    =       tokenizer('This is me'			,return_tensors='pt'			)

							_UpperCamelCase :		str			    =       model.to_bettertransformer()

							self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules()			)			)

							_UpperCamelCase :		Optional[Any]			    =       model.generate(**lowerCamelCase__			)

							_UpperCamelCase :		Union[str, Any]			    =       model.reverse_bettertransformer()

							self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules()			)			)

							with tempfile.TemporaryDirectory() as tmpdirname:
													model.save_pretrained(lowerCamelCase__			)

													_UpperCamelCase :		List[Any]			    =       AutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase__			)

													self.assertFalse(
													    any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules()			)			)

													_UpperCamelCase :		Optional[Any]			    =       model_reloaded.generate(**lowerCamelCase__			)
													self.assertTrue(torch.allclose(lowerCamelCase__			,lowerCamelCase__			)			)





	def      UpperCamelCase_  (			self :    Any			):







							'''simple docstring'''
							_UpperCamelCase :		List[Any]			    =       'hf-internal-testing/tiny-random-t5'
							_UpperCamelCase :		List[Any]			    =       AutoModelForSeqaSeqLM.from_pretrained(lowerCamelCase__			)

							_UpperCamelCase :		List[str]			    =       model.to_bettertransformer()

							with tempfile.TemporaryDirectory() as tmpdirname:
													with self.assertRaises(lowerCamelCase__			):
																			model.save_pretrained(lowerCamelCase__			)

													_UpperCamelCase :		str			    =       model.reverse_bettertransformer()
													model.save_pretrained(lowerCamelCase__			)


