


"""simple docstring"""
from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
				import numpy
				import tensorflow as tf

				from transformers import (
				    TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
				    BertConfig,
				    DPRConfig,
				    TFDPRContextEncoder,
				    TFDPRQuestionEncoder,
				    TFDPRReader,
				)





class        __A       :





							'''simple docstring'''

							def __init__(			self							: Any						,    UpperCAmelCase_							: Optional[Any]						,    UpperCAmelCase_							: Dict=13						,    UpperCAmelCase_							: str=7						,    UpperCAmelCase_							: Dict=True						,    UpperCAmelCase_							: List[Any]=True						,    UpperCAmelCase_							: str=True						,    UpperCAmelCase_							: Dict=True						,    UpperCAmelCase_							: List[str]=99						,    UpperCAmelCase_							: List[str]=32						,    UpperCAmelCase_							: List[Any]=2						,    UpperCAmelCase_							: List[str]=4						,    UpperCAmelCase_							: str=37						,    UpperCAmelCase_							: Tuple="gelu"						,    UpperCAmelCase_							: List[Any]=0.1						,    UpperCAmelCase_							: List[str]=0.1						,    UpperCAmelCase_							: str=512						,    UpperCAmelCase_							: int=16						,    UpperCAmelCase_							: List[str]=2						,    UpperCAmelCase_							: Tuple=0.02						,    UpperCAmelCase_							: Any=3						,    UpperCAmelCase_							: Optional[int]=4						,    UpperCAmelCase_							: str=None						,    UpperCAmelCase_							: Dict=0						,    )   ->List[str]:



														"""simple docstring"""



														snake_case_          =						parent
														snake_case_          =						batch_size
														snake_case_          =						seq_length
														snake_case_          =						is_training
														snake_case_          =						use_input_mask
														snake_case_          =						use_token_type_ids
														snake_case_          =						use_labels
														snake_case_          =						vocab_size
														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_          =						max_position_embeddings
														snake_case_          =						type_vocab_size
														snake_case_          =						type_sequence_label_size
														snake_case_          =						initializer_range
														snake_case_          =						num_labels
														snake_case_          =						num_choices
														snake_case_          =						scope
														snake_case_          =						projection_dim



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



														"""simple docstring"""



														snake_case_          =						ids_tensor([self.batch_size, self.seq_length]						,    self.vocab_size    )

														snake_case_          =						None
														if self.use_input_mask:
																					# follow test_modeling_tf_ctrl.py
																					snake_case_          =						random_attention_mask([self.batch_size, self.seq_length]    )

														snake_case_          =						None
														if self.use_token_type_ids:
																					snake_case_          =						ids_tensor([self.batch_size, self.seq_length]						,    self.type_vocab_size    )

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

														snake_case_          =						BertConfig(
														    vocab_size=self.vocab_size						,    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						,    max_position_embeddings=self.max_position_embeddings						,    type_vocab_size=self.type_vocab_size						,    is_decoder=UpperCAmelCase_						,    initializer_range=self.initializer_range						,    )
														snake_case_          =						DPRConfig(projection_dim=self.projection_dim						,    **config.to_dict()    )

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



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



														"""simple docstring"""



														snake_case_          =						TFDPRContextEncoder(config=UpperCAmelCase_    )
														snake_case_          =						model(UpperCAmelCase_						,    attention_mask=UpperCAmelCase_						,    token_type_ids=UpperCAmelCase_    )
														snake_case_          =						model(UpperCAmelCase_						,    token_type_ids=UpperCAmelCase_    )
														snake_case_          =						model(UpperCAmelCase_    )
														self.parent.assertEqual(result.pooler_output.shape						,    (self.batch_size, self.projection_dim or self.hidden_size)    )



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



														"""simple docstring"""



														snake_case_          =						TFDPRQuestionEncoder(config=UpperCAmelCase_    )
														snake_case_          =						model(UpperCAmelCase_						,    attention_mask=UpperCAmelCase_						,    token_type_ids=UpperCAmelCase_    )
														snake_case_          =						model(UpperCAmelCase_						,    token_type_ids=UpperCAmelCase_    )
														snake_case_          =						model(UpperCAmelCase_    )
														self.parent.assertEqual(result.pooler_output.shape						,    (self.batch_size, self.projection_dim or self.hidden_size)    )



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



														"""simple docstring"""



														snake_case_          =						TFDPRReader(config=UpperCAmelCase_    )
														snake_case_          =						model(UpperCAmelCase_						,    attention_mask=UpperCAmelCase_    )

														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)    )
														self.parent.assertEqual(result.relevance_logits.shape						,    (self.batch_size,)    )



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



														"""simple docstring"""



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





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





							'''simple docstring'''

							__lowercase:						int							 =      (
							    (
							        TFDPRContextEncoder,
							        TFDPRQuestionEncoder,
							        TFDPRReader,
							    )
							    if is_tf_available()
							    else ()
							)
							__lowercase:						Union[str, Any]							 =      {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {}

							__lowercase:						Tuple							 =      False
							__lowercase:						Optional[Any]							 =      False
							__lowercase:						str							 =      False
							__lowercase:						Tuple							 =      False
							__lowercase:						Tuple							 =      False



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



														"""simple docstring"""



														snake_case_          =						TFDPRModelTester(self    )
														snake_case_          =						ConfigTester(self						,    config_class=UpperCAmelCase_						,    hidden_size=37    )



							def 						lowerCAmelCase    (			self							: Dict    )   ->Dict:



														"""simple docstring"""



														self.config_tester.run_common_tests()



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



														"""simple docstring"""



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



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



														"""simple docstring"""



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



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



														"""simple docstring"""



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



							@slow
							def 						lowerCAmelCase    (			self							: Union[str, Any]    )   ->List[Any]:



														"""simple docstring"""



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

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

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

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





@require_tf
class        __A       (unittest.TestCase):





							'''simple docstring'''

							@slow
							def 						lowerCAmelCase    (			self							: List[str]    )   ->Optional[int]:



														"""simple docstring"""



														snake_case_          =						TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base"""    )

														snake_case_          =						tf.constant(
														    [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]]    )  # [CLS] hello, is my dog cute? [SEP]
														snake_case_          =						model(UpperCAmelCase_    )[0]  # embedding shape = (1, 768)
														# compare the actual values for a slice.
														snake_case_          =						tf.constant(
														    [
														        [
														            0.03_236_253,
														            0.12_753_335,
														            0.16_818_509,
														            0.00_279_786,
														            0.3_896_933,
														            0.24_264_945,
														            0.2_178_971,
														            -0.02_335_227,
														            -0.08_481_959,
														            -0.14_324_117,
														        ]
														    ]    )
														self.assertTrue(numpy.allclose(output[:, :10].numpy()						,    expected_slice.numpy()						,    atol=1E-4    )    )







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



