





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







 '''simple docstring'''

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



   '''simple docstring'''



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

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[str])	->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:				Dict        =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

   lowerCamelCase__:				Optional[int]        =self.get_config()

   return config, pixel_values, labels

 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple)	->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 							SCREAMING_SNAKE_CASE_ (self    :       List[Any])	->Union[str, Any]:



   '''simple docstring'''



   return UperNetConfig(
       backbone_config=self.get_backbone_config()	,			hidden_size=512	,			pool_scales=[1, 2, 3, 6]	,			use_auxiliary_head=UpperCAmelCase_	,			auxiliary_loss_weight=0.4	,			auxiliary_in_channels=40	,			auxiliary_channels=256	,			auxiliary_num_convs=1	,			auxiliary_concat_input=UpperCAmelCase_	,			loss_ignore_index=255	,			num_labels=self.num_labels	,			)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict	,			UpperCAmelCase_    :       List[str]	,			UpperCAmelCase_    :       Optional[int]	,			UpperCAmelCase_    :       Optional[Any])	->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:				Optional[int]        =UperNetForSemanticSegmentation(config=UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__:				Union[str, Any]        =model(UpperCAmelCase_)
   self.parent.assertEqual(
       result.logits.shape	,			(self.batch_size, self.num_labels, self.image_size, self.image_size))







 def 							SCREAMING_SNAKE_CASE_ (self    :       Optional[Any])	->Tuple:



   '''simple docstring'''



   lowerCamelCase__:				str        =self.prepare_config_and_inputs()
   (
       (
       lowerCamelCase__
   )  , (
       lowerCamelCase__
   )  , (
       lowerCamelCase__
   )  , 
   ):				Optional[int]        =config_and_inputs
   lowerCamelCase__:				List[Any]        ={"pixel_values": pixel_values}
   return config, inputs_dict



@require_torch
class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ,							__SCREAMING_SNAKE_CASE   ,							unittest.TestCase   ):







 '''simple docstring'''
 lowercase_		=      (UperNetForSemanticSegmentation,) if is_torch_available() else ()
 lowercase_		=      {"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {}
 lowercase_		=      False
 lowercase_		=      False
 lowercase_		=      False
 lowercase_		=      False
 lowercase_		=      False
 lowercase_		=      False

 def 							SCREAMING_SNAKE_CASE_ (self    :       Union[str, Any])	->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:				int        =UperNetModelTester(self)
   lowerCamelCase__:				Optional[Any]        =ConfigTester(self	,			config_class=UpperCAmelCase_	,			has_text_modality=UpperCAmelCase_	,			hidden_size=37)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple)	->int:



   '''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 							SCREAMING_SNAKE_CASE_ (self    :       Tuple)	->int:



   '''simple docstring'''



   return

 def 							SCREAMING_SNAKE_CASE_ (self    :       Optional[int])	->str:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				Union[str, Any]        =self.model_tester.prepare_config_and_inputs_for_common()

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

     lowerCamelCase__:				Dict        =["pixel_values"]
     self.assertListEqual(arg_names[:1]	,			UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict)	->int:



   '''simple docstring'''



   lowerCamelCase__:				int        =self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_)

 @unittest.skip(reason="UperNet does not use inputs_embeds")
 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict)	->Union[str, Any]:



   '''simple docstring'''



   pass

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



   '''simple docstring'''



   pass

 @unittest.skip(reason="UperNet does not have a base model")
 def 							SCREAMING_SNAKE_CASE_ (self    :       Optional[Any])	->Union[str, Any]:



   '''simple docstring'''



   pass

 @unittest.skip(reason="UperNet does not have a base model")
 def 							SCREAMING_SNAKE_CASE_ (self    :       Any)	->Dict:



   '''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 							SCREAMING_SNAKE_CASE_ (self    :       Tuple)	->Any:



   '''simple docstring'''



   pass

 @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests.")
 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple)	->str:



   '''simple docstring'''



   pass

 def 							SCREAMING_SNAKE_CASE_ (self    :       str)	->Optional[Any]:



   '''simple docstring'''



   def check_hidden_states_output(UpperCAmelCase_    :       Optional[Any]	,			UpperCAmelCase_    :       List[str]	,			UpperCAmelCase_    :       Optional[int]):
     lowerCamelCase__:				Optional[Any]        =model_class(UpperCAmelCase_)
     model.to(UpperCAmelCase_)
     model.eval()

     with torch.no_grad():
       lowerCamelCase__:				int        =model(**self._prepare_for_class(UpperCAmelCase_	,			UpperCAmelCase_))

     lowerCamelCase__:				List[Any]        =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

     lowerCamelCase__:				Optional[int]        =self.model_tester.num_stages
     self.assertEqual(len(UpperCAmelCase_)	,			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__:				str        =self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     lowerCamelCase__:				Dict        =True
     check_hidden_states_output(UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_)

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

     check_hidden_states_output(UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_)

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



   '''simple docstring'''



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

   lowerCamelCase__:				Union[str, Any]        =_config_zero_init(UpperCAmelCase_)
   lowerCamelCase__:				Optional[Any]        =_config_zero_init(configs_no_init.backbone_config)
   for model_class in self.all_model_classes:
     lowerCamelCase__:				Optional[int]        =model_class(config=UpperCAmelCase_)
     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 							SCREAMING_SNAKE_CASE_ (self    :       Union[str, Any])	->Tuple:



   '''simple docstring'''



   pass







 @slow
 def 							SCREAMING_SNAKE_CASE_ (self    :       Optional[int])	->int:



   '''simple docstring'''



   for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     lowerCamelCase__:				Dict        =UperNetForSemanticSegmentation.from_pretrained(UpperCAmelCase_)
     self.assertIsNotNone(UpperCAmelCase_)





def 					lowerCAmelCase_			(	)					->		List[str]:







  """simple docstring"""





  lowerCamelCase__:				Optional[Any]        =hf_hub_download(
      repo_id="hf-internal-testing/fixtures_ade20k"     ,   repo_type="dataset"     ,   filename="ADE_val_00000001.jpg"		)
  lowerCamelCase__:				Dict        =Image.open(__a		).convert("RGB"		)
  return image






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







 '''simple docstring'''

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[Any])	->str:



   '''simple docstring'''



   lowerCamelCase__:				str        =AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny")
   lowerCamelCase__:				Optional[Any]        =UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny").to(UpperCAmelCase_)

   lowerCamelCase__:				Union[str, Any]        =prepare_img()
   lowerCamelCase__:				Tuple        =processor(images=UpperCAmelCase_	,			return_tensors="pt").to(UpperCAmelCase_)

   with torch.no_grad():
     lowerCamelCase__:				Tuple        =model(**UpperCAmelCase_)

   lowerCamelCase__:				Dict        =torch.Size((1, model.config.num_labels, 512, 512))
   self.assertEqual(outputs.logits.shape	,			UpperCAmelCase_)

   lowerCamelCase__:				Any        =torch.tensor(
       [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]).to(UpperCAmelCase_)
   self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]	,			UpperCAmelCase_	,			atol=1E-4))







 def 							SCREAMING_SNAKE_CASE_ (self    :       Union[str, Any])	->Dict:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny")
   lowerCamelCase__:				List[Any]        =UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny").to(UpperCAmelCase_)

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

   with torch.no_grad():
     lowerCamelCase__:				Optional[Any]        =model(**UpperCAmelCase_)

   lowerCamelCase__:				List[Any]        =torch.Size((1, model.config.num_labels, 512, 512))
   self.assertEqual(outputs.logits.shape	,			UpperCAmelCase_)

   lowerCamelCase__:				List[Any]        =torch.tensor(
       [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]).to(UpperCAmelCase_)
   self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]	,			UpperCAmelCase_	,			atol=1E-4))








from ..utils import DummyObject, requires_backends



class        _SCREAMING_SNAKE_CASE						(     metaclass=__SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''
 lowercase_		=      ["torch", "torchsde"]

 def __init__(self    :       Union[str, Any]	,			*UpperCAmelCase_    :       Dict	,			**UpperCAmelCase_    :       Tuple)	->Any:



   '''simple docstring'''



   requires_backends(self	,			["torch", "torchsde"])

 @classmethod
 def 							SCREAMING_SNAKE_CASE_ (cls    :       Dict	,			*UpperCAmelCase_    :       Optional[int]	,			**UpperCAmelCase_    :       Optional[int])	->List[Any]:



   '''simple docstring'''



   requires_backends(cls	,			["torch", "torchsde"])







 @classmethod
 def 							SCREAMING_SNAKE_CASE_ (cls    :       Tuple	,			*UpperCAmelCase_    :       Tuple	,			**UpperCAmelCase_    :       Any)	->Any:



   '''simple docstring'''



   requires_backends(cls	,			["torch", "torchsde"])

