





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    lowerCAmelCase							(					__UpperCamelCase			):
 UpperCAmelCase__													=		42


class    lowerCAmelCase							(					nn.Module			):
 def __init__(      self  :      Tuple			,     UpperCAmelCase  :      Dict=3			,     UpperCAmelCase  :      Union[str, Any]=3			,     UpperCAmelCase  :      Optional[Any]=("DownEncoderBlock2D",)			,     UpperCAmelCase  :      List[str]=(64,)			,     UpperCAmelCase  :      Any=2			,     UpperCAmelCase  :      List[Any]=32			,     UpperCAmelCase  :      List[str]="silu"			,     UpperCAmelCase  :      Tuple=True			,     )			->	Tuple:
     super().__init__()
     lowerCamelCase__    :      Optional[Any]					 =		layers_per_block

     lowerCamelCase__    :      Dict					 =		torch.nn.Convad(
         UpperCAmelCase			,     block_out_channels[0]			,     kernel_size=3			,     stride=1			,     padding=1			,     )

     lowerCamelCase__    :      Tuple					 =		None
     lowerCamelCase__    :      Union[str, Any]					 =		nn.ModuleList([]	)

     # down
     lowerCamelCase__    :      Tuple					 =		block_out_channels[0]
     for i, down_block_type in enumerate(UpperCAmelCase	):
         lowerCamelCase__    :      List[Any]					 =		output_channel
         lowerCamelCase__    :      Dict					 =		block_out_channels[i]
         lowerCamelCase__    :      int					 =		i == len(UpperCAmelCase	) - 1

         lowerCamelCase__    :      int					 =		get_down_block(
             UpperCAmelCase			,     num_layers=self.layers_per_block			,     in_channels=UpperCAmelCase			,     out_channels=UpperCAmelCase			,     add_downsample=not is_final_block			,     resnet_eps=1e-6			,     downsample_padding=0			,     resnet_act_fn=UpperCAmelCase			,     resnet_groups=UpperCAmelCase			,     attention_head_dim=UpperCAmelCase			,     temb_channels=UpperCAmelCase			,     )
         self.down_blocks.append(UpperCAmelCase	)

     # mid
     lowerCamelCase__    :      Tuple					 =		UNetMidBlockaD(
         in_channels=block_out_channels[-1]			,     resnet_eps=1e-6			,     resnet_act_fn=UpperCAmelCase			,     output_scale_factor=1			,     resnet_time_scale_shift='default'			,     attention_head_dim=block_out_channels[-1]			,     resnet_groups=UpperCAmelCase			,     temb_channels=UpperCAmelCase			,     )

     # out
     lowerCamelCase__    :      Optional[Any]					 =		nn.GroupNorm(num_channels=block_out_channels[-1]			,     num_groups=UpperCAmelCase			,     eps=1e-6	)
     lowerCamelCase__    :      List[Any]					 =		nn.SiLU()

     lowerCamelCase__    :      List[str]					 =		2 * out_channels if double_z else out_channels
     lowerCamelCase__    :      Any					 =		nn.Convad(block_out_channels[-1]			,     UpperCAmelCase			,     3			,     padding=1	)

     lowerCamelCase__    :      List[Any]					 =		False







 def      A_	(      self  :      Dict			,     UpperCAmelCase  :      Optional[int]	)			->	Union[str, Any]:
     lowerCamelCase__    :      Dict					 =		x
     lowerCamelCase__    :      Dict					 =		self.conv_in(UpperCAmelCase	)

     if self.training and self.gradient_checkpointing:

         def create_custom_forward(UpperCAmelCase  :      Dict	):
             def custom_forward(*UpperCAmelCase  :      Any	):
                 return module(*UpperCAmelCase	)

             return custom_forward

         # down
         if is_torch_version('>='			,     '1.11.0'	):
             for down_block in self.down_blocks:
                 lowerCamelCase__    :      Optional[Any]					 =		torch.utils.checkpoint.checkpoint(
                     create_custom_forward(UpperCAmelCase	)			,     UpperCAmelCase			,     use_reentrant=UpperCAmelCase	)
             # middle
             lowerCamelCase__    :      Tuple					 =		torch.utils.checkpoint.checkpoint(
                 create_custom_forward(self.mid_block	)			,     UpperCAmelCase			,     use_reentrant=UpperCAmelCase	)
         else:
             for down_block in self.down_blocks:
                 lowerCamelCase__    :      str					 =		torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCAmelCase	)			,     UpperCAmelCase	)
             # middle
             lowerCamelCase__    :      Dict					 =		torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block	)			,     UpperCAmelCase	)

     else:
         # down
         for down_block in self.down_blocks:
             lowerCamelCase__    :      Optional[Any]					 =		down_block(UpperCAmelCase	)

         # middle
         lowerCamelCase__    :      List[str]					 =		self.mid_block(UpperCAmelCase	)

     # post-process
     lowerCamelCase__    :      str					 =		self.conv_norm_out(UpperCAmelCase	)
     lowerCamelCase__    :      List[Any]					 =		self.conv_act(UpperCAmelCase	)
     lowerCamelCase__    :      Union[str, Any]					 =		self.conv_out(UpperCAmelCase	)

     return sample


