





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




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     List[Any]:
  lowercase__			    =						["""head.weight""", """head.bias"""]
  for k in ignore_keys:
    state_dict.pop(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     int:
  lowercase__			    =						dct.pop(_SCREAMING_SNAKE_CASE	)
  lowercase__			    =						val




def     __UpperCamelCase						()       ->     Optional[int]:
  lowercase__			    =						"""http://images.cocodataset.org/val2017/000000039769.jpg"""
  lowercase__			    =						Image.open(requests.get(_SCREAMING_SNAKE_CASE	,		stream=_SCREAMING_SNAKE_CASE	).raw	)
  return im




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

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

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

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

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

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

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


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)









import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


lowercase_					     =	False
class        SCREAMING_SNAKE_CASE     (unittest.TestCase   ):
   pass






@nightly
@require_torch_gpu
class        SCREAMING_SNAKE_CASE     (unittest.TestCase   ):


   def  SCREAMING_SNAKE_CASE_							(					self    :       str )->     Optional[int]:





     """simple docstring"""







     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any] )->     Union[str, Any]:





     """simple docstring"""







     lowercase__			    =						VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion'    ,  torch_dtype=torch.floataa )
     pipe.to(a )
     pipe.set_progress_bar_config(disable=a )

     lowercase__			    =						load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' )

     lowercase__			    =						torch.manual_seed(0 )
     lowercase__			    =						pipe.dual_guided(
         prompt='first prompt'    ,  image=a    ,  text_to_image_strength=0.75    ,  generator=a    ,  guidance_scale=7.5    ,  num_inference_steps=2    ,  output_type='numpy'    ,  ).images

     with tempfile.TemporaryDirectory() as tmpdirname:
       pipe.save_pretrained(a )
       lowercase__			    =						VersatileDiffusionPipeline.from_pretrained(a    ,  torch_dtype=torch.floataa )
     pipe.to(a )
     pipe.set_progress_bar_config(disable=a )

     lowercase__			    =						generator.manual_seed(0 )
     lowercase__			    =						pipe.dual_guided(
         prompt='first prompt'    ,  image=a    ,  text_to_image_strength=0.75    ,  generator=a    ,  guidance_scale=7.5    ,  num_inference_steps=2    ,  output_type='numpy'    ,  ).images

     assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass"


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     List[str]:





     """simple docstring"""







     lowercase__			    =						VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion'    ,  torch_dtype=torch.floataa )
     pipe.to(a )
     pipe.set_progress_bar_config(disable=a )

     lowercase__			    =						'cyberpunk 2077'
     lowercase__			    =						load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' )
     lowercase__			    =						torch.manual_seed(0 )
     lowercase__			    =						pipe.dual_guided(
         prompt=a    ,  image=a    ,  text_to_image_strength=0.75    ,  generator=a    ,  guidance_scale=7.5    ,  num_inference_steps=50    ,  output_type='numpy'    ,  ).images

     lowercase__			    =						image[0, 253:256, 253:256, -1]

     assert image.shape == (1, 512, 512, 3)
     lowercase__			    =						np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001] )

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

     lowercase__			    =						'A painting of a squirrel eating a burger '
     lowercase__			    =						torch.manual_seed(0 )
     lowercase__			    =						pipe.text_to_image(
         prompt=a    ,  generator=a    ,  guidance_scale=7.5    ,  num_inference_steps=50    ,  output_type='numpy' ).images

     lowercase__			    =						image[0, 253:256, 253:256, -1]

     assert image.shape == (1, 512, 512, 3)
     lowercase__			    =						np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] )

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

     lowercase__			    =						pipe.image_variation(a    ,  generator=a    ,  output_type='numpy' ).images

     lowercase__			    =						image[0, 253:256, 253:256, -1]

     assert image.shape == (1, 512, 512, 3)
     lowercase__			    =						np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456] )

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


