



'''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        UpperCAmelCase_			:
    """simple docstring"""







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




    def lowerCamelCase			(       self   :	Dict		):
          snake_case__    :       Tuple       		= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

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

          return config, pixel_values, labels




    def lowerCamelCase			(       self   :	Union[str, 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 lowerCamelCase			(       self   :	Union[str, Any]		):
          return UperNetConfig(
              backbone_config=self.get_backbone_config()					,	hidden_size=512					,	pool_scales=[1, 2, 3, 6]					,	use_auxiliary_head=__lowercase					,	auxiliary_loss_weight=0.4					,	auxiliary_in_channels=40					,	auxiliary_channels=256					,	auxiliary_num_convs=1					,	auxiliary_concat_input=__lowercase					,	loss_ignore_index=255					,	num_labels=self.num_labels					,	)




    def lowerCamelCase			(       self   :	Optional[int]					,	snake_case_   :	Tuple					,	snake_case_   :	Union[str, Any]					,	snake_case_   :	int		):
          snake_case__    :       int       		= UperNetForSemanticSegmentation(config=__lowercase		)
          model.to(__lowercase		)
          model.eval()
          snake_case__    :       Optional[int]       		= model(__lowercase		)
          self.parent.assertEqual(
              result.logits.shape					,	(self.batch_size, self.num_labels, self.image_size, self.image_size)		)




    def lowerCamelCase			(       self   :	Optional[Any]		):
          snake_case__    :       Optional[int]       		= self.prepare_config_and_inputs()
          (
              (
              snake_case__ 
          )		,							(
              snake_case__ 
          )		,							(
              snake_case__ 
          )		,							 
          )    :       List[str]       		= config_and_inputs
          snake_case__    :       str       		= {"""pixel_values""": pixel_values}
          return config, inputs_dict







@require_torch
class        UpperCAmelCase_			(			UpperCAmelCase__						,						UpperCAmelCase__						,						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 lowerCamelCase			(       self   :	int		):
          snake_case__    :       str       		= UperNetModelTester(self		)
          snake_case__    :       List[Any]       		= ConfigTester(self					,	config_class=__lowercase					,	has_text_modality=__lowercase					,	hidden_size=37		)




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




    def lowerCamelCase			(       self   :	Any		):
          snake_case__		,							snake_case__    :       Optional[Any]       		= self.model_tester.prepare_config_and_inputs_for_common()

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

                snake_case__    :       Dict       		= ["""pixel_values"""]
                self.assertListEqual(arg_names[:1]					,	__lowercase		)




    def lowerCamelCase			(       self   :	Optional[Any]		):
          snake_case__    :       List[Any]       		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*__lowercase		)




    @unittest.skip(reason="""UperNet does not use inputs_embeds"""		)
    def lowerCamelCase			(       self   :	Dict		):
          pass




    @unittest.skip(reason="""UperNet does not support input and output embeddings"""		)
    def lowerCamelCase			(       self   :	Tuple		):
          pass




    @unittest.skip(reason="""UperNet does not have a base model"""		)
    def lowerCamelCase			(       self   :	Any		):
          pass




    @unittest.skip(reason="""UperNet does not have a base model"""		)
    def lowerCamelCase			(       self   :	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 lowerCamelCase			(       self   :	Tuple		):
          pass




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




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






          def check_hidden_states_output(snake_case_   :	int					,	snake_case_   :	Dict					,	snake_case_   :	Dict		):
                snake_case__    :       Union[str, Any]       		= model_class(__lowercase		)
                model.to(__lowercase		)
                model.eval()

                with torch.no_grad():
                      snake_case__    :       int       		= model(**self._prepare_for_class(__lowercase					,	__lowercase		)		)

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

                snake_case__    :       Optional[Any]       		= self.model_tester.num_stages
                self.assertEqual(len(__lowercase		)					,	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]					,	)

          snake_case__		,							snake_case__    :       List[Any]       		= self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                snake_case__    :       List[str]       		= True
                check_hidden_states_output(__lowercase					,	__lowercase					,	__lowercase		)

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

                check_hidden_states_output(__lowercase					,	__lowercase					,	__lowercase		)




    def lowerCamelCase			(       self   :	Union[str, Any]		):
          snake_case__		,							snake_case__    :       Optional[Any]       		= self.model_tester.prepare_config_and_inputs_for_common()

          snake_case__    :       Tuple       		= _config_zero_init(__lowercase		)
          snake_case__    :       int       		= _config_zero_init(configs_no_init.backbone_config		)
          for model_class in self.all_model_classes:
                snake_case__    :       int       		= model_class(config=__lowercase		)
                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   :	Optional[int]		):
          pass




    @slow
    def lowerCamelCase			(       self   :	Tuple		):






          for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                snake_case__    :       Dict       		= UperNetForSemanticSegmentation.from_pretrained(__lowercase		)
                self.assertIsNotNone(__lowercase		)





def 		__snake_case(							)						->					Union[str, Any]:
      snake_case__    :       List[Any]       		= hf_hub_download(
          repo_id="""hf-internal-testing/fixtures_ade20k"""	,  repo_type="""dataset"""	,  filename="""ADE_val_00000001.jpg"""						)
      snake_case__    :       str       		= Image.open(_A						).convert("""RGB"""						)
      return image







@require_torch
@require_vision
@slow
class        UpperCAmelCase_			(			unittest.TestCase      ):
    """simple docstring"""







    def lowerCamelCase			(       self   :	Tuple		):
          snake_case__    :       List[Any]       		= AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny"""		)
          snake_case__    :       Dict       		= UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny"""		).to(__lowercase		)

          snake_case__    :       Tuple       		= prepare_img()
          snake_case__    :       Any       		= processor(images=__lowercase					,	return_tensors="""pt"""		).to(__lowercase		)

          with torch.no_grad():
                snake_case__    :       List[Any]       		= model(**__lowercase		)

          snake_case__    :       List[Any]       		= torch.Size((1, model.config.num_labels, 512, 512)		)
          self.assertEqual(outputs.logits.shape					,	__lowercase		)

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




    def lowerCamelCase			(       self   :	Union[str, Any]		):
          snake_case__    :       str       		= AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny"""		)
          snake_case__    :       Optional[int]       		= UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny"""		).to(__lowercase		)

          snake_case__    :       Any       		= prepare_img()
          snake_case__    :       List[Any]       		= processor(images=__lowercase					,	return_tensors="""pt"""		).to(__lowercase		)

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

          snake_case__    :       str       		= torch.Size((1, model.config.num_labels, 512, 512)		)
          self.assertEqual(outputs.logits.shape					,	__lowercase		)

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






def 		lowerCamelCase__       (						_A	,      _A				):







	'''simple docstring'''





	_validate_point(_A				)
	_validate_point(_A				)
	if len(_A				) != len(_A				):
		raise ValueError("Both points must be in the same n-dimensional space"				)

	return float(sum(abs(a - b				) for a, b in zip(_A	,      _A				)				)				)


def 		lowerCamelCase__       (						_A				):







	'''simple docstring'''





	if point:
		if isinstance(_A	,      _A				):
			for item in point:
				if not isinstance(_A	,      (int, float)				):
					snake_case_						       =	(
					    "Expected a list of numbers as input, found "
					    f"{type(_A				).__name__}"
					)
					raise TypeError(_A				)
		else:
			snake_case_						       =	f"Expected a list of numbers as input, found {type(_A				).__name__}"
			raise TypeError(_A				)
	else:
		raise ValueError("Missing an input"				)


def 		lowerCamelCase__       (						_A	,      _A				):







	'''simple docstring'''





	_validate_point(_A				)
	_validate_point(_A				)
	if len(_A				) != len(_A				):
		raise ValueError("Both points must be in the same n-dimensional space"				)

	return float(sum(abs(x - y				) for x, y in zip(_A	,      _A				)				)				)


if __name__ == "__main__":
		import doctest

		doctest.testmod()
