



"""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 PoolFormerImageProcessor

class  __SCREAMING_SNAKE_CASE			(   unittest.TestCase     ):


					'''simple docstring'''





					def __init__( self							:						int,						lowerCamelCase							:						Optional[Any],						lowerCamelCase							:						List[str]=7,						lowerCamelCase							:						Optional[Any]=3,						lowerCamelCase							:						Any=30,						lowerCamelCase							:						Dict=400,						lowerCamelCase							:						Optional[int]=True,						lowerCamelCase							:						int=None,						lowerCamelCase							:						int=0.9,						lowerCamelCase							:						Optional[int]=None,						lowerCamelCase							:						List[Any]=True,						lowerCamelCase							:						Union[str, Any]=[0.5, 0.5, 0.5],						lowerCamelCase							:						Union[str, Any]=[0.5, 0.5, 0.5],						)->      Any:
								lowerCamelCase__	:	str				=size if size is not None else {'''shortest_edge''': 30}
								lowerCamelCase__	:	List[str]				=crop_size if crop_size is not None else {'''height''': 30, '''width''': 30}
								lowerCamelCase__	:	List[Any]				=parent
								lowerCamelCase__	:	Any				=batch_size
								lowerCamelCase__	:	Union[str, Any]				=num_channels
								lowerCamelCase__	:	str				=min_resolution
								lowerCamelCase__	:	int				=max_resolution
								lowerCamelCase__	:	Any				=do_resize_and_center_crop
								lowerCamelCase__	:	Any				=size
								lowerCamelCase__	:	Any				=crop_pct
								lowerCamelCase__	:	Optional[Any]				=crop_size
								lowerCamelCase__	:	int				=do_normalize
								lowerCamelCase__	:	Union[str, Any]				=image_mean
								lowerCamelCase__	:	int				=image_std




					def 	snake_case ( self							:						Optional[Any]  )->      Any:
								return {
								    "size": self.size,
								    "do_resize_and_center_crop": self.do_resize_and_center_crop,
								    "crop_pct": self.crop_pct,
								    "crop_size": self.crop_size,
								    "do_normalize": self.do_normalize,
								    "image_mean": self.image_mean,
								    "image_std": self.image_std,
								}





@require_torch
@require_vision
class  __SCREAMING_SNAKE_CASE			(   lowerCAmelCase_	,     unittest.TestCase     ):


					'''simple docstring'''





					_a         =							PoolFormerImageProcessor if is_vision_available() else None



					def 	snake_case ( self							:						List[str]  )->      Dict:
								lowerCamelCase__	:	Optional[int]				=PoolFormerImageProcessingTester(self  )



					@property
					def 	snake_case ( self							:						Optional[Any]  )->      Any:
								return self.image_processor_tester.prepare_image_processor_dict()



					def 	snake_case ( self							:						Union[str, Any]  )->      Union[str, Any]:
								lowerCamelCase__	:	int				=self.image_processing_class(**self.image_processor_dict  )
								self.assertTrue(hasattr(lowerCamelCase,						'''do_resize_and_center_crop'''  )  )
								self.assertTrue(hasattr(lowerCamelCase,						'''size'''  )  )
								self.assertTrue(hasattr(lowerCamelCase,						'''crop_pct'''  )  )
								self.assertTrue(hasattr(lowerCamelCase,						'''do_normalize'''  )  )
								self.assertTrue(hasattr(lowerCamelCase,						'''image_mean'''  )  )
								self.assertTrue(hasattr(lowerCamelCase,						'''image_std'''  )  )



					def 	snake_case ( self							:						Optional[int]  )->      str:
								lowerCamelCase__	:	Optional[int]				=self.image_processing_class.from_dict(self.image_processor_dict  )
								self.assertEqual(image_processor.size,						{'''shortest_edge''': 30}  )
								self.assertEqual(image_processor.crop_size,						{'''height''': 30, '''width''': 30}  )

								lowerCamelCase__	:	str				=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 	snake_case ( self							:						Tuple  )->      List[str]:
								pass



					def 	snake_case ( self							:						Dict  )->      Tuple:
								# Initialize image_processing
								lowerCamelCase__	:	int				=self.image_processing_class(**self.image_processor_dict  )
								# create random PIL images
								lowerCamelCase__	:	Optional[Any]				=prepare_image_inputs(self.image_processor_tester,						equal_resolution=lowerCamelCase  )
								for image in image_inputs:
											self.assertIsInstance(lowerCamelCase,						Image.Image  )

								# Test not batched input
								lowerCamelCase__	:	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
								lowerCamelCase__	:	Any				=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 	snake_case ( self							:						List[str]  )->      Dict:
								# Initialize image_processing
								lowerCamelCase__	:	str				=self.image_processing_class(**self.image_processor_dict  )
								# create random numpy tensors
								lowerCamelCase__	:	Optional[int]				=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
								lowerCamelCase__	:	Dict				=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
								lowerCamelCase__	:	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 	snake_case ( self							:						Optional[Any]  )->      List[Any]:
								# Initialize image_processing
								lowerCamelCase__	:	int				=self.image_processing_class(**self.image_processor_dict  )
								# create random PyTorch tensors
								lowerCamelCase__	:	List[Any]				=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
								lowerCamelCase__	:	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
								lowerCamelCase__	:	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'''],
								    ),						)









"""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  __SCREAMING_SNAKE_CASE			:


					'''simple docstring'''





					def __init__( self							:						Optional[Any],						lowerCamelCase							:						Tuple,						lowerCamelCase							:						List[str]=13,						lowerCamelCase							:						List[Any]=32,						lowerCamelCase							:						Dict=3,						lowerCamelCase							:						int=4,						lowerCamelCase							:						str=[10, 20, 30, 40],						lowerCamelCase							:						Any=[2, 2, 3, 2],						lowerCamelCase							:						int=True,						lowerCamelCase							:						int=True,						lowerCamelCase							:						str=37,						lowerCamelCase							:						Optional[int]="gelu",						lowerCamelCase							:						Optional[int]=10,						lowerCamelCase							:						Any=0.02,						lowerCamelCase							:						Union[str, Any]=["stage2", "stage3", "stage4"],						lowerCamelCase							:						Optional[int]=3,						lowerCamelCase							:						Tuple=None,						)->      List[str]:
								lowerCamelCase__	:	List[str]				=parent
								lowerCamelCase__	:	Tuple				=batch_size
								lowerCamelCase__	:	str				=image_size
								lowerCamelCase__	:	Any				=num_channels
								lowerCamelCase__	:	Tuple				=num_stages
								lowerCamelCase__	:	List[str]				=hidden_sizes
								lowerCamelCase__	:	Any				=depths
								lowerCamelCase__	:	Union[str, Any]				=is_training
								lowerCamelCase__	:	Tuple				=use_labels
								lowerCamelCase__	:	int				=intermediate_size
								lowerCamelCase__	:	Optional[int]				=hidden_act
								lowerCamelCase__	:	Dict				=type_sequence_label_size
								lowerCamelCase__	:	Tuple				=initializer_range
								lowerCamelCase__	:	Any				=out_features
								lowerCamelCase__	:	Tuple				=num_labels
								lowerCamelCase__	:	Optional[int]				=scope
								lowerCamelCase__	:	Optional[int]				=num_stages



					def 	snake_case ( self							:						str  )->      Optional[int]:
								lowerCamelCase__	:	str				=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

								lowerCamelCase__	:	Tuple				=None
								if self.use_labels:
											lowerCamelCase__	:	Union[str, Any]				=ids_tensor([self.batch_size],						self.type_sequence_label_size  )

								lowerCamelCase__	:	int				=self.get_config()

								return config, pixel_values, labels



					def 	snake_case ( self							:						Union[str, Any]  )->      Any:
								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							:						Union[str, Any]  )->      Any:
								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 	snake_case ( self							:						int,						lowerCamelCase							:						str,						lowerCamelCase							:						List[str],						lowerCamelCase							:						List[Any]  )->      Tuple:
								lowerCamelCase__	:	List[str]				=UperNetForSemanticSegmentation(config=lowerCamelCase  )
								model.to(lowerCamelCase  )
								model.eval()
								lowerCamelCase__	:	int				=model(lowerCamelCase  )
								self.parent.assertEqual(
								    result.logits.shape,						(self.batch_size, self.num_labels, self.image_size, self.image_size)  )




					def 	snake_case ( self							:						Any  )->      Tuple:
								lowerCamelCase__	:	Dict				=self.prepare_config_and_inputs()
								(
								    (
								    lowerCamelCase__
								)			,     (
								    lowerCamelCase__
								)			,     (
								    lowerCamelCase__
								)			,     
								)	:	Any				=config_and_inputs
								lowerCamelCase__	:	Optional[int]				={'''pixel_values''': pixel_values}
								return config, inputs_dict





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


					'''simple docstring'''





					_a         =							(UperNetForSemanticSegmentation,) if is_torch_available() else ()
					_a         =							{'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {}
					_a         =							False
					_a         =							False
					_a         =							False
					_a         =							False
					_a         =							False
					_a         =							False



					def 	snake_case ( self							:						Optional[int]  )->      Optional[int]:
								lowerCamelCase__	:	Optional[Any]				=UperNetModelTester(self  )
								lowerCamelCase__	:	Union[str, Any]				=ConfigTester(self,						config_class=lowerCamelCase,						has_text_modality=lowerCamelCase,						hidden_size=37  )



					def 	snake_case ( self							:						Optional[int]  )->      Optional[int]:
								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							:						List[str]  )->      Dict:
								return



					def 	snake_case ( self							:						Optional[int]  )->      List[str]:
								lowerCamelCase__			,     lowerCamelCase__	:	str				=self.model_tester.prepare_config_and_inputs_for_common()

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

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



					def 	snake_case ( self							:						Any  )->      Union[str, Any]:
								lowerCamelCase__	:	Dict				=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 	snake_case ( self							:						Optional[Any]  )->      List[Any]:
								pass



					@unittest.skip(reason='''UperNet does not support input and output embeddings'''  )
					def 	snake_case ( self							:						Any  )->      List[str]:
								pass



					@unittest.skip(reason='''UperNet does not have a base model'''  )
					def 	snake_case ( self							:						int  )->      Any:
								pass



					@unittest.skip(reason='''UperNet does not have a base model'''  )
					def 	snake_case ( self							:						Dict  )->      str:
								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							:						List[Any]  )->      List[str]:
								pass



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



					def 	snake_case ( self							:						Optional[int]  )->      List[str]:
								def check_hidden_states_output(lowerCamelCase							:						Dict,						lowerCamelCase							:						int,						lowerCamelCase							:						List[str]  ):
											lowerCamelCase__	:	Union[str, Any]				=model_class(lowerCamelCase  )
											model.to(lowerCamelCase  )
											model.eval()

											with torch.no_grad():
														lowerCamelCase__	:	Optional[Any]				=model(**self._prepare_for_class(lowerCamelCase,						lowerCamelCase  )  )

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

											lowerCamelCase__	:	List[str]				=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],						)

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

								for model_class in self.all_model_classes:
											lowerCamelCase__	:	Optional[int]				=True
											check_hidden_states_output(lowerCamelCase,						lowerCamelCase,						lowerCamelCase  )

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

											check_hidden_states_output(lowerCamelCase,						lowerCamelCase,						lowerCamelCase  )



					def 	snake_case ( self							:						Any  )->      List[Any]:
								lowerCamelCase__			,     lowerCamelCase__	:	Optional[int]				=self.model_tester.prepare_config_and_inputs_for_common()

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




					@slow
					def 	snake_case ( self							:						int  )->      Union[str, Any]:
								for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											lowerCamelCase__	:	str				=UperNetForSemanticSegmentation.from_pretrained(lowerCamelCase  )
											self.assertIsNotNone(lowerCamelCase  )






