# AsymmetricAutoencoderKL

KL損失を用いたインペインティングタスク向けの改良された大規模な変分オートエンコーダ（VAE）モデル: Zixin Zhu, Xuelu Feng, Dongdong Chen, Jianmin Bao, Le Wang, Yinpeng Chen, Lu Yuan, Gang Hua による [Designing a Better Asymmetric VQGAN for StableDiffusion](https://huggingface.co/papers/2306.04632)

論文の抄録は以下の通りです：

*StableDiffusionは、画像生成・編集の世界で大きな話題を呼んでいる革新的なテキストから画像を生成するモデルです。ピクセル空間で拡散モデルを学習する従来の手法とは異なり、StableDiffusionはVQGANを通じて潜在空間で拡散モデルを学習することで、効率性と品質の両方を確保しています。画像生成タスクをサポートするだけでなく、インペインティングや局所編集など、実写画像の編集も可能にします。しかし、StableDiffusionで使用されているバニラVQGANは、編集されていない画像領域でも歪みアーティファクトを引き起こすほどの著しい情報損失を招くことが観察されています。そこで、2つのシンプルな設計を持つ新しい非対称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, *optional*, デフォルトは 3) : 入力画像のチャネル数。

out_channels (int, *optional*, デフォルトは 3) : 出力のチャネル数。

down_block_types (`tuple[str]`、*任意*、デフォルトは`("DownEncoderBlock2D",)`) : ダウンサンプルブロックのタイプのタプル。

down_block_out_channels (`tuple[int]`、*optional*、デフォルトは`(64,)`) : ダウンブロックの出力チャネルのタプル。

layers_per_down_block (`int`、*任意*、デフォルトは`1`) : ダウンブロックの層数。

up_block_types (`tuple[str]`、*任意*、デフォルトは`("UpDecoderBlock2D",)`) : アップサンプリングブロックのタイプのタプル。

up_block_out_channels (`tuple[int]`、*任意*、デフォルトは`(64,)`) : up block の出力チャネル数のタプル。

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`、*optional*、デフォルト値は 0.18215) : 学習セットの最初のバッチを使用して計算された、学習済み潜在空間の要素ごとの標準偏差です。これは、拡散モデルの学習時に潜在空間を分散 1 にスケーリングするために使用されます。潜在変数は、拡散モデルに渡される前に `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 を参照してください。

StableDiffusion 向けにより優れた非対称 VQGAN の設計 https://huggingface.co/papers/2306.04632 。KL 損失を用いた VAE モデルで、画像を潜在変数にエンコードし、潜在表現を画像にデコードします。

このモデルは [ModelMixin](/docs/diffusers/v0.43.0/ja/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)`) : モデルの最終層からのデコード済み出力サンプル。

デコードメソッドの出力。

