


"""simple docstring"""







import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
 from transformers.models.mobilevitva.modeling_mobilevitva import (
     MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
     make_divisible,
 )


if is_vision_available():
 from PIL import Image

 from transformers import MobileViTImageProcessor






class 						_A     (  _a  ):







    """simple docstring"""




    def      __snake_case							( self    :   Union[str, Any]):
      a						:		List[str]											=      self.config_class(**self.inputs_dict)
      self.parent.assertTrue(hasattr(__UpperCAmelCase    ,			"width_multiplier"))






class 						_A     :







    """simple docstring"""




    def __init__( self    :   int    ,			__UpperCAmelCase    :   str    ,			__UpperCAmelCase    :   str=13    ,			__UpperCAmelCase    :   str=64    ,			__UpperCAmelCase    :   Any=2    ,			__UpperCAmelCase    :   int=3    ,			__UpperCAmelCase    :   Optional[Any]="swish"    ,			__UpperCAmelCase    :   str=3    ,			__UpperCAmelCase    :   int=32    ,			__UpperCAmelCase    :   List[str]=0.1    ,			__UpperCAmelCase    :   int=0.02    ,			__UpperCAmelCase    :   List[str]=True    ,			__UpperCAmelCase    :   Tuple=True    ,			__UpperCAmelCase    :   List[str]=10    ,			__UpperCAmelCase    :   Union[str, Any]=None    ,			__UpperCAmelCase    :   Optional[Any]=0.25    ,			__UpperCAmelCase    :   Union[str, Any]=0.0    ,			__UpperCAmelCase    :   Tuple=0.0    ,			):
      a						:		Tuple											=      parent
      a						:		Optional[Any]											=      batch_size
      a						:		List[Any]											=      image_size
      a						:		Tuple											=      patch_size
      a						:		Any											=      num_channels
      a						:		Union[str, Any]											=      make_divisible(512 * width_multiplier    ,			divisor=8)
      a						:		Any											=      hidden_act
      a						:		List[Any]											=      conv_kernel_size
      a						:		Tuple											=      output_stride
      a						:		int											=      classifier_dropout_prob
      a						:		int											=      use_labels
      a						:		Dict											=      is_training
      a						:		Any											=      num_labels
      a						:		Any											=      initializer_range
      a						:		int											=      scope
      a						:		Any											=      width_multiplier
      a						:		Optional[int]											=      ffn_dropout
      a						:		Optional[int]											=      attn_dropout






    def      __snake_case							( self    :   Any):
      a						:		List[Any]											=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

      a						:		List[Any]											=      None
      a						:		Any											=      None
      if self.use_labels:
        a						:		Optional[int]											=      ids_tensor([self.batch_size]    ,			self.num_labels)
        a						:		List[str]											=      ids_tensor([self.batch_size, self.image_size, self.image_size]    ,			self.num_labels)

      a						:		Tuple											=      self.get_config()

      return config, pixel_values, labels, pixel_labels






    def      __snake_case							( self    :   Dict):
      return MobileViTVaConfig(
          image_size=self.image_size    ,			patch_size=self.patch_size    ,			num_channels=self.num_channels    ,			hidden_act=self.hidden_act    ,			conv_kernel_size=self.conv_kernel_size    ,			output_stride=self.output_stride    ,			classifier_dropout_prob=self.classifier_dropout_prob    ,			initializer_range=self.initializer_range    ,			width_multiplier=self.width_multiplier    ,			ffn_dropout=self.ffn_dropout_prob    ,			attn_dropout=self.attn_dropout_prob    ,			)






    def      __snake_case							( self    :   str    ,			__UpperCAmelCase    :   Optional[int]    ,			__UpperCAmelCase    :   Any    ,			__UpperCAmelCase    :   Any    ,			__UpperCAmelCase    :   Optional[int]):
      a						:		Union[str, Any]											=      MobileViTVaModel(config=__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		Tuple											=      model(__UpperCAmelCase)
      self.parent.assertEqual(
          result.last_hidden_state.shape    ,			(
              self.batch_size,
              self.last_hidden_size,
              self.image_size // self.output_stride,
              self.image_size // self.output_stride,
          )    ,			)






    def      __snake_case							( self    :   List[Any]    ,			__UpperCAmelCase    :   Union[str, Any]    ,			__UpperCAmelCase    :   int    ,			__UpperCAmelCase    :   Any    ,			__UpperCAmelCase    :   Tuple):
      a						:		List[Any]											=      self.num_labels
      a						:		List[str]											=      MobileViTVaForImageClassification(__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		List[str]											=      model(__UpperCAmelCase    ,			labels=__UpperCAmelCase)
      self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.num_labels))






    def      __snake_case							( self    :   str    ,			__UpperCAmelCase    :   int    ,			__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   Any    ,			__UpperCAmelCase    :   Optional[int]):
      a						:		Union[str, Any]											=      self.num_labels
      a						:		List[str]											=      MobileViTVaForSemanticSegmentation(__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		List[str]											=      model(__UpperCAmelCase)
      self.parent.assertEqual(
          result.logits.shape    ,			(
              self.batch_size,
              self.num_labels,
              self.image_size // self.output_stride,
              self.image_size // self.output_stride,
          )    ,			)
      a						:		List[Any]											=      model(__UpperCAmelCase    ,			labels=__UpperCAmelCase)
      self.parent.assertEqual(
          result.logits.shape    ,			(
              self.batch_size,
              self.num_labels,
              self.image_size // self.output_stride,
              self.image_size // self.output_stride,
          )    ,			)






    def      __snake_case							( self    :   Any):
      a						:		Any											=      self.prepare_config_and_inputs()
      a						:		Optional[int]											=      config_and_inputs
      a						:		Optional[Any]											=      {"pixel_values": pixel_values}
      return config, inputs_dict






@require_torch
class 						_A     (  _a   ,_a   ,unittest.TestCase  ):







    """simple docstring"""




    UpperCAmelCase	:							int     =	(
        (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
        if is_torch_available()
        else ()
    )

    UpperCAmelCase	:							Dict     =	(
        {
            """feature-extraction""": MobileViTVaModel,
            """image-classification""": MobileViTVaForImageClassification,
            """image-segmentation""": MobileViTVaForSemanticSegmentation,
        }
        if is_torch_available()
        else {}
    )

    UpperCAmelCase	:							Any     =	False
    UpperCAmelCase	:							int     =	False
    UpperCAmelCase	:							int     =	False
    UpperCAmelCase	:							Optional[Any]     =	False






    def      __snake_case							( self    :   List[Any]):
      a						:		Tuple											=      MobileViTVaModelTester(self)
      a						:		Dict											=      MobileViTVaConfigTester(self    ,			config_class=__UpperCAmelCase    ,			has_text_modality=__UpperCAmelCase)






    def      __snake_case							( self    :   Dict):
      self.config_tester.run_common_tests()






    @unittest.skip(reason="MobileViTV2 does not use inputs_embeds")
    def      __snake_case							( self    :   Optional[int]):
      pass






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






    @unittest.skip(reason="MobileViTV2 does not output attentions")
    def      __snake_case							( self    :   List[str]):
      pass






    @require_torch_multi_gpu
    @unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run.")
    def      __snake_case							( self    :   str):
      pass






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






    def      __snake_case							( self    :   Any):
      a						:		Any											=      self.model_tester.prepare_config_and_inputs_for_common()

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

        a						:		List[Any]											=      ["pixel_values"]
        self.assertListEqual(arg_names[:1]    ,			__UpperCAmelCase)






    def      __snake_case							( self    :   str):
      a						:		int											=      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__UpperCAmelCase)






    def      __snake_case							( self    :   Dict):
      def check_hidden_states_output(__UpperCAmelCase    :   Union[str, Any]    ,			__UpperCAmelCase    :   str    ,			__UpperCAmelCase    :   List[Any]):
        a						:		Dict											=      model_class(__UpperCAmelCase)
        model.to(__UpperCAmelCase)
        model.eval()

        with torch.no_grad():
          a						:		Optional[int]											=      model(**self._prepare_for_class(__UpperCAmelCase    ,			__UpperCAmelCase))

        a						:		Tuple											=      outputs.hidden_states

        a						:		str											=      5
        self.assertEqual(len(__UpperCAmelCase)    ,			__UpperCAmelCase)

        # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
        # with the width and height being successively divided by 2.
        a						:		int											=      2
        for i in range(len(__UpperCAmelCase)):
          self.assertListEqual(
              list(hidden_states[i].shape[-2:])    ,			[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]    ,			)
          divisor *= 2

        self.assertEqual(self.model_tester.output_stride    ,			divisor // 2)

      a						:		Union[str, Any]											=      self.model_tester.prepare_config_and_inputs_for_common()

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

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

        check_hidden_states_output(__UpperCAmelCase    ,			__UpperCAmelCase    ,			__UpperCAmelCase)






    def      __snake_case							( self    :   Tuple):
      a						:		List[str]											=      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase)






    def      __snake_case							( self    :   Optional[int]):
      a						:		Dict											=      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCAmelCase)






    @slow
    def      __snake_case							( self    :   Optional[int]):
      for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a						:		Optional[Any]											=      MobileViTVaModel.from_pretrained(__UpperCAmelCase)
        self.assertIsNotNone(__UpperCAmelCase)






