# AsymmetricAutoencoderKL

用于图像修复任务的改进型大型变分自编码器（VAE）模型，采用 KL 损失：[Designing a Better Asymmetric VQGAN for StableDiffusion](https://huggingface.co/papers/2306.04632)，作者为 Zixin Zhu、Xuelu Feng、Dongdong Chen、Jianmin Bao、Le Wang、Yinpeng Chen、Lu Yuan、Gang Hua。

该论文的摘要如下：

*StableDiffusion 是一款革命性的文本生成图像模型，正在图像生成与编辑领域引起广泛关注。与在像素空间学习扩散模型的传统方法不同，StableDiffusion 通过 VQGAN 在潜在空间学习扩散模型，从而兼顾效率与质量。它不仅支持图像生成任务，还能对真实图像进行编辑，例如图像修复（inpainting）和局部编辑。然而，我们观察到 StableDiffusion 中使用的原始 VQGAN 会导致显著的信息损失，即使在未编辑的图像区域也会出现失真伪影。为此，我们提出了一种新的非对称 VQGAN，包含两个简单的设计。首先，除了来自编码器的输入外，解码器还包含一个条件分支，用于引入任务特定的先验信息，例如修复任务中未掩码的图像区域。其次，解码器比编码器重得多，从而能够恢复更多细节，同时仅略微增加总推理成本。我们的非对称 VQGAN 训练成本较低，只需重新训练一个新的非对称解码器，而保持原始 VQGAN 编码器和 StableDiffusion 不变。我们的非对称 VQGAN 可广泛应用于基于 StableDiffusion 的修复和局部编辑方法。大量实验表明，它能在保持原有文本生成图像能力的同时，显著提升修复和编辑性能。代码已开源：https://github.com/buxiangzhiren/Asymmetric_VQGAN*

评估结果可在原论文的 4.1 节中找到。

## 可用的检查点

* [https://huggingface.co/cross-attention/asymmetric-autoencoder-kl-x-1-5](https://huggingface.co/cross-attention/asymmetric-autoencoder-kl-x-1-5)
* [https://huggingface.co/cross-attention/asymmetric-autoencoder-kl-x-2](https://huggingface.co/cross-attention/asymmetric-autoencoder-kl-x-2)

## 使用示例

```python
from diffusers import AsymmetricAutoencoderKL, StableDiffusionInpaintPipeline
from diffusers.utils import load_image, make_image_grid

prompt = "a photo of a person with beard"
img_url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/repaint/celeba_hq_256.png"
mask_url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/repaint/mask_256.png"

original_image = load_image(img_url).resize((512, 512))
mask_image = load_image(mask_url).resize((512, 512))

pipe = StableDiffusionInpaintPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-inpainting")
pipe.vae = AsymmetricAutoencoderKL.from_pretrained("cross-attention/asymmetric-autoencoder-kl-x-1-5")
pipe.to("cuda")  # or "mps", "xpu", "cpu"

image = pipe(prompt=prompt, image=original_image, mask_image=mask_image).images[0]
make_image_grid([original_image, mask_image, image], rows=1, cols=3)
```

## AsymmetricAutoencoderKL[[diffusers.AsymmetricAutoencoderKL]]

#### diffusers.AsymmetricAutoencoderKL[[diffusers.AsymmetricAutoencoderKL]]

```python
diffusers.AsymmetricAutoencoderKL(in_channels: int = 3, out_channels: int = 3, down_block_types: tuple[str, ...] = ('DownEncoderBlock2D',), down_block_out_channels: tuple[int, ...] = (64,), layers_per_down_block: int = 1, up_block_types: tuple[str, ...] = ('UpDecoderBlock2D',), up_block_out_channels: tuple[int, ...] = (64,), layers_per_up_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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/autoencoders/autoencoder_asym_kl.py#L24)

**参数：**

in_channels (int, *可选*，默认为 3)：输入图像的通道数。

out_channels (int, *可选*，默认为 3)：输出中的通道数。

down_block_types (`tuple[str]`，*可选*，默认为 `("DownEncoderBlock2D",)`)：下采样块类型的元组。

down_block_out_channels (`tuple[int]`，*可选*，默认为 `(64,)`)：下采样块输出通道的元组。

layers_per_down_block (`int`，*可选*，默认为 `1`)：下采样块中的层数。

up_block_types (`tuple[str]`，*可选*，默认为 `("UpDecoderBlock2D",)`)：上采样块类型的元组。

up_block_out_channels (`tuple[int]`，*可选*，默认为 `(64,)`)：上采样块输出通道的元组。

layers_per_up_block (`int`，*可选*，默认为 `1`)：上采样块中的层数。

act_fn (`str`，*可选*，默认为 `"silu"`)：要使用的激活函数。

latent_channels (`int`，*可选*，默认为 4)：潜在空间中的通道数。

sample_size (`int`，*可选*，默认为 `32`)：采样输入大小。

norm_num_groups (`int`，*可选*，默认为 `32`)：ResNet 块中第一个归一化层使用的组数。

scaling_factor (`float`, *可选*，默认为 0.18215)：使用训练集的第一个批次计算得出的训练后潜在空间的逐分量标准差。此值用于在训练扩散模型时将潜在空间缩放至单位方差。在传入扩散模型之前，潜在变量会按公式 `z = z * scaling_factor` 进行缩放。在解码时，潜在变量会按公式 `z = 1 / scaling_factor * z` 缩放回原始尺度。更多细节请参阅 [High-Resolution Image Synthesis with Latent Diffusion Models](https://huggingface.co/papers/2112.10752) 论文的 4.3.2 节和 D.1 节。

Designing a Better Asymmetric VQGAN for StableDiffusion https://huggingface.co/papers/2306.04632。一个使用 KL 损失的 VAE 模型，用于将图像编码为潜在表示，并将潜在表示解码为图像。

该模型继承自 [ModelMixin](/docs/diffusers/v0.43.0/zh/api/models/overview#diffusers.ModelMixin)。请查阅其父类文档，了解为所有模型实现的通用方法（例如下载或保存）。

#### forward[[diffusers.AsymmetricAutoencoderKL.forward]]

```python
forward(sample: Tensor, mask: typing.Optional[torch.Tensor] = None, sample_posterior: bool = False, return_dict: bool = True, generator: typing.Optional[torch.Generator] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/autoencoders/autoencoder_asym_kl.py#L153)

**参数：**

sample (`torch.Tensor`) : 输入样本。

mask (`torch.Tensor`，*可选*，默认为 `None`)：可选的修复蒙版。

sample_posterior (`bool`，*可选*，默认为 `False`)：是否从后验分布中采样。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `DecoderOutput` 而不是普通元组。

generator (`torch.Generator`，*可选*)：一个 [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使采样过程具有确定性。

**返回：** `DecoderOutput` 或 `tuple`

如果 `return_dict` 为 True，则返回 `DecoderOutput`，否则返回普通的 `tuple`。

## AutoencoderKLOutput[[diffusers.models.modeling_outputs.AutoencoderKLOutput]]

#### diffusers.models.modeling_outputs.AutoencoderKLOutput[[diffusers.models.modeling_outputs.AutoencoderKLOutput]]

```python
diffusers.models.modeling_outputs.AutoencoderKLOutput(latent_dist: DiagonalGaussianDistribution)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/modeling_outputs.py#L7)

**参数：**

latent_dist (`DiagonalGaussianDistribution`)：`Encoder` 的编码输出，表示为 `DiagonalGaussianDistribution` 的均值和 logvar。`DiagonalGaussianDistribution` 允许从该分布中采样潜在变量。

AutoencoderKL 编码方法的输出。

## DecoderOutput[[diffusers.models.autoencoders.vae.DecoderOutput]]

#### diffusers.models.autoencoders.vae.DecoderOutput[[diffusers.models.autoencoders.vae.DecoderOutput]]

```python
diffusers.models.autoencoders.vae.DecoderOutput(sample: Tensor, commit_loss: typing.Optional[torch.FloatTensor] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/autoencoders/vae.py#L49)

**参数：**

sample (`torch.Tensor`，形状为 `(batch_size, num_channels, height, width)`)：模型最后一层解码后的输出样本。

解码方法的输出。

