






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		:       Optional[int],    lowerCamelCase		:       List[Any],    lowerCamelCase		:       Union[str, Any]=13,    lowerCamelCase		:       Any=32,    lowerCamelCase		:       Optional[int]=3,    lowerCamelCase		:       int=4,    lowerCamelCase		:       str=[10, 20, 30, 40],    lowerCamelCase		:       Union[str, Any]=[2, 2, 3, 2],    lowerCamelCase		:       List[Any]=True,    lowerCamelCase		:       int=True,    lowerCamelCase		:       Optional[Any]=37,    lowerCamelCase		:       Dict="gelu",    lowerCamelCase		:       List[str]=10,    lowerCamelCase		:       Optional[Any]=0.02,    lowerCamelCase		:       int=["stage2", "stage3", "stage4"],    lowerCamelCase		:       Tuple=3,    lowerCamelCase		:       Optional[Any]=None,    ):

								'''simple docstring'''
								lowercase__  					=     parent
								lowercase__  					=     batch_size
								lowercase__  					=     image_size
								lowercase__  					=     num_channels
								lowercase__  					=     num_stages
								lowercase__  					=     hidden_sizes
								lowercase__  					=     depths
								lowercase__  					=     is_training
								lowercase__  					=     use_labels
								lowercase__  					=     intermediate_size
								lowercase__  					=     hidden_act
								lowercase__  					=     type_sequence_label_size
								lowercase__  					=     initializer_range
								lowercase__  					=     out_features
								lowercase__  					=     num_labels
								lowercase__  					=     scope
								lowercase__  					=     num_stages




				def 							lowercase__  (	self		:       Optional[Any]    ):

								'''simple docstring'''
								lowercase__  					=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

								lowercase__  					=     self.get_config()

								return config, pixel_values, labels




				def 							lowercase__  (	self		:       List[str]    ):

								'''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 							lowercase__  (	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=lowerCamelCase,    auxiliary_loss_weight=0.4,    auxiliary_in_channels=40,    auxiliary_channels=256,    auxiliary_num_convs=1,    auxiliary_concat_input=lowerCamelCase,    loss_ignore_index=255,    num_labels=self.num_labels,    )




				def 							lowercase__  (	self		:       List[Any],    lowerCamelCase		:       int,    lowerCamelCase		:       Tuple,    lowerCamelCase		:       Dict    ):

								'''simple docstring'''
								lowercase__  					=     UperNetForSemanticSegmentation(config=lowerCamelCase    )
								model.to(lowerCamelCase    )
								model.eval()
								lowercase__  					=     model(lowerCamelCase    )
								self.parent.assertEqual(
								    result.logits.shape,    (self.batch_size, self.num_labels, self.image_size, self.image_size)    )




				def 							lowercase__  (	self		:       List[str]    ):

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



@require_torch
class  _UpperCAmelCase   (			A__						,A__						,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 							lowercase__  (	self		:       str    ):

								'''simple docstring'''
								lowercase__  					=     UperNetModelTester(self    )
								lowercase__  					=     ConfigTester(self,    config_class=lowerCamelCase,    has_text_modality=lowerCamelCase,    hidden_size=37    )




				def 							lowercase__  (	self		:       str    ):

								'''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 							lowercase__  (	self		:       List[Any]    ):

								'''simple docstring'''
								return




				def 							lowercase__  (	self		:       Union[str, Any]    ):

								'''simple docstring'''
								lowercase__					,		lowercase__  					=     self.model_tester.prepare_config_and_inputs_for_common()

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

												lowercase__  					=     ['''pixel_values''']
												self.assertListEqual(arg_names[:1],    lowerCamelCase    )




				def 							lowercase__  (	self		:       Optional[Any]    ):

								'''simple docstring'''
								lowercase__  					=     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase    )




				@unittest.skip(reason='''UperNet does not use inputs_embeds'''    )
				def 							lowercase__  (	self		:       int    ):

								'''simple docstring'''
								pass




				@unittest.skip(reason='''UperNet does not support input and output embeddings'''    )
				def 							lowercase__  (	self		:       Union[str, Any]    ):

								'''simple docstring'''
								pass




				@unittest.skip(reason='''UperNet does not have a base model'''    )
				def 							lowercase__  (	self		:       Optional[Any]    ):

								'''simple docstring'''
								pass




				@unittest.skip(reason='''UperNet does not have a base model'''    )
				def 							lowercase__  (	self		:       Optional[int]    ):

								'''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 							lowercase__  (	self		:       List[Any]    ):

								'''simple docstring'''
								pass




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

								'''simple docstring'''
								pass




				def 							lowercase__  (	self		:       Any    ):

								'''simple docstring'''
								def check_hidden_states_output(lowerCamelCase		:       int,    lowerCamelCase		:       Optional[int],    lowerCamelCase		:       Optional[Any]    ):
												lowercase__  					=     model_class(lowerCamelCase    )
												model.to(lowerCamelCase    )
												model.eval()

												with torch.no_grad():
																lowercase__  					=     model(**self._prepare_for_class(lowerCamelCase,    lowerCamelCase    )    )

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

												lowercase__  					=     self.model_tester.num_stages
												self.assertEqual(len(lowerCamelCase    ),    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],    )

								lowercase__					,		lowercase__  					=     self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
												lowercase__  					=     True
												check_hidden_states_output(lowerCamelCase,    lowerCamelCase,    lowerCamelCase    )

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

												check_hidden_states_output(lowerCamelCase,    lowerCamelCase,    lowerCamelCase    )




				def 							lowercase__  (	self		:       Optional[int]    ):

								'''simple docstring'''
								lowercase__					,		lowercase__  					=     self.model_tester.prepare_config_and_inputs_for_common()

								lowercase__  					=     _config_zero_init(lowerCamelCase    )
								lowercase__  					=     _config_zero_init(configs_no_init.backbone_config    )
								for model_class in self.all_model_classes:
												lowercase__  					=     model_class(config=lowerCamelCase    )
												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 							lowercase__  (	self		:       Any    ):

								'''simple docstring'''
								pass




				@slow
				def 							lowercase__  (	self		:       Any    ):

								'''simple docstring'''
								for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												lowercase__  					=     UperNetForSemanticSegmentation.from_pretrained(lowerCamelCase    )
												self.assertIsNotNone(lowerCamelCase    )






def     a     (		):






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




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

				"""simple docstring"""




				def 							lowercase__  (	self		:       str    ):

								'''simple docstring'''
								lowercase__  					=     AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny'''    )
								lowercase__  					=     UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny'''    ).to(lowerCamelCase    )

								lowercase__  					=     prepare_img()
								lowercase__  					=     processor(images=lowerCamelCase,    return_tensors='''pt'''    ).to(lowerCamelCase    )

								with torch.no_grad():
												lowercase__  					=     model(**lowerCamelCase    )

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

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




				def 							lowercase__  (	self		:       Tuple    ):

								'''simple docstring'''
								lowercase__  					=     AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny'''    )
								lowercase__  					=     UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny'''    ).to(lowerCamelCase    )

								lowercase__  					=     prepare_img()
								lowercase__  					=     processor(images=lowerCamelCase,    return_tensors='''pt'''    ).to(lowerCamelCase    )

								with torch.no_grad():
												lowercase__  					=     model(**lowerCamelCase    )

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

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












import importlib.metadata
import operator
import re
import sys
from typing import Optional

from packaging import version


A__      :     Tuple       =					{
    '<': operator.lt,
    '<=': operator.le,
    '==': operator.eq,
    '!=': operator.ne,
    '>=': operator.ge,
    '>': operator.gt,
}






def     a     (		lowerCamelCase_						,  lowerCamelCase_						,  lowerCamelCase_						,  lowerCamelCase_						,  lowerCamelCase_						,  lowerCamelCase_							):






				'''simple docstring'''
				if got_ver is None or want_ver is None:
								raise ValueError(
								    F"""Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider"""
								    F""" reinstalling {pkg}."""							)
				if not ops[op](version.parse(lowerCamelCase_							)						,  version.parse(lowerCamelCase_							)							):
								raise ImportError(
								    F"""{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}"""							)






def     a     (		lowerCamelCase_						,  lowerCamelCase_ = None							):






				'''simple docstring'''
				lowercase__  					=     F"""\n{hint}""" if hint is not None else ''''''

				# non-versioned check
				if re.match(r'''^[\w_\-\d]+$'''						,  lowerCamelCase_							):
								lowercase__					,		lowercase__					,		lowercase__  					=     requirement, None, None
				else:
								lowercase__  					=     re.findall(r'''^([^!=<>\s]+)([\s!=<>]{1,2}.+)'''						,  lowerCamelCase_							)
								if not match:
												raise ValueError(
												    '''requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but'''
												    F""" got {requirement}"""							)
								lowercase__					,		lowercase__  					=     match[0]
								lowercase__  					=     want_full.split(''','''							)  # there could be multiple requirements
								lowercase__  					=     {}
								for w in want_range:
												lowercase__  					=     re.findall(r'''^([\s!=<>]{1,2})(.+)'''						,  lowerCamelCase_							)
												if not match:
																raise ValueError(
																    '''requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,'''
																    F""" but got {requirement}"""							)
												lowercase__					,		lowercase__  					=     match[0]
												lowercase__  					=     want_ver
												if op not in ops:
																raise ValueError(F"""{requirement}: need one of {list(ops.keys()							)}, but got {op}"""							)

    # special case
				if pkg == "python":
								lowercase__  					=     '''.'''.join([str(lowerCamelCase_							) for x in sys.version_info[:3]]							)
								for op, want_ver in wanted.items():
												_compare_versions(lowerCamelCase_						,  lowerCamelCase_						,  lowerCamelCase_						,  lowerCamelCase_						,  lowerCamelCase_						,  lowerCamelCase_							)
								return

				# check if any version is installed
				try:
								lowercase__  					=     importlib.metadata.version(lowerCamelCase_							)
				except importlib.metadata.PackageNotFoundError:
								raise importlib.metadata.PackageNotFoundError(
								    F"""The '{requirement}' distribution was not found and is required by this application. {hint}"""							)

				# check that the right version is installed if version number or a range was provided
				if want_ver is not None:
								for op, want_ver in wanted.items():
												_compare_versions(lowerCamelCase_						,  lowerCamelCase_						,  lowerCamelCase_						,  lowerCamelCase_						,  lowerCamelCase_						,  lowerCamelCase_							)






def     a     (		lowerCamelCase_							):






				'''simple docstring'''
				lowercase__  					=     '''Try: pip install transformers -U or pip install -e \'.[dev]\' if you\'re working with git main'''
				return require_version(lowerCamelCase_						,  lowerCamelCase_							)