class    lowerCAmelCase							(					nn.Module			):
 def __init__(      self  :      Any			,     UpperCAmelCase  :      Optional[int]=3			,     UpperCAmelCase  :      List[Any]=3			,     UpperCAmelCase  :      int=("UpDecoderBlock2D",)			,     UpperCAmelCase  :      Optional[Any]=(64,)			,     UpperCAmelCase  :      str=2			,     UpperCAmelCase  :      Union[str, Any]=32			,     UpperCAmelCase  :      int="silu"			,     UpperCAmelCase  :      List[str]="group"			,     )			->	Any:
     super().__init__()
     lowerCamelCase__    :      List[str]					 =		layers_per_block

     lowerCamelCase__    :      Optional[Any]					 =		nn.Convad(
         UpperCAmelCase			,     block_out_channels[-1]			,     kernel_size=3			,     stride=1			,     padding=1			,     )

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

     lowerCamelCase__    :      Dict					 =		in_channels if norm_type == 'spatial' else None

     # mid
     lowerCamelCase__    :      List[Any]					 =		UNetMidBlockaD(
         in_channels=block_out_channels[-1]			,     resnet_eps=1e-6			,     resnet_act_fn=UpperCAmelCase			,     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=UpperCAmelCase			,     temb_channels=UpperCAmelCase			,     )

     # up
     lowerCamelCase__    :      Tuple					 =		list(reversed(UpperCAmelCase	)	)
     lowerCamelCase__    :      Dict					 =		reversed_block_out_channels[0]
     for i, up_block_type in enumerate(UpperCAmelCase	):
         lowerCamelCase__    :      Dict					 =		output_channel
         lowerCamelCase__    :      List[Any]					 =		reversed_block_out_channels[i]

         lowerCamelCase__    :      Union[str, Any]					 =		i == len(UpperCAmelCase	) - 1

         lowerCamelCase__    :      Union[str, Any]					 =		get_up_block(
             UpperCAmelCase			,     num_layers=self.layers_per_block + 1			,     in_channels=UpperCAmelCase			,     out_channels=UpperCAmelCase			,     prev_output_channel=UpperCAmelCase			,     add_upsample=not is_final_block			,     resnet_eps=1e-6			,     resnet_act_fn=UpperCAmelCase			,     resnet_groups=UpperCAmelCase			,     attention_head_dim=UpperCAmelCase			,     temb_channels=UpperCAmelCase			,     resnet_time_scale_shift=UpperCAmelCase			,     )
         self.up_blocks.append(UpperCAmelCase	)
         lowerCamelCase__    :      str					 =		output_channel

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

     lowerCamelCase__    :      Dict					 =		False







 def      A_	(      self  :      Tuple			,     UpperCAmelCase  :      Tuple			,     UpperCAmelCase  :      Any=None	)			->	List[str]:
     lowerCamelCase__    :      Any					 =		z
     lowerCamelCase__    :      Union[str, Any]					 =		self.conv_in(UpperCAmelCase	)

     lowerCamelCase__    :      Optional[int]					 =		next(iter(self.up_blocks.parameters()	)	).dtype
     if self.training and self.gradient_checkpointing:

         def create_custom_forward(UpperCAmelCase  :      Any	):
             def custom_forward(*UpperCAmelCase  :      Any	):
                 return module(*UpperCAmelCase	)

             return custom_forward

         if is_torch_version('>='			,     '1.11.0'	):
             # middle
             lowerCamelCase__    :      str					 =		torch.utils.checkpoint.checkpoint(
                 create_custom_forward(self.mid_block	)			,     UpperCAmelCase			,     UpperCAmelCase			,     use_reentrant=UpperCAmelCase	)
             lowerCamelCase__    :      Tuple					 =		sample.to(UpperCAmelCase	)

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

             # up
             for up_block in self.up_blocks:
                 lowerCamelCase__    :      Tuple					 =		torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCAmelCase	)			,     UpperCAmelCase			,     UpperCAmelCase	)
     else:
         # middle
         lowerCamelCase__    :      Any					 =		self.mid_block(UpperCAmelCase			,     UpperCAmelCase	)
         lowerCamelCase__    :      Optional[int]					 =		sample.to(UpperCAmelCase	)

         # up
         for up_block in self.up_blocks:
             lowerCamelCase__    :      List[Any]					 =		up_block(UpperCAmelCase			,     UpperCAmelCase	)

        # post-process
     if latent_embeds is None:
         lowerCamelCase__    :      str					 =		self.conv_norm_out(UpperCAmelCase	)
     else:
         lowerCamelCase__    :      Optional[Any]					 =		self.conv_norm_out(UpperCAmelCase			,     UpperCAmelCase	)
     lowerCamelCase__    :      List[str]					 =		self.conv_act(UpperCAmelCase	)
     lowerCamelCase__    :      Optional[Any]					 =		self.conv_out(UpperCAmelCase	)

     return sample


