'''simple docstring'''





import gc
import unittest

import torch
from parameterized import parameterized

from diffusers import AutoencoderKL
from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()




class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE   , unittest.TestCase	):







				'''simple docstring'''
				UpperCAmelCase__							=							AutoencoderKL
				UpperCAmelCase__							=							'''sample'''
				UpperCAmelCase__							=							1E-2





				@property
				def  snake_case__				(						self					:						Union[str, Any]					)							->Optional[Any]:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						4
										_UpperCamelCase			:			str   			=						3
										_UpperCamelCase			:			str   			=						(32, 32)

										_UpperCamelCase			:			List[str]   			=						floats_tensor((batch_size, num_channels) + sizes					).to(lowercase__					)

										return {"sample": image}





				@property
				def  snake_case__				(						self					:						Optional[int]					)							->Dict:


										'''simple docstring'''




										return (3, 32, 32)





				@property
				def  snake_case__				(						self					:						str					)							->Optional[int]:


										'''simple docstring'''




										return (3, 32, 32)





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


										'''simple docstring'''




										_UpperCamelCase			:			List[Any]   			=						{
										    "block_out_channels": [32, 64],
										    "in_channels": 3,
										    "out_channels": 3,
										    "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"],
										    "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"],
										    "latent_channels": 4,
										}
										_UpperCamelCase			:			Union[str, Any]   			=						self.dummy_input
										return init_dict, inputs_dict





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


										'''simple docstring'''




										pass





				def  snake_case__				(						self					:						str					)							->int:


										'''simple docstring'''




										pass





				@unittest.skipIf(torch_device == "mps"       ,		"Gradient checkpointing skipped on MPS"					)
				def  snake_case__				(						self					:						str					)							->List[str]:


										'''simple docstring'''




										_UpperCamelCase			,       _UpperCamelCase			:			Optional[Any]   			=						self.prepare_init_args_and_inputs_for_common()
										_UpperCamelCase			:			Optional[Any]   			=						self.model_class(**lowercase__					)
										model.to(lowercase__					)

										assert not model.is_gradient_checkpointing and model.training

										_UpperCamelCase			:			str   			=						model(**lowercase__					).sample
										# run the backwards pass on the model. For backwards pass, for simplicity purpose,
										# we won't calculate the loss and rather backprop on out.sum()
										model.zero_grad()

										_UpperCamelCase			:			Optional[Any]   			=						torch.randn_like(lowercase__					)
										_UpperCamelCase			:			Optional[int]   			=						(out - labels).mean()
										loss.backward()

										# re-instantiate the model now enabling gradient checkpointing
										_UpperCamelCase			:			Dict   			=						self.model_class(**lowercase__					)
										# clone model
										model_a.load_state_dict(model.state_dict()					)
										model_a.to(lowercase__					)
										model_a.enable_gradient_checkpointing()

										assert model_a.is_gradient_checkpointing and model_a.training

										_UpperCamelCase			:			Union[str, Any]   			=						model_a(**lowercase__					).sample
										# run the backwards pass on the model. For backwards pass, for simplicity purpose,
										# we won't calculate the loss and rather backprop on out.sum()
										model_a.zero_grad()
										_UpperCamelCase			:			Dict   			=						(out_a - labels).mean()
										loss_a.backward()

										# compare the output and parameters gradients
										self.assertTrue((loss - loss_a).abs() < 1e-5					)
										_UpperCamelCase			:			Optional[int]   			=						dict(model.named_parameters()					)
										_UpperCamelCase			:			List[Any]   			=						dict(model_a.named_parameters()					)
										for name, param in named_params.items():
																self.assertTrue(torch_all_close(param.grad.data       ,		named_params_a[name].grad.data       ,		atol=5e-5					)					)





				def  snake_case__				(						self					:						Optional[int]					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			,       _UpperCamelCase			:			Optional[int]   			=						AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy"       ,		output_loading_info=lowercase__					)
										self.assertIsNotNone(lowercase__					)
										self.assertEqual(len(loading_info["missing_keys"]					)       ,		0					)

										model.to(lowercase__					)
										_UpperCamelCase			:			int   			=						model(**self.dummy_input					)

										assert image is not None, "Make sure output is not None"







				def  snake_case__				(						self					:						str					)							->Tuple:


										'''simple docstring'''




										_UpperCamelCase			:			str   			=						AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy"					)
										_UpperCamelCase			:			List[Any]   			=						model.to(lowercase__					)
										model.eval()

										if torch_device == "mps":
																_UpperCamelCase			:			int   			=						torch.manual_seed(0					)
										else:
																_UpperCamelCase			:			List[str]   			=						torch.Generator(device=lowercase__					).manual_seed(0					)

										_UpperCamelCase			:			Optional[Any]   			=						torch.randn(
										    1       ,		model.config.in_channels       ,		model.config.sample_size       ,		model.config.sample_size       ,		generator=torch.manual_seed(0					)       ,		)
										_UpperCamelCase			:			Optional[Any]   			=						image.to(lowercase__					)
										with torch.no_grad():
																_UpperCamelCase			:			List[Any]   			=						model(lowercase__       ,		sample_posterior=lowercase__       ,		generator=lowercase__					).sample

										_UpperCamelCase			:			str   			=						output[0, -1, -3:, -3:].flatten().cpu()

										# Since the VAE Gaussian prior's generator is seeded on the appropriate device,
										# the expected output slices are not the same for CPU and GPU.
										if torch_device == "mps":
																_UpperCamelCase			:			Tuple   			=						torch.tensor(
																    [
																        -4.0078e-01,
																        -3.8323e-04,
																        -1.2681e-01,
																        -1.1462e-01,
																        2.0095e-01,
																        1.0893e-01,
																        -8.8247e-02,
																        -3.0361e-01,
																        -9.8644e-03,
																    ]					)
										elif torch_device == "cpu":
																_UpperCamelCase			:			Optional[int]   			=						torch.tensor(
																    [-0.1_3_5_2, 0.0_8_7_8, 0.0_4_1_9, -0.0_8_1_8, -0.1_0_6_9, 0.0_6_8_8, -0.1_4_5_8, -0.4_4_4_6, -0.0_0_2_6]					)
										else:
																_UpperCamelCase			:			Tuple   			=						torch.tensor(
																    [-0.2_4_2_1, 0.4_6_4_2, 0.2_5_0_7, -0.0_4_3_8, 0.0_6_8_2, 0.3_1_6_0, -0.2_0_1_8, -0.0_7_2_7, 0.2_4_8_5]					)

										self.assertTrue(torch_all_close(lowercase__       ,		lowercase__       ,		rtol=1e-2					)					)





@slow
class 		SCREAMING_SNAKE_CASE     (					unittest.TestCase	):







				'''simple docstring'''





				def  snake_case__				(						self					:						Tuple       ,		lowercase__					:						Any       ,		lowercase__					:						List[Any]					)							->Dict:


										'''simple docstring'''




										return f'''gaussian_noise_s={seed}_shape={'_'.join([str(lowercase__					) for s in shape]					)}.npy'''





				def  snake_case__				(						self					:						Tuple					)							->List[Any]:


										'''simple docstring'''




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





				def  snake_case__				(						self					:						str       ,		lowercase__					:						List[Any]=0       ,		lowercase__					:						Optional[Any]=(4, 3, 512, 512)       ,		lowercase__					:						str=False					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Union[str, Any]   			=						torch.floataa if fpaa else torch.floataa
										_UpperCamelCase			:			Dict   			=						torch.from_numpy(load_hf_numpy(self.get_file_format(lowercase__       ,		lowercase__					)					)					).to(lowercase__					).to(lowercase__					)
										return image





				def  snake_case__				(						self					:						Union[str, Any]       ,		lowercase__					:						Optional[Any]="CompVis/stable-diffusion-v1-4"       ,		lowercase__					:						List[str]=False					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						"fp16" if fpaa else None
										_UpperCamelCase			:			List[str]   			=						torch.floataa if fpaa else torch.floataa

										_UpperCamelCase			:			str   			=						AutoencoderKL.from_pretrained(
										    lowercase__       ,		subfolder="vae"       ,		torch_dtype=lowercase__       ,		revision=lowercase__       ,		)
										model.to(lowercase__					).eval()

										return model





				def  snake_case__				(						self					:						Dict       ,		lowercase__					:						Tuple=0					)							->str:


										'''simple docstring'''




										if torch_device == "mps":
																return torch.manual_seed(lowercase__					)
										return torch.Generator(device=lowercase__					).manual_seed(lowercase__					)





				@parameterized.expand(
				    [
				        # fmt: off
				        [33, [-0.1_6_0_3, 0.9_8_7_8, -0.0_4_9_5, -0.0_7_9_0, -0.2_7_0_9, 0.8_3_7_5, -0.2_0_6_0, -0.0_8_2_4], [-0.2_3_9_5, 0.0_0_9_8, 0.0_1_0_2, -0.0_7_0_9, -0.2_8_4_0, -0.0_2_7_4, -0.0_7_1_8, -0.1_8_2_4]],
				        [47, [-0.2_3_7_6, 0.1_1_6_8, 0.1_3_3_2, -0.4_8_4_0, -0.2_5_0_8, -0.0_7_9_1, -0.0_4_9_3, -0.4_0_8_9], [0.0_3_5_0, 0.0_8_4_7, 0.0_4_6_7, 0.0_3_4_4, -0.0_8_4_2, -0.0_5_4_7, -0.0_6_3_3, -0.1_1_3_1]],
				        # fmt: on
				    ]					)
				def  snake_case__				(						self					:						List[Any]       ,		lowercase__					:						Dict       ,		lowercase__					:						List[Any]       ,		lowercase__					:						Optional[Any]					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			Dict   			=						self.get_sd_vae_model()
										_UpperCamelCase			:			Tuple   			=						self.get_sd_image(lowercase__					)
										_UpperCamelCase			:			str   			=						self.get_generator(lowercase__					)

										with torch.no_grad():
																_UpperCamelCase			:			Optional[int]   			=						model(lowercase__       ,		generator=lowercase__       ,		sample_posterior=lowercase__					).sample

										assert sample.shape == image.shape

										_UpperCamelCase			:			List[Any]   			=						sample[-1, -2:, -2:, :2].flatten().float().cpu()
										_UpperCamelCase			:			List[Any]   			=						torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice					)

										assert torch_all_close(lowercase__       ,		lowercase__       ,		atol=3e-3					)





				@parameterized.expand(
				    [
				        # fmt: off
				        [33, [-0.0_5_1_3, 0.0_2_8_9, 1.3_7_9_9, 0.2_1_6_6, -0.2_5_7_3, -0.0_8_7_1, 0.5_1_0_3, -0.0_9_9_9]],
				        [47, [-0.4_1_2_8, -0.1_3_2_0, -0.3_7_0_4, 0.1_9_6_5, -0.4_1_1_6, -0.2_3_3_2, -0.3_3_4_0, 0.2_2_4_7]],
				        # fmt: on
				    ]					)
				@require_torch_gpu
				def  snake_case__				(						self					:						int       ,		lowercase__					:						str       ,		lowercase__					:						Optional[Any]					)							->Tuple:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						self.get_sd_vae_model(fpaa=lowercase__					)
										_UpperCamelCase			:			Any   			=						self.get_sd_image(lowercase__       ,		fpaa=lowercase__					)
										_UpperCamelCase			:			Any   			=						self.get_generator(lowercase__					)

										with torch.no_grad():
																_UpperCamelCase			:			Tuple   			=						model(lowercase__       ,		generator=lowercase__       ,		sample_posterior=lowercase__					).sample

										assert sample.shape == image.shape

										_UpperCamelCase			:			Union[str, Any]   			=						sample[-1, -2:, :2, -2:].flatten().float().cpu()
										_UpperCamelCase			:			List[str]   			=						torch.tensor(lowercase__					)

										assert torch_all_close(lowercase__       ,		lowercase__       ,		atol=1e-2					)





				@parameterized.expand(
				    [
				        # fmt: off
				        [33, [-0.1_6_0_9, 0.9_8_6_6, -0.0_4_8_7, -0.0_7_7_7, -0.2_7_1_6, 0.8_3_6_8, -0.2_0_5_5, -0.0_8_1_4], [-0.2_3_9_5, 0.0_0_9_8, 0.0_1_0_2, -0.0_7_0_9, -0.2_8_4_0, -0.0_2_7_4, -0.0_7_1_8, -0.1_8_2_4]],
				        [47, [-0.2_3_7_7, 0.1_1_4_7, 0.1_3_3_3, -0.4_8_4_1, -0.2_5_0_6, -0.0_8_0_5, -0.0_4_9_1, -0.4_0_8_5], [0.0_3_5_0, 0.0_8_4_7, 0.0_4_6_7, 0.0_3_4_4, -0.0_8_4_2, -0.0_5_4_7, -0.0_6_3_3, -0.1_1_3_1]],
				        # fmt: on
				    ]					)
				def  snake_case__				(						self					:						Dict       ,		lowercase__					:						Optional[int]       ,		lowercase__					:						int       ,		lowercase__					:						List[str]					)							->Tuple:


										'''simple docstring'''




										_UpperCamelCase			:			Optional[int]   			=						self.get_sd_vae_model()
										_UpperCamelCase			:			Dict   			=						self.get_sd_image(lowercase__					)

										with torch.no_grad():
																_UpperCamelCase			:			int   			=						model(lowercase__					).sample

										assert sample.shape == image.shape

										_UpperCamelCase			:			Any   			=						sample[-1, -2:, -2:, :2].flatten().float().cpu()
										_UpperCamelCase			:			List[Any]   			=						torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice					)

										assert torch_all_close(lowercase__       ,		lowercase__       ,		atol=3e-3					)





				@parameterized.expand(
				    [
				        # fmt: off
				        [13, [-0.2_0_5_1, -0.1_8_0_3, -0.2_3_1_1, -0.2_1_1_4, -0.3_2_9_2, -0.3_5_7_4, -0.2_9_5_3, -0.3_3_2_3]],
				        [37, [-0.2_6_3_2, -0.2_6_2_5, -0.2_1_9_9, -0.2_7_4_1, -0.4_5_3_9, -0.4_9_9_0, -0.3_7_2_0, -0.4_9_2_5]],
				        # fmt: on
				    ]					)
				@require_torch_gpu
				def  snake_case__				(						self					:						str       ,		lowercase__					:						List[Any]       ,		lowercase__					:						str					)							->int:


										'''simple docstring'''




										_UpperCamelCase			:			List[str]   			=						self.get_sd_vae_model()
										_UpperCamelCase			:			int   			=						self.get_sd_image(lowercase__       ,		shape=(3, 4, 64, 64)					)

										with torch.no_grad():
																_UpperCamelCase			:			Dict   			=						model.decode(lowercase__					).sample

										assert list(sample.shape					) == [3, 3, 512, 512]

										_UpperCamelCase			:			Optional[Any]   			=						sample[-1, -2:, :2, -2:].flatten().cpu()
										_UpperCamelCase			:			int   			=						torch.tensor(lowercase__					)

										assert torch_all_close(lowercase__       ,		lowercase__       ,		atol=1e-3					)





				@parameterized.expand(
				    [
				        # fmt: off
				        [27, [-0.0_3_6_9, 0.0_2_0_7, -0.0_7_7_6, -0.0_6_8_2, -0.1_7_4_7, -0.1_9_3_0, -0.1_4_6_5, -0.2_0_3_9]],
				        [16, [-0.1_6_2_8, -0.2_1_3_4, -0.2_7_4_7, -0.2_6_4_2, -0.3_7_7_4, -0.4_4_0_4, -0.3_6_8_7, -0.4_2_7_7]],
				        # fmt: on
				    ]					)
				@require_torch_gpu
				def  snake_case__				(						self					:						Union[str, Any]       ,		lowercase__					:						Union[str, Any]       ,		lowercase__					:						Optional[Any]					)							->Optional[int]:


										'''simple docstring'''




										_UpperCamelCase			:			int   			=						self.get_sd_vae_model(fpaa=lowercase__					)
										_UpperCamelCase			:			Optional[Any]   			=						self.get_sd_image(lowercase__       ,		shape=(3, 4, 64, 64)       ,		fpaa=lowercase__					)

										with torch.no_grad():
																_UpperCamelCase			:			Optional[Any]   			=						model.decode(lowercase__					).sample

										assert list(sample.shape					) == [3, 3, 512, 512]

										_UpperCamelCase			:			str   			=						sample[-1, -2:, :2, -2:].flatten().float().cpu()
										_UpperCamelCase			:			Union[str, Any]   			=						torch.tensor(lowercase__					)

										assert torch_all_close(lowercase__       ,		lowercase__       ,		atol=5e-3					)





				@parameterized.expand([(13,), (16,), (27,)]					)
				@require_torch_gpu
				@unittest.skipIf(not is_xformers_available()       ,		reason="xformers is not required when using PyTorch 2.0."					)
				def  snake_case__				(						self					:						int       ,		lowercase__					:						int					)							->str:


										'''simple docstring'''




										_UpperCamelCase			:			Optional[int]   			=						self.get_sd_vae_model(fpaa=lowercase__					)
										_UpperCamelCase			:			List[Any]   			=						self.get_sd_image(lowercase__       ,		shape=(3, 4, 64, 64)       ,		fpaa=lowercase__					)

										with torch.no_grad():
																_UpperCamelCase			:			Optional[Any]   			=						model.decode(lowercase__					).sample

										model.enable_xformers_memory_efficient_attention()
										with torch.no_grad():
																_UpperCamelCase			:			int   			=						model.decode(lowercase__					).sample

										assert list(sample.shape					) == [3, 3, 512, 512]

										assert torch_all_close(lowercase__       ,		lowercase__       ,		atol=1e-1					)





				@parameterized.expand([(13,), (16,), (37,)]					)
				@require_torch_gpu
				@unittest.skipIf(not is_xformers_available()       ,		reason="xformers is not required when using PyTorch 2.0."					)
				def  snake_case__				(						self					:						Tuple       ,		lowercase__					:						List[Any]					)							->Optional[int]:


										'''simple docstring'''




										_UpperCamelCase			:			Optional[Any]   			=						self.get_sd_vae_model()
										_UpperCamelCase			:			Dict   			=						self.get_sd_image(lowercase__       ,		shape=(3, 4, 64, 64)					)

										with torch.no_grad():
																_UpperCamelCase			:			Optional[int]   			=						model.decode(lowercase__					).sample

										model.enable_xformers_memory_efficient_attention()
										with torch.no_grad():
																_UpperCamelCase			:			int   			=						model.decode(lowercase__					).sample

										assert list(sample.shape					) == [3, 3, 512, 512]

										assert torch_all_close(lowercase__       ,		lowercase__       ,		atol=1e-2					)







				@parameterized.expand(
				    [
				        # fmt: off
				        [33, [-0.3_0_0_1, 0.0_9_1_8, -2.6_9_8_4, -3.9_7_2_0, -3.2_0_9_9, -5.0_3_5_3, 1.7_3_3_8, -0.2_0_6_5, 3.4_2_6_7]],
				        [47, [-1.5_0_3_0, -4.3_8_7_1, -6.0_3_5_5, -9.1_1_5_7, -1.6_6_6_1, -2.7_8_5_3, 2.1_6_0_7, -5.0_8_2_3, 2.5_6_3_3]],
				        # fmt: on
				    ]					)
				def  snake_case__				(						self					:						List[str]       ,		lowercase__					:						int       ,		lowercase__					:						Optional[Any]					)							->Optional[int]:


										'''simple docstring'''




										_UpperCamelCase			:			Optional[Any]   			=						self.get_sd_vae_model()
										_UpperCamelCase			:			str   			=						self.get_sd_image(lowercase__					)
										_UpperCamelCase			:			List[Any]   			=						self.get_generator(lowercase__					)

										with torch.no_grad():
																_UpperCamelCase			:			List[Any]   			=						model.encode(lowercase__					).latent_dist
																_UpperCamelCase			:			Optional[Any]   			=						dist.sample(generator=lowercase__					)

										assert list(sample.shape					) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]

										_UpperCamelCase			:			Any   			=						sample[0, -1, -3:, -3:].flatten().cpu()
										_UpperCamelCase			:			List[str]   			=						torch.tensor(lowercase__					)

										_UpperCamelCase			:			Optional[int]   			=						3e-3 if torch_device != "mps" else 1e-2
										assert torch_all_close(lowercase__       ,		lowercase__       ,		atol=lowercase__					)



'''simple docstring'''





from dataclasses import dataclass
from typing import Optional

import numpy as np
import torch
import torch.nn as nn

from ..utils import BaseOutput, is_torch_version, randn_tensor
from .attention_processor import SpatialNorm
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block




@dataclass
class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''
				UpperCAmelCase__							=							42





class 		SCREAMING_SNAKE_CASE     (					nn.Module	):







				'''simple docstring'''





				def __init__(						self					:						Optional[Any]       ,		lowercase__					:						List[str]=3       ,		lowercase__					:						Tuple=3       ,		lowercase__					:						List[str]=("DownEncoderBlock2D",)       ,		lowercase__					:						Optional[int]=(64,)       ,		lowercase__					:						List[Any]=2       ,		lowercase__					:						int=32       ,		lowercase__					:						Optional[int]="silu"       ,		lowercase__					:						List[Any]=True       ,		)							->Optional[Any]:


										'''simple docstring'''




										super().__init__()
										_UpperCamelCase			:			Union[str, Any]   			=						layers_per_block

										_UpperCamelCase			:			Union[str, Any]   			=						torch.nn.Convad(
										    lowercase__       ,		block_out_channels[0]       ,		kernel_size=3       ,		stride=1       ,		padding=1       ,		)

										_UpperCamelCase			:			int   			=						None
										_UpperCamelCase			:			Optional[Any]   			=						nn.ModuleList([]					)

										# down
										_UpperCamelCase			:			Optional[int]   			=						block_out_channels[0]
										for i, down_block_type in enumerate(lowercase__					):
																_UpperCamelCase			:			int   			=						output_channel
																_UpperCamelCase			:			int   			=						block_out_channels[i]
																_UpperCamelCase			:			Tuple   			=						i == len(lowercase__					) - 1

																_UpperCamelCase			:			List[Any]   			=						get_down_block(
																    lowercase__       ,		num_layers=self.layers_per_block       ,		in_channels=lowercase__       ,		out_channels=lowercase__       ,		add_downsample=not is_final_block       ,		resnet_eps=1e-6       ,		downsample_padding=0       ,		resnet_act_fn=lowercase__       ,		resnet_groups=lowercase__       ,		attention_head_dim=lowercase__       ,		temb_channels=lowercase__       ,		)
																self.down_blocks.append(lowercase__					)

										# mid
										_UpperCamelCase			:			Dict   			=						UNetMidBlockaD(
										    in_channels=block_out_channels[-1]       ,		resnet_eps=1e-6       ,		resnet_act_fn=lowercase__       ,		output_scale_factor=1       ,		resnet_time_scale_shift="default"       ,		attention_head_dim=block_out_channels[-1]       ,		resnet_groups=lowercase__       ,		temb_channels=lowercase__       ,		)

										# out
										_UpperCamelCase			:			List[str]   			=						nn.GroupNorm(num_channels=block_out_channels[-1]       ,		num_groups=lowercase__       ,		eps=1e-6					)
										_UpperCamelCase			:			Union[str, Any]   			=						nn.SiLU()

										_UpperCamelCase			:			Tuple   			=						2 * out_channels if double_z else out_channels
										_UpperCamelCase			:			List[Any]   			=						nn.Convad(block_out_channels[-1]       ,		lowercase__       ,		3       ,		padding=1					)

										_UpperCamelCase			:			Tuple   			=						False







				def  snake_case__				(						self					:						str       ,		lowercase__					:						Any					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Dict   			=						x
										_UpperCamelCase			:			str   			=						self.conv_in(lowercase__					)

										if self.training and self.gradient_checkpointing:

																def create_custom_forward(lowercase__					:						Any					):
																						def custom_forward(*lowercase__					:						List[Any]					):
																												return module(*lowercase__					)

																						return custom_forward

																# down
																if is_torch_version(">="       ,		"1.11.0"					):
																						for down_block in self.down_blocks:
																												_UpperCamelCase			:			Optional[Any]   			=						torch.utils.checkpoint.checkpoint(
																												    create_custom_forward(lowercase__					)       ,		lowercase__       ,		use_reentrant=lowercase__					)
																						# middle
																						_UpperCamelCase			:			List[Any]   			=						torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(self.mid_block					)       ,		lowercase__       ,		use_reentrant=lowercase__					)
																else:
																						for down_block in self.down_blocks:
																												_UpperCamelCase			:			List[str]   			=						torch.utils.checkpoint.checkpoint(create_custom_forward(lowercase__					)       ,		lowercase__					)
																						# middle
																						_UpperCamelCase			:			Union[str, Any]   			=						torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block					)       ,		lowercase__					)

										else:
																# down
																for down_block in self.down_blocks:
																						_UpperCamelCase			:			Tuple   			=						down_block(lowercase__					)

																# middle
																_UpperCamelCase			:			Optional[int]   			=						self.mid_block(lowercase__					)

										# post-process
										_UpperCamelCase			:			List[Any]   			=						self.conv_norm_out(lowercase__					)
										_UpperCamelCase			:			Tuple   			=						self.conv_act(lowercase__					)
										_UpperCamelCase			:			int   			=						self.conv_out(lowercase__					)

										return sample





