


"""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()
_lowerCAmelCase							:    str					   =	logging.get_logger(__name__)







def        lowerCamelCase_(		_lowerCamelCase			,		_lowerCamelCase=False       )    ->     List[Any]:
   '''simple docstring'''





   _lowerCamelCase   :				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"
      _lowerCamelCase   :				List[str]							=     [(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			,		_lowerCamelCase			,		_lowerCamelCase=False       )    ->     Optional[int]:
   '''simple docstring'''





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







def        lowerCamelCase_(		_lowerCamelCase       )    ->     int:
   '''simple docstring'''





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







def        lowerCamelCase_(		_lowerCamelCase			,		_lowerCamelCase			,		_lowerCamelCase       )    ->     Any:
   '''simple docstring'''





   _lowerCamelCase   :				Any							=     dct.pop(_lowerCamelCase       )
   _lowerCamelCase   :				Dict							=     val







def        lowerCamelCase_(		)    ->     Optional[int]:
   '''simple docstring'''





   _lowerCamelCase   :				Optional[int]							=     "http://images.cocodataset.org/val2017/000000039769.jpg"
   _lowerCamelCase   :				List[str]							=     Image.open(requests.get(_lowerCamelCase			,		stream=_lowerCamelCase       ).raw       )
   return im







@torch.no_grad()
def        lowerCamelCase_(		_lowerCamelCase			,		_lowerCamelCase			,		_lowerCamelCase=True       )    ->     str:
   '''simple docstring'''





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

   # load original model from torch hub
   _lowerCamelCase   :				Union[str, Any]							=     torch.hub.load("facebookresearch/dino:main"			,		_lowerCamelCase       )
   original_model.eval()

   # load state_dict of original model, remove and rename some keys
   _lowerCamelCase   :				List[str]							=     original_model.state_dict()
   if base_model:
      remove_classification_head_(_lowerCamelCase       )
   _lowerCamelCase   :				Tuple							=     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:
      _lowerCamelCase   :				Optional[Any]							=     ViTModel(_lowerCamelCase			,		add_pooling_layer=_lowerCamelCase       ).eval()
   else:
      _lowerCamelCase   :				Union[str, Any]							=     ViTForImageClassification(_lowerCamelCase       ).eval()
   model.load_state_dict(_lowerCamelCase       )

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

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


import gc
import unittest

import numpy as np
import torch

from diffusers import StableDiffusionKDiffusionPipeline
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()






@slow
@require_torch_gpu
class _UpperCamelCase				(				unittest.TestCase ):
			'''simple docstring'''







			def 				__UpperCamelCase			(      self				:			Dict						)				->							Tuple:

				"""simple docstring"""

				super().tearDown()
				gc.collect()
				torch.cuda.empty_cache()
			def 				__UpperCamelCase			(      self				:			Optional[int]						)				->							int:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Optional[Any]					  =							StableDiffusionKDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4"						)
				SCREAMING_SNAKE_CASE :   str					  =							sd_pipe.to(a						)
				sd_pipe.set_progress_bar_config(disable=a						)

				sd_pipe.set_scheduler("sample_euler"						)

				SCREAMING_SNAKE_CASE :   Optional[int]					  =							"A painting of a squirrel eating a burger"
				SCREAMING_SNAKE_CASE :   Any					  =							torch.manual_seed(0						)
				SCREAMING_SNAKE_CASE :   List[Any]					  =							sd_pipe([prompt]   ,   generator=a   ,   guidance_scale=9.0   ,   num_inference_steps=20   ,   output_type="np"						)

				SCREAMING_SNAKE_CASE :   Tuple					  =							output.images

				SCREAMING_SNAKE_CASE :   Any					  =							image[0, -3:, -3:, -1]

				assert image.shape == (1, 512, 512, 3)
				SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							np.array([0.0447, 0.0492, 0.0468, 0.0408, 0.0383, 0.0408, 0.0354, 0.0380, 0.0339]						)

				assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2
			def 				__UpperCamelCase			(      self				:			List[Any]						)				->							Optional[int]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   int					  =							StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base"						)
				SCREAMING_SNAKE_CASE :   Tuple					  =							sd_pipe.to(a						)
				sd_pipe.set_progress_bar_config(disable=a						)

				sd_pipe.set_scheduler("sample_euler"						)

				SCREAMING_SNAKE_CASE :   List[str]					  =							"A painting of a squirrel eating a burger"
				SCREAMING_SNAKE_CASE :   List[str]					  =							torch.manual_seed(0						)
				SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							sd_pipe([prompt]   ,   generator=a   ,   guidance_scale=9.0   ,   num_inference_steps=20   ,   output_type="np"						)

				SCREAMING_SNAKE_CASE :   List[Any]					  =							output.images

				SCREAMING_SNAKE_CASE :   Tuple					  =							image[0, -3:, -3:, -1]

				assert image.shape == (1, 512, 512, 3)
				SCREAMING_SNAKE_CASE :   int					  =							np.array([0.1237, 0.1320, 0.1438, 0.1359, 0.1390, 0.1132, 0.1277, 0.1175, 0.1112]						)

				assert np.abs(image_slice.flatten() - expected_slice						).max() < 5e-1






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

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Dict					  =							StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base"						)
				SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							sd_pipe.to(a						)
				sd_pipe.set_progress_bar_config(disable=a						)

				sd_pipe.set_scheduler("sample_dpmpp_2m"						)

				SCREAMING_SNAKE_CASE :   str					  =							"A painting of a squirrel eating a burger"
				SCREAMING_SNAKE_CASE :   Any					  =							torch.manual_seed(0						)
				SCREAMING_SNAKE_CASE :   str					  =							sd_pipe(
				    [prompt]   ,   generator=a   ,   guidance_scale=7.5   ,   num_inference_steps=15   ,   output_type="np"   ,   use_karras_sigmas=a   ,   )

				SCREAMING_SNAKE_CASE :   str					  =							output.images

				SCREAMING_SNAKE_CASE :   Optional[int]					  =							image[0, -3:, -3:, -1]

				assert image.shape == (1, 512, 512, 3)
				SCREAMING_SNAKE_CASE :   int					  =							np.array(
				    [0.1138_1689, 0.1211_2921, 0.138_9457, 0.1254_9606, 0.124_4964, 0.1083_1517, 0.1156_2866, 0.1086_7816, 0.1049_9048]						)

				assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2