class    lowerCAmelCase							(					nn.Module			):
 def __init__(      self  :      Dict			,     UpperCAmelCase  :      str			,     UpperCAmelCase  :      Optional[int]			,     UpperCAmelCase  :      Optional[Any]			,     UpperCAmelCase  :      str=None			,     UpperCAmelCase  :      Optional[Any]="random"			,     UpperCAmelCase  :      Optional[int]=False			,     UpperCAmelCase  :      List[Any]=True	)			->	Optional[int]:
     super().__init__()
     lowerCamelCase__    :      int					 =		n_e
     lowerCamelCase__    :      Any					 =		vq_embed_dim
     lowerCamelCase__    :      Optional[int]					 =		beta
     lowerCamelCase__    :      Optional[Any]					 =		legacy

     lowerCamelCase__    :      Any					 =		nn.Embedding(self.n_e			,     self.vq_embed_dim	)
     self.embedding.weight.data.uniform_(-1.0 / self.n_e			,     1.0 / self.n_e	)

     lowerCamelCase__    :      Any					 =		remap
     if self.remap is not None:
         self.register_buffer('used'			,     torch.tensor(np.load(self.remap	)	)	)
         lowerCamelCase__    :      str					 =		self.used.shape[0]
         lowerCamelCase__    :      Any					 =		unknown_index  # "random" or "extra" or integer
         if self.unknown_index == "extra":
             lowerCamelCase__    :      List[Any]					 =		self.re_embed
             lowerCamelCase__    :      List[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:
         lowerCamelCase__    :      List[Any]					 =		n_e

     lowerCamelCase__    :      Optional[Any]					 =		sane_index_shape
 def      A_	(      self  :      Union[str, Any]			,     UpperCAmelCase  :      Any	)			->	Dict:
     lowerCamelCase__    :      Any					 =		inds.shape
     assert len(UpperCAmelCase	) > 1
     lowerCamelCase__    :      str					 =		inds.reshape(ishape[0]			,     -1	)
     lowerCamelCase__    :      str					 =		self.used.to(UpperCAmelCase	)
     lowerCamelCase__    :      Dict					 =		(inds[:, :, None] == used[None, None, ...]).long()
     lowerCamelCase__    :      Optional[int]					 =		match.argmax(-1	)
     lowerCamelCase__    :      Dict					 =		match.sum(2	) < 1
     if self.unknown_index == "random":
         lowerCamelCase__    :      Optional[int]					 =		torch.randint(0			,     self.re_embed			,     size=new[unknown].shape	).to(device=new.device	)
     else:
         lowerCamelCase__    :      int					 =		self.unknown_index
     return new.reshape(UpperCAmelCase	)
 def      A_	(      self  :      List[str]			,     UpperCAmelCase  :      Tuple	)			->	Optional[int]:
     lowerCamelCase__    :      List[Any]					 =		inds.shape
     assert len(UpperCAmelCase	) > 1
     lowerCamelCase__    :      List[Any]					 =		inds.reshape(ishape[0]			,     -1	)
     lowerCamelCase__    :      str					 =		self.used.to(UpperCAmelCase	)
     if self.re_embed > self.used.shape[0]:  # extra token
         lowerCamelCase__    :      Any					 =		0  # simply set to zero
     lowerCamelCase__    :      Any					 =		torch.gather(used[None, :][inds.shape[0] * [0], :]			,     1			,     UpperCAmelCase	)
     return back.reshape(UpperCAmelCase	)
 def      A_	(      self  :      Tuple			,     UpperCAmelCase  :      Union[str, Any]	)			->	Optional[int]:
     # reshape z -> (batch, height, width, channel) and flatten
     lowerCamelCase__    :      Tuple					 =		z.permute(0			,     2			,     3			,     1	).contiguous()
     lowerCamelCase__    :      List[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
     lowerCamelCase__    :      List[str]					 =		torch.argmin(torch.cdist(UpperCAmelCase			,     self.embedding.weight	)			,     dim=1	)

     lowerCamelCase__    :      Optional[Any]					 =		self.embedding(UpperCAmelCase	).view(z.shape	)
     lowerCamelCase__    :      int					 =		None
     lowerCamelCase__    :      Union[str, Any]					 =		None

     # compute loss for embedding
     if not self.legacy:
         lowerCamelCase__    :      Dict					 =		self.beta * torch.mean((z_q.detach() - z) ** 2	) + torch.mean((z_q - z.detach()) ** 2	)
     else:
         lowerCamelCase__    :      List[str]					 =		torch.mean((z_q.detach() - z) ** 2	) + self.beta * torch.mean((z_q - z.detach()) ** 2	)

     # preserve gradients
     lowerCamelCase__    :      Union[str, Any]					 =		z + (z_q - z).detach()

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

     if self.remap is not None:
         lowerCamelCase__    :      int					 =		min_encoding_indices.reshape(z.shape[0]			,     -1	)  # add batch axis
         lowerCamelCase__    :      Union[str, Any]					 =		self.remap_to_used(UpperCAmelCase	)
         lowerCamelCase__    :      Optional[int]					 =		min_encoding_indices.reshape(-1			,     1	)  # flatten

     if self.sane_index_shape:
         lowerCamelCase__    :      Any					 =		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      A_	(      self  :      int			,     UpperCAmelCase  :      Dict			,     UpperCAmelCase  :      List[Any]	)			->	List[Any]:
     # shape specifying (batch, height, width, channel)
     if self.remap is not None:
         lowerCamelCase__    :      str					 =		indices.reshape(shape[0]			,     -1	)  # add batch axis
         lowerCamelCase__    :      Optional[Any]					 =		self.unmap_to_all(UpperCAmelCase	)
         lowerCamelCase__    :      Union[str, Any]					 =		indices.reshape(-1	)  # flatten again

     # get quantized latent vectors
     lowerCamelCase__    :      str					 =		self.embedding(UpperCAmelCase	)

     if shape is not None:
         lowerCamelCase__    :      List[str]					 =		z_q.view(UpperCAmelCase	)
         # reshape back to match original input shape
         lowerCamelCase__    :      Union[str, Any]					 =		z_q.permute(0			,     3			,     1			,     2	).contiguous()

     return z_q


class    lowerCAmelCase							(					__UpperCamelCase			):
 def __init__(      self  :      Any			,     UpperCAmelCase  :      Tuple			,     UpperCAmelCase  :      List[Any]=False	)			->	List[str]:
     lowerCamelCase__    :      List[str]					 =		parameters
     lowerCamelCase__ ,							lowerCamelCase__    :      List[str]					 =		torch.chunk(UpperCAmelCase			,     2			,     dim=1	)
     lowerCamelCase__    :      Union[str, Any]					 =		torch.clamp(self.logvar			,     -3_0.0			,     2_0.0	)
     lowerCamelCase__    :      List[Any]					 =		deterministic
     lowerCamelCase__    :      Optional[int]					 =		torch.exp(0.5 * self.logvar	)
     lowerCamelCase__    :      Optional[Any]					 =		torch.exp(self.logvar	)
     if self.deterministic:
         lowerCamelCase__    :      str					 =		torch.zeros_like(
             self.mean			,     device=self.parameters.device			,     dtype=self.parameters.dtype	)
 def      A_	(      self  :      List[str]			,     UpperCAmelCase  :      Optional[torch.Generator] = None	)			->	torch.FloatTensor:
     # make sure sample is on the same device as the parameters and has same dtype
     lowerCamelCase__    :      Any					 =		randn_tensor(
         self.mean.shape			,     generator=UpperCAmelCase			,     device=self.parameters.device			,     dtype=self.parameters.dtype	)
     lowerCamelCase__    :      Optional[int]					 =		self.mean + self.std * sample
     return x
 def      A_	(      self  :      Dict			,     UpperCAmelCase  :      Optional[Any]=None	)			->	Optional[Any]:
     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      A_	(      self  :      str			,     UpperCAmelCase  :      int			,     UpperCAmelCase  :      List[Any]=[1, 2, 3]	)			->	List[str]:
     if self.deterministic:
         return torch.Tensor([0.0]	)
     lowerCamelCase__    :      int					 =		np.log(2.0 * np.pi	)
     return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean			,     2	) / self.var			,     dim=UpperCAmelCase	)







 def      A_	(      self  :      Optional[int]	)			->	List[str]:
     return self.mean












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 get_down_block, get_mid_block, get_out_block, get_up_block

