






import gc
import random
import unittest

import numpy as np
import torch

from diffusers import (
    DDIMScheduler,
    KandinskyVaaControlnetPipeline,
    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 	snake_case__ (							UpperCamelCase_						,  unittest.TestCase				):
	lowercase__						:					str											=   KandinskyVaaControlnetPipeline
	lowercase__						:					Optional[int]											=   ["""image_embeds""", """negative_image_embeds""", """hint"""]
	lowercase__						:					int											=   ["""image_embeds""", """negative_image_embeds""", """hint"""]
	lowercase__						:					Dict											=   [
	    """generator""",
	    """height""",
	    """width""",
	    """latents""",
	    """guidance_scale""",
	    """num_inference_steps""",
	    """return_dict""",
	    """guidance_scale""",
	    """num_images_per_prompt""",
	    """output_type""",
	    """return_dict""",
	]
	lowercase__						:					Tuple											=   False
	@property
	def       __magic_name__    (    self			)							->				Any:
							return 32
	@property
	def       __magic_name__    (    self			)							->				Union[str, Any]:
							return 32
	@property
	def       __magic_name__    (    self			)							->				List[str]:
							return self.time_input_dim
	@property
	def       __magic_name__    (    self			)							->				str:
							return self.time_input_dim * 4
	@property
	def       __magic_name__    (    self			)							->				Optional[Any]:
							return 1_00
	@property
	def       __magic_name__    (    self			)							->				Any:
							torch.manual_seed(0			)

							__magic_name__      :       Any       						= {
							    """in_channels""": 8,
							    # Out channels is double in channels because predicts mean and variance
							    """out_channels""": 8,
							    """addition_embed_type""": """image_hint""",
							    """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,
							}

							__magic_name__      :       Optional[int]       						= UNetaDConditionModel(**_a			)
							return model
	@property
	def       __magic_name__    (    self			)							->				Optional[Any]:
							return {
							    "block_out_channels": [32, 32, 64, 64],
							    "down_block_types": [
							        "DownEncoderBlock2D",
							        "DownEncoderBlock2D",
							        "DownEncoderBlock2D",
							        "AttnDownEncoderBlock2D",
							    ],
							    "in_channels": 3,
							    "latent_channels": 4,
							    "layers_per_block": 1,
							    "norm_num_groups": 8,
							    "norm_type": "spatial",
							    "num_vq_embeddings": 12,
							    "out_channels": 3,
							    "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
							    "vq_embed_dim": 4,
							}
	@property
	def       __magic_name__    (    self			)							->				List[Any]:
							torch.manual_seed(0			)
							__magic_name__      :       List[str]       						= VQModel(**self.dummy_movq_kwargs			)
							return model
	def       __magic_name__    (    self			)							->				Union[str, Any]:
							__magic_name__      :       Union[str, Any]       						= self.dummy_unet
							__magic_name__      :       Optional[Any]       						= self.dummy_movq

							__magic_name__      :       Any       						= DDIMScheduler(
							    num_train_timesteps=10_00      ,       beta_schedule="""linear"""      ,       beta_start=0.0_0_0_8_5      ,       beta_end=0.0_1_2      ,       clip_sample=_a      ,       set_alpha_to_one=_a      ,       steps_offset=1      ,       prediction_type="""epsilon"""      ,       thresholding=_a      ,       )

							__magic_name__      :       str       						= {
							    """unet""": unet,
							    """scheduler""": scheduler,
							    """movq""": movq,
							}
							return components
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__=0			)							->				Optional[Any]:
							__magic_name__      :       Optional[int]       						= floats_tensor((1, self.text_embedder_hidden_size)      ,       rng=random.Random(_a			)			).to(_a			)
							__magic_name__      :       Union[str, Any]       						= floats_tensor((1, self.text_embedder_hidden_size)      ,       rng=random.Random(seed + 1			)			).to(
							    _a			)

							# create hint
							__magic_name__      :       Dict       						= floats_tensor((1, 3, 64, 64)      ,       rng=random.Random(_a			)			).to(_a			)

							if str(_a			).startswith("""mps"""			):
													__magic_name__      :       Optional[Any]       						= torch.manual_seed(_a			)
							else:
													__magic_name__      :       Tuple       						= torch.Generator(device=_a			).manual_seed(_a			)
							__magic_name__      :       Tuple       						= {
							    """image_embeds""": image_embeds,
							    """negative_image_embeds""": negative_image_embeds,
							    """hint""": hint,
							    """generator""": generator,
							    """height""": 64,
							    """width""": 64,
							    """guidance_scale""": 4.0,
							    """num_inference_steps""": 2,
							    """output_type""": """np""",
							}
							return inputs







	def       __magic_name__    (    self			)							->				str:
							__magic_name__      :       str       						= """cpu"""

							__magic_name__      :       Any       						= self.get_dummy_components()

							__magic_name__      :       str       						= self.pipeline_class(**_a			)
							__magic_name__      :       Optional[int]       						= pipe.to(_a			)

							pipe.set_progress_bar_config(disable=_a			)

							__magic_name__      :       Dict       						= pipe(**self.get_dummy_inputs(_a			)			)
							__magic_name__      :       Optional[int]       						= output.images

							__magic_name__      :       Any       						= pipe(
							    **self.get_dummy_inputs(_a			)      ,       return_dict=_a      ,       )[0]

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

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

							__magic_name__      :       Tuple       						= np.array(
							    [0.6_9_5_9_8_2_6, 0.8_6_8_2_7_9, 0.7_5_5_8_0_9_2, 0.6_8_7_6_9_4_6_7, 0.8_5_8_0_5_8_0_4, 0.6_5_9_7_7_4_9_6, 0.4_4_8_8_5_3_0_2, 0.5_9_5_9_1_1_1, 0.4_2_5_1_5_9_5]			)

							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 	snake_case__ (							unittest.TestCase				):
	def       __magic_name__    (    self			)							->				Any:
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()







	def       __magic_name__    (    self			)							->				str:
							__magic_name__      :       Dict       						= load_numpy(
							    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
							    """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy"""			)

							__magic_name__      :       List[str]       						= load_image(
							    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
							    """/kandinskyv22/hint_image_cat.png"""			)
							__magic_name__      :       int       						= torch.from_numpy(np.array(_a			)			).float() / 2_5_5.0
							__magic_name__      :       List[Any]       						= hint.permute(2      ,       0      ,       1			).unsqueeze(0			)

							__magic_name__      :       Optional[Any]       						= KandinskyVaaPriorPipeline.from_pretrained(
							    """kandinsky-community/kandinsky-2-2-prior"""      ,       torch_dtype=torch.floataa			)
							pipe_prior.to(_a			)

							__magic_name__      :       Optional[Any]       						= KandinskyVaaControlnetPipeline.from_pretrained(
							    """kandinsky-community/kandinsky-2-2-controlnet-depth"""      ,       torch_dtype=torch.floataa			)
							__magic_name__      :       Dict       						= pipeline.to(_a			)
							pipeline.set_progress_bar_config(disable=_a			)

							__magic_name__      :       Tuple       						= """A robot, 4k photo"""

							__magic_name__      :       Dict       						= torch.Generator(device="""cuda"""			).manual_seed(0			)
							__magic_name__      :       List[Any]       						= pipe_prior(
							    _a      ,       generator=_a      ,       num_inference_steps=5      ,       negative_prompt=""""""      ,       ).to_tuple()

							__magic_name__      :       int       						= torch.Generator(device="""cuda"""			).manual_seed(0			)
							__magic_name__      :       Union[str, Any]       						= pipeline(
							    image_embeds=_a      ,       negative_image_embeds=_a      ,       hint=_a      ,       generator=_a      ,       num_inference_steps=1_00      ,       output_type="""np"""      ,       )

							__magic_name__      :       List[Any]       						= output.images[0]

							assert image.shape == (5_12, 5_12, 3)

							assert_mean_pixel_difference(_a      ,       _a			)








from manim import *





class 	snake_case__ (							_lowerCAmelCase				):
	def       __magic_name__    (    self			)							->				Dict:
							__magic_name__      :       int       						= Rectangle(height=0.5      ,       width=0.5			)
							__magic_name__      :       Optional[int]       						= Rectangle(height=0.2_5      ,       width=0.2_5			)
							__magic_name__      :       str       						= Rectangle(height=0.4_6      ,       width=0.4_6			).set_stroke(width=0			)

							__magic_name__      :       List[Any]       						= [mem.copy() for i in range(6			)]
							__magic_name__      :       int       						= [mem.copy() for i in range(6			)]
							__magic_name__      :       Tuple       						= VGroup(*lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0			)
							__magic_name__      :       List[str]       						= VGroup(*lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0			)
							__magic_name__      :       str       						= VGroup(lowerCAmelCase__      ,       lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0			)
							__magic_name__      :       Union[str, Any]       						= Text("""CPU"""      ,       font_size=24			)
							__magic_name__      :       Tuple       						= Group(lowerCAmelCase__      ,       lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0.5      ,       aligned_edge=lowerCAmelCase__			)
							cpu.move_to([-2.5, -0.5, 0]			)
							self.add(lowerCAmelCase__			)

							__magic_name__      :       Any       						= [mem.copy() for i in range(4			)]
							__magic_name__      :       List[Any]       						= VGroup(*lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0			)
							__magic_name__      :       Tuple       						= Text("""GPU"""      ,       font_size=24			)
							__magic_name__      :       Tuple       						= Group(lowerCAmelCase__      ,       lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0.5      ,       aligned_edge=lowerCAmelCase__			)
							gpu.move_to([-1, -1, 0]			)
							self.add(lowerCAmelCase__			)

							__magic_name__      :       Union[str, Any]       						= [mem.copy() for i in range(6			)]
							__magic_name__      :       Union[str, Any]       						= VGroup(*lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0			)

							__magic_name__      :       str       						= Text("""Model"""      ,       font_size=24			)
							__magic_name__      :       Optional[int]       						= Group(lowerCAmelCase__      ,       lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0.5      ,       aligned_edge=lowerCAmelCase__			)
							model.move_to([3, -1.0, 0]			)
							self.add(lowerCAmelCase__			)

							__magic_name__      :       str       						= []
							__magic_name__      :       Tuple       						= []
							__magic_name__      :       Union[str, Any]       						= []

							for i, rect in enumerate(lowerCAmelCase__			):
													rect.set_stroke(lowerCAmelCase__			)

													__magic_name__      :       Optional[Any]       						= Rectangle(height=0.4_6 / 4      ,       width=0.4_6 / 3			).set_stroke(width=0.0			).set_fill(lowerCAmelCase__      ,       opacity=0.7			)

													if i == 0:
																			cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT			)      ,       buff=0.0_2      ,       direction=lowerCAmelCase__			)
																			cpu_target.set_x(cpu_target.get_x() + 0.1			)
													elif i == 3:
																			cpu_target.next_to(model_cpu_arr[0]      ,       direction=lowerCAmelCase__      ,       buff=0.0			)
													else:
																			cpu_target.next_to(model_cpu_arr[i - 1]      ,       direction=lowerCAmelCase__      ,       buff=0.0			)
													self.add(lowerCAmelCase__			)
													model_cpu_arr.append(lowerCAmelCase__			)

							self.add(*lowerCAmelCase__      ,       *lowerCAmelCase__      ,       *lowerCAmelCase__			)

							__magic_name__      :       Optional[Any]       						= [mem.copy() for i in range(6			)]
							__magic_name__      :       Optional[Any]       						= VGroup(*lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0			)

							__magic_name__      :       Any       						= Text("""Loaded Checkpoint"""      ,       font_size=24			)
							__magic_name__      :       Optional[int]       						= Group(lowerCAmelCase__      ,       lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0.5      ,       aligned_edge=lowerCAmelCase__			)
							checkpoint.move_to([3, 0.5, 0]			)

							self.add(lowerCAmelCase__			)

							__magic_name__      :       Optional[int]       						= []
							__magic_name__      :       Tuple       						= []

							for i, rect in enumerate(lowerCAmelCase__			):
													__magic_name__      :       Dict       						= fill.copy().set_fill(lowerCAmelCase__      ,       opacity=0.7			)
													target.move_to(lowerCAmelCase__			)
													ckpt_arr.append(lowerCAmelCase__			)

													__magic_name__      :       int       						= target.copy()
													if i < 5:
																			cpu_target.move_to(cpu_left_col_base[i + 1]			)
													else:
																			cpu_target.move_to(cpu_right_col_base[i - 5]			)
													ckpt_cpu_arr.append(lowerCAmelCase__			)
							self.add(*lowerCAmelCase__      ,       *lowerCAmelCase__			)

							__magic_name__      :       Tuple       						= Square(side_length=2.2			)
							key.move_to([-5, 2, 0]			)

							__magic_name__      :       str       						= MarkupText(
							    F'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model'      ,       font_size=18      ,       )

							key_text.move_to([-5, 2.4, 0]			)

							self.add(lowerCAmelCase__      ,       lowerCAmelCase__			)

							__magic_name__      :       Any       						= MarkupText(
							    F'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint'      ,       font_size=18      ,       )

							blue_text.next_to(lowerCAmelCase__      ,       DOWN * 2.4      ,       aligned_edge=key_text.get_left()			)
							self.add(lowerCAmelCase__			)

							__magic_name__      :       Optional[Any]       						= MarkupText(
							    F'Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.'      ,       font_size=24      ,       )
							step_a.move_to([2, 2, 0]			)

							__magic_name__      :       int       						= [meta_mem.copy() for i in range(6			)]
							__magic_name__      :       Union[str, Any]       						= [meta_mem.copy() for i in range(6			)]
							__magic_name__      :       Any       						= VGroup(*lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0			)
							__magic_name__      :       str       						= VGroup(*lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0			)
							__magic_name__      :       Tuple       						= VGroup(lowerCAmelCase__      ,       lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0			)
							__magic_name__      :       int       						= Text("""Disk"""      ,       font_size=24			)
							__magic_name__      :       Union[str, Any]       						= Group(lowerCAmelCase__      ,       lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0.5      ,       aligned_edge=lowerCAmelCase__			)
							disk.move_to([-4.0, -1.2_5, 0]			)
							self.play(Write(lowerCAmelCase__      ,       run_time=3			)      ,       Write(lowerCAmelCase__      ,       run_time=1			)      ,       Create(lowerCAmelCase__      ,       run_time=1			)			)

							__magic_name__      :       List[Any]       						= []
							for i, rect in enumerate(lowerCAmelCase__			):
													__magic_name__      :       Dict       						= rect.copy()
													target.generate_target()
													target.target.move_to(disk_left_col_base[i]			).scale(0.5			)
													animations.append(MoveToTarget(lowerCAmelCase__      ,       run_time=1.5			)			)
							self.play(*lowerCAmelCase__			)

							self.play(FadeOut(lowerCAmelCase__			)			)

							__magic_name__      :       str       						= MarkupText(F'Then, the checkpoint is removed from memory\nthrough garbage collection.'      ,       font_size=24			)
							step_a.move_to([2, 2, 0]			)

							self.play(Write(lowerCAmelCase__      ,       run_time=3			)			)

							self.play(
							    FadeOut(lowerCAmelCase__      ,       lowerCAmelCase__      ,       *lowerCAmelCase__      ,       *lowerCAmelCase__			)      ,       )

							self.wait()
