





'''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						(       _lowerCamelCase    ,	_lowerCamelCase=False ) ->				List[str]:



			"""simple docstring"""


			__snake_case					:      Any							      =     []
			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"
						__snake_case					:      Any							      =     [(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						(       _lowerCamelCase    ,	_lowerCamelCase    ,	_lowerCamelCase=False ) ->				Optional[Any]:



			"""simple docstring"""


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







def 					_a						(       _lowerCamelCase ) ->				Optional[int]:



			"""simple docstring"""


			__snake_case					:      Optional[Any]							      =     ["""head.weight""", """head.bias"""]
			for k in ignore_keys:
						state_dict.pop(_lowerCamelCase    ,	_lowerCamelCase )







def 					_a						(       _lowerCamelCase ) ->				Optional[Any]:



			"""simple docstring"""


			__snake_case					:      List[str]							      =     [
			    """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 					_a						(       _lowerCamelCase    ,	_lowerCamelCase    ,	_lowerCamelCase ) ->				Dict:



			"""simple docstring"""


			__snake_case					:      Optional[int]							      =     dct.pop(_lowerCamelCase )
			__snake_case					:      Optional[Any]							      =     val







def 					_a						(       _lowerCamelCase    ,	_lowerCamelCase ) ->				Dict:



			"""simple docstring"""


			__snake_case					:      Tuple							      =     ViTMSNConfig()
			__snake_case					:      Union[str, Any]							      =     1000

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

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

			__snake_case					:      int							      =     ViTMSNModel(_lowerCamelCase )

			__snake_case					:      Union[str, Any]							      =     torch.hub.load_state_dict_from_url(_lowerCamelCase    ,	map_location="""cpu""" )["""target_encoder"""]

			__snake_case					:      Dict							      =     ViTImageProcessor(size=config.image_size )

			remove_projection_head(_lowerCamelCase )
			__snake_case					:      Tuple							      =     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()

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

			__snake_case					:      Any							      =     Image.open(requests.get(_lowerCamelCase    ,	stream=_lowerCamelCase ).raw )
			__snake_case					:      Any							      =     ViTImageProcessor(
			    size=config.image_size    ,	image_mean=_lowerCamelCase    ,	image_std=_lowerCamelCase )
			__snake_case					:      Dict							      =     image_processor(images=_lowerCamelCase    ,	return_tensors="""pt""" )

			# forward pass
			torch.manual_seed(2 )
			__snake_case					:      List[str]							      =     model(**_lowerCamelCase )
			__snake_case					:      Optional[int]							      =     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:
						__snake_case					:      Union[str, Any]							      =     torch.tensor([[-1.09_15, -1.48_76, -1.18_09]] )
			elif "b16" in checkpoint_url:
						__snake_case					:      Optional[Any]							      =     torch.tensor([[14.28_89, -18.90_45, 11.72_81]] )
			elif "l16" in checkpoint_url:
						__snake_case					:      Optional[Any]							      =     torch.tensor([[41.50_28, -22.86_81, 45.64_75]] )
			elif "b4" in checkpoint_url:
						__snake_case					:      str							      =     torch.tensor([[-4.38_68, 5.29_32, -0.41_37]] )
			else:
						__snake_case					:      str							      =     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__":
	__UpperCamelCase					    =	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."
	)

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









'''simple docstring'''






from unittest import TestCase

from datasets import Sequence, Value
from datasets.arrow_dataset import Dataset




class  _A (					__lowercase		):

		def 	lowercase__     (   self					:   Any			)					->    str:


					"""simple docstring"""

					return [
					    {"col_1": 3, "col_2": "a"},
					    {"col_1": 2, "col_2": "b"},
					    {"col_1": 1, "col_2": "c"},
					    {"col_1": 0, "col_2": "d"},
					]

		def 	lowercase__     (   self					:   str			)					->    int:


					"""simple docstring"""

					__snake_case					:      Union[str, Any]							      =     {"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]}
					return Dataset.from_dict(__magic_name__			)

		def 	lowercase__     (   self					:   str			)					->    List[Any]:


					"""simple docstring"""

					__snake_case					:      Any							      =     self._create_example_records()
					__snake_case					:      str							      =     Dataset.from_list(__magic_name__			)
					self.assertListEqual(dset.column_names  ,      ["""col_1""", """col_2"""]			)
					for i, r in enumerate(__magic_name__			):
								self.assertDictEqual(__magic_name__  ,      example_records[i]			)

		def 	lowercase__     (   self					:   Optional[Any]			)					->    List[Any]:


					"""simple docstring"""

					__snake_case					:      List[Any]							      =     self._create_example_records()
					__snake_case					:      Dict							      =     Dataset.from_list(__magic_name__			)
					__snake_case					:      List[Any]							      =     Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]}			)
					self.assertEqual(dset.info  ,      dset_from_dict.info			)

		def 	lowercase__     (   self					:   str			)					->    List[Any]:  # checks what happens with missing columns


					"""simple docstring"""

					__snake_case					:      Union[str, Any]							      =     [{"""col_1""": 1}, {"""col_2""": """x"""}]
					__snake_case					:      Optional[int]							      =     Dataset.from_list(__magic_name__			)
					self.assertDictEqual(dset[0]  ,      {"""col_1""": 1}			)
					self.assertDictEqual(dset[1]  ,      {"""col_1""": None}			)  # NB: first record is used for columns

		def 	lowercase__     (   self					:   List[str]			)					->    Optional[Any]:  # checks if the type can be inferred from the second record


					"""simple docstring"""

					__snake_case					:      List[Any]							      =     [{"""col_1""": []}, {"""col_1""": [1, 2]}]
					__snake_case					:      int							      =     Dataset.from_list(__magic_name__			)
					self.assertEqual(dset.info.features["""col_1"""]  ,      Sequence(Value("""int64"""			)			)			)

		def 	lowercase__     (   self					:   int			)					->    Union[str, Any]:


					"""simple docstring"""

					__snake_case					:      Tuple							      =     Dataset.from_list([]			)
					self.assertEqual(len(__magic_name__			)  ,      0			)
					self.assertListEqual(dset.column_names  ,      []			)


