






'''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 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__=False						)->    Any:



			"""simple docstring"""



			snake_case_				:					Union[str, 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_				:					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 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__     ,__magic_name__=False						)->    List[str]:



			"""simple docstring"""



			for i in range(config.num_hidden_layers						):
						if base_model:
									snake_case_				:					Dict   =       ""
						else:
									snake_case_				:					Tuple   =       "vit."
						# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
						snake_case_				:					Tuple   =       state_dict.pop(F'''module.blocks.{i}.attn.qkv.weight'''						)
						snake_case_				:					Tuple   =       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_				:					List[Any]   =       in_proj_weight[
						    : config.hidden_size, :
						]
						snake_case_				:					str   =       in_proj_bias[: config.hidden_size]
						snake_case_				:					Tuple   =       in_proj_weight[
						    config.hidden_size : config.hidden_size * 2, :
						]
						snake_case_				:					str   =       in_proj_bias[
						    config.hidden_size : config.hidden_size * 2
						]
						snake_case_				:					int   =       in_proj_weight[
						    -config.hidden_size :, :
						]
						snake_case_				:					Optional[int]   =       in_proj_bias[-config.hidden_size :]

def 	__UpperCAmelCase       ( __magic_name__						)->    Optional[Any]:



			"""simple docstring"""



			snake_case_				:					Union[str, Any]   =       ["head.weight", "head.bias"]
			for k in ignore_keys:
						state_dict.pop(__magic_name__     ,__magic_name__						)

def 	__UpperCAmelCase       ( __magic_name__						)->    Tuple:



			"""simple docstring"""



			snake_case_				:					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(__magic_name__     ,__magic_name__						)

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__     ,__magic_name__						)->    Optional[Any]:



			"""simple docstring"""



			snake_case_				:					Dict   =       dct.pop(__magic_name__						)
			snake_case_				:					Optional[int]   =       val

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__						)->    Union[str, Any]:



			"""simple docstring"""



			snake_case_				:					Tuple   =       ViTMSNConfig()
			snake_case_				:					Optional[Any]   =       1000

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

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

			snake_case_				:					Tuple   =       ViTMSNModel(__magic_name__						)

			snake_case_				:					Tuple   =       torch.hub.load_state_dict_from_url(__magic_name__     ,map_location="cpu"						)["target_encoder"]

			snake_case_				:					str   =       ViTImageProcessor(size=config.image_size						)

			remove_projection_head(__magic_name__						)
			snake_case_				:					Optional[Any]   =       create_rename_keys(__magic_name__     ,base_model=__magic_name__						)

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

			model.load_state_dict(__magic_name__						)
			model.eval()

			snake_case_				:					Optional[Any]   =       "http://images.cocodataset.org/val2017/000000039769.jpg"

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

			# forward pass
			torch.manual_seed(2						)
			snake_case_				:					Dict   =       model(**__magic_name__						)
			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_				:					int   =       torch.tensor([[-1.0_915, -1.4_876, -1.1_809]]						)
			elif "b16" in checkpoint_url:
						snake_case_				:					Optional[Any]   =       torch.tensor([[14.2_889, -18.9_045, 11.7_281]]						)
			elif "l16" in checkpoint_url:
						snake_case_				:					int   =       torch.tensor([[41.5_028, -22.8_681, 45.6_475]]						)
			elif "b4" in checkpoint_url:
						snake_case_				:					Tuple   =       torch.tensor([[-4.3_868, 5.2_932, -0.4_137]]						)
			else:
						snake_case_				:					Any   =       torch.tensor([[-0.1_792, -0.6_465, 2.4_263]]						)

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

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

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


if __name__ == "__main__":
		__lowerCamelCase   :					List[str]   							=					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   :					Any   							=					parser.parse_args()
		convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)












'''simple docstring'''




from __future__ import annotations

import math

import numpy as np
from numpy.linalg import norm

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__						)->    float:



			"""simple docstring"""



			return math.sqrt(sum(pow(a - b     ,2						) for a, b in zip(__magic_name__     ,__magic_name__						)						)						)

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__						)->    list[list[list[float] | float]]:



			"""simple docstring"""



			if dataset.ndim != value_array.ndim:
						snake_case_				:					int   =       (
						    "Wrong input data's dimensions... "
						    F'''dataset : {dataset.ndim}, value_array : {value_array.ndim}'''
						)
						raise ValueError(__magic_name__						)

			try:
						if dataset.shape[1] != value_array.shape[1]:
									snake_case_				:					Dict   =       (
									    "Wrong input data's shape... "
									    F'''dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}'''
									)
									raise ValueError(__magic_name__						)
			except IndexError:
						if dataset.ndim != value_array.ndim:
									raise TypeError("Wrong shape"						)

			if dataset.dtype != value_array.dtype:
						snake_case_				:					Dict   =       (
						    "Input data have different datatype... "
						    F'''dataset : {dataset.dtype}, value_array : {value_array.dtype}'''
						)
						raise TypeError(__magic_name__						)

			snake_case_				:					Optional[int]   =       []

			for value in value_array:
						snake_case_				:					List[str]   =       euclidean(__magic_name__     ,dataset[0]						)
						snake_case_				:					int   =       dataset[0].tolist()

						for dataset_value in dataset[1:]:
									snake_case_				:					Optional[Any]   =       euclidean(__magic_name__     ,__magic_name__						)

									if dist > temp_dist:
												snake_case_				:					Tuple   =       temp_dist
												snake_case_				:					Optional[int]   =       dataset_value.tolist()

						answer.append([vector, dist]						)

			return answer

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__						)->    float:



			"""simple docstring"""



			return np.dot(__magic_name__     ,__magic_name__						) / (norm(__magic_name__						) * norm(__magic_name__						))


if __name__ == "__main__":
		import doctest

		doctest.testmod()




