

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







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







				def  lowerCamelCase_	(       self     :		Union[str, Any]   ):
										'''simple docstring'''
										lowercase :							List[str]    		=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

										lowercase :							str    		=self.get_config()

										return config, pixel_values, labels







				def  lowerCamelCase_	(       self     :		Optional[Any]   ):
										'''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  lowerCamelCase_	(       self     :		int   ):
										'''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  lowerCamelCase_	(       self     :		Dict		,					UpperCAmelCase__     :		str		,					UpperCAmelCase__     :		Any		,					UpperCAmelCase__     :		Optional[Any]   ):
										'''simple docstring'''
										lowercase :							Tuple    		=UperNetForSemanticSegmentation(config=UpperCAmelCase__   )
										model.to(UpperCAmelCase__   )
										model.eval()
										lowercase :							Any    		=model(UpperCAmelCase__   )
										self.parent.assertEqual(
										    result.logits.shape		,					(self.batch_size, self.num_labels, self.image_size, self.image_size)   )







				def  lowerCamelCase_	(       self     :		Optional[Any]   ):
										'''simple docstring'''
										lowercase :							int    		=self.prepare_config_and_inputs()
										(
										    (
										    lowercase
										)		,	(
										    lowercase
										)		,	(
										    lowercase
										)		,	
										) :							Dict    		=config_and_inputs
										lowercase :							Optional[Any]    		={'''pixel_values''': pixel_values}
										return config, inputs_dict





