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





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





     def 		UpperCAmelCase(self				:   Optional[Any]       )						->						Tuple:
         snake_case								= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

         snake_case								= None
         if self.use_labels:
             snake_case								= ids_tensor([self.batch_size]    ,   self.type_sequence_label_size       )

         snake_case								= self.get_config()

         return config, pixel_values, labels





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





     def 		UpperCAmelCase(self				:   Optional[int]    ,   _A				:   Tuple    ,   _A				:   Optional[int]    ,   _A				:   List[str]       )						->						List[str]:
         snake_case								= UperNetForSemanticSegmentation(config=_A       )
         model.to(_A       )
         model.eval()
         snake_case								= model(_A       )
         self.parent.assertEqual(
             result.logits.shape    ,   (self.batch_size, self.num_labels, self.image_size, self.image_size)       )





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







@require_torch
class 					lowerCamelCase		(  A_							,			A_							,			unittest.TestCase  ):
     UpperCAmelCase__    :							str									=		(UperNetForSemanticSegmentation,) if is_torch_available() else ()
     UpperCAmelCase__    :							Dict									=		{"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {}
     UpperCAmelCase__    :							List[str]									=		False
     UpperCAmelCase__    :							List[Any]									=		False
     UpperCAmelCase__    :							str									=		False
     UpperCAmelCase__    :							Tuple									=		False
     UpperCAmelCase__    :							Union[str, Any]									=		False
     UpperCAmelCase__    :							Tuple									=		False





     def 		UpperCAmelCase(self				:   Union[str, Any]       )						->						int:
         snake_case								= UperNetModelTester(self       )
         snake_case								= ConfigTester(self    ,   config_class=_A    ,   has_text_modality=_A    ,   hidden_size=3_7       )





     def 		UpperCAmelCase(self				:   List[Any]       )						->						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 		UpperCAmelCase(self				:   List[Any]       )						->						Tuple:
         return





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

         for model_class in self.all_model_classes:
             snake_case								= model_class(_A       )
             snake_case								= inspect.signature(model.forward       )
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             snake_case								= [*signature.parameters.keys()]

             snake_case								= ["pixel_values"]
             self.assertListEqual(arg_names[:1]    ,   _A       )





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





     @unittest.skip(reason="UperNet does not support input and output embeddings"       )
     def 		UpperCAmelCase(self				:   int       )						->						Optional[Any]:
         pass





     @unittest.skip(reason="UperNet does not have a base model"       )
     def 		UpperCAmelCase(self				:   Optional[int]       )						->						Optional[int]:
         pass





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





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





     def 		UpperCAmelCase(self				:   str       )						->						Tuple:
         def check_hidden_states_output(_A				:   Tuple    ,   _A				:   Optional[int]    ,   _A				:   str       ):
             snake_case								= model_class(_A       )
             model.to(_A       )
             model.eval()

             with torch.no_grad():
                 snake_case								= model(**self._prepare_for_class(_A    ,   _A       )       )

             snake_case								= outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             snake_case								= 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]    ,   )

         snake_case					,							snake_case								= self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             snake_case								= True
             check_hidden_states_output(_A    ,   _A    ,   _A       )

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             snake_case								= True

             check_hidden_states_output(_A    ,   _A    ,   _A       )





     def 		UpperCAmelCase(self				:   Union[str, Any]       )						->						str:
         snake_case					,							snake_case								= self.model_tester.prepare_config_and_inputs_for_common()

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





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



def 						lowercase_      (       )							->							Dict:
    """simple docstring"""

    snake_case								= hf_hub_download(
        repo_id="hf-internal-testing/fixtures_ade20k"			,		repo_type="dataset"			,		filename="ADE_val_00000001.jpg"		)
    snake_case								= Image.open(A__		).convert("RGB"		)
    return image







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





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

         snake_case								= prepare_img()
         snake_case								= processor(images=_A    ,   return_tensors="pt"       ).to(_A       )

         with torch.no_grad():
             snake_case								= model(**_A       )

         snake_case								= torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)       )
         self.assertEqual(outputs.logits.shape    ,   _A       )

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





     def 		UpperCAmelCase(self				:   List[Any]       )						->						int:
         snake_case								= AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny"       )
         snake_case								= UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny"       ).to(_A       )

         snake_case								= prepare_img()
         snake_case								= processor(images=_A    ,   return_tensors="pt"       ).to(_A       )

         with torch.no_grad():
             snake_case								= model(**_A       )

         snake_case								= torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)       )
         self.assertEqual(outputs.logits.shape    ,   _A       )

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



