AutoencoderKL
The variational autoencoder (VAE) model with KL loss was introduced in Auto-Encoding Variational Bayes by Diederik P. Kingma and Max Welling. The model is used in 🤗 Diffusers to encode images into latents and to decode latent representations into images.
The abstract from the paper is:
How can we perform efficient inference and learning in directed probabilistic models, in the presence of continuous latent variables with intractable posterior distributions, and large datasets? We introduce a stochastic variational inference and learning algorithm that scales to large datasets and, under some mild differentiability conditions, even works in the intractable case. Our contributions are two-fold. First, we show that a reparameterization of the variational lower bound yields a lower bound estimator that can be straightforwardly optimized using standard stochastic gradient methods. Second, we show that for i.i.d. datasets with continuous latent variables per datapoint, posterior inference can be made especially efficient by fitting an approximate inference model (also called a recognition model) to the intractable posterior using the proposed lower bound estimator. Theoretical advantages are reflected in experimental results.
Loading from the original format
By default the AutoencoderKL should be loaded with from_pretrained(), but it can also be loaded
from the original format using FromOriginalModelMixin.from_single_file
as follows:
from diffusers import AutoencoderKL
url = "https://huggingface.co/stabilityai/sd-vae-ft-mse-original/blob/main/vae-ft-mse-840000-ema-pruned.safetensors" # can also be a local file
model = AutoencoderKL.from_single_file(url)
AutoencoderKL
class diffusers.AutoencoderKL
< source >( in_channels: int = 3 out_channels: int = 3 down_block_types: Tuple = ('DownEncoderBlock2D',) up_block_types: Tuple = ('UpDecoderBlock2D',) block_out_channels: Tuple = (64,) layers_per_block: int = 1 act_fn: str = 'silu' latent_channels: int = 4 norm_num_groups: int = 32 sample_size: int = 32 scaling_factor: float = 0.18215 shift_factor: Optional = None latents_mean: Optional = None latents_std: Optional = None force_upcast: float = True use_quant_conv: bool = True use_post_quant_conv: bool = True mid_block_add_attention: bool = True )
Parameters
- in_channels (int, optional, defaults to 3) — Number of channels in the input image.
- out_channels (int, optional, defaults to 3) — Number of channels in the output.
- down_block_types (
Tuple[str]
, optional, defaults to("DownEncoderBlock2D",)
) — Tuple of downsample block types. - up_block_types (
Tuple[str]
, optional, defaults to("UpDecoderBlock2D",)
) — Tuple of upsample block types. - block_out_channels (
Tuple[int]
, optional, defaults to(64,)
) — Tuple of block output channels. - act_fn (
str
, optional, defaults to"silu"
) — The activation function to use. - latent_channels (
int
, optional, defaults to 4) — Number of channels in the latent space. - sample_size (
int
, optional, defaults to32
) — Sample input size. - scaling_factor (
float
, optional, defaults to 0.18215) — The component-wise standard deviation of the trained latent space computed using the first batch of the training set. This is used to scale the latent space to have unit variance when training the diffusion model. The latents are scaled with the formulaz = z * scaling_factor
before being passed to the diffusion model. When decoding, the latents are scaled back to the original scale with the formula:z = 1 / scaling_factor * z
. For more details, refer to sections 4.3.2 and D.1 of the High-Resolution Image Synthesis with Latent Diffusion Models paper. - force_upcast (
bool
, optional, default toTrue
) — If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE can be fine-tuned / trained to a lower range without loosing too much precision in which caseforce_upcast
can be set toFalse
- see: https://huggingface.co/madebyollin/sdxl-vae-fp16-fix - mid_block_add_attention (
bool
, optional, default toTrue
) — If enabled, the mid_block of the Encoder and Decoder will have attention blocks. If set to false, the mid_block will only have resnet blocks
A VAE model with KL loss for encoding images into latents and decoding latent representations into images.
This model inherits from ModelMixin. Check the superclass documentation for it’s generic methods implemented for all models (such as downloading or saving).
Disable sliced VAE decoding. If enable_slicing
was previously enabled, this method will go back to computing
decoding in one step.
Disable tiled VAE decoding. If enable_tiling
was previously enabled, this method will go back to computing
decoding in one step.
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow processing larger images.
forward
< source >( sample: Tensor sample_posterior: bool = False return_dict: bool = True generator: Optional = None )
Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value) are fused. For cross-attention modules, key and value projection matrices are fused.
This API is 🧪 experimental.
set_attn_processor
< source >( processor: Union )
Parameters
- processor (
dict
ofAttentionProcessor
or onlyAttentionProcessor
) — The instantiated processor class or a dictionary of processor classes that will be set as the processor for allAttention
layers.If
processor
is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors.
Sets the attention processor to use to compute attention.
Disables custom attention processors and sets the default attention implementation.
tiled_decode
< source >( z: Tensor return_dict: bool = True ) → ~models.vae.DecoderOutput
or tuple
Parameters
- z (
torch.Tensor
) — Input batch of latent vectors. - return_dict (
bool
, optional, defaults toTrue
) — Whether or not to return a~models.vae.DecoderOutput
instead of a plain tuple.
Returns
~models.vae.DecoderOutput
or tuple
If return_dict is True, a ~models.vae.DecoderOutput
is returned, otherwise a plain tuple
is
returned.
Decode a batch of images using a tiled decoder.
tiled_encode
< source >( x: Tensor return_dict: bool = True ) → ~models.autoencoder_kl.AutoencoderKLOutput
or tuple
Parameters
- x (
torch.Tensor
) — Input batch of images. - return_dict (
bool
, optional, defaults toTrue
) — Whether or not to return a~models.autoencoder_kl.AutoencoderKLOutput
instead of a plain tuple.
Returns
~models.autoencoder_kl.AutoencoderKLOutput
or tuple
If return_dict is True, a ~models.autoencoder_kl.AutoencoderKLOutput
is returned, otherwise a plain
tuple
is returned.
Encode a batch of images using a tiled encoder.
When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several steps. This is useful to keep memory use constant regardless of image size. The end result of tiled encoding is different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the output, but they should be much less noticeable.
Disables the fused QKV projection if enabled.
This API is 🧪 experimental.
AutoencoderKLOutput
class diffusers.models.modeling_outputs.AutoencoderKLOutput
< source >( latent_dist: DiagonalGaussianDistribution )
Output of AutoencoderKL encoding method.
DecoderOutput
class diffusers.models.autoencoders.vae.DecoderOutput
< source >( sample: Tensor commit_loss: Optional = None )
Output of decoding method.
FlaxAutoencoderKL
class diffusers.FlaxAutoencoderKL
< source >( in_channels: int = 3 out_channels: int = 3 down_block_types: Tuple = ('DownEncoderBlock2D',) up_block_types: Tuple = ('UpDecoderBlock2D',) block_out_channels: Tuple = (64,) layers_per_block: int = 1 act_fn: str = 'silu' latent_channels: int = 4 norm_num_groups: int = 32 sample_size: int = 32 scaling_factor: float = 0.18215 dtype: dtype = <class 'jax.numpy.float32'> parent: Union = <flax.linen.module._Sentinel object at 0x7f302329ffa0> name: Optional = None )
Parameters
- in_channels (
int
, optional, defaults to 3) — Number of channels in the input image. - out_channels (
int
, optional, defaults to 3) — Number of channels in the output. - down_block_types (
Tuple[str]
, optional, defaults to(DownEncoderBlock2D)
) — Tuple of downsample block types. - up_block_types (
Tuple[str]
, optional, defaults to(UpDecoderBlock2D)
) — Tuple of upsample block types. - block_out_channels (
Tuple[str]
, optional, defaults to(64,)
) — Tuple of block output channels. - layers_per_block (
int
, optional, defaults to2
) — Number of ResNet layer for each block. - act_fn (
str
, optional, defaults tosilu
) — The activation function to use. - latent_channels (
int
, optional, defaults to4
) — Number of channels in the latent space. - norm_num_groups (
int
, optional, defaults to32
) — The number of groups for normalization. - sample_size (
int
, optional, defaults to 32) — Sample input size. - scaling_factor (
float
, optional, defaults to 0.18215) — The component-wise standard deviation of the trained latent space computed using the first batch of the training set. This is used to scale the latent space to have unit variance when training the diffusion model. The latents are scaled with the formulaz = z * scaling_factor
before being passed to the diffusion model. When decoding, the latents are scaled back to the original scale with the formula:z = 1 / scaling_factor * z
. For more details, refer to sections 4.3.2 and D.1 of the High-Resolution Image Synthesis with Latent Diffusion Models paper. - dtype (
jnp.dtype
, optional, defaults tojnp.float32
) — Thedtype
of the parameters.
Flax implementation of a VAE model with KL loss for decoding latent representations.
This model inherits from FlaxModelMixin. Check the superclass documentation for it’s generic methods implemented for all models (such as downloading or saving).
This model is a Flax Linen flax.linen.Module subclass. Use it as a regular Flax Linen module and refer to the Flax documentation for all matter related to its general usage and behavior.
Inherent JAX features such as the following are supported:
FlaxAutoencoderKLOutput
class diffusers.models.vae_flax.FlaxAutoencoderKLOutput
< source >( latent_dist: FlaxDiagonalGaussianDistribution )
Output of AutoencoderKL encoding method.
“Returns a new object replacing the specified fields with new values.
FlaxDecoderOutput
class diffusers.models.vae_flax.FlaxDecoderOutput
< source >( sample: Array )
Output of decoding method.
“Returns a new object replacing the specified fields with new values.