



from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block

@dataclass
class 			__snake_case   ( _lowerCamelCase):







							'''simple docstring'''






							UpperCamelCase__					:   List[Any]       =       4_2




class 			__snake_case   ( _lowerCamelCase      ,_lowerCamelCase):







							'''simple docstring'''






							@register_to_config
							def __init__(				self	,	a_ = None	,	a_ = 3	,	a_ = 3	,	a_ = False	,	a_ = "positional"	,	a_ = 0	,	a_ = True	,	a_ = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")	,	a_ = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")	,	a_ = (224, 448, 672, 896)	,	a_ = 2	,	a_ = 1	,	a_ = 1	,	a_ = "conv"	,	a_ = "conv"	,	a_ = "silu"	,	a_ = 8	,	a_ = 32	,	a_ = 1E-5	,	a_ = "default"	,	a_ = True	,	a_ = None	,	a_ = None	,	):
											super().__init__()

											a__					   =		sample_size
											a__					   =		block_out_channels[0] * 4

											# Check inputs
											if len(__UpperCamelCase		) != len(__UpperCamelCase		):
															raise ValueError(
															    F'''Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}.'''		)

											if len(__UpperCamelCase		) != len(__UpperCamelCase		):
															raise ValueError(
															    F'''Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.'''		)

											# input
											a__					   =		nn.Convad(__UpperCamelCase	,	block_out_channels[0]	,	kernel_size=3	,	padding=(1, 1)		)

											# time
											if time_embedding_type == "fourier":
															a__					   =		GaussianFourierProjection(embedding_size=block_out_channels[0]	,	scale=16		)
															a__					   =		2 * block_out_channels[0]
											elif time_embedding_type == "positional":
															a__					   =		Timesteps(block_out_channels[0]	,	__UpperCamelCase	,	__UpperCamelCase		)
															a__					   =		block_out_channels[0]

											a__					   =		TimestepEmbedding(__UpperCamelCase	,	__UpperCamelCase		)

											# class embedding
											if class_embed_type is None and num_class_embeds is not None:
															a__					   =		nn.Embedding(__UpperCamelCase	,	__UpperCamelCase		)
											elif class_embed_type == "timestep":
															a__					   =		TimestepEmbedding(__UpperCamelCase	,	__UpperCamelCase		)
											elif class_embed_type == "identity":
															a__					   =		nn.Identity(__UpperCamelCase	,	__UpperCamelCase		)
											else:
															a__					   =		None

											a__					   =		nn.ModuleList([]		)
											a__					   =		None
											a__					   =		nn.ModuleList([]		)

											# down
											a__					   =		block_out_channels[0]
											for i, down_block_type in enumerate(__UpperCamelCase		):
															a__					   =		output_channel
															a__					   =		block_out_channels[i]
															a__					   =		i == len(__UpperCamelCase		) - 1

															a__					   =		get_down_block(
															    __UpperCamelCase	,	num_layers=__UpperCamelCase	,	in_channels=__UpperCamelCase	,	out_channels=__UpperCamelCase	,	temb_channels=__UpperCamelCase	,	add_downsample=not is_final_block	,	resnet_eps=__UpperCamelCase	,	resnet_act_fn=__UpperCamelCase	,	resnet_groups=__UpperCamelCase	,	attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel	,	downsample_padding=__UpperCamelCase	,	resnet_time_scale_shift=__UpperCamelCase	,	downsample_type=__UpperCamelCase	,	)
															self.down_blocks.append(__UpperCamelCase		)

											# mid
											a__					   =		UNetMidBlockaD(
											    in_channels=block_out_channels[-1]	,	temb_channels=__UpperCamelCase	,	resnet_eps=__UpperCamelCase	,	resnet_act_fn=__UpperCamelCase	,	output_scale_factor=__UpperCamelCase	,	resnet_time_scale_shift=__UpperCamelCase	,	attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1]	,	resnet_groups=__UpperCamelCase	,	add_attention=__UpperCamelCase	,	)

											# up
											a__					   =		list(reversed(__UpperCamelCase		)		)
											a__					   =		reversed_block_out_channels[0]
											for i, up_block_type in enumerate(__UpperCamelCase		):
															a__					   =		output_channel
															a__					   =		reversed_block_out_channels[i]
															a__					   =		reversed_block_out_channels[min(i + 1	,	len(__UpperCamelCase		) - 1		)]

															a__					   =		i == len(__UpperCamelCase		) - 1

															a__					   =		get_up_block(
															    __UpperCamelCase	,	num_layers=layers_per_block + 1	,	in_channels=__UpperCamelCase	,	out_channels=__UpperCamelCase	,	prev_output_channel=__UpperCamelCase	,	temb_channels=__UpperCamelCase	,	add_upsample=not is_final_block	,	resnet_eps=__UpperCamelCase	,	resnet_act_fn=__UpperCamelCase	,	resnet_groups=__UpperCamelCase	,	attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel	,	resnet_time_scale_shift=__UpperCamelCase	,	upsample_type=__UpperCamelCase	,	)
															self.up_blocks.append(__UpperCamelCase		)
															a__					   =		output_channel

											# out
											a__					   =		norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4	,	32		)
											a__					   =		nn.GroupNorm(num_channels=block_out_channels[0]	,	num_groups=__UpperCamelCase	,	eps=__UpperCamelCase		)
											a__					   =		nn.SiLU()
											a__					   =		nn.Convad(block_out_channels[0]	,	__UpperCamelCase	,	kernel_size=3	,	padding=1		)







							def _a   (				self	,	a_	,	a_	,	a_ = None	,	a_ = True	,	):







											if self.config.center_input_sample:
															a__					   =		2 * sample - 1.0

											# 1. time
											a__					   =		timestep
											if not torch.is_tensor(__UpperCamelCase		):
															a__					   =		torch.tensor([timesteps]	,	dtype=torch.long	,	device=sample.device		)
											elif torch.is_tensor(__UpperCamelCase		) and len(timesteps.shape		) == 0:
															a__					   =		timesteps[None].to(sample.device		)

											# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
											a__					   =		timesteps * torch.ones(sample.shape[0]	,	dtype=timesteps.dtype	,	device=timesteps.device		)

											a__					   =		self.time_proj(__UpperCamelCase		)

											# timesteps does not contain any weights and will always return f32 tensors
											# but time_embedding might actually be running in fp16. so we need to cast here.
											# there might be better ways to encapsulate this.
											a__					   =		t_emb.to(dtype=self.dtype		)
											a__					   =		self.time_embedding(__UpperCamelCase		)

											if self.class_embedding is not None:
															if class_labels is None:
																			raise ValueError("""class_labels should be provided when doing class conditioning"""		)

															if self.config.class_embed_type == "timestep":
																			a__					   =		self.time_proj(__UpperCamelCase		)

															a__					   =		self.class_embedding(__UpperCamelCase		).to(dtype=self.dtype		)
															a__					   =		emb + class_emb

											# 2. pre-process
											a__					   =		sample
											a__					   =		self.conv_in(__UpperCamelCase		)

											# 3. down
											a__					   =		(sample,)
											for downsample_block in self.down_blocks:
															if hasattr(__UpperCamelCase	,	"""skip_conv"""		):
																			a__					   =		downsample_block(
																			    hidden_states=__UpperCamelCase	,	temb=__UpperCamelCase	,	skip_sample=__UpperCamelCase		)
															else:
																			a__					   =		downsample_block(hidden_states=__UpperCamelCase	,	temb=__UpperCamelCase		)

															down_block_res_samples += res_samples

											# 4. mid
											a__					   =		self.mid_block(__UpperCamelCase	,	__UpperCamelCase		)

											# 5. up
											a__					   =		None
											for upsample_block in self.up_blocks:
															a__					   =		down_block_res_samples[-len(upsample_block.resnets		) :]
															a__					   =		down_block_res_samples[: -len(upsample_block.resnets		)]

															if hasattr(__UpperCamelCase	,	"""skip_conv"""		):
																			a__					   =		upsample_block(__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase		)
															else:
																			a__					   =		upsample_block(__UpperCamelCase	,	__UpperCamelCase	,	__UpperCamelCase		)

        # 6. post-process
											a__					   =		self.conv_norm_out(__UpperCamelCase		)
											a__					   =		self.conv_act(__UpperCamelCase		)
											a__					   =		self.conv_out(__UpperCamelCase		)

											if skip_sample is not None:
															sample += skip_sample

											if self.config.time_embedding_type == "fourier":
															a__					   =		timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]		)))		)
															a__					   =		sample / timesteps

											if not return_dict:
															return (sample,)

											return UNetaDOutput(sample=__UpperCamelCase		)


from ...utils import is_transformers_available
from .pipeline_latent_diffusion_superresolution import LDMSuperResolutionPipeline


if is_transformers_available():
				from .pipeline_latent_diffusion import LDMBertModel, LDMTextToImagePipeline


