


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



def  _a			(						__UpperCamelCase ):
     a_    :     Optional[Any]										=    ["""head.weight""", """head.bias"""]
     for k in ignore_keys:
          state_dict.pop(_SCREAMING_SNAKE_CASE  ,  _SCREAMING_SNAKE_CASE )



def  _a			(						__UpperCamelCase ):
     # projection head is used in the self-supervised pre-training in MSN,
     # for downstream task it's not needed.
     a_    :     int										=    [
         """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(_SCREAMING_SNAKE_CASE  ,  _SCREAMING_SNAKE_CASE )



def  _a			(						__UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase ):
     a_    :     Tuple										=    dct.pop(_SCREAMING_SNAKE_CASE )
     a_    :     Optional[int]										=    val



def  _a			(						__UpperCamelCase  ,  __UpperCamelCase ):
     a_    :     Dict										=    ViTMSNConfig()
     a_    :     Tuple										=    1_0_0_0

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

     if "s16" in checkpoint_url:
          a_    :     Tuple										=    3_8_4
          a_    :     List[Any]										=    1_5_3_6
          a_    :     Optional[int]										=    6
     elif "l16" in checkpoint_url:
          a_    :     List[str]										=    1_0_2_4
          a_    :     int										=    4_0_9_6
          a_    :     List[str]										=    2_4
          a_    :     int										=    1_6
          a_    :     Optional[int]										=    0.1
     elif "b4" in checkpoint_url:
          a_    :     Union[str, Any]										=    4
     elif "l7" in checkpoint_url:
          a_    :     List[Any]										=    7
          a_    :     Any										=    1_0_2_4
          a_    :     Dict										=    4_0_9_6
          a_    :     List[str]										=    2_4
          a_    :     Any										=    1_6
          a_    :     Any										=    0.1

     a_    :     Optional[Any]										=    ViTMSNModel(_SCREAMING_SNAKE_CASE )

     a_    :     Optional[int]										=    torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE  ,  map_location="""cpu""" )["""target_encoder"""]

     a_    :     List[Any]										=    ViTImageProcessor(size=config.image_size )

     remove_projection_head(_SCREAMING_SNAKE_CASE )
     a_    :     Any										=    create_rename_keys(_SCREAMING_SNAKE_CASE  ,  base_model=_SCREAMING_SNAKE_CASE )

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

     model.load_state_dict(_SCREAMING_SNAKE_CASE )
     model.eval()

     a_    :     List[Any]										=    """http://images.cocodataset.org/val2017/000000039769.jpg"""

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

     # forward pass
     torch.manual_seed(2 )
     a_    :     Any										=    model(**_SCREAMING_SNAKE_CASE )
     a_    :     Optional[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:
          a_    :     Optional[Any]										=    torch.tensor([[-1.09_15, -1.48_76, -1.18_09]] )
     elif "b16" in checkpoint_url:
          a_    :     Tuple										=    torch.tensor([[14.28_89, -18.90_45, 11.72_81]] )
     elif "l16" in checkpoint_url:
          a_    :     Dict										=    torch.tensor([[41.50_28, -22.86_81, 45.64_75]] )
     elif "b4" in checkpoint_url:
          a_    :     Dict										=    torch.tensor([[-4.38_68, 5.29_32, -0.41_37]] )
     else:
          a_    :     List[str]										=    torch.tensor([[-0.17_92, -0.64_65, 2.42_63]] )

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

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

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


if __name__ == "__main__":
      __lowerCamelCase        =     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.'''
      )

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







import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List

from ..utils import logging


__lowerCamelCase        =     logging.get_logger(__name__)



def  _a			(						__UpperCamelCase=None  ,  __UpperCamelCase=None ):
     return field(default_factory=lambda: default  ,  metadata=__UpperCamelCase )


@dataclass
class   a__	:
       lowerCamelCase__:     List[str]							    =     list_field(
           default=[]						,       metadata={
               """help""": (
                   """Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version"""
                   """ of all available models"""
               )
           }						,       )

       lowerCamelCase__:     List[int]							    =     list_field(
           default=[8]						,       metadata={"""help""": """List of batch sizes for which memory and time performance will be evaluated"""}    )

       lowerCamelCase__:     List[int]							    =     list_field(
           default=[8, 32, 128, 512]						,       metadata={"""help""": """List of sequence lengths for which memory and time performance will be evaluated"""}						,       )

       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={"""help""": """Whether to benchmark inference of model. Inference can be disabled via --no-inference."""}						,       )
       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={"""help""": """Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."""}						,       )
       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={"""help""": """Whether to run on available tpu devices. TPU can be disabled via --no-tpu."""}    )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Use FP16 to accelerate inference."""}    )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Benchmark training of model"""}    )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Verbose memory tracing"""}    )
       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={"""help""": """Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."""}						,       )
       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={
               """help""": """Whether to perform memory measurements. Memory measurements can be disabled via --no-memory"""
           }						,       )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Trace memory line by line"""}    )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Save result to a CSV file"""}    )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Save all print statements in a log file"""}    )
       lowerCamelCase__:     bool							    =     field(default=lowerCAmelCase_						,       metadata={"""help""": """Whether to print environment information"""}    )
       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={
               """help""": (
                   """Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use"""
                   """ multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled"""
                   """ for debugging / testing and on TPU."""
               )
           }						,       )
       lowerCamelCase__:     str							    =     field(
           default=F"""inference_time_{round(time()    )}.csv"""						,       metadata={"""help""": """CSV filename used if saving time results to csv."""}						,       )
       lowerCamelCase__:     str							    =     field(
           default=F"""inference_memory_{round(time()    )}.csv"""						,       metadata={"""help""": """CSV filename used if saving memory results to csv."""}						,       )
       lowerCamelCase__:     str							    =     field(
           default=F"""train_time_{round(time()    )}.csv"""						,       metadata={"""help""": """CSV filename used if saving time results to csv for training."""}						,       )
       lowerCamelCase__:     str							    =     field(
           default=F"""train_memory_{round(time()    )}.csv"""						,       metadata={"""help""": """CSV filename used if saving memory results to csv for training."""}						,       )
       lowerCamelCase__:     str							    =     field(
           default=F"""env_info_{round(time()    )}.csv"""						,       metadata={"""help""": """CSV filename used if saving environment information."""}						,       )
       lowerCamelCase__:     str							    =     field(
           default=F"""log_{round(time()    )}.csv"""						,       metadata={"""help""": """Log filename used if print statements are saved in log."""}						,       )
       lowerCamelCase__:     int							    =     field(default=3						,       metadata={"""help""": """Times an experiment will be run."""}    )
       lowerCamelCase__:     bool							    =     field(
           default=lowerCAmelCase_						,       metadata={
               """help""": (
                   """Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain"""
                   """ model weights."""
               )
           }						,       )

       def 						UpperCAmelCase(   self      :     Any    ):
            warnings.warn(
                F'''The class {self.__class__} is deprecated. Hugging Face Benchmarking utils'''
                """ are deprecated in general and it is advised to use external Benchmarking libraries """
                """ to benchmark Transformer models."""      ,							lowerCamelCase_      ,							)

       def 						UpperCAmelCase(   self      :     Union[str, Any]    ):
            return json.dumps(dataclasses.asdict(self    )      ,							indent=2    )

       @property
       def 						UpperCAmelCase(   self      :     List[str]    ):
            if len(self.models    ) <= 0:
                 raise ValueError(
                     """Please make sure you provide at least one model name / model identifier, *e.g.* `--models"""
                     """ bert-base-cased` or `args.models = ['bert-base-cased']."""    )
            return self.models

       @property
       def 						UpperCAmelCase(   self      :     Union[str, Any]    ):
            if not self.multi_process:
                 return False
            elif self.is_tpu:
                 logger.info("""Multiprocessing is currently not possible on TPU."""    )
                 return False
            else:
                 return True