def 					lowercase      (    )->				Dict:
  '''simple docstring'''







  a						:		Optional[Any]											=      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
  return image







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







    """simple docstring"""




    @cached_property
    def      __snake_case							( self    :   Tuple):
      return (
          MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")
          if is_vision_available()
          else None
      )






    @slow
    def      __snake_case							( self    :   List[Any]):
      a						:		Optional[int]											=      MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256").to(
          __UpperCAmelCase)

      a						:		Union[str, Any]											=      self.default_image_processor
      a						:		Optional[Any]											=      prepare_img()
      a						:		Union[str, Any]											=      image_processor(images=__UpperCAmelCase    ,			return_tensors="pt").to(__UpperCAmelCase)

      # forward pass
      with torch.no_grad():
        a						:		str											=      model(**__UpperCAmelCase)

      # verify the logits
      a						:		Dict											=      torch.Size((1, 1000))
      self.assertEqual(outputs.logits.shape    ,			__UpperCAmelCase)

      a						:		int											=      torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01]).to(__UpperCAmelCase)

      self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,			__UpperCAmelCase    ,			atol=1e-4))






    @slow
    def      __snake_case							( self    :   str):
      a						:		Optional[Any]											=      MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3")
      a						:		Optional[Any]											=      model.to(__UpperCAmelCase)

      a						:		Optional[Any]											=      MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3")

      a						:		Optional[Any]											=      prepare_img()
      a						:		Any											=      image_processor(images=__UpperCAmelCase    ,			return_tensors="pt").to(__UpperCAmelCase)

      # forward pass
      with torch.no_grad():
        a						:		Union[str, Any]											=      model(**__UpperCAmelCase)
      a						:		int											=      outputs.logits

      # verify the logits
      a						:		Dict											=      torch.Size((1, 21, 32, 32))
      self.assertEqual(logits.shape    ,			__UpperCAmelCase)

      a						:		Optional[int]											=      torch.tensor(
          [
              [[7.0_863, 7.1_525, 6.8_201], [6.6_931, 6.8_770, 6.8_933], [6.2_978, 7.0_366, 6.9_636]],
              [[-3.7_134, -3.6_712, -3.6_675], [-3.5_825, -3.3_549, -3.4_777], [-3.3_435, -3.3_979, -3.2_857]],
              [[-2.9_329, -2.8_003, -2.7_369], [-3.0_564, -2.4_780, -2.0_207], [-2.6_889, -1.9_298, -1.7_640]],
          ]    ,			device=__UpperCAmelCase    ,			)

      self.assertTrue(torch.allclose(logits[0, :3, :3, :3]    ,			__UpperCAmelCase    ,			atol=1e-4))






    @slow
    def      __snake_case							( self    :   List[str]):
      a						:		Optional[Any]											=      MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3")
      a						:		str											=      model.to(__UpperCAmelCase)

      a						:		Union[str, Any]											=      MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3")

      a						:		List[Any]											=      prepare_img()
      a						:		Dict											=      image_processor(images=__UpperCAmelCase    ,			return_tensors="pt").to(__UpperCAmelCase)

      # forward pass
      with torch.no_grad():
        a						:		str											=      model(**__UpperCAmelCase)

      a						:		int											=      outputs.logits.detach().cpu()

      a						:		Union[str, Any]											=      image_processor.post_process_semantic_segmentation(outputs=__UpperCAmelCase    ,			target_sizes=[(50, 60)])
      a						:		str											=      torch.Size((50, 60))
      self.assertEqual(segmentation[0].shape    ,			__UpperCAmelCase)

      a						:		Optional[int]											=      image_processor.post_process_semantic_segmentation(outputs=__UpperCAmelCase)
      a						:		Tuple											=      torch.Size((32, 32))
      self.assertEqual(segmentation[0].shape    ,			__UpperCAmelCase)










