


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




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




def      lowerCamelCase					(      lowerCamelCase  :      int):
      A_						:  Union[str, Any]          =				["""head.weight""", """head.bias"""]
      for k in ignore_keys:
            state_dict.pop(lowerCamelCase							,						lowerCamelCase)




def      lowerCamelCase					(      lowerCamelCase  :      int							,						lowerCamelCase  :      Dict							,						lowerCamelCase  :      int):
      A_						:  List[str]          =				dct.pop(lowerCamelCase)
      A_						:  Tuple          =				val




def      lowerCamelCase					(      ):
      A_						:  Any          =				"""http://images.cocodataset.org/val2017/000000039769.jpg"""
      A_						:  Optional[Any]          =				Image.open(requests.get(lowerCamelCase							,						stream=lowerCamelCase).raw)
      return im




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

      # load original model from torch hub
      A_						:  Tuple          =				torch.hub.load("""facebookresearch/dino:main"""							,						lowerCamelCase)
      original_model.eval()

      # load state_dict of original model, remove and rename some keys
      A_						:  Tuple          =				original_model.state_dict()
      if base_model:
            remove_classification_head_(lowerCamelCase)
      A_						:  Optional[Any]          =				create_rename_keys(lowerCamelCase							,						base_model=lowerCamelCase)
      for src, dest in rename_keys:
            rename_key(lowerCamelCase							,						lowerCamelCase							,						lowerCamelCase)
      read_in_q_k_v(lowerCamelCase							,						lowerCamelCase							,						lowerCamelCase)

      # load HuggingFace model
      if base_model:
            A_						:  Tuple          =				ViTModel(lowerCamelCase							,						add_pooling_layer=lowerCamelCase).eval()
      else:
            A_						:  Union[str, Any]          =				ViTForImageClassification(lowerCamelCase).eval()
      model.load_state_dict(lowerCamelCase)

      # Check outputs on an image, prepared by ViTImageProcessor
      A_						:  Tuple          =				ViTImageProcessor()
      A_						:  str          =				image_processor(images=prepare_img()							,						return_tensors="""pt""")
      A_						:  List[Any]          =				encoding["""pixel_values"""]
      A_						:  Tuple          =				model(lowerCamelCase)

      if base_model:
            A_						:  str          =				original_model(lowerCamelCase)
            assert torch.allclose(lowerCamelCase							,						outputs.last_hidden_state[:, 0, :]							,						atol=1E-1)
      else:
            A_						:  int          =				original_model(lowerCamelCase)
            assert logits.shape == outputs.logits.shape
            assert torch.allclose(lowerCamelCase							,						outputs.logits							,						atol=1E-3)

      Path(lowerCamelCase).mkdir(exist_ok=lowerCamelCase)
      print(F'Saving model {model_name} to {pytorch_dump_folder_path}')
      model.save_pretrained(lowerCamelCase)
      print(F'Saving image processor to {pytorch_dump_folder_path}')
      image_processor.save_pretrained(lowerCamelCase)


if __name__ == "__main__":
     __magic_name__			=      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)
     __magic_name__			=      parser.parse_args()
     convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)




'''simple docstring'''


import copy
import os
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union


if TYPE_CHECKING:
     from ...processing_utils import ProcessorMixin
     from ...utils import TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__magic_name__			=      logging.get_logger(__name__)

__magic_name__			=      {
    'google/owlvit-base-patch32': 'https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json',
    'google/owlvit-base-patch16': 'https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json',
    'google/owlvit-large-patch14': 'https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json',
}



