
'''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      :       Optional[Any],__A      :       Union[str, Any],__A      :       Optional[Any]=1_3,__A      :       Optional[Any]=3_2,__A      :       Union[str, Any]=3,__A      :       List[Any]=4,__A      :       List[str]=[1_0, 2_0, 3_0, 4_0],__A      :       Tuple=[2, 2, 3, 2],__A      :       int=True,__A      :       List[str]=True,__A      :       Dict=3_7,__A      :       Optional[int]="gelu",__A      :       Dict=1_0,__A      :       Optional[Any]=0.02,__A      :       Any=["stage2", "stage3", "stage4"],__A      :       List[Any]=3,__A      :       Any=None,):
          _lowerCamelCase				:   Any								=   parent
          _lowerCamelCase				:   Optional[int]								=   batch_size
          _lowerCamelCase				:   Dict								=   image_size
          _lowerCamelCase				:   List[str]								=   num_channels
          _lowerCamelCase				:   Tuple								=   num_stages
          _lowerCamelCase				:   Dict								=   hidden_sizes
          _lowerCamelCase				:   Dict								=   depths
          _lowerCamelCase				:   Dict								=   is_training
          _lowerCamelCase				:   Optional[int]								=   use_labels
          _lowerCamelCase				:   List[str]								=   intermediate_size
          _lowerCamelCase				:   List[str]								=   hidden_act
          _lowerCamelCase				:   Dict								=   type_sequence_label_size
          _lowerCamelCase				:   List[str]								=   initializer_range
          _lowerCamelCase				:   List[Any]								=   out_features
          _lowerCamelCase				:   int								=   num_labels
          _lowerCamelCase				:   Union[str, Any]								=   scope
          _lowerCamelCase				:   str								=   num_stages



    def   lowerCamelCase_  (	self      :       List[str]     ):
          _lowerCamelCase				:   str								=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

          _lowerCamelCase				:   List[str]								=   None
          if self.use_labels:
                _lowerCamelCase				:   List[Any]								=   ids_tensor([self.batch_size],self.type_sequence_label_size     )

          _lowerCamelCase				:   str								=   self.get_config()

          return config, pixel_values, labels



    def   lowerCamelCase_  (	self      :       Dict     ):
          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   lowerCamelCase_  (	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=__A,auxiliary_loss_weight=0.4,auxiliary_in_channels=4_0,auxiliary_channels=2_5_6,auxiliary_num_convs=1,auxiliary_concat_input=__A,loss_ignore_index=2_5_5,num_labels=self.num_labels,)



    def   lowerCamelCase_  (	self      :       Optional[int],__A      :       List[Any],__A      :       str,__A      :       List[Any]     ):
          _lowerCamelCase				:   Union[str, Any]								=   UperNetForSemanticSegmentation(config=__A     )
          model.to(__A     )
          model.eval()
          _lowerCamelCase				:   List[str]								=   model(__A     )
          self.parent.assertEqual(
              result.logits.shape,(self.batch_size, self.num_labels, self.image_size, self.image_size)     )



    def   lowerCamelCase_  (	self      :       List[str]     ):
          _lowerCamelCase				:   Tuple								=   self.prepare_config_and_inputs()
          (
              (
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		
          )				:   Union[str, Any]								=   config_and_inputs
          _lowerCamelCase				:   str								=   {"pixel_values": pixel_values}
          return config, inputs_dict


@require_torch
class  UpperCAmelCase__						(       A						,	A						,	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   lowerCamelCase_  (	self      :       int     ):
          _lowerCamelCase				:   int								=   UperNetModelTester(self     )
          _lowerCamelCase				:   str								=   ConfigTester(self,config_class=__A,has_text_modality=__A,hidden_size=3_7     )



    def   lowerCamelCase_  (	self      :       Dict     ):
          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   lowerCamelCase_  (	self      :       str     ):
          return



    def   lowerCamelCase_  (	self      :       int     ):
          _lowerCamelCase						,		_lowerCamelCase				:   Tuple								=   self.model_tester.prepare_config_and_inputs_for_common()

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

                _lowerCamelCase				:   Dict								=   ["pixel_values"]
                self.assertListEqual(arg_names[:1],__A     )



    def   lowerCamelCase_  (	self      :       Optional[int]     ):
          _lowerCamelCase				:   Optional[int]								=   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   lowerCamelCase_  (	self      :       Dict     ):
          pass



    @unittest.skip(reason="UperNet does not support input and output embeddings"     )
    def   lowerCamelCase_  (	self      :       List[Any]     ):
          pass



    @unittest.skip(reason="UperNet does not have a base model"     )
    def   lowerCamelCase_  (	self      :       Dict     ):
          pass



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



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



    def   lowerCamelCase_  (	self      :       int     ):
          def check_hidden_states_output(__A      :       int,__A      :       List[str],__A      :       Optional[int]     ):
                _lowerCamelCase				:   Any								=   model_class(__A     )
                model.to(__A     )
                model.eval()

                with torch.no_grad():
                      _lowerCamelCase				:   Dict								=   model(**self._prepare_for_class(__A,__A     )     )

                _lowerCamelCase				:   Optional[int]								=   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                _lowerCamelCase				:   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],)

          _lowerCamelCase						,		_lowerCamelCase				:   int								=   self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                _lowerCamelCase				:   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"]
                _lowerCamelCase				:   List[str]								=   True

                check_hidden_states_output(__A,__A,__A     )



    def   lowerCamelCase_  (	self      :       List[str]     ):
          _lowerCamelCase						,		_lowerCamelCase				:   Optional[int]								=   self.model_tester.prepare_config_and_inputs_for_common()

          _lowerCamelCase				:   Optional[int]								=   _config_zero_init(__A     )
          _lowerCamelCase				:   int								=   _config_zero_init(configs_no_init.backbone_config     )
          for model_class in self.all_model_classes:
                _lowerCamelCase				:   Union[str, 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   lowerCamelCase_  (	self      :       Optional[Any]     ):
          pass



    @slow
    def   lowerCamelCase_  (	self      :       Any     ):
          for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                _lowerCamelCase				:   int								=   UperNetForSemanticSegmentation.from_pretrained(__A     )
                self.assertIsNotNone(__A     )







def 		A_       (	):



      """simple docstring"""




      _lowerCamelCase				:   Union[str, Any]								=   hf_hub_download(
          repo_id="hf-internal-testing/fixtures_ade20k"				,	repo_type="dataset"				,	filename="ADE_val_00000001.jpg"							)
      _lowerCamelCase				:   Any								=   Image.open(_lowerCAmelCase							).convert("RGB"							)
      return image



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



    def   lowerCamelCase_  (	self      :       List[Any]     ):
          _lowerCamelCase				:   List[Any]								=   AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny"     )
          _lowerCamelCase				:   List[Any]								=   UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny"     ).to(__A     )

          _lowerCamelCase				:   Optional[int]								=   prepare_img()
          _lowerCamelCase				:   Dict								=   processor(images=__A,return_tensors="pt"     ).to(__A     )

          with torch.no_grad():
                _lowerCamelCase				:   Optional[int]								=   model(**__A     )

          _lowerCamelCase				:   Union[str, Any]								=   torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)     )
          self.assertEqual(outputs.logits.shape,__A     )

          _lowerCamelCase				:   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   lowerCamelCase_  (	self      :       Dict     ):
          _lowerCamelCase				:   int								=   AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny"     )
          _lowerCamelCase				:   List[Any]								=   UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny"     ).to(__A     )

          _lowerCamelCase				:   List[str]								=   prepare_img()
          _lowerCamelCase				:   Optional[Any]								=   processor(images=__A,return_tensors="pt"     ).to(__A     )

          with torch.no_grad():
                _lowerCamelCase				:   Any								=   model(**__A     )

          _lowerCamelCase				:   str								=   torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)     )
          self.assertEqual(outputs.logits.shape,__A     )

          _lowerCamelCase				:   Dict								=   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'''






def 		A_       (	_lowerCAmelCase   :    int							):



      """simple docstring"""




      if isinstance(_lowerCAmelCase				,	_lowerCAmelCase							):
            raise TypeError("'float' object cannot be interpreted as an integer"							)
      if isinstance(_lowerCAmelCase				,	_lowerCAmelCase							):
            raise TypeError("'str' object cannot be interpreted as an integer"							)

      if num == 0:
            return "0b0"

      _lowerCamelCase				:   Tuple								=   False

      if num < 0:
            _lowerCamelCase				:   List[Any]								=   True
            _lowerCamelCase				:   int								=   -num

      _lowerCamelCase				:   list[int]								=   []
      while num > 0:
            binary.insert(0				,	num % 2							)
            num >>= 1

      if negative:
            return "-0b" + "".join(str(_lowerCAmelCase							) for e in binary							)

      return "0b" + "".join(str(_lowerCAmelCase							) for e in binary							)


if __name__ == "__main__":
 import doctest

 doctest.testmod()