

'''simple docstring'''

import argparse
import json

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

from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD


torch.set_grad_enabled(False)





def       A_     (       snake_case					,				snake_case=False       ):
  SCREAMING_SNAKE_CASE:Dict  					=    []
  for i in range(config.num_hidden_layers       ):
    # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
    rename_keys.append((F'''module.blocks.{i}.norm1.weight''', F'''vit.encoder.layer.{i}.layernorm_before.weight''')       )
    rename_keys.append((F'''module.blocks.{i}.norm1.bias''', F'''vit.encoder.layer.{i}.layernorm_before.bias''')       )
    rename_keys.append(
        (F'''module.blocks.{i}.attn.proj.weight''', F'''vit.encoder.layer.{i}.attention.output.dense.weight''')       )
    rename_keys.append((F'''module.blocks.{i}.attn.proj.bias''', F'''vit.encoder.layer.{i}.attention.output.dense.bias''')       )
    rename_keys.append((F'''module.blocks.{i}.norm2.weight''', F'''vit.encoder.layer.{i}.layernorm_after.weight''')       )
    rename_keys.append((F'''module.blocks.{i}.norm2.bias''', F'''vit.encoder.layer.{i}.layernorm_after.bias''')       )
    rename_keys.append((F'''module.blocks.{i}.mlp.fc1.weight''', F'''vit.encoder.layer.{i}.intermediate.dense.weight''')       )
    rename_keys.append((F'''module.blocks.{i}.mlp.fc1.bias''', F'''vit.encoder.layer.{i}.intermediate.dense.bias''')       )
    rename_keys.append((F'''module.blocks.{i}.mlp.fc2.weight''', F'''vit.encoder.layer.{i}.output.dense.weight''')       )
    rename_keys.append((F'''module.blocks.{i}.mlp.fc2.bias''', F'''vit.encoder.layer.{i}.output.dense.bias''')       )

  # projection layer + position embeddings
  rename_keys.extend(
      [
          ("module.cls_token", "vit.embeddings.cls_token"),
          ("module.patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"),
          ("module.patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"),
          ("module.pos_embed", "vit.embeddings.position_embeddings"),
      ]       )

  if base_model:
    # layernorm + pooler
    rename_keys.extend(
        [
            ("module.norm.weight", "layernorm.weight"),
            ("module.norm.bias", "layernorm.bias"),
        ]       )

    # if just the base model, we should remove "vit" from all keys that start with "vit"
    SCREAMING_SNAKE_CASE:Dict  					=    [(pair[0], pair[1][4:]) if pair[1].startswith("vit"       ) else pair for pair in rename_keys]
  else:
    # layernorm + classification head
    rename_keys.extend(
        [
            ("norm.weight", "vit.layernorm.weight"),
            ("norm.bias", "vit.layernorm.bias"),
            ("head.weight", "classifier.weight"),
            ("head.bias", "classifier.bias"),
        ]       )

  return rename_keys





def       A_     (       snake_case					,				snake_case					,				snake_case=False       ):



  for i in range(config.num_hidden_layers       ):
    if base_model:
      SCREAMING_SNAKE_CASE:str  					=    ""
    else:
      SCREAMING_SNAKE_CASE:Optional[int]  					=    "vit."
    # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
    SCREAMING_SNAKE_CASE:Any  					=    state_dict.pop(F'''module.blocks.{i}.attn.qkv.weight'''       )
    SCREAMING_SNAKE_CASE:List[str]  					=    state_dict.pop(F'''module.blocks.{i}.attn.qkv.bias'''       )
    # next, add query, keys and values (in that order) to the state dict
    SCREAMING_SNAKE_CASE:Optional[Any]  					=    in_proj_weight[
        : config.hidden_size, :
    ]
    SCREAMING_SNAKE_CASE:int  					=    in_proj_bias[: config.hidden_size]
    SCREAMING_SNAKE_CASE:str  					=    in_proj_weight[
        config.hidden_size : config.hidden_size * 2, :
    ]
    SCREAMING_SNAKE_CASE:List[str]  					=    in_proj_bias[
        config.hidden_size : config.hidden_size * 2
    ]
    SCREAMING_SNAKE_CASE:Dict  					=    in_proj_weight[
        -config.hidden_size :, :
    ]
    SCREAMING_SNAKE_CASE:Union[str, Any]  					=    in_proj_bias[-config.hidden_size :]





