



'''simple docstring'''




import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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


if is_torch_available():
							import torch
							from torch import nn

							from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
							from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import DPTImageProcessor

class 			UpperCamelCase_ :





	def __init__(  self		,		A		,		A=2		,		A=32		,		A=16		,		A=3		,		A=True		,		A=True		,		A=32		,		A=4		,		A=[0, 1, 2, 3]		,		A=4		,		A=37		,		A="gelu"		,		A=0.1		,		A=0.1		,		A=0.0_2		,		A=3		,		A=[1, 384, 24, 24]		,		A=True		,		A=None		,		)			->			List[Any]:
								UpperCAmelCase     :		str							     =		parent
								UpperCAmelCase     :		List[str]							     =		batch_size
								UpperCAmelCase     :		int							     =		image_size
								UpperCAmelCase     :		Any							     =		patch_size
								UpperCAmelCase     :		List[str]							     =		num_channels
								UpperCAmelCase     :		Union[str, Any]							     =		is_training
								UpperCAmelCase     :		Union[str, Any]							     =		use_labels
								UpperCAmelCase     :		Optional[int]							     =		hidden_size
								UpperCAmelCase     :		List[str]							     =		num_hidden_layers
								UpperCAmelCase     :		Tuple							     =		backbone_out_indices
								UpperCAmelCase     :		Dict							     =		num_attention_heads
								UpperCAmelCase     :		int							     =		intermediate_size
								UpperCAmelCase     :		Optional[int]							     =		hidden_act
								UpperCAmelCase     :		Dict							     =		hidden_dropout_prob
								UpperCAmelCase     :		Optional[int]							     =		attention_probs_dropout_prob
								UpperCAmelCase     :		List[Any]							     =		initializer_range
								UpperCAmelCase     :		Tuple							     =		num_labels
								UpperCAmelCase     :		Optional[int]							     =		backbone_featmap_shape
								UpperCAmelCase     :		Tuple							     =		scope
								UpperCAmelCase     :		int							     =		is_hybrid
								# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
								UpperCAmelCase     :		List[Any]							     =		(image_size // patch_size) ** 2
								UpperCAmelCase     :		Union[str, Any]							     =		num_patches + 1





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

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

								UpperCAmelCase     :		List[Any]							     =		self.get_config()

								return config, pixel_values, labels





	def  _lowercase(  self    )			->			Union[str, Any]:
								UpperCAmelCase     :		List[Any]							     =		{
								    'global_padding': 'same',
								    'layer_type': 'bottleneck',
								    'depths': [3, 4, 9],
								    'out_features': ['stage1', 'stage2', 'stage3'],
								    'embedding_dynamic_padding': True,
								    'hidden_sizes': [96, 192, 384, 768],
								    'num_groups': 2,
								}

								return DPTConfig(
								    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		,		backbone_out_indices=self.backbone_out_indices		,		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=SCREAMING_SNAKE_CASE_		,		initializer_range=self.initializer_range		,		is_hybrid=self.is_hybrid		,		backbone_config=SCREAMING_SNAKE_CASE_		,		backbone_featmap_shape=self.backbone_featmap_shape		,		)





	def  _lowercase(  self		,		A		,		A		,		A    )			->			Tuple:
								UpperCAmelCase     :		Optional[int]							     =		DPTModel(config=SCREAMING_SNAKE_CASE_    )
								model.to(SCREAMING_SNAKE_CASE_    )
								model.eval()
								UpperCAmelCase     :		Any							     =		model(SCREAMING_SNAKE_CASE_    )
								self.parent.assertEqual(result.last_hidden_state.shape		,		(self.batch_size, self.seq_length, self.hidden_size)    )





	def  _lowercase(  self		,		A		,		A		,		A    )			->			Optional[Any]:
								UpperCAmelCase     :		Dict							     =		self.num_labels
								UpperCAmelCase     :		Dict							     =		DPTForDepthEstimation(SCREAMING_SNAKE_CASE_    )
								model.to(SCREAMING_SNAKE_CASE_    )
								model.eval()
								UpperCAmelCase     :		Tuple							     =		model(SCREAMING_SNAKE_CASE_    )
								self.parent.assertEqual(result.predicted_depth.shape		,		(self.batch_size, self.image_size, self.image_size)    )





	def  _lowercase(  self		,		A		,		A		,		A    )			->			List[Any]:
								UpperCAmelCase     :		Union[str, Any]							     =		self.num_labels
								UpperCAmelCase     :		str							     =		DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE_    )
								model.to(SCREAMING_SNAKE_CASE_    )
								model.eval()
								UpperCAmelCase     :		List[Any]							     =		model(SCREAMING_SNAKE_CASE_		,		labels=SCREAMING_SNAKE_CASE_    )
								self.parent.assertEqual(
								    result.logits.shape		,		(self.batch_size, self.num_labels, self.image_size, self.image_size)    )






	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		Optional[Any]							     =		self.prepare_config_and_inputs()
								UpperCAmelCase     :		int							     =		config_and_inputs
								UpperCAmelCase     :		List[str]							     =		{'pixel_values': pixel_values}
								return config, inputs_dict




