



import argparse
import json
from pathlib import Path

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

from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel
from transformers.utils import logging


logging.set_verbosity_info()
__A   			=logging.get_logger(__name__)

def        a						(      _UpperCAmelCase							:					str ,   _UpperCAmelCase							:					int=False						):







		'''simple docstring'''





		__UpperCAmelCase    :     Optional[int]													=	[]
		for i in range(config.num_hidden_layers						):
				# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
				rename_keys.append((f'blocks.{i}.norm1.weight', f'vit.encoder.layer.{i}.layernorm_before.weight')						)
				rename_keys.append((f'blocks.{i}.norm1.bias', f'vit.encoder.layer.{i}.layernorm_before.bias')						)
				rename_keys.append((f'blocks.{i}.attn.proj.weight', f'vit.encoder.layer.{i}.attention.output.dense.weight')						)
				rename_keys.append((f'blocks.{i}.attn.proj.bias', f'vit.encoder.layer.{i}.attention.output.dense.bias')						)
				rename_keys.append((f'blocks.{i}.norm2.weight', f'vit.encoder.layer.{i}.layernorm_after.weight')						)
				rename_keys.append((f'blocks.{i}.norm2.bias', f'vit.encoder.layer.{i}.layernorm_after.bias')						)
				rename_keys.append((f'blocks.{i}.mlp.fc1.weight', f'vit.encoder.layer.{i}.intermediate.dense.weight')						)
				rename_keys.append((f'blocks.{i}.mlp.fc1.bias', f'vit.encoder.layer.{i}.intermediate.dense.bias')						)
				rename_keys.append((f'blocks.{i}.mlp.fc2.weight', f'vit.encoder.layer.{i}.output.dense.weight')						)
				rename_keys.append((f'blocks.{i}.mlp.fc2.bias', f'vit.encoder.layer.{i}.output.dense.bias')						)

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

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

				# if just the base model, we should remove "vit" from all keys that start with "vit"
				__UpperCAmelCase    :     int													=	[(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							:					Optional[Any] ,   _UpperCAmelCase							:					Dict ,   _UpperCAmelCase							:					Union[str, Any]=False						):







		'''simple docstring'''





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

def        a						(      _UpperCAmelCase							:					List[str]						):







		'''simple docstring'''





		__UpperCAmelCase    :     Dict													=	['''head.weight''', '''head.bias''']
		for k in ignore_keys:
				state_dict.pop(_UpperCAmelCase ,   _UpperCAmelCase						)

def        a						(      _UpperCAmelCase							:					Optional[int] ,   _UpperCAmelCase							:					Dict ,   _UpperCAmelCase							:					Dict						):







		'''simple docstring'''





		__UpperCAmelCase    :     Dict													=	dct.pop(_UpperCAmelCase						)
		__UpperCAmelCase    :     Optional[int]													=	val

def        a						(      ):







		'''simple docstring'''





		__UpperCAmelCase    :     Dict													=	'''http://images.cocodataset.org/val2017/000000039769.jpg'''
		__UpperCAmelCase    :     List[Any]													=	Image.open(requests.get(_UpperCAmelCase ,   stream=_UpperCAmelCase						).raw						)
		return im

@torch.no_grad()
def        a						(      _UpperCAmelCase							:					Optional[int] ,   _UpperCAmelCase							:					List[str] ,   _UpperCAmelCase							:					Optional[Any]=True						):







		'''simple docstring'''





		__UpperCAmelCase    :     int													=	ViTConfig()
		# patch_size
		if model_name[-1] == "8":
				__UpperCAmelCase    :     Optional[Any]													=	8
		# set labels if required
		if not base_model:
				__UpperCAmelCase    :     Optional[int]													=	10_00
				__UpperCAmelCase    :     int													=	'''huggingface/label-files'''
				__UpperCAmelCase    :     str													=	'''imagenet-1k-id2label.json'''
				__UpperCAmelCase    :     str													=	json.load(open(hf_hub_download(_UpperCAmelCase ,   _UpperCAmelCase ,   repo_type='''dataset'''						) ,   '''r'''						)						)
				__UpperCAmelCase    :     Dict													=	{int(_UpperCAmelCase						): v for k, v in idalabel.items()}
				__UpperCAmelCase    :     str													=	idalabel
				__UpperCAmelCase    :     Tuple													=	{v: k for k, v in idalabel.items()}
		# size of the architecture
		if model_name in ["dino_vits8", "dino_vits16"]:
				__UpperCAmelCase    :     List[str]													=	3_84
				__UpperCAmelCase    :     str													=	15_36
				__UpperCAmelCase    :     List[Any]													=	12
				__UpperCAmelCase    :     List[Any]													=	6

		# load original model from torch hub
		__UpperCAmelCase    :     str													=	torch.hub.load('''facebookresearch/dino:main''' ,   _UpperCAmelCase						)
		original_model.eval()

		# load state_dict of original model, remove and rename some keys
		__UpperCAmelCase    :     Optional[Any]													=	original_model.state_dict()
		if base_model:
				remove_classification_head_(_UpperCAmelCase						)
		__UpperCAmelCase    :     Dict													=	create_rename_keys(_UpperCAmelCase ,   base_model=_UpperCAmelCase						)
		for src, dest in rename_keys:
				rename_key(_UpperCAmelCase ,   _UpperCAmelCase ,   _UpperCAmelCase						)
		read_in_q_k_v(_UpperCAmelCase ,   _UpperCAmelCase ,   _UpperCAmelCase						)

		# load HuggingFace model
		if base_model:
				__UpperCAmelCase    :     int													=	ViTModel(_UpperCAmelCase ,   add_pooling_layer=_UpperCAmelCase						).eval()
		else:
				__UpperCAmelCase    :     Optional[int]													=	ViTForImageClassification(_UpperCAmelCase						).eval()
		model.load_state_dict(_UpperCAmelCase						)

		# Check outputs on an image, prepared by ViTImageProcessor
		__UpperCAmelCase    :     Tuple													=	ViTImageProcessor()
		__UpperCAmelCase    :     Tuple													=	image_processor(images=prepare_img() ,   return_tensors='''pt'''						)
		__UpperCAmelCase    :     List[Any]													=	encoding['''pixel_values''']
		__UpperCAmelCase    :     Optional[Any]													=	model(_UpperCAmelCase						)

		if base_model:
				__UpperCAmelCase    :     List[str]													=	original_model(_UpperCAmelCase						)
				assert torch.allclose(_UpperCAmelCase ,   outputs.last_hidden_state[:, 0, :] ,   atol=1e-1						)
		else:
				__UpperCAmelCase    :     Tuple													=	original_model(_UpperCAmelCase						)
				assert logits.shape == outputs.logits.shape
				assert torch.allclose(_UpperCAmelCase ,   outputs.logits ,   atol=1e-3						)

		Path(_UpperCAmelCase						).mkdir(exist_ok=_UpperCAmelCase						)
		print(f'Saving model {model_name} to {pytorch_dump_folder_path}'						)
		model.save_pretrained(_UpperCAmelCase						)
		print(f'Saving image processor to {pytorch_dump_folder_path}'						)
		image_processor.save_pretrained(_UpperCAmelCase						)


if __name__ == "__main__":
				__A   			=argparse.ArgumentParser()
				# Required parameters
				parser.add_argument(
				    "--model_name",
				    default="dino_vitb16",
				    type=str,
				    help="Name of the model trained with DINO you'd like to convert.",
				)
				parser.add_argument(
				    "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
				)
				parser.add_argument(
				    "--base_model",
				    action="store_true",
				    help="Whether to only convert the base model (no projection head weights).",
				)

				parser.set_defaults(base_model=True)
				__A   			=parser.parse_args()
				convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)










