



'''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 							lowercase__     :





	def __init__(			self :    int			,lowerCamelCase__ :    Optional[int]			,lowerCamelCase__ :    Union[str, Any]=13			,lowerCamelCase__ :    Union[str, Any]=32			,lowerCamelCase__ :    Dict=3			,lowerCamelCase__ :    Dict=4			,lowerCamelCase__ :    Any=[10, 20, 30, 40]			,lowerCamelCase__ :    Any=[2, 2, 3, 2]			,lowerCamelCase__ :    Union[str, Any]=True			,lowerCamelCase__ :    int=True			,lowerCamelCase__ :    Dict=37			,lowerCamelCase__ :    Union[str, Any]="gelu"			,lowerCamelCase__ :    int=10			,lowerCamelCase__ :    Dict=0.0_2			,lowerCamelCase__ :    List[str]=["stage2", "stage3", "stage4"]			,lowerCamelCase__ :    List[Any]=3			,lowerCamelCase__ :    List[str]=None			,):







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





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







							'''simple docstring'''
							_UpperCamelCase :		str			    =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

							_UpperCamelCase :		List[Any]			    =       None
							if self.use_labels:
													_UpperCamelCase :		str			    =       ids_tensor([self.batch_size]			,self.type_sequence_label_size			)

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

							return config, pixel_values, labels





	def      UpperCamelCase_  (			self :    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      UpperCamelCase_  (			self :    Dict			):







							'''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 :    int			,lowerCamelCase__ :    Any			,lowerCamelCase__ :    List[str]			,lowerCamelCase__ :    Union[str, Any]			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[int]			    =       UperNetForSemanticSegmentation(config=__A			)
							model.to(__A			)
							model.eval()
							_UpperCamelCase :		Union[str, Any]			    =       model(__A			)
							self.parent.assertEqual(
							    result.logits.shape			,(self.batch_size, self.num_labels, self.image_size, self.image_size)			)





	def      UpperCamelCase_  (			self :    Tuple			):







							'''simple docstring'''
							_UpperCamelCase :		Dict			    =       self.prepare_config_and_inputs()
							(
							    _UpperCamelCase						
							) :		List[Any]			    =       config_and_inputs
							_UpperCamelCase :		str			    =       {'''pixel_values''': pixel_values}
							return config, inputs_dict