@require_torch
class 			UpperCamelCase_ (							lowercase_      ,     lowercase_      ,     unittest.TestCase			):
	lowercase          = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
	lowercase          = (
	    {
	        'depth-estimation': DPTForDepthEstimation,
	        'feature-extraction': DPTModel,
	        'image-segmentation': DPTForSemanticSegmentation,
	    }
	    if is_torch_available()
	    else {}
	)

	lowercase          = False
	lowercase          = False
	lowercase          = False





	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		List[str]							     =		DPTModelTester(self    )
								UpperCAmelCase     :		int							     =		ConfigTester(self		,		config_class=SCREAMING_SNAKE_CASE_		,		has_text_modality=SCREAMING_SNAKE_CASE_		,		hidden_size=37    )





	def  _lowercase(  self    )			->			Dict:
								self.config_tester.run_common_tests()





	@unittest.skip(reason="""DPT does not use inputs_embeds"""    )
	def  _lowercase(  self    )			->			Dict:
								pass





	def  _lowercase(  self    )			->			Union[str, Any]:
								UpperCAmelCase     :		str							     =		self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase     :		Any							     =		model_class(SCREAMING_SNAKE_CASE_    )
															self.assertIsInstance(model.get_input_embeddings()		,		(nn.Module)    )
															UpperCAmelCase     :		List[str]							     =		model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_		,		nn.Linear    )    )





	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		Dict							     =		self.model_tester.prepare_config_and_inputs_for_common()

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

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





	def  _lowercase(  self    )			->			Dict:
								UpperCAmelCase     :		Optional[Any]							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_    )





	def  _lowercase(  self    )			->			List[str]:
								UpperCAmelCase     :		Dict							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE_    )





	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		int							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_    )





	def  _lowercase(  self    )			->			Union[str, Any]:
								for model_class in self.all_model_classes:
															if model_class.__name__ == "DPTForDepthEstimation":
																						continue

															UpperCAmelCase     :		Dict							     =		self.model_tester.prepare_config_and_inputs_for_common()
															UpperCAmelCase     :		Tuple							     =		True

															if model_class in get_values(SCREAMING_SNAKE_CASE_    ):
																						continue

															UpperCAmelCase     :		int							     =		model_class(SCREAMING_SNAKE_CASE_    )
															model.to(SCREAMING_SNAKE_CASE_    )
															model.train()
															UpperCAmelCase     :		Dict							     =		self._prepare_for_class(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		return_labels=SCREAMING_SNAKE_CASE_    )
															UpperCAmelCase     :		str							     =		model(**SCREAMING_SNAKE_CASE_    ).loss
															loss.backward()





	def  _lowercase(  self    )			->			int:
								for model_class in self.all_model_classes:
															if model_class.__name__ == "DPTForDepthEstimation":
																						continue

															UpperCAmelCase     :		List[str]							     =		self.model_tester.prepare_config_and_inputs_for_common()
															UpperCAmelCase     :		int							     =		False
															UpperCAmelCase     :		Union[str, Any]							     =		True

															if model_class in get_values(SCREAMING_SNAKE_CASE_    ) or not model_class.supports_gradient_checkpointing:
																						continue
															UpperCAmelCase     :		Dict							     =		model_class(SCREAMING_SNAKE_CASE_    )
															model.to(SCREAMING_SNAKE_CASE_    )
															model.gradient_checkpointing_enable()
															model.train()
															UpperCAmelCase     :		List[str]							     =		self._prepare_for_class(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		return_labels=SCREAMING_SNAKE_CASE_    )
															UpperCAmelCase     :		Union[str, Any]							     =		model(**SCREAMING_SNAKE_CASE_    ).loss
															loss.backward()





	def  _lowercase(  self    )			->			Tuple:
								UpperCAmelCase     :		Dict							     =		self.model_tester.prepare_config_and_inputs_for_common()

								UpperCAmelCase     :		List[Any]							     =		_config_zero_init(SCREAMING_SNAKE_CASE_    )
								for model_class in self.all_model_classes:
															UpperCAmelCase     :		Optional[int]							     =		model_class(config=SCREAMING_SNAKE_CASE_    )
															# Skip the check for the backbone
															UpperCAmelCase     :		Union[str, Any]							     =		[]
															for name, module in model.named_modules():
																						if module.__class__.__name__ == "DPTViTHybridEmbeddings":
																													UpperCAmelCase     :		List[Any]							     =		[f'''{name}.{key}''' for key in module.state_dict().keys()]
																													break

															for name, param in model.named_parameters():
																						if param.requires_grad:
																													if name in backbone_params:
																																				continue
																													self.assertIn(
																													    ((param.data.mean() * 1e9).round() / 1e9).item()		,		[0.0, 1.0]		,		msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''		,		)





	@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""    )
	def  _lowercase(  self    )			->			str:
								pass





	@slow
	def  _lowercase(  self    )			->			List[str]:
								for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
															UpperCAmelCase     :		Tuple							     =		DPTModel.from_pretrained(SCREAMING_SNAKE_CASE_    )
															self.assertIsNotNone(SCREAMING_SNAKE_CASE_    )






	def  _lowercase(  self    )			->			Union[str, Any]:
								# We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
								UpperCAmelCase     :		List[str]							     =		self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase     :		Dict							     =		'add'
								with self.assertRaises(SCREAMING_SNAKE_CASE_    ):
															UpperCAmelCase     :		Optional[int]							     =		DPTForDepthEstimation(SCREAMING_SNAKE_CASE_    )




