
import inspect
import unittest

from transformers import ConvNextConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
 import torch

 from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
 from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor


class 						__lowerCAmelCase	:



      """simple docstring"""







      def __init__(      self		:       Optional[Any]				,       _snake_case		:       Tuple				,       _snake_case		:       Tuple=13				,       _snake_case		:       Optional[Any]=32				,       _snake_case		:       Dict=3				,       _snake_case		:       Any=4				,       _snake_case		:       Optional[Any]=[10, 20, 30, 40]				,       _snake_case		:       Dict=[2, 2, 3, 2]				,       _snake_case		:       Union[str, Any]=True				,       _snake_case		:       List[str]=True				,       _snake_case		:       Optional[int]=37				,       _snake_case		:       str="gelu"				,       _snake_case		:       int=10				,       _snake_case		:       Optional[int]=0.02				,       _snake_case		:       Optional[int]=["stage2", "stage3", "stage4"]				,       _snake_case		:       Optional[Any]=[2, 3, 4]				,       _snake_case		:       Union[str, Any]=None				,       ):
          __lowercase		:			int	    =       parent
          __lowercase		:			Optional[Any]	    =       batch_size
          __lowercase		:			Optional[int]	    =       image_size
          __lowercase		:			Tuple	    =       num_channels
          __lowercase		:			int	    =       num_stages
          __lowercase		:			Optional[int]	    =       hidden_sizes
          __lowercase		:			List[Any]	    =       depths
          __lowercase		:			List[str]	    =       is_training
          __lowercase		:			Tuple	    =       use_labels
          __lowercase		:			List[str]	    =       intermediate_size
          __lowercase		:			str	    =       hidden_act
          __lowercase		:			Any	    =       num_labels
          __lowercase		:			Dict	    =       initializer_range
          __lowercase		:			Optional[int]	    =       out_features
          __lowercase		:			List[Any]	    =       out_indices
          __lowercase		:			List[str]	    =       scope




      def 		snake_case_			(      self		:       Optional[Any]				):
          __lowercase		:			Dict	    =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

          __lowercase		:			List[Any]	    =       self.get_config()
          return config, pixel_values, labels




      def 		snake_case_			(      self		:       List[Any]				):
          return ConvNextConfig(
              num_channels=self.num_channels				,       hidden_sizes=self.hidden_sizes				,       depths=self.depths				,       num_stages=self.num_stages				,       hidden_act=self.hidden_act				,       is_decoder=_snake_case				,       initializer_range=self.initializer_range				,       out_features=self.out_features				,       out_indices=self.out_indices				,       num_labels=self.num_labels				,       )




      def 		snake_case_			(      self		:       Optional[int]				,       _snake_case		:       Union[str, Any]				,       _snake_case		:       List[Any]				,       _snake_case		:       List[Any]				):
          __lowercase		:			List[str]	    =       ConvNextModel(config=_snake_case				)
          model.to(_snake_case				)
          model.eval()
          __lowercase		:			List[Any]	    =       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 		snake_case_			(      self		:       str				,       _snake_case		:       Tuple				,       _snake_case		:       List[str]				,       _snake_case		:       Union[str, Any]				):
          __lowercase		:			Any	    =       ConvNextForImageClassification(_snake_case				)
          model.to(_snake_case				)
          model.eval()
          __lowercase		:			str	    =       model(_snake_case				,       labels=_snake_case				)
          self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.num_labels)				)




      def 		snake_case_			(      self		:       Tuple				,       _snake_case		:       str				,       _snake_case		:       Optional[int]				,       _snake_case		:       Tuple				):
          __lowercase		:			Optional[Any]	    =       ConvNextBackbone(config=_snake_case				)
          model.to(_snake_case				)
          model.eval()
          __lowercase		:			Dict	    =       model(_snake_case				)

          # verify hidden states
          self.parent.assertEqual(len(result.feature_maps				)				,       len(config.out_features				)				)
          self.parent.assertListEqual(list(result.feature_maps[0].shape				)				,       [self.batch_size, self.hidden_sizes[1], 4, 4]				)

          # verify channels
          self.parent.assertEqual(len(model.channels				)				,       len(config.out_features				)				)
          self.parent.assertListEqual(model.channels				,       config.hidden_sizes[1:]				)

          # verify backbone works with out_features=None
          __lowercase		:			Tuple	    =       None
          __lowercase		:			List[Any]	    =       ConvNextBackbone(config=_snake_case				)
          model.to(_snake_case				)
          model.eval()
          __lowercase		:			Dict	    =       model(_snake_case				)

          # verify feature maps
          self.parent.assertEqual(len(result.feature_maps				)				,       1				)
          self.parent.assertListEqual(list(result.feature_maps[0].shape				)				,       [self.batch_size, self.hidden_sizes[-1], 1, 1]				)

          # verify channels
          self.parent.assertEqual(len(model.channels				)				,       1				)
          self.parent.assertListEqual(model.channels				,       [config.hidden_sizes[-1]]				)




      def 		snake_case_			(      self		:       Tuple				):
          __lowercase		:			Any	    =       self.prepare_config_and_inputs()
          __lowercase    ,      __lowercase    ,      __lowercase		:			List[Any]	    =       config_and_inputs
          __lowercase		:			Tuple	    =       {'''pixel_values''': pixel_values}
          return config, inputs_dict