"""simple docstring"""







import argparse
import json

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation


def 					lowercase      (    A_	)->				Optional[Any]:
  '''simple docstring'''







  a						:		Optional[Any]											=      384
  if "tiny" in model_name:
    a						:		List[str]											=      [3, 3, 9, 3]
    a						:		Optional[Any]											=      [96, 192, 384, 768]
  if "small" in model_name:
    a						:		Tuple											=      [3, 3, 27, 3]
    a						:		str											=      [96, 192, 384, 768]
  if "base" in model_name:
    a						:		Union[str, Any]											=      [3, 3, 27, 3]
    a						:		Dict											=      [128, 256, 512, 1_024]
    a						:		Any											=      512
  if "large" in model_name:
    a						:		Optional[Any]											=      [3, 3, 27, 3]
    a						:		str											=      [192, 384, 768, 1_536]
    a						:		Dict											=      768
  if "xlarge" in model_name:
    a						:		str											=      [3, 3, 27, 3]
    a						:		List[Any]											=      [256, 512, 1_024, 2_048]
    a						:		List[Any]											=      1_024

  # set label information
  a						:		int											=      150
  a						:		str											=      "huggingface/label-files"
  a						:		Tuple											=      "ade20k-id2label.json"
  a						:		Dict											=      json.load(open(hf_hub_download(A_  ,       A_  ,       repo_type="dataset"	)  ,       "r"	)	)
  a						:		int											=      {int(A_	): v for k, v in idalabel.items()}
  a						:		List[Any]											=      {v: k for k, v in idalabel.items()}

  a						:		Optional[int]											=      ConvNextConfig(
      depths=A_  ,       hidden_sizes=A_  ,       out_features=["stage1", "stage2", "stage3", "stage4"]	)
  a						:		Tuple											=      UperNetConfig(
      backbone_config=A_  ,       auxiliary_in_channels=A_  ,       num_labels=A_  ,       idalabel=A_  ,       labelaid=A_  ,       )

  return config