def       __lowerCamelCase  (					)      ->			Tuple:
							UpperCAmelCase     :		List[str]							     =		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
							return image


@require_torch
@require_vision
@slow
class 			UpperCamelCase_ (							unittest.TestCase			):





	def  _lowercase(  self    )			->			Union[str, Any]:
								UpperCAmelCase     :		str							     =		DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas"""    )
								UpperCAmelCase     :		str							     =		DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas"""    ).to(SCREAMING_SNAKE_CASE_    )

								UpperCAmelCase     :		int							     =		prepare_img()
								UpperCAmelCase     :		Optional[int]							     =		image_processor(images=SCREAMING_SNAKE_CASE_		,		return_tensors="""pt"""    ).to(SCREAMING_SNAKE_CASE_    )

								# forward pass
								with torch.no_grad():
															UpperCAmelCase     :		int							     =		model(**SCREAMING_SNAKE_CASE_    )
															UpperCAmelCase     :		int							     =		outputs.predicted_depth

								# verify the predicted depth
								UpperCAmelCase     :		List[Any]							     =		torch.Size((1, 384, 384)    )
								self.assertEqual(predicted_depth.shape		,		SCREAMING_SNAKE_CASE_    )

								UpperCAmelCase     :		Dict							     =		torch.tensor(
								    [[[5.6_4_3_7, 5.6_1_4_6, 5.6_5_1_1], [5.4_3_7_1, 5.5_6_4_9, 5.5_9_5_8], [5.5_2_1_5, 5.5_1_8_4, 5.5_2_9_3]]]    ).to(SCREAMING_SNAKE_CASE_    )

								self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100		,		SCREAMING_SNAKE_CASE_		,		atol=1e-4    )    )






