
"""simple docstring"""



import inspect
import unittest

from huggingface_hub import hf_hub_download

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

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 transformers import UperNetForSemanticSegmentation
    from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor





class 				a			:



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



      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      Union[str, Any]     							=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

          UpperCAmelCase__	:      Any     							=					None
          if self.use_labels:
              UpperCAmelCase__	:      Dict     							=					ids_tensor([self.batch_size]     ,	self.type_sequence_label_size      )

          UpperCAmelCase__	:      Tuple     							=					self.get_config()

          return config, pixel_values, labels



      def  __snake_case							(   self      ):
          return ConvNextConfig(
              num_channels=self.num_channels     ,	num_stages=self.num_stages     ,	hidden_sizes=self.hidden_sizes     ,	depths=self.depths     ,	is_training=self.is_training     ,	intermediate_size=self.intermediate_size     ,	hidden_act=self.hidden_act     ,	out_features=self.out_features     ,	)



      def  __snake_case							(   self      ):
          return UperNetConfig(
              backbone_config=self.get_backbone_config()     ,	hidden_size=512     ,	pool_scales=[1, 2, 3, 6]     ,	use_auxiliary_head=A_     ,	auxiliary_loss_weight=0.4     ,	auxiliary_in_channels=40     ,	auxiliary_channels=256     ,	auxiliary_num_convs=1     ,	auxiliary_concat_input=A_     ,	loss_ignore_index=255     ,	num_labels=self.num_labels     ,	)



      def  __snake_case							(   self     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_      ):
          UpperCAmelCase__	:      List[str]     							=					UperNetForSemanticSegmentation(config=A_      )
          model.to(A_      )
          model.eval()
          UpperCAmelCase__	:      int     							=					model(A_      )
          self.parent.assertEqual(
              result.logits.shape     ,	(self.batch_size, self.num_labels, self.image_size, self.image_size)      )



      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      Optional[int]     							=					self.prepare_config_and_inputs()
          (
              UpperCAmelCase__					
          )	:      Tuple     							=					config_and_inputs
          UpperCAmelCase__	:      str     							=					{'''pixel_values''': pixel_values}
          return config, inputs_dict





@require_torch
class 				a			(					SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__						,		unittest.TestCase      ):
      UpperCamelCase							:   str           =     (UperNetForSemanticSegmentation,) if is_torch_available() else ()
      UpperCamelCase							:   Union[str, Any]           =     {"""image-segmentation""": UperNetForSemanticSegmentation} if is_torch_available() else {}
      UpperCamelCase							:   Dict           =     False
      UpperCamelCase							:   Dict           =     False
      UpperCamelCase							:   Optional[Any]           =     False
      UpperCamelCase							:   Tuple           =     False
      UpperCamelCase							:   Any           =     False
      UpperCamelCase							:   int           =     False



      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      List[Any]     							=					UperNetModelTester(self      )
          UpperCAmelCase__	:      Optional[Any]     							=					ConfigTester(self     ,	config_class=A_     ,	has_text_modality=A_     ,	hidden_size=37      )



      def  __snake_case							(   self      ):
          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      ):
          return



      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      Union[str, Any]     							=					self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              UpperCAmelCase__	:      Optional[Any]     							=					model_class(A_      )
              UpperCAmelCase__	:      int     							=					inspect.signature(model.forward      )
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              UpperCAmelCase__	:      Dict     							=					[*signature.parameters.keys()]

              UpperCAmelCase__	:      int     							=					['''pixel_values''']
              self.assertListEqual(arg_names[:1]     ,	A_      )



      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      List[str]     							=					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*A_      )



      @unittest.skip(reason='UperNet does not use inputs_embeds'      )
      def  __snake_case							(   self      ):
          pass



      @unittest.skip(reason='UperNet does not support input and output embeddings'      )
      def  __snake_case							(   self      ):
          pass



      @unittest.skip(reason='UperNet does not have a base model'      )
      def  __snake_case							(   self      ):
          pass



      @unittest.skip(reason='UperNet does not have a base model'      )
      def  __snake_case							(   self      ):
          pass



      @require_torch_multi_gpu
      @unittest.skip(reason='UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'      )
      def  __snake_case							(   self      ):
          pass



      @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'      )
      def  __snake_case							(   self      ):
          pass



      def  __snake_case							(   self      ):




          def check_hidden_states_output(UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_      ):
              UpperCAmelCase__	:      Dict     							=					model_class(A_      )
              model.to(A_      )
              model.eval()

              with torch.no_grad():
                  UpperCAmelCase__	:      List[str]     							=					model(**self._prepare_for_class(A_     ,	A_      )      )

              UpperCAmelCase__	:      Tuple     							=					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              UpperCAmelCase__	:      Union[str, Any]     							=					self.model_tester.num_stages
              self.assertEqual(len(A_      )     ,	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]     ,	)

          UpperCAmelCase__	:      Dict     							=					self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              UpperCAmelCase__	:      Optional[int]     							=					True
              check_hidden_states_output(A_     ,	A_     ,	A_      )

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              UpperCAmelCase__	:      Union[str, Any]     							=					True

              check_hidden_states_output(A_     ,	A_     ,	A_      )



      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      Any     							=					self.model_tester.prepare_config_and_inputs_for_common()

          UpperCAmelCase__	:      int     							=					_config_zero_init(A_      )
          UpperCAmelCase__	:      Optional[Any]     							=					_config_zero_init(configs_no_init.backbone_config      )
          for model_class in self.all_model_classes:
              UpperCAmelCase__	:      Any     							=					model_class(config=A_      )
              for name, param in model.named_parameters():
                  if param.requires_grad:
                      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(reason='UperNet does not have tied weights'      )
      def  __snake_case							(   self      ):
          pass



      @slow
      def  __snake_case							(   self      ):




          for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase__	:      Union[str, Any]     							=					UperNetForSemanticSegmentation.from_pretrained(A_      )
              self.assertIsNotNone(A_      )




