


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 					__magic_name__		:


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





      '''simple docstring'''






      UpperCamelCase__    :			List[Any]      				=      parent
      UpperCamelCase__    :			Optional[int]      				=      batch_size
      UpperCamelCase__    :			Dict      				=      image_size
      UpperCamelCase__    :			Tuple      				=      num_channels
      UpperCamelCase__    :			List[Any]      				=      embeddings_size
      UpperCamelCase__    :			Dict      				=      hidden_sizes
      UpperCamelCase__    :			Tuple      				=      depths
      UpperCamelCase__    :			Optional[Any]      				=      is_training
      UpperCamelCase__    :			str      				=      use_labels
      UpperCamelCase__    :			Any      				=      hidden_act
      UpperCamelCase__    :			Union[str, Any]      				=      num_labels
      UpperCamelCase__    :			Union[str, Any]      				=      scope
      UpperCamelCase__    :			List[Any]      				=      len(__lowercase	)


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





      '''simple docstring'''






      UpperCamelCase__    :			List[Any]      				=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

      UpperCamelCase__    :			Optional[int]      				=      self.get_config()

      return config, pixel_values, labels


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





      '''simple docstring'''






      UpperCamelCase__    :			List[str]      				=      TFResNetModel(config=__lowercase	)
      UpperCamelCase__    :			List[str]      				=      model(__lowercase	)
      # 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							:   Optional[Any]							,		lowerCamelCase__							:   Any							,		lowerCamelCase__							:   Dict							,		lowerCamelCase__							:   int	)     ->					str:





      '''simple docstring'''






      UpperCamelCase__    :			str      				=      self.num_labels
      UpperCamelCase__    :			str      				=      TFResNetForImageClassification(__lowercase	)
      UpperCamelCase__    :			int      				=      model(__lowercase							,		labels=__lowercase	)
      self.parent.assertEqual(result.logits.shape							,		(self.batch_size, self.num_labels)	)


     def    UpperCAmelCase__		(					self							:   Dict	)     ->					Optional[int]:





      '''simple docstring'''






      UpperCamelCase__    :			List[Any]      				=      self.prepare_config_and_inputs()
      UpperCamelCase__    :			Dict      				=      config_and_inputs
      UpperCamelCase__    :			Tuple      				=      {"""pixel_values""": pixel_values}
      return config, inputs_dict



@require_tf
class 					__magic_name__		(   lowercase__    , lowercase__    , unittest.TestCase):
     A:						Dict								=					(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
     A:						List[str]								=					(
         {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
         if is_tf_available()
         else {}
     )

     A:						Tuple								=					False
     A:						Tuple								=					False
     A:						Optional[int]								=					False
     A:						Any								=					False
     A:						Any								=					False


     def    UpperCAmelCase__		(					self							:   List[Any]	)     ->					Any:





      '''simple docstring'''






      UpperCamelCase__    :			str      				=      TFResNetModelTester(self	)
      UpperCamelCase__    :			List[Any]      				=      ConfigTester(self							,		config_class=__lowercase							,		has_text_modality=__lowercase	)


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





      '''simple docstring'''






      return


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





      '''simple docstring'''






      pass


     @unittest.skip(reason='''ResNet does not support input and output embeddings'''	)
     def    UpperCAmelCase__		(					self							:   int	)     ->					List[str]:





      '''simple docstring'''






      pass


     def    UpperCAmelCase__		(					self							:   Any	)     ->					Tuple:





      '''simple docstring'''






      UpperCamelCase__    :			Optional[Any]      				=      self.model_tester.prepare_config_and_inputs_for_common()

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

       UpperCamelCase__    :			int      				=      ["""pixel_values"""]
       self.assertListEqual(arg_names[:1]							,		__lowercase	)


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





      '''simple docstring'''






      UpperCamelCase__    :			Dict      				=      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__lowercase	)


     def    UpperCAmelCase__		(					self							:   Dict	)     ->					Tuple:





      '''simple docstring'''






      def check_hidden_states_output(lowerCamelCase__							:   Optional[Any]							,		lowerCamelCase__							:   int							,		lowerCamelCase__							:   Any	):
       UpperCamelCase__    :			int      				=      model_class(__lowercase	)
       UpperCamelCase__    :			str      				=      model(**self._prepare_for_class(__lowercase							,		__lowercase	)	)

       UpperCamelCase__    :			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(__lowercase	)							,		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__    :			Optional[Any]      				=      self.model_tester.prepare_config_and_inputs_for_common()
      UpperCamelCase__    :			Optional[Any]      				=      ["""basic""", """bottleneck"""]
      for model_class in self.all_model_classes:
       for layer_type in layers_type:
        UpperCamelCase__    :			Optional[Any]      				=      layer_type
        UpperCamelCase__    :			Tuple      				=      True
        check_hidden_states_output(__lowercase							,		__lowercase							,		__lowercase	)

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

        check_hidden_states_output(__lowercase							,		__lowercase							,		__lowercase	)


     def    UpperCAmelCase__		(					self							:   Dict	)     ->					int:





      '''simple docstring'''






      UpperCamelCase__    :			int      				=      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__lowercase	)


     @slow
     def    UpperCAmelCase__		(					self							:   Optional[int]	)     ->					Tuple:





      '''simple docstring'''






      for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       UpperCamelCase__    :			int      				=      TFResNetModel.from_pretrained(__lowercase	)
       self.assertIsNotNone(__lowercase	)