class 		SCREAMING_SNAKE_CASE     (					nn.Module	):







				'''simple docstring'''





				def __init__(						self					:						Dict       ,		lowercase__					:						str=3       ,		lowercase__					:						List[Any]=3       ,		lowercase__					:						Optional[int]=("UpDecoderBlock2D",)       ,		lowercase__					:						Any=(64,)       ,		lowercase__					:						str=2       ,		lowercase__					:						List[Any]=32       ,		lowercase__					:						Optional[int]="silu"       ,		lowercase__					:						List[str]="group"       ,		)							->Any:


										'''simple docstring'''




										super().__init__()
										_UpperCamelCase			:			List[Any]   			=						layers_per_block

										_UpperCamelCase			:			Any   			=						nn.Convad(
										    lowercase__       ,		block_out_channels[-1]       ,		kernel_size=3       ,		stride=1       ,		padding=1       ,		)

										_UpperCamelCase			:			List[str]   			=						None
										_UpperCamelCase			:			Dict   			=						nn.ModuleList([]					)

										_UpperCamelCase			:			Optional[int]   			=						in_channels if norm_type == "spatial" else None

										# mid
										_UpperCamelCase			:			int   			=						UNetMidBlockaD(
										    in_channels=block_out_channels[-1]       ,		resnet_eps=1e-6       ,		resnet_act_fn=lowercase__       ,		output_scale_factor=1       ,		resnet_time_scale_shift="default" if norm_type == "group" else norm_type       ,		attention_head_dim=block_out_channels[-1]       ,		resnet_groups=lowercase__       ,		temb_channels=lowercase__       ,		)

										# up
										_UpperCamelCase			:			Dict   			=						list(reversed(lowercase__					)					)
										_UpperCamelCase			:			Tuple   			=						reversed_block_out_channels[0]
										for i, up_block_type in enumerate(lowercase__					):
																_UpperCamelCase			:			Union[str, Any]   			=						output_channel
																_UpperCamelCase			:			Dict   			=						reversed_block_out_channels[i]

																_UpperCamelCase			:			List[str]   			=						i == len(lowercase__					) - 1

																_UpperCamelCase			:			Tuple   			=						get_up_block(
																    lowercase__       ,		num_layers=self.layers_per_block + 1       ,		in_channels=lowercase__       ,		out_channels=lowercase__       ,		prev_output_channel=lowercase__       ,		add_upsample=not is_final_block       ,		resnet_eps=1e-6       ,		resnet_act_fn=lowercase__       ,		resnet_groups=lowercase__       ,		attention_head_dim=lowercase__       ,		temb_channels=lowercase__       ,		resnet_time_scale_shift=lowercase__       ,		)
																self.up_blocks.append(lowercase__					)
																_UpperCamelCase			:			Any   			=						output_channel

										# out
										if norm_type == "spatial":
																_UpperCamelCase			:			Any   			=						SpatialNorm(block_out_channels[0]       ,		lowercase__					)
										else:
																_UpperCamelCase			:			int   			=						nn.GroupNorm(num_channels=block_out_channels[0]       ,		num_groups=lowercase__       ,		eps=1e-6					)
										_UpperCamelCase			:			Tuple   			=						nn.SiLU()
										_UpperCamelCase			:			Tuple   			=						nn.Convad(block_out_channels[0]       ,		lowercase__       ,		3       ,		padding=1					)

										_UpperCamelCase			:			Optional[Any]   			=						False







				def  snake_case__				(						self					:						Tuple       ,		lowercase__					:						Union[str, Any]       ,		lowercase__					:						Optional[Any]=None					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			str   			=						z
										_UpperCamelCase			:			str   			=						self.conv_in(lowercase__					)

										_UpperCamelCase			:			Any   			=						next(iter(self.up_blocks.parameters()					)					).dtype
										if self.training and self.gradient_checkpointing:

																def create_custom_forward(lowercase__					:						Optional[int]					):
																						def custom_forward(*lowercase__					:						List[str]					):
																												return module(*lowercase__					)

																						return custom_forward

																if is_torch_version(">="       ,		"1.11.0"					):
																						# middle
																						_UpperCamelCase			:			Dict   			=						torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(self.mid_block					)       ,		lowercase__       ,		lowercase__       ,		use_reentrant=lowercase__					)
																						_UpperCamelCase			:			Union[str, Any]   			=						sample.to(lowercase__					)

																						# up
																						for up_block in self.up_blocks:
																												_UpperCamelCase			:			Dict   			=						torch.utils.checkpoint.checkpoint(
																												    create_custom_forward(lowercase__					)       ,		lowercase__       ,		lowercase__       ,		use_reentrant=lowercase__					)
																else:
																						# middle
																						_UpperCamelCase			:			Any   			=						torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(self.mid_block					)       ,		lowercase__       ,		lowercase__					)
																						_UpperCamelCase			:			int   			=						sample.to(lowercase__					)

																						# up
																						for up_block in self.up_blocks:
																												_UpperCamelCase			:			Dict   			=						torch.utils.checkpoint.checkpoint(create_custom_forward(lowercase__					)       ,		lowercase__       ,		lowercase__					)
										else:
																# middle
																_UpperCamelCase			:			str   			=						self.mid_block(lowercase__       ,		lowercase__					)
																_UpperCamelCase			:			int   			=						sample.to(lowercase__					)

																# up
																for up_block in self.up_blocks:
																						_UpperCamelCase			:			str   			=						up_block(lowercase__       ,		lowercase__					)

        # post-process
										if latent_embeds is None:
																_UpperCamelCase			:			Union[str, Any]   			=						self.conv_norm_out(lowercase__					)
										else:
																_UpperCamelCase			:			Any   			=						self.conv_norm_out(lowercase__       ,		lowercase__					)
										_UpperCamelCase			:			List[str]   			=						self.conv_act(lowercase__					)
										_UpperCamelCase			:			Dict   			=						self.conv_out(lowercase__					)

										return sample





