


"""simple docstring"""
import inspect
import unittest

from transformers import ViTHybridConfig
from transformers.testing_utils import require_accelerate, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel
				from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image





class        __A       :





							'''simple docstring'''

							def __init__(			self							: Optional[Any]						,    UpperCAmelCase_							: Optional[Any]						,    UpperCAmelCase_							: Optional[int]=13						,    UpperCAmelCase_							: Any=64						,    UpperCAmelCase_							: List[str]=2						,    UpperCAmelCase_							: Any=3						,    UpperCAmelCase_							: List[str]=True						,    UpperCAmelCase_							: Dict=True						,    UpperCAmelCase_							: Tuple=32						,    UpperCAmelCase_							: Tuple=5						,    UpperCAmelCase_							: Union[str, Any]=4						,    UpperCAmelCase_							: List[str]=37						,    UpperCAmelCase_							: List[Any]="gelu"						,    UpperCAmelCase_							: int=0.1						,    UpperCAmelCase_							: Tuple=0.1						,    UpperCAmelCase_							: Any=10						,    UpperCAmelCase_							: Dict=0.02						,    UpperCAmelCase_							: Any=[1, 16, 4, 4]						,    UpperCAmelCase_							: Optional[int]=None						,    )   ->str:



														"""simple docstring"""



														snake_case_          =						parent
														snake_case_          =						batch_size
														snake_case_          =						image_size
														snake_case_          =						patch_size
														snake_case_          =						num_channels
														snake_case_          =						is_training
														snake_case_          =						use_labels
														snake_case_          =						hidden_size
														snake_case_          =						num_hidden_layers
														snake_case_          =						num_attention_heads
														snake_case_          =						intermediate_size
														snake_case_          =						hidden_act
														snake_case_          =						hidden_dropout_prob
														snake_case_          =						attention_probs_dropout_prob
														snake_case_          =						type_sequence_label_size
														snake_case_          =						initializer_range
														snake_case_          =						scope
														snake_case_          =						backbone_featmap_shape

														# in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
														# the number of patches is based on the feature map of the backbone, which by default uses an output stride
														# of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size
														snake_case_          =						(self.image_size // 32) ** 2
														snake_case_          =						num_patches + 1



							def 						lowerCAmelCase    (			self							: List[Any]    )   ->Any:



														"""simple docstring"""



														snake_case_          =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

														snake_case_          =						None
														if self.use_labels:
																					snake_case_          =						ids_tensor([self.batch_size]						,    self.type_sequence_label_size    )

														snake_case_          =						self.get_config()

														return config, pixel_values, labels



							def 						lowerCAmelCase    (			self							: str    )   ->Dict:



														"""simple docstring"""



														snake_case_          =						{
														    """global_padding""": """same""",
														    """layer_type""": """bottleneck""",
														    """depths""": [3, 4, 9],
														    """out_features""": ["""stage1""", """stage2""", """stage3"""],
														    """embedding_dynamic_padding""": True,
														    """hidden_sizes""": [4, 8, 16, 32],
														    """num_groups""": 2,
														}

														return ViTHybridConfig(
														    image_size=self.image_size						,    patch_size=self.patch_size						,    num_channels=self.num_channels						,    hidden_size=self.hidden_size						,    num_hidden_layers=self.num_hidden_layers						,    num_attention_heads=self.num_attention_heads						,    intermediate_size=self.intermediate_size						,    hidden_act=self.hidden_act						,    hidden_dropout_prob=self.hidden_dropout_prob						,    attention_probs_dropout_prob=self.attention_probs_dropout_prob						,    is_decoder=UpperCAmelCase_						,    initializer_range=self.initializer_range						,    backbone_featmap_shape=self.backbone_featmap_shape						,    backbone_config=UpperCAmelCase_						,    )



							def 						lowerCAmelCase    (			self							: Dict						,    UpperCAmelCase_							: Any						,    UpperCAmelCase_							: Dict						,    UpperCAmelCase_							: int    )   ->Optional[int]:



														"""simple docstring"""



														snake_case_          =						ViTHybridModel(config=UpperCAmelCase_    )
														model.to(UpperCAmelCase_    )
														model.eval()
														snake_case_          =						model(UpperCAmelCase_    )
														self.parent.assertEqual(result.last_hidden_state.shape						,    (self.batch_size, self.seq_length, self.hidden_size)    )



							def 						lowerCAmelCase    (			self							: Optional[int]						,    UpperCAmelCase_							: Optional[Any]						,    UpperCAmelCase_							: str						,    UpperCAmelCase_							: Tuple    )   ->int:



														"""simple docstring"""



														snake_case_          =						self.type_sequence_label_size
														snake_case_          =						ViTHybridForImageClassification(UpperCAmelCase_    )
														model.to(UpperCAmelCase_    )
														model.eval()
														snake_case_          =						model(UpperCAmelCase_						,    labels=UpperCAmelCase_    )
														self.parent.assertEqual(result.logits.shape						,    (self.batch_size, self.type_sequence_label_size)    )



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



														"""simple docstring"""



														snake_case_          =						self.prepare_config_and_inputs()
														snake_case_    ,  snake_case_    ,  snake_case_          =						config_and_inputs
														snake_case_          =						{"""pixel_values""": pixel_values}
														return config, inputs_dict





@require_torch
class        __A       (snake_case__  ,						snake_case__  ,						unittest.TestCase):





							'''simple docstring'''

							__lowercase:						str							 =      (ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else ()
							__lowercase:						int							 =      (
							    {"""feature-extraction""": ViTHybridModel, """image-classification""": ViTHybridForImageClassification}
							    if is_torch_available()
							    else {}
							)
							__lowercase:						Optional[Any]							 =      False
							__lowercase:						List[Any]							 =      False
							__lowercase:						int							 =      False



							def 						lowerCAmelCase    (			self							: Optional[Any]    )   ->Union[str, Any]:



														"""simple docstring"""



														snake_case_          =						ViTHybridModelTester(self    )
														snake_case_          =						ConfigTester(self						,    config_class=UpperCAmelCase_						,    has_text_modality=UpperCAmelCase_						,    hidden_size=37    )



							def 						lowerCAmelCase    (			self							: Optional[int]    )   ->Optional[int]:



														"""simple docstring"""



														self.config_tester.run_common_tests()



							@unittest.skip(reason="""ViT does not use inputs_embeds"""    )
							def 						lowerCAmelCase    (			self							: int    )   ->List[Any]:



														"""simple docstring"""



														pass



							def 						lowerCAmelCase    (			self							: int    )   ->Any:



														"""simple docstring"""



														snake_case_    ,  snake_case_          =						self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					snake_case_          =						model_class(UpperCAmelCase_    )
																					self.assertIsInstance(model.get_input_embeddings()						,    (nn.Module)    )
																					snake_case_          =						model.get_output_embeddings()
																					self.assertTrue(x is None or isinstance(UpperCAmelCase_						,    nn.Linear    )    )



							def 						lowerCAmelCase    (			self							: List[Any]    )   ->Any:



														"""simple docstring"""



														snake_case_    ,  snake_case_          =						self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					snake_case_          =						model_class(UpperCAmelCase_    )
																					snake_case_          =						inspect.signature(model.forward    )
																					# signature.parameters is an OrderedDict => so arg_names order is deterministic
																					snake_case_          =						[*signature.parameters.keys()]

																					snake_case_          =						["""pixel_values"""]
																					self.assertListEqual(arg_names[:1]						,    UpperCAmelCase_    )



							def 						lowerCAmelCase    (			self							: List[Any]    )   ->Any:



														"""simple docstring"""



														snake_case_          =						self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*UpperCAmelCase_    )



							def 						lowerCAmelCase    (			self							: int    )   ->Any:



														"""simple docstring"""



														snake_case_          =						self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_    )



							def 						lowerCAmelCase    (			self							: Dict    )   ->Tuple:



														"""simple docstring"""



														snake_case_    ,  snake_case_          =						self.model_tester.prepare_config_and_inputs_for_common()

														snake_case_          =						_config_zero_init(UpperCAmelCase_    )
														for model_class in self.all_model_classes:
																					snake_case_          =						model_class(config=UpperCAmelCase_    )
																					# Skip the check for the backbone
																					for name, module in model.named_modules():
																												if module.__class__.__name__ == "ViTHybridPatchEmbeddings":
																																			snake_case_          =						[F"""{name}.{key}""" for key in module.state_dict().keys()]
																																			break

																					for name, param in model.named_parameters():
																												if param.requires_grad:
																																			if name in backbone_params:
																																										continue
																																			self.assertIn(
																																			    ((param.data.mean() * 1E9).round() / 1E9).item()						,    [0.0, 1.0]						,    msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""						,    )



							@slow
							def 						lowerCAmelCase    (			self							: List[Any]    )   ->Tuple:



														"""simple docstring"""



														for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					snake_case_          =						ViTHybridModel.from_pretrained(UpperCAmelCase_    )
																					self.assertIsNotNone(UpperCAmelCase_    )