@dataclass
class    lowerCAmelCase							(					__UpperCamelCase			):
 UpperCAmelCase__													=		42


class    lowerCAmelCase							(					__UpperCamelCase,  __UpperCamelCase			):
 @register_to_config
 def __init__(      self  :      List[str]			,     UpperCAmelCase  :      int = 65536			,     UpperCAmelCase  :      Optional[int] = None			,     UpperCAmelCase  :      int = 2			,     UpperCAmelCase  :      int = 2			,     UpperCAmelCase  :      int = 0			,     UpperCAmelCase  :      str = "fourier"			,     UpperCAmelCase  :      bool = True			,     UpperCAmelCase  :      bool = False			,     UpperCAmelCase  :      float = 0.0			,     UpperCAmelCase  :      Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")			,     UpperCAmelCase  :      Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")			,     UpperCAmelCase  :      Tuple[str] = "UNetMidBlock1D"			,     UpperCAmelCase  :      str = None			,     UpperCAmelCase  :      Tuple[int] = (32, 32, 64)			,     UpperCAmelCase  :      str = None			,     UpperCAmelCase  :      int = 8			,     UpperCAmelCase  :      int = 1			,     UpperCAmelCase  :      bool = False			,     )			->	List[Any]:
     super().__init__()
     lowerCamelCase__    :      Optional[int]					 =		sample_size

     # time
     if time_embedding_type == "fourier":
         lowerCamelCase__    :      Optional[Any]					 =		GaussianFourierProjection(
             embedding_size=8			,     set_W_to_weight=UpperCAmelCase			,     log=UpperCAmelCase			,     flip_sin_to_cos=UpperCAmelCase	)
         lowerCamelCase__    :      Any					 =		2 * block_out_channels[0]
     elif time_embedding_type == "positional":
         lowerCamelCase__    :      List[Any]					 =		Timesteps(
             block_out_channels[0]			,     flip_sin_to_cos=UpperCAmelCase			,     downscale_freq_shift=UpperCAmelCase	)
         lowerCamelCase__    :      Dict					 =		block_out_channels[0]

     if use_timestep_embedding:
         lowerCamelCase__    :      str					 =		block_out_channels[0] * 4
         lowerCamelCase__    :      List[Any]					 =		TimestepEmbedding(
             in_channels=UpperCAmelCase			,     time_embed_dim=UpperCAmelCase			,     act_fn=UpperCAmelCase			,     out_dim=block_out_channels[0]			,     )

     lowerCamelCase__    :      Any					 =		nn.ModuleList([]	)
     lowerCamelCase__    :      Tuple					 =		None
     lowerCamelCase__    :      List[str]					 =		nn.ModuleList([]	)
     lowerCamelCase__    :      Optional[int]					 =		None

     # down
     lowerCamelCase__    :      Optional[int]					 =		in_channels
     for i, down_block_type in enumerate(UpperCAmelCase	):
         lowerCamelCase__    :      Union[str, Any]					 =		output_channel
         lowerCamelCase__    :      Tuple					 =		block_out_channels[i]

         if i == 0:
             input_channel += extra_in_channels

         lowerCamelCase__    :      Union[str, Any]					 =		i == len(UpperCAmelCase	) - 1

         lowerCamelCase__    :      Optional[int]					 =		get_down_block(
             UpperCAmelCase			,     num_layers=UpperCAmelCase			,     in_channels=UpperCAmelCase			,     out_channels=UpperCAmelCase			,     temb_channels=block_out_channels[0]			,     add_downsample=not is_final_block or downsample_each_block			,     )
         self.down_blocks.append(UpperCAmelCase	)

     # mid
     lowerCamelCase__    :      Optional[int]					 =		get_mid_block(
         UpperCAmelCase			,     in_channels=block_out_channels[-1]			,     mid_channels=block_out_channels[-1]			,     out_channels=block_out_channels[-1]			,     embed_dim=block_out_channels[0]			,     num_layers=UpperCAmelCase			,     add_downsample=UpperCAmelCase			,     )

     # up
     lowerCamelCase__    :      Optional[int]					 =		list(reversed(UpperCAmelCase	)	)
     lowerCamelCase__    :      Optional[int]					 =		reversed_block_out_channels[0]
     if out_block_type is None:
         lowerCamelCase__    :      List[str]					 =		out_channels
     else:
         lowerCamelCase__    :      Any					 =		block_out_channels[0]

     for i, up_block_type in enumerate(UpperCAmelCase	):
         lowerCamelCase__    :      Tuple					 =		output_channel
         lowerCamelCase__    :      Union[str, Any]					 =		(
             reversed_block_out_channels[i + 1] if i < len(UpperCAmelCase	) - 1 else final_upsample_channels
         )

         lowerCamelCase__    :      List[str]					 =		i == len(UpperCAmelCase	) - 1

         lowerCamelCase__    :      Dict					 =		get_up_block(
             UpperCAmelCase			,     num_layers=UpperCAmelCase			,     in_channels=UpperCAmelCase			,     out_channels=UpperCAmelCase			,     temb_channels=block_out_channels[0]			,     add_upsample=not is_final_block			,     )
         self.up_blocks.append(UpperCAmelCase	)
         lowerCamelCase__    :      int					 =		output_channel

     # out
     lowerCamelCase__    :      int					 =		norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4			,     32	)
     lowerCamelCase__    :      List[Any]					 =		get_out_block(
         out_block_type=UpperCAmelCase			,     num_groups_out=UpperCAmelCase			,     embed_dim=block_out_channels[0]			,     out_channels=UpperCAmelCase			,     act_fn=UpperCAmelCase			,     fc_dim=block_out_channels[-1] // 4			,     )







 def      A_	(      self  :      List[Any]			,     UpperCAmelCase  :      torch.FloatTensor			,     UpperCAmelCase  :      Union[torch.Tensor, float, int]			,     UpperCAmelCase  :      bool = True			,     )			->	Union[UNetaDOutput, Tuple]:
     lowerCamelCase__    :      Optional[Any]					 =		timestep
     if not torch.is_tensor(UpperCAmelCase	):
         lowerCamelCase__    :      Optional[int]					 =		torch.tensor([timesteps]			,     dtype=torch.long			,     device=sample.device	)
     elif torch.is_tensor(UpperCAmelCase	) and len(timesteps.shape	) == 0:
         lowerCamelCase__    :      List[str]					 =		timesteps[None].to(sample.device	)

     lowerCamelCase__    :      Optional[int]					 =		self.time_proj(UpperCAmelCase	)
     if self.config.use_timestep_embedding:
         lowerCamelCase__    :      str					 =		self.time_mlp(UpperCAmelCase	)
     else:
         lowerCamelCase__    :      List[str]					 =		timestep_embed[..., None]
         lowerCamelCase__    :      str					 =		timestep_embed.repeat([1, 1, sample.shape[2]]	).to(sample.dtype	)
         lowerCamelCase__    :      str					 =		timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:])	)

     # 2. down
     lowerCamelCase__    :      str					 =		()
     for downsample_block in self.down_blocks:
         lowerCamelCase__ ,							lowerCamelCase__    :      Union[str, Any]					 =		downsample_block(hidden_states=UpperCAmelCase			,     temb=UpperCAmelCase	)
         down_block_res_samples += res_samples

     # 3. mid
     if self.mid_block:
         lowerCamelCase__    :      Optional[Any]					 =		self.mid_block(UpperCAmelCase			,     UpperCAmelCase	)

     # 4. up
     for i, upsample_block in enumerate(self.up_blocks	):
         lowerCamelCase__    :      Dict					 =		down_block_res_samples[-1:]
         lowerCamelCase__    :      Optional[Any]					 =		down_block_res_samples[:-1]
         lowerCamelCase__    :      Any					 =		upsample_block(UpperCAmelCase			,     res_hidden_states_tuple=UpperCAmelCase			,     temb=UpperCAmelCase	)

     # 5. post-process
     if self.out_block:
         lowerCamelCase__    :      Any					 =		self.out_block(UpperCAmelCase			,     UpperCAmelCase	)

     if not return_dict:
         return (sample,)

     return UNetaDOutput(sample=UpperCAmelCase	)





