






"""simple docstring"""




import argparse
import json
from pathlib import Path

import requests
import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform

from transformers import (
    BitConfig,
    ViTHybridConfig,
    ViTHybridForImageClassification,
    ViTHybridImageProcessor,
    ViTHybridModel,
)
from transformers.image_utils import PILImageResampling
from transformers.utils import logging


logging.set_verbosity_info()
UpperCamelCase							       =    logging.get_logger(__name__)






def        lowerCAmelCase (      UpperCamelCase_:							str     , UpperCamelCase_:							List[Any]=False					)       ->							Dict:







  '''simple docstring'''







  _a							=	[]

  # fmt: off
  # stem:
  rename_keys.append(("cls_token", "vit.embeddings.cls_token")					)
  rename_keys.append(("pos_embed", "vit.embeddings.position_embeddings")					)

  rename_keys.append(("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight")					)
  rename_keys.append(("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias")					)

  # backbone
  rename_keys.append(("patch_embed.backbone.stem.conv.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight")					)
  rename_keys.append(("patch_embed.backbone.stem.norm.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight")					)
  rename_keys.append(("patch_embed.backbone.stem.norm.bias", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias")					)

  for stage_idx in range(len(config.backbone_config.depths					)					):
    for layer_idx in range(config.backbone_config.depths[stage_idx]					):
      rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight''')					)
      rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight''')					)
      rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias''')					)
      rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight''')					)
      rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight''')					)
      rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias''')					)
      rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight''')					)
      rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight''')					)
      rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias''')					)

    rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight''')					)
    rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight''')					)
    rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias''')					)

  # transformer encoder
  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''')					)

  if base_model:
    # layernorm + pooler
    rename_keys.extend(
        [
            ("norm.weight", "layernorm.weight"),
            ("norm.bias", "layernorm.bias"),
            ("pre_logits.fc.weight", "pooler.dense.weight"),
            ("pre_logits.fc.bias", "pooler.dense.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"),
        ]					)
  # fmt: on

  return rename_keys






def        lowerCAmelCase (      UpperCamelCase_:							int     , UpperCamelCase_:							Dict     , UpperCamelCase_:							Optional[Any]=False					)       ->							Any:







  '''simple docstring'''







  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        lowerCAmelCase (      UpperCamelCase_:							int					)       ->							str:







  '''simple docstring'''







  _a							=	["head.weight", "head.bias"]
  for k in ignore_keys:
    state_dict.pop(UpperCamelCase_     , UpperCamelCase_					)






def        lowerCAmelCase (      UpperCamelCase_:							Optional[Any]     , UpperCamelCase_:							List[Any]     , UpperCamelCase_:							Optional[int]					)       ->							Tuple:







  '''simple docstring'''







  _a							=	dct.pop(UpperCamelCase_					)
  _a							=	val






def        lowerCAmelCase (      )       ->							Dict:







  '''simple docstring'''







  _a							=	"http://images.cocodataset.org/val2017/000000039769.jpg"
  _a							=	Image.open(requests.get(UpperCamelCase_     , stream=UpperCamelCase_					).raw					)
  return im






@torch.no_grad()
def        lowerCAmelCase (      UpperCamelCase_:							Dict     , UpperCamelCase_:							Dict     , UpperCamelCase_:							str=False					)       ->							Dict:







  '''simple docstring'''







  _a							=	BitConfig(
      global_padding="same"     , layer_type="bottleneck"     , depths=(3, 4, 9)     , out_features=["stage3"]     , embedding_dynamic_padding=UpperCamelCase_     , )
  _a							=	ViTHybridConfig(backbone_config=UpperCamelCase_     , image_size=384     , num_labels=1000					)
  _a							=	False

  # load original model from timm
  _a							=	timm.create_model(UpperCamelCase_     , pretrained=UpperCamelCase_					)
  timm_model.eval()

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

  _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()}

  # load HuggingFace model
  if vit_name[-5:] == "in21k":
    _a							=	ViTHybridModel(UpperCamelCase_					).eval()
  else:
    _a							=	ViTHybridForImageClassification(UpperCamelCase_					).eval()
  model.load_state_dict(UpperCamelCase_					)

  # create image processor
  _a							=	create_transform(**resolve_data_config({}     , model=UpperCamelCase_					)					)
  _a							=	transform.transforms

  _a							=	{
      "bilinear": PILImageResampling.BILINEAR,
      "bicubic": PILImageResampling.BICUBIC,
      "nearest": PILImageResampling.NEAREST,
  }

  _a							=	ViTHybridImageProcessor(
      do_resize=UpperCamelCase_     , size={"shortest_edge": timm_transforms[0].size}     , resample=pillow_resamplings[timm_transforms[0].interpolation.value]     , do_center_crop=UpperCamelCase_     , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]}     , do_normalize=UpperCamelCase_     , image_mean=timm_transforms[-1].mean.tolist()     , image_std=timm_transforms[-1].std.tolist()     , )

  _a							=	prepare_img()
  _a							=	transform(UpperCamelCase_					).unsqueeze(0					)
  _a							=	processor(UpperCamelCase_     , return_tensors="pt"					).pixel_values

  # verify pixel values
  assert torch.allclose(UpperCamelCase_     , UpperCamelCase_					)

  # verify logits
  with torch.no_grad():
    _a							=	model(UpperCamelCase_					)
    _a							=	outputs.logits

  print("Predicted class:"     , logits.argmax(-1					).item()					)
  if base_model:
    _a							=	timm_model.forward_features(UpperCamelCase_					)
    assert timm_pooled_output.shape == outputs.pooler_output.shape
    assert torch.allclose(UpperCamelCase_     , outputs.pooler_output     , atol=1E-3					)
  else:
    _a							=	timm_model(UpperCamelCase_					)
    assert timm_logits.shape == outputs.logits.shape
    assert torch.allclose(UpperCamelCase_     , outputs.logits     , atol=1E-3					)
  print("Looks ok!"					)

  if pytorch_dump_folder_path is not None:
    Path(UpperCamelCase_					).mkdir(exist_ok=UpperCamelCase_					)
    print(f'''Saving model {vit_name} to {pytorch_dump_folder_path}'''					)
    model.save_pretrained(UpperCamelCase_					)
    print(f'''Saving processor to {pytorch_dump_folder_path}'''					)
    processor.save_pretrained(UpperCamelCase_					)

  if push_to_hub:
    print(f'''Pushing model and processor to the hub {vit_name}'''					)
    model.push_to_hub(f'''ybelkada/{vit_name}'''					)
    processor.push_to_hub(f'''ybelkada/{vit_name}'''					)


if __name__ == "__main__":
     UpperCamelCase							       =    argparse.ArgumentParser()
     # Required parameters
     parser.add_argument(
         """--vit_name""",
         default="""vit_base_r50_s16_384""",
         type=str,
         help="""Name of the hybrid ViT timm model 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(
         """--push_to_hub""", action="""store_true""", help="""Whether to upload the model to the HuggingFace hub."""
     )

     UpperCamelCase							       =    parser.parse_args()
     convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)









"""simple docstring"""




from __future__ import annotations

from collections.abc import Callable
from typing import Generic, TypeVar

UpperCamelCase							       =    TypeVar("""T""")
UpperCamelCase							       =    TypeVar("""U""")




class    lowercase_    (Generic[T, U]     ):






      def __init__(    self     ,     a_     ,     a_	)	->Any:







        '''simple docstring'''


        _a							=	key
        _a							=	val
        _a							=	None
        _a							=	None






      def __repr__(    self	)	->str:







        '''simple docstring'''


        return (
            f'''Node: key: {self.key}, val: {self.val}, '''
            f'''has next: {bool(self.next	)}, has prev: {bool(self.prev	)}'''
        )







class    lowercase_    (Generic[T, U]     ):






      def __init__(    self	)	->None:







        '''simple docstring'''


        _a							=	DoubleLinkedListNode(a_     ,     a_	)
        _a							=	DoubleLinkedListNode(a_     ,     a_	)
        _a			,	_a							=	self.rear, self.head






      def __repr__(    self	)	->str:







        '''simple docstring'''


        _a							=	["DoubleLinkedList"]
        _a							=	self.head
        while node.next is not None:
          rep.append(str(a_	)	)
          _a							=	node.next
        rep.append(str(self.rear	)	)
        return ",\n    ".join(a_	)






      def 			lowerCamelCase__    (    self     ,     a_	)	->None:







        '''simple docstring'''


        _a							=	self.rear.prev

        # All nodes other than self.head are guaranteed to have non-None previous
        assert previous is not None

        _a							=	node
        _a							=	previous
        _a							=	node
        _a							=	self.rear






      def 			lowerCamelCase__    (    self     ,     a_	)	->DoubleLinkedListNode[T, U] | None:







        '''simple docstring'''


        if node.prev is None or node.next is None:
          return None

        _a							=	node.next
        _a							=	node.prev
        _a							=	None
        _a							=	None
        return node







class    lowercase_    (Generic[T, U]     ):
      A__	:		dict[Callable[[T], U], LRUCache[T, U]]       			=				{}






      def __init__(    self     ,     a_	)	->int:







        '''simple docstring'''


        _a							=	DoubleLinkedList()
        _a							=	capacity
        _a							=	0
        _a							=	0
        _a							=	0
        _a							=	{}






      def __repr__(    self	)	->str:







        '''simple docstring'''


        return (
            f'''CacheInfo(hits={self.hits}, misses={self.miss}, '''
            f'''capacity={self.capacity}, current size={self.num_keys})'''
        )






      def __contains__(    self     ,     a_	)	->bool:







        '''simple docstring'''


        return key in self.cache






      def 			lowerCamelCase__    (    self     ,     a_	)	->U | None:







        '''simple docstring'''


        if key in self.cache:
          self.hits += 1
          _a							=	self.cache[key]
          _a							=	self.list.remove(self.cache[key]	)
          assert node == value_node

          # node is guaranteed not None because it is in self.cache
          assert node is not None
          self.list.add(a_	)
          return node.val
        self.miss += 1
        return None






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_	)	->None:







        '''simple docstring'''


        if key not in self.cache:
          if self.num_keys >= self.capacity:
            # delete first node (oldest) when over capacity
            _a							=	self.list.head.next

            # guaranteed to have a non-None first node when num_keys > 0
            # explain to type checker via assertions
            assert first_node is not None
            assert first_node.key is not None
            assert (
                self.list.remove(a_	) is not None
            )  # node guaranteed to be in list assert node.key is not None

            del self.cache[first_node.key]
            self.num_keys -= 1
          _a							=	DoubleLinkedListNode(a_     ,     a_	)
          self.list.add(self.cache[key]	)
          self.num_keys += 1

        else:
          # bump node to the end of the list, update value
          _a							=	self.list.remove(self.cache[key]	)
          assert node is not None  # node guaranteed to be in list
          _a							=	value
          self.list.add(a_	)






      @classmethod
      def 			lowerCamelCase__    (    cls     ,     a_ = 1_2_8	)	->Callable[[Callable[[T], U]], Callable[..., U]]:







        '''simple docstring'''


        def cache_decorator_inner(a_	) -> Callable[..., U]:
          def cache_decorator_wrapper(*a_	) -> U:
            if func not in cls.decorator_function_to_instance_map:
              _a							=	LRUCache(a_	)

            _a							=	cls.decorator_function_to_instance_map[func].get(args[0]	)
            if result is None:
              _a							=	func(*a_	)
              cls.decorator_function_to_instance_map[func].put(args[0]     ,     a_	)
            return result

          def cache_info() -> LRUCache[T, U]:
            return cls.decorator_function_to_instance_map[func]

          setattr(a_     ,     "cache_info"     ,     a_	)  # noqa: B010

          return cache_decorator_wrapper

        return cache_decorator_inner


if __name__ == "__main__":
     import doctest

     doctest.testmod()