def   snake_case__     (	):
			"""simple docstring"""
			lowerCamelCase__	:	Optional[int]				=hf_hub_download(
			    repo_id='''hf-internal-testing/fixtures_ade20k'''							,	repo_type='''dataset'''							,	filename='''ADE_val_00000001.jpg'''			)
			lowerCamelCase__	:	List[str]				=Image.open(__lowerCamelCase			).convert('''RGB'''			)
			return image

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


					'''simple docstring'''





					def 	snake_case ( self							:						str  )->      Union[str, Any]:
								lowerCamelCase__	:	List[Any]				=AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny'''  )
								lowerCamelCase__	:	List[Any]				=UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny'''  ).to(lowerCamelCase  )

								lowerCamelCase__	:	List[Any]				=prepare_img()
								lowerCamelCase__	:	List[Any]				=processor(images=lowerCamelCase,						return_tensors='''pt'''  ).to(lowerCamelCase  )

								with torch.no_grad():
											lowerCamelCase__	:	List[Any]				=model(**lowerCamelCase  )

								lowerCamelCase__	:	Optional[int]				=torch.Size((1, model.config.num_labels, 512, 512)  )
								self.assertEqual(outputs.logits.shape,						lowerCamelCase  )

								lowerCamelCase__	:	Dict				=torch.tensor(
								    [[-7.5_958, -7.5_958, -7.4_302], [-7.5_958, -7.5_958, -7.4_302], [-7.4_797, -7.4_797, -7.3_068]]  ).to(lowerCamelCase  )
								self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3],						lowerCamelCase,						atol=1E-4  )  )




					def 	snake_case ( self							:						Optional[int]  )->      Optional[Any]:
								lowerCamelCase__	:	str				=AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny'''  )
								lowerCamelCase__	:	Tuple				=UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny'''  ).to(lowerCamelCase  )

								lowerCamelCase__	:	Dict				=prepare_img()
								lowerCamelCase__	:	Any				=processor(images=lowerCamelCase,						return_tensors='''pt'''  ).to(lowerCamelCase  )

								with torch.no_grad():
											lowerCamelCase__	:	Any				=model(**lowerCamelCase  )

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

								lowerCamelCase__	:	List[str]				=torch.tensor(
								    [[-8.8_110, -8.8_110, -8.6_521], [-8.8_110, -8.8_110, -8.6_521], [-8.7_746, -8.7_746, -8.6_130]]  ).to(lowerCamelCase  )
								self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3],						lowerCamelCase,						atol=1E-4  )  )




