


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




      '''simple docstring'''


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




      def 					_snake_case     (    self:	str    ):
       __lowerCamelCase		:							List[Any]		 =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

       __lowerCamelCase		:							List[Any]		 =						self.get_config()

       return config, pixel_values, labels




      def 					_snake_case     (    self:	str    ):
       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:	List[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 					_snake_case     (    self:	Any						,				a:	List[str]						,				a:	Any						,				a:	Any    ):
       __lowerCamelCase		:							Tuple		 =						UperNetForSemanticSegmentation(config=lowercase__    )
       model.to(lowercase__    )
       model.eval()
       __lowerCamelCase		:							str		 =						model(lowercase__    )
       self.parent.assertEqual(
           result.logits.shape						,				(self.batch_size, self.num_labels, self.image_size, self.image_size)    )




      def 					_snake_case     (    self:	Union[str, Any]    ):
       __lowerCamelCase		:							str		 =						self.prepare_config_and_inputs()
       (
           (
           __lowerCamelCase     
       ) ,					(
           __lowerCamelCase     
       ) ,					(
           __lowerCamelCase     
       ) ,					     
       )		:							Optional[Any]		 =						config_and_inputs
       __lowerCamelCase		:							Union[str, Any]		 =						{'pixel_values': pixel_values}
       return config, inputs_dict



@require_torch
class 	A_ (	lowerCamelCase__ ,				lowerCamelCase__ ,				unittest.TestCase   ):




      '''simple docstring'''


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




      def 					_snake_case     (    self:	Union[str, Any]    ):
       __lowerCamelCase		:							List[str]		 =						UperNetModelTester(self    )
       __lowerCamelCase		:							List[Any]		 =						ConfigTester(self						,				config_class=lowercase__						,				has_text_modality=lowercase__						,				hidden_size=37    )




      def 					_snake_case     (    self:	Union[str, 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 					_snake_case     (    self:	Optional[int]    ):
       return




      def 					_snake_case     (    self:	Optional[Any]    ):
       __lowerCamelCase ,					__lowerCamelCase		:							str		 =						self.model_tester.prepare_config_and_inputs_for_common()

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

        __lowerCamelCase		:							str		 =						['pixel_values']
        self.assertListEqual(arg_names[:1]						,				lowercase__    )




      def 					_snake_case     (    self:	Optional[Any]    ):
       __lowerCamelCase		:							str		 =						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 					_snake_case     (    self:	int    ):
       pass




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




      @unittest.skip(reason='UperNet does not have a base model'    )
      def 					_snake_case     (    self:	Optional[Any]    ):
       pass




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




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




      def 					_snake_case     (    self:	Any    ):
       def check_hidden_states_output(a:	List[str]						,				a:	int						,				a:	List[str]    ):
        __lowerCamelCase		:							Tuple		 =						model_class(lowercase__    )
        model.to(lowercase__    )
        model.eval()

        with torch.no_grad():
         __lowerCamelCase		:							Dict		 =						model(**self._prepare_for_class(lowercase__						,				lowercase__    )    )

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

        __lowerCamelCase		:							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]						,				)

       __lowerCamelCase ,					__lowerCamelCase		:							str		 =						self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        __lowerCamelCase		:							Optional[Any]		 =						True
        check_hidden_states_output(lowercase__						,				lowercase__						,				lowercase__    )

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        __lowerCamelCase		:							Union[str, Any]		 =						True

        check_hidden_states_output(lowercase__						,				lowercase__						,				lowercase__    )




      def 					_snake_case     (    self:	Dict    ):
       __lowerCamelCase ,					__lowerCamelCase		:							List[Any]		 =						self.model_tester.prepare_config_and_inputs_for_common()

       __lowerCamelCase		:							Optional[int]		 =						_config_zero_init(lowercase__    )
       __lowerCamelCase		:							Tuple		 =						_config_zero_init(configs_no_init.backbone_config    )
       for model_class in self.all_model_classes:
        __lowerCamelCase		:							Tuple		 =						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 					_snake_case     (    self:	Optional[Any]    ):
       pass




      @slow
      def 					_snake_case     (    self:	Optional[Any]    ):
       for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __lowerCamelCase		:							int		 =						UperNetForSemanticSegmentation.from_pretrained(lowercase__    )
        self.assertIsNotNone(lowercase__    )



def 				UpperCamelCase__					(  ):
 __lowerCamelCase		:							List[str]		 =						hf_hub_download(
     repo_id='hf-internal-testing/fixtures_ade20k'      ,	repo_type='dataset'      ,	filename='ADE_val_00000001.jpg'			)
 __lowerCamelCase		:							str		 =						Image.open(A__			).convert('RGB'			)
 return image



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




      '''simple docstring'''


      def 					_snake_case     (    self:	Optional[Any]    ):
       __lowerCamelCase		:							List[Any]		 =						AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'    )
       __lowerCamelCase		:							Any		 =						UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'    ).to(lowercase__    )

       __lowerCamelCase		:							Union[str, Any]		 =						prepare_img()
       __lowerCamelCase		:							Any		 =						processor(images=lowercase__						,				return_tensors='pt'    ).to(lowercase__    )

       with torch.no_grad():
        __lowerCamelCase		:							Tuple		 =						model(**lowercase__    )

       __lowerCamelCase		:							Union[str, Any]		 =						torch.Size((1, model.config.num_labels, 512, 512)    )
       self.assertEqual(outputs.logits.shape						,				lowercase__    )

       __lowerCamelCase		:							Tuple		 =						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(lowercase__    )
       self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]						,				lowercase__						,				atol=1e-4    )    )




      def 					_snake_case     (    self:	Tuple    ):
       __lowerCamelCase		:							Optional[int]		 =						AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny'    )
       __lowerCamelCase		:							Optional[Any]		 =						UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny'    ).to(lowercase__    )

       __lowerCamelCase		:							Tuple		 =						prepare_img()
       __lowerCamelCase		:							Tuple		 =						processor(images=lowercase__						,				return_tensors='pt'    ).to(lowercase__    )

       with torch.no_grad():
        __lowerCamelCase		:							int		 =						model(**lowercase__    )

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

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





from __future__ import annotations
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__						):
 __lowerCamelCase		:							Optional[Any]		 =						0.00
 __lowerCamelCase		:							Tuple		 =						0
 for resistor in resistors:
  if resistor <= 0:
   __lowerCamelCase		:							Union[str, Any]		 =						f'Resistor at index {index} has a negative or zero value!'
   raise ValueError(SCREAMING_SNAKE_CASE__						)
  first_sum += 1 / float(SCREAMING_SNAKE_CASE__						)
  index += 1
 return 1 / first_sum
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__						):
 __lowerCamelCase		:							Union[str, Any]		 =						0.00
 __lowerCamelCase		:							str		 =						0
 for resistor in resistors:
  sum_r += resistor
  if resistor < 0:
   __lowerCamelCase		:							Any		 =						f'Resistor at index {index} has a negative value!'
   raise ValueError(SCREAMING_SNAKE_CASE__						)
  index += 1
 return sum_r


if __name__ == "__main__":
       import doctest

       doctest.testmod()