class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  a_  					=							"""owlvit_text_model"""






  def __init__(							self :       Union[str, Any]	,_a :       Any=49408	,_a :       Any=512	,_a :       Tuple=2048	,_a :       Dict=12	,_a :       Optional[int]=8	,_a :       Tuple=16	,_a :       Tuple="quick_gelu"	,_a :       Optional[Any]=1e-5	,_a :       List[Any]=0.0	,_a :       Optional[int]=0.02	,_a :       Dict=1.0	,_a :       Dict=0	,_a :       Any=49406	,_a :       Tuple=49407	,**_a :       List[Any]	,):

        '''simple docstring'''




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

        A_						:  Tuple          =				vocab_size
        A_						:  int          =				hidden_size
        A_						:  Optional[int]          =				intermediate_size
        A_						:  Optional[int]          =				num_hidden_layers
        A_						:  Union[str, Any]          =				num_attention_heads
        A_						:  int          =				max_position_embeddings
        A_						:  str          =				hidden_act
        A_						:  Union[str, Any]          =				layer_norm_eps
        A_						:  Tuple          =				attention_dropout
        A_						:  Union[str, Any]          =				initializer_range
        A_						:  List[Any]          =				initializer_factor






  @classmethod
  def        _a							(							cls :       List[str]	,_a :       Union[str, os.PathLike]	,**_a :       str ):

        '''simple docstring'''




        cls._set_token_in_kwargs(_a )

        A_   ,					A_						:  int          =				cls.get_config_dict(_a	,**_a )

        # get the text config dict if we are loading from OwlViTConfig
        if config_dict.get("""model_type""" ) == "owlvit":
              A_						:  Union[str, Any]          =				config_dict["""text_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(_a	,**_a )







class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  a_  					=							"""owlvit_vision_model"""






  def __init__(							self :       List[Any]	,_a :       Optional[Any]=768	,_a :       Tuple=3072	,_a :       Dict=12	,_a :       int=12	,_a :       Dict=3	,_a :       Tuple=768	,_a :       int=32	,_a :       int="quick_gelu"	,_a :       List[Any]=1e-5	,_a :       Tuple=0.0	,_a :       List[Any]=0.02	,_a :       str=1.0	,**_a :       int	,):

        '''simple docstring'''




        super().__init__(**_a )

        A_						:  List[str]          =				hidden_size
        A_						:  Union[str, Any]          =				intermediate_size
        A_						:  Union[str, Any]          =				num_hidden_layers
        A_						:  Optional[Any]          =				num_attention_heads
        A_						:  int          =				num_channels
        A_						:  str          =				image_size
        A_						:  List[Any]          =				patch_size
        A_						:  int          =				hidden_act
        A_						:  List[Any]          =				layer_norm_eps
        A_						:  List[str]          =				attention_dropout
        A_						:  str          =				initializer_range
        A_						:  str          =				initializer_factor






  @classmethod
  def        _a							(							cls :       List[Any]	,_a :       Union[str, os.PathLike]	,**_a :       str ):

        '''simple docstring'''




        cls._set_token_in_kwargs(_a )

        A_   ,					A_						:  Optional[int]          =				cls.get_config_dict(_a	,**_a )

        # get the vision config dict if we are loading from OwlViTConfig
        if config_dict.get("""model_type""" ) == "owlvit":
              A_						:  List[str]          =				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(_a	,**_a )







class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  a_  					=							"""owlvit"""
  a_  					=							True






  def __init__(							self :       Union[str, Any]	,_a :       List[str]=None	,_a :       List[str]=None	,_a :       Dict=512	,_a :       List[Any]=2.6592	,_a :       Optional[Any]=True	,**_a :       Optional[int]	,):

        '''simple docstring'''




        super().__init__(**_a )

        if text_config is None:
              A_						:  List[Any]          =				{}
              logger.info("""text_config is None. Initializing the OwlViTTextConfig with default values.""" )

        if vision_config is None:
              A_						:  Tuple          =				{}
              logger.info("""vision_config is None. initializing the OwlViTVisionConfig with default values.""" )

        A_						:  Dict          =				OwlViTTextConfig(**_a )
        A_						:  Dict          =				OwlViTVisionConfig(**_a )

        A_						:  Any          =				projection_dim
        A_						:  Optional[int]          =				logit_scale_init_value
        A_						:  Optional[int]          =				return_dict
        A_						:  Dict          =				1.0






  @classmethod
  def        _a							(							cls :       Union[str, Any]	,_a :       Union[str, os.PathLike]	,**_a :       Optional[int] ):

        '''simple docstring'''




        cls._set_token_in_kwargs(_a )

        A_   ,					A_						:  List[Any]          =				cls.get_config_dict(_a	,**_a )

        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(_a	,**_a )






  @classmethod
  def        _a							(							cls :       int	,_a :       Dict	,_a :       Dict	,**_a :       List[str] ):

        '''simple docstring'''




        A_						:  str          =				{}
        A_						:  int          =				text_config
        A_						:  Union[str, Any]          =				vision_config

        return cls.from_dict(_a	,**_a )






  def        _a							(							self :       Optional[int] ):

        '''simple docstring'''




        A_						:  Dict          =				copy.deepcopy(self.__dict__ )
        A_						:  str          =				self.text_config.to_dict()
        A_						:  Optional[int]          =				self.vision_config.to_dict()
        A_						:  List[Any]          =				self.__class__.model_type
        return output







class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  @property
  def        _a							(							self :       int ):

        '''simple docstring'''




        return OrderedDict(
            [
                ("""input_ids""", {0: """batch""", 1: """sequence"""}),
                ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
                ("""attention_mask""", {0: """batch""", 1: """sequence"""}),
            ] )






  @property
  def        _a							(							self :       str ):

        '''simple docstring'''




        return OrderedDict(
            [
                ("""logits_per_image""", {0: """batch"""}),
                ("""logits_per_text""", {0: """batch"""}),
                ("""text_embeds""", {0: """batch"""}),
                ("""image_embeds""", {0: """batch"""}),
            ] )






  @property
  def        _a							(							self :       Optional[Any] ):

        '''simple docstring'''




        return 1e-4






  def        _a							(							self :       int	,_a :       "ProcessorMixin"	,_a :       int = -1	,_a :       int = -1	,_a :       Optional["TensorType"] = None	,):

        '''simple docstring'''




        A_						:  Any          =				super().generate_dummy_inputs(
            processor.tokenizer	,batch_size=_a	,seq_length=_a	,framework=_a )
        A_						:  Any          =				super().generate_dummy_inputs(
            processor.image_processor	,batch_size=_a	,framework=_a )
        return {**text_input_dict, **image_input_dict}






  @property
  def        _a							(							self :       Optional[Any] ):

        '''simple docstring'''




        return 14
