'''simple docstring'''





from ..utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_scipy_available,
    is_torch_available,
    is_torchsde_available,
)


try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			from ..utils.dummy_pt_objects import *  # noqa F403
else:
			from .scheduling_consistency_models import CMStochasticIterativeScheduler
			from .scheduling_ddim import DDIMScheduler
			from .scheduling_ddim_inverse import DDIMInverseScheduler
			from .scheduling_ddim_parallel import DDIMParallelScheduler
			from .scheduling_ddpm import DDPMScheduler
			from .scheduling_ddpm_parallel import DDPMParallelScheduler
			from .scheduling_deis_multistep import DEISMultistepScheduler
			from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler
			from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler
			from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler
			from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler
			from .scheduling_euler_discrete import EulerDiscreteScheduler
			from .scheduling_heun_discrete import HeunDiscreteScheduler
			from .scheduling_ipndm import IPNDMScheduler
			from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler
			from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler
			from .scheduling_karras_ve import KarrasVeScheduler
			from .scheduling_pndm import PNDMScheduler
			from .scheduling_repaint import RePaintScheduler
			from .scheduling_sde_ve import ScoreSdeVeScheduler
			from .scheduling_sde_vp import ScoreSdeVpScheduler
			from .scheduling_unclip import UnCLIPScheduler
			from .scheduling_unipc_multistep import UniPCMultistepScheduler
			from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
			from .scheduling_vq_diffusion import VQDiffusionScheduler

try:
			if not is_flax_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			from ..utils.dummy_flax_objects import *  # noqa F403
else:
			from .scheduling_ddim_flax import FlaxDDIMScheduler
			from .scheduling_ddpm_flax import FlaxDDPMScheduler
			from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler
			from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler
			from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler
			from .scheduling_pndm_flax import FlaxPNDMScheduler
			from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler
			from .scheduling_utils_flax import (
			    FlaxKarrasDiffusionSchedulers,
			    FlaxSchedulerMixin,
			    FlaxSchedulerOutput,
			    broadcast_to_shape_from_left,
			)


try:
			if not (is_torch_available() and is_scipy_available()):
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			from ..utils.dummy_torch_and_scipy_objects import *  # noqa F403
else:
			from .scheduling_lms_discrete import LMSDiscreteScheduler

try:
			if not (is_torch_available() and is_torchsde_available()):
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			from ..utils.dummy_torch_and_torchsde_objects import *  # noqa F403
else:
			from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler



'''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


