

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

								__lowerCamelCase    :    Optional[Any] 	=			None
								if self.use_labels:
									__lowerCamelCase    :    Optional[int] 	=			ids_tensor([self.batch_size]       ,self.type_sequence_label_size)

								__lowerCamelCase    :    int 	=			self.get_config()

								return config, pixel_values, labels
							def    lowerCAmelCase					(		self		:      int):
								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		:      int):
								return UperNetConfig(
								    backbone_config=self.get_backbone_config()       ,hidden_size=5_1_2       ,pool_scales=[1, 2, 3, 6]       ,use_auxiliary_head=SCREAMING_SNAKE_CASE__       ,auxiliary_loss_weight=0.4       ,auxiliary_in_channels=4_0       ,auxiliary_channels=2_5_6       ,auxiliary_num_convs=1       ,auxiliary_concat_input=SCREAMING_SNAKE_CASE__       ,loss_ignore_index=2_5_5       ,num_labels=self.num_labels       ,)
							def    lowerCAmelCase					(		self		:      Optional[int]       ,SCREAMING_SNAKE_CASE__		:      Any       ,SCREAMING_SNAKE_CASE__		:      List[Any]       ,SCREAMING_SNAKE_CASE__		:      Dict):
								__lowerCamelCase    :    str 	=			UperNetForSemanticSegmentation(config=SCREAMING_SNAKE_CASE__)
								model.to(SCREAMING_SNAKE_CASE__)
								model.eval()
								__lowerCamelCase    :    Optional[int] 	=			model(SCREAMING_SNAKE_CASE__)
								self.parent.assertEqual(
								    result.logits.shape       ,(self.batch_size, self.num_labels, self.image_size, self.image_size))


							def    lowerCAmelCase					(		self		:      Union[str, Any]):
								__lowerCamelCase    :    Union[str, Any] 	=			self.prepare_config_and_inputs()
								(
								    (
								    __lowerCamelCase
								)	,			(
								    __lowerCamelCase
								)	,			(
								    __lowerCamelCase
								)	,			
								)    :    Optional[int] 	=			config_and_inputs
								__lowerCamelCase    :    Union[str, Any] 	=			{'pixel_values': pixel_values}
								return config, inputs_dict






