



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



 '''simple docstring'''







 def __init__(self					,  A					,  A=13					,  A=32					,  A=3					,  A=4					,  A=[10, 20, 30, 40]					,  A=[2, 2, 3, 2]					,  A=True					,  A=True					,  A=37					,  A="gelu"					,  A=10					,  A=0.02					,  A=["stage2", "stage3", "stage4"]					,  A=3					,  A=None					,  )       ->	List[str]:


      """simple docstring"""



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



 def    a__    (self			)       ->	List[Any]:


      """simple docstring"""



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

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

      _a           =    self.get_config()

      return config, pixel_values, labels



 def    a__    (self			)       ->	Optional[int]:


      """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					,  A					,  A					,  A			)       ->	Union[str, Any]:


      """simple docstring"""



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



 def    a__    (self			)       ->	int:


      """simple docstring"""



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






@require_torch
class __A     (    A  ,  A  ,  unittest.TestCase		):



 '''simple docstring'''







 __lowerCamelCase       :			Tuple		=			(UperNetForSemanticSegmentation,) if is_torch_available() else ()
 __lowerCamelCase       :			Any		=			{'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {}
 __lowerCamelCase       :			List[Any]		=			False
 __lowerCamelCase       :			Tuple		=			False
 __lowerCamelCase       :			int		=			False
 __lowerCamelCase       :			str		=			False
 __lowerCamelCase       :			List[str]		=			False
 __lowerCamelCase       :			int		=			False



 def    a__    (self			)       ->	List[str]:


      """simple docstring"""



      _a           =    UperNetModelTester(self			)
      _a           =    ConfigTester(self					,  config_class=A					,  has_text_modality=A					,  hidden_size=37			)



 def    a__    (self			)       ->	List[Any]:


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


      """simple docstring"""



      _a    ,       _a           =    self.model_tester.prepare_config_and_inputs_for_common()

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

           _a           =    ['''pixel_values''']
           self.assertListEqual(arg_names[:1]					,  A			)



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


      """simple docstring"""



      _a           =    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			)       ->	Any:


      """simple docstring"""



      pass



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


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


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


      """simple docstring"""



      pass



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


      """simple docstring"""



      pass



 def    a__    (self			)       ->	str:


      """simple docstring"""



      def check_hidden_states_output(A					,  A					,  A			):
           _a           =    model_class(A			)
           model.to(A			)
           model.eval()

           with torch.no_grad():
                _a           =    model(**self._prepare_for_class(A					,  A			)			)

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

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

      _a    ,       _a           =    self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           _a           =    True
           check_hidden_states_output(A					,  A					,  A			)

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

           check_hidden_states_output(A					,  A					,  A			)



 def    a__    (self			)       ->	str:


      """simple docstring"""



      _a    ,       _a           =    self.model_tester.prepare_config_and_inputs_for_common()

      _a           =    _config_zero_init(A			)
      _a           =    _config_zero_init(configs_no_init.backbone_config			)
      for model_class in self.all_model_classes:
           _a           =    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			)       ->	Tuple:


      """simple docstring"""



      pass



 @slow
 def    a__    (self			)       ->	str:


      """simple docstring"""



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





def lowerCAmelCase    ():



     """simple docstring"""



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






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



 '''simple docstring'''







 def    a__    (self			)       ->	List[str]:


      """simple docstring"""



      _a           =    AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny'''			)
      _a           =    UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny'''			).to(A			)

      _a           =    prepare_img()
      _a           =    processor(images=A					,  return_tensors='''pt'''			).to(A			)

      with torch.no_grad():
           _a           =    model(**A			)

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

      _a           =    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    a__    (self			)       ->	List[str]:


      """simple docstring"""



      _a           =    AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny'''			)
      _a           =    UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny'''			).to(A			)

      _a           =    prepare_img()
      _a           =    processor(images=A					,  return_tensors='''pt'''			).to(A			)

      with torch.no_grad():
           _a           =    model(**A			)

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

      _a           =    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 lowerCAmelCase    (__A    ,      __A):



     """simple docstring"""



     if digit_amount > 0:
          return round(number - int(__A)    ,      __A)
     return number - int(__A)


if __name__ == "__main__":
  print(decimal_isolate(1.53, 0))
  print(decimal_isolate(35.345, 1))
  print(decimal_isolate(35.345, 2))
  print(decimal_isolate(35.345, 3))
  print(decimal_isolate(-14.789, 3))
  print(decimal_isolate(0, 2))
  print(decimal_isolate(-14.123, 1))
  print(decimal_isolate(-14.123, 2))
  print(decimal_isolate(-14.123, 3))



