






"""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       _lowerCAmelCase       (      lowerCAmelCase	,      lowerCAmelCase=False		):







       '''simple docstring'''
       UpperCAmelCase	    =			[]
       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"
              UpperCAmelCase	    =			[(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       _lowerCAmelCase       (      lowerCAmelCase	,      lowerCAmelCase	,      lowerCAmelCase=False		):







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






def       _lowerCAmelCase       (      lowerCAmelCase		):







       '''simple docstring'''
       UpperCAmelCase	    =			["""head.weight""", """head.bias"""]
       for k in ignore_keys:
              state_dict.pop(lowerCAmelCase	,      lowerCAmelCase		)






def       _lowerCAmelCase       (      lowerCAmelCase		):







       '''simple docstring'''
       # projection head is used in the self-supervised pre-training in MSN,
       # for downstream task it's not needed.
       UpperCAmelCase	    =			[
           """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(lowerCAmelCase	,      lowerCAmelCase		)






def       _lowerCAmelCase       (      lowerCAmelCase	,      lowerCAmelCase	,      lowerCAmelCase		):







       '''simple docstring'''
       UpperCAmelCase	    =			dct.pop(lowerCAmelCase		)
       UpperCAmelCase	    =			val






def       _lowerCAmelCase       (      lowerCAmelCase	,      lowerCAmelCase		):







       '''simple docstring'''
       UpperCAmelCase	    =			ViTMSNConfig()
       UpperCAmelCase	    =			1000

       UpperCAmelCase	    =			"""datasets/huggingface/label-files"""
       UpperCAmelCase	    =			"""imagenet-1k-id2label.json"""
       UpperCAmelCase	    =			json.load(open(hf_hub_download(lowerCAmelCase	,      lowerCAmelCase		)	,      """r"""		)		)
       UpperCAmelCase	    =			{int(lowerCAmelCase		): v for k, v in idalabel.items()}
       UpperCAmelCase	    =			idalabel
       UpperCAmelCase	    =			{v: k for k, v in idalabel.items()}

       if "s16" in checkpoint_url:
              UpperCAmelCase	    =			384
              UpperCAmelCase	    =			1536
              UpperCAmelCase	    =			6
       elif "l16" in checkpoint_url:
              UpperCAmelCase	    =			1024
              UpperCAmelCase	    =			4096
              UpperCAmelCase	    =			24
              UpperCAmelCase	    =			16
              UpperCAmelCase	    =			0.1
       elif "b4" in checkpoint_url:
              UpperCAmelCase	    =			4
       elif "l7" in checkpoint_url:
              UpperCAmelCase	    =			7
              UpperCAmelCase	    =			1024
              UpperCAmelCase	    =			4096
              UpperCAmelCase	    =			24
              UpperCAmelCase	    =			16
              UpperCAmelCase	    =			0.1

       UpperCAmelCase	    =			ViTMSNModel(lowerCAmelCase		)

       UpperCAmelCase	    =			torch.hub.load_state_dict_from_url(lowerCAmelCase	,      map_location="""cpu"""		)["""target_encoder"""]

       UpperCAmelCase	    =			ViTImageProcessor(size=config.image_size		)

       remove_projection_head(lowerCAmelCase		)
       UpperCAmelCase	    =			create_rename_keys(lowerCAmelCase	,      base_model=lowerCAmelCase		)

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

       model.load_state_dict(lowerCAmelCase		)
       model.eval()

       UpperCAmelCase	    =			"""http://images.cocodataset.org/val2017/000000039769.jpg"""

       UpperCAmelCase	    =			Image.open(requests.get(lowerCAmelCase	,      stream=lowerCAmelCase		).raw		)
       UpperCAmelCase	    =			ViTImageProcessor(
           size=config.image_size	,      image_mean=lowerCAmelCase	,      image_std=lowerCAmelCase		)
       UpperCAmelCase	    =			image_processor(images=lowerCAmelCase	,      return_tensors="""pt"""		)

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

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

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

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


if __name__ == "__main__":
 lowerCAmelCase_	:    Any            =      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_	:    Dict            =      parser.parse_args()
 convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)








"""simple docstring"""







import argparse
import json
import os
from collections import OrderedDict

import numpy as np
import tensorflow as tf
import torch






