


"""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    :
							'''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.0_2       ,  __a=["stage2", "stage3", "stage4"]       ,  __a=3       ,  __a=None       ,  ):
										__lowerCAmelCase							       =     parent
										__lowerCAmelCase							       =     batch_size
										__lowerCAmelCase							       =     image_size
										__lowerCAmelCase							       =     num_channels
										__lowerCAmelCase							       =     num_stages
										__lowerCAmelCase							       =     hidden_sizes
										__lowerCAmelCase							       =     depths
										__lowerCAmelCase							       =     is_training
										__lowerCAmelCase							       =     use_labels
										__lowerCAmelCase							       =     intermediate_size
										__lowerCAmelCase							       =     hidden_act
										__lowerCAmelCase							       =     type_sequence_label_size
										__lowerCAmelCase							       =     initializer_range
										__lowerCAmelCase							       =     out_features
										__lowerCAmelCase							       =     num_labels
										__lowerCAmelCase							       =     scope
										__lowerCAmelCase							       =     num_stages

							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

										__lowerCAmelCase							       =     self.get_config()

										return config, pixel_values, labels

							def      snake_case							(	self      ):
										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      snake_case							(	self      ):
										return UperNetConfig(
										    backbone_config=self.get_backbone_config()       ,  hidden_size=5_12       ,  pool_scales=[1, 2, 3, 6]       ,  use_auxiliary_head=__a       ,  auxiliary_loss_weight=0.4       ,  auxiliary_in_channels=40       ,  auxiliary_channels=2_56       ,  auxiliary_num_convs=1       ,  auxiliary_concat_input=__a       ,  loss_ignore_index=2_55       ,  num_labels=self.num_labels       ,  )

							def      snake_case							(	self       ,  __a       ,  __a       ,  __a      ):
										__lowerCAmelCase							       =     UperNetForSemanticSegmentation(config=__a      )
										model.to(__a      )
										model.eval()
										__lowerCAmelCase							       =     model(__a      )
										self.parent.assertEqual(
										    result.logits.shape       ,  (self.batch_size, self.num_labels, self.image_size, self.image_size)      )



							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     self.prepare_config_and_inputs()
										(
										    __lowerCAmelCase
										)							       =     config_and_inputs
										__lowerCAmelCase							       =     {"pixel_values": pixel_values}
										return config, inputs_dict
@require_torch
class     _UpperCamelCase    (  lowerCAmelCase__			,lowerCAmelCase__			,unittest.TestCase						):
							'''simple docstring'''







							__UpperCAmelCase		:       int							 =(UperNetForSemanticSegmentation,) if is_torch_available() else ()
							__UpperCAmelCase		:       Tuple							 ={"""image-segmentation""": UperNetForSemanticSegmentation} if is_torch_available() else {}
							__UpperCAmelCase		:       Dict							 =False
							__UpperCAmelCase		:       Optional[Any]							 =False
							__UpperCAmelCase		:       Dict							 =False
							__UpperCAmelCase		:       Optional[int]							 =False
							__UpperCAmelCase		:       List[str]							 =False
							__UpperCAmelCase		:       Tuple							 =False

							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     UperNetModelTester(self      )
										__lowerCAmelCase							       =     ConfigTester(self       ,  config_class=__a       ,  has_text_modality=__a       ,  hidden_size=37      )

							def      snake_case							(	self      ):
										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      snake_case							(	self      ):
										return

							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     self.model_tester.prepare_config_and_inputs_for_common()

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

													__lowerCAmelCase							       =     ["pixel_values"]
													self.assertListEqual(arg_names[:1]       ,  __a      )

							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     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      snake_case							(	self      ):
										pass

							@unittest.skip(reason="UperNet does not support input and output embeddings"      )
							def      snake_case							(	self      ):
										pass

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

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

							@require_torch_multi_gpu
							@unittest.skip(reason="UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`"      )
							def      snake_case							(	self      ):
										pass

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

							def      snake_case							(	self      ):





										def check_hidden_states_output(__a       ,  __a       ,  __a      ):
													__lowerCAmelCase							       =     model_class(__a      )
													model.to(__a      )
													model.eval()

													with torch.no_grad():
																__lowerCAmelCase							       =     model(**self._prepare_for_class(__a       ,  __a      )      )

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

													__lowerCAmelCase							       =     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							       =     self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													__lowerCAmelCase							       =     True
													check_hidden_states_output(__a       ,  __a       ,  __a      )

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

													check_hidden_states_output(__a       ,  __a       ,  __a      )

							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     self.model_tester.prepare_config_and_inputs_for_common()

										__lowerCAmelCase							       =     _config_zero_init(__a      )
										__lowerCAmelCase							       =     _config_zero_init(configs_no_init.backbone_config      )
										for model_class in self.all_model_classes:
													__lowerCAmelCase							       =     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      snake_case							(	self      ):
										pass



							@slow
							def      snake_case							(	self      ):





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


def _lowerCamelCase      (						):

			'''simple docstring'''




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


@require_torch
@require_vision
@slow
class     _UpperCamelCase    (  unittest.TestCase						):
							'''simple docstring'''







							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny"      )
										__lowerCAmelCase							       =     UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny"      ).to(__a      )

										__lowerCAmelCase							       =     prepare_img()
										__lowerCAmelCase							       =     processor(images=__a       ,  return_tensors="pt"      ).to(__a      )

										with torch.no_grad():
													__lowerCAmelCase							       =     model(**__a      )

										__lowerCAmelCase							       =     torch.Size((1, model.config.num_labels, 5_12, 5_12)      )
										self.assertEqual(outputs.logits.shape       ,  __a      )

										__lowerCAmelCase							       =     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      snake_case							(	self      ):
										__lowerCAmelCase							       =     AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny"      )
										__lowerCAmelCase							       =     UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny"      ).to(__a      )

										__lowerCAmelCase							       =     prepare_img()
										__lowerCAmelCase							       =     processor(images=__a       ,  return_tensors="pt"      ).to(__a      )

										with torch.no_grad():
													__lowerCAmelCase							       =     model(**__a      )

										__lowerCAmelCase							       =     torch.Size((1, model.config.num_labels, 5_12, 5_12)      )
										self.assertEqual(outputs.logits.shape       ,  __a      )

										__lowerCAmelCase							       =     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      )      )








'''simple docstring'''


from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_UpperCamelCase 							=  {
    """configuration_upernet""": ["""UperNetConfig"""],
}

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _UpperCamelCase 							=  [
          """UperNetForSemanticSegmentation""",
          """UperNetPreTrainedModel""",
      ]


if TYPE_CHECKING:
      from .configuration_upernet import UperNetConfig

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel


else:
      import sys

      _UpperCamelCase 							=  _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