def 					lowercase      (    A_	)->				Tuple:
  '''simple docstring'''







  a						:		int											=      []

  # fmt: off
  # stem
  rename_keys.append(("backbone.downsample_layers.0.0.weight", "backbone.embeddings.patch_embeddings.weight")	)
  rename_keys.append(("backbone.downsample_layers.0.0.bias", "backbone.embeddings.patch_embeddings.bias")	)
  rename_keys.append(("backbone.downsample_layers.0.1.weight", "backbone.embeddings.layernorm.weight")	)
  rename_keys.append(("backbone.downsample_layers.0.1.bias", "backbone.embeddings.layernorm.bias")	)
  # stages
  for i in range(len(config.backbone_config.depths	)	):
    for j in range(config.backbone_config.depths[i]	):
      rename_keys.append((F'''backbone.stages.{i}.{j}.gamma''', F'''backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter''')	)
      rename_keys.append((F'''backbone.stages.{i}.{j}.depthwise_conv.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.dwconv.weight''')	)
      rename_keys.append((F'''backbone.stages.{i}.{j}.depthwise_conv.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.dwconv.bias''')	)
      rename_keys.append((F'''backbone.stages.{i}.{j}.norm.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.layernorm.weight''')	)
      rename_keys.append((F'''backbone.stages.{i}.{j}.norm.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.layernorm.bias''')	)
      rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv1.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight''')	)
      rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv1.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias''')	)
      rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv2.weight''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight''')	)
      rename_keys.append((F'''backbone.stages.{i}.{j}.pointwise_conv2.bias''', F'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias''')	)
    if i > 0:
      rename_keys.append((F'''backbone.downsample_layers.{i}.0.weight''', F'''backbone.encoder.stages.{i}.downsampling_layer.0.weight''')	)
      rename_keys.append((F'''backbone.downsample_layers.{i}.0.bias''', F'''backbone.encoder.stages.{i}.downsampling_layer.0.bias''')	)
      rename_keys.append((F'''backbone.downsample_layers.{i}.1.weight''', F'''backbone.encoder.stages.{i}.downsampling_layer.1.weight''')	)
      rename_keys.append((F'''backbone.downsample_layers.{i}.1.bias''', F'''backbone.encoder.stages.{i}.downsampling_layer.1.bias''')	)

    rename_keys.append((F'''backbone.norm{i}.weight''', F'''backbone.hidden_states_norms.stage{i+1}.weight''')	)
    rename_keys.append((F'''backbone.norm{i}.bias''', F'''backbone.hidden_states_norms.stage{i+1}.bias''')	)

  # decode head
  rename_keys.extend(
      [
          ("decode_head.conv_seg.weight", "decode_head.classifier.weight"),
          ("decode_head.conv_seg.bias", "decode_head.classifier.bias"),
          ("auxiliary_head.conv_seg.weight", "auxiliary_head.classifier.weight"),
          ("auxiliary_head.conv_seg.bias", "auxiliary_head.classifier.bias"),
      ]	)
  # fmt: on

  return rename_keys