def 					lowerCamelCase   (     ):
    UpperCAmelCase__	:      List[str]     							=					hf_hub_download(
        repo_id='hf-internal-testing/fixtures_ade20k'    ,repo_type='dataset'    ,filename='ADE_val_00000001.jpg' )
    UpperCAmelCase__	:      Optional[int]     							=					Image.open(_UpperCamelCase ).convert('RGB' )
    return image





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



      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      Optional[Any]     							=					AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'      )
          UpperCAmelCase__	:      Optional[Any]     							=					UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'      ).to(A_      )

          UpperCAmelCase__	:      List[Any]     							=					prepare_img()
          UpperCAmelCase__	:      Any     							=					processor(images=A_     ,	return_tensors='pt'      ).to(A_      )

          with torch.no_grad():
              UpperCAmelCase__	:      str     							=					model(**A_      )

          UpperCAmelCase__	:      Union[str, Any]     							=					torch.Size((1, model.config.num_labels, 512, 512)      )
          self.assertEqual(outputs.logits.shape     ,	A_      )

          UpperCAmelCase__	:      Optional[Any]     							=					torch.tensor(
              [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]      ).to(A_      )
          self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]     ,	A_     ,	atol=1E-4      )      )



      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      Tuple     							=					AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny'      )
          UpperCAmelCase__	:      str     							=					UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny'      ).to(A_      )

          UpperCAmelCase__	:      Union[str, Any]     							=					prepare_img()
          UpperCAmelCase__	:      Optional[Any]     							=					processor(images=A_     ,	return_tensors='pt'      ).to(A_      )

          with torch.no_grad():
              UpperCAmelCase__	:      str     							=					model(**A_      )

          UpperCAmelCase__	:      Optional[Any]     							=					torch.Size((1, model.config.num_labels, 512, 512)      )
          self.assertEqual(outputs.logits.shape     ,	A_      )

          UpperCAmelCase__	:      Tuple     							=					torch.tensor(
              [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]      ).to(A_      )
          self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]     ,	A_     ,	atol=1E-4      )      )



"""simple docstring"""




import functools
import logging
import os
import sys
import threading
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib


A__ :       int				= threading.Lock()
A__ :       Optional[logging.Handler]				= None

A__ :       str				= {
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'error': logging.ERROR,
    'critical': logging.CRITICAL,
}

A__ :       str				= logging.WARNING