def       A_     (       snake_case       ):
  SCREAMING_SNAKE_CASE:Optional[Any]  					=    ["head.weight", "head.bias"]
  for k in ignore_keys:
    state_dict.pop(__A					,				__A       )





def       A_     (       snake_case       ):
  SCREAMING_SNAKE_CASE:List[Any]  					=    [
      "module.fc.fc1.weight",
      "module.fc.fc1.bias",
      "module.fc.bn1.weight",
      "module.fc.bn1.bias",
      "module.fc.bn1.running_mean",
      "module.fc.bn1.running_var",
      "module.fc.bn1.num_batches_tracked",
      "module.fc.fc2.weight",
      "module.fc.fc2.bias",
      "module.fc.bn2.weight",
      "module.fc.bn2.bias",
      "module.fc.bn2.running_mean",
      "module.fc.bn2.running_var",
      "module.fc.bn2.num_batches_tracked",
      "module.fc.fc3.weight",
      "module.fc.fc3.bias",
  ]
  for k in ignore_keys:
    state_dict.pop(__A					,				__A       )





def       A_     (       snake_case					,				snake_case					,				snake_case       ):
  SCREAMING_SNAKE_CASE:Optional[Any]  					=    dct.pop(__A       )
  SCREAMING_SNAKE_CASE:List[Any]  					=    val





def       A_     (       snake_case					,				snake_case       ):
  SCREAMING_SNAKE_CASE:List[str]  					=    ViTMSNConfig()
  SCREAMING_SNAKE_CASE:Optional[Any]  					=    1000

  SCREAMING_SNAKE_CASE:int  					=    "datasets/huggingface/label-files"
  SCREAMING_SNAKE_CASE:Optional[int]  					=    "imagenet-1k-id2label.json"
  SCREAMING_SNAKE_CASE:str  					=    json.load(open(hf_hub_download(__A					,				__A       )					,				"r"       )       )
  SCREAMING_SNAKE_CASE:Optional[int]  					=    {int(__A       ): v for k, v in idalabel.items()}
  SCREAMING_SNAKE_CASE:Any  					=    idalabel
  SCREAMING_SNAKE_CASE:Tuple  					=    {v: k for k, v in idalabel.items()}

  if "s16" in checkpoint_url:
    SCREAMING_SNAKE_CASE:Any  					=    384
    SCREAMING_SNAKE_CASE:Tuple  					=    1536
    SCREAMING_SNAKE_CASE:str  					=    6
  elif "l16" in checkpoint_url:
    SCREAMING_SNAKE_CASE:Optional[Any]  					=    1024
    SCREAMING_SNAKE_CASE:Union[str, Any]  					=    4096
    SCREAMING_SNAKE_CASE:List[str]  					=    24
    SCREAMING_SNAKE_CASE:Tuple  					=    16
    SCREAMING_SNAKE_CASE:Dict  					=    0.1
  elif "b4" in checkpoint_url:
    SCREAMING_SNAKE_CASE:List[str]  					=    4
  elif "l7" in checkpoint_url:
    SCREAMING_SNAKE_CASE:Tuple  					=    7
    SCREAMING_SNAKE_CASE:List[str]  					=    1024
    SCREAMING_SNAKE_CASE:Union[str, Any]  					=    4096
    SCREAMING_SNAKE_CASE:Dict  					=    24
    SCREAMING_SNAKE_CASE:Optional[int]  					=    16
    SCREAMING_SNAKE_CASE:Tuple  					=    0.1

  SCREAMING_SNAKE_CASE:Dict  					=    ViTMSNModel(__A       )

  SCREAMING_SNAKE_CASE:Dict  					=    torch.hub.load_state_dict_from_url(__A					,				map_location="cpu"       )["target_encoder"]

  SCREAMING_SNAKE_CASE:Tuple  					=    ViTImageProcessor(size=config.image_size       )

  remove_projection_head(__A       )
  SCREAMING_SNAKE_CASE:List[str]  					=    create_rename_keys(__A					,				base_model=__A       )

  for src, dest in rename_keys:
    rename_key(__A					,				__A					,				__A       )
  read_in_q_k_v(__A					,				__A					,				base_model=__A       )

  model.load_state_dict(__A       )
  model.eval()

  SCREAMING_SNAKE_CASE:Union[str, Any]  					=    "http://images.cocodataset.org/val2017/000000039769.jpg"

  SCREAMING_SNAKE_CASE:int  					=    Image.open(requests.get(__A					,				stream=__A       ).raw       )
  SCREAMING_SNAKE_CASE:List[Any]  					=    ViTImageProcessor(
      size=config.image_size					,				image_mean=__A					,				image_std=__A       )
  SCREAMING_SNAKE_CASE:Optional[Any]  					=    image_processor(images=__A					,				return_tensors="pt"       )

  # forward pass
  torch.manual_seed(2       )
  SCREAMING_SNAKE_CASE:Any  					=    model(**__A       )
  SCREAMING_SNAKE_CASE:Any  					=    outputs.last_hidden_state

  # The following Colab Notebook was used to generate these outputs:
  # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb
  if "s16" in checkpoint_url:
    SCREAMING_SNAKE_CASE:Any  					=    torch.tensor([[-1.0915, -1.4876, -1.1809]]       )
  elif "b16" in checkpoint_url:
    SCREAMING_SNAKE_CASE:Any  					=    torch.tensor([[14.2889, -18.9045, 11.7281]]       )
  elif "l16" in checkpoint_url:
    SCREAMING_SNAKE_CASE:Any  					=    torch.tensor([[41.5028, -22.8681, 45.6475]]       )
  elif "b4" in checkpoint_url:
    SCREAMING_SNAKE_CASE:int  					=    torch.tensor([[-4.3868, 5.2932, -0.4137]]       )
  else:
    SCREAMING_SNAKE_CASE:Dict  					=    torch.tensor([[-0.1792, -0.6465, 2.4263]]       )

  # verify logits
  assert torch.allclose(last_hidden_state[:, 0, :3]					,				__A					,				atol=1e-4       )

  print(F'''Saving model to {pytorch_dump_folder_path}'''       )
  model.save_pretrained(__A       )

  print(F'''Saving image processor to {pytorch_dump_folder_path}'''       )
  image_processor.save_pretrained(__A       )


