




"""simple docstring"""
import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__SCREAMING_SNAKE_CASE							:      Any						=      logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE							:      Union[str, Any]						=      {
    'BAAI/AltCLIP': 'https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json',
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}





class        __A       (lowerCamelCase__):





							'''simple docstring'''

							__lowercase:						int							 =      """altclip_text_model"""



							def __init__(			self							: List[Any]						,    UpperCAmelCase_							: Tuple=250_002						,    UpperCAmelCase_							: List[Any]=1_024						,    UpperCAmelCase_							: Union[str, Any]=24						,    UpperCAmelCase_							: str=16						,    UpperCAmelCase_							: str=4_096						,    UpperCAmelCase_							: Optional[Any]="gelu"						,    UpperCAmelCase_							: List[Any]=0.1						,    UpperCAmelCase_							: Any=0.1						,    UpperCAmelCase_							: List[str]=514						,    UpperCAmelCase_							: Tuple=1						,    UpperCAmelCase_							: Any=0.02						,    UpperCAmelCase_							: List[str]=0.02						,    UpperCAmelCase_							: List[Any]=1E-05						,    UpperCAmelCase_							: Dict=1						,    UpperCAmelCase_							: int=0						,    UpperCAmelCase_							: Any=2						,    UpperCAmelCase_							: Optional[Any]="absolute"						,    UpperCAmelCase_							: Optional[Any]=True						,    UpperCAmelCase_							: List[str]=768						,    **UpperCAmelCase_							: Any						,    )   ->str:



														"""simple docstring"""



														super().__init__(pad_token_id=__snake_case						,    bos_token_id=__snake_case						,    eos_token_id=__snake_case						,    **__snake_case    )

														snake_case_          =						vocab_size
														snake_case_          =						hidden_size
														snake_case_          =						num_hidden_layers
														snake_case_          =						num_attention_heads
														snake_case_          =						hidden_act
														snake_case_          =						intermediate_size
														snake_case_          =						hidden_dropout_prob
														snake_case_          =						attention_probs_dropout_prob
														snake_case_          =						max_position_embeddings
														snake_case_          =						type_vocab_size
														snake_case_          =						initializer_range
														snake_case_          =						initializer_factor
														snake_case_          =						layer_norm_eps
														snake_case_          =						position_embedding_type
														snake_case_          =						use_cache
														snake_case_          =						project_dim





class        __A       (lowerCamelCase__):





							'''simple docstring'''

							__lowercase:						Optional[Any]							 =      """altclip_vision_model"""



							def __init__(			self							: Union[str, Any]						,    UpperCAmelCase_							: Any=768						,    UpperCAmelCase_							: str=3_072						,    UpperCAmelCase_							: Tuple=512						,    UpperCAmelCase_							: int=12						,    UpperCAmelCase_							: Any=12						,    UpperCAmelCase_							: List[Any]=3						,    UpperCAmelCase_							: Optional[int]=224						,    UpperCAmelCase_							: str=32						,    UpperCAmelCase_							: Union[str, Any]="quick_gelu"						,    UpperCAmelCase_							: Any=1E-5						,    UpperCAmelCase_							: Tuple=0.0						,    UpperCAmelCase_							: Union[str, Any]=0.02						,    UpperCAmelCase_							: List[str]=1.0						,    **UpperCAmelCase_							: Union[str, Any]						,    )   ->Any:



														"""simple docstring"""



														super().__init__(**__snake_case    )

														snake_case_          =						hidden_size
														snake_case_          =						intermediate_size
														snake_case_          =						projection_dim
														snake_case_          =						num_hidden_layers
														snake_case_          =						num_attention_heads
														snake_case_          =						num_channels
														snake_case_          =						patch_size
														snake_case_          =						image_size
														snake_case_          =						initializer_range
														snake_case_          =						initializer_factor
														snake_case_          =						attention_dropout
														snake_case_          =						layer_norm_eps
														snake_case_          =						hidden_act



							@classmethod
							def 						lowerCAmelCase    (			cls							: int						,    UpperCAmelCase_							: Union[str, os.PathLike]						,    **UpperCAmelCase_							: Dict    )   ->List[str]:



														"""simple docstring"""



														cls._set_token_in_kwargs(__snake_case    )

														snake_case_          =						cls.get_config_dict(__snake_case						,    **__snake_case    )

														# get the vision config dict if we are loading from AltCLIPConfig
														if config_dict.get("""model_type"""    ) == "altclip":
																					snake_case_          =						config_dict['vision_config']

														if "model_type" in config_dict and hasattr(cls						,    """model_type"""    ) and config_dict["model_type"] != cls.model_type:
																					logger.warning(
																					    F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
																					    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""    )

														return cls.from_dict(__snake_case						,    **__snake_case    )





