
"""simple docstring"""





import argparse

import gdown
import numpy as np
import torch
from huggingface_hub import hf_hub_download

from transformers import (
    CLIPTokenizer,
    CLIPTokenizerFast,
    VideoMAEImageProcessor,
    XCLIPConfig,
    XCLIPModel,
    XCLIPProcessor,
    XCLIPTextConfig,
    XCLIPVisionConfig,
)



def 						_lowerCAmelCase				(				UpperCamelCase_  ,				UpperCamelCase_				):
		__SCREAMING_SNAKE_CASE            = XCLIPTextConfig()

		# derive patch size from model name
		__SCREAMING_SNAKE_CASE            = model_name.find("""patch"""				)
		__SCREAMING_SNAKE_CASE            = int(model_name[start_idx + len("""patch"""				) : start_idx + len("""patch"""				) + 2]				)
		__SCREAMING_SNAKE_CASE            = XCLIPVisionConfig(patch_size=UpperCamelCase_  ,				num_frames=UpperCamelCase_				)

		if "large" in model_name:
				__SCREAMING_SNAKE_CASE            = 768
				__SCREAMING_SNAKE_CASE            = 3072
				__SCREAMING_SNAKE_CASE            = 12

				__SCREAMING_SNAKE_CASE            = 1024
				__SCREAMING_SNAKE_CASE            = 4096
				__SCREAMING_SNAKE_CASE            = 16
				__SCREAMING_SNAKE_CASE            = 24
				__SCREAMING_SNAKE_CASE            = 768
				__SCREAMING_SNAKE_CASE            = 3072

		if model_name == "xclip-large-patch14-16-frames":
				__SCREAMING_SNAKE_CASE            = 336

		__SCREAMING_SNAKE_CASE            = XCLIPConfig.from_text_vision_configs(UpperCamelCase_  ,				UpperCamelCase_				)

		if "large" in model_name:
				__SCREAMING_SNAKE_CASE            = 768

		return config



