
"""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      _UpperCAmelCase							:




      def __init__(							self   ,       lowercase_   ,       lowercase_=1_3   ,       lowercase_=3_2   ,       lowercase_=3   ,       lowercase_=4   ,       lowercase_=[1_0, 2_0, 3_0, 4_0]   ,       lowercase_=[2, 2, 3, 2]   ,       lowercase_=True   ,       lowercase_=True   ,       lowercase_=3_7   ,       lowercase_="gelu"   ,       lowercase_=1_0   ,       lowercase_=0.0_2   ,       lowercase_=["stage2", "stage3", "stage4"]   ,       lowercase_=3   ,       lowercase_=None   ,       )						->					List[Any]:
          UpperCAmelCase									=					parent
          UpperCAmelCase									=					batch_size
          UpperCAmelCase									=					image_size
          UpperCAmelCase									=					num_channels
          UpperCAmelCase									=					num_stages
          UpperCAmelCase									=					hidden_sizes
          UpperCAmelCase									=					depths
          UpperCAmelCase									=					is_training
          UpperCAmelCase									=					use_labels
          UpperCAmelCase									=					intermediate_size
          UpperCAmelCase									=					hidden_act
          UpperCAmelCase									=					type_sequence_label_size
          UpperCAmelCase									=					initializer_range
          UpperCAmelCase									=					out_features
          UpperCAmelCase									=					num_labels
          UpperCAmelCase									=					scope
          UpperCAmelCase									=					num_stages




      def     a_      (							self							)						->					str:
          UpperCAmelCase									=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

          UpperCAmelCase									=					self.get_config()

          return config, pixel_values, labels




      def     a_      (							self							)						->					Tuple:
          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							)						->					List[str]:
          return UperNetConfig(
              backbone_config=self.get_backbone_config()   ,       hidden_size=5_1_2   ,       pool_scales=[1, 2, 3, 6]   ,       use_auxiliary_head=lowercase_   ,       auxiliary_loss_weight=0.4   ,       auxiliary_in_channels=4_0   ,       auxiliary_channels=2_5_6   ,       auxiliary_num_convs=1   ,       auxiliary_concat_input=lowercase_   ,       loss_ignore_index=2_5_5   ,       num_labels=self.num_labels   ,       )




      def     a_      (							self   ,       lowercase_   ,       lowercase_   ,       lowercase_							)						->					List[Any]:
          UpperCAmelCase									=					UperNetForSemanticSegmentation(config=lowercase_							)
          model.to(lowercase_							)
          model.eval()
          UpperCAmelCase									=					model(lowercase_							)
          self.parent.assertEqual(
              result.logits.shape   ,       (self.batch_size, self.num_labels, self.image_size, self.image_size)							)




      def     a_      (							self							)						->					Any:
          UpperCAmelCase									=					self.prepare_config_and_inputs()
          (
              (
              UpperCAmelCase
          )			,							(
              UpperCAmelCase
          )			,							(
              UpperCAmelCase
          )			,							
          )									=					config_and_inputs
          UpperCAmelCase									=					{'pixel_values': pixel_values}
          return config, inputs_dict

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




      def     a_      (							self							)						->					Any:
          UpperCAmelCase									=					UperNetModelTester(self							)
          UpperCAmelCase									=					ConfigTester(self   ,       config_class=lowercase_   ,       has_text_modality=lowercase_   ,       hidden_size=3_7							)




      def     a_      (							self							)						->					Union[str, Any]:
          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							)						->					str:
          return




      def     a_      (							self							)						->					Optional[Any]:
          UpperCAmelCase			,							UpperCAmelCase									=					self.model_tester.prepare_config_and_inputs_for_common()

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

              UpperCAmelCase									=					['pixel_values']
              self.assertListEqual(arg_names[:1]   ,       lowercase_							)




      def     a_      (							self							)						->					Optional[int]:
          UpperCAmelCase									=					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]:
          pass




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




      @unittest.skip(reason='UperNet does not have a base model'							)
      def     a_      (							self							)						->					List[str]:
          pass




      @unittest.skip(reason='UperNet does not have a base model'							)
      def     a_      (							self							)						->					Any:
          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[str]:
          pass




      @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'							)
      def     a_      (							self							)						->					Optional[Any]:
          pass




      def     a_      (							self							)						->					Optional[int]:
          def check_hidden_states_output(lowercase_   ,       lowercase_   ,       lowercase_							):
              UpperCAmelCase									=					model_class(lowercase_							)
              model.to(lowercase_							)
              model.eval()

              with torch.no_grad():
                  UpperCAmelCase									=					model(**self._prepare_for_class(lowercase_   ,       lowercase_							)							)

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

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

          UpperCAmelCase			,							UpperCAmelCase									=					self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              UpperCAmelCase									=					True
              check_hidden_states_output(lowercase_   ,       lowercase_   ,       lowercase_							)

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

              check_hidden_states_output(lowercase_   ,       lowercase_   ,       lowercase_							)




      def     a_      (							self							)						->					List[str]:
          UpperCAmelCase			,							UpperCAmelCase									=					self.model_tester.prepare_config_and_inputs_for_common()

          UpperCAmelCase									=					_config_zero_init(lowercase_							)
          UpperCAmelCase									=					_config_zero_init(configs_no_init.backbone_config							)
          for model_class in self.all_model_classes:
              UpperCAmelCase									=					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							)						->					int:
          pass




      @slow
      def     a_      (							self							)						->					str:
          for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase									=					UperNetForSemanticSegmentation.from_pretrained(lowercase_							)
              self.assertIsNotNone(lowercase_							)




def     lowercase__						(					) ->      Tuple:






    """simple docstring"""




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







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




      def     a_      (							self							)						->					Any:
          UpperCAmelCase									=					AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'							)
          UpperCAmelCase									=					UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'							).to(lowercase_							)

          UpperCAmelCase									=					prepare_img()
          UpperCAmelCase									=					processor(images=lowercase_   ,       return_tensors='pt'							).to(lowercase_							)

          with torch.no_grad():
              UpperCAmelCase									=					model(**lowercase_							)

          UpperCAmelCase									=					torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)							)
          self.assertEqual(outputs.logits.shape   ,       lowercase_							)

          UpperCAmelCase									=					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(lowercase_							)
          self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]   ,       lowercase_   ,       atol=1E-4							)							)




      def     a_      (							self							)						->					Union[str, Any]:
          UpperCAmelCase									=					AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny'							)
          UpperCAmelCase									=					UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny'							).to(lowercase_							)

          UpperCAmelCase									=					prepare_img()
          UpperCAmelCase									=					processor(images=lowercase_   ,       return_tensors='pt'							).to(lowercase_							)

          with torch.no_grad():
              UpperCAmelCase									=					model(**lowercase_							)

          UpperCAmelCase									=					torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)							)
          self.assertEqual(outputs.logits.shape   ,       lowercase_							)

          UpperCAmelCase									=					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(lowercase_							)
          self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]   ,       lowercase_   ,       atol=1E-4							)							)





"""simple docstring"""

def     lowercase__						(					lowerCAmelCase				:					int ,				lowerCAmelCase				:					int ) ->      int:






    """simple docstring"""




    return number | (1 << position)




def     lowercase__						(					lowerCAmelCase				:					int ,				lowerCAmelCase				:					int ) ->      int:






    """simple docstring"""




    return number & ~(1 << position)




def     lowercase__						(					lowerCAmelCase				:					int ,				lowerCAmelCase				:					int ) ->      int:






    """simple docstring"""




    return number ^ (1 << position)




def     lowercase__						(					lowerCAmelCase				:					int ,				lowerCAmelCase				:					int ) ->      bool:






    """simple docstring"""




    return ((number >> position) & 1) == 1




def     lowercase__						(					lowerCAmelCase				:					int ,				lowerCAmelCase				:					int ) ->      int:






    """simple docstring"""




    return int((number & (1 << position)) != 0 )


if __name__ == "__main__":
   import doctest

   doctest.testmod()