def   _a			( )      ->			Tuple:
							snake_case_          =						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
							return image





@require_torch
@require_vision
class        __A       (unittest.TestCase):





							'''simple docstring'''

							@cached_property
							def 						lowerCAmelCase    (			self							: int    )   ->int:



														"""simple docstring"""



														return (
														    ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )
														    if is_vision_available()
														    else None
														)



							@slow
							def 						lowerCAmelCase    (			self							: Dict    )   ->Dict:



														"""simple docstring"""



														snake_case_          =						ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]    ).to(
														    UpperCAmelCase_    )

														snake_case_          =						self.default_image_processor
														snake_case_          =						prepare_img()
														snake_case_          =						image_processor(images=UpperCAmelCase_						,    return_tensors="""pt"""    ).to(UpperCAmelCase_    )

														# forward pass
														with torch.no_grad():
																					snake_case_          =						model(**UpperCAmelCase_    )

														# verify the logits
														snake_case_          =						torch.Size((1, 1_000)    )
														self.assertEqual(outputs.logits.shape						,    UpperCAmelCase_    )

														snake_case_          =						torch.tensor([-1.9_090, -0.4_993, -0.2_389]    ).to(UpperCAmelCase_    )

														self.assertTrue(torch.allclose(outputs.logits[0, :3]						,    UpperCAmelCase_						,    atol=1E-4    )    )



							@slow
							@require_accelerate
							def 						lowerCAmelCase    (			self							: str    )   ->Tuple:



														"""simple docstring"""



														snake_case_          =						ViTHybridImageProcessor.from_pretrained("""google/vit-hybrid-base-bit-384"""    )
														snake_case_          =						ViTHybridForImageClassification.from_pretrained("""google/vit-hybrid-base-bit-384"""						,    device_map="""auto"""    )

														snake_case_          =						prepare_img()

														snake_case_          =						image_processor(images=UpperCAmelCase_						,    return_tensors="""pt"""    )
														snake_case_          =						model(**UpperCAmelCase_    )
														snake_case_          =						outputs.logits
														# model predicts one of the 1000 ImageNet classes
														snake_case_          =						logits.argmax(-1    ).item()

														self.assertTrue(model.config.idalabel[predicted_class_idx]						,    """tabby, tabby cat"""    )