def       _lowerCAmelCase       (      lowerCAmelCase		):







       '''simple docstring'''
       UpperCAmelCase	    =			os.path.join(args.tf_model_dir	,      """parameters.json"""		)
       UpperCAmelCase	    =			json.loads(open(lowerCAmelCase		).read()		)
       if not params:
              raise ValueError(
                  F'''It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.'''		)
       if not args.output.endswith(""".pt"""		):
              UpperCAmelCase	    =			args.output + """.pt"""
       UpperCAmelCase	    =			OrderedDict()
       with tf.device("""/CPU:0"""		):
              UpperCAmelCase	    =			tf.train.load_checkpoint(args.tf_model_dir		)
              UpperCAmelCase	    =			reader.get_variable_to_shape_map()
              for key_name in shapes.keys():
                     UpperCAmelCase	    =			reader.get_tensor(lowerCAmelCase		).astype(np.floataa		)
                     if key_name.endswith("""/adam_m"""		) or key_name.endswith("""/adam_v"""		):
                            continue
                     if key_name.startswith("""pasts/"""		):
                            if key_name.startswith("""pasts/mlp"""		):
                                   UpperCAmelCase	    =			int(key_name[9]		)
                            elif key_name.startswith("""pasts/out"""		):
                                   UpperCAmelCase	    =			8
                            UpperCAmelCase	    =			"""model.sqout.%d.weight""" % (player * 2)  # enter to nn.Sequencial with Tanh, so 2 at a time
                            UpperCAmelCase	    =			vnp.transpose([1, 0]		).copy()  # Mesh-Tensorflow is a diagonal matrix
                            UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                     elif key_name.startswith("""model/moe"""		):
                            UpperCAmelCase	    =			int(key_name[9:].split("""/"""		)[0]		)
                            if key_name.endswith("""/switch_gating/kernel"""		):
                                   UpperCAmelCase	    =			"""model.blocks.%d.feed_forward.mlp.router.classifier.weight""" % player
                                   UpperCAmelCase	    =			vnp.transpose([1, 0]		).copy()  # Mesh-Tensorflow is a diagonal matrix
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                            elif key_name.endswith("""/softmlp/kernel"""		):
                                   UpperCAmelCase	    =			"""model.blocks.%d.feed_forward.soft_bypass_mlp.weight""" % player
                                   UpperCAmelCase	    =			vnp.transpose([1, 0]		).copy()  # Mesh-Tensorflow is a diagonal matrix
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                            elif key_name.endswith("""/wo/kernel"""		) or key_name.endswith("""/wi/kernel"""		):
                                   UpperCAmelCase	    =			key_name[-9:-7]
                                   for i in range(16		):
                                          UpperCAmelCase	    =			"""model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight""" % (player, i, nlayer)
                                          UpperCAmelCase	    =			(
                                              vnp[i].transpose([1, 0]		).copy()
                                          )  # In Mesh-Tensorflow, it is one array, so it is divided
                                          UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                     elif key_name.startswith("""model/mlp"""		):
                            UpperCAmelCase	    =			int(key_name[9:].split("""/"""		)[0]		)
                            if key_name.endswith("""/p1/kernel"""		):
                                   UpperCAmelCase	    =			"""model.blocks.%d.feed_forward.mlp.wi.weight""" % player
                                   UpperCAmelCase	    =			vnp.transpose([1, 0]		).copy()  # Mesh-Tensorflow is a diagonal matrix
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                            elif key_name.endswith("""/p1/bias"""		):
                                   UpperCAmelCase	    =			"""model.blocks.%d.feed_forward.mlp.wi.bias""" % player
                                   UpperCAmelCase	    =			vnp.copy()  # same because it is one dimensional
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                            elif key_name.endswith("""/p2/kernel"""		):
                                   UpperCAmelCase	    =			"""model.blocks.%d.feed_forward.mlp.wo.weight""" % player
                                   UpperCAmelCase	    =			vnp.transpose([1, 0]		).copy()  # Mesh-Tensorflow is a diagonal matrix
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                            elif key_name.endswith("""/p2/bias"""		):
                                   UpperCAmelCase	    =			"""model.blocks.%d.feed_forward.mlp.wo.bias""" % player
                                   UpperCAmelCase	    =			vnp.copy()  # same because it is one dimensional
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                     elif key_name.startswith("""model/ln"""		):
                            UpperCAmelCase	    =			int(key_name[8:].split("""/"""		)[0]		)
                            if key_name.endswith("""/b"""		):
                                   UpperCAmelCase	    =			"""model.blocks.%d.feed_forward.norm.bias""" % player
                                   UpperCAmelCase	    =			vnp.copy()  # same because it is one dimensional
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                            elif key_name.endswith("""/g"""		):
                                   UpperCAmelCase	    =			"""model.blocks.%d.feed_forward.norm.weight""" % player
                                   UpperCAmelCase	    =			vnp.copy()  # same because it is one dimensional
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                     elif key_name.startswith("""model/att"""		):
                            UpperCAmelCase	    =			int(key_name[9:].split("""/"""		)[0]		)
                            if key_name.endswith("""/qkv/kernel"""		):
                                   UpperCAmelCase	    =			vnp.copy()  # Compute same dimension as Mesh-tensorflow using einsum
                                   UpperCAmelCase	    =			state[:, 0, :, :]
                                   UpperCAmelCase	    =			state[:, 1, :, :]
                                   UpperCAmelCase	    =			state[:, 2, :, :]
                                   UpperCAmelCase	    =			(
                                       state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]]		)
                                       .transpose([1, 0]		)
                                       .copy()
                                   )  # Mesh-Tensorflow is a diagonal matrix
                                   UpperCAmelCase	    =			(
                                       state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]]		)
                                       .transpose([1, 0]		)
                                       .copy()
                                   )  # Mesh-Tensorflow is a diagonal matrix
                                   UpperCAmelCase	    =			(
                                       state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]]		)
                                       .transpose([1, 0]		)
                                       .copy()
                                   )  # Mesh-Tensorflow is a diagonal matrix
                                   UpperCAmelCase	    =			"""model.blocks.%d.self_attn.self_attn.q_proj.weight""" % player
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                                   UpperCAmelCase	    =			"""model.blocks.%d.self_attn.self_attn.k_proj.weight""" % player
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                                   UpperCAmelCase	    =			"""model.blocks.%d.self_attn.self_attn.v_proj.weight""" % player
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                            elif key_name.endswith("""/o/kernel"""		):
                                   UpperCAmelCase	    =			"""model.blocks.%d.self_attn.self_attn.out_proj.weight""" % player
                                   UpperCAmelCase	    =			(
                                       vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]]		).transpose([1, 0]		).copy()
                                   )  # Mesh-Tensorflow is a diagonal matrix
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                     elif key_name.startswith("""model/an"""		):
                            UpperCAmelCase	    =			int(key_name[8:].split("""/"""		)[0]		)
                            if key_name.endswith("""/b"""		):
                                   UpperCAmelCase	    =			"""model.blocks.%d.self_attn.norm.bias""" % player
                                   UpperCAmelCase	    =			vnp.copy()  # same because it is one dimensional
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                            elif key_name.endswith("""/g"""		):
                                   UpperCAmelCase	    =			"""model.blocks.%d.self_attn.norm.weight""" % player
                                   UpperCAmelCase	    =			vnp.copy()  # same because it is one dimensional
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                     elif (
                         key_name.startswith("""model/wte"""		)
                         or key_name.startswith("""model/wpe"""		)
                         or key_name.startswith("""model/ete"""		)
                     ):
                            UpperCAmelCase	    =			{"""wte""": """embed_tokens""", """wpe""": """position_embeddings""", """ete""": """extra_position_embeddings"""}[
                                key_name[-3:]
                            ]
                            UpperCAmelCase	    =			"""model.%s.weight""" % nlayer
                            UpperCAmelCase	    =			vnp.copy()  # same in embedded
                            UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                            if key_name.startswith("""model/wte"""		):
                                   UpperCAmelCase	    =			"""lm_head.weight"""
                                   UpperCAmelCase	    =			vnp.copy()  # same in embedded
                                   UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                     elif key_name.startswith("""model/wob"""		):
                            UpperCAmelCase	    =			"""final_logits_bias"""
                            UpperCAmelCase	    =			vnp.copy()  # same in embedded
                            UpperCAmelCase	    =			state.reshape((1, -1)		)
                            UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                     elif key_name == "model/dense/kernel":
                            UpperCAmelCase	    =			"""model.last_project.weight"""
                            UpperCAmelCase	    =			vnp.transpose([1, 0]		).copy()  # Mesh-Tensorflow is a diagonal matrix
                            UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
                     elif key_name == "model/dense_1/bias":
                            UpperCAmelCase	    =			"""model.last_project.bias"""
                            UpperCAmelCase	    =			vnp.copy()  # same because it is one dimensional
                            UpperCAmelCase	    =			torch.tensor(lowerCAmelCase		)
       torch.save(lowerCAmelCase	,      args.output		)


if __name__ == "__main__":
 lowerCAmelCase_	:    Union[str, Any]            =      argparse.ArgumentParser(
     description='''model converter.''', formatter_class=argparse.ArgumentDefaultsHelpFormatter
 )
 parser.add_argument('''--tf_model_dir''', metavar='''PATH''', type=str, required=True, help='''import model''')
 parser.add_argument('''--output''', metavar='''PATH''', type=str, required=True, help='''output model''')
 lowerCAmelCase_	:    Any            =      parser.parse_args()
 convert_tf_gptsan_to_pt(args)