from __future__ import annotations

from decimal import Decimal

from numpy import array



def 						lowercase_      (       A__		)							->							list[list[float]]:
    """simple docstring"""

    snake_case								= Decimal

    # Check if the provided matrix has 2 rows and 2 columns
    # since this implementation only works for 2x2 matrices
    if len(A__		) == 2 and len(matrix[0]		) == 2 and len(matrix[1]		) == 2:
        # Calculate the determinant of the matrix
        snake_case								= float(
            d(matrix[0][0]		) * d(matrix[1][1]		) - d(matrix[1][0]		) * d(matrix[0][1]		)		)
        if determinant == 0:
            raise ValueError("This matrix has no inverse."		)

        # Creates a copy of the matrix with swapped positions of the elements
        snake_case								= [[0.0, 0.0], [0.0, 0.0]]
        snake_case					,							snake_case								= matrix[1][1], matrix[0][0]
        snake_case					,							snake_case								= -matrix[1][0], -matrix[0][1]

        # Calculate the inverse of the matrix
        return [
            [(float(d(A__		)		) / determinant) or 0.0 for n in row] for row in swapped_matrix
        ]
    elif (
        len(A__		) == 3
        and len(matrix[0]		) == 3
        and len(matrix[1]		) == 3
        and len(matrix[2]		) == 3
    ):
        # Calculate the determinant of the matrix using Sarrus rule
        snake_case								= float(
            (
                (d(matrix[0][0]		) * d(matrix[1][1]		) * d(matrix[2][2]		))
                + (d(matrix[0][1]		) * d(matrix[1][2]		) * d(matrix[2][0]		))
                + (d(matrix[0][2]		) * d(matrix[1][0]		) * d(matrix[2][1]		))
            )
            - (
                (d(matrix[0][2]		) * d(matrix[1][1]		) * d(matrix[2][0]		))
                + (d(matrix[0][1]		) * d(matrix[1][0]		) * d(matrix[2][2]		))
                + (d(matrix[0][0]		) * d(matrix[1][2]		) * d(matrix[2][1]		))
            )		)
        if determinant == 0:
            raise ValueError("This matrix has no inverse."		)

        # Creating cofactor matrix
        snake_case								= [
            [d(0.0		), d(0.0		), d(0.0		)],
            [d(0.0		), d(0.0		), d(0.0		)],
            [d(0.0		), d(0.0		), d(0.0		)],
        ]
        snake_case								= (d(matrix[1][1]		) * d(matrix[2][2]		)) - (
            d(matrix[1][2]		) * d(matrix[2][1]		)
        )
        snake_case								= -(
            (d(matrix[1][0]		) * d(matrix[2][2]		)) - (d(matrix[1][2]		) * d(matrix[2][0]		))
        )
        snake_case								= (d(matrix[1][0]		) * d(matrix[2][1]		)) - (
            d(matrix[1][1]		) * d(matrix[2][0]		)
        )
        snake_case								= -(
            (d(matrix[0][1]		) * d(matrix[2][2]		)) - (d(matrix[0][2]		) * d(matrix[2][1]		))
        )
        snake_case								= (d(matrix[0][0]		) * d(matrix[2][2]		)) - (
            d(matrix[0][2]		) * d(matrix[2][0]		)
        )
        snake_case								= -(
            (d(matrix[0][0]		) * d(matrix[2][1]		)) - (d(matrix[0][1]		) * d(matrix[2][0]		))
        )
        snake_case								= (d(matrix[0][1]		) * d(matrix[1][2]		)) - (
            d(matrix[0][2]		) * d(matrix[1][1]		)
        )
        snake_case								= -(
            (d(matrix[0][0]		) * d(matrix[1][2]		)) - (d(matrix[0][2]		) * d(matrix[1][0]		))
        )
        snake_case								= (d(matrix[0][0]		) * d(matrix[1][1]		)) - (
            d(matrix[0][1]		) * d(matrix[1][0]		)
        )

        # Transpose the cofactor matrix (Adjoint matrix)
        snake_case								= array(A__		)
        for i in range(3		):
            for j in range(3		):
                snake_case								= cofactor_matrix[j][i]

        # Inverse of the matrix using the formula (1/determinant) * adjoint matrix
        snake_case								= array(A__		)
        for i in range(3		):
            for j in range(3		):
                inverse_matrix[i][j] /= d(A__		)

        # Calculate the inverse of the matrix
        return [[float(d(A__		)		) or 0.0 for n in row] for row in inverse_matrix]
    raise ValueError("Please provide a matrix of size 2x2 or 3x3."		)

