



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()
a_      :      Tuple    =     logging.get_logger(__name__)






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






def     __a					(		__UpperCAmelCase       ):
 a__												= ['''head.weight''', '''head.bias''']
 for k in ignore_keys:
  state_dict.pop(__UpperCAmelCase							,  __UpperCAmelCase       )






def     __a					(		__UpperCAmelCase							,  __UpperCAmelCase							,  __UpperCAmelCase       ):
 a__												= dct.pop(__UpperCAmelCase       )
 a__												= val






def     __a					(		):
 a__												= '''http://images.cocodataset.org/val2017/000000039769.jpg'''
 a__												= Image.open(requests.get(__UpperCAmelCase							,  stream=__UpperCAmelCase       ).raw       )
 return im






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

 # load original model from torch hub
 a__												= torch.hub.load('''facebookresearch/dino:main'''							,  __UpperCAmelCase       )
 original_model.eval()

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

 # Check outputs on an image, prepared by ViTImageProcessor
 a__												= ViTImageProcessor()
 a__												= image_processor(images=prepare_img()							,  return_tensors='''pt'''       )
 a__												= encoding['''pixel_values''']
 a__												= model(__UpperCAmelCase       )

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










from typing import List, Optional, TypeVar

from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .info import DatasetInfo
from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets
from .splits import NamedSplit
from .utils import logging
from .utils.py_utils import Literal


a_      :      Any    =     logging.get_logger(__name__)


a_      :      str    =     TypeVar('DatasetType', Dataset, IterableDataset)






def     __a					(		__UpperCAmelCase							,  __UpperCAmelCase = None							,  __UpperCAmelCase = None							,  __UpperCAmelCase = None							,  __UpperCAmelCase = None							,  __UpperCAmelCase = "first_exhausted"							,  ):
 from .arrow_dataset import Dataset
 from .iterable_dataset import IterableDataset

 if not datasets:
  raise ValueError('''Unable to interleave an empty list of datasets.'''       )
 for i, dataset in enumerate(__UpperCAmelCase       ):
  if not isinstance(__UpperCAmelCase							,  (Dataset, IterableDataset)       ):
   if isinstance(__UpperCAmelCase							,  (DatasetDict, IterableDatasetDict)       ):
    if not dataset:
     raise ValueError(
         f"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} "
         '''is an empty dataset dictionary.'''       )
    raise ValueError(
        f"Dataset at position {i} has at least one split: {list(__UpperCAmelCase       )}\n"
        f"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(__UpperCAmelCase       )       )}']"       )
   raise ValueError(
       f"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(__UpperCAmelCase       ).__name__}."       )
  if i == 0:
   a__							,			a__												= (
       (Dataset, IterableDataset) if isinstance(__UpperCAmelCase							,  __UpperCAmelCase       ) else (IterableDataset, Dataset)
   )
  elif not isinstance(__UpperCAmelCase							,  __UpperCAmelCase       ):
   raise ValueError(
       f"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects."       )
 if stopping_strategy not in ["first_exhausted", "all_exhausted"]:
  raise ValueError(f"{stopping_strategy} is not supported. Please enter a valid stopping_strategy."       )
 if dataset_type is Dataset:
  return _interleave_map_style_datasets(
      __UpperCAmelCase							,  __UpperCAmelCase							,  __UpperCAmelCase							,  info=__UpperCAmelCase							,  split=__UpperCAmelCase							,  stopping_strategy=__UpperCAmelCase       )
 else:
  return _interleave_iterable_datasets(
      __UpperCAmelCase							,  __UpperCAmelCase							,  __UpperCAmelCase							,  info=__UpperCAmelCase							,  split=__UpperCAmelCase							,  stopping_strategy=__UpperCAmelCase       )






def     __a					(		__UpperCAmelCase							,  __UpperCAmelCase = None							,  __UpperCAmelCase = None							,  __UpperCAmelCase = 0							,  ):

 if not dsets:
  raise ValueError('''Unable to concatenate an empty list of datasets.'''       )
 for i, dataset in enumerate(__UpperCAmelCase       ):
  if not isinstance(__UpperCAmelCase							,  (Dataset, IterableDataset)       ):
   if isinstance(__UpperCAmelCase							,  (DatasetDict, IterableDatasetDict)       ):
    if not dataset:
     raise ValueError(
         f"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} "
         '''is an empty dataset dictionary.'''       )
    raise ValueError(
        f"Dataset at position {i} has at least one split: {list(__UpperCAmelCase       )}\n"
        f"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(__UpperCAmelCase       )       )}']"       )
   raise ValueError(
       f"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(__UpperCAmelCase       ).__name__}."       )
  if i == 0:
   a__							,			a__												= (
       (Dataset, IterableDataset) if isinstance(__UpperCAmelCase							,  __UpperCAmelCase       ) else (IterableDataset, Dataset)
   )
  elif not isinstance(__UpperCAmelCase							,  __UpperCAmelCase       ):
   raise ValueError(
       f"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects."       )
 if dataset_type is Dataset:
  return _concatenate_map_style_datasets(__UpperCAmelCase							,  info=__UpperCAmelCase							,  split=__UpperCAmelCase							,  axis=__UpperCAmelCase       )
 else:
  return _concatenate_iterable_datasets(__UpperCAmelCase							,  info=__UpperCAmelCase							,  split=__UpperCAmelCase							,  axis=__UpperCAmelCase       )