def 						_lowerCAmelCase				(				UpperCamelCase_				):
		# text encoder
		if name == "token_embedding.weight":
				__SCREAMING_SNAKE_CASE            = name.replace("""token_embedding.weight"""  ,				"""text_model.embeddings.token_embedding.weight"""				)
		if name == "positional_embedding":
				__SCREAMING_SNAKE_CASE            = name.replace("""positional_embedding"""  ,				"""text_model.embeddings.position_embedding.weight"""				)
		if "ln_1" in name:
				__SCREAMING_SNAKE_CASE            = name.replace("""ln_1"""  ,				"""layer_norm1"""				)
		if "ln_2" in name:
				__SCREAMING_SNAKE_CASE            = name.replace("""ln_2"""  ,				"""layer_norm2"""				)
		if "c_fc" in name:
				__SCREAMING_SNAKE_CASE            = name.replace("""c_fc"""  ,				"""fc1"""				)
		if "c_proj" in name:
				__SCREAMING_SNAKE_CASE            = name.replace("""c_proj"""  ,				"""fc2"""				)
		if name.startswith("""transformer.resblocks"""				):
				__SCREAMING_SNAKE_CASE            = name.replace("""transformer.resblocks"""  ,				"""text_model.encoder.layers"""				)
		if "attn.out_proj" in name and "message" not in name:
				__SCREAMING_SNAKE_CASE            = name.replace("""attn.out_proj"""  ,				"""self_attn.out_proj"""				)
		if "ln_final" in name:
				__SCREAMING_SNAKE_CASE            = name.replace("""ln_final"""  ,				"""text_model.final_layer_norm"""				)
		# visual encoder
		if name == "visual.class_embedding":
				__SCREAMING_SNAKE_CASE            = name.replace("""visual.class_embedding"""  ,				"""vision_model.embeddings.class_embedding"""				)
		if name == "visual.positional_embedding":
				__SCREAMING_SNAKE_CASE            = name.replace("""visual.positional_embedding"""  ,				"""vision_model.embeddings.position_embedding.weight"""				)
		if name.startswith("""visual.transformer.resblocks"""				):
				__SCREAMING_SNAKE_CASE            = name.replace("""visual.transformer.resblocks"""  ,				"""vision_model.encoder.layers"""				)
		if "visual.conv1" in name:
				__SCREAMING_SNAKE_CASE            = name.replace("""visual.conv1"""  ,				"""vision_model.embeddings.patch_embedding"""				)
		if "visual.ln_pre" in name:
				__SCREAMING_SNAKE_CASE            = name.replace("""visual.ln_pre"""  ,				"""vision_model.pre_layernorm"""				)
		if "visual.ln_post" in name:
				__SCREAMING_SNAKE_CASE            = name.replace("""visual.ln_post"""  ,				"""vision_model.post_layernorm"""				)
		if "visual.proj" in name:
				__SCREAMING_SNAKE_CASE            = name.replace("""visual.proj"""  ,				"""visual_projection.weight"""				)
		if "text_projection" in name:
				__SCREAMING_SNAKE_CASE            = name.replace("""text_projection"""  ,				"""text_projection.weight"""				)
		# things on top
		if "prompts_visual_proj" in name:
				__SCREAMING_SNAKE_CASE            = name.replace("""prompts_visual_proj"""  ,				"""prompts_visual_projection"""				)
		if "prompts_visual_ln" in name:
				__SCREAMING_SNAKE_CASE            = name.replace("""prompts_visual_ln"""  ,				"""prompts_visual_layernorm"""				)
		# mit
		if name == "mit.positional_embedding":
				__SCREAMING_SNAKE_CASE            = name.replace("""positional"""  ,				"""position"""				)
		if name.startswith("""mit.resblocks"""				):
				__SCREAMING_SNAKE_CASE            = name.replace("""mit.resblocks"""  ,				"""mit.encoder.layers"""				)
		# prompts generator
		if name.startswith("""prompts_generator.norm"""				):
				__SCREAMING_SNAKE_CASE            = name.replace("""prompts_generator.norm"""  ,				"""prompts_generator.layernorm"""				)

		return name



def 						_lowerCAmelCase				(				UpperCamelCase_  ,				UpperCamelCase_				):
		for key in orig_state_dict.copy().keys():
				__SCREAMING_SNAKE_CASE            = orig_state_dict.pop(UpperCamelCase_				)

				if "attn.in_proj" in key:
						__SCREAMING_SNAKE_CASE            = key.split("""."""				)
						if key.startswith("""visual"""				):
								__SCREAMING_SNAKE_CASE            = key_split[3]
								__SCREAMING_SNAKE_CASE            = config.vision_config.hidden_size
								if "message_attn" in key:
										if "weight" in key:
												__SCREAMING_SNAKE_CASE            = val[
												    :dim, :
												]
												__SCREAMING_SNAKE_CASE            = val[
												    dim : dim * 2, :
												]
												__SCREAMING_SNAKE_CASE            = val[
												    -dim:, :
												]
										else:
												__SCREAMING_SNAKE_CASE            = val[
												    :dim
												]
												__SCREAMING_SNAKE_CASE            = val[
												    dim : dim * 2
												]
												__SCREAMING_SNAKE_CASE            = val[
												    -dim:
												]
								else:
										if "weight" in key:
												__SCREAMING_SNAKE_CASE            = val[
												    :dim, :
												]
												__SCREAMING_SNAKE_CASE            = val[
												    dim : dim * 2, :
												]
												__SCREAMING_SNAKE_CASE            = val[
												    -dim:, :
												]
										else:
												__SCREAMING_SNAKE_CASE            = val[:dim]
												__SCREAMING_SNAKE_CASE            = val[
												    dim : dim * 2
												]
												__SCREAMING_SNAKE_CASE            = val[-dim:]
						elif key.startswith("""mit"""				):
								__SCREAMING_SNAKE_CASE            = key_split[2]
								__SCREAMING_SNAKE_CASE            = config.vision_config.mit_hidden_size
								if "weight" in key:
										__SCREAMING_SNAKE_CASE            = val[:dim, :]
										__SCREAMING_SNAKE_CASE            = val[dim : dim * 2, :]
										__SCREAMING_SNAKE_CASE            = val[-dim:, :]
								else:
										__SCREAMING_SNAKE_CASE            = val[:dim]
										__SCREAMING_SNAKE_CASE            = val[dim : dim * 2]
										__SCREAMING_SNAKE_CASE            = val[-dim:]
						else:
								__SCREAMING_SNAKE_CASE            = key_split[2]
								__SCREAMING_SNAKE_CASE            = config.text_config.hidden_size
								if "weight" in key:
										__SCREAMING_SNAKE_CASE            = val[:dim, :]
										__SCREAMING_SNAKE_CASE            = val[
										    dim : dim * 2, :
										]
										__SCREAMING_SNAKE_CASE            = val[-dim:, :]
								else:
										__SCREAMING_SNAKE_CASE            = val[:dim]
										__SCREAMING_SNAKE_CASE            = val[
										    dim : dim * 2
										]
										__SCREAMING_SNAKE_CASE            = val[-dim:]
				else:
						__SCREAMING_SNAKE_CASE            = rename_key(UpperCamelCase_				)
						if new_key_name in ["visual_projection.weight", "text_projection.weight"]:
								__SCREAMING_SNAKE_CASE            = val.T
						__SCREAMING_SNAKE_CASE            = val

		return orig_state_dict



