

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		:

  def __init__(				self ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE=13 ,					_SCREAMING_SNAKE_CASE=32 ,					_SCREAMING_SNAKE_CASE=3 ,					_SCREAMING_SNAKE_CASE=4 ,					_SCREAMING_SNAKE_CASE=[10, 20, 30, 40] ,					_SCREAMING_SNAKE_CASE=[2, 2, 3, 2] ,					_SCREAMING_SNAKE_CASE=True ,					_SCREAMING_SNAKE_CASE=True ,					_SCREAMING_SNAKE_CASE=37 ,					_SCREAMING_SNAKE_CASE="gelu" ,					_SCREAMING_SNAKE_CASE=10 ,					_SCREAMING_SNAKE_CASE=0.02 ,					_SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"] ,					_SCREAMING_SNAKE_CASE=3 ,					_SCREAMING_SNAKE_CASE=None ,					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Dict           =     parent
        SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     batch_size
        SCREAMING_SNAKE_CASE_				:  List[str]           =     image_size
        SCREAMING_SNAKE_CASE_				:  int           =     num_channels
        SCREAMING_SNAKE_CASE_				:  List[str]           =     num_stages
        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     hidden_sizes
        SCREAMING_SNAKE_CASE_				:  List[Any]           =     depths
        SCREAMING_SNAKE_CASE_				:  Any           =     is_training
        SCREAMING_SNAKE_CASE_				:  List[Any]           =     use_labels
        SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     intermediate_size
        SCREAMING_SNAKE_CASE_				:  List[str]           =     hidden_act
        SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     type_sequence_label_size
        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     initializer_range
        SCREAMING_SNAKE_CASE_				:  Any           =     out_features
        SCREAMING_SNAKE_CASE_				:  Any           =     num_labels
        SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     scope
        SCREAMING_SNAKE_CASE_				:  int           =     num_stages

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

        SCREAMING_SNAKE_CASE_				:  int           =     self.get_config()

        return config, pixel_values, labels

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







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





        """simple docstring"""







        return UperNetConfig(
            backbone_config=self.get_backbone_config() ,					hidden_size=512 ,					pool_scales=[1, 2, 3, 6] ,					use_auxiliary_head=_SCREAMING_SNAKE_CASE ,					auxiliary_loss_weight=0.4 ,					auxiliary_in_channels=40 ,					auxiliary_channels=256 ,					auxiliary_num_convs=1 ,					auxiliary_concat_input=_SCREAMING_SNAKE_CASE ,					loss_ignore_index=255 ,					num_labels=self.num_labels ,					)

  def  UpperCAmelCase    (				self ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Tuple           =     UperNetForSemanticSegmentation(config=_SCREAMING_SNAKE_CASE					)
        model.to(_SCREAMING_SNAKE_CASE					)
        model.eval()
        SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     model(_SCREAMING_SNAKE_CASE					)
        self.parent.assertEqual(
            result.logits.shape ,					(self.batch_size, self.num_labels, self.image_size, self.image_size)					)



  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     self.prepare_config_and_inputs()
        (
            (
            SCREAMING_SNAKE_CASE_
        )       ,						(
            SCREAMING_SNAKE_CASE_
        )       ,						(
            SCREAMING_SNAKE_CASE_
        )       ,						
        )				:  Dict           =     config_and_inputs
        SCREAMING_SNAKE_CASE_				:  List[Any]           =     {'pixel_values': pixel_values}
        return config, inputs_dict

@require_torch
class  _A		(  __magic_name__   ,     __magic_name__   ,     unittest.TestCase):
  SCREAMING_SNAKE_CASE    :      Dict       =  (UperNetForSemanticSegmentation,) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE    :      List[str]       =  {'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {}
  SCREAMING_SNAKE_CASE    :      Any       =  False
  SCREAMING_SNAKE_CASE    :      int       =  False
  SCREAMING_SNAKE_CASE    :      Any       =  False
  SCREAMING_SNAKE_CASE    :      Dict       =  False
  SCREAMING_SNAKE_CASE    :      Tuple       =  False
  SCREAMING_SNAKE_CASE    :      str       =  False

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     UperNetModelTester(self					)
        SCREAMING_SNAKE_CASE_				:  int           =     ConfigTester(self ,					config_class=_SCREAMING_SNAKE_CASE ,					has_text_modality=_SCREAMING_SNAKE_CASE ,					hidden_size=37					)

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







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





        """simple docstring"""







        return

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_       ,						SCREAMING_SNAKE_CASE_				:  Any           =     self.model_tester.prepare_config_and_inputs_for_common()

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

              SCREAMING_SNAKE_CASE_				:  Optional[int]           =     ['pixel_values']
              self.assertListEqual(arg_names[:1] ,					_SCREAMING_SNAKE_CASE					)

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_SNAKE_CASE					)

  @unittest.skip(reason='UperNet does not use inputs_embeds'					)
  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        pass

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





        """simple docstring"""







        pass

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





        """simple docstring"""







        pass

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





        """simple docstring"""







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





        """simple docstring"""







        pass

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





        """simple docstring"""







        pass

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        def check_hidden_states_output(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					):
              SCREAMING_SNAKE_CASE_				:  List[str]           =     model_class(_SCREAMING_SNAKE_CASE					)
              model.to(_SCREAMING_SNAKE_CASE					)
              model.eval()

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

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

              SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     self.model_tester.num_stages
              self.assertEqual(len(_SCREAMING_SNAKE_CASE					) ,					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] ,					)

        SCREAMING_SNAKE_CASE_       ,						SCREAMING_SNAKE_CASE_				:  Tuple           =     self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE_				:  Optional[int]           =     True
              check_hidden_states_output(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     True

              check_hidden_states_output(_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					)

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_       ,						SCREAMING_SNAKE_CASE_				:  Dict           =     self.model_tester.prepare_config_and_inputs_for_common()

        SCREAMING_SNAKE_CASE_				:  Any           =     _config_zero_init(_SCREAMING_SNAKE_CASE					)
        SCREAMING_SNAKE_CASE_				:  str           =     _config_zero_init(configs_no_init.backbone_config					)
        for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE_				:  int           =     model_class(config=_SCREAMING_SNAKE_CASE					)
              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					):





        """simple docstring"""







        pass



  @slow
  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              SCREAMING_SNAKE_CASE_				:  str           =     UperNetForSemanticSegmentation.from_pretrained(_SCREAMING_SNAKE_CASE					)
              self.assertIsNotNone(_SCREAMING_SNAKE_CASE					)

def    A_  (							):

      """simple docstring"""



      SCREAMING_SNAKE_CASE_				:  Tuple           =     hf_hub_download(
          repo_id='hf-internal-testing/fixtures_ade20k'					,   repo_type='dataset'					,   filename='ADE_val_00000001.jpg'  )
      SCREAMING_SNAKE_CASE_				:  int           =     Image.open(a  ).convert('RGB'  )
      return image



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

  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  Tuple           =     AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'					)
        SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'					).to(_SCREAMING_SNAKE_CASE					)

        SCREAMING_SNAKE_CASE_				:  Optional[int]           =     prepare_img()
        SCREAMING_SNAKE_CASE_				:  str           =     processor(images=_SCREAMING_SNAKE_CASE ,					return_tensors='pt'					).to(_SCREAMING_SNAKE_CASE					)

        with torch.no_grad():
              SCREAMING_SNAKE_CASE_				:  Any           =     model(**_SCREAMING_SNAKE_CASE					)

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

        SCREAMING_SNAKE_CASE_				:  List[str]           =     torch.tensor(
            [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]					).to(_SCREAMING_SNAKE_CASE					)
        self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] ,					_SCREAMING_SNAKE_CASE ,					atol=1e-4					)					)



  def  UpperCAmelCase    (				self					):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_				:  List[str]           =     AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny'					)
        SCREAMING_SNAKE_CASE_				:  List[Any]           =     UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny'					).to(_SCREAMING_SNAKE_CASE					)

        SCREAMING_SNAKE_CASE_				:  Any           =     prepare_img()
        SCREAMING_SNAKE_CASE_				:  List[Any]           =     processor(images=_SCREAMING_SNAKE_CASE ,					return_tensors='pt'					).to(_SCREAMING_SNAKE_CASE					)

        with torch.no_grad():
              SCREAMING_SNAKE_CASE_				:  Dict           =     model(**_SCREAMING_SNAKE_CASE					)

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

        SCREAMING_SNAKE_CASE_				:  str           =     torch.tensor(
            [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]					).to(_SCREAMING_SNAKE_CASE					)
        self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] ,					_SCREAMING_SNAKE_CASE ,					atol=1e-4					)					)









def    A_  (							a  ):

      """simple docstring"""



      SCREAMING_SNAKE_CASE_				:  List[Any]           =     0
      while num > 0:
            digit_sum += num % 1_0
            num //= 1_0
      return digit_sum

def    A_  (							a = 1_0_0  ):

      """simple docstring"""



      SCREAMING_SNAKE_CASE_				:  List[str]           =     1
      SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     2

      for i in range(2					,   max_n + 1  ):
            SCREAMING_SNAKE_CASE_				:  List[str]           =     pre_numerator
            SCREAMING_SNAKE_CASE_				:  str           =     2 * i // 3 if i % 3 == 0 else 1
            SCREAMING_SNAKE_CASE_				:  Tuple           =     cur_numerator
            SCREAMING_SNAKE_CASE_				:  Tuple           =     e_cont * pre_numerator + temp

      return sum_digits(a  )


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






