





from importlib import import_module

from .logging import get_logger


lowercase				:	Union[str, Any]      						=  get_logger(__name__)





class 			A__   :




   """simple docstring"""



   def __init__( self ,  lowercase ,  lowercase=None)      ->						Tuple:







          '''simple docstring'''

          a__						:     Tuple			=    attrs or []
          if module is not None:
                 for key in module.__dict__:
                        if key in attrs or not key.startswith('__'):
                               setattr(self ,  lowercase ,  getattr(lowercase ,  lowercase))
          a__						:     Any			=    module._original_module if isinstance(lowercase ,  _PatchedModuleObj) else module





class 			A__   :




   """simple docstring"""



   __A       :    Tuple	  =  []

   def __init__( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None)      ->						Optional[int]:







          '''simple docstring'''

          a__						:     int			=    obj
          a__						:     int			=    target
          a__						:     Optional[int]			=    new
          a__						:     Optional[int]			=    target.split('.')[0]
          a__						:     Optional[int]			=    {}
          a__						:     Optional[Any]			=    attrs or []

   def __enter__( self)      ->						int:







          '''simple docstring'''

          *a__			,							a__						:     Optional[Any]			=    self.target.split('.')

          # Patch modules:
          # it's used to patch attributes of submodules like "os.path.join";
          # in this case we need to patch "os" and "os.path"

          for i in range(len(lowercase)):
                 try:
                        a__						:     Tuple			=    import_module('.'.join(submodules[: i + 1]))
                 except ModuleNotFoundError:
                        continue
                 # We iterate over all the globals in self.obj in case we find "os" or "os.path"
                 for attr in self.obj.__dir__():
                        a__						:     List[Any]			=    getattr(self.obj ,  lowercase)
                        # We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
                        # This allows to patch renamed modules like "from os import path as ospath".
                        if obj_attr is submodule or (
                            (isinstance(lowercase ,  _PatchedModuleObj) and obj_attr._original_module is submodule)
                        ):
                               a__						:     int			=    obj_attr
                               # patch at top level
                               setattr(self.obj ,  lowercase ,  _PatchedModuleObj(lowercase ,  attrs=self.attrs))
                               a__						:     Dict			=    getattr(self.obj ,  lowercase)
                               # construct lower levels patches
                               for key in submodules[i + 1 :]:
                                      setattr(lowercase ,  lowercase ,  _PatchedModuleObj(getattr(lowercase ,  lowercase ,  lowercase) ,  attrs=self.attrs))
                                      a__						:     int			=    getattr(lowercase ,  lowercase)
                               # finally set the target attribute
                               setattr(lowercase ,  lowercase ,  self.new)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

          if submodules:  # if it's an attribute of a submodule like "os.path.join"
                 try:
                        a__						:     List[str]			=    getattr(import_module('.'.join(lowercase)) ,  lowercase)
                 except (AttributeError, ModuleNotFoundError):
                        return
                 # We iterate over all the globals in self.obj in case we find "os.path.join"
                 for attr in self.obj.__dir__():
                        # We don't check for the name of the global, but rather if its value *is* "os.path.join".
                        # This allows to patch renamed attributes like "from os.path import join as pjoin".
                        if getattr(self.obj ,  lowercase) is attr_value:
                               a__						:     str			=    getattr(self.obj ,  lowercase)
                               setattr(self.obj ,  lowercase ,  self.new)
          elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
                 a__						:     Any			=    globals()['__builtins__'][target_attr]
                 setattr(self.obj ,  lowercase ,  self.new)
          else:
                 raise RuntimeError(F'Tried to patch attribute {target_attr} instead of a submodule.')

   def __exit__( self ,  *lowercase)      ->						Dict:







          '''simple docstring'''

          for attr in list(self.original):
                 setattr(self.obj ,  lowercase ,  self.original.pop(lowercase))

   def 							__lowercase		( self)      ->						int:







          '''simple docstring'''

          self.__enter__()
          self._active_patches.append(self)

   def 							__lowercase		( self)      ->						int:







          '''simple docstring'''

          try:
                 self._active_patches.remove(self)
          except ValueError:
                 # If the patch hasn't been started this will fail
                 return None

          return self.__exit__()









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 A_     (		A__    )  ->		str:
       a__						:     Any			=    384
       if "tiny" in model_name:
              a__						:     List[Any]			=    [3, 3, 9, 3]
              a__						:     Optional[Any]			=    [96, 192, 384, 768]
       if "small" in model_name:
              a__						:     Union[str, Any]			=    [3, 3, 27, 3]
              a__						:     List[Any]			=    [96, 192, 384, 768]
       if "base" in model_name:
              a__						:     int			=    [3, 3, 27, 3]
              a__						:     List[str]			=    [128, 256, 512, 1024]
              a__						:     Optional[int]			=    512
       if "large" in model_name:
              a__						:     Optional[int]			=    [3, 3, 27, 3]
              a__						:     Any			=    [192, 384, 768, 1536]
              a__						:     int			=    768
       if "xlarge" in model_name:
              a__						:     str			=    [3, 3, 27, 3]
              a__						:     int			=    [256, 512, 1024, 2048]
              a__						:     List[str]			=    1024

       # set label information
       a__						:     int			=    150
       a__						:     List[Any]			=    'huggingface/label-files'
       a__						:     str			=    'ade20k-id2label.json'
       a__						:     Optional[int]			=    json.load(open(hf_hub_download(A__		,				A__		,				repo_type='dataset'    )		,				'r'    )    )
       a__						:     List[str]			=    {int(A__    ): v for k, v in idalabel.items()}
       a__						:     Union[str, Any]			=    {v: k for k, v in idalabel.items()}

       a__						:     List[Any]			=    ConvNextConfig(
           depths=A__		,				hidden_sizes=A__		,				out_features=['stage1', 'stage2', 'stage3', 'stage4']    )
       a__						:     Optional[int]			=    UperNetConfig(
           backbone_config=A__		,				auxiliary_in_channels=A__		,				num_labels=A__		,				idalabel=A__		,				labelaid=A__		,				)

       return config