def 						_lowerCAmelCase				(				UpperCamelCase_				):
		if num_frames == 8:
				__SCREAMING_SNAKE_CASE            = """eating_spaghetti_8_frames.npy"""
		elif num_frames == 16:
				__SCREAMING_SNAKE_CASE            = """eating_spaghetti.npy"""
		elif num_frames == 32:
				__SCREAMING_SNAKE_CASE            = """eating_spaghetti_32_frames.npy"""
		__SCREAMING_SNAKE_CASE            = hf_hub_download(
		    repo_id="""hf-internal-testing/spaghetti-video"""  ,				filename=UpperCamelCase_  ,				repo_type="""dataset"""  ,				)
		__SCREAMING_SNAKE_CASE            = np.load(UpperCamelCase_				)
		return list(UpperCamelCase_				)



def 						_lowerCAmelCase				(				UpperCamelCase_  ,				UpperCamelCase_=None  ,				UpperCamelCase_=False				):
		__SCREAMING_SNAKE_CASE            = {
		    # fully supervised kinetics-400 checkpoints
		    """xclip-base-patch32""": """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth""",
		    """xclip-base-patch32-16-frames""": (
		        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth"""
		    ),
		    """xclip-base-patch16""": """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth""",
		    """xclip-base-patch16-16-frames""": (
		        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth"""
		    ),
		    """xclip-large-patch14""": """https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb""",
		    """xclip-large-patch14-16-frames""": """https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f""",
		    # fully supervised kinetics-600 checkpoints
		    """xclip-base-patch16-kinetics-600""": (
		        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth"""
		    ),
		    """xclip-base-patch16-kinetics-600-16-frames""": (
		        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth"""
		    ),
		    """xclip-large-patch14-kinetics-600""": """https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be""",
		    # few shot
		    """xclip-base-patch16-hmdb-2-shot""": (
		        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth"""
		    ),
		    """xclip-base-patch16-hmdb-4-shot""": (
		        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth"""
		    ),
		    """xclip-base-patch16-hmdb-8-shot""": (
		        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth"""
		    ),
		    """xclip-base-patch16-hmdb-16-shot""": (
		        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth"""
		    ),
		    """xclip-base-patch16-ucf-2-shot""": (
		        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth"""
		    ),
		    """xclip-base-patch16-ucf-4-shot""": (
		        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth"""
		    ),
		    """xclip-base-patch16-ucf-8-shot""": (
		        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth"""
		    ),
		    """xclip-base-patch16-ucf-16-shot""": (
		        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth"""
		    ),
		    # zero shot
		    """xclip-base-patch16-zero-shot""": """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth""",
		}

		__SCREAMING_SNAKE_CASE            = model_to_url[model_name]
		__SCREAMING_SNAKE_CASE            = 8
		if "16-frames" in model_name:
				__SCREAMING_SNAKE_CASE            = 16
		elif "shot" in model_name:
				__SCREAMING_SNAKE_CASE            = 32

		__SCREAMING_SNAKE_CASE            = get_xclip_config(UpperCamelCase_  ,				UpperCamelCase_				)
		__SCREAMING_SNAKE_CASE            = XCLIPModel(UpperCamelCase_				)
		model.eval()

		if "drive" in checkpoint_url:
				__SCREAMING_SNAKE_CASE            = """pytorch_model.bin"""
				gdown.cached_download(UpperCamelCase_  ,				UpperCamelCase_  ,				quiet=UpperCamelCase_				)
				__SCREAMING_SNAKE_CASE            = torch.load(UpperCamelCase_  ,				map_location="""cpu"""				)["""model"""]
		else:
				__SCREAMING_SNAKE_CASE            = torch.hub.load_state_dict_from_url(UpperCamelCase_				)["""model"""]

		__SCREAMING_SNAKE_CASE            = convert_state_dict(UpperCamelCase_  ,				UpperCamelCase_				)

		__SCREAMING_SNAKE_CASE            = XCLIPModel(UpperCamelCase_				)
		__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = model.load_state_dict(UpperCamelCase_  ,				strict=UpperCamelCase_				)
		assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"]
		model.eval()

		__SCREAMING_SNAKE_CASE            = 336 if model_name == """xclip-large-patch14-16-frames""" else 224
		__SCREAMING_SNAKE_CASE            = VideoMAEImageProcessor(size=UpperCamelCase_				)
		__SCREAMING_SNAKE_CASE            = CLIPTokenizer.from_pretrained("""openai/clip-vit-base-patch32"""				)
		__SCREAMING_SNAKE_CASE            = CLIPTokenizerFast.from_pretrained("""openai/clip-vit-base-patch32"""				)
		__SCREAMING_SNAKE_CASE            = XCLIPProcessor(image_processor=UpperCamelCase_  ,				tokenizer=UpperCamelCase_				)

		__SCREAMING_SNAKE_CASE            = prepare_video(UpperCamelCase_				)
		__SCREAMING_SNAKE_CASE            = processor(
		    text=["""playing sports""", """eating spaghetti""", """go shopping"""]  ,				videos=UpperCamelCase_  ,				return_tensors="""pt"""  ,				padding=UpperCamelCase_				)

		print("""Shape of pixel values:"""  ,				inputs.pixel_values.shape				)

		with torch.no_grad():
				__SCREAMING_SNAKE_CASE            = model(**UpperCamelCase_				)

		# Verify outputs
		__SCREAMING_SNAKE_CASE            = outputs.logits_per_video
		__SCREAMING_SNAKE_CASE            = logits_per_video.softmax(dim=1				)
		print("""Probs:"""  ,				UpperCamelCase_				)
		# kinetics-400
		if model_name == "xclip-base-patch32":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[0.0_019, 0.9_951, 0.0_030]]				)
		elif model_name == "xclip-base-patch32-16-frames":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[7.0999e-04, 9.9883e-01, 4.5580e-04]]				)
		elif model_name == "xclip-base-patch16":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[0.0_083, 0.9_681, 0.0_236]]				)
		elif model_name == "xclip-base-patch16-16-frames":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[7.6937e-04, 9.9728e-01, 1.9473e-03]]				)
		elif model_name == "xclip-large-patch14":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[0.0_062, 0.9_864, 0.0_075]]				)
		elif model_name == "xclip-large-patch14-16-frames":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[3.3877e-04, 9.9937e-01, 2.8888e-04]]				)
		# kinetics-600
		elif model_name == "xclip-base-patch16-kinetics-600":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[0.0_555, 0.8_914, 0.0_531]]				)
		elif model_name == "xclip-base-patch16-kinetics-600-16-frames":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[3.8554e-04, 9.9929e-01, 3.2754e-04]]				)
		elif model_name == "xclip-large-patch14-kinetics-600":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[0.0_036, 0.9_920, 0.0_045]]				)
		# few shot
		elif model_name == "xclip-base-patch16-hmdb-2-shot":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[7.1890e-06, 9.9994e-01, 5.6559e-05]]				)
		elif model_name == "xclip-base-patch16-hmdb-4-shot":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[1.0320e-05, 9.9993e-01, 6.2435e-05]]				)
		elif model_name == "xclip-base-patch16-hmdb-8-shot":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[4.1377e-06, 9.9990e-01, 9.8386e-05]]				)
		elif model_name == "xclip-base-patch16-hmdb-16-shot":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[4.1347e-05, 9.9962e-01, 3.3411e-04]]				)
		elif model_name == "xclip-base-patch16-ucf-2-shot":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[8.5857e-05, 9.9928e-01, 6.3291e-04]]				)
		elif model_name == "xclip-base-patch16-ucf-4-shot":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[8.5857e-05, 9.9928e-01, 6.3291e-04]]				)
		elif model_name == "xclip-base-patch16-ucf-8-shot":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[0.0_027, 0.9_904, 0.0_070]]				)
		elif model_name == "xclip-base-patch16-ucf-16-shot":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[9.8219e-04, 9.9593e-01, 3.0863e-03]]				)
		# zero shot
		elif model_name == "xclip-base-patch16-zero-shot":
				__SCREAMING_SNAKE_CASE            = torch.tensor([[3.5082e-04, 9.9785e-01, 1.7966e-03]]				)
		else:
				raise ValueError(f"Model name {model_name} not supported"				)
		assert torch.allclose(UpperCamelCase_  ,				UpperCamelCase_  ,				atol=1e-3				)
		print("""Looks ok!"""				)

		if pytorch_dump_folder_path is not None:
				print(f"Saving model {model_name} to {pytorch_dump_folder_path}"				)
				model.save_pretrained(UpperCamelCase_				)

		if push_to_hub:
				print("""Pushing model, processor and slow tokenizer files to the hub..."""				)
				model.push_to_hub(UpperCamelCase_  ,				organization="""nielsr"""				)
				processor.push_to_hub(UpperCamelCase_  ,				organization="""nielsr"""				)
				slow_tokenizer.push_to_hub(UpperCamelCase_  ,				organization="""nielsr"""				)


