






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




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




     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  List[str]				      =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

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

          return config, pixel_values, labels




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




     def   __UpperCAmelCase  (				self	,						_lowerCAmelCase	,						_lowerCAmelCase	,						_lowerCAmelCase		):
          UpperCAmelCase__      :  Optional[Any]				      =			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   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Tuple				      =			self.prepare_config_and_inputs()
          (
              UpperCAmelCase__     
          )      :  List[str]				      =			config_and_inputs
          UpperCAmelCase__      :  int				      =			{"""pixel_values""": pixel_values}
          return config, inputs_dict







@require_torch
class 				UpperCAmelCase_  (		__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   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Optional[Any]				      =			UperNetModelTester(self		)
          UpperCAmelCase__      :  Union[str, Any]				      =			ConfigTester(self	,						config_class=_lowerCAmelCase	,						has_text_modality=_lowerCAmelCase	,						hidden_size=37		)




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




     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Optional[Any]				      =			self.model_tester.prepare_config_and_inputs_for_common()

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

               UpperCAmelCase__      :  str				      =			["""pixel_values"""]
               self.assertListEqual(arg_names[:1]	,						_lowerCAmelCase		)




     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Optional[Any]				      =			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   __UpperCAmelCase  (				self		):
          pass




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




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




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




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




     def   __UpperCAmelCase  (				self		):

          def check_hidden_states_output(_lowerCAmelCase	,						_lowerCAmelCase	,						_lowerCAmelCase		):
               UpperCAmelCase__      :  Dict				      =			model_class(_lowerCAmelCase		)
               model.to(_lowerCAmelCase		)
               model.eval()

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

               UpperCAmelCase__      :  int				      =			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__      :  str				      =			self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               UpperCAmelCase__      :  List[str]				      =			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   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Dict				      =			self.model_tester.prepare_config_and_inputs_for_common()

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




     @slow
     def   __UpperCAmelCase  (				self		):

          for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCAmelCase__      :  List[str]				      =			UperNetForSemanticSegmentation.from_pretrained(_lowerCAmelCase		)
               self.assertIsNotNone(_lowerCAmelCase		)





def  _lowerCamelCase						(						) ->			Any:

     '''simple docstring'''
     UpperCAmelCase__      :  Dict				      =			hf_hub_download(
         repo_id="""hf-internal-testing/fixtures_ade20k""" ,							repo_type="""dataset""" ,							filename="""ADE_val_00000001.jpg"""       )
     UpperCAmelCase__      :  List[str]				      =			Image.open(_lowerCamelCase       ).convert("""RGB"""       )
     return image







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




     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Union[str, Any]				      =			AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny"""		)
          UpperCAmelCase__      :  int				      =			UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny"""		).to(_lowerCAmelCase		)

          UpperCAmelCase__      :  Tuple				      =			prepare_img()
          UpperCAmelCase__      :  int				      =			processor(images=_lowerCAmelCase	,						return_tensors="""pt"""		).to(_lowerCAmelCase		)

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

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

          UpperCAmelCase__      :  List[str]				      =			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   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  str				      =			AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny"""		)
          UpperCAmelCase__      :  Any				      =			UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny"""		).to(_lowerCAmelCase		)

          UpperCAmelCase__      :  Union[str, Any]				      =			prepare_img()
          UpperCAmelCase__      :  Optional[int]				      =			processor(images=_lowerCAmelCase	,						return_tensors="""pt"""		).to(_lowerCAmelCase		)

          with torch.no_grad():
               UpperCAmelCase__      :  int				      =			model(**_lowerCAmelCase		)

          UpperCAmelCase__      :  Optional[Any]				      =			torch.Size((1, model.config.num_labels, 512, 512)		)
          self.assertEqual(outputs.logits.shape	,						_lowerCAmelCase		)

          UpperCAmelCase__      :  str				      =			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'''






def 					_a						(       _lowerCamelCase = 100 ) ->				int:



			"""simple docstring"""


			__snake_case					:      Any							      =     n * (n + 1) * (2 * n + 1) / 6
			__snake_case					:      List[Any]							      =     (n * (n + 1) / 2) ** 2
			return int(square_of_sum - sum_of_squares )


if __name__ == "__main__":
	print(f"""{solution() = }""")


