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




   def __init__(    self			:				Union[str, Any]       ,	_lowercase			:				Optional[Any]       ,	_lowercase			:				Union[str, Any]=13       ,	_lowercase			:				Union[str, Any]=32       ,	_lowercase			:				str=3       ,	_lowercase			:				int=4       ,	_lowercase			:				Union[str, Any]=[10, 20, 30, 40]       ,	_lowercase			:				Union[str, Any]=[2, 2, 3, 2]       ,	_lowercase			:				Tuple=True       ,	_lowercase			:				Optional[int]=True       ,	_lowercase			:				Optional[Any]=37       ,	_lowercase			:				Optional[Any]="gelu"       ,	_lowercase			:				str=10       ,	_lowercase			:				str=0.02       ,	_lowercase			:				int=["stage2", "stage3", "stage4"]       ,	_lowercase			:				Tuple=3       ,	_lowercase			:				int=None       ,	):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__										=      parent
     SCREAMING_SNAKE_CASE__										=      batch_size
     SCREAMING_SNAKE_CASE__										=      image_size
     SCREAMING_SNAKE_CASE__										=      num_channels
     SCREAMING_SNAKE_CASE__										=      num_stages
     SCREAMING_SNAKE_CASE__										=      hidden_sizes
     SCREAMING_SNAKE_CASE__										=      depths
     SCREAMING_SNAKE_CASE__										=      is_training
     SCREAMING_SNAKE_CASE__										=      use_labels
     SCREAMING_SNAKE_CASE__										=      intermediate_size
     SCREAMING_SNAKE_CASE__										=      hidden_act
     SCREAMING_SNAKE_CASE__										=      type_sequence_label_size
     SCREAMING_SNAKE_CASE__										=      initializer_range
     SCREAMING_SNAKE_CASE__										=      out_features
     SCREAMING_SNAKE_CASE__										=      num_labels
     SCREAMING_SNAKE_CASE__										=      scope
     SCREAMING_SNAKE_CASE__										=      num_stages




   def 	__a						(    self			:				List[str]      ):



     """simple docstring"""






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

     SCREAMING_SNAKE_CASE__										=      None
     if self.use_labels:
       SCREAMING_SNAKE_CASE__										=      ids_tensor([self.batch_size]       ,	self.type_sequence_label_size      )

     SCREAMING_SNAKE_CASE__										=      self.get_config()

     return config, pixel_values, labels




   def 	__a						(    self			:				str      ):



     """simple docstring"""






     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 	__a						(    self			:				Optional[int]      ):



     """simple docstring"""






     return UperNetConfig(
         backbone_config=self.get_backbone_config()       ,	hidden_size=5_12       ,	pool_scales=[1, 2, 3, 6]       ,	use_auxiliary_head=_lowercase       ,	auxiliary_loss_weight=0.4       ,	auxiliary_in_channels=40       ,	auxiliary_channels=2_56       ,	auxiliary_num_convs=1       ,	auxiliary_concat_input=_lowercase       ,	loss_ignore_index=2_55       ,	num_labels=self.num_labels       ,	)




   def 	__a						(    self			:				int       ,	_lowercase			:				int       ,	_lowercase			:				int       ,	_lowercase			:				str      ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__										=      UperNetForSemanticSegmentation(config=_lowercase      )
     model.to(_lowercase      )
     model.eval()
     SCREAMING_SNAKE_CASE__										=      model(_lowercase      )
     self.parent.assertEqual(
         result.logits.shape       ,	(self.batch_size, self.num_labels, self.image_size, self.image_size)      )




   def 	__a						(    self			:				Optional[int]      ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__										=      self.prepare_config_and_inputs()
     (
         (
         SCREAMING_SNAKE_CASE__
     )							,     (
         SCREAMING_SNAKE_CASE__
     )							,     (
         SCREAMING_SNAKE_CASE__
     )							,     
     )										=      config_and_inputs
     SCREAMING_SNAKE_CASE__										=      {"""pixel_values""": pixel_values}
     return config, inputs_dict







@require_torch
class __snake_case				(						lowerCamelCase_   ,		lowerCamelCase_   ,		unittest.TestCase		):
   lowerCAmelCase_														=							(UperNetForSemanticSegmentation,) if is_torch_available() else ()
   lowerCAmelCase_														=							{"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {}
   lowerCAmelCase_														=							False
   lowerCAmelCase_														=							False
   lowerCAmelCase_														=							False
   lowerCAmelCase_														=							False
   lowerCAmelCase_														=							False
   lowerCAmelCase_														=							False




   def 	__a						(    self			:				List[Any]      ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__										=      UperNetModelTester(self      )
     SCREAMING_SNAKE_CASE__										=      ConfigTester(self       ,	config_class=_lowercase       ,	has_text_modality=_lowercase       ,	hidden_size=37      )




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



     """simple docstring"""






     return




   def 	__a						(    self			:				Union[str, Any]      ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__							,     SCREAMING_SNAKE_CASE__										=      self.model_tester.prepare_config_and_inputs_for_common()

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

       SCREAMING_SNAKE_CASE__										=      ["""pixel_values"""]
       self.assertListEqual(arg_names[:1]       ,	_lowercase      )




   def 	__a						(    self			:				str      ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__										=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_semantic_segmentation(*_lowercase      )




   @unittest.skip(reason="""UperNet does not use inputs_embeds"""      )
   def 	__a						(    self			:				Optional[Any]      ):



     """simple docstring"""






     pass




   @unittest.skip(reason="""UperNet does not support input and output embeddings"""      )
   def 	__a						(    self			:				Tuple      ):



     """simple docstring"""






     pass




   @unittest.skip(reason="""UperNet does not have a base model"""      )
   def 	__a						(    self			:				Any      ):



     """simple docstring"""






     pass




   @unittest.skip(reason="""UperNet does not have a base model"""      )
   def 	__a						(    self			:				Union[str, Any]      ):



     """simple docstring"""






     pass




   @require_torch_multi_gpu
   @unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""      )
   def 	__a						(    self			:				List[Any]      ):



     """simple docstring"""






     pass




   @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""      )
   def 	__a						(    self			:				Tuple      ):



     """simple docstring"""






     pass




   def 	__a						(    self			:				str      ):



     """simple docstring"""






     def check_hidden_states_output(_lowercase			:				Dict       ,	_lowercase			:				Any       ,	_lowercase			:				Optional[Any]      ):
       SCREAMING_SNAKE_CASE__										=      model_class(_lowercase      )
       model.to(_lowercase      )
       model.eval()

       with torch.no_grad():
         SCREAMING_SNAKE_CASE__										=      model(**self._prepare_for_class(_lowercase       ,	_lowercase      )      )

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

       SCREAMING_SNAKE_CASE__										=      self.model_tester.num_stages
       self.assertEqual(len(_lowercase      )       ,	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]       ,	)

     SCREAMING_SNAKE_CASE__							,     SCREAMING_SNAKE_CASE__										=      self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
       SCREAMING_SNAKE_CASE__										=      True
       check_hidden_states_output(_lowercase       ,	_lowercase       ,	_lowercase      )

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

       check_hidden_states_output(_lowercase       ,	_lowercase       ,	_lowercase      )




   def 	__a						(    self			:				int      ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__							,     SCREAMING_SNAKE_CASE__										=      self.model_tester.prepare_config_and_inputs_for_common()

     SCREAMING_SNAKE_CASE__										=      _config_zero_init(_lowercase      )
     SCREAMING_SNAKE_CASE__										=      _config_zero_init(configs_no_init.backbone_config      )
     for model_class in self.all_model_classes:
       SCREAMING_SNAKE_CASE__										=      model_class(config=_lowercase      )
       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 	__a						(    self			:				List[str]      ):



     """simple docstring"""






     pass




   @slow
   def 	__a						(    self			:				Any      ):



     """simple docstring"""






     for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       SCREAMING_SNAKE_CASE__										=      UperNetForSemanticSegmentation.from_pretrained(_lowercase      )
       self.assertIsNotNone(_lowercase      )





def 	__SCREAMING_SNAKE_CASE  (					)							->					Optional[int]:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__										=      hf_hub_download(
      repo_id="""hf-internal-testing/fixtures_ade20k""" ,     repo_type="""dataset""" ,     filename="""ADE_val_00000001.jpg"""	)
  SCREAMING_SNAKE_CASE__										=      Image.open(__UpperCamelCase	).convert("""RGB"""	)
  return image







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




   def 	__a						(    self			:				Tuple      ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__										=      AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny"""      )
     SCREAMING_SNAKE_CASE__										=      UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny"""      ).to(_lowercase      )

     SCREAMING_SNAKE_CASE__										=      prepare_img()
     SCREAMING_SNAKE_CASE__										=      processor(images=_lowercase       ,	return_tensors="""pt"""      ).to(_lowercase      )

     with torch.no_grad():
       SCREAMING_SNAKE_CASE__										=      model(**_lowercase      )

     SCREAMING_SNAKE_CASE__										=      torch.Size((1, model.config.num_labels, 5_12, 5_12)      )
     self.assertEqual(outputs.logits.shape       ,	_lowercase      )

     SCREAMING_SNAKE_CASE__										=      torch.tensor(
         [[-7.59_58, -7.59_58, -7.43_02], [-7.59_58, -7.59_58, -7.43_02], [-7.47_97, -7.47_97, -7.30_68]]      ).to(_lowercase      )
     self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]       ,	_lowercase       ,	atol=1E-4      )      )




   def 	__a						(    self			:				str      ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__										=      AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny"""      )
     SCREAMING_SNAKE_CASE__										=      UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny"""      ).to(_lowercase      )

     SCREAMING_SNAKE_CASE__										=      prepare_img()
     SCREAMING_SNAKE_CASE__										=      processor(images=_lowercase       ,	return_tensors="""pt"""      ).to(_lowercase      )

     with torch.no_grad():
       SCREAMING_SNAKE_CASE__										=      model(**_lowercase      )

     SCREAMING_SNAKE_CASE__										=      torch.Size((1, model.config.num_labels, 5_12, 5_12)      )
     self.assertEqual(outputs.logits.shape       ,	_lowercase      )

     SCREAMING_SNAKE_CASE__										=      torch.tensor(
         [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]]      ).to(_lowercase      )
     self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]       ,	_lowercase       ,	atol=1E-4      )      )

def 	__SCREAMING_SNAKE_CASE  (					__UpperCamelCase    :       int ,     __UpperCamelCase    :       int	)							->					str:







  """simple docstring"""





  if a < 0 or b < 0:
    raise ValueError("""the value of both inputs must be positive"""	)

  SCREAMING_SNAKE_CASE__										=      str(bin(__UpperCamelCase	)	)[2:]  # remove the leading "0b"
  SCREAMING_SNAKE_CASE__										=      str(bin(__UpperCamelCase	)	)[2:]  # remove the leading "0b"

  SCREAMING_SNAKE_CASE__										=      max(len(__UpperCamelCase	) ,     len(__UpperCamelCase	)	)

  return "0b" + "".join(
      str(int(char_a != char_b	)	)
      for char_a, char_b in zip(a_binary.zfill(__UpperCamelCase	) ,     b_binary.zfill(__UpperCamelCase	)	)	)


if __name__ == "__main__":
   import doctest

   doctest.testmod()
