



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



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






									'''simple docstring'''

									A         =					parent
									A         =					batch_size
									A         =					image_size
									A         =					num_channels
									A         =					embeddings_size
									A         =					hidden_sizes
									A         =					depths
									A         =					is_training
									A         =					use_labels
									A         =					hidden_act
									A         =					num_labels
									A         =					scope
									A         =					len(snake_case				)



		def 					A_		( self  :    Any				)			->						Any:






									'''simple docstring'''

									A         =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

									A         =					self.get_config()

									return config, pixel_values, labels



		def 					A_		( self  :    Any				)			->						Tuple:






									'''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 					A_		( self  :    List[str]      ,							snake_case  :    int      ,							snake_case  :    Tuple      ,							snake_case  :    Optional[Any]				)			->						Any:






									'''simple docstring'''

									A         =					TFResNetModel(config=snake_case				)
									A         =					model(snake_case				)
									# 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 					A_		( self  :    Union[str, Any]      ,							snake_case  :    str      ,							snake_case  :    List[Any]      ,							snake_case  :    Optional[Any]				)			->						Optional[int]:






									'''simple docstring'''

									A         =					self.num_labels
									A         =					TFResNetForImageClassification(snake_case				)
									A         =					model(snake_case      ,							labels=snake_case				)
									self.parent.assertEqual(result.logits.shape      ,							(self.batch_size, self.num_labels)				)



		def 					A_		( self  :    List[str]				)			->						Dict:






									'''simple docstring'''

									A         =					self.prepare_config_and_inputs()
									A      ,  A      ,  A         =					config_and_inputs
									A         =					{'pixel_values': pixel_values}
									return config, inputs_dict






@require_tf
class      UpperCAmelCase__		(      UpperCamelCase   ,UpperCamelCase   ,unittest.TestCase     ):
		lowerCAmelCase_       :	str 							=     (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
		lowerCAmelCase_       :	Optional[Any] 							=     (
		    {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification}
		    if is_tf_available()
		    else {}
		)

		lowerCAmelCase_       :	int 							=     False
		lowerCAmelCase_       :	Optional[int] 							=     False
		lowerCAmelCase_       :	Any 							=     False
		lowerCAmelCase_       :	Tuple 							=     False
		lowerCAmelCase_       :	List[Any] 							=     False



		def 					A_		( self  :    str				)			->						Optional[Any]:






									'''simple docstring'''

									A         =					TFResNetModelTester(self				)
									A         =					ConfigTester(self      ,							config_class=snake_case      ,							has_text_modality=snake_case				)



		def 					A_		( self  :    Optional[Any]				)			->						List[str]:






									'''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 					A_		( self  :    Dict				)			->						int:






									'''simple docstring'''

									return



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






									'''simple docstring'''

									pass



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






									'''simple docstring'''

									pass



		def 					A_		( self  :    List[Any]				)			->						Tuple:






									'''simple docstring'''

									A      ,  A         =					self.model_tester.prepare_config_and_inputs_for_common()

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

																A         =					['pixel_values']
																self.assertListEqual(arg_names[:1]      ,							snake_case				)



		def 					A_		( self  :    List[Any]				)			->						Union[str, Any]:






									'''simple docstring'''

									A         =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*snake_case				)



		def 					A_		( self  :    List[str]				)			->						Dict:






									'''simple docstring'''

									def check_hidden_states_output(snake_case  :    List[Any]      ,							snake_case  :    Optional[int]      ,							snake_case  :    Optional[Any]				):
																A         =					model_class(snake_case				)
																A         =					model(**self._prepare_for_class(snake_case      ,							snake_case				)				)

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

																A         =					self.model_tester.num_stages
																self.assertEqual(len(snake_case				)      ,							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         =					self.model_tester.prepare_config_and_inputs_for_common()
									A         =					['basic', 'bottleneck']
									for model_class in self.all_model_classes:
																for layer_type in layers_type:
																							A         =					layer_type
																							A         =					True
																							check_hidden_states_output(snake_case      ,							snake_case      ,							snake_case				)

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

																							check_hidden_states_output(snake_case      ,							snake_case      ,							snake_case				)



		def 					A_		( self  :    List[str]				)			->						Tuple:






									'''simple docstring'''

									A         =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*snake_case				)



		@slow
		def 					A_		( self  :    Optional[int]				)			->						Dict:






									'''simple docstring'''

									for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																A         =					TFResNetModel.from_pretrained(snake_case				)
																self.assertIsNotNone(snake_case				)



def   lowerCAmelCase__			(     ) ->							Union[str, Any]:
							A         =					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
							return image






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



		@cached_property
		def 					A_		( self  :    str				)			->						Union[str, Any]:






									'''simple docstring'''

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



		@slow
		def 					A_		( self  :    str				)			->						Union[str, Any]:






									'''simple docstring'''

									A         =					TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)

									A         =					self.default_image_processor
									A         =					prepare_img()
									A         =					image_processor(images=snake_case      ,							return_tensors='tf'				)

									# forward pass
									A         =					model(**snake_case				)

									# verify the logits
									A         =					tf.TensorShape((1, 1_000)				)
									self.assertEqual(outputs.logits.shape      ,							snake_case				)

									A         =					tf.constant([-11.1069, -9.7877, -8.3777]				)

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








"""simple docstring"""







# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


A    =			{'configuration_mra': ['MRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MraConfig']}

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							A    =			[
							    'MRA_PRETRAINED_MODEL_ARCHIVE_LIST',
							    'MraForMaskedLM',
							    'MraForMultipleChoice',
							    'MraForQuestionAnswering',
							    'MraForSequenceClassification',
							    'MraForTokenClassification',
							    'MraLayer',
							    'MraModel',
							    'MraPreTrainedModel',
							]


if TYPE_CHECKING:
							from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_mra import (
														    MRA_PRETRAINED_MODEL_ARCHIVE_LIST,
														    MraForMaskedLM,
														    MraForMultipleChoice,
														    MraForQuestionAnswering,
														    MraForSequenceClassification,
														    MraForTokenClassification,
														    MraLayer,
														    MraModel,
														    MraPreTrainedModel,
														)
else:
							import sys

							A    =			_LazyModule(__name__, globals()['__file__'], _import_structure)



