





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





      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 ,							):
       '''simple docstring'''




       UpperCamelCase			:      Any 			=     parent
       UpperCamelCase			:      Tuple 			=     batch_size
       UpperCamelCase			:      List[str] 			=     image_size
       UpperCamelCase			:      List[Any] 			=     num_channels
       UpperCamelCase			:      Any 			=     num_stages
       UpperCamelCase			:      int 			=     hidden_sizes
       UpperCamelCase			:      Optional[Any] 			=     depths
       UpperCamelCase			:      Tuple 			=     is_training
       UpperCamelCase			:      Any 			=     use_labels
       UpperCamelCase			:      Tuple 			=     intermediate_size
       UpperCamelCase			:      List[Any] 			=     hidden_act
       UpperCamelCase			:      Any 			=     type_sequence_label_size
       UpperCamelCase			:      Optional[int] 			=     initializer_range
       UpperCamelCase			:      Optional[Any] 			=     out_features
       UpperCamelCase			:      Dict 			=     num_labels
       UpperCamelCase			:      Union[str, Any] 			=     scope
       UpperCamelCase			:      int 			=     num_stages





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

       UpperCamelCase			:      Dict 			=     None
       if self.use_labels:
        UpperCamelCase			:      Any 			=     ids_tensor([self.batch_size] ,							self.type_sequence_label_size     )

       UpperCamelCase			:      int 			=     self.get_config()

       return config, pixel_values, labels





      def  __UpperCamelCase(				self     ):
       '''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  __UpperCamelCase(				self     ):
       '''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  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Union[str, Any] 			=     UperNetForSemanticSegmentation(config=A_     )
       model.to(A_     )
       model.eval()
       UpperCamelCase			:      Tuple 			=     model(A_     )
       self.parent.assertEqual(
           result.logits.shape ,							(self.batch_size, self.num_labels, self.image_size, self.image_size)     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




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



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





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      int 			=     UperNetModelTester(self     )
       UpperCamelCase			:      Union[str, Any] 			=     ConfigTester(self ,							config_class=A_ ,							has_text_modality=A_ ,							hidden_size=37     )





      def  __UpperCamelCase(				self     ):
       '''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  __UpperCamelCase(				self     ):
       '''simple docstring'''




       return





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			,					UpperCamelCase			:      Optional[int] 			=     self.model_tester.prepare_config_and_inputs_for_common()

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

        UpperCamelCase			:      Tuple 			=     ["pixel_values"]
        self.assertListEqual(arg_names[:1] ,							A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     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  __UpperCamelCase(				self     ):
       '''simple docstring'''




       pass





      @unittest.skip(reason="UperNet does not support input and output embeddings"     )
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       pass





      @unittest.skip(reason="UperNet does not have a base model"     )
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       pass





      @unittest.skip(reason="UperNet does not have a base model"     )
      def  __UpperCamelCase(				self     ):
       '''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  __UpperCamelCase(				self     ):
       '''simple docstring'''




       pass





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




       pass





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       def check_hidden_states_output(A_ ,							A_ ,							A_     ):
        UpperCamelCase			:      Any 			=     model_class(A_     )
        model.to(A_     )
        model.eval()

        with torch.no_grad():
         UpperCamelCase			:      Tuple 			=     model(**self._prepare_for_class(A_ ,							A_     )     )

        UpperCamelCase			:      Optional[Any] 			=     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        UpperCamelCase			:      Union[str, 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] ,							)

       UpperCamelCase			,					UpperCamelCase			:      str 			=     self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        UpperCamelCase			:      List[str] 			=     True
        check_hidden_states_output(A_ ,							A_ ,							A_     )

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        UpperCamelCase			:      List[Any] 			=     True

        check_hidden_states_output(A_ ,							A_ ,							A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




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

       UpperCamelCase			:      List[str] 			=     _config_zero_init(A_     )
       UpperCamelCase			:      Optional[Any] 			=     _config_zero_init(configs_no_init.backbone_config     )
       for model_class in self.all_model_classes:
        UpperCamelCase			:      List[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  __UpperCamelCase(				self     ):
       '''simple docstring'''




       pass





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCamelCase			:      Tuple 			=     UperNetForSemanticSegmentation.from_pretrained(A_     )
        self.assertIsNotNone(A_     )



def 	A_       (  )		->				Optional[Any]:
 UpperCamelCase			:      str 			=     hf_hub_download(
     repo_id="hf-internal-testing/fixtures_ade20k"							,     repo_type="dataset"							,     filename="ADE_val_00000001.jpg"  )
 UpperCamelCase			:      Tuple 			=     Image.open(UpperCamelCase__  ).convert("RGB"  )
 return image



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





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Union[str, Any] 			=     AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny"     )
       UpperCamelCase			:      Tuple 			=     UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny"     ).to(A_     )

       UpperCamelCase			:      Any 			=     prepare_img()
       UpperCamelCase			:      Optional[int] 			=     processor(images=A_ ,							return_tensors="pt"     ).to(A_     )

       with torch.no_grad():
        UpperCamelCase			:      Optional[int] 			=     model(**A_     )

       UpperCamelCase			:      Union[str, Any] 			=     torch.Size((1, model.config.num_labels, 512, 512)     )
       self.assertEqual(outputs.logits.shape ,							A_     )

       UpperCamelCase			:      List[Any] 			=     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(A_     )
       self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] ,							A_ ,							atol=1e-4     )     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Any 			=     AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny"     )
       UpperCamelCase			:      Dict 			=     UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny"     ).to(A_     )

       UpperCamelCase			:      Optional[Any] 			=     prepare_img()
       UpperCamelCase			:      Tuple 			=     processor(images=A_ ,							return_tensors="pt"     ).to(A_     )

       with torch.no_grad():
        UpperCamelCase			:      List[Any] 			=     model(**A_     )

       UpperCamelCase			:      str 			=     torch.Size((1, model.config.num_labels, 512, 512)     )
       self.assertEqual(outputs.logits.shape ,							A_     )

       UpperCamelCase			:      Tuple 			=     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(A_     )
       self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] ,							A_ ,							atol=1e-4     )     )








from ..utils import DummyObject, requires_backends



class       A__     ( metaclass=__snake_case    ):
      _UpperCAmelCase			:Tuple							=     ['note_seq']





      def __init__(				self ,							*A_ ,							**A_     ):
       '''simple docstring'''




       requires_backends(self ,							["note_seq"]     )





      @classmethod
      def  __UpperCamelCase(				cls ,							*A_ ,							**A_     ):
       '''simple docstring'''




       requires_backends(cls ,							["note_seq"]     )





      @classmethod
      def  __UpperCamelCase(				cls ,							*A_ ,							**A_     ):
       '''simple docstring'''




       requires_backends(cls ,							["note_seq"]     )