if __name__ == "__main__":
    A_				  =							argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        "--checkpoint_url",
        default="https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar",
        type=str,
        help="URL of the checkpoint you'd like to convert.",
    )
    parser.add_argument(
        "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
    )

    A_				  =							parser.parse_args()
    convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)











'''simple docstring'''





from typing import Dict, Optional

import numpy as np

import datasets


lowercase_		       =  "\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n"

lowercase_		       =  "\nArgs:\n    predictions (`List[ndarray]`):\n        List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    references (`List[ndarray]`):\n        List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    num_labels (`int`):\n        Number of classes (categories).\n    ignore_index (`int`):\n        Index that will be ignored during evaluation.\n    nan_to_num (`int`, *optional*):\n        If specified, NaN values will be replaced by the number defined by the user.\n    label_map (`dict`, *optional*):\n        If specified, dictionary mapping old label indices to new label indices.\n    reduce_labels (`bool`, *optional*, defaults to `False`):\n        Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n        and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n    `Dict[str, float | ndarray]` comprising various elements:\n    - *mean_iou* (`float`):\n        Mean Intersection-over-Union (IoU averaged over all categories).\n    - *mean_accuracy* (`float`):\n        Mean accuracy (averaged over all categories).\n    - *overall_accuracy* (`float`):\n        Overall accuracy on all images.\n    - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n        Per category accuracy.\n    - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n        Per category IoU.\n\nExamples:\n\n    >>> import numpy as np\n\n    >>> mean_iou = datasets.load_metric(\"mean_iou\")\n\n    >>> # suppose one has 3 different segmentation maps predicted\n    >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n    >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n    >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n    >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n    >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n    >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n    >>> predicted = [predicted_1, predicted_2, predicted_3]\n    >>> ground_truth = [actual_1, actual_2, actual_3]\n\n    >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n    >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n    {'mean_iou': 0.47750000000000004, 'mean_accuracy': 0.5916666666666666, 'overall_accuracy': 0.5263157894736842, 'per_category_iou': array([0.   , 0.   , 0.375, 0.4  , 0.5  , 0.   , 0.5  , 1.   , 1.   , 1.   ]), 'per_category_accuracy': array([0.        , 0.        , 0.75      , 0.66666667, 1.        , 0.        , 0.5       , 1.        , 1.        , 1.        ])}\n"