A__ :       Union[str, Any]				= True




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:      List[Any]   			=  os.getenv('''TRANSFORMERS_VERBOSITY'''			,					_UpperCamelCase    )
  if env_level_str:
    if env_level_str in log_levels:
      return log_levels[env_level_str]
    else:
      logging.getLogger().warning(
          f'''Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, '''
          f'''has to be one of: { ", ".join(log_levels.keys()    ) }'''    )
  return _default_log_level




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return __name__.split('''.'''    )[0]




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return logging.getLogger(_get_library_name()    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  global _default_handler

  with _lock:
    if _default_handler:
      # This library has already configured the library root logger.
      return
    _lowercase:      int   			=  logging.StreamHandler()  # Set sys.stderr as stream.
    _lowercase:      Dict   			=  sys.stderr.flush

    # Apply our default configuration to the library root logger.
    _lowercase:      Dict   			=  _get_library_root_logger()
    library_root_logger.addHandler(_default_handler    )
    library_root_logger.setLevel(_get_default_logging_level()    )
    _lowercase:      Optional[Any]   			=  False




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  global _default_handler

  with _lock:
    if not _default_handler:
      return

    _lowercase:      Tuple   			=  _get_library_root_logger()
    library_root_logger.removeHandler(_default_handler    )
    library_root_logger.setLevel(logging.NOTSET    )
    _lowercase:      Dict   			=  None




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return log_levels




def 			_lowerCAmelCase		(		_UpperCamelCase = None    ):






  """simple docstring"""



  if name is None:
    _lowercase:      Tuple   			=  _get_library_name()

  _configure_library_root_logger()
  return logging.getLogger(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _configure_library_root_logger()
  return _get_library_root_logger().getEffectiveLevel()




def 			_lowerCAmelCase		(		_UpperCamelCase    ):






  """simple docstring"""



  _configure_library_root_logger()
  _get_library_root_logger().setLevel(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return set_verbosity(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return set_verbosity(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return set_verbosity(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return set_verbosity(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().removeHandler(_default_handler    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().addHandler(_default_handler    )




def 			_lowerCAmelCase		(		_UpperCamelCase    ):






  """simple docstring"""



  _configure_library_root_logger()

  assert handler is not None
  _get_library_root_logger().addHandler(_UpperCamelCase    )




def 			_lowerCAmelCase		(		_UpperCamelCase    ):






  """simple docstring"""



  _configure_library_root_logger()

  assert handler is not None and handler not in _get_library_root_logger().handlers
  _get_library_root_logger().removeHandler(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _configure_library_root_logger()
  _lowercase:      str   			=  False




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _configure_library_root_logger()
  _lowercase:      List[str]   			=  True




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:      Any   			=  _get_library_root_logger().handlers

  for handler in handlers:
    _lowercase:      int   			=  logging.Formatter('''[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s'''    )
    handler.setFormatter(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:      List[str]   			=  _get_library_root_logger().handlers

  for handler in handlers:
    handler.setFormatter(_UpperCamelCase    )




def 			_lowerCAmelCase		(		self			,					*_UpperCamelCase			,					**_UpperCamelCase    ):






  """simple docstring"""



  _lowercase:      Any   			=  os.getenv('''TRANSFORMERS_NO_ADVISORY_WARNINGS'''			,					_UpperCamelCase    )
  if no_advisory_warnings:
    return
  self.warning(*_UpperCamelCase			,					**_UpperCamelCase    )


A__ :       Optional[int]				= warning_advice




@functools.lru_cache(_UpperCamelCase    )
def 			_lowerCAmelCase		(		self			,					*_UpperCamelCase			,					**_UpperCamelCase    ):






  """simple docstring"""



  self.warning(*_UpperCamelCase			,					**_UpperCamelCase    )


A__ :       List[Any]				= warning_once


class       __magic_name__							:
       def __init__(  self			,					*A_			,					**A_							)  ->						Any:  # pylint: disable=unused-argument





         """simple docstring"""




         _lowercase:      Tuple   			=  args[0] if args else None
       def __iter__(  self							)  ->						Union[str, Any]:





         """simple docstring"""




         return iter(self._iterator							)
       def __getattr__(  self			,					A_							)  ->						List[Any]:





         """simple docstring"""




         def empty_fn(*A_			,					**A_							):  # pylint: disable=unused-argument
           return

         return empty_fn
       def __enter__(  self							)  ->						Tuple:





         """simple docstring"""




         return self



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





         """simple docstring"""




         return


class       __magic_name__							:
       def __call__(  self			,					*A_			,					**A_							)  ->						Dict:





         """simple docstring"""




         if _tqdm_active:
           return tqdm_lib.tqdm(*A_			,					**A_							)
         else:
           return EmptyTqdm(*A_			,					**A_							)
       def 				lowercase_				(  self			,					*A_			,					**A_							)  ->						List[str]:





         """simple docstring"""




         _lowercase:      Optional[Any]   			=  None
         if _tqdm_active:
           return tqdm_lib.tqdm.set_lock(*A_			,					**A_							)



       def 				lowercase_				(  self							)  ->						Optional[Any]:





         """simple docstring"""




         if _tqdm_active:
           return tqdm_lib.tqdm.get_lock()

A__ :       str				= _tqdm_cls()




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  global _tqdm_active
  return bool(_tqdm_active    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  global _tqdm_active
  _lowercase:      str   			=  True
  hf_hub_utils.enable_progress_bars()







def 			_lowerCAmelCase		(		):






  """simple docstring"""



  global _tqdm_active
  _lowercase:      Union[str, Any]   			=  False
  hf_hub_utils.disable_progress_bars()
