





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

def    __UpperCamelCase	(	a    : str					,   a    : Optional[Any]=False     ) ->Tuple:
 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    __UpperCamelCase	(	a    : Any					,   a    : Dict					,   a    : Optional[Any]=False     ) ->Optional[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    __UpperCamelCase	(	a    : Any     ) ->Optional[int]:
 snake_case				=			['''head.weight''', '''head.bias''']
 for k in ignore_keys:
  state_dict.pop(a					,   a     )

def    __UpperCamelCase	(	a    : Union[str, Any]					,   a    : List[Any]					,   a    : Dict     ) ->List[Any]:
 snake_case				=			dct.pop(a     )
 snake_case				=			val

def    __UpperCamelCase	(	) ->int:
 snake_case				=			'''http://images.cocodataset.org/val2017/000000039769.jpg'''
 snake_case				=			Image.open(requests.get(a					,   stream=a     ).raw     )
 return im

@torch.no_grad()
def    __UpperCamelCase	(	a    : List[Any]					,   a    : int					,   a    : List[str]=True     ) ->str:
 snake_case				=			ViTConfig()
 # patch_size
 if model_name[-1] == "8":
  snake_case				=			8
 # set labels if required
 if not base_model:
  snake_case				=			1000
  snake_case				=			'''huggingface/label-files'''
  snake_case				=			'''imagenet-1k-id2label.json'''
  snake_case				=			json.load(open(hf_hub_download(a					,   a					,   repo_type='''dataset'''     )					,   '''r'''     )     )
  snake_case				=			{int(a     ): 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				=			1536
  snake_case				=			12
  snake_case				=			6

 # load original model from torch hub
 snake_case				=			torch.hub.load('''facebookresearch/dino:main'''					,   a     )
 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_(a     )
 snake_case				=			create_rename_keys(a					,   base_model=a     )
 for src, dest in rename_keys:
  rename_key(a					,   a					,   a     )
 read_in_q_k_v(a					,   a					,   a     )

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

 # 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(a     )

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

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


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)








'''simple docstring'''







import inspect
import re
from hashlib import shaaaa
from typing import Dict, List

from .arrow import arrow
from .audiofolder import audiofolder
from .csv import csv
from .imagefolder import imagefolder
from .json import json
from .pandas import pandas
from .parquet import parquet
from .sql import sql  # noqa F401
from .text import text

def    __UpperCamelCase	(	a    : List[str]     ) ->str:
 snake_case				=			[]
 for line in lines:
  snake_case				=			re.sub(R'''#.*'''					,   ''''''					,   a     )  # remove comments
  if line:
   filtered_lines.append(a     )
 snake_case				=			'''\n'''.join(a     )

 # Make a hash from all this code
 snake_case				=			full_str.encode('''utf-8'''     )
 return shaaaa(a     ).hexdigest()


# get importable module names and hash for caching
_lowercase       						=			{
    'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())),
    'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())),
    'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())),
    'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())),
    'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())),
    'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())),
    'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())),
    'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())),
}

# Used to infer the module to use based on the data files extensions
_lowercase       						=			{
    '.csv': ('csv', {}),
    '.tsv': ('csv', {'sep': '\t'}),
    '.json': ('json', {}),
    '.jsonl': ('json', {}),
    '.parquet': ('parquet', {}),
    '.arrow': ('arrow', {}),
    '.txt': ('text', {}),
}
_EXTENSION_TO_MODULE.update({ext: ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext: ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
_lowercase       						=			{'imagefolder', 'audiofolder'}

# Used to filter data files based on extensions given a module name
_lowercase       						=			{}
for _ext, (_module, _) in _EXTENSION_TO_MODULE.items():
   _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext)

_MODULE_TO_EXTENSIONS["imagefolder"].append('.zip')






_MODULE_TO_EXTENSIONS["audiofolder"].append('.zip')

