# AutoencoderRAE

NYU VISIONx의 Boyang Zheng, Nanye Ma, Shengbang Tong, Saining Xie가 [Diffusion Transformers with Representation Autoencoders](https://huggingface.co/papers/2510.11690)에서 소개한 Representation Autoencoder(RAE) 모델입니다.

RAE는 동결된 사전 학습된 비전 인코더(DINOv2, SigLIP2 또는 MAE)와 학습 가능한 ViT-MAE 스타일의 디코더를 결합합니다. 2단계 RAE 학습 레시피에서 오토인코더는 1단계(재구성)에서 학습되고, 이후 2단계(생성)에서 생성된 잠재 공간(latent space)에 대해 확산 모델(diffusion model)이 학습됩니다.

다음 RAE 모델들이 Diffusers에서 릴리스되고 지원됩니다:

| 모델 | 인코더 | Latent shape (224px 입력) |
|:------|:--------|:---------------------------|
| [`nyu-visionx/RAE-dinov2-wReg-base-ViTXL-n08`](https://huggingface.co/nyu-visionx/RAE-dinov2-wReg-base-ViTXL-n08) | DINOv2-base | 768 x 16 x 16 |
| [`nyu-visionx/RAE-dinov2-wReg-base-ViTXL-n08-i512`](https://huggingface.co/nyu-visionx/RAE-dinov2-wReg-base-ViTXL-n08-i512) | DINOv2-base (512px) | 768 x 32 x 32 |
| [`nyu-visionx/RAE-dinov2-wReg-small-ViTXL-n08`](https://huggingface.co/nyu-visionx/RAE-dinov2-wReg-small-ViTXL-n08) | DINOv2-small | 384 x 16 x 16 |
| [`nyu-visionx/RAE-dinov2-wReg-large-ViTXL-n08`](https://huggingface.co/nyu-visionx/RAE-dinov2-wReg-large-ViTXL-n08) | DINOv2-large | 1024 x 16 x 16 |
| [`nyu-visionx/RAE-siglip2-base-p16-i256-ViTXL-n08`](https://huggingface.co/nyu-visionx/RAE-siglip2-base-p16-i256-ViTXL-n08) | SigLIP2-base | 768 x 16 x 16 |
| [`nyu-visionx/RAE-mae-base-p16-ViTXL-n08`](https://huggingface.co/nyu-visionx/RAE-mae-base-p16-ViTXL-n08) | MAE-base | 768 x 16 x 16 |

## 사전 학습된 모델 로드

```python
from diffusers import AutoencoderRAE

model = AutoencoderRAE.from_pretrained(
    "nyu-visionx/RAE-dinov2-wReg-base-ViTXL-n08"
).to("cuda").eval()  # or "mps", "xpu", "cpu"
```

## 실제 이미지의 인코딩 및 디코딩

```python
import torch
from diffusers import AutoencoderRAE
from diffusers.utils import load_image
from torchvision.transforms.functional import to_tensor, to_pil_image

model = AutoencoderRAE.from_pretrained(
    "nyu-visionx/RAE-dinov2-wReg-base-ViTXL-n08"
).to("cuda").eval()  # or "mps", "xpu", "cpu"

image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat.png")
image = image.convert("RGB").resize((224, 224))
x = to_tensor(image).unsqueeze(0).to("cuda")  # (1, 3, 224, 224), values in [0, 1]

with torch.no_grad():
    latents = model.encode(x).latent        # (1, 768, 16, 16)
    recon = model.decode(latents).sample     # (1, 3, 256, 256)

recon_image = to_pil_image(recon[0].clamp(0, 1).cpu())
recon_image.save("recon.png")
```

## 잠재 정규화

일부 사전 학습된 체크포인트에는 잠재 공간 정규화를 위한 채널별 `latents_mean` 및 `latents_std` 통계가 포함되어 있습니다. 이러한 통계가 존재하면 `encode`와 `decode`가 각각 정규화와 역정규화를 자동으로 적용합니다.

```python
model = AutoencoderRAE.from_pretrained(
    "nyu-visionx/RAE-dinov2-wReg-base-ViTXL-n08"
).to("cuda").eval()  # or "mps", "xpu", "cpu"

# Latent normalization is handled automatically inside encode/decode
# when the checkpoint config includes latents_mean/latents_std.
with torch.no_grad():
    latents = model.encode(x).latent   # normalized latents
    recon = model.decode(latents).sample
```

## AutoencoderRAE[[diffusers.AutoencoderRAE]]

#### diffusers.AutoencoderRAE[[diffusers.AutoencoderRAE]]

```python
diffusers.AutoencoderRAE(encoder_type: str = 'dinov2', encoder_hidden_size: int = 768, encoder_patch_size: int = 14, encoder_num_hidden_layers: int = 12, decoder_hidden_size: int = 512, decoder_num_hidden_layers: int = 8, decoder_num_attention_heads: int = 16, decoder_intermediate_size: int = 2048, patch_size: int = 16, encoder_input_size: int = 224, image_size: int | None = None, num_channels: int = 3, encoder_norm_mean: list | None = None, encoder_norm_std: list | None = None, latents_mean: typing.Union[list, tuple, torch.Tensor, NoneType] = None, latents_std: typing.Union[list, tuple, torch.Tensor, NoneType] = None, noise_tau: float = 0.0, reshape_to_2d: bool = True, use_encoder_loss: bool = False, scaling_factor: float = 1.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/autoencoders/autoencoder_rae.py#L393)

**매개변수:**

encoder_type (`str`, *선택 사항*, 기본값 `"dinov2"`) : 사용할 동결된 인코더의 유형. `"dinov2"`, `"siglip2"`, 또는 `"mae"` 중 하나입니다.

encoder_hidden_size (`int`, *선택 사항*, 기본값 `768`) : 인코더 모델의 숨겨진 크기입니다.

encoder_patch_size (`int`, *선택 사항*, 기본값 `14`) : 인코더 모델의 패치 크기입니다.

encoder_num_hidden_layers (`int`, *선택 사항*, 기본값 `12`) : 인코더 모델의 숨겨진 레이어 수.

patch_size (`int`, *선택 사항*, 기본값 `16`) : Decoder patch size (unpatchify 및 decoder head에 사용됨).

encoder_input_size (`int`, *선택 사항*, 기본값 `224`) : 인코더가 기대하는 입력 크기.

image_size (`int`, *선택 사항*) : 디코더 출력 이미지 크기. `None`인 경우, RAE-main과 마찬가지로 인코더 토큰 수와 `patch_size`에서 유도됩니다: `image_size = patch_size * sqrt(num_patches)`, 여기서 `num_patches = (encoder_input_size // encoder_patch_size) ** 2`입니다.

num_channels (`int`, *선택 사항*, 기본값 `3`) : 입력/출력 채널 수.

encoder_norm_mean (`list`, *선택 사항*, 기본값 `[0.485, 0.456, 0.406]`) : 인코더 입력 정규화를 위한 채널별 평균 (ImageNet 기본값).

encoder_norm_std (`list`, *선택 사항*, 기본값 `[0.229, 0.224, 0.225]`) : 인코더 입력 정규화를 위한 채널별 표준편차 (ImageNet 기본값).

latents_mean (`list` 또는 `tuple`, *선택 사항*) : 잠재 변수 정규화를 위한 선택적 평균 값. Tensor 입력을 허용하며, config 직렬화가 가능한 리스트로 변환됩니다.

latents_std (`list` 또는 `tuple`, *선택 사항*) : 잠재 변수 정규화를 위한 선택적 표준 편차. Tensor 입력을 허용하며 config 직렬화 가능한 리스트로 변환됩니다.

noise_tau (`float`, *선택 사항*, 기본값 `0.0`) : 학습 시 사용할 노이즈 수준(학습 중 latents에 노이즈를 추가합니다).

reshape_to_2d (`bool`, *선택 사항*, 기본값 `True`) : latents를 2D (B, C, H, W) 형식으로 reshape할지 여부.

use_encoder_loss (`bool`, *선택 사항*, 기본값 `False`) : 손실에 인코더 히든 상태를 사용할지 여부(고급 학습용).

이미지를 latent로 인코딩하고 latent를 이미지로 디코딩하는 Representation Autoencoder (RAE) 모델.

이 모델은 학습된 표현으로부터 이미지를 재구성하기 위해 동결된 사전 학습 인코더(DINOv2, SigLIP2, 또는 MAE)와 학습 가능한 ViT 디코더를 사용합니다.

이 모델은 [ModelMixin](/docs/diffusers/main/ko/api/models/overview#diffusers.ModelMixin)에서 상속됩니다. 모든 모델에 대해 구현된 일반적 메서드(다운로드 또는 저장 등)에 대해서는 상위 클래스 문서를 확인하세요.

#### encode[[diffusers.AutoencoderRAE.encode]]

```python
encode(x: Tensor, return_dict: bool = True, generator: typing.Optional[torch.Generator] = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/autoencoders/autoencoder_rae.py#L640)

#### decode[[diffusers.AutoencoderRAE.decode]]

```python
decode(z: Tensor, return_dict: bool = True)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/autoencoders/autoencoder_rae.py#L671)

#### forward[[diffusers.AutoencoderRAE.forward]]

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

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/autoencoders/autoencoder_rae.py#L682)

**매개변수:**

sample (`torch.Tensor`) : 입력 샘플.

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`이 반환됩니다.

## 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/main/src/diffusers/models/autoencoders/vae.py#L49)

**매개변수:**

sample (`torch.Tensor`, shape `(batch_size, num_channels, height, width)`) : 모델의 마지막 레이어에서 디코딩된 출력 샘플.

디코딩 메서드의 출력.