@require_torch
class 						__lowerCAmelCase	(	lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase      ):



      """simple docstring"""







      A__	:			List[str]        =    (
          (
              ConvNextModel,
              ConvNextForImageClassification,
              ConvNextBackbone,
          )
          if is_torch_available()
          else ()
      )
      A__	:			Optional[Any]        =    (
          {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
          if is_torch_available()
          else {}
      )

      A__	:			Optional[Any]        =    True
      A__	:			Optional[int]        =    False
      A__	:			str        =    False
      A__	:			Dict        =    False
      A__	:			str        =    False




      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase		:			Optional[int]	    =       ConvNextModelTester(self				)
          __lowercase		:			Tuple	    =       ConfigTester(self				,       config_class=_snake_case				,       has_text_modality=_snake_case				,       hidden_size=37				)




      def 		snake_case_			(      self		:       Tuple				):
          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 		snake_case_			(      self		:       List[str]				):
          return




      @unittest.skip(reason='''ConvNext does not use inputs_embeds'''				)
      def 		snake_case_			(      self		:       Tuple				):
          pass




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




      @unittest.skip(reason='''ConvNext does not use feedforward chunking'''				)
      def 		snake_case_			(      self		:       Tuple				):
          pass




      def 		snake_case_			(      self		:       Dict				):
          __lowercase    ,      __lowercase		:			Tuple	    =       self.model_tester.prepare_config_and_inputs_for_common()

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

              __lowercase		:			Dict	    =       ['''pixel_values''']
              self.assertListEqual(arg_names[:1]				,       _snake_case				)




      def 		snake_case_			(      self		:       Optional[Any]				):
          __lowercase		:			int	    =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_snake_case				)




      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase		:			List[str]	    =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_backbone(*_snake_case				)




      def 		snake_case_			(      self		:       Optional[int]				):
          def check_hidden_states_output(_snake_case		:       Any				,       _snake_case		:       List[str]				,       _snake_case		:       str				):
              __lowercase		:			int	    =       model_class(_snake_case				)
              model.to(_snake_case				)
              model.eval()

              with torch.no_grad():
                  __lowercase		:			Optional[int]	    =       model(**self._prepare_for_class(_snake_case				,       _snake_case				)				)

              __lowercase		:			Dict	    =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              __lowercase		:			List[Any]	    =       self.model_tester.num_stages
              self.assertEqual(len(_snake_case				)				,       expected_num_stages + 1				)

              # ConvNext'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]				,       )

          __lowercase    ,      __lowercase		:			str	    =       self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              __lowercase		:			Any	    =       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"]
              __lowercase		:			Any	    =       True

              check_hidden_states_output(_snake_case				,       _snake_case				,       _snake_case				)




      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase		:			int	    =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_snake_case				)




      @slow
      def 		snake_case_			(      self		:       Optional[int]				):
          for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __lowercase		:			List[str]	    =       ConvNextModel.from_pretrained(_snake_case				)
              self.assertIsNotNone(_snake_case				)






def     UpperCAmelCase_  (						) ->						Tuple:
    __lowercase		:			str	    =       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
    return image


@require_torch
@require_vision
class 						__lowerCAmelCase	(	unittest.TestCase      ):



      """simple docstring"""







      @cached_property
      def 		snake_case_			(      self		:       int				):
          return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''				) if is_vision_available() else None




      @slow
      def 		snake_case_			(      self		:       Union[str, Any]				):
          __lowercase		:			Any	    =       ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''				).to(_snake_case				)

          __lowercase		:			Any	    =       self.default_image_processor
          __lowercase		:			Any	    =       prepare_img()
          __lowercase		:			Optional[int]	    =       image_processor(images=_snake_case				,       return_tensors='''pt'''				).to(_snake_case				)

          # forward pass
          with torch.no_grad():
              __lowercase		:			Tuple	    =       model(**_snake_case				)

          # verify the logits
          __lowercase		:			Dict	    =       torch.Size((1, 1000)				)
          self.assertEqual(outputs.logits.shape				,       _snake_case				)

          __lowercase		:			Optional[Any]	    =       torch.tensor([-0.02_60, -0.47_39, 0.19_11]				).to(_snake_case				)

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






@require_torch
class 						__lowerCAmelCase	(	unittest.TestCase , lowerCAmelCase_      ):



      """simple docstring"""







      A__	:			List[str]        =    (ConvNextBackbone,) if is_torch_available() else ()
      A__	:			int        =    ConvNextConfig

      A__	:			str        =    False




      def 		snake_case_			(      self		:       Tuple				):
          __lowercase		:			Any	    =       ConvNextModelTester(self				)




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


__lowerCAmelCase					:			Union[str, Any]			      =		logging.get_logger(__name__)

__lowerCAmelCase					:			Optional[int]			      =		{
    "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 						__lowerCAmelCase	(	lowerCAmelCase_      ):



      """simple docstring"""







      A__	:			Dict        =    '''segformer'''




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

          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.'''				,       _snake_case				,       )

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






class 						__lowerCAmelCase	(	lowerCAmelCase_      ):



      """simple docstring"""







      A__	:			Union[str, Any]        =    version.parse('''1.11'''      )




      @property
      def 		snake_case_			(      self		:       Dict				):
          return OrderedDict(
              [
                  ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
              ]				)




      @property
      def 		snake_case_			(      self		:       int				):
          return 1E-4




      @property
      def 		snake_case_			(      self		:       List[Any]				):
          return 12