class 		SCREAMING_SNAKE_CASE     (					nn.Module	):







				'''simple docstring'''





				def __init__(						self					:						Optional[int]       ,		lowercase__					:						str       ,		lowercase__					:						Tuple       ,		lowercase__					:						Optional[Any]       ,		lowercase__					:						Tuple=None       ,		lowercase__					:						Dict="random"       ,		lowercase__					:						List[Any]=False       ,		lowercase__					:						List[Any]=True					)							->Optional[int]:


										'''simple docstring'''




										super().__init__()
										_UpperCamelCase			:			List[Any]   			=						n_e
										_UpperCamelCase			:			List[str]   			=						vq_embed_dim
										_UpperCamelCase			:			List[str]   			=						beta
										_UpperCamelCase			:			Any   			=						legacy

										_UpperCamelCase			:			Optional[int]   			=						nn.Embedding(self.n_e       ,		self.vq_embed_dim					)
										self.embedding.weight.data.uniform_(-1.0 / self.n_e       ,		1.0 / self.n_e					)

										_UpperCamelCase			:			str   			=						remap
										if self.remap is not None:
																self.register_buffer("used"       ,		torch.tensor(np.load(self.remap					)					)					)
																_UpperCamelCase			:			List[Any]   			=						self.used.shape[0]
																_UpperCamelCase			:			Optional[int]   			=						unknown_index  # "random" or "extra" or integer
																if self.unknown_index == "extra":
																						_UpperCamelCase			:			Any   			=						self.re_embed
																						_UpperCamelCase			:			Any   			=						self.re_embed + 1
																print(
																    f'''Remapping {self.n_e} indices to {self.re_embed} indices. '''
																    f'''Using {self.unknown_index} for unknown indices.'''					)
										else:
																_UpperCamelCase			:			Optional[Any]   			=						n_e

										_UpperCamelCase			:			Optional[Any]   			=						sane_index_shape





				def  snake_case__				(						self					:						str       ,		lowercase__					:						Dict					)							->Optional[int]:


										'''simple docstring'''




										_UpperCamelCase			:			str   			=						inds.shape
										assert len(lowercase__					) > 1
										_UpperCamelCase			:			List[Any]   			=						inds.reshape(ishape[0]       ,		-1					)
										_UpperCamelCase			:			Tuple   			=						self.used.to(lowercase__					)
										_UpperCamelCase			:			List[str]   			=						(inds[:, :, None] == used[None, None, ...]).long()
										_UpperCamelCase			:			Optional[Any]   			=						match.argmax(-1					)
										_UpperCamelCase			:			int   			=						match.sum(2					) < 1
										if self.unknown_index == "random":
																_UpperCamelCase			:			int   			=						torch.randint(0       ,		self.re_embed       ,		size=new[unknown].shape					).to(device=new.device					)
										else:
																_UpperCamelCase			:			Optional[int]   			=						self.unknown_index
										return new.reshape(lowercase__					)





				def  snake_case__				(						self					:						Any       ,		lowercase__					:						Optional[Any]					)							->int:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						inds.shape
										assert len(lowercase__					) > 1
										_UpperCamelCase			:			Dict   			=						inds.reshape(ishape[0]       ,		-1					)
										_UpperCamelCase			:			Optional[Any]   			=						self.used.to(lowercase__					)
										if self.re_embed > self.used.shape[0]:  # extra token
																_UpperCamelCase			:			int   			=						0  # simply set to zero
										_UpperCamelCase			:			Tuple   			=						torch.gather(used[None, :][inds.shape[0] * [0], :]       ,		1       ,		lowercase__					)
										return back.reshape(lowercase__					)





				def  snake_case__				(						self					:						List[Any]       ,		lowercase__					:						Union[str, Any]					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Any   			=						z.permute(0       ,		2       ,		3       ,		1					).contiguous()
										_UpperCamelCase			:			Optional[Any]   			=						z.view(-1       ,		self.vq_embed_dim					)

										# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
										_UpperCamelCase			:			Optional[Any]   			=						torch.argmin(torch.cdist(lowercase__       ,		self.embedding.weight					)       ,		dim=1					)

										_UpperCamelCase			:			List[str]   			=						self.embedding(lowercase__					).view(z.shape					)
										_UpperCamelCase			:			Optional[int]   			=						None
										_UpperCamelCase			:			Tuple   			=						None

										# compute loss for embedding
										if not self.legacy:
																_UpperCamelCase			:			Any   			=						self.beta * torch.mean((z_q.detach() - z) ** 2					) + torch.mean((z_q - z.detach()) ** 2					)
										else:
																_UpperCamelCase			:			str   			=						torch.mean((z_q.detach() - z) ** 2					) + self.beta * torch.mean((z_q - z.detach()) ** 2					)

										# preserve gradients
										_UpperCamelCase			:			List[Any]   			=						z + (z_q - z).detach()

										# reshape back to match original input shape
										_UpperCamelCase			:			List[Any]   			=						z_q.permute(0       ,		3       ,		1       ,		2					).contiguous()

										if self.remap is not None:
																_UpperCamelCase			:			str   			=						min_encoding_indices.reshape(z.shape[0]       ,		-1					)  # add batch axis
																_UpperCamelCase			:			int   			=						self.remap_to_used(lowercase__					)
																_UpperCamelCase			:			List[str]   			=						min_encoding_indices.reshape(-1       ,		1					)  # flatten

										if self.sane_index_shape:
																_UpperCamelCase			:			Tuple   			=						min_encoding_indices.reshape(z_q.shape[0]       ,		z_q.shape[2]       ,		z_q.shape[3]					)

										return z_q, loss, (perplexity, min_encodings, min_encoding_indices)







				def  snake_case__				(						self					:						Optional[Any]       ,		lowercase__					:						List[str]       ,		lowercase__					:						List[str]					)							->Dict:


										'''simple docstring'''




										if self.remap is not None:
																_UpperCamelCase			:			Tuple   			=						indices.reshape(shape[0]       ,		-1					)  # add batch axis
																_UpperCamelCase			:			str   			=						self.unmap_to_all(lowercase__					)
																_UpperCamelCase			:			str   			=						indices.reshape(-1					)  # flatten again

										# get quantized latent vectors
										_UpperCamelCase			:			Dict   			=						self.embedding(lowercase__					)

										if shape is not None:
																_UpperCamelCase			:			List[Any]   			=						z_q.view(lowercase__					)
																# reshape back to match original input shape
																_UpperCamelCase			:			Optional[int]   			=						z_q.permute(0       ,		3       ,		1       ,		2					).contiguous()

										return z_q





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				def __init__(						self					:						Dict       ,		lowercase__					:						str       ,		lowercase__					:						List[Any]=False					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						parameters
										_UpperCamelCase			,       _UpperCamelCase			:			Tuple   			=						torch.chunk(lowercase__       ,		2       ,		dim=1					)
										_UpperCamelCase			:			str   			=						torch.clamp(self.logvar       ,		-3_0.0       ,		2_0.0					)
										_UpperCamelCase			:			str   			=						deterministic
										_UpperCamelCase			:			Optional[Any]   			=						torch.exp(0.5 * self.logvar					)
										_UpperCamelCase			:			Optional[Any]   			=						torch.exp(self.logvar					)
										if self.deterministic:
																_UpperCamelCase			:			Optional[Any]   			=						torch.zeros_like(
																    self.mean       ,		device=self.parameters.device       ,		dtype=self.parameters.dtype					)





				def  snake_case__				(						self					:						Any       ,		lowercase__					:						Optional[torch.Generator] = None					)							->torch.FloatTensor:


										'''simple docstring'''




										_UpperCamelCase			:			Union[str, Any]   			=						randn_tensor(
										    self.mean.shape       ,		generator=lowercase__       ,		device=self.parameters.device       ,		dtype=self.parameters.dtype					)
										_UpperCamelCase			:			Optional[int]   			=						self.mean + self.std * sample
										return x





				def  snake_case__				(						self					:						str       ,		lowercase__					:						Optional[int]=None					)							->List[str]:


										'''simple docstring'''




										if self.deterministic:
																return torch.Tensor([0.0]					)
										else:
																if other is None:
																						return 0.5 * torch.sum(torch.pow(self.mean       ,		2					) + self.var - 1.0 - self.logvar       ,		dim=[1, 2, 3]					)
																else:
																						return 0.5 * torch.sum(
																						    torch.pow(self.mean - other.mean       ,		2					) / other.var
																						    + self.var / other.var
																						    - 1.0
																						    - self.logvar
																						    + other.logvar       ,		dim=[1, 2, 3]       ,		)





				def  snake_case__				(						self					:						List[Any]       ,		lowercase__					:						str       ,		lowercase__					:						List[Any]=[1, 2, 3]					)							->Dict:


										'''simple docstring'''




										if self.deterministic:
																return torch.Tensor([0.0]					)
										_UpperCamelCase			:			Optional[Any]   			=						np.log(2.0 * np.pi					)
										return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean       ,		2					) / self.var       ,		dim=lowercase__					)







				def  snake_case__				(						self					:						List[Any]					)							->str:


										'''simple docstring'''




										return self.mean