class        __A       (lowerCamelCase__):





							'''simple docstring'''

							__lowercase:						Any							 =      """altclip"""
							__lowercase:						Optional[int]							 =      True



							def __init__(			self							: str						,    UpperCAmelCase_							: Optional[int]=None						,    UpperCAmelCase_							: Optional[int]=None						,    UpperCAmelCase_							: Tuple=768						,    UpperCAmelCase_							: Any=2.6_592						,    **UpperCAmelCase_							: List[Any]    )   ->Optional[Any]:



														"""simple docstring"""



														snake_case_          =						kwargs.pop("""text_config_dict"""						,    __snake_case    )
														snake_case_          =						kwargs.pop("""vision_config_dict"""						,    __snake_case    )

														super().__init__(**__snake_case    )

														# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
														# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
														# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
														if text_config_dict is not None:
																					if text_config is None:
																												snake_case_          =						{}

																					# This is the complete result when using `text_config_dict`.
																					snake_case_          =						AltCLIPTextConfig(**__snake_case    ).to_dict()

																					# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
																					for key, value in _text_config_dict.items():
																												if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
																																			# If specified in `text_config_dict`
																																			if key in text_config_dict:
																																										snake_case_          =						(
																																										    F"""`{key}` is found in both `text_config_dict` and `text_config` but with different values. """
																																										    F"""The value `text_config_dict[\"{key}\"]` will be used instead."""
																																										)
																																			# If inferred from default argument values (just to be super careful)
																																			else:
																																										snake_case_          =						(
																																										    F"""`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The """
																																										    F"""value `text_config[\"{key}\"]` will be overriden."""
																																										)
																																			logger.warning(__snake_case    )

																																			# Update all values in `text_config` with the ones in `_text_config_dict`.
																					text_config.update(_text_config_dict    )

														if vision_config_dict is not None:
																					if vision_config is None:
																												snake_case_          =						{}

																					# This is the complete result when using `vision_config_dict`.
																					snake_case_          =						AltCLIPVisionConfig(**__snake_case    ).to_dict()
																					# convert keys to string instead of integer
																					if "id2label" in _vision_config_dict:
																												snake_case_          =						{
																												    str(__snake_case    ): value for key, value in _vision_config_dict['id2label'].items()
																												}

																					# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
																					for key, value in _vision_config_dict.items():
																												if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
																																			# If specified in `vision_config_dict`
																																			if key in vision_config_dict:
																																										snake_case_          =						(
																																										    F"""`{key}` is found in both `vision_config_dict` and `vision_config` but with different """
																																										    F"""values. The value `vision_config_dict[\"{key}\"]` will be used instead."""
																																										)
																																			# If inferred from default argument values (just to be super careful)
																																			else:
																																										snake_case_          =						(
																																										    F"""`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. """
																																										    F"""The value `vision_config[\"{key}\"]` will be overriden."""
																																										)
																																			logger.warning(__snake_case    )

																																			# Update all values in `vision_config` with the ones in `_vision_config_dict`.
																					vision_config.update(_vision_config_dict    )

														if text_config is None:
																					snake_case_          =						{}
																					logger.info("""`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values."""    )

														if vision_config is None:
																					snake_case_          =						{}
																					logger.info("""`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values."""    )

														snake_case_          =						AltCLIPTextConfig(**__snake_case    )
														snake_case_          =						AltCLIPVisionConfig(**__snake_case    )

														snake_case_          =						projection_dim
														snake_case_          =						logit_scale_init_value
														snake_case_          =						1.0



							@classmethod
							def 						lowerCAmelCase    (			cls							: Any						,    UpperCAmelCase_							: AltCLIPTextConfig						,    UpperCAmelCase_							: AltCLIPVisionConfig						,    **UpperCAmelCase_							: str    )   ->Tuple:



														"""simple docstring"""



														return cls(text_config=text_config.to_dict()						,    vision_config=vision_config.to_dict()						,    **__snake_case    )



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



														"""simple docstring"""



														snake_case_          =						copy.deepcopy(self.__dict__    )
														snake_case_          =						self.text_config.to_dict()
														snake_case_          =						self.vision_config.to_dict()
														snake_case_          =						self.__class__.model_type
														return output







"""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)