"""simple docstring"""
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()
__SCREAMING_SNAKE_CASE							:      List[str]						=      logging.get_logger(__name__)







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







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			Union[str, Any]:
							snake_case_          =						["""head.weight""", """head.bias"""]
							for k in ignore_keys:
														state_dict.pop(_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)







def   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)      ->			int:
							snake_case_          =						dct.pop(_SCREAMING_SNAKE_CASE			)
							snake_case_          =						val







def   _a			( )      ->			Dict:
							snake_case_          =						"""http://images.cocodataset.org/val2017/000000039769.jpg"""
							snake_case_          =						Image.open(requests.get(_SCREAMING_SNAKE_CASE			,	stream=_SCREAMING_SNAKE_CASE			).raw			)
							return im







@torch.no_grad()
def   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE=True			)      ->			Any:
							snake_case_          =						ViTConfig()
							# patch_size
							if model_name[-1] == "8":
														snake_case_          =						8
							# set labels if required
							if not base_model:
														snake_case_          =						1_000
														snake_case_          =						"""huggingface/label-files"""
														snake_case_          =						"""imagenet-1k-id2label.json"""
														snake_case_          =						json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	repo_type="""dataset"""			)			,	"""r"""			)			)
														snake_case_          =						{int(_SCREAMING_SNAKE_CASE			): v for k, v in idalabel.items()}
														snake_case_          =						idalabel
														snake_case_          =						{v: k for k, v in idalabel.items()}
							# size of the architecture
							if model_name in ["dino_vits8", "dino_vits16"]:
														snake_case_          =						384
														snake_case_          =						1_536
														snake_case_          =						12
														snake_case_          =						6

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

							# load state_dict of original model, remove and rename some keys
							snake_case_          =						original_model.state_dict()
							if base_model:
														remove_classification_head_(_SCREAMING_SNAKE_CASE			)
							snake_case_          =						create_rename_keys(_SCREAMING_SNAKE_CASE			,	base_model=_SCREAMING_SNAKE_CASE			)
							for src, dest in rename_keys:
														rename_key(_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)
							read_in_q_k_v(_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)

							# load HuggingFace model
							if base_model:
														snake_case_          =						ViTModel(_SCREAMING_SNAKE_CASE			,	add_pooling_layer=_SCREAMING_SNAKE_CASE			).eval()
							else:
														snake_case_          =						ViTForImageClassification(_SCREAMING_SNAKE_CASE			).eval()
							model.load_state_dict(_SCREAMING_SNAKE_CASE			)

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

							if base_model:
														snake_case_          =						original_model(_SCREAMING_SNAKE_CASE			)
														assert torch.allclose(_SCREAMING_SNAKE_CASE			,	outputs.last_hidden_state[:, 0, :]			,	atol=1E-1			)
							else:
														snake_case_          =						original_model(_SCREAMING_SNAKE_CASE			)
														assert logits.shape == outputs.logits.shape
														assert torch.allclose(_SCREAMING_SNAKE_CASE			,	outputs.logits			,	atol=1E-3			)

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


if __name__ == "__main__":
				__SCREAMING_SNAKE_CASE							:      Optional[int]						=      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)
				__SCREAMING_SNAKE_CASE							:      int						=      parser.parse_args()
				convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)