lowercase_		       =  "\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}"




def lowerCAmelCase  (__A  ,	__A  ,	__A  ,	__A  ,	__A = None  ,	__A = False  ,	):



     """simple docstring"""



     if label_map is not None:
          for old_id, new_id in label_map.items():
               _a      =  new_id

    # turn into Numpy arrays
     _a      =  np.array(__A)
     _a      =  np.array(__A)

     if reduce_labels:
          _a      =  255
          _a      =  label - 1
          _a      =  255

     _a      =  label != ignore_index
     _a      =  np.not_equal(__A  ,	__A)
     _a      =  pred_label[mask]
     _a      =  np.array(__A)[mask]

     _a      =  pred_label[pred_label == label]

     _a      =  np.histogram(__A  ,	bins=__A  ,	range=(0, num_labels - 1))[0]
     _a      =  np.histogram(__A  ,	bins=__A  ,	range=(0, num_labels - 1))[0]
     _a      =  np.histogram(__A  ,	bins=__A  ,	range=(0, num_labels - 1))[0]

     _a      =  area_pred_label + area_label - area_intersect

     return area_intersect, area_union, area_pred_label, area_label




def lowerCAmelCase  (__A  ,	__A  ,	__A  ,	__A  ,	__A = None  ,	__A = False  ,	):



     """simple docstring"""



     _a      =  np.zeros((num_labels,)  ,	dtype=np.floataa)
     _a      =  np.zeros((num_labels,)  ,	dtype=np.floataa)
     _a      =  np.zeros((num_labels,)  ,	dtype=np.floataa)
     _a      =  np.zeros((num_labels,)  ,	dtype=np.floataa)
     for result, gt_seg_map in zip(__A  ,	__A):
          _a  ,    _a  ,    _a  ,    _a      =  intersect_and_union(
              __A  ,	__A  ,	__A  ,	__A  ,	__A  ,	__A)
          total_area_intersect += area_intersect
          total_area_union += area_union
          total_area_pred_label += area_pred_label
          total_area_label += area_label
     return total_area_intersect, total_area_union, total_area_pred_label, total_area_label




def lowerCAmelCase  (__A  ,	__A  ,	__A  ,	__A  ,	__A = None  ,	__A = None  ,	__A = False  ,	):



     """simple docstring"""



     _a  ,    _a  ,    _a  ,    _a      =  total_intersect_and_union(
         __A  ,	__A  ,	__A  ,	__A  ,	__A  ,	__A)

     # compute metrics
     _a      =  {}

     _a      =  total_area_intersect.sum() / total_area_label.sum()
     _a      =  total_area_intersect / total_area_union
     _a      =  total_area_intersect / total_area_label

     _a      =  np.nanmean(__A)
     _a      =  np.nanmean(__A)
     _a      =  all_acc
     _a      =  iou
     _a      =  acc

     if nan_to_num is not None:
          _a      =  {metric: np.nan_to_num(__A  ,	nan=__A) for metric, metric_value in metrics.items()}

     return metrics






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,   _KWARGS_DESCRIPTION						)
class __A			(  datasets.Metric						):



 '''simple docstring'''







 def 					a__  (self       )    ->     List[str]:


      """simple docstring"""



      return datasets.MetricInfo(
          description=_DESCRIPTION ,   citation=_CITATION ,   inputs_description=_KWARGS_DESCRIPTION ,   features=datasets.Features(
              # 1st Seq - height dim, 2nd - width dim
              {
                  '''predictions''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16'''       )       )       ),
                  '''references''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16'''       )       )       ),
              }       ) ,   reference_urls=[
              '''https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py'''
          ] ,   )



 def 					a__  (self ,   A ,   A ,   A ,   A ,   A = None ,   A = None ,   A = False ,   )    ->     List[Any]:


      """simple docstring"""



      _a      =  mean_iou(
          results=A ,   gt_seg_maps=A ,   num_labels=A ,   ignore_index=A ,   nan_to_num=A ,   label_map=A ,   reduce_labels=A ,   )
      return iou_result



