

"""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  lowerCamelCase    :

			def __init__(       self					:    Any     ,					__UpperCAmelCase					:    str     ,					__UpperCAmelCase					:    int=3     ,					__UpperCAmelCase					:    Optional[Any]=3_2     ,					__UpperCAmelCase					:    str=3     ,					__UpperCAmelCase					:    List[str]=1_0     ,					__UpperCAmelCase					:    int=[1_0, 2_0, 3_0, 4_0]     ,					__UpperCAmelCase					:    Any=[1, 1, 2, 1]     ,					__UpperCAmelCase					:    Any=True     ,					__UpperCAmelCase					:    Tuple=True     ,					__UpperCAmelCase					:    List[str]="relu"     ,					__UpperCAmelCase					:    List[Any]=3     ,					__UpperCAmelCase					:    Optional[Any]=None     ,					) ->     Tuple:
						SCREAMING_SNAKE_CASE__										=   parent
						SCREAMING_SNAKE_CASE__										=   batch_size
						SCREAMING_SNAKE_CASE__										=   image_size
						SCREAMING_SNAKE_CASE__										=   num_channels
						SCREAMING_SNAKE_CASE__										=   embeddings_size
						SCREAMING_SNAKE_CASE__										=   hidden_sizes
						SCREAMING_SNAKE_CASE__										=   depths
						SCREAMING_SNAKE_CASE__										=   is_training
						SCREAMING_SNAKE_CASE__										=   use_labels
						SCREAMING_SNAKE_CASE__										=   hidden_act
						SCREAMING_SNAKE_CASE__										=   num_labels
						SCREAMING_SNAKE_CASE__										=   scope
						SCREAMING_SNAKE_CASE__										=   len(__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    str							) ->     List[str]:
						SCREAMING_SNAKE_CASE__										=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

						SCREAMING_SNAKE_CASE__										=   None
						if self.use_labels:
									SCREAMING_SNAKE_CASE__										=   ids_tensor([self.batch_size]     ,					self.num_labels							)

						SCREAMING_SNAKE_CASE__										=   self.get_config()

						return config, pixel_values, labels

			def        SCREAMING_SNAKE_CASE					(       self					:    List[str]							) ->     Optional[Any]:
						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        SCREAMING_SNAKE_CASE					(       self					:    List[Any]     ,					__UpperCAmelCase					:    Dict     ,					__UpperCAmelCase					:    str     ,					__UpperCAmelCase					:    List[str]							) ->     Any:
						SCREAMING_SNAKE_CASE__										=   TFResNetModel(config=__UpperCAmelCase							)
						SCREAMING_SNAKE_CASE__										=   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 // 3_2, self.image_size // 3_2)     ,					)

			def        SCREAMING_SNAKE_CASE					(       self					:    List[str]     ,					__UpperCAmelCase					:    str     ,					__UpperCAmelCase					:    List[Any]     ,					__UpperCAmelCase					:    Tuple							) ->     List[Any]:
						SCREAMING_SNAKE_CASE__										=   self.num_labels
						SCREAMING_SNAKE_CASE__										=   TFResNetForImageClassification(__UpperCAmelCase							)
						SCREAMING_SNAKE_CASE__										=   model(__UpperCAmelCase     ,					labels=__UpperCAmelCase							)
						self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.num_labels)							)





			def        SCREAMING_SNAKE_CASE					(       self					:    Optional[Any]							) ->     Tuple:
						SCREAMING_SNAKE_CASE__										=   self.prepare_config_and_inputs()
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   config_and_inputs
						SCREAMING_SNAKE_CASE__										=   {"""pixel_values""": pixel_values}
						return config, inputs_dict





@require_tf
class  lowerCamelCase    (A__      ,A__      ,unittest.TestCase      ):
			lowerCamelCase__ :		Optional[Any]       		=				(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
			lowerCamelCase__ :		Union[str, Any]       		=				(
			    {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
			    if is_tf_available()
			    else {}
			)

			lowerCamelCase__ :		List[str]       		=				False
			lowerCamelCase__ :		Any       		=				False
			lowerCamelCase__ :		List[Any]       		=				False
			lowerCamelCase__ :		int       		=				False
			lowerCamelCase__ :		Tuple       		=				False

			def        SCREAMING_SNAKE_CASE					(       self					:    Any							) ->     str:
						SCREAMING_SNAKE_CASE__										=   TFResNetModelTester(self							)
						SCREAMING_SNAKE_CASE__										=   ConfigTester(self     ,					config_class=__UpperCAmelCase     ,					has_text_modality=__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Optional[int]							) ->     Any:
						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        SCREAMING_SNAKE_CASE					(       self					:    Any							) ->     Union[str, Any]:
						return

			@unittest.skip(reason="""ResNet does not use inputs_embeds"""							)
			def        SCREAMING_SNAKE_CASE					(       self					:    List[Any]							) ->     Union[str, Any]:
						pass

			@unittest.skip(reason="""ResNet does not support input and output embeddings"""							)
			def        SCREAMING_SNAKE_CASE					(       self					:    List[Any]							) ->     Any:
						pass

			def        SCREAMING_SNAKE_CASE					(       self					:    Dict							) ->     Optional[int]:
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs_for_common()

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

									SCREAMING_SNAKE_CASE__										=   ["""pixel_values"""]
									self.assertListEqual(arg_names[:1]     ,					__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Union[str, Any]							) ->     List[str]:
						SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Tuple							) ->     Any:
						def check_hidden_states_output(__UpperCAmelCase					:    str     ,					__UpperCAmelCase					:    Union[str, Any]     ,					__UpperCAmelCase					:    List[str]							):
									SCREAMING_SNAKE_CASE__										=   model_class(__UpperCAmelCase							)
									SCREAMING_SNAKE_CASE__										=   model(**self._prepare_for_class(__UpperCAmelCase     ,					__UpperCAmelCase							)							)

									SCREAMING_SNAKE_CASE__										=   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

									SCREAMING_SNAKE_CASE__										=   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]     ,					)

						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs_for_common()
						SCREAMING_SNAKE_CASE__										=   ["""basic""", """bottleneck"""]
						for model_class in self.all_model_classes:
									for layer_type in layers_type:
												SCREAMING_SNAKE_CASE__										=   layer_type
												SCREAMING_SNAKE_CASE__										=   True
												check_hidden_states_output(__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase							)

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												SCREAMING_SNAKE_CASE__										=   True

												check_hidden_states_output(__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Any							) ->     str:
						SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase							)





			@slow
			def        SCREAMING_SNAKE_CASE					(       self					:    Dict							) ->     Optional[Any]:
						for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									SCREAMING_SNAKE_CASE__										=   TFResNetModel.from_pretrained(__UpperCAmelCase							)
									self.assertIsNotNone(__UpperCAmelCase							)

def 						A							(  ):




			'''simple docstring'''


			SCREAMING_SNAKE_CASE__										=   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
			return image





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

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





			@slow
			def        SCREAMING_SNAKE_CASE					(       self					:    int							) ->     Any:
						SCREAMING_SNAKE_CASE__										=   TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)

						SCREAMING_SNAKE_CASE__										=   self.default_image_processor
						SCREAMING_SNAKE_CASE__										=   prepare_img()
						SCREAMING_SNAKE_CASE__										=   image_processor(images=__UpperCAmelCase     ,					return_tensors="""tf"""							)

						# forward pass
						SCREAMING_SNAKE_CASE__										=   model(**__UpperCAmelCase							)

						# verify the logits
						SCREAMING_SNAKE_CASE__										=   tf.TensorShape((1, 1_0_0_0)							)
						self.assertEqual(outputs.logits.shape     ,					__UpperCAmelCase							)

						SCREAMING_SNAKE_CASE__										=   tf.constant([-11.1_069, -9.7_877, -8.3_777]							)

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





"""simple docstring"""




import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
						import jax

						from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel





class  lowerCamelCase    (unittest.TestCase      ):

			def __init__(       self					:    List[Any]     ,					__UpperCAmelCase					:    Dict     ,					__UpperCAmelCase					:    Optional[Any]=1_3     ,					__UpperCAmelCase					:    Tuple=3_0     ,					__UpperCAmelCase					:    str=2     ,					__UpperCAmelCase					:    List[Any]=3     ,					__UpperCAmelCase					:    Any=True     ,					__UpperCAmelCase					:    Dict=True     ,					__UpperCAmelCase					:    Optional[Any]=3_2     ,					__UpperCAmelCase					:    Any=5     ,					__UpperCAmelCase					:    Optional[Any]=4     ,					__UpperCAmelCase					:    Tuple=3_7     ,					__UpperCAmelCase					:    List[str]="gelu"     ,					__UpperCAmelCase					:    Union[str, Any]=0.1     ,					__UpperCAmelCase					:    List[str]=0.1     ,					__UpperCAmelCase					:    int=1_0     ,					__UpperCAmelCase					:    Any=0.02     ,					) ->     Union[str, Any]:
						SCREAMING_SNAKE_CASE__										=   parent
						SCREAMING_SNAKE_CASE__										=   batch_size
						SCREAMING_SNAKE_CASE__										=   image_size
						SCREAMING_SNAKE_CASE__										=   patch_size
						SCREAMING_SNAKE_CASE__										=   num_channels
						SCREAMING_SNAKE_CASE__										=   is_training
						SCREAMING_SNAKE_CASE__										=   use_labels
						SCREAMING_SNAKE_CASE__										=   hidden_size
						SCREAMING_SNAKE_CASE__										=   num_hidden_layers
						SCREAMING_SNAKE_CASE__										=   num_attention_heads
						SCREAMING_SNAKE_CASE__										=   intermediate_size
						SCREAMING_SNAKE_CASE__										=   hidden_act
						SCREAMING_SNAKE_CASE__										=   hidden_dropout_prob
						SCREAMING_SNAKE_CASE__										=   attention_probs_dropout_prob
						SCREAMING_SNAKE_CASE__										=   type_sequence_label_size
						SCREAMING_SNAKE_CASE__										=   initializer_range

						# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
						SCREAMING_SNAKE_CASE__										=   (image_size // patch_size) ** 2
						SCREAMING_SNAKE_CASE__										=   num_patches + 1

			def        SCREAMING_SNAKE_CASE					(       self					:    List[str]							) ->     Any:
						SCREAMING_SNAKE_CASE__										=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

						SCREAMING_SNAKE_CASE__										=   ViTConfig(
						    image_size=self.image_size     ,					patch_size=self.patch_size     ,					num_channels=self.num_channels     ,					hidden_size=self.hidden_size     ,					num_hidden_layers=self.num_hidden_layers     ,					num_attention_heads=self.num_attention_heads     ,					intermediate_size=self.intermediate_size     ,					hidden_act=self.hidden_act     ,					hidden_dropout_prob=self.hidden_dropout_prob     ,					attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,					is_decoder=__UpperCAmelCase     ,					initializer_range=self.initializer_range     ,					)

						return config, pixel_values

			def        SCREAMING_SNAKE_CASE					(       self					:    Dict     ,					__UpperCAmelCase					:    int     ,					__UpperCAmelCase					:    int							) ->     Optional[Any]:
						SCREAMING_SNAKE_CASE__										=   FlaxViTModel(config=__UpperCAmelCase							)
						SCREAMING_SNAKE_CASE__										=   model(__UpperCAmelCase							)
						# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
						SCREAMING_SNAKE_CASE__										=   (self.image_size, self.image_size)
						SCREAMING_SNAKE_CASE__										=   (self.patch_size, self.patch_size)
						SCREAMING_SNAKE_CASE__										=   (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
						self.parent.assertEqual(result.last_hidden_state.shape     ,					(self.batch_size, num_patches + 1, self.hidden_size)							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Union[str, Any]     ,					__UpperCAmelCase					:    Optional[int]     ,					__UpperCAmelCase					:    Optional[Any]							) ->     int:
						SCREAMING_SNAKE_CASE__										=   self.type_sequence_label_size
						SCREAMING_SNAKE_CASE__										=   FlaxViTForImageClassification(config=__UpperCAmelCase							)
						SCREAMING_SNAKE_CASE__										=   model(__UpperCAmelCase							)
						self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.type_sequence_label_size)							)

						# test greyscale images
						SCREAMING_SNAKE_CASE__										=   1
						SCREAMING_SNAKE_CASE__										=   FlaxViTForImageClassification(__UpperCAmelCase							)

						SCREAMING_SNAKE_CASE__										=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
						SCREAMING_SNAKE_CASE__										=   model(__UpperCAmelCase							)





			def        SCREAMING_SNAKE_CASE					(       self					:    Tuple							) ->     str:
						SCREAMING_SNAKE_CASE__										=   self.prepare_config_and_inputs()
						(
						    (
						    SCREAMING_SNAKE_CASE__
						)				,		(
						    SCREAMING_SNAKE_CASE__
						)				,		
						)										=   config_and_inputs
						SCREAMING_SNAKE_CASE__										=   {"""pixel_values""": pixel_values}
						return config, inputs_dict





@require_flax
class  lowerCamelCase    (A__      ,unittest.TestCase      ):
			lowerCamelCase__ :		Tuple       		=				(FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()

			def        SCREAMING_SNAKE_CASE					(       self					:    int							) ->     None:
						SCREAMING_SNAKE_CASE__										=   FlaxViTModelTester(self							)
						SCREAMING_SNAKE_CASE__										=   ConfigTester(self     ,					config_class=__UpperCAmelCase     ,					has_text_modality=__UpperCAmelCase     ,					hidden_size=3_7							)

			def        SCREAMING_SNAKE_CASE					(       self					:    int							) ->     Dict:
						self.config_tester.run_common_tests()

			def        SCREAMING_SNAKE_CASE					(       self					:    Optional[int]							) ->     Optional[Any]:
						SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Optional[Any]							) ->     List[str]:
						SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Any							) ->     str:
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE__										=   model_class(__UpperCAmelCase							)
									SCREAMING_SNAKE_CASE__										=   inspect.signature(model.__call__							)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									SCREAMING_SNAKE_CASE__										=   [*signature.parameters.keys()]

									SCREAMING_SNAKE_CASE__										=   ["""pixel_values"""]
									self.assertListEqual(arg_names[:1]     ,					__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Any							) ->     Optional[Any]:
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									with self.subTest(model_class.__name__							):
												SCREAMING_SNAKE_CASE__										=   self._prepare_for_class(__UpperCAmelCase     ,					__UpperCAmelCase							)
												SCREAMING_SNAKE_CASE__										=   model_class(__UpperCAmelCase							)

												@jax.jit
												def model_jitted(__UpperCAmelCase					:    int     ,					**__UpperCAmelCase					:    Tuple							):
															return model(pixel_values=__UpperCAmelCase     ,					**__UpperCAmelCase							)

												with self.subTest("""JIT Enabled"""							):
															SCREAMING_SNAKE_CASE__										=   model_jitted(**__UpperCAmelCase							).to_tuple()

												with self.subTest("""JIT Disabled"""							):
															with jax.disable_jit():
																		SCREAMING_SNAKE_CASE__										=   model_jitted(**__UpperCAmelCase							).to_tuple()

												self.assertEqual(len(__UpperCAmelCase							)     ,					len(__UpperCAmelCase							)							)
												for jitted_output, output in zip(__UpperCAmelCase     ,					__UpperCAmelCase							):
															self.assertEqual(jitted_output.shape     ,					output.shape							)





			@slow
			def        SCREAMING_SNAKE_CASE					(       self					:    Any							) ->     Dict:
						for model_class_name in self.all_model_classes:
									SCREAMING_SNAKE_CASE__										=   model_class_name.from_pretrained("""google/vit-base-patch16-224"""							)
									SCREAMING_SNAKE_CASE__										=   model(np.ones((1, 3, 2_2_4, 2_2_4)							)							)
									self.assertIsNotNone(__UpperCAmelCase							)