if __name__ == "__main__":
							__magic_name__       =			argparse.ArgumentParser()
							# Required parameters
							parser.add_argument(
							    "--model_name",
							    default="xclip-base-patch32",
							    type=str,
							    help="Name of the model.",
							)
							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 or not to push the converted model to the 🤗 hub."
							)

							__magic_name__       =			parser.parse_args()
							convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)






"""simple docstring"""





import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image

from diffusers import (
    DDIMScheduler,
    KandinskyVaaImgaImgPipeline,
    KandinskyVaaPriorPipeline,
    UNetaDConditionModel,
    VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()
class 						SCREAMING_SNAKE_CASE_ (						__a     ,				unittest.TestCase ):




		"""simple docstring"""





		__lowercase							:  Optional[Any]						   =		KandinskyVaaImgaImgPipeline
		__lowercase							:  str						   =		['''image_embeds''', '''negative_image_embeds''', '''image''']
		__lowercase							:  Dict						   =		[
		    '''image_embeds''',
		    '''negative_image_embeds''',
		    '''image''',
		]
		__lowercase							:  Tuple						   =		[
		    '''generator''',
		    '''height''',
		    '''width''',
		    '''strength''',
		    '''guidance_scale''',
		    '''num_inference_steps''',
		    '''return_dict''',
		    '''guidance_scale''',
		    '''num_images_per_prompt''',
		    '''output_type''',
		    '''return_dict''',
		]
		__lowercase							:  Tuple						   =		False




		@property
		def 	snake_case_     (     self):
				return 3_2




		@property
		def 	snake_case_     (     self):
				return 3_2




		@property
		def 	snake_case_     (     self):
				return self.time_input_dim




		@property
		def 	snake_case_     (     self):
				return self.time_input_dim * 4




		@property
		def 	snake_case_     (     self):
				return 1_0_0




		@property
		def 	snake_case_     (     self):
				torch.manual_seed(0)

				__SCREAMING_SNAKE_CASE            = {
				    """in_channels""": 4,
				    # Out channels is double in channels because predicts mean and variance
				    """out_channels""": 8,
				    """addition_embed_type""": """image""",
				    """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""),
				    """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""),
				    """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""",
				    """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2),
				    """layers_per_block""": 1,
				    """encoder_hid_dim""": self.text_embedder_hidden_size,
				    """encoder_hid_dim_type""": """image_proj""",
				    """cross_attention_dim""": self.cross_attention_dim,
				    """attention_head_dim""": 4,
				    """resnet_time_scale_shift""": """scale_shift""",
				    """class_embed_type""": None,
				}

				__SCREAMING_SNAKE_CASE            = UNetaDConditionModel(**lowerCAmelCase__)
				return model




		@property
		def 	snake_case_     (     self):
				return {
				    "block_out_channels": [3_2, 6_4],
				    "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
				    "in_channels": 3,
				    "latent_channels": 4,
				    "layers_per_block": 1,
				    "norm_num_groups": 8,
				    "norm_type": "spatial",
				    "num_vq_embeddings": 1_2,
				    "out_channels": 3,
				    "up_block_types": [
				        "AttnUpDecoderBlock2D",
				        "UpDecoderBlock2D",
				    ],
				    "vq_embed_dim": 4,
				}




		@property
		def 	snake_case_     (     self):
				torch.manual_seed(0)
				__SCREAMING_SNAKE_CASE            = VQModel(**self.dummy_movq_kwargs)
				return model




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.dummy_unet
				__SCREAMING_SNAKE_CASE            = self.dummy_movq

				__SCREAMING_SNAKE_CASE            = {
				    """num_train_timesteps""": 1_0_0_0,
				    """beta_schedule""": """linear""",
				    """beta_start""": 0.0_00_85,
				    """beta_end""": 0.0_12,
				    """clip_sample""": False,
				    """set_alpha_to_one""": False,
				    """steps_offset""": 0,
				    """prediction_type""": """epsilon""",
				    """thresholding""": False,
				}

				__SCREAMING_SNAKE_CASE            = DDIMScheduler(**lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = {
				    """unet""": unet,
				    """scheduler""": scheduler,
				    """movq""": movq,
				}

				return components




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__=0):
				__SCREAMING_SNAKE_CASE            = floats_tensor((1, self.text_embedder_hidden_size)							,  rng=random.Random(lowerCAmelCase__)).to(lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = floats_tensor((1, self.text_embedder_hidden_size)							,  rng=random.Random(seed + 1)).to(
				    lowerCAmelCase__)
				# create init_image
				__SCREAMING_SNAKE_CASE            = floats_tensor((1, 3, 6_4, 6_4)							,  rng=random.Random(lowerCAmelCase__)).to(lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = image.cpu().permute(0							,  2							,  3							,  1)[0]
				__SCREAMING_SNAKE_CASE            = Image.fromarray(np.uinta(lowerCAmelCase__)).convert("""RGB""").resize((2_5_6, 2_5_6))

				if str(lowerCAmelCase__).startswith("""mps"""):
						__SCREAMING_SNAKE_CASE            = torch.manual_seed(lowerCAmelCase__)
				else:
						__SCREAMING_SNAKE_CASE            = torch.Generator(device=lowerCAmelCase__).manual_seed(lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = {
				    """image""": init_image,
				    """image_embeds""": image_embeds,
				    """negative_image_embeds""": negative_image_embeds,
				    """generator""": generator,
				    """height""": 6_4,
				    """width""": 6_4,
				    """num_inference_steps""": 1_0,
				    """guidance_scale""": 7.0,
				    """strength""": 0.2,
				    """output_type""": """np""",
				}
				return inputs




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = """cpu"""

				__SCREAMING_SNAKE_CASE            = self.get_dummy_components()

				__SCREAMING_SNAKE_CASE            = self.pipeline_class(**lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = pipe.to(lowerCAmelCase__)

				pipe.set_progress_bar_config(disable=lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = pipe(**self.get_dummy_inputs(lowerCAmelCase__))
				__SCREAMING_SNAKE_CASE            = output.images

				__SCREAMING_SNAKE_CASE            = pipe(
				    **self.get_dummy_inputs(lowerCAmelCase__)							,  return_dict=lowerCAmelCase__							,  )[0]

				__SCREAMING_SNAKE_CASE            = image[0, -3:, -3:, -1]
				__SCREAMING_SNAKE_CASE            = image_from_tuple[0, -3:, -3:, -1]

				assert image.shape == (1, 6_4, 6_4, 3)

				__SCREAMING_SNAKE_CASE            = np.array(
				    [0.6_19_97_78, 0.63_98_44_06, 0.46_14_57_85, 0.62_94_49_84, 0.5_62_22_15, 0.47_30_61_32, 0.47_44_14_56, 0.4_60_76_06, 0.48_71_92_63])
				assert (
				    np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
				), f" expected_slice {expected_slice}, but got {image_slice.flatten()}"
				assert (
				    np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1E-2
				), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"



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




		"""simple docstring"""





		def 	snake_case_     (     self):
				# clean up the VRAM after each test
				super().tearDown()
				gc.collect()
				torch.cuda.empty_cache()




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = load_numpy(
				    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
				    """/kandinskyv22/kandinskyv22_img2img_frog.npy""")

				__SCREAMING_SNAKE_CASE            = load_image(
				    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""")
				__SCREAMING_SNAKE_CASE            = """A red cartoon frog, 4k"""

				__SCREAMING_SNAKE_CASE            = KandinskyVaaPriorPipeline.from_pretrained(
				    """kandinsky-community/kandinsky-2-2-prior"""							,  torch_dtype=torch.floataa)
				pipe_prior.to(lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = KandinskyVaaImgaImgPipeline.from_pretrained(
				    """kandinsky-community/kandinsky-2-2-decoder"""							,  torch_dtype=torch.floataa)
				__SCREAMING_SNAKE_CASE            = pipeline.to(lowerCAmelCase__)

				pipeline.set_progress_bar_config(disable=lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = torch.Generator(device="""cpu""").manual_seed(0)
				__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = pipe_prior(
				    lowerCAmelCase__							,  generator=lowerCAmelCase__							,  num_inference_steps=5							,  negative_prompt=""""""							,  ).to_tuple()

				__SCREAMING_SNAKE_CASE            = pipeline(
				    image=lowerCAmelCase__							,  image_embeds=lowerCAmelCase__							,  negative_image_embeds=lowerCAmelCase__							,  generator=lowerCAmelCase__							,  num_inference_steps=1_0_0							,  height=7_6_8							,  width=7_6_8							,  strength=0.2							,  output_type="""np"""							,  )

				__SCREAMING_SNAKE_CASE            = output.images[0]

				assert image.shape == (7_6_8, 7_6_8, 3)

				assert_mean_pixel_difference(lowerCAmelCase__							,  lowerCAmelCase__)