def 	_a     ( ):







 """simple docstring"""



 UpperCamelCase__    :			int      				=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
 return image






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


     @cached_property
     def    UpperCAmelCase__		(					self							:   str	)     ->					List[str]:





      '''simple docstring'''






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


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





      '''simple docstring'''






      UpperCamelCase__    :			int      				=      TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)

      UpperCamelCase__    :			Dict      				=      self.default_image_processor
      UpperCamelCase__    :			str      				=      prepare_img()
      UpperCamelCase__    :			Optional[Any]      				=      image_processor(images=__lowercase							,		return_tensors='''tf'''	)

      # forward pass
      UpperCamelCase__    :			Optional[Any]      				=      model(**__lowercase	)

      # verify the logits
      UpperCamelCase__    :			Optional[int]      				=      tf.TensorShape((1, 1000)	)
      self.assertEqual(outputs.logits.shape							,		__lowercase	)

      UpperCamelCase__    :			Optional[int]      				=      tf.constant([-11.1069, -9.7877, -8.3777]	)

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










import warnings
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


a		:       List[Any]			     = logging.get_logger(__name__)

a		:       List[Any]			     = {
    "nvidia/segformer-b0-finetuned-ade-512-512": (
        "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json"
    ),
    # See all SegFormer models at https://huggingface.co/models?filter=segformer
}
class     a    ( lowercase__   ):



      """simple docstring"""


      a  : int							       =	'segformer'
      def __init__(      self					:			Dict		,      __lowercase					:			str=3		,      __lowercase					:			Dict=4		,      __lowercase					:			Any=[2, 2, 2, 2]		,      __lowercase					:			Optional[int]=[8, 4, 2, 1]		,      __lowercase					:			List[str]=[32, 64, 160, 256]		,      __lowercase					:			Union[str, Any]=[7, 3, 3, 3]		,      __lowercase					:			Optional[int]=[4, 2, 2, 2]		,      __lowercase					:			Any=[1, 2, 5, 8]		,      __lowercase					:			List[str]=[4, 4, 4, 4]		,      __lowercase					:			Any="gelu"		,      __lowercase					:			Optional[int]=0.0		,      __lowercase					:			Dict=0.0		,      __lowercase					:			Optional[Any]=0.1		,      __lowercase					:			int=0.02		,      __lowercase					:			Optional[int]=0.1		,      __lowercase					:			Optional[Any]=1e-6		,      __lowercase					:			Tuple=256		,      __lowercase					:			List[Any]=255		,      **__lowercase					:			Union[str, Any]		,      )							->      List[Any]:
        super().__init__(**__lowercase					)

        if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
          warnings.warn(
              """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be"""
              """ removed, as the behaviour will default to that of reshape_last_stage = True."""		,      __lowercase		,      )

        __UpperCAmelCase							:	Tuple           =  num_channels
        __UpperCAmelCase							:	Any           =  num_encoder_blocks
        __UpperCAmelCase							:	List[Any]           =  depths
        __UpperCAmelCase							:	Dict           =  sr_ratios
        __UpperCAmelCase							:	int           =  hidden_sizes
        __UpperCAmelCase							:	Optional[Any]           =  patch_sizes
        __UpperCAmelCase							:	List[Any]           =  strides
        __UpperCAmelCase							:	List[str]           =  mlp_ratios
        __UpperCAmelCase							:	Tuple           =  num_attention_heads
        __UpperCAmelCase							:	List[str]           =  hidden_act
        __UpperCAmelCase							:	Tuple           =  hidden_dropout_prob
        __UpperCAmelCase							:	Dict           =  attention_probs_dropout_prob
        __UpperCAmelCase							:	Any           =  classifier_dropout_prob
        __UpperCAmelCase							:	Optional[int]           =  initializer_range
        __UpperCAmelCase							:	Optional[Any]           =  drop_path_rate
        __UpperCAmelCase							:	int           =  layer_norm_eps
        __UpperCAmelCase							:	Dict           =  decoder_hidden_size
        __UpperCAmelCase							:	Tuple           =  kwargs.get("""reshape_last_stage"""		,      __lowercase					)
        __UpperCAmelCase							:	int           =  semantic_loss_ignore_index


class     a    ( lowercase__   ):



      """simple docstring"""


      a  : Union[str, Any]							       =	version.parse('1.11'   )
      @property
      def 	UpperCAmelCase      (      self					:			Union[str, Any]					)							->      Mapping[str, Mapping[int, str]]:
        return OrderedDict(
            [
                ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
            ]					)
      @property
      def 	UpperCAmelCase      (      self					:			Optional[Any]					)							->      float:
        return 1e-4




      @property
      def 	UpperCAmelCase      (      self					:			str					)							->      int:
        return 12