@require_torch
class 							lowercase__     (							lowerCamelCase__						, lowerCamelCase__						, unittest.TestCase       ):
	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      UpperCamelCase_  (			self :    Optional[Any]			):







							'''simple docstring'''
							_UpperCamelCase :		List[str]			    =       UperNetModelTester(self			)
							_UpperCamelCase :		Tuple			    =       ConfigTester(self			,config_class=__A			,has_text_modality=__A			,hidden_size=37			)





	def      UpperCamelCase_  (			self :    Optional[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      UpperCamelCase_  (			self :    Union[str, Any]			):







							'''simple docstring'''
							return





	def      UpperCamelCase_  (			self :    Optional[int]			):







							'''simple docstring'''
							_UpperCamelCase :		int			    =       self.model_tester.prepare_config_and_inputs_for_common()

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

													_UpperCamelCase :		List[Any]			    =       ['''pixel_values''']
													self.assertListEqual(arg_names[:1]			,__A			)





	def      UpperCamelCase_  (			self :    str			):







							'''simple docstring'''
							_UpperCamelCase :		int			    =       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 :    Optional[int]			):







							'''simple docstring'''
							pass





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







							'''simple docstring'''
							pass





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







							'''simple docstring'''
							pass





	@unittest.skip(reason='UperNet does not have a base model'			)
	def      UpperCamelCase_  (			self :    Union[str, Any]			):







							'''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 :    Optional[Any]			):







							'''simple docstring'''
							pass





	@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'			)
	def      UpperCamelCase_  (			self :    Optional[int]			):







							'''simple docstring'''
							pass





	def      UpperCamelCase_  (			self :    int			):







							'''simple docstring'''
							def check_hidden_states_output(lowerCamelCase__ :    Optional[int]			,lowerCamelCase__ :    Union[str, Any]			,lowerCamelCase__ :    Tuple			):
													_UpperCamelCase :		Union[str, Any]			    =       model_class(__A			)
													model.to(__A			)
													model.eval()

													with torch.no_grad():
																			_UpperCamelCase :		str			    =       model(**self._prepare_for_class(__A			,__A			)			)

													_UpperCamelCase :		List[str]			    =       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 :		List[str]			    =       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_UpperCamelCase :		Optional[Any]			    =       True
													check_hidden_states_output(__A			,__A			,__A			)

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													_UpperCamelCase :		Tuple			    =       True

													check_hidden_states_output(__A			,__A			,__A			)





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







							'''simple docstring'''
							_UpperCamelCase :		Union[str, Any]			    =       self.model_tester.prepare_config_and_inputs_for_common()

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







							'''simple docstring'''
							pass





	@slow
	def      UpperCamelCase_  (			self :    Any			):







							'''simple docstring'''
							for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_UpperCamelCase :		List[Any]			    =       UperNetForSemanticSegmentation.from_pretrained(__A			)
													self.assertIsNotNone(__A			)






def A__   (					):
						_UpperCamelCase :		Tuple			    =       hf_hub_download(
						    repo_id='hf-internal-testing/fixtures_ade20k'  ,  repo_type='dataset'  ,  filename='ADE_val_00000001.jpg'							)
						_UpperCamelCase :		str			    =       Image.open(UpperCAmelCase_							).convert('RGB'							)
						return image






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





	def      UpperCamelCase_  (			self :    Dict			):







							'''simple docstring'''
							_UpperCamelCase :		int			    =       AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'			)
							_UpperCamelCase :		Union[str, Any]			    =       UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'			).to(__A			)

							_UpperCamelCase :		Optional[Any]			    =       prepare_img()
							_UpperCamelCase :		Tuple			    =       processor(images=__A			,return_tensors='pt'			).to(__A			)

							with torch.no_grad():
													_UpperCamelCase :		Union[str, Any]			    =       model(**__A			)

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

							_UpperCamelCase :		Union[str, Any]			    =       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      UpperCamelCase_  (			self :    Union[str, Any]			):







							'''simple docstring'''
							_UpperCamelCase :		List[str]			    =       AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny'			)
							_UpperCamelCase :		List[Any]			    =       UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny'			).to(__A			)

							_UpperCamelCase :		Any			    =       prepare_img()
							_UpperCamelCase :		Dict			    =       processor(images=__A			,return_tensors='pt'			).to(__A			)

							with torch.no_grad():
													_UpperCamelCase :		Tuple			    =       model(**__A			)

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

							_UpperCamelCase :		Dict			    =       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'''
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
					import torch

if is_vision_available():
					from PIL import Image

					from transformers import MobileViTImageProcessor






class 							lowercase__     (							unittest.TestCase       ):





	def __init__(			self :    List[str]			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    Tuple=7			,lowerCamelCase__ :    Tuple=3			,lowerCamelCase__ :    Any=18			,lowerCamelCase__ :    Tuple=30			,lowerCamelCase__ :    Tuple=400			,lowerCamelCase__ :    int=True			,lowerCamelCase__ :    int=None			,lowerCamelCase__ :    str=True			,lowerCamelCase__ :    str=None			,lowerCamelCase__ :    Any=True			,):







							'''simple docstring'''
							_UpperCamelCase :		Any			    =       size if size is not None else {'shortest_edge': 20}
							_UpperCamelCase :		int			    =       crop_size if crop_size is not None else {'height': 18, 'width': 18}
							_UpperCamelCase :		List[str]			    =       parent
							_UpperCamelCase :		List[Any]			    =       batch_size
							_UpperCamelCase :		int			    =       num_channels
							_UpperCamelCase :		Optional[int]			    =       image_size
							_UpperCamelCase :		List[Any]			    =       min_resolution
							_UpperCamelCase :		List[str]			    =       max_resolution
							_UpperCamelCase :		int			    =       do_resize
							_UpperCamelCase :		Optional[int]			    =       size
							_UpperCamelCase :		str			    =       do_center_crop
							_UpperCamelCase :		List[Any]			    =       crop_size
							_UpperCamelCase :		Optional[Any]			    =       do_flip_channel_order





	def      UpperCamelCase_  (			self :    Optional[Any]			):







							'''simple docstring'''
							return {
							    "do_resize": self.do_resize,
							    "size": self.size,
							    "do_center_crop": self.do_center_crop,
							    "crop_size": self.crop_size,
							    "do_flip_channel_order": self.do_flip_channel_order,
							}






@require_torch
@require_vision
class 							lowercase__     (							lowercase						, unittest.TestCase       ):
	lowercase__      =      MobileViTImageProcessor if is_vision_available() else None





	def      UpperCamelCase_  (			self :    Optional[Any]			):







							'''simple docstring'''
							_UpperCamelCase :		Tuple			    =       MobileViTImageProcessingTester(self			)





	@property
	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							return self.image_processor_tester.prepare_image_processor_dict()





	def      UpperCamelCase_  (			self :    Any			):







							'''simple docstring'''
							_UpperCamelCase :		Any			    =       self.image_processing_class(**self.image_processor_dict			)
							self.assertTrue(hasattr(lowerCamelCase__			,'do_resize'			)			)
							self.assertTrue(hasattr(lowerCamelCase__			,'size'			)			)
							self.assertTrue(hasattr(lowerCamelCase__			,'do_center_crop'			)			)
							self.assertTrue(hasattr(lowerCamelCase__			,'center_crop'			)			)
							self.assertTrue(hasattr(lowerCamelCase__			,'do_flip_channel_order'			)			)





	def      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''
							_UpperCamelCase :		Tuple			    =       self.image_processing_class.from_dict(self.image_processor_dict			)
							self.assertEqual(image_processor.size			,{'shortest_edge': 20}			)
							self.assertEqual(image_processor.crop_size			,{'height': 18, 'width': 18}			)

							_UpperCamelCase :		Union[str, Any]			    =       self.image_processing_class.from_dict(self.image_processor_dict			,size=42			,crop_size=84			)
							self.assertEqual(image_processor.size			,{'shortest_edge': 42}			)
							self.assertEqual(image_processor.crop_size			,{'height': 84, 'width': 84}			)





	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							pass





	def      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''
							# Initialize image_processing
							_UpperCamelCase :		int			    =       self.image_processing_class(**self.image_processor_dict			)
							# create random PIL images
							_UpperCamelCase :		int			    =       prepare_image_inputs(self.image_processor_tester			,equal_resolution=lowerCamelCase__			)
							for image in image_inputs:
													self.assertIsInstance(lowerCamelCase__			,Image.Image			)

							# Test not batched input
							_UpperCamelCase :		Optional[Any]			    =       image_processing(image_inputs[0]			,return_tensors='pt'			).pixel_values
							self.assertEqual(
							    encoded_images.shape			,(
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size['height'],
							        self.image_processor_tester.crop_size['width'],
							    )			,)

							# Test batched
							_UpperCamelCase :		int			    =       image_processing(lowerCamelCase__			,return_tensors='pt'			).pixel_values
							self.assertEqual(
							    encoded_images.shape			,(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size['height'],
							        self.image_processor_tester.crop_size['width'],
							    )			,)





	def      UpperCamelCase_  (			self :    Dict			):







							'''simple docstring'''
							# Initialize image_processing
							_UpperCamelCase :		int			    =       self.image_processing_class(**self.image_processor_dict			)
							# create random numpy tensors
							_UpperCamelCase :		List[Any]			    =       prepare_image_inputs(self.image_processor_tester			,equal_resolution=lowerCamelCase__			,numpify=lowerCamelCase__			)
							for image in image_inputs:
													self.assertIsInstance(lowerCamelCase__			,np.ndarray			)

							# Test not batched input
							_UpperCamelCase :		Optional[int]			    =       image_processing(image_inputs[0]			,return_tensors='pt'			).pixel_values
							self.assertEqual(
							    encoded_images.shape			,(
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size['height'],
							        self.image_processor_tester.crop_size['width'],
							    )			,)

							# Test batched
							_UpperCamelCase :		List[str]			    =       image_processing(lowerCamelCase__			,return_tensors='pt'			).pixel_values
							self.assertEqual(
							    encoded_images.shape			,(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size['height'],
							        self.image_processor_tester.crop_size['width'],
							    )			,)





	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							# Initialize image_processing
							_UpperCamelCase :		Optional[Any]			    =       self.image_processing_class(**self.image_processor_dict			)
							# create random PyTorch tensors
							_UpperCamelCase :		str			    =       prepare_image_inputs(self.image_processor_tester			,equal_resolution=lowerCamelCase__			,torchify=lowerCamelCase__			)
							for image in image_inputs:
													self.assertIsInstance(lowerCamelCase__			,torch.Tensor			)

							# Test not batched input
							_UpperCamelCase :		str			    =       image_processing(image_inputs[0]			,return_tensors='pt'			).pixel_values
							self.assertEqual(
							    encoded_images.shape			,(
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size['height'],
							        self.image_processor_tester.crop_size['width'],
							    )			,)

							# Test batched
							_UpperCamelCase :		Optional[int]			    =       image_processing(lowerCamelCase__			,return_tensors='pt'			).pixel_values
							self.assertEqual(
							    encoded_images.shape			,(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size['height'],
							        self.image_processor_tester.crop_size['width'],
							    )			,)