@require_torch
class 		__SCREAMING_SNAKE_CASE							(			lowercase__						,							lowercase__						,							unittest.TestCase      ):
				lowerCamelCase_		       =    (UperNetForSemanticSegmentation,) if is_torch_available() else ()
				lowerCamelCase_		       =    {'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {}
				lowerCamelCase_		       =    False
				lowerCamelCase_		       =    False
				lowerCamelCase_		       =    False
				lowerCamelCase_		       =    False
				lowerCamelCase_		       =    False
				lowerCamelCase_		       =    False







				def  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										lowercase :							int    		=UperNetModelTester(self   )
										lowercase :							Optional[int]    		=ConfigTester(self		,					config_class=UpperCAmelCase__		,					has_text_modality=UpperCAmelCase__		,					hidden_size=37   )







				def  lowerCamelCase_	(       self     :		Union[str, Any]   ):
										'''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  lowerCamelCase_	(       self     :		Union[str, Any]   ):
										'''simple docstring'''
										return







				def  lowerCamelCase_	(       self     :		Any   ):
										'''simple docstring'''
										lowercase		,	lowercase :							str    		=self.model_tester.prepare_config_and_inputs_for_common()

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

																lowercase :							str    		=['''pixel_values''']
																self.assertListEqual(arg_names[:1]		,					UpperCAmelCase__   )







				def  lowerCamelCase_	(       self     :		Tuple   ):
										'''simple docstring'''
										lowercase :							Optional[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  lowerCamelCase_	(       self     :		int   ):
										'''simple docstring'''
										pass







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







				@unittest.skip(reason='''UperNet does not have a base model'''   )
				def  lowerCamelCase_	(       self     :		List[Any]   ):
										'''simple docstring'''
										pass







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







				@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''   )
				def  lowerCamelCase_	(       self     :		Union[str, Any]   ):
										'''simple docstring'''
										pass







				def  lowerCamelCase_	(       self     :		int   ):
										'''simple docstring'''
										def check_hidden_states_output(UpperCAmelCase__     :		List[Any]		,					UpperCAmelCase__     :		Any		,					UpperCAmelCase__     :		Tuple   ):
																lowercase :							Optional[int]    		=model_class(UpperCAmelCase__   )
																model.to(UpperCAmelCase__   )
																model.eval()

																with torch.no_grad():
																						lowercase :							Union[str, Any]    		=model(**self._prepare_for_class(UpperCAmelCase__		,					UpperCAmelCase__   )   )

																lowercase :							Optional[int]    		=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																lowercase :							str    		=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]		,					)

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

										for model_class in self.all_model_classes:
																lowercase :							Dict    		=True
																check_hidden_states_output(UpperCAmelCase__		,					UpperCAmelCase__		,					UpperCAmelCase__   )

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

																check_hidden_states_output(UpperCAmelCase__		,					UpperCAmelCase__		,					UpperCAmelCase__   )







				def  lowerCamelCase_	(       self     :		Optional[int]   ):
										'''simple docstring'''
										lowercase		,	lowercase :							Optional[int]    		=self.model_tester.prepare_config_and_inputs_for_common()

										lowercase :							int    		=_config_zero_init(UpperCAmelCase__   )
										lowercase :							List[Any]    		=_config_zero_init(configs_no_init.backbone_config   )
										for model_class in self.all_model_classes:
																lowercase :							List[str]    		=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  lowerCamelCase_	(       self     :		Dict   ):
										'''simple docstring'''
										pass







				@slow
				def  lowerCamelCase_	(       self     :		Any   ):
										'''simple docstring'''
										for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																lowercase :							str    		=UperNetForSemanticSegmentation.from_pretrained(UpperCAmelCase__   )
																self.assertIsNotNone(UpperCAmelCase__   )






def 				_lowerCAmelCase			(   )				->  str:
						lowercase :							str    		=hf_hub_download(
						    repo_id='''hf-internal-testing/fixtures_ade20k'''   , repo_type='''dataset'''   , filename='''ADE_val_00000001.jpg'''						)
						lowercase :							str    		=Image.open(__magic_name__						).convert('''RGB'''						)
						return image







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







				def  lowerCamelCase_	(       self     :		Any   ):
										'''simple docstring'''
										lowercase :							Tuple    		=AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny'''   )
										lowercase :							int    		=UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny'''   ).to(UpperCAmelCase__   )

										lowercase :							Dict    		=prepare_img()
										lowercase :							List[str]    		=processor(images=UpperCAmelCase__		,					return_tensors='''pt'''   ).to(UpperCAmelCase__   )

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

										lowercase :							Tuple    		=torch.Size((1, model.config.num_labels, 512, 512)   )
										self.assertEqual(outputs.logits.shape		,					UpperCAmelCase__   )

										lowercase :							int    		=torch.tensor(
										    [[-7.59_58, -7.59_58, -7.43_02], [-7.59_58, -7.59_58, -7.43_02], [-7.47_97, -7.47_97, -7.30_68]]   ).to(UpperCAmelCase__   )
										self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]		,					UpperCAmelCase__		,					atol=1E-4   )   )







				def  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										lowercase :							Dict    		=AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny'''   )
										lowercase :							Optional[int]    		=UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny'''   ).to(UpperCAmelCase__   )

										lowercase :							Optional[int]    		=prepare_img()
										lowercase :							Dict    		=processor(images=UpperCAmelCase__		,					return_tensors='''pt'''   ).to(UpperCAmelCase__   )

										with torch.no_grad():
																lowercase :							Any    		=model(**UpperCAmelCase__   )

										lowercase :							int    		=torch.Size((1, model.config.num_labels, 512, 512)   )
										self.assertEqual(outputs.logits.shape		,					UpperCAmelCase__   )

										lowercase :							List[str]    		=torch.tensor(
										    [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]]   ).to(UpperCAmelCase__   )
										self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]		,					UpperCAmelCase__		,					atol=1E-4   )   )






'''simple docstring'''




from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__UpperCAmelCase					=logging.get_logger(__name__)

__UpperCAmelCase					={
    "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json",
    # See all LeViT models at https://huggingface.co/models?filter=levit
}




class        a__ (  UpperCAmelCase__					):
     lowerCamelCase    :	Optional[Any]				="levit"






     def __init__(					self						:						Optional[int]    ,							a						:						int=2_24    ,							a						:						Union[str, Any]=3    ,							a						:						List[Any]=3    ,							a						:						Dict=2    ,							a						:						Tuple=1    ,							a						:						Optional[int]=16    ,							a						:						Optional[Any]=[1_28, 2_56, 3_84]    ,							a						:						Dict=[4, 8, 12]    ,							a						:						Optional[Any]=[4, 4, 4]    ,							a						:						Optional[int]=[16, 16, 16]    ,							a						:						Any=0    ,							a						:						List[Any]=[2, 2, 2]    ,							a						:						Optional[Any]=[2, 2, 2]    ,							a						:						Union[str, Any]=0.02    ,							**a						:						Optional[int]    ,							):





         """simple docstring"""



         super().__init__(**a       )
         __lowerCamelCase            =    image_size
         __lowerCamelCase            =    num_channels
         __lowerCamelCase            =    kernel_size
         __lowerCamelCase            =    stride
         __lowerCamelCase            =    padding
         __lowerCamelCase            =    hidden_sizes
         __lowerCamelCase            =    num_attention_heads
         __lowerCamelCase            =    depths
         __lowerCamelCase            =    key_dim
         __lowerCamelCase            =    drop_path_rate
         __lowerCamelCase            =    patch_size
         __lowerCamelCase            =    attention_ratio
         __lowerCamelCase            =    mlp_ratio
         __lowerCamelCase            =    initializer_range
         __lowerCamelCase            =    [
             ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
             ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
         ]




class        a__ (  UpperCAmelCase__					):
     lowerCamelCase    :	Tuple				=version.parse("1.11"					)






     @property
     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[int]       ):





         """simple docstring"""



         return OrderedDict(
             [
                 ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
             ]       )






     @property
     def   SCREAMING_SNAKE_CASE__  (					self						:						Union[str, Any]       ):





         """simple docstring"""



         return 1e-4