def 					lowercase      (    A_  ,       A_  ,       A_	)->				str:
  '''simple docstring'''







  a						:		str											=      dct.pop(A_	)
  a						:		str											=      val


def 					lowercase      (    A_  ,       A_  ,       A_	)->				int:
  '''simple docstring'''







  a						:		Any											=      {
      "upernet-convnext-tiny": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth",
      "upernet-convnext-small": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth",
      "upernet-convnext-base": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth",
      "upernet-convnext-large": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth",
      "upernet-convnext-xlarge": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth",
  }
  a						:		Tuple											=      model_name_to_url[model_name]
  a						:		int											=      torch.hub.load_state_dict_from_url(A_  ,       map_location="cpu"	)["state_dict"]

  a						:		Optional[Any]											=      get_upernet_config(A_	)
  a						:		int											=      UperNetForSemanticSegmentation(A_	)
  model.eval()

  # replace "bn" => "batch_norm"
  for key in state_dict.copy().keys():
    a						:		Tuple											=      state_dict.pop(A_	)
    if "bn" in key:
      a						:		Optional[int]											=      key.replace("bn"  ,       "batch_norm"	)
    a						:		Any											=      val

  # rename keys
  a						:		Any											=      create_rename_keys(A_	)
  for src, dest in rename_keys:
    rename_key(A_  ,       A_  ,       A_	)

  model.load_state_dict(A_	)

  # verify on image
  a						:		Dict											=      "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"
  a						:		Any											=      Image.open(requests.get(A_  ,       stream=A_	).raw	).convert("RGB"	)

  a						:		Union[str, Any]											=      SegformerImageProcessor()
  a						:		Dict											=      processor(A_  ,       return_tensors="pt"	).pixel_values

  with torch.no_grad():
    a						:		Any											=      model(A_	)

  if model_name == "upernet-convnext-tiny":
    a						:		List[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]]	)
  elif model_name == "upernet-convnext-small":
    a						:		int											=      torch.tensor(
        [[-8.8_2_3_6, -8.8_2_3_6, -8.6_7_7_1], [-8.8_2_3_6, -8.8_2_3_6, -8.6_7_7_1], [-8.7_6_3_8, -8.7_6_3_8, -8.6_2_4_0]]	)
  elif model_name == "upernet-convnext-base":
    a						:		Union[str, Any]											=      torch.tensor(
        [[-8.8_5_5_8, -8.8_5_5_8, -8.6_9_0_5], [-8.8_5_5_8, -8.8_5_5_8, -8.6_9_0_5], [-8.7_6_6_9, -8.7_6_6_9, -8.6_0_2_1]]	)
  elif model_name == "upernet-convnext-large":
    a						:		Union[str, Any]											=      torch.tensor(
        [[-8.6_6_6_0, -8.6_6_6_0, -8.6_2_1_0], [-8.6_6_6_0, -8.6_6_6_0, -8.6_2_1_0], [-8.6_3_1_0, -8.6_3_1_0, -8.5_9_6_4]]	)
  elif model_name == "upernet-convnext-xlarge":
    a						:		str											=      torch.tensor(
        [[-8.4_9_8_0, -8.4_9_8_0, -8.3_9_7_7], [-8.4_9_8_0, -8.4_9_8_0, -8.3_9_7_7], [-8.4_3_7_9, -8.4_3_7_9, -8.3_4_1_2]]	)
  print("Logits:"  ,       outputs.logits[0, 0, :3, :3]	)
  assert torch.allclose(outputs.logits[0, 0, :3, :3]  ,       A_  ,       atol=1e-4	)
  print("Looks ok!"	)

  if pytorch_dump_folder_path is not None:
    print(F'''Saving model {model_name} to {pytorch_dump_folder_path}'''	)
    model.save_pretrained(A_	)
    print(F'''Saving processor to {pytorch_dump_folder_path}'''	)
    processor.save_pretrained(A_	)

  if push_to_hub:
    print(F'''Pushing model and processor for {model_name} to hub'''	)
    model.push_to_hub(F'''openmmlab/{model_name}'''	)
    processor.push_to_hub(F'''openmmlab/{model_name}'''	)


if __name__ == "__main__":
 __lowercase    =				argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     """--model_name""",
     default="""upernet-convnext-tiny""",
     type=str,
     choices=[f'''upernet-convnext-{size}''' for size in ["""tiny""", """small""", """base""", """large""", """xlarge"""]],
     help="""Name of the ConvNext UperNet model you'd like to convert.""",
 )
 parser.add_argument(
     """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
 )
 parser.add_argument(
     """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
 )

 __lowercase    =				parser.parse_args()
 convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)