"""simple docstring"""







from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor







class       UpperCamelCase__   :




      """simple docstring"""




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



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

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

        lowerCAmelCase_   :				List[str]								= self.get_config()
        return config, pixel_values, labels



      def      SCREAMING_SNAKE_CASE__ (      self				:      str       ):
        return RegNetConfig(
            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    ,			)



      def      SCREAMING_SNAKE_CASE__ (      self				:      Any    ,			SCREAMING_SNAKE_CASE_				:      List[str]    ,			SCREAMING_SNAKE_CASE_				:      List[Any]    ,			SCREAMING_SNAKE_CASE_				:      int       ):
        lowerCAmelCase_   :				List[Any]								= TFRegNetModel(config=SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				List[Any]								= model(SCREAMING_SNAKE_CASE_    ,			training=SCREAMING_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 // 3_2, self.image_size // 3_2)    ,			)



      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]    ,			SCREAMING_SNAKE_CASE_				:      Tuple    ,			SCREAMING_SNAKE_CASE_				:      Optional[int]    ,			SCREAMING_SNAKE_CASE_				:      Optional[Any]       ):
        lowerCAmelCase_   :				int								= self.num_labels
        lowerCAmelCase_   :				int								= TFRegNetForImageClassification(SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				Dict								= model(SCREAMING_SNAKE_CASE_    ,			labels=SCREAMING_SNAKE_CASE_    ,			training=SCREAMING_SNAKE_CASE_       )
        self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.num_labels)       )





      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]       ):
        lowerCAmelCase_   :				str								= self.prepare_config_and_inputs()
        lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_   :				Tuple								= config_and_inputs
        lowerCAmelCase_   :				Optional[Any]								= {'pixel_values': pixel_values}
        return config, inputs_dict







