






'''simple docstring'''





from dataclasses import dataclass
from typing import Optional

import torch
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .modeling_utils import ModelMixin


@dataclass
class       snake_case__	( __a):
					a_								= 42






class       snake_case__	( __a			,							__a):




					@register_to_config
					def __init__(   self   :						int							,      _A   :						Optional[int] = 16							,      _A   :						str = 88							,      _A   :						List[Any] = None							,      _A   :						Dict = None							,      _A   :						List[Any] = 1							,      _A   :						List[Any] = 0.0							,      _A   :						List[str] = 32							,      _A   :						int = None							,      _A   :						str = False							,      _A   :						Tuple = None							,      _A   :						Optional[int] = "geglu"							,      _A   :						Union[str, Any] = True							,      _A   :						Optional[Any] = True							,      )  ->				Dict:
								super().__init__()
								UpperCAmelCase_	:    Optional[int]	  =    num_attention_heads
								UpperCAmelCase_	:    int	  =    attention_head_dim
								UpperCAmelCase_	:    Dict	  =    num_attention_heads * attention_head_dim

								UpperCAmelCase_	:    Dict	  =    in_channels

								UpperCAmelCase_	:    Union[str, Any]	  =    torch.nn.GroupNorm(num_groups=lowerCAmelCase__							,      num_channels=lowerCAmelCase__							,      eps=1e-6							,      affine=lowerCAmelCase__	)
								UpperCAmelCase_	:    List[str]	  =    nn.Linear(lowerCAmelCase__							,      lowerCAmelCase__	)

								# 3. Define transformers blocks
								UpperCAmelCase_	:    Union[str, Any]	  =    nn.ModuleList(
								    [
								        BasicTransformerBlock(
								            lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__							,      dropout=lowerCAmelCase__							,      cross_attention_dim=lowerCAmelCase__							,      activation_fn=lowerCAmelCase__							,      attention_bias=lowerCAmelCase__							,      double_self_attention=lowerCAmelCase__							,      norm_elementwise_affine=lowerCAmelCase__							,      )
								        for d in range(lowerCAmelCase__	)
								    ]	)

								UpperCAmelCase_	:    List[Any]	  =    nn.Linear(lowerCAmelCase__							,      lowerCAmelCase__	)





					def 						A	(   self   :						Union[str, Any]							,      _A   :						int							,      _A   :						str=None							,      _A   :						Optional[Any]=None							,      _A   :						List[Any]=None							,      _A   :						int=1							,      _A   :						Union[str, Any]=None							,      _A   :						Any = True							,      )  ->				List[str]:
								UpperCAmelCase_  ,	UpperCAmelCase_  ,	UpperCAmelCase_  ,	UpperCAmelCase_	:    str	  =    hidden_states.shape
								UpperCAmelCase_	:    str	  =    batch_frames // num_frames

								UpperCAmelCase_	:    Tuple	  =    hidden_states

								UpperCAmelCase_	:    Optional[int]	  =    hidden_states[None, :].reshape(lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__	)
								UpperCAmelCase_	:    Optional[int]	  =    hidden_states.permute(0							,      2							,      1							,      3							,      4	)

								UpperCAmelCase_	:    Optional[int]	  =    self.norm(lowerCAmelCase__	)
								UpperCAmelCase_	:    List[Any]	  =    hidden_states.permute(0							,      3							,      4							,      2							,      1	).reshape(batch_size * height * width							,      lowerCAmelCase__							,      lowerCAmelCase__	)

								UpperCAmelCase_	:    List[str]	  =    self.proj_in(lowerCAmelCase__	)

								# 2. Blocks
								for block in self.transformer_blocks:
											UpperCAmelCase_	:    Tuple	  =    block(
											    lowerCAmelCase__							,      encoder_hidden_states=lowerCAmelCase__							,      timestep=lowerCAmelCase__							,      cross_attention_kwargs=lowerCAmelCase__							,      class_labels=lowerCAmelCase__							,      )

								# 3. Output
								UpperCAmelCase_	:    Dict	  =    self.proj_out(lowerCAmelCase__	)
								UpperCAmelCase_	:    str	  =    (
								    hidden_states[None, None, :]
								    .reshape(lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__	)
								    .permute(0							,      3							,      4							,      1							,      2	)
								    .contiguous()
								)
								UpperCAmelCase_	:    List[Any]	  =    hidden_states.reshape(lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__	)

								UpperCAmelCase_	:    Dict	  =    hidden_states + residual

								if not return_dict:
											return (output,)

								return TransformerTemporalModelOutput(sample=lowerCAmelCase__	)




"""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__)