@require_torch
class 	A_		(	SCREAMING_SNAKE_CASE      ,							SCREAMING_SNAKE_CASE      ,							unittest.TestCase    ):
							_UpperCAmelCase   :  Optional[Any]										=				(UperNetForSemanticSegmentation,) if is_torch_available() else ()
							_UpperCAmelCase   :  str										=				{'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {}
							_UpperCAmelCase   :  str										=				False
							_UpperCAmelCase   :  Any										=				False
							_UpperCAmelCase   :  int										=				False
							_UpperCAmelCase   :  Optional[Any]										=				False
							_UpperCAmelCase   :  str										=				False
							_UpperCAmelCase   :  Optional[Any]										=				False
							def    lowerCAmelCase					(		self		:      Any):
								__lowerCamelCase    :    Tuple 	=			UperNetModelTester(self)
								__lowerCamelCase    :    int 	=			ConfigTester(self       ,config_class=SCREAMING_SNAKE_CASE__       ,has_text_modality=SCREAMING_SNAKE_CASE__       ,hidden_size=3_7)
							def    lowerCAmelCase					(		self		:      Union[str, Any]):
								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		:      Optional[Any]):
								__lowerCamelCase	,			__lowerCamelCase    :    Optional[Any] 	=			self.model_tester.prepare_config_and_inputs_for_common()

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

									__lowerCamelCase    :    Optional[Any] 	=			['pixel_values']
									self.assertListEqual(arg_names[:1]       ,SCREAMING_SNAKE_CASE__)
							def    lowerCAmelCase					(		self		:      int):
								__lowerCamelCase    :    Tuple 	=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE__)
							@unittest.skip(reason='UperNet does not use inputs_embeds')
							def    lowerCAmelCase					(		self		:      int):
								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		:      str):
								pass
							@unittest.skip(reason='UperNet does not have a base model')
							def    lowerCAmelCase					(		self		:      Optional[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		:      List[str]):
								pass
							@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
							def    lowerCAmelCase					(		self		:      str):
								pass
							def    lowerCAmelCase					(		self		:      int):
								def check_hidden_states_output(SCREAMING_SNAKE_CASE__		:      Optional[Any]       ,SCREAMING_SNAKE_CASE__		:      List[Any]       ,SCREAMING_SNAKE_CASE__		:      int):
									__lowerCamelCase    :    Tuple 	=			model_class(SCREAMING_SNAKE_CASE__)
									model.to(SCREAMING_SNAKE_CASE__)
									model.eval()

									with torch.no_grad():
										__lowerCamelCase    :    Tuple 	=			model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__))

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

									__lowerCamelCase    :    str 	=			self.model_tester.num_stages
									self.assertEqual(len(SCREAMING_SNAKE_CASE__)       ,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    :    Dict 	=			self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									__lowerCamelCase    :    int 	=			True
									check_hidden_states_output(SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__)

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

									check_hidden_states_output(SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__)
							def    lowerCAmelCase					(		self		:      str):
								__lowerCamelCase	,			__lowerCamelCase    :    str 	=			self.model_tester.prepare_config_and_inputs_for_common()

								__lowerCamelCase    :    Any 	=			_config_zero_init(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[Any] 	=			_config_zero_init(configs_no_init.backbone_config)
								for model_class in self.all_model_classes:
									__lowerCamelCase    :    List[str] 	=			model_class(config=SCREAMING_SNAKE_CASE__)
									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		:      List[Any]):
								pass


							@slow
							def    lowerCAmelCase					(		self		:      Any):
								for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									__lowerCamelCase    :    Union[str, Any] 	=			UperNetForSemanticSegmentation.from_pretrained(SCREAMING_SNAKE_CASE__)
									self.assertIsNotNone(SCREAMING_SNAKE_CASE__)






def        SCREAMING_SNAKE_CASE__	(  )  ->					Any:
	__lowerCamelCase    :    str 	=			hf_hub_download(
	    repo_id='hf-internal-testing/fixtures_ade20k'     ,			repo_type='dataset'     ,			filename='ADE_val_00000001.jpg'      )
	__lowerCamelCase    :    Union[str, Any] 	=			Image.open(lowerCamelCase__      ).convert('RGB'      )
	return image






@require_torch
@require_vision
@slow
class 	A_		(	unittest.TestCase    ):
							def    lowerCAmelCase					(		self		:      Optional[int]):
								__lowerCamelCase    :    Union[str, Any] 	=			AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny')
								__lowerCamelCase    :    str 	=			UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny').to(SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Optional[Any] 	=			prepare_img()
								__lowerCamelCase    :    Optional[Any] 	=			processor(images=SCREAMING_SNAKE_CASE__       ,return_tensors='pt').to(SCREAMING_SNAKE_CASE__)

								with torch.no_grad():
									__lowerCamelCase    :    List[Any] 	=			model(**SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Optional[Any] 	=			torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2))
								self.assertEqual(outputs.logits.shape       ,SCREAMING_SNAKE_CASE__)

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


							def    lowerCAmelCase					(		self		:      Tuple):
								__lowerCamelCase    :    Optional[Any] 	=			AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny')
								__lowerCamelCase    :    Tuple 	=			UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny').to(SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    int 	=			prepare_img()
								__lowerCamelCase    :    Optional[Any] 	=			processor(images=SCREAMING_SNAKE_CASE__       ,return_tensors='pt').to(SCREAMING_SNAKE_CASE__)

								with torch.no_grad():
									__lowerCamelCase    :    Any 	=			model(**SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    List[str] 	=			torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2))
								self.assertEqual(outputs.logits.shape       ,SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    str 	=			torch.tensor(
								    [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]).to(SCREAMING_SNAKE_CASE__)
								self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]       ,SCREAMING_SNAKE_CASE__       ,atol=1E-4))







# This is the module that test_patching.py uses to test patch_submodule()

import os  # noqa: this is just for tests
import os as renamed_os  # noqa: this is just for tests
from os import path  # noqa: this is just for tests
from os import path as renamed_path  # noqa: this is just for tests
from os.path import join  # noqa: this is just for tests
from os.path import join as renamed_join  # noqa: this is just for tests


a		=open  # noqa: we just need to have a builtin inside this module to test it properly




