





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


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





         """simple docstring"""



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


      def    a (self       :      Optional[Any]      ):





         """simple docstring"""



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

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

         __snake_case							       =   self.get_config()

         return config, pixel_values, labels


      def    a (self       :      Any      ):





         """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[Any]      ):





         """simple docstring"""



         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    a (self       :      Tuple				,			a__       :      int				,			a__       :      Optional[int]				,			a__       :      Tuple      ):





         """simple docstring"""



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


      def    a (self       :      Optional[Any]      ):





         """simple docstring"""



         __snake_case							       =   self.prepare_config_and_inputs()
         (
             (
             __snake_case
         )       ,	(
             __snake_case
         )       ,	(
             __snake_case
         )       ,	
         )							       =   config_and_inputs
         __snake_case							       =   {'''pixel_values''': pixel_values}
         return config, inputs_dict






@require_torch
class 		SCREAMING_SNAKE_CASE__				(       _UpperCAmelCase						,      _UpperCAmelCase						,      unittest.TestCase  ):
      A_						:				int							=    (UperNetForSemanticSegmentation,) if is_torch_available() else ()
      A_						:				List[str]							=    {'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {}
      A_						:				int							=    False
      A_						:				int							=    False
      A_						:				Tuple							=    False
      A_						:				Any							=    False
      A_						:				Optional[Any]							=    False
      A_						:				Optional[Any]							=    False


      def    a (self       :      Dict      ):





         """simple docstring"""



         __snake_case							       =   UperNetModelTester(self      )
         __snake_case							       =   ConfigTester(self				,			config_class=a__				,			has_text_modality=a__				,			hidden_size=37      )


      def    a (self       :      Dict      ):





         """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       :      int      ):





         """simple docstring"""



         return


      def    a (self       :      List[str]      ):





         """simple docstring"""



         __snake_case       ,	__snake_case							       =   self.model_tester.prepare_config_and_inputs_for_common()

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

            __snake_case							       =   ['''pixel_values''']
            self.assertListEqual(arg_names[:1]				,			a__      )


      def    a (self       :      List[Any]      ):





         """simple docstring"""



         __snake_case							       =   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    a (self       :      Union[str, Any]      ):





         """simple docstring"""



         pass


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





         """simple docstring"""



         pass


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





         """simple docstring"""



         pass


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





         """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       :      Optional[Any]      ):





         """simple docstring"""



         pass


      @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''      )
      def    a (self       :      Optional[int]      ):





         """simple docstring"""



         pass


      def    a (self       :      Any      ):





         """simple docstring"""



         def check_hidden_states_output(a__       :      List[Any]				,			a__       :      List[str]				,			a__       :      int      ):
            __snake_case							       =   model_class(a__      )
            model.to(a__      )
            model.eval()

            with torch.no_grad():
               __snake_case							       =   model(**self._prepare_for_class(a__				,			a__      )      )

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

            __snake_case							       =   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]				,			)

         __snake_case       ,	__snake_case							       =   self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            __snake_case							       =   True
            check_hidden_states_output(a__				,			a__				,			a__      )

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

            check_hidden_states_output(a__				,			a__				,			a__      )


      def    a (self       :      Dict      ):





         """simple docstring"""



         __snake_case       ,	__snake_case							       =   self.model_tester.prepare_config_and_inputs_for_common()

         __snake_case							       =   _config_zero_init(a__      )
         __snake_case							       =   _config_zero_init(configs_no_init.backbone_config      )
         for model_class in self.all_model_classes:
            __snake_case							       =   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    a (self       :      Union[str, Any]      ):





         """simple docstring"""



         pass


      @slow
      def    a (self       :      int      ):





         """simple docstring"""



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






def lowerCamelCase__    (							)      ->				int:
   __snake_case							       =   hf_hub_download(
       repo_id='''hf-internal-testing/fixtures_ade20k'''       ,      repo_type='''dataset'''       ,      filename='''ADE_val_00000001.jpg'''       )
   __snake_case							       =   Image.open(snake_case_       ).convert('''RGB'''       )
   return image







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


      def    a (self       :      Optional[int]      ):





         """simple docstring"""



         __snake_case							       =   AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny'''      )
         __snake_case							       =   UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny'''      ).to(a__      )

         __snake_case							       =   prepare_img()
         __snake_case							       =   processor(images=a__				,			return_tensors='''pt'''      ).to(a__      )

         with torch.no_grad():
            __snake_case							       =   model(**a__      )

         __snake_case							       =   torch.Size((1, model.config.num_labels, 512, 512)      )
         self.assertEqual(outputs.logits.shape				,			a__      )

         __snake_case							       =   torch.tensor(
             [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]]      ).to(a__      )
         self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]				,			a__				,			atol=1E-4      )      )


      def    a (self       :      Tuple      ):





         """simple docstring"""



         __snake_case							       =   AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny'''      )
         __snake_case							       =   UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny'''      ).to(a__      )

         __snake_case							       =   prepare_img()
         __snake_case							       =   processor(images=a__				,			return_tensors='''pt'''      ).to(a__      )

         with torch.no_grad():
            __snake_case							       =   model(**a__      )

         __snake_case							       =   torch.Size((1, model.config.num_labels, 512, 512)      )
         self.assertEqual(outputs.logits.shape				,			a__      )

         __snake_case							       =   torch.tensor(
             [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]]      ).to(a__      )
         self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]				,			a__				,			atol=1E-4      )      )








def lowerCamelCase__    (							snake_case_	:  int       )      ->				int:
   if not isinstance(snake_case_       ,      snake_case_       ) or number < 0:
      raise ValueError('''Input must be a non-negative integer'''       )

   __snake_case							       =   0
   while number:
      # This way we arrive at next set bit (next 1) instead of looping
      # through each bit and checking for 1s hence the
      # loop won't run 32 times it will only run the number of `1` times
      number &= number - 1
      count += 1
   return count


if __name__ == "__main__":
    import doctest

    doctest.testmod()

