


import os
import tempfile
import unittest

from transformers import DistilBertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import (
				    DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    DistilBertForMaskedLM,
				    DistilBertForMultipleChoice,
				    DistilBertForQuestionAnswering,
				    DistilBertForSequenceClassification,
				    DistilBertForTokenClassification,
				    DistilBertModel,
				)







class 	__lowercase    (__SCREAMING_SNAKE_CASE  ):





							"""simple docstring"""







							def __init__(      self			,						lowerCAmelCase__			,						lowerCAmelCase__=1_3			,						lowerCAmelCase__=7			,						lowerCAmelCase__=True			,						lowerCAmelCase__=True			,						lowerCAmelCase__=False			,						lowerCAmelCase__=True			,						lowerCAmelCase__=9_9			,						lowerCAmelCase__=3_2			,						lowerCAmelCase__=5			,						lowerCAmelCase__=4			,						lowerCAmelCase__=3_7			,						lowerCAmelCase__="gelu"			,						lowerCAmelCase__=0.1			,						lowerCAmelCase__=0.1			,						lowerCAmelCase__=5_1_2			,						lowerCAmelCase__=1_6			,						lowerCAmelCase__=2			,						lowerCAmelCase__=0.02			,						lowerCAmelCase__=3			,						lowerCAmelCase__=4			,						lowerCAmelCase__=None			,						):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     str					=					parent
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					batch_size
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					seq_length
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					is_training
										SCREAMING_SNAKE_CASE_		:     Dict					=					use_input_mask
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					use_token_type_ids
										SCREAMING_SNAKE_CASE_		:     Dict					=					use_labels
										SCREAMING_SNAKE_CASE_		:     str					=					vocab_size
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					hidden_size
										SCREAMING_SNAKE_CASE_		:     Tuple					=					num_hidden_layers
										SCREAMING_SNAKE_CASE_		:     Tuple					=					num_attention_heads
										SCREAMING_SNAKE_CASE_		:     str					=					intermediate_size
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					hidden_act
										SCREAMING_SNAKE_CASE_		:     int					=					hidden_dropout_prob
										SCREAMING_SNAKE_CASE_		:     Any					=					attention_probs_dropout_prob
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					max_position_embeddings
										SCREAMING_SNAKE_CASE_		:     Dict					=					type_vocab_size
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					type_sequence_label_size
										SCREAMING_SNAKE_CASE_		:     int					=					initializer_range
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					num_labels
										SCREAMING_SNAKE_CASE_		:     int					=					num_choices
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					scope






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Any					=					ids_tensor([self.batch_size, self.seq_length]			,						self.vocab_size       )

										SCREAMING_SNAKE_CASE_		:     Any					=					None
										if self.use_input_mask:
													SCREAMING_SNAKE_CASE_		:     List[Any]					=					random_attention_mask([self.batch_size, self.seq_length]       )

										SCREAMING_SNAKE_CASE_		:     Dict					=					None
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					None
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					None
										if self.use_labels:
													SCREAMING_SNAKE_CASE_		:     Optional[int]					=					ids_tensor([self.batch_size]			,						self.type_sequence_label_size       )
													SCREAMING_SNAKE_CASE_		:     Optional[int]					=					ids_tensor([self.batch_size, self.seq_length]			,						self.num_labels       )
													SCREAMING_SNAKE_CASE_		:     Tuple					=					ids_tensor([self.batch_size]			,						self.num_choices       )

										SCREAMING_SNAKE_CASE_		:     Any					=					self.get_config()

										return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										return DistilBertConfig(
										    vocab_size=self.vocab_size			,						dim=self.hidden_size			,						n_layers=self.num_hidden_layers			,						n_heads=self.num_attention_heads			,						hidden_dim=self.intermediate_size			,						hidden_act=self.hidden_act			,						dropout=self.hidden_dropout_prob			,						attention_dropout=self.attention_probs_dropout_prob			,						max_position_embeddings=self.max_position_embeddings			,						initializer_range=self.initializer_range			,						)






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Tuple					=					DistilBertModel(config=lowerCAmelCase__       )
										model.to(lowerCAmelCase__       )
										model.eval()
										SCREAMING_SNAKE_CASE_		:     List[str]					=					model(lowerCAmelCase__			,						lowerCAmelCase__       )
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					model(lowerCAmelCase__       )
										self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.seq_length, self.hidden_size)       )






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					DistilBertForMaskedLM(config=lowerCAmelCase__       )
										model.to(lowerCAmelCase__       )
										model.eval()
										SCREAMING_SNAKE_CASE_		:     Dict					=					model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						labels=lowerCAmelCase__       )
										self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.seq_length, self.vocab_size)       )






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					DistilBertForQuestionAnswering(config=lowerCAmelCase__       )
										model.to(lowerCAmelCase__       )
										model.eval()
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					model(
										    lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						start_positions=lowerCAmelCase__			,						end_positions=lowerCAmelCase__       )
										self.parent.assertEqual(result.start_logits.shape			,						(self.batch_size, self.seq_length)       )
										self.parent.assertEqual(result.end_logits.shape			,						(self.batch_size, self.seq_length)       )






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					self.num_labels
										SCREAMING_SNAKE_CASE_		:     str					=					DistilBertForSequenceClassification(lowerCAmelCase__       )
										model.to(lowerCAmelCase__       )
										model.eval()
										SCREAMING_SNAKE_CASE_		:     int					=					model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						labels=lowerCAmelCase__       )
										self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.num_labels)       )






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					self.num_labels
										SCREAMING_SNAKE_CASE_		:     str					=					DistilBertForTokenClassification(config=lowerCAmelCase__       )
										model.to(lowerCAmelCase__       )
										model.eval()

										SCREAMING_SNAKE_CASE_		:     str					=					model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						labels=lowerCAmelCase__       )
										self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.seq_length, self.num_labels)       )






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     str					=					self.num_choices
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					DistilBertForMultipleChoice(config=lowerCAmelCase__       )
										model.to(lowerCAmelCase__       )
										model.eval()
										SCREAMING_SNAKE_CASE_		:     Any					=					input_ids.unsqueeze(1       ).expand(-1			,						self.num_choices			,						-1       ).contiguous()
										SCREAMING_SNAKE_CASE_		:     Tuple					=					input_mask.unsqueeze(1       ).expand(-1			,						self.num_choices			,						-1       ).contiguous()
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					model(
										    lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						labels=lowerCAmelCase__			,						)
										self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.num_choices)       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Dict					=					self.prepare_config_and_inputs()
										((SCREAMING_SNAKE_CASE_)		,      (SCREAMING_SNAKE_CASE_)		,      (SCREAMING_SNAKE_CASE_)		,      (SCREAMING_SNAKE_CASE_)		,      (SCREAMING_SNAKE_CASE_)		,      (SCREAMING_SNAKE_CASE_))		:     Union[str, Any]					=					config_and_inputs
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					{'input_ids': input_ids, 'attention_mask': input_mask}
										return config, inputs_dict