def A_     (		A__    )  ->		Tuple:
       a__						:     Optional[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 A_     (		A__		,				A__		,				A__    )  ->		str:
       a__						:     List[str]			=    dct.pop(A__    )
       a__						:     int			=    val



def A_     (		A__		,				A__		,				A__    )  ->		str:
       a__						:     Tuple			=    {
           '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__						:     Dict			=    model_name_to_url[model_name]
       a__						:     Optional[int]			=    torch.hub.load_state_dict_from_url(A__		,				map_location='cpu'    )['state_dict']

       a__						:     List[Any]			=    get_upernet_config(A__    )
       a__						:     Dict			=    UperNetForSemanticSegmentation(A__    )
       model.eval()

       # replace "bn" => "batch_norm"
       for key in state_dict.copy().keys():
              a__						:     Dict			=    state_dict.pop(A__    )
              if "bn" in key:
                     a__						:     Optional[int]			=    key.replace('bn'		,				'batch_norm'    )
              a__						:     List[Any]			=    val

       # rename keys
       a__						:     Union[str, 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__						:     str			=    'https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg'
       a__						:     int			=    Image.open(requests.get(A__		,				stream=A__    ).raw    ).convert('RGB'    )

       a__						:     Union[str, Any]			=    SegformerImageProcessor()
       a__						:     Union[str, Any]			=    processor(A__		,				return_tensors='pt'    ).pixel_values

       with torch.no_grad():
              a__						:     Optional[Any]			=    model(A__    )

       if model_name == "upernet-convnext-tiny":
              a__						:     Union[str, Any]			=    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]]    )
       elif model_name == "upernet-convnext-small":
              a__						:     int			=    torch.tensor(
                  [[-8.82_36, -8.82_36, -8.67_71], [-8.82_36, -8.82_36, -8.67_71], [-8.76_38, -8.76_38, -8.62_40]]    )
       elif model_name == "upernet-convnext-base":
              a__						:     int			=    torch.tensor(
                  [[-8.85_58, -8.85_58, -8.69_05], [-8.85_58, -8.85_58, -8.69_05], [-8.76_69, -8.76_69, -8.60_21]]    )
       elif model_name == "upernet-convnext-large":
              a__						:     Optional[Any]			=    torch.tensor(
                  [[-8.66_60, -8.66_60, -8.62_10], [-8.66_60, -8.66_60, -8.62_10], [-8.63_10, -8.63_10, -8.59_64]]    )
       elif model_name == "upernet-convnext-xlarge":
              a__						:     Optional[int]			=    torch.tensor(
                  [[-8.49_80, -8.49_80, -8.39_77], [-8.49_80, -8.49_80, -8.39_77], [-8.43_79, -8.43_79, -8.34_12]]    )
       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				:	Optional[Any]      						=  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				:	str      						=  parser.parse_args()
    convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)