#
# This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or
# many nodes) can talk to each other via nccl and allocate gpu memory.
#
# To run first adjust the number of processes and nodes:
#
# python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port
#
# You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d
#
# use torch.distributed.launch instead of torch.distributed.run for torch < 1.9
#
# If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with:
#
# NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# which should tell you what's going on behind the scenes.
#
#
# This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that
# runs on 2 nodes of 4 gpus per node:
#
# #SBATCH --job-name=test-nodes        # name
# #SBATCH --nodes=2                    # nodes
# #SBATCH --ntasks-per-node=1          # crucial - only 1 task per dist per node!
# #SBATCH --cpus-per-task=10           # number of cores per tasks
# #SBATCH --gres=gpu:4                 # number of gpus
# #SBATCH --time 0:05:00               # maximum execution time (HH:MM:SS)
# #SBATCH --output=%x-%j.out           # output file name
#
# GPUS_PER_NODE=4
# MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1)
# MASTER_PORT=6000
#
# srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \
# --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \
# --master_addr $MASTER_ADDR --master_port $MASTER_PORT \
# torch-distributed-gpu-test.py'
#

import fcntl
import os
import socket

import torch
import torch.distributed as dist

def        a						(      *_UpperCAmelCase							:					List[str]						):







		'''simple docstring'''





		with open(_UpperCAmelCase ,   '''r'''						) as fh:
				fcntl.flock(_UpperCAmelCase ,   fcntl.LOCK_EX						)
				try:
						print(*_UpperCAmelCase						)
				finally:
						fcntl.flock(_UpperCAmelCase ,   fcntl.LOCK_UN						)


__A   			=int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
__A   			=torch.device("cuda", local_rank)
__A   			=socket.gethostname()

__A   			=f'''[{hostname}-{local_rank}]'''

try:
				# test distributed
				dist.init_process_group("nccl")
				dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM)
				dist.barrier()

				# test cuda is available and can allocate memory
				torch.cuda.is_available()
				torch.ones(1).cuda(local_rank)

				# global rank
				__A   			=dist.get_rank()
				__A   			=dist.get_world_size()

				printflock(f'''{gpu} is OK (global rank: {rank}/{world_size})''')

				dist.barrier()
				if rank == 0:
								printflock(f'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''')

except Exception:
				printflock(f'''{gpu} is broken''')
				raise





