




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


def 					UpperCamelCase_(     snake_case							:	List[str]							,    snake_case							:	List[str]=False					):

							'''simple docstring'''






							snake_case_      =				[]
							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"
														snake_case_      =				[(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_(     snake_case							:	Tuple							,    snake_case							:	str							,    snake_case							:	Any=False					):

							'''simple docstring'''






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


def 					UpperCamelCase_(     snake_case							:	Union[str, Any]					):

							'''simple docstring'''






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


def 					UpperCamelCase_(     snake_case							:	Union[str, Any]							,    snake_case							:	Dict							,    snake_case							:	Optional[Any]					):

							'''simple docstring'''






							snake_case_      =				dct.pop(snake_case					)
							snake_case_      =				val


def 					UpperCamelCase_(     ):

							'''simple docstring'''






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


@torch.no_grad()
def 					UpperCamelCase_(     snake_case							:	Dict							,    snake_case							:	Optional[int]							,    snake_case							:	Union[str, Any]=True					):

							'''simple docstring'''






							snake_case_      =				ViTConfig()
							# patch_size
							if model_name[-1] == "8":
														snake_case_      =				8
							# set labels if required
							if not base_model:
														snake_case_      =				1_0_0_0
														snake_case_      =				"huggingface/label-files"
														snake_case_      =				"imagenet-1k-id2label.json"
														snake_case_      =				json.load(open(hf_hub_download(snake_case							,    snake_case							,    repo_type="dataset"					)							,    "r"					)					)
														snake_case_      =				{int(snake_case					): v for k, v in idalabel.items()}
														snake_case_      =				idalabel
														snake_case_      =				{v: k for k, v in idalabel.items()}
							# size of the architecture
							if model_name in ["dino_vits8", "dino_vits16"]:
														snake_case_      =				3_8_4
														snake_case_      =				1_5_3_6
														snake_case_      =				1_2
														snake_case_      =				6

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

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

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

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

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

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


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






'''simple docstring'''





import gc
import random
import unittest

import torch

from diffusers import (
    IFImgaImgPipeline,
    IFImgaImgSuperResolutionPipeline,
    IFInpaintingPipeline,
    IFInpaintingSuperResolutionPipeline,
    IFPipeline,
    IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
from . import IFPipelineTesterMixin




@skip_mps
class 			_snake_case		(     lowercase_						,						lowercase_						,						unittest.TestCase							):
			lowerCAmelCase_					:				List[str]							=   IFPipeline
			lowerCAmelCase_					:				int							=   TEXT_TO_IMAGE_PARAMS - {"width", "height", "latents"}
			lowerCAmelCase_					:				Optional[int]							=   TEXT_TO_IMAGE_BATCH_PARAMS
			lowerCAmelCase_					:				List[Any]							=   PipelineTesterMixin.required_optional_params - {"latents"}




			def        lowerCAmelCase__    ( self							)    ->    Optional[Any]:

										'''simple docstring'''




										return self._get_dummy_components()




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__=0							)    ->    str:

										'''simple docstring'''




										if str(a__							).startswith("mps"							):
																	snake_case_      =				torch.manual_seed(a__							)
										else:
																	snake_case_      =				torch.Generator(device=a__							).manual_seed(a__							)

										snake_case_      =				{
										    "prompt": "A painting of a squirrel eating a burger",
										    "generator": generator,
										    "num_inference_steps": 2,
										    "output_type": "numpy",
										}

										return inputs




			def        lowerCAmelCase__    ( self							)    ->    List[str]:

										'''simple docstring'''




										self._test_save_load_optional_components()




			@unittest.skipIf(torch_device != "cuda"    ,							reason="float16 requires CUDA"							)
			def        lowerCAmelCase__    ( self							)    ->    str:

										'''simple docstring'''




										super().test_save_load_floataa(expected_max_diff=1e-1							)




			def        lowerCAmelCase__    ( self							)    ->    List[Any]:

										'''simple docstring'''




										self._test_attention_slicing_forward_pass(expected_max_diff=1e-2							)




			def        lowerCAmelCase__    ( self							)    ->    int:

										'''simple docstring'''




										self._test_save_load_local()




			def        lowerCAmelCase__    ( self							)    ->    int:

										'''simple docstring'''




										self._test_inference_batch_single_identical(
										    expected_max_diff=1e-2    ,							)




			@unittest.skipIf(
			    torch_device != "cuda" or not is_xformers_available()    ,							reason="XFormers attention is only available with CUDA and `xformers` installed"    ,							)
			def        lowerCAmelCase__    ( self							)    ->    List[str]:

										'''simple docstring'''




										self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3							)




@slow
@require_torch_gpu
class 			_snake_case		(     unittest.TestCase							):




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

										'''simple docstring'''




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




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

										'''simple docstring'''




										snake_case_      =				IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0"    ,							variant="fp16"    ,							torch_dtype=torch.floataa							)

										snake_case_      =				IFSuperResolutionPipeline.from_pretrained(
										    "DeepFloyd/IF-II-L-v1.0"    ,							variant="fp16"    ,							torch_dtype=torch.floataa    ,							text_encoder=a__    ,							tokenizer=a__							)

										# pre compute text embeddings and remove T5 to save memory

										pipe_a.text_encoder.to("cuda"							)

										snake_case_ ,				snake_case_      =				pipe_a.encode_prompt("anime turtle"    ,							device="cuda"							)

										del pipe_a.tokenizer
										del pipe_a.text_encoder
										gc.collect()

										snake_case_      =				None
										snake_case_      =				None

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if(a__    ,							a__    ,							a__    ,							a__							)

										pipe_a.remove_all_hooks()
										pipe_a.remove_all_hooks()

										# img2img

										snake_case_      =				IFImgaImgPipeline(**pipe_a.components							)
										snake_case_      =				IFImgaImgSuperResolutionPipeline(**pipe_a.components							)

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if_imgaimg(a__    ,							a__    ,							a__    ,							a__							)

										pipe_a.remove_all_hooks()
										pipe_a.remove_all_hooks()

										# inpainting

										snake_case_      =				IFInpaintingPipeline(**pipe_a.components							)
										snake_case_      =				IFInpaintingSuperResolutionPipeline(**pipe_a.components							)

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if_inpainting(a__    ,							a__    ,							a__    ,							a__							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    Dict:

										'''simple docstring'''




										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)
										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							num_inference_steps=2    ,							generator=a__    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (64, 64, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 13 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)

										# pipeline 2

										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							generator=a__    ,							num_inference_steps=2    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (256, 256, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    Dict:

										'''simple docstring'''




										_start_torch_memory_measurement()

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							num_inference_steps=2    ,							generator=a__    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (64, 64, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 10 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)

										# pipeline 2

										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				floats_tensor((1, 3, 256, 256)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							original_image=a__    ,							generator=a__    ,							num_inference_steps=2    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (256, 256, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    str:

										'''simple docstring'''




										_start_torch_memory_measurement()

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(1							)							).to(a__							)

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)
										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							mask_image=a__    ,							num_inference_steps=2    ,							generator=a__    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (64, 64, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 10 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)

										# pipeline 2

										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 256, 256)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 256, 256)    ,							rng=random.Random(1							)							).to(a__							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							mask_image=a__    ,							original_image=a__    ,							generator=a__    ,							num_inference_steps=2    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (256, 256, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)


def 					UpperCamelCase_(     ):

							'''simple docstring'''






							torch.cuda.empty_cache()
							torch.cuda.reset_max_memory_allocated()
							torch.cuda.reset_peak_memory_stats()




