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







     """simple docstring"""






     def __init__(		self     ,			_lowerCamelCase     ,			_lowerCamelCase=1_3     ,			_lowerCamelCase=3_2     ,			_lowerCamelCase=3     ,			_lowerCamelCase=4     ,			_lowerCamelCase=[1_0, 2_0, 3_0, 4_0]     ,			_lowerCamelCase=[2, 2, 3, 2]     ,			_lowerCamelCase=True     ,			_lowerCamelCase=True     ,			_lowerCamelCase=3_7     ,			_lowerCamelCase="gelu"     ,			_lowerCamelCase=1_0     ,			_lowerCamelCase=0.0_2     ,			_lowerCamelCase=["stage2", "stage3", "stage4"]     ,			_lowerCamelCase=3     ,			_lowerCamelCase=None     ,			):
         __UpperCamelCase	:	str		    =  parent
         __UpperCamelCase	:	Optional[int]		    =  batch_size
         __UpperCamelCase	:	int		    =  image_size
         __UpperCamelCase	:	int		    =  num_channels
         __UpperCamelCase	:	Dict		    =  num_stages
         __UpperCamelCase	:	Union[str, Any]		    =  hidden_sizes
         __UpperCamelCase	:	int		    =  depths
         __UpperCamelCase	:	Union[str, Any]		    =  is_training
         __UpperCamelCase	:	Optional[int]		    =  use_labels
         __UpperCamelCase	:	Tuple		    =  intermediate_size
         __UpperCamelCase	:	Optional[int]		    =  hidden_act
         __UpperCamelCase	:	Optional[int]		    =  type_sequence_label_size
         __UpperCamelCase	:	List[Any]		    =  initializer_range
         __UpperCamelCase	:	Union[str, Any]		    =  out_features
         __UpperCamelCase	:	Any		    =  num_labels
         __UpperCamelCase	:	str		    =  scope
         __UpperCamelCase	:	List[str]		    =  num_stages







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Optional[int]		    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

         __UpperCamelCase	:	Union[str, Any]		    =  self.get_config()

         return config, pixel_values, labels







     def lowerCAmelCase     (		self    ):
         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    ):
         return UperNetConfig(
             backbone_config=self.get_backbone_config()     ,			hidden_size=5_1_2     ,			pool_scales=[1, 2, 3, 6]     ,			use_auxiliary_head=_lowerCamelCase     ,			auxiliary_loss_weight=0.4     ,			auxiliary_in_channels=4_0     ,			auxiliary_channels=2_5_6     ,			auxiliary_num_convs=1     ,			auxiliary_concat_input=_lowerCamelCase     ,			loss_ignore_index=2_5_5     ,			num_labels=self.num_labels     ,			)







     def lowerCAmelCase     (		self     ,			_lowerCamelCase     ,			_lowerCamelCase     ,			_lowerCamelCase    ):
         __UpperCamelCase	:	str		    =  UperNetForSemanticSegmentation(config=_lowerCamelCase    )
         model.to(_lowerCamelCase    )
         model.eval()
         __UpperCamelCase	:	int		    =  model(_lowerCamelCase    )
         self.parent.assertEqual(
             result.logits.shape     ,			(self.batch_size, self.num_labels, self.image_size, self.image_size)    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	List[Any]		    =  self.prepare_config_and_inputs()
         (
             (
             __UpperCamelCase
         )    ,					(
             __UpperCamelCase
         )    ,					(
             __UpperCamelCase
         )    ,					
         )	:	Optional[int]		    =  config_and_inputs
         __UpperCamelCase	:	Union[str, Any]		    =  {'pixel_values': pixel_values}
         return config, inputs_dict






@require_torch
class 			__lowercase		(						_lowerCamelCase			,							_lowerCamelCase			,							unittest.TestCase						):







     """simple docstring"""






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







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	int		    =  UperNetModelTester(self    )
         __UpperCamelCase	:	Dict		    =  ConfigTester(self     ,			config_class=_lowerCamelCase     ,			has_text_modality=_lowerCamelCase     ,			hidden_size=3_7    )







     def lowerCAmelCase     (		self    ):
         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    ):
         return







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase    ,					__UpperCamelCase	:	Optional[Any]		    =  self.model_tester.prepare_config_and_inputs_for_common()

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

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







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	List[str]		    =  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 lowerCAmelCase     (		self    ):
         pass







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







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







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







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







     def lowerCAmelCase     (		self    ):
         def check_hidden_states_output(_lowerCamelCase     ,			_lowerCamelCase     ,			_lowerCamelCase    ):
             __UpperCamelCase	:	List[str]		    =  model_class(_lowerCamelCase    )
             model.to(_lowerCamelCase    )
             model.eval()

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

             __UpperCamelCase	:	str		    =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             __UpperCamelCase	:	Optional[Any]		    =  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]     ,			)

         __UpperCamelCase    ,					__UpperCamelCase	:	Optional[int]		    =  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             __UpperCamelCase	:	Tuple		    =  True
             check_hidden_states_output(_lowerCamelCase     ,			_lowerCamelCase     ,			_lowerCamelCase    )

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

             check_hidden_states_output(_lowerCamelCase     ,			_lowerCamelCase     ,			_lowerCamelCase    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase    ,					__UpperCamelCase	:	Any		    =  self.model_tester.prepare_config_and_inputs_for_common()

         __UpperCamelCase	:	List[Any]		    =  _config_zero_init(_lowerCamelCase    )
         __UpperCamelCase	:	List[str]		    =  _config_zero_init(configs_no_init.backbone_config    )
         for model_class in self.all_model_classes:
             __UpperCamelCase	:	Tuple		    =  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 lowerCAmelCase     (		self    ):
         pass







     @slow
     def lowerCAmelCase     (		self    ):
         for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __UpperCamelCase	:	Tuple		    =  UperNetForSemanticSegmentation.from_pretrained(_lowerCamelCase    )
             self.assertIsNotNone(_lowerCamelCase    )







def  _UpperCamelCase (     ):




    """simple docstring"""



    __UpperCamelCase	:	Any		    =  hf_hub_download(
        repo_id='hf-internal-testing/fixtures_ade20k'				,     repo_type='dataset'				,     filename='ADE_val_00000001.jpg'			)
    __UpperCamelCase	:	Optional[Any]		    =  Image.open(_a			).convert('RGB'			)
    return image






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







     """simple docstring"""






     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Dict		    =  AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'    )
         __UpperCamelCase	:	List[str]		    =  UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'    ).to(_lowerCamelCase    )

         __UpperCamelCase	:	Optional[Any]		    =  prepare_img()
         __UpperCamelCase	:	Optional[int]		    =  processor(images=_lowerCamelCase     ,			return_tensors='pt'    ).to(_lowerCamelCase    )

         with torch.no_grad():
             __UpperCamelCase	:	Dict		    =  model(**_lowerCamelCase    )

         __UpperCamelCase	:	int		    =  torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)    )
         self.assertEqual(outputs.logits.shape     ,			_lowerCamelCase    )

         __UpperCamelCase	:	List[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(_lowerCamelCase    )
         self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]     ,			_lowerCamelCase     ,			atol=1E-4    )    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Dict		    =  AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny'    )
         __UpperCamelCase	:	List[str]		    =  UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny'    ).to(_lowerCamelCase    )

         __UpperCamelCase	:	str		    =  prepare_img()
         __UpperCamelCase	:	List[Any]		    =  processor(images=_lowerCamelCase     ,			return_tensors='pt'    ).to(_lowerCamelCase    )

         with torch.no_grad():
             __UpperCamelCase	:	Dict		    =  model(**_lowerCamelCase    )

         __UpperCamelCase	:	Optional[int]		    =  torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)    )
         self.assertEqual(outputs.logits.shape     ,			_lowerCamelCase    )

         __UpperCamelCase	:	List[Any]		    =  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(_lowerCamelCase    )
         self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]     ,			_lowerCamelCase     ,			atol=1E-4    )    )