@require_torch
class 	__lowercase    (__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE	,       unittest.TestCase  ):





							"""simple docstring"""







							_UpperCAmelCase      =						(
							    (
							        DistilBertModel,
							        DistilBertForMaskedLM,
							        DistilBertForMultipleChoice,
							        DistilBertForQuestionAnswering,
							        DistilBertForSequenceClassification,
							        DistilBertForTokenClassification,
							    )
							    if is_torch_available()
							    else None
							)
							_UpperCAmelCase      =						(
							    {
							        """feature-extraction""": DistilBertModel,
							        """fill-mask""": DistilBertForMaskedLM,
							        """question-answering""": DistilBertForQuestionAnswering,
							        """text-classification""": DistilBertForSequenceClassification,
							        """token-classification""": DistilBertForTokenClassification,
							        """zero-shot""": DistilBertForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							_UpperCAmelCase      =						True
							_UpperCAmelCase      =						True
							_UpperCAmelCase      =						True
							_UpperCAmelCase      =						True






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     List[str]					=					DistilBertModelTester(self       )
										SCREAMING_SNAKE_CASE_		:     List[str]					=					ConfigTester(self			,						config_class=lowerCAmelCase__			,						dim=3_7       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										self.config_tester.run_common_tests()






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Tuple					=					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_distilbert_model(*lowerCAmelCase__       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Any					=					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_distilbert_for_masked_lm(*lowerCAmelCase__       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_distilbert_for_question_answering(*lowerCAmelCase__       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowerCAmelCase__       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_distilbert_for_token_classification(*lowerCAmelCase__       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowerCAmelCase__       )






							@slow
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													SCREAMING_SNAKE_CASE_		:     List[Any]					=					DistilBertModel.from_pretrained(lowerCAmelCase__       )
													self.assertIsNotNone(lowerCAmelCase__       )






							@slow
							@require_torch_gpu
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					self.model_tester.prepare_config_and_inputs_for_common()
										for model_class in self.all_model_classes:
													# BertForMultipleChoice behaves incorrectly in JIT environments.
													if model_class == DistilBertForMultipleChoice:
																return

													SCREAMING_SNAKE_CASE_		:     str					=					True
													SCREAMING_SNAKE_CASE_		:     Optional[int]					=					model_class(config=lowerCAmelCase__       )

													SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					self._prepare_for_class(lowerCAmelCase__			,						lowerCAmelCase__       )
													SCREAMING_SNAKE_CASE_		:     List[str]					=					torch.jit.trace(
													    lowerCAmelCase__			,						(inputs_dict['input_ids'].to('cpu'       ), inputs_dict['attention_mask'].to('cpu'       ))       )

													with tempfile.TemporaryDirectory() as tmp:
																torch.jit.save(lowerCAmelCase__			,						os.path.join(lowerCAmelCase__			,						'traced_model.pt'       )       )
																SCREAMING_SNAKE_CASE_		:     Any					=					torch.jit.load(os.path.join(lowerCAmelCase__			,						'traced_model.pt'       )			,						map_location=lowerCAmelCase__       )
																loaded(inputs_dict['input_ids'].to(lowerCAmelCase__       )			,						inputs_dict['attention_mask'].to(lowerCAmelCase__       )       )







@require_torch
class 	__lowercase    (unittest.TestCase  ):





							"""simple docstring"""







							@slow
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					DistilBertModel.from_pretrained('distilbert-base-uncased'       )
										SCREAMING_SNAKE_CASE_		:     str					=					torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]       )
										SCREAMING_SNAKE_CASE_		:     Tuple					=					torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]       )
										with torch.no_grad():
													SCREAMING_SNAKE_CASE_		:     Any					=					model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__       )[0]
										SCREAMING_SNAKE_CASE_		:     Dict					=					torch.Size((1, 1_1, 7_6_8)       )
										self.assertEqual(output.shape			,						lowerCAmelCase__       )
										SCREAMING_SNAKE_CASE_		:     str					=					torch.tensor(
										    [[[-0.1_639, 0.3_299, 0.1_648], [-0.1_746, 0.3_289, 0.1_710], [-0.1_884, 0.3_357, 0.1_810]]]       )

										self.assertTrue(torch.allclose(output[:, 1:4, 1:4]			,						lowerCAmelCase__			,						atol=1E-4       )       )







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()
lowercase   =	logging.get_logger(__name__)



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



def   __lowerCAmelCase    (				UpperCAmelCase__					:   str							)	->     str:
							lowerCamelCase_					=       ["""head.weight""", """head.bias"""]
							for k in ignore_keys:
														state_dict.pop(UpperCAmelCase__      ,					UpperCAmelCase__							)



def   __lowerCAmelCase    (				UpperCAmelCase__					:   Dict      ,					UpperCAmelCase__					:   int      ,					UpperCAmelCase__					:   int							)	->     Tuple:
							lowerCamelCase_					=       dct.pop(UpperCAmelCase__							)
							lowerCamelCase_					=       val



def   __lowerCAmelCase    (				)	->     Any:
							lowerCamelCase_					=       """http://images.cocodataset.org/val2017/000000039769.jpg"""
							lowerCamelCase_					=       Image.open(requests.get(UpperCAmelCase__      ,					stream=UpperCAmelCase__							).raw							)
							return im



@torch.no_grad()
def   __lowerCAmelCase    (				UpperCAmelCase__					:   str      ,					UpperCAmelCase__					:   Optional[int]      ,					UpperCAmelCase__					:   Tuple=True							)	->     Dict:
							lowerCamelCase_					=       ViTConfig()
							# patch_size
							if model_name[-1] == "8":
														lowerCamelCase_					=       8
							# set labels if required
							if not base_model:
														lowerCamelCase_					=       1_0_0_0
														lowerCamelCase_					=       """huggingface/label-files"""
														lowerCamelCase_					=       """imagenet-1k-id2label.json"""
														lowerCamelCase_					=       json.load(open(hf_hub_download(UpperCAmelCase__      ,					UpperCAmelCase__      ,					repo_type="""dataset"""							)      ,					"""r"""							)							)
														lowerCamelCase_					=       {int(UpperCAmelCase__							): v for k, v in idalabel.items()}
														lowerCamelCase_					=       idalabel
														lowerCamelCase_					=       {v: k for k, v in idalabel.items()}
							# size of the architecture
							if model_name in ["dino_vits8", "dino_vits16"]:
														lowerCamelCase_					=       3_8_4
														lowerCamelCase_					=       1_5_3_6
														lowerCamelCase_					=       1_2
														lowerCamelCase_					=       6

							# load original model from torch hub
							lowerCamelCase_					=       torch.hub.load("""facebookresearch/dino:main"""      ,					UpperCAmelCase__							)
							original_model.eval()

							# load state_dict of original model, remove and rename some keys
							lowerCamelCase_					=       original_model.state_dict()
							if base_model:
														remove_classification_head_(UpperCAmelCase__							)
							lowerCamelCase_					=       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:
														lowerCamelCase_					=       ViTModel(UpperCAmelCase__      ,					add_pooling_layer=UpperCAmelCase__							).eval()
							else:
														lowerCamelCase_					=       ViTForImageClassification(UpperCAmelCase__							).eval()
							model.load_state_dict(UpperCAmelCase__							)

							# Check outputs on an image, prepared by ViTImageProcessor
							lowerCamelCase_					=       ViTImageProcessor()
							lowerCamelCase_					=       image_processor(images=prepare_img()      ,					return_tensors="""pt"""							)
							lowerCamelCase_					=       encoding["""pixel_values"""]
							lowerCamelCase_					=       model(UpperCAmelCase__							)

							if base_model:
														lowerCamelCase_					=       original_model(UpperCAmelCase__							)
														assert torch.allclose(UpperCAmelCase__      ,					outputs.last_hidden_state[:, 0, :]      ,					atol=1e-1							)
							else:
														lowerCamelCase_					=       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__":
		lowercase   =	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)
		lowercase   =	parser.parse_args()
		convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)