@require_tf
class       UpperCamelCase__   (	lowercase_,					lowercase_,					unittest.TestCase  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE  				=     (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
      _SCREAMING_SNAKE_CASE  				=     (
          {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
          if is_tf_available()
          else {}
      )

      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False



      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        lowerCAmelCase_   :				List[Any]								= TFRegNetModelTester(self       )
        lowerCAmelCase_   :				Tuple								= ConfigTester(self    ,			config_class=SCREAMING_SNAKE_CASE_    ,			has_text_modality=SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[int]       ):
        return



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



      @unittest.skipIf(
          not is_tf_available() or len(tf.config.list_physical_devices('GPU'       )       ) == 0    ,			reason='TF does not support backprop for grouped convolutions on CPU.'    ,			)
      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      Tuple       ):
        super().test_keras_fit()



      @unittest.skip(reason='RegNet does not support input and output embeddings'       )
      def      SCREAMING_SNAKE_CASE__ (      self				:      Union[str, Any]       ):
        pass



      def      SCREAMING_SNAKE_CASE__ (      self				:      int       ):
        lowerCAmelCase_						,lowerCAmelCase_   :				Optional[int]								= self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          lowerCAmelCase_   :				int								= model_class(SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				Dict								= inspect.signature(model.call       )
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          lowerCAmelCase_   :				List[Any]								= [*signature.parameters.keys()]

          lowerCAmelCase_   :				Any								= ['pixel_values']
          self.assertListEqual(arg_names[:1]    ,			SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Any       ):
        lowerCAmelCase_   :				Dict								= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[int]       ):
        def check_hidden_states_output(SCREAMING_SNAKE_CASE_				:      Tuple    ,			SCREAMING_SNAKE_CASE_				:      int    ,			SCREAMING_SNAKE_CASE_				:      Tuple       ):
          lowerCAmelCase_   :				List[Any]								= model_class(SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				Union[str, Any]								= model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )    ,			training=SCREAMING_SNAKE_CASE_       )

          lowerCAmelCase_   :				List[str]								= outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          lowerCAmelCase_   :				Union[str, Any]								= self.model_tester.num_stages
          self.assertEqual(len(SCREAMING_SNAKE_CASE_       )    ,			expected_num_stages + 1       )

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

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

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

            check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[Any]       ):
        lowerCAmelCase_						,lowerCAmelCase_   :				int								= self.model_tester.prepare_config_and_inputs_for_common()

        def check_equivalence(SCREAMING_SNAKE_CASE_				:      Dict    ,			SCREAMING_SNAKE_CASE_				:      str    ,			SCREAMING_SNAKE_CASE_				:      Optional[int]    ,			SCREAMING_SNAKE_CASE_				:      str={}       ):
          lowerCAmelCase_   :				Optional[Any]								= model(SCREAMING_SNAKE_CASE_    ,			return_dict=SCREAMING_SNAKE_CASE_    ,			**SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				List[Any]								= model(SCREAMING_SNAKE_CASE_    ,			return_dict=SCREAMING_SNAKE_CASE_    ,			**SCREAMING_SNAKE_CASE_       ).to_tuple()

          def recursive_check(SCREAMING_SNAKE_CASE_				:      int    ,			SCREAMING_SNAKE_CASE_				:      int       ):
            if isinstance(SCREAMING_SNAKE_CASE_    ,			(List, Tuple)       ):
              for tuple_iterable_value, dict_iterable_value in zip(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       ):
                recursive_check(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
            elif tuple_object is None:
              return
            else:
              self.assertTrue(
                  all(tf.equal(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )       )    ,			msg=(
                      'Tuple and dict output are not equal. Difference:'
                      F" {tf.math.reduce_max(tf.abs(tuple_object - dict_object       )       )}"
                  )    ,			)

            recursive_check(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )

        for model_class in self.all_model_classes:
          lowerCAmelCase_   :				Union[str, Any]								= model_class(SCREAMING_SNAKE_CASE_       )

          lowerCAmelCase_   :				List[Any]								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				Union[str, Any]								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
          check_equivalence(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )

          lowerCAmelCase_   :				Optional[int]								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			return_labels=SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				str								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			return_labels=SCREAMING_SNAKE_CASE_       )
          check_equivalence(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )

          lowerCAmelCase_   :				Tuple								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				int								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )
          check_equivalence(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			{'output_hidden_states': True}       )

          lowerCAmelCase_   :				List[Any]								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			return_labels=SCREAMING_SNAKE_CASE_       )
          lowerCAmelCase_   :				Any								= self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			return_labels=SCREAMING_SNAKE_CASE_       )
          check_equivalence(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			{'output_hidden_states': True}       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Union[str, Any]       ):
        lowerCAmelCase_   :				List[str]								= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_       )





      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      Union[str, Any]       ):
        for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase_   :				int								= TFRegNetModel.from_pretrained(SCREAMING_SNAKE_CASE_       )
          self.assertIsNotNone(SCREAMING_SNAKE_CASE_       )




def 				UpperCamelCase_    (    )						->   List[str]:

  """simple docstring"""




  lowerCAmelCase_   :				Optional[Any]								= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
  return image







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




      """simple docstring"""




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





      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        lowerCAmelCase_   :				int								= TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

        lowerCAmelCase_   :				Tuple								= self.default_image_processor
        lowerCAmelCase_   :				Dict								= prepare_img()
        lowerCAmelCase_   :				Union[str, Any]								= image_processor(images=SCREAMING_SNAKE_CASE_    ,			return_tensors='tf'       )

        # forward pass
        lowerCAmelCase_   :				List[str]								= model(**SCREAMING_SNAKE_CASE_    ,			training=SCREAMING_SNAKE_CASE_       )

        # verify the logits
        lowerCAmelCase_   :				Optional[Any]								= tf.TensorShape((1, 1_0_0_0)       )
        self.assertEqual(outputs.logits.shape    ,			SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				List[Any]								= tf.constant([-0.41_80, -1.50_51, -3.48_36]       )

        tf.debugging.assert_near(outputs.logits[0, :3]    ,			SCREAMING_SNAKE_CASE_    ,			atol=1E-4       )