'''simple docstring'''
import unittest

from .lib import (
    Matrix,
    Vector,
    axpy,
    square_zero_matrix,
    unit_basis_vector,
    zero_vector,
)






class 			__lowercase		(						unittest.TestCase						):







     """simple docstring"""






     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Dict		    =  Vector([1, 2, 3]    )
         self.assertEqual(x.component(0    )     ,			1    )
         self.assertEqual(x.component(2    )     ,			3    )
         __UpperCamelCase	:	Dict		    =  Vector()







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	str		    =  Vector([0, 0, 0, 0, 0, 1]    )
         self.assertEqual(str(_lowerCamelCase    )     ,			'(0,0,0,0,0,1)'    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Dict		    =  Vector([1, 2, 3, 4]    )
         self.assertEqual(len(_lowerCamelCase    )     ,			4    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Any		    =  Vector([1, 2]    )
         __UpperCamelCase	:	Optional[int]		    =  Vector([1, 2, 3, 4, 5]    )
         __UpperCamelCase	:	Optional[Any]		    =  Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]    )
         __UpperCamelCase	:	List[str]		    =  Vector([1, -1, 1, -1, 2, -3, 4, -5]    )
         self.assertAlmostEqual(x.euclidean_length()     ,			2.2_3_6     ,			3    )
         self.assertAlmostEqual(y.euclidean_length()     ,			7.4_1_6     ,			3    )
         self.assertEqual(z.euclidean_length()     ,			0    )
         self.assertAlmostEqual(w.euclidean_length()     ,			7.6_1_6     ,			3    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	int		    =  Vector([1, 2, 3]    )
         __UpperCamelCase	:	List[str]		    =  Vector([1, 1, 1]    )
         self.assertEqual((x + y).component(0    )     ,			2    )
         self.assertEqual((x + y).component(1    )     ,			3    )
         self.assertEqual((x + y).component(2    )     ,			4    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Optional[Any]		    =  Vector([1, 2, 3]    )
         __UpperCamelCase	:	Dict		    =  Vector([1, 1, 1]    )
         self.assertEqual((x - y).component(0    )     ,			0    )
         self.assertEqual((x - y).component(1    )     ,			1    )
         self.assertEqual((x - y).component(2    )     ,			2    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Dict		    =  Vector([1, 2, 3]    )
         __UpperCamelCase	:	int		    =  Vector([2, -1, 4]    )  # for test of dot product
         __UpperCamelCase	:	int		    =  Vector([1, -2, -1]    )
         self.assertEqual(str(x * 3.0    )     ,			'(3.0,6.0,9.0)'    )
         self.assertEqual((a * b)     ,			0    )







     def lowerCAmelCase     (		self    ):
         self.assertEqual(str(zero_vector(1_0    )    ).count('0'    )     ,			1_0    )







     def lowerCAmelCase     (		self    ):
         self.assertEqual(str(unit_basis_vector(3     ,			1    )    )     ,			'(0,1,0)'    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Optional[int]		    =  Vector([1, 2, 3]    )
         __UpperCamelCase	:	Union[str, Any]		    =  Vector([1, 0, 1]    )
         self.assertEqual(str(axpy(2     ,			_lowerCamelCase     ,			_lowerCamelCase    )    )     ,			'(3,4,7)'    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	List[str]		    =  Vector([1, 0, 0, 0, 0, 0]    )
         __UpperCamelCase	:	Optional[Any]		    =  x.copy()
         self.assertEqual(str(_lowerCamelCase    )     ,			str(_lowerCamelCase    )    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	List[str]		    =  Vector([1, 0, 0]    )
         x.change_component(0     ,			0    )
         x.change_component(1     ,			1    )
         self.assertEqual(str(_lowerCamelCase    )     ,			'(0,1,0)'    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Tuple		    =  Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]]     ,			3     ,			3    )
         self.assertEqual('|1,2,3|\n|2,4,5|\n|6,7,8|\n'     ,			str(_lowerCamelCase    )    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Optional[int]		    =  Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]]     ,			3     ,			3    )
         __UpperCamelCase	:	List[str]		    =  [[-3, -1_4, -1_0], [-5, -1_0, -5], [-2, -1, 0]]
         for x in range(a.height()    ):
             for y in range(a.width()    ):
                 self.assertEqual(minors[x][y]     ,			a.minor(_lowerCamelCase     ,			_lowerCamelCase    )    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	int		    =  Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]]     ,			3     ,			3    )
         __UpperCamelCase	:	List[str]		    =  [[-3, 1_4, -1_0], [5, -1_0, 5], [-2, 1, 0]]
         for x in range(a.height()    ):
             for y in range(a.width()    ):
                 self.assertEqual(cofactors[x][y]     ,			a.cofactor(_lowerCamelCase     ,			_lowerCamelCase    )    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Any		    =  Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]]     ,			3     ,			3    )
         self.assertEqual(-5     ,			a.determinant()    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	int		    =  Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]     ,			3     ,			3    )
         __UpperCamelCase	:	Union[str, Any]		    =  Vector([1, 2, 3]    )
         self.assertEqual('(14,32,50)'     ,			str(a * x    )    )
         self.assertEqual('|2,4,6|\n|8,10,12|\n|14,16,18|\n'     ,			str(a * 2    )    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Union[str, Any]		    =  Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]]     ,			3     ,			3    )
         a.change_component(0     ,			2     ,			5    )
         self.assertEqual('|1,2,5|\n|2,4,5|\n|6,7,8|\n'     ,			str(_lowerCamelCase    )    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	int		    =  Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]]     ,			3     ,			3    )
         self.assertEqual(7     ,			a.component(2     ,			1    )     ,			0.0_1    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	List[str]		    =  Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]]     ,			3     ,			3    )
         __UpperCamelCase	:	Optional[Any]		    =  Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 1_0]]     ,			3     ,			3    )
         self.assertEqual('|2,4,10|\n|4,8,10|\n|12,14,18|\n'     ,			str(a + b    )    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Optional[int]		    =  Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]]     ,			3     ,			3    )
         __UpperCamelCase	:	Optional[int]		    =  Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 1_0]]     ,			3     ,			3    )
         self.assertEqual('|0,0,-4|\n|0,0,0|\n|0,0,-2|\n'     ,			str(a - b    )    )







     def lowerCAmelCase     (		self    ):
         self.assertEqual(
             '|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n'     ,			str(square_zero_matrix(5    )    )     ,			)


if __name__ == "__main__":
  unittest.main()



