Initial upload: iRDiffAE v1.0 (p16_c128, EMA weights)
Browse files- README.md +118 -0
- config.json +14 -0
- ir_diffae/__init__.py +26 -0
- ir_diffae/adaln.py +51 -0
- ir_diffae/compact_channel_attention.py +21 -0
- ir_diffae/config.py +51 -0
- ir_diffae/conv_mlp.py +26 -0
- ir_diffae/decoder.py +175 -0
- ir_diffae/dico_block.py +111 -0
- ir_diffae/encoder.py +55 -0
- ir_diffae/model.py +291 -0
- ir_diffae/norms.py +39 -0
- ir_diffae/samplers.py +226 -0
- ir_diffae/straight_through_encoder.py +27 -0
- ir_diffae/time_embed.py +83 -0
- ir_diffae/vp_diffusion.py +151 -0
- model.safetensors +3 -0
- technical_report.md +709 -0
README.md
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
tags:
|
| 4 |
+
- diffusion
|
| 5 |
+
- autoencoder
|
| 6 |
+
- image-reconstruction
|
| 7 |
+
- pytorch
|
| 8 |
+
library_name: irdiffae
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# irdiffae_v1
|
| 12 |
+
|
| 13 |
+
**iRDiffAE** β **i**REPA **Diff**usion **A**uto**E**ncoder.
|
| 14 |
+
A fast, single-GPU-trainable diffusion autoencoder with spatially structured
|
| 15 |
+
latents for rapid downstream model convergence. Encoding runs ~5Γ faster than
|
| 16 |
+
Flux VAE; single-step decoding runs ~3Γ faster.
|
| 17 |
+
|
| 18 |
+
## Model Variants
|
| 19 |
+
|
| 20 |
+
| Variant | Patch | Channels | Compression | |
|
| 21 |
+
|---------|-------|----------|-------------|---|
|
| 22 |
+
| **irdiffae_v1** | 16x16 | 128 | 6x | recommended |
|
| 23 |
+
|
| 24 |
+
This variant (irdiffae_v1): 121.0M parameters, 461.4 MB.
|
| 25 |
+
|
| 26 |
+
## Documentation
|
| 27 |
+
|
| 28 |
+
- [Technical Report](technical_report.md) β diffusion math, architecture, training, and results
|
| 29 |
+
- [Results β interactive viewer](https://huggingface.co/spaces/data-archetype/irdiffae-results) β full-resolution side-by-side comparison
|
| 30 |
+
- [Results β summary stats](technical_report.md#7-results) β metrics and per-image PSNR
|
| 31 |
+
|
| 32 |
+
## Quick Start
|
| 33 |
+
|
| 34 |
+
```python
|
| 35 |
+
import torch
|
| 36 |
+
from ir_diffae import IRDiffAE
|
| 37 |
+
|
| 38 |
+
# Load from HuggingFace Hub (or a local path)
|
| 39 |
+
model = IRDiffAE.from_pretrained("irdiffae_v1", device="cuda")
|
| 40 |
+
|
| 41 |
+
# Encode
|
| 42 |
+
images = ... # [B, 3, H, W] in [-1, 1], H and W divisible by 16
|
| 43 |
+
latents = model.encode(images)
|
| 44 |
+
|
| 45 |
+
# Decode
|
| 46 |
+
recon = model.decode(latents, height=H, width=W)
|
| 47 |
+
|
| 48 |
+
# Reconstruct (encode + decode)
|
| 49 |
+
recon = model.reconstruct(images)
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
> **Note:** Requires `pip install huggingface_hub safetensors` for Hub downloads.
|
| 53 |
+
> You can also pass a local directory path to `from_pretrained()`.
|
| 54 |
+
|
| 55 |
+
## Architecture
|
| 56 |
+
|
| 57 |
+
| Property | Value |
|
| 58 |
+
|---|---|
|
| 59 |
+
| Parameters | 120,957,440 |
|
| 60 |
+
| File size | 461.4 MB |
|
| 61 |
+
| Patch size | 16 |
|
| 62 |
+
| Model dim | 896 |
|
| 63 |
+
| Encoder depth | 4 |
|
| 64 |
+
| Decoder depth | 8 |
|
| 65 |
+
| Bottleneck dim | 128 |
|
| 66 |
+
| MLP ratio | 4.0 |
|
| 67 |
+
| Depthwise kernel | 7 |
|
| 68 |
+
| AdaLN rank | 128 |
|
| 69 |
+
|
| 70 |
+
**Encoder**: Deterministic. Patchify (PixelUnshuffle + 1x1 conv) followed by
|
| 71 |
+
DiCo blocks (depthwise conv + compact channel attention + GELU MLP) with
|
| 72 |
+
learned residual gates.
|
| 73 |
+
|
| 74 |
+
**Decoder**: VP diffusion conditioned on encoder latents and timestep via
|
| 75 |
+
shared-base + per-layer low-rank AdaLN-Zero. Start blocks (2) -> middle
|
| 76 |
+
blocks (4) -> skip fusion -> end blocks (2). Supports
|
| 77 |
+
Path-Drop Guidance (PDG) at inference for quality/speed tradeoff.
|
| 78 |
+
|
| 79 |
+
## Recommended Settings
|
| 80 |
+
|
| 81 |
+
Best quality is achieved with just **1 DDIM step** and PDG disabled,
|
| 82 |
+
making inference extremely fast. PDG (strength 2-4) can optionally
|
| 83 |
+
increase perceptual sharpness but is easy to overdo.
|
| 84 |
+
|
| 85 |
+
| Setting | Default |
|
| 86 |
+
|---|---|
|
| 87 |
+
| Sampler | DDIM |
|
| 88 |
+
| Steps | 1 |
|
| 89 |
+
| PDG | Disabled |
|
| 90 |
+
|
| 91 |
+
```python
|
| 92 |
+
from ir_diffae import IRDiffAEInferenceConfig
|
| 93 |
+
|
| 94 |
+
# PSNR-optimal (fast, 1 step)
|
| 95 |
+
cfg = IRDiffAEInferenceConfig(num_steps=1, sampler="ddim")
|
| 96 |
+
recon = model.decode(latents, height=H, width=W, inference_config=cfg)
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
## Citation
|
| 100 |
+
|
| 101 |
+
```bibtex
|
| 102 |
+
@misc{irdiffae_v1,
|
| 103 |
+
title = {iRDiffAE: A Fast, Representation Aligned Diffusion Autoencoder with DiCo Blocks},
|
| 104 |
+
author = {data-archetype},
|
| 105 |
+
year = {2026},
|
| 106 |
+
month = feb,
|
| 107 |
+
url = {https://huggingface.co/irdiffae_v1},
|
| 108 |
+
}
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
## Dependencies
|
| 112 |
+
|
| 113 |
+
- PyTorch >= 2.0
|
| 114 |
+
- safetensors (for loading weights)
|
| 115 |
+
|
| 116 |
+
## License
|
| 117 |
+
|
| 118 |
+
Apache 2.0
|
config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"in_channels": 3,
|
| 3 |
+
"patch_size": 16,
|
| 4 |
+
"model_dim": 896,
|
| 5 |
+
"encoder_depth": 4,
|
| 6 |
+
"decoder_depth": 8,
|
| 7 |
+
"bottleneck_dim": 128,
|
| 8 |
+
"mlp_ratio": 4.0,
|
| 9 |
+
"depthwise_kernel_size": 7,
|
| 10 |
+
"adaln_low_rank_rank": 128,
|
| 11 |
+
"logsnr_min": -10.0,
|
| 12 |
+
"logsnr_max": 10.0,
|
| 13 |
+
"pixel_noise_std": 0.558
|
| 14 |
+
}
|
ir_diffae/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""iRDiffAE: Standalone diffusion autoencoder for HuggingFace distribution.
|
| 2 |
+
|
| 3 |
+
iREPA Diffusion AutoEncoder β a compact diffusion autoencoder
|
| 4 |
+
that encodes images to spatial latents and decodes via iterative VP diffusion.
|
| 5 |
+
|
| 6 |
+
Usage::
|
| 7 |
+
|
| 8 |
+
from ir_diffae import IRDiffAE, IRDiffAEInferenceConfig
|
| 9 |
+
|
| 10 |
+
model = IRDiffAE.from_pretrained("path/to/weights", device="cuda")
|
| 11 |
+
|
| 12 |
+
# Encode
|
| 13 |
+
latents = model.encode(images) # images: [B,3,H,W] in [-1,1]
|
| 14 |
+
|
| 15 |
+
# Decode with custom settings
|
| 16 |
+
cfg = IRDiffAEInferenceConfig(num_steps=50, sampler="dpmpp_2m")
|
| 17 |
+
recon = model.decode(latents, height=512, width=512, inference_config=cfg)
|
| 18 |
+
|
| 19 |
+
# Reconstruct (encode + decode)
|
| 20 |
+
recon = model.reconstruct(images)
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from .config import IRDiffAEConfig, IRDiffAEInferenceConfig
|
| 24 |
+
from .model import IRDiffAE
|
| 25 |
+
|
| 26 |
+
__all__ = ["IRDiffAE", "IRDiffAEConfig", "IRDiffAEInferenceConfig"]
|
ir_diffae/adaln.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AdaLN-Zero modules for shared-base + low-rank-delta conditioning."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from torch import Tensor, nn
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class AdaLNZeroProjector(nn.Module):
|
| 9 |
+
"""Shared base AdaLN projection: SiLU -> Linear(d_cond -> 4*d_model).
|
| 10 |
+
|
| 11 |
+
Returns packed modulation tensor [B, 4*d_model]. Zero-initialized.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
def __init__(self, d_model: int, d_cond: int) -> None:
|
| 15 |
+
super().__init__()
|
| 16 |
+
self.d_model = int(d_model)
|
| 17 |
+
self.d_cond = int(d_cond)
|
| 18 |
+
self.act = nn.SiLU()
|
| 19 |
+
self.proj = nn.Linear(self.d_cond, 4 * self.d_model)
|
| 20 |
+
nn.init.zeros_(self.proj.weight)
|
| 21 |
+
nn.init.zeros_(self.proj.bias)
|
| 22 |
+
|
| 23 |
+
def forward(self, cond: Tensor) -> Tensor:
|
| 24 |
+
"""Return packed modulation [B, 4*d_model] from conditioning [B, d_cond]."""
|
| 25 |
+
act = self.act(cond)
|
| 26 |
+
return self.proj(act)
|
| 27 |
+
|
| 28 |
+
def forward_activated(self, act_cond: Tensor) -> Tensor:
|
| 29 |
+
"""Return packed modulation from pre-activated conditioning."""
|
| 30 |
+
return self.proj(act_cond)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class AdaLNZeroLowRankDelta(nn.Module):
|
| 34 |
+
"""Per-layer low-rank delta: down(d_cond -> rank) -> up(rank -> 4*d_model).
|
| 35 |
+
|
| 36 |
+
Zero-initialized up-projection preserves AdaLN "zero output" at init.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
def __init__(self, *, d_model: int, d_cond: int, rank: int) -> None:
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.d_model = int(d_model)
|
| 42 |
+
self.d_cond = int(d_cond)
|
| 43 |
+
self.rank = int(rank)
|
| 44 |
+
self.down = nn.Linear(self.d_cond, self.rank, bias=False)
|
| 45 |
+
self.up = nn.Linear(self.rank, 4 * self.d_model, bias=False)
|
| 46 |
+
nn.init.normal_(self.down.weight, mean=0.0, std=0.02)
|
| 47 |
+
nn.init.zeros_(self.up.weight)
|
| 48 |
+
|
| 49 |
+
def forward(self, act_cond: Tensor) -> Tensor:
|
| 50 |
+
"""Return packed delta modulation [B, 4*d_model] from activated cond."""
|
| 51 |
+
return self.up(self.down(act_cond))
|
ir_diffae/compact_channel_attention.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compact Channel Attention (CCA) module."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from torch import Tensor, nn
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class CompactChannelAttention(nn.Module):
|
| 9 |
+
"""Global average pool -> 1x1 Conv2d -> Sigmoid channel gate."""
|
| 10 |
+
|
| 11 |
+
def __init__(self, channels: int) -> None:
|
| 12 |
+
super().__init__()
|
| 13 |
+
c = int(channels)
|
| 14 |
+
self.pool = nn.AdaptiveAvgPool2d(1)
|
| 15 |
+
self.proj = nn.Conv2d(c, c, kernel_size=1, padding=0, stride=1, bias=True)
|
| 16 |
+
self.act = nn.Sigmoid()
|
| 17 |
+
|
| 18 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 19 |
+
w = self.pool(x)
|
| 20 |
+
w = self.proj(w)
|
| 21 |
+
return self.act(w)
|
ir_diffae/config.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen model architecture and user-tunable inference configuration."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from dataclasses import asdict, dataclass
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass(frozen=True)
|
| 11 |
+
class IRDiffAEConfig:
|
| 12 |
+
"""Frozen model architecture config. Stored alongside weights as config.json."""
|
| 13 |
+
|
| 14 |
+
in_channels: int = 3
|
| 15 |
+
patch_size: int = 16
|
| 16 |
+
model_dim: int = 896
|
| 17 |
+
encoder_depth: int = 4
|
| 18 |
+
decoder_depth: int = 8
|
| 19 |
+
bottleneck_dim: int = 128
|
| 20 |
+
mlp_ratio: float = 4.0
|
| 21 |
+
depthwise_kernel_size: int = 7
|
| 22 |
+
adaln_low_rank_rank: int = 128
|
| 23 |
+
# VP diffusion schedule endpoints
|
| 24 |
+
logsnr_min: float = -10.0
|
| 25 |
+
logsnr_max: float = 10.0
|
| 26 |
+
# Pixel-space noise std for VP diffusion initialization
|
| 27 |
+
pixel_noise_std: float = 0.558
|
| 28 |
+
|
| 29 |
+
def save(self, path: str | Path) -> None:
|
| 30 |
+
"""Save config as JSON."""
|
| 31 |
+
p = Path(path)
|
| 32 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
p.write_text(json.dumps(asdict(self), indent=2) + "\n")
|
| 34 |
+
|
| 35 |
+
@classmethod
|
| 36 |
+
def load(cls, path: str | Path) -> IRDiffAEConfig:
|
| 37 |
+
"""Load config from JSON."""
|
| 38 |
+
data = json.loads(Path(path).read_text())
|
| 39 |
+
return cls(**data)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
class IRDiffAEInferenceConfig:
|
| 44 |
+
"""User-tunable inference parameters with sensible defaults."""
|
| 45 |
+
|
| 46 |
+
num_steps: int = 1 # decoder forward passes (NFE)
|
| 47 |
+
sampler: str = "ddim" # "ddim" or "dpmpp_2m"
|
| 48 |
+
schedule: str = "linear" # "linear" or "cosine"
|
| 49 |
+
pdg_enabled: bool = False
|
| 50 |
+
pdg_strength: float = 2.0
|
| 51 |
+
seed: int | None = None
|
ir_diffae/conv_mlp.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conv-based MLP with GELU activation for DiCo blocks."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch import Tensor, nn
|
| 7 |
+
|
| 8 |
+
from .norms import ChannelWiseRMSNorm
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ConvMLP(nn.Module):
|
| 12 |
+
"""1x1 Conv-based MLP: RMSNorm -> Conv1x1 -> GELU -> Conv1x1."""
|
| 13 |
+
|
| 14 |
+
def __init__(
|
| 15 |
+
self, channels: int, hidden_channels: int, norm_eps: float = 1e-6
|
| 16 |
+
) -> None:
|
| 17 |
+
super().__init__()
|
| 18 |
+
self.norm = ChannelWiseRMSNorm(channels, eps=norm_eps, affine=False)
|
| 19 |
+
self.conv_in = nn.Conv2d(channels, hidden_channels, kernel_size=1, bias=True)
|
| 20 |
+
self.conv_out = nn.Conv2d(hidden_channels, channels, kernel_size=1, bias=True)
|
| 21 |
+
|
| 22 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 23 |
+
y = self.norm(x)
|
| 24 |
+
y = self.conv_in(y)
|
| 25 |
+
y = F.gelu(y)
|
| 26 |
+
return self.conv_out(y)
|
ir_diffae/decoder.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""iRDiffAE decoder: conditioned DiCoBlocks with AdaLN + skip connection."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch import Tensor, nn
|
| 7 |
+
|
| 8 |
+
from .adaln import AdaLNZeroLowRankDelta, AdaLNZeroProjector
|
| 9 |
+
from .dico_block import DiCoBlock
|
| 10 |
+
from .norms import ChannelWiseRMSNorm
|
| 11 |
+
from .straight_through_encoder import Patchify
|
| 12 |
+
from .time_embed import SinusoidalTimeEmbeddingMLP
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Decoder(nn.Module):
|
| 16 |
+
"""VP diffusion decoder conditioned on encoder latents and timestep.
|
| 17 |
+
|
| 18 |
+
Architecture:
|
| 19 |
+
Patchify x_t -> Norm -> Fuse with upsampled z
|
| 20 |
+
-> Start blocks (2) -> Middle blocks (depth-4) -> Skip fuse -> End blocks (2)
|
| 21 |
+
-> Norm -> Conv1x1 -> PixelShuffle
|
| 22 |
+
|
| 23 |
+
Middle blocks support path-drop for PDG (inference-time guidance).
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
in_channels: int,
|
| 29 |
+
patch_size: int,
|
| 30 |
+
model_dim: int,
|
| 31 |
+
depth: int,
|
| 32 |
+
bottleneck_dim: int,
|
| 33 |
+
mlp_ratio: float,
|
| 34 |
+
depthwise_kernel_size: int,
|
| 35 |
+
adaln_low_rank_rank: int,
|
| 36 |
+
) -> None:
|
| 37 |
+
super().__init__()
|
| 38 |
+
self.patch_size = int(patch_size)
|
| 39 |
+
self.model_dim = int(model_dim)
|
| 40 |
+
|
| 41 |
+
# Input processing
|
| 42 |
+
self.patchify = Patchify(in_channels, patch_size, model_dim)
|
| 43 |
+
self.norm_in = ChannelWiseRMSNorm(model_dim, eps=1e-6, affine=True)
|
| 44 |
+
|
| 45 |
+
# Latent conditioning path
|
| 46 |
+
self.latent_up = nn.Conv2d(bottleneck_dim, model_dim, kernel_size=1, bias=True)
|
| 47 |
+
self.latent_norm = ChannelWiseRMSNorm(model_dim, eps=1e-6, affine=True)
|
| 48 |
+
self.fuse_in = nn.Conv2d(2 * model_dim, model_dim, kernel_size=1, bias=True)
|
| 49 |
+
|
| 50 |
+
# Time embedding
|
| 51 |
+
self.time_embed = SinusoidalTimeEmbeddingMLP(model_dim)
|
| 52 |
+
|
| 53 |
+
# AdaLN: shared base projector + per-block low-rank deltas
|
| 54 |
+
self.adaln_base = AdaLNZeroProjector(d_model=model_dim, d_cond=model_dim)
|
| 55 |
+
self.adaln_deltas = nn.ModuleList(
|
| 56 |
+
[
|
| 57 |
+
AdaLNZeroLowRankDelta(
|
| 58 |
+
d_model=model_dim, d_cond=model_dim, rank=adaln_low_rank_rank
|
| 59 |
+
)
|
| 60 |
+
for _ in range(depth)
|
| 61 |
+
]
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
# Block layout: start(2) + middle(depth-4) + end(2)
|
| 65 |
+
start_count = 2
|
| 66 |
+
end_count = 2
|
| 67 |
+
middle_count = depth - start_count - end_count
|
| 68 |
+
self._middle_start_idx = start_count
|
| 69 |
+
self._end_start_idx = start_count + middle_count
|
| 70 |
+
|
| 71 |
+
def _make_blocks(count: int) -> nn.ModuleList:
|
| 72 |
+
return nn.ModuleList(
|
| 73 |
+
[
|
| 74 |
+
DiCoBlock(
|
| 75 |
+
model_dim,
|
| 76 |
+
mlp_ratio,
|
| 77 |
+
depthwise_kernel_size=depthwise_kernel_size,
|
| 78 |
+
use_external_adaln=True,
|
| 79 |
+
)
|
| 80 |
+
for _ in range(count)
|
| 81 |
+
]
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
self.start_blocks = _make_blocks(start_count)
|
| 85 |
+
self.middle_blocks = _make_blocks(middle_count)
|
| 86 |
+
self.fuse_skip = nn.Conv2d(2 * model_dim, model_dim, kernel_size=1, bias=True)
|
| 87 |
+
self.end_blocks = _make_blocks(end_count)
|
| 88 |
+
|
| 89 |
+
# Learned mask feature for path-drop guidance
|
| 90 |
+
self.mask_feature = nn.Parameter(torch.zeros((1, model_dim, 1, 1)))
|
| 91 |
+
|
| 92 |
+
# Output head
|
| 93 |
+
self.norm_out = ChannelWiseRMSNorm(model_dim, eps=1e-6, affine=True)
|
| 94 |
+
self.out_proj = nn.Conv2d(
|
| 95 |
+
model_dim, in_channels * (patch_size**2), kernel_size=1, bias=True
|
| 96 |
+
)
|
| 97 |
+
self.unpatchify = nn.PixelShuffle(patch_size)
|
| 98 |
+
|
| 99 |
+
def _adaln_m_for_layer(self, cond: Tensor, layer_idx: int) -> Tensor:
|
| 100 |
+
"""Compute packed AdaLN modulation = shared_base + per-layer delta."""
|
| 101 |
+
act = self.adaln_base.act(cond)
|
| 102 |
+
base_m = self.adaln_base.forward_activated(act)
|
| 103 |
+
delta_m = self.adaln_deltas[layer_idx](act)
|
| 104 |
+
return base_m + delta_m
|
| 105 |
+
|
| 106 |
+
def _run_blocks(
|
| 107 |
+
self, blocks: nn.ModuleList, x: Tensor, cond: Tensor, start_index: int
|
| 108 |
+
) -> Tensor:
|
| 109 |
+
"""Run a group of decoder blocks with per-block AdaLN modulation."""
|
| 110 |
+
for local_idx, block in enumerate(blocks):
|
| 111 |
+
adaln_m = self._adaln_m_for_layer(cond, layer_idx=start_index + local_idx)
|
| 112 |
+
x = block(x, adaln_m=adaln_m)
|
| 113 |
+
return x
|
| 114 |
+
|
| 115 |
+
def forward(
|
| 116 |
+
self,
|
| 117 |
+
x_t: Tensor,
|
| 118 |
+
t: Tensor,
|
| 119 |
+
latents: Tensor,
|
| 120 |
+
*,
|
| 121 |
+
drop_middle_blocks: bool = False,
|
| 122 |
+
) -> Tensor:
|
| 123 |
+
"""Single decoder forward pass.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
x_t: Noised image [B, C, H, W].
|
| 127 |
+
t: Timestep [B] in [0, 1].
|
| 128 |
+
latents: Encoder latents [B, bottleneck_dim, h, w].
|
| 129 |
+
drop_middle_blocks: If True, replace middle block output with mask_feature (for PDG).
|
| 130 |
+
|
| 131 |
+
Returns:
|
| 132 |
+
x0 prediction [B, C, H, W].
|
| 133 |
+
"""
|
| 134 |
+
# Patchify and normalize x_t
|
| 135 |
+
x_feat = self.patchify(x_t)
|
| 136 |
+
x_feat = self.norm_in(x_feat)
|
| 137 |
+
|
| 138 |
+
# Upsample and normalize latents, fuse with x_feat
|
| 139 |
+
z_up = self.latent_up(latents)
|
| 140 |
+
z_up = self.latent_norm(z_up)
|
| 141 |
+
fused = torch.cat([x_feat, z_up], dim=1)
|
| 142 |
+
fused = self.fuse_in(fused)
|
| 143 |
+
|
| 144 |
+
# Time conditioning
|
| 145 |
+
cond = self.time_embed(t.to(torch.float32).to(device=x_t.device))
|
| 146 |
+
|
| 147 |
+
# Start blocks
|
| 148 |
+
start_out = self._run_blocks(self.start_blocks, fused, cond, start_index=0)
|
| 149 |
+
|
| 150 |
+
# Middle blocks (or mask feature for PDG)
|
| 151 |
+
if drop_middle_blocks:
|
| 152 |
+
middle_out = self.mask_feature.to(
|
| 153 |
+
device=x_t.device, dtype=x_t.dtype
|
| 154 |
+
).expand_as(start_out)
|
| 155 |
+
else:
|
| 156 |
+
middle_out = self._run_blocks(
|
| 157 |
+
self.middle_blocks,
|
| 158 |
+
start_out,
|
| 159 |
+
cond,
|
| 160 |
+
start_index=self._middle_start_idx,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# Skip fusion
|
| 164 |
+
skip_fused = torch.cat([start_out, middle_out], dim=1)
|
| 165 |
+
skip_fused = self.fuse_skip(skip_fused)
|
| 166 |
+
|
| 167 |
+
# End blocks
|
| 168 |
+
end_out = self._run_blocks(
|
| 169 |
+
self.end_blocks, skip_fused, cond, start_index=self._end_start_idx
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
# Output head
|
| 173 |
+
end_out = self.norm_out(end_out)
|
| 174 |
+
patches = self.out_proj(end_out)
|
| 175 |
+
return self.unpatchify(patches)
|
ir_diffae/dico_block.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DiCo block: conv path (1x1 -> depthwise -> SiLU -> CCA -> 1x1) + GELU MLP."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from torch import Tensor, nn
|
| 8 |
+
|
| 9 |
+
from .compact_channel_attention import CompactChannelAttention
|
| 10 |
+
from .conv_mlp import ConvMLP
|
| 11 |
+
from .norms import ChannelWiseRMSNorm
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class DiCoBlock(nn.Module):
|
| 15 |
+
"""DiCo-style conv block with optional external AdaLN conditioning.
|
| 16 |
+
|
| 17 |
+
Two modes:
|
| 18 |
+
- Unconditioned (encoder): uses learned per-channel residual gates.
|
| 19 |
+
- External AdaLN (decoder): receives packed modulation [B, 4*C] via adaln_m.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
channels: int,
|
| 25 |
+
mlp_ratio: float,
|
| 26 |
+
*,
|
| 27 |
+
depthwise_kernel_size: int = 7,
|
| 28 |
+
use_external_adaln: bool = False,
|
| 29 |
+
norm_eps: float = 1e-6,
|
| 30 |
+
) -> None:
|
| 31 |
+
super().__init__()
|
| 32 |
+
self.channels = int(channels)
|
| 33 |
+
self.use_external_adaln = bool(use_external_adaln)
|
| 34 |
+
|
| 35 |
+
# Pre-norm for conv and MLP paths (no affine)
|
| 36 |
+
self.norm1 = ChannelWiseRMSNorm(self.channels, eps=norm_eps, affine=False)
|
| 37 |
+
self.norm2 = ChannelWiseRMSNorm(self.channels, eps=norm_eps, affine=False)
|
| 38 |
+
|
| 39 |
+
# Conv path: 1x1 -> depthwise kxk -> SiLU -> CCA -> 1x1
|
| 40 |
+
self.conv1 = nn.Conv2d(self.channels, self.channels, kernel_size=1, bias=True)
|
| 41 |
+
self.conv2 = nn.Conv2d(
|
| 42 |
+
self.channels,
|
| 43 |
+
self.channels,
|
| 44 |
+
kernel_size=depthwise_kernel_size,
|
| 45 |
+
padding=depthwise_kernel_size // 2,
|
| 46 |
+
groups=self.channels,
|
| 47 |
+
bias=True,
|
| 48 |
+
)
|
| 49 |
+
self.conv3 = nn.Conv2d(self.channels, self.channels, kernel_size=1, bias=True)
|
| 50 |
+
self.cca = CompactChannelAttention(self.channels)
|
| 51 |
+
|
| 52 |
+
# MLP path: GELU activation
|
| 53 |
+
hidden_channels = max(int(round(float(self.channels) * mlp_ratio)), 1)
|
| 54 |
+
self.mlp = ConvMLP(self.channels, hidden_channels, norm_eps=norm_eps)
|
| 55 |
+
|
| 56 |
+
# Conditioning: learned gates (encoder) or external adaln_m (decoder)
|
| 57 |
+
if not self.use_external_adaln:
|
| 58 |
+
self.gate_attn = nn.Parameter(torch.zeros(self.channels))
|
| 59 |
+
self.gate_mlp = nn.Parameter(torch.zeros(self.channels))
|
| 60 |
+
|
| 61 |
+
def forward(self, x: Tensor, *, adaln_m: Tensor | None = None) -> Tensor:
|
| 62 |
+
b, c = x.shape[:2]
|
| 63 |
+
|
| 64 |
+
if self.use_external_adaln:
|
| 65 |
+
if adaln_m is None:
|
| 66 |
+
raise ValueError(
|
| 67 |
+
"adaln_m required for externally-conditioned DiCoBlock"
|
| 68 |
+
)
|
| 69 |
+
adaln_m_cast = adaln_m.to(device=x.device, dtype=x.dtype)
|
| 70 |
+
scale_a, gate_a, scale_m, gate_m = adaln_m_cast.chunk(4, dim=-1)
|
| 71 |
+
elif adaln_m is not None:
|
| 72 |
+
raise ValueError("adaln_m must be None for unconditioned DiCoBlock")
|
| 73 |
+
|
| 74 |
+
residual = x
|
| 75 |
+
|
| 76 |
+
# Conv path
|
| 77 |
+
x_att = self.norm1(x)
|
| 78 |
+
if self.use_external_adaln:
|
| 79 |
+
x_att = x_att * (1.0 + scale_a.view(b, c, 1, 1)) # type: ignore[possibly-undefined]
|
| 80 |
+
y = self.conv1(x_att)
|
| 81 |
+
y = self.conv2(y)
|
| 82 |
+
y = F.silu(y)
|
| 83 |
+
y = y * self.cca(y)
|
| 84 |
+
y = self.conv3(y)
|
| 85 |
+
|
| 86 |
+
if self.use_external_adaln:
|
| 87 |
+
gate_a_view = torch.tanh(gate_a).view(b, c, 1, 1) # type: ignore[possibly-undefined]
|
| 88 |
+
x = residual + gate_a_view * y
|
| 89 |
+
else:
|
| 90 |
+
gate = self.gate_attn.view(1, self.channels, 1, 1).to(
|
| 91 |
+
dtype=y.dtype, device=y.device
|
| 92 |
+
)
|
| 93 |
+
x = residual + gate * y
|
| 94 |
+
|
| 95 |
+
# MLP path
|
| 96 |
+
residual_mlp = x
|
| 97 |
+
x_mlp = self.norm2(x)
|
| 98 |
+
if self.use_external_adaln:
|
| 99 |
+
x_mlp = x_mlp * (1.0 + scale_m.view(b, c, 1, 1)) # type: ignore[possibly-undefined]
|
| 100 |
+
y_mlp = self.mlp(x_mlp)
|
| 101 |
+
|
| 102 |
+
if self.use_external_adaln:
|
| 103 |
+
gate_m_view = torch.tanh(gate_m).view(b, c, 1, 1) # type: ignore[possibly-undefined]
|
| 104 |
+
x = residual_mlp + gate_m_view * y_mlp
|
| 105 |
+
else:
|
| 106 |
+
gate = self.gate_mlp.view(1, self.channels, 1, 1).to(
|
| 107 |
+
dtype=y_mlp.dtype, device=y_mlp.device
|
| 108 |
+
)
|
| 109 |
+
x = residual_mlp + gate * y_mlp
|
| 110 |
+
|
| 111 |
+
return x
|
ir_diffae/encoder.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""iRDiffAE encoder: patchify -> DiCoBlocks -> bottleneck projection."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from torch import Tensor, nn
|
| 6 |
+
|
| 7 |
+
from .dico_block import DiCoBlock
|
| 8 |
+
from .norms import ChannelWiseRMSNorm
|
| 9 |
+
from .straight_through_encoder import Patchify
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Encoder(nn.Module):
|
| 13 |
+
"""Deterministic encoder: Image [B,3,H,W] -> latents [B,bottleneck_dim,h,w].
|
| 14 |
+
|
| 15 |
+
Pipeline: Patchify -> RMSNorm -> DiCoBlocks (unconditioned) -> Conv1x1 -> RMSNorm(no affine)
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
in_channels: int,
|
| 21 |
+
patch_size: int,
|
| 22 |
+
model_dim: int,
|
| 23 |
+
depth: int,
|
| 24 |
+
bottleneck_dim: int,
|
| 25 |
+
mlp_ratio: float,
|
| 26 |
+
depthwise_kernel_size: int,
|
| 27 |
+
) -> None:
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.patchify = Patchify(in_channels, patch_size, model_dim)
|
| 30 |
+
self.norm_in = ChannelWiseRMSNorm(model_dim, eps=1e-6, affine=True)
|
| 31 |
+
self.blocks = nn.ModuleList(
|
| 32 |
+
[
|
| 33 |
+
DiCoBlock(
|
| 34 |
+
model_dim,
|
| 35 |
+
mlp_ratio,
|
| 36 |
+
depthwise_kernel_size=depthwise_kernel_size,
|
| 37 |
+
use_external_adaln=False,
|
| 38 |
+
)
|
| 39 |
+
for _ in range(depth)
|
| 40 |
+
]
|
| 41 |
+
)
|
| 42 |
+
self.to_bottleneck = nn.Conv2d(
|
| 43 |
+
model_dim, bottleneck_dim, kernel_size=1, bias=True
|
| 44 |
+
)
|
| 45 |
+
self.norm_out = ChannelWiseRMSNorm(bottleneck_dim, eps=1e-6, affine=False)
|
| 46 |
+
|
| 47 |
+
def forward(self, images: Tensor) -> Tensor:
|
| 48 |
+
"""Encode images [B,3,H,W] in [-1,1] to latents [B,bottleneck_dim,h,w]."""
|
| 49 |
+
z = self.patchify(images)
|
| 50 |
+
z = self.norm_in(z)
|
| 51 |
+
for block in self.blocks:
|
| 52 |
+
z = block(z)
|
| 53 |
+
z = self.to_bottleneck(z)
|
| 54 |
+
z = self.norm_out(z)
|
| 55 |
+
return z
|
ir_diffae/model.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""IRDiffAE: standalone HuggingFace-compatible iRDiffAE model."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import Tensor, nn
|
| 9 |
+
|
| 10 |
+
from .config import IRDiffAEConfig, IRDiffAEInferenceConfig
|
| 11 |
+
from .decoder import Decoder
|
| 12 |
+
from .encoder import Encoder
|
| 13 |
+
from .samplers import run_ddim, run_dpmpp_2m
|
| 14 |
+
from .vp_diffusion import get_schedule, make_initial_state, sample_noise
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _resolve_model_dir(
|
| 18 |
+
path_or_repo_id: str | Path,
|
| 19 |
+
*,
|
| 20 |
+
revision: str | None,
|
| 21 |
+
cache_dir: str | Path | None,
|
| 22 |
+
) -> Path:
|
| 23 |
+
"""Resolve a local path or HuggingFace Hub repo ID to a local directory."""
|
| 24 |
+
|
| 25 |
+
local = Path(path_or_repo_id)
|
| 26 |
+
if local.is_dir():
|
| 27 |
+
return local
|
| 28 |
+
# Not a local directory β try HuggingFace Hub
|
| 29 |
+
repo_id = str(path_or_repo_id)
|
| 30 |
+
try:
|
| 31 |
+
from huggingface_hub import snapshot_download
|
| 32 |
+
except ImportError:
|
| 33 |
+
raise ImportError(
|
| 34 |
+
f"'{repo_id}' is not an existing local directory. "
|
| 35 |
+
"To download from HuggingFace Hub, install huggingface_hub: "
|
| 36 |
+
"pip install huggingface_hub"
|
| 37 |
+
)
|
| 38 |
+
cache_dir_str = str(cache_dir) if cache_dir is not None else None
|
| 39 |
+
local_dir = snapshot_download(
|
| 40 |
+
repo_id,
|
| 41 |
+
revision=revision,
|
| 42 |
+
cache_dir=cache_dir_str,
|
| 43 |
+
)
|
| 44 |
+
return Path(local_dir)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class IRDiffAE(nn.Module):
|
| 48 |
+
"""Standalone iRDiffAE model for HuggingFace distribution.
|
| 49 |
+
|
| 50 |
+
A diffusion autoencoder that encodes images to compact latents and
|
| 51 |
+
decodes them back via iterative VP diffusion.
|
| 52 |
+
|
| 53 |
+
Usage::
|
| 54 |
+
|
| 55 |
+
model = IRDiffAE.from_pretrained("path/to/weights")
|
| 56 |
+
model = model.to("cuda", dtype=torch.bfloat16)
|
| 57 |
+
|
| 58 |
+
# Encode
|
| 59 |
+
latents = model.encode(images) # images: [B,3,H,W] in [-1,1]
|
| 60 |
+
|
| 61 |
+
# Decode
|
| 62 |
+
recon = model.decode(latents, height=H, width=W)
|
| 63 |
+
|
| 64 |
+
# Reconstruct (encode + decode)
|
| 65 |
+
recon = model.reconstruct(images)
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
def __init__(self, config: IRDiffAEConfig) -> None:
|
| 69 |
+
super().__init__()
|
| 70 |
+
self.config = config
|
| 71 |
+
|
| 72 |
+
self.encoder = Encoder(
|
| 73 |
+
in_channels=config.in_channels,
|
| 74 |
+
patch_size=config.patch_size,
|
| 75 |
+
model_dim=config.model_dim,
|
| 76 |
+
depth=config.encoder_depth,
|
| 77 |
+
bottleneck_dim=config.bottleneck_dim,
|
| 78 |
+
mlp_ratio=config.mlp_ratio,
|
| 79 |
+
depthwise_kernel_size=config.depthwise_kernel_size,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
self.decoder = Decoder(
|
| 83 |
+
in_channels=config.in_channels,
|
| 84 |
+
patch_size=config.patch_size,
|
| 85 |
+
model_dim=config.model_dim,
|
| 86 |
+
depth=config.decoder_depth,
|
| 87 |
+
bottleneck_dim=config.bottleneck_dim,
|
| 88 |
+
mlp_ratio=config.mlp_ratio,
|
| 89 |
+
depthwise_kernel_size=config.depthwise_kernel_size,
|
| 90 |
+
adaln_low_rank_rank=config.adaln_low_rank_rank,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
@classmethod
|
| 94 |
+
def from_pretrained(
|
| 95 |
+
cls,
|
| 96 |
+
path_or_repo_id: str | Path,
|
| 97 |
+
*,
|
| 98 |
+
dtype: torch.dtype = torch.bfloat16,
|
| 99 |
+
device: str | torch.device = "cpu",
|
| 100 |
+
revision: str | None = None,
|
| 101 |
+
cache_dir: str | Path | None = None,
|
| 102 |
+
) -> IRDiffAE:
|
| 103 |
+
"""Load a pretrained model from a local directory or HuggingFace Hub.
|
| 104 |
+
|
| 105 |
+
The directory (or repo) should contain:
|
| 106 |
+
- config.json: Model architecture config.
|
| 107 |
+
- model.safetensors (preferred) or model.pt: Model weights.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
path_or_repo_id: Local directory path or HuggingFace Hub repo ID
|
| 111 |
+
(e.g. ``"data-archetype/irdiffae-v1"``).
|
| 112 |
+
dtype: Load weights in this dtype (float32 or bfloat16).
|
| 113 |
+
device: Target device.
|
| 114 |
+
revision: Git revision (branch, tag, or commit) for Hub downloads.
|
| 115 |
+
cache_dir: Where to cache Hub downloads. Uses HF default if None.
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
Loaded model in eval mode.
|
| 119 |
+
"""
|
| 120 |
+
model_dir = _resolve_model_dir(
|
| 121 |
+
path_or_repo_id, revision=revision, cache_dir=cache_dir
|
| 122 |
+
)
|
| 123 |
+
config = IRDiffAEConfig.load(model_dir / "config.json")
|
| 124 |
+
model = cls(config)
|
| 125 |
+
|
| 126 |
+
# Try safetensors first, fall back to .pt
|
| 127 |
+
safetensors_path = model_dir / "model.safetensors"
|
| 128 |
+
pt_path = model_dir / "model.pt"
|
| 129 |
+
|
| 130 |
+
if safetensors_path.exists():
|
| 131 |
+
try:
|
| 132 |
+
from safetensors.torch import load_file
|
| 133 |
+
|
| 134 |
+
state_dict = load_file(str(safetensors_path), device=str(device))
|
| 135 |
+
except ImportError:
|
| 136 |
+
raise ImportError(
|
| 137 |
+
"safetensors package required to load .safetensors files. "
|
| 138 |
+
"Install with: pip install safetensors"
|
| 139 |
+
)
|
| 140 |
+
elif pt_path.exists():
|
| 141 |
+
state_dict = torch.load(
|
| 142 |
+
str(pt_path), map_location=device, weights_only=True
|
| 143 |
+
)
|
| 144 |
+
else:
|
| 145 |
+
raise FileNotFoundError(
|
| 146 |
+
f"No model weights found in {model_dir}. "
|
| 147 |
+
"Expected model.safetensors or model.pt."
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
model.load_state_dict(state_dict)
|
| 151 |
+
model = model.to(dtype=dtype, device=torch.device(device))
|
| 152 |
+
model.eval()
|
| 153 |
+
return model
|
| 154 |
+
|
| 155 |
+
def encode(self, images: Tensor) -> Tensor:
|
| 156 |
+
"""Encode images to latents.
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
images: [B, 3, H, W] in [-1, 1], H and W must be divisible by patch_size.
|
| 160 |
+
|
| 161 |
+
Returns:
|
| 162 |
+
Latents [B, bottleneck_dim, H/patch, W/patch].
|
| 163 |
+
"""
|
| 164 |
+
try:
|
| 165 |
+
model_dtype = next(self.parameters()).dtype
|
| 166 |
+
except StopIteration:
|
| 167 |
+
model_dtype = torch.float32
|
| 168 |
+
return self.encoder(images.to(dtype=model_dtype))
|
| 169 |
+
|
| 170 |
+
@torch.no_grad()
|
| 171 |
+
def decode(
|
| 172 |
+
self,
|
| 173 |
+
latents: Tensor,
|
| 174 |
+
height: int,
|
| 175 |
+
width: int,
|
| 176 |
+
*,
|
| 177 |
+
inference_config: IRDiffAEInferenceConfig | None = None,
|
| 178 |
+
) -> Tensor:
|
| 179 |
+
"""Decode latents to images via VP diffusion.
|
| 180 |
+
|
| 181 |
+
Args:
|
| 182 |
+
latents: [B, bottleneck_dim, h, w] encoder latents.
|
| 183 |
+
height: Output image height (must be divisible by patch_size).
|
| 184 |
+
width: Output image width (must be divisible by patch_size).
|
| 185 |
+
inference_config: Optional inference parameters. Uses defaults if None.
|
| 186 |
+
|
| 187 |
+
Returns:
|
| 188 |
+
Reconstructed images [B, 3, H, W] in float32.
|
| 189 |
+
"""
|
| 190 |
+
cfg = inference_config or IRDiffAEInferenceConfig()
|
| 191 |
+
config = self.config
|
| 192 |
+
batch = int(latents.shape[0])
|
| 193 |
+
device = latents.device
|
| 194 |
+
|
| 195 |
+
# Determine model dtype from parameters
|
| 196 |
+
try:
|
| 197 |
+
model_dtype = next(self.parameters()).dtype
|
| 198 |
+
except StopIteration:
|
| 199 |
+
model_dtype = torch.float32
|
| 200 |
+
|
| 201 |
+
# Validate dimensions
|
| 202 |
+
if height % config.patch_size != 0 or width % config.patch_size != 0:
|
| 203 |
+
raise ValueError(
|
| 204 |
+
f"height={height} and width={width} must be divisible by patch_size={config.patch_size}"
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
# Generate initial noise
|
| 208 |
+
shape = (batch, config.in_channels, height, width)
|
| 209 |
+
noise = sample_noise(
|
| 210 |
+
shape,
|
| 211 |
+
noise_std=config.pixel_noise_std,
|
| 212 |
+
seed=cfg.seed,
|
| 213 |
+
device=torch.device("cpu"),
|
| 214 |
+
dtype=torch.float32,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
# Build schedule
|
| 218 |
+
schedule = get_schedule(cfg.schedule, cfg.num_steps).to(device=device)
|
| 219 |
+
|
| 220 |
+
# Construct initial state: sigma_start * noise
|
| 221 |
+
initial_state = make_initial_state(
|
| 222 |
+
noise=noise.to(device=device),
|
| 223 |
+
t_start=schedule[0:1],
|
| 224 |
+
logsnr_min=config.logsnr_min,
|
| 225 |
+
logsnr_max=config.logsnr_max,
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
# Disable autocast for numerical precision
|
| 229 |
+
device_type = "cuda" if device.type == "cuda" else "cpu"
|
| 230 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 231 |
+
latents_in = latents.to(device=device)
|
| 232 |
+
|
| 233 |
+
def _forward_fn(
|
| 234 |
+
x_t: Tensor,
|
| 235 |
+
t: Tensor,
|
| 236 |
+
latents: Tensor,
|
| 237 |
+
*,
|
| 238 |
+
drop_middle_blocks: bool = False,
|
| 239 |
+
) -> Tensor:
|
| 240 |
+
return self.decoder(
|
| 241 |
+
x_t.to(dtype=model_dtype),
|
| 242 |
+
t,
|
| 243 |
+
latents.to(dtype=model_dtype),
|
| 244 |
+
drop_middle_blocks=drop_middle_blocks,
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
# Select sampler
|
| 248 |
+
if cfg.sampler == "ddim":
|
| 249 |
+
sampler_fn = run_ddim
|
| 250 |
+
elif cfg.sampler == "dpmpp_2m":
|
| 251 |
+
sampler_fn = run_dpmpp_2m
|
| 252 |
+
else:
|
| 253 |
+
raise ValueError(
|
| 254 |
+
f"Unsupported sampler: {cfg.sampler!r}. Use 'ddim' or 'dpmpp_2m'."
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
result = sampler_fn(
|
| 258 |
+
forward_fn=_forward_fn,
|
| 259 |
+
initial_state=initial_state,
|
| 260 |
+
schedule=schedule,
|
| 261 |
+
latents=latents_in,
|
| 262 |
+
logsnr_min=config.logsnr_min,
|
| 263 |
+
logsnr_max=config.logsnr_max,
|
| 264 |
+
pdg_enabled=cfg.pdg_enabled,
|
| 265 |
+
pdg_strength=cfg.pdg_strength,
|
| 266 |
+
device=device,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
return result
|
| 270 |
+
|
| 271 |
+
@torch.no_grad()
|
| 272 |
+
def reconstruct(
|
| 273 |
+
self,
|
| 274 |
+
images: Tensor,
|
| 275 |
+
*,
|
| 276 |
+
inference_config: IRDiffAEInferenceConfig | None = None,
|
| 277 |
+
) -> Tensor:
|
| 278 |
+
"""Encode then decode. Convenience wrapper.
|
| 279 |
+
|
| 280 |
+
Args:
|
| 281 |
+
images: [B, 3, H, W] in [-1, 1].
|
| 282 |
+
inference_config: Optional inference parameters.
|
| 283 |
+
|
| 284 |
+
Returns:
|
| 285 |
+
Reconstructed images [B, 3, H, W] in float32.
|
| 286 |
+
"""
|
| 287 |
+
latents = self.encode(images)
|
| 288 |
+
_, _, h, w = images.shape
|
| 289 |
+
return self.decode(
|
| 290 |
+
latents, height=h, width=w, inference_config=inference_config
|
| 291 |
+
)
|
ir_diffae/norms.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Channel-wise RMSNorm for NCHW tensors."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch import Tensor, nn
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ChannelWiseRMSNorm(nn.Module):
|
| 10 |
+
"""Channel-wise RMSNorm with float32 reduction for numerical stability.
|
| 11 |
+
|
| 12 |
+
Normalizes across channels per spatial position. Supports optional
|
| 13 |
+
per-channel affine weight and bias.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
def __init__(self, channels: int, eps: float = 1e-6, affine: bool = True) -> None:
|
| 17 |
+
super().__init__()
|
| 18 |
+
self.channels: int = int(channels)
|
| 19 |
+
self._eps: float = float(eps)
|
| 20 |
+
if affine:
|
| 21 |
+
self.weight = nn.Parameter(torch.ones(self.channels))
|
| 22 |
+
self.bias = nn.Parameter(torch.zeros(self.channels))
|
| 23 |
+
else:
|
| 24 |
+
self.register_parameter("weight", None)
|
| 25 |
+
self.register_parameter("bias", None)
|
| 26 |
+
|
| 27 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 28 |
+
if x.dim() < 2:
|
| 29 |
+
return x
|
| 30 |
+
# Float32 accumulation for stability
|
| 31 |
+
ms = torch.mean(torch.square(x), dim=1, keepdim=True, dtype=torch.float32)
|
| 32 |
+
inv_rms = torch.rsqrt(ms + self._eps)
|
| 33 |
+
y = x * inv_rms
|
| 34 |
+
if self.weight is not None:
|
| 35 |
+
shape = (1, -1) + (1,) * (x.dim() - 2)
|
| 36 |
+
y = y * self.weight.view(shape).to(dtype=y.dtype)
|
| 37 |
+
if self.bias is not None:
|
| 38 |
+
y = y + self.bias.view(shape).to(dtype=y.dtype)
|
| 39 |
+
return y.to(dtype=x.dtype)
|
ir_diffae/samplers.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DDIM and DPM++2M samplers for VP diffusion with x-prediction objective."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import Protocol
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
|
| 10 |
+
from .vp_diffusion import (
|
| 11 |
+
alpha_sigma_from_logsnr,
|
| 12 |
+
broadcast_time_like,
|
| 13 |
+
shifted_cosine_interpolated_logsnr_from_t,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class DecoderForwardFn(Protocol):
|
| 18 |
+
"""Callable that predicts x0 from (x_t, t, latents)."""
|
| 19 |
+
|
| 20 |
+
def __call__(
|
| 21 |
+
self,
|
| 22 |
+
x_t: Tensor,
|
| 23 |
+
t: Tensor,
|
| 24 |
+
latents: Tensor,
|
| 25 |
+
*,
|
| 26 |
+
drop_middle_blocks: bool = False,
|
| 27 |
+
) -> Tensor: ...
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _reconstruct_eps_from_x0(
|
| 31 |
+
*, x_t: Tensor, x0_hat: Tensor, alpha: Tensor, sigma: Tensor
|
| 32 |
+
) -> Tensor:
|
| 33 |
+
"""Reconstruct eps_hat from (x_t, x0_hat) under VP parameterization.
|
| 34 |
+
|
| 35 |
+
eps_hat = (x_t - alpha * x0_hat) / sigma. All float32.
|
| 36 |
+
"""
|
| 37 |
+
alpha_view = broadcast_time_like(alpha, x_t).to(dtype=torch.float32)
|
| 38 |
+
sigma_view = broadcast_time_like(sigma, x_t).to(dtype=torch.float32)
|
| 39 |
+
x_t_f32 = x_t.to(torch.float32)
|
| 40 |
+
x0_f32 = x0_hat.to(torch.float32)
|
| 41 |
+
return (x_t_f32 - alpha_view * x0_f32) / sigma_view
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _ddim_step(
|
| 45 |
+
*,
|
| 46 |
+
x0_hat: Tensor,
|
| 47 |
+
eps_hat: Tensor,
|
| 48 |
+
alpha_next: Tensor,
|
| 49 |
+
sigma_next: Tensor,
|
| 50 |
+
ref: Tensor,
|
| 51 |
+
) -> Tensor:
|
| 52 |
+
"""DDIM step: x_next = alpha_next * x0_hat + sigma_next * eps_hat."""
|
| 53 |
+
a = broadcast_time_like(alpha_next, ref).to(dtype=torch.float32)
|
| 54 |
+
s = broadcast_time_like(sigma_next, ref).to(dtype=torch.float32)
|
| 55 |
+
return a * x0_hat + s * eps_hat
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def run_ddim(
|
| 59 |
+
*,
|
| 60 |
+
forward_fn: DecoderForwardFn,
|
| 61 |
+
initial_state: Tensor,
|
| 62 |
+
schedule: Tensor,
|
| 63 |
+
latents: Tensor,
|
| 64 |
+
logsnr_min: float,
|
| 65 |
+
logsnr_max: float,
|
| 66 |
+
log_change_high: float = 0.0,
|
| 67 |
+
log_change_low: float = 0.0,
|
| 68 |
+
pdg_enabled: bool = False,
|
| 69 |
+
pdg_strength: float = 1.5,
|
| 70 |
+
device: torch.device | None = None,
|
| 71 |
+
) -> Tensor:
|
| 72 |
+
"""Run DDIM sampling loop.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
forward_fn: Decoder forward function (x_t, t, latents) -> x0_hat.
|
| 76 |
+
initial_state: Starting noised state [B, C, H, W] in float32.
|
| 77 |
+
schedule: Descending t-schedule [num_steps] in [0, 1].
|
| 78 |
+
latents: Encoder latents [B, bottleneck_dim, h, w].
|
| 79 |
+
logsnr_min, logsnr_max: VP schedule endpoints.
|
| 80 |
+
log_change_high, log_change_low: Shifted-cosine schedule parameters.
|
| 81 |
+
pdg_enabled: Whether to use Path-Drop Guidance.
|
| 82 |
+
pdg_strength: CFG-like strength for PDG.
|
| 83 |
+
device: Target device.
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
Denoised samples [B, C, H, W] in float32.
|
| 87 |
+
"""
|
| 88 |
+
run_device = device or initial_state.device
|
| 89 |
+
batch_size = int(initial_state.shape[0])
|
| 90 |
+
state = initial_state.to(device=run_device, dtype=torch.float32)
|
| 91 |
+
|
| 92 |
+
# Precompute logSNR, alpha, sigma for all schedule points
|
| 93 |
+
lmb = shifted_cosine_interpolated_logsnr_from_t(
|
| 94 |
+
schedule.to(device=run_device),
|
| 95 |
+
logsnr_min=logsnr_min,
|
| 96 |
+
logsnr_max=logsnr_max,
|
| 97 |
+
log_change_high=log_change_high,
|
| 98 |
+
log_change_low=log_change_low,
|
| 99 |
+
)
|
| 100 |
+
alpha_sched, sigma_sched = alpha_sigma_from_logsnr(lmb)
|
| 101 |
+
|
| 102 |
+
for i in range(int(schedule.numel()) - 1):
|
| 103 |
+
t_i = schedule[i]
|
| 104 |
+
a_t = alpha_sched[i].expand(batch_size)
|
| 105 |
+
s_t = sigma_sched[i].expand(batch_size)
|
| 106 |
+
a_next = alpha_sched[i + 1].expand(batch_size)
|
| 107 |
+
s_next = sigma_sched[i + 1].expand(batch_size)
|
| 108 |
+
|
| 109 |
+
# Model prediction
|
| 110 |
+
t_vec = t_i.expand(batch_size).to(device=run_device, dtype=torch.float32)
|
| 111 |
+
if pdg_enabled:
|
| 112 |
+
x0_uncond = forward_fn(state, t_vec, latents, drop_middle_blocks=True).to(
|
| 113 |
+
torch.float32
|
| 114 |
+
)
|
| 115 |
+
x0_cond = forward_fn(state, t_vec, latents, drop_middle_blocks=False).to(
|
| 116 |
+
torch.float32
|
| 117 |
+
)
|
| 118 |
+
x0_hat = x0_uncond + pdg_strength * (x0_cond - x0_uncond)
|
| 119 |
+
else:
|
| 120 |
+
x0_hat = forward_fn(state, t_vec, latents, drop_middle_blocks=False).to(
|
| 121 |
+
torch.float32
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
eps_hat = _reconstruct_eps_from_x0(
|
| 125 |
+
x_t=state, x0_hat=x0_hat, alpha=a_t, sigma=s_t
|
| 126 |
+
)
|
| 127 |
+
state = _ddim_step(
|
| 128 |
+
x0_hat=x0_hat,
|
| 129 |
+
eps_hat=eps_hat,
|
| 130 |
+
alpha_next=a_next,
|
| 131 |
+
sigma_next=s_next,
|
| 132 |
+
ref=state,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
return state
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def run_dpmpp_2m(
|
| 139 |
+
*,
|
| 140 |
+
forward_fn: DecoderForwardFn,
|
| 141 |
+
initial_state: Tensor,
|
| 142 |
+
schedule: Tensor,
|
| 143 |
+
latents: Tensor,
|
| 144 |
+
logsnr_min: float,
|
| 145 |
+
logsnr_max: float,
|
| 146 |
+
log_change_high: float = 0.0,
|
| 147 |
+
log_change_low: float = 0.0,
|
| 148 |
+
pdg_enabled: bool = False,
|
| 149 |
+
pdg_strength: float = 1.5,
|
| 150 |
+
device: torch.device | None = None,
|
| 151 |
+
) -> Tensor:
|
| 152 |
+
"""Run DPM++2M sampling loop.
|
| 153 |
+
|
| 154 |
+
Multi-step solver using exponential integrator formulation in half-lambda space.
|
| 155 |
+
"""
|
| 156 |
+
run_device = device or initial_state.device
|
| 157 |
+
batch_size = int(initial_state.shape[0])
|
| 158 |
+
state = initial_state.to(device=run_device, dtype=torch.float32)
|
| 159 |
+
|
| 160 |
+
# Precompute logSNR, alpha, sigma, half-lambda for all schedule points
|
| 161 |
+
lmb = shifted_cosine_interpolated_logsnr_from_t(
|
| 162 |
+
schedule.to(device=run_device),
|
| 163 |
+
logsnr_min=logsnr_min,
|
| 164 |
+
logsnr_max=logsnr_max,
|
| 165 |
+
log_change_high=log_change_high,
|
| 166 |
+
log_change_low=log_change_low,
|
| 167 |
+
)
|
| 168 |
+
alpha_sched, sigma_sched = alpha_sigma_from_logsnr(lmb)
|
| 169 |
+
half_lambda = 0.5 * lmb.to(torch.float32)
|
| 170 |
+
|
| 171 |
+
x0_prev: Tensor | None = None
|
| 172 |
+
|
| 173 |
+
for i in range(int(schedule.numel()) - 1):
|
| 174 |
+
t_i = schedule[i]
|
| 175 |
+
s_t = sigma_sched[i].expand(batch_size)
|
| 176 |
+
a_next = alpha_sched[i + 1].expand(batch_size)
|
| 177 |
+
s_next = sigma_sched[i + 1].expand(batch_size)
|
| 178 |
+
|
| 179 |
+
# Model prediction
|
| 180 |
+
t_vec = t_i.expand(batch_size).to(device=run_device, dtype=torch.float32)
|
| 181 |
+
if pdg_enabled:
|
| 182 |
+
x0_uncond = forward_fn(state, t_vec, latents, drop_middle_blocks=True).to(
|
| 183 |
+
torch.float32
|
| 184 |
+
)
|
| 185 |
+
x0_cond = forward_fn(state, t_vec, latents, drop_middle_blocks=False).to(
|
| 186 |
+
torch.float32
|
| 187 |
+
)
|
| 188 |
+
x0_hat = x0_uncond + pdg_strength * (x0_cond - x0_uncond)
|
| 189 |
+
else:
|
| 190 |
+
x0_hat = forward_fn(state, t_vec, latents, drop_middle_blocks=False).to(
|
| 191 |
+
torch.float32
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
lam_t = half_lambda[i].expand(batch_size)
|
| 195 |
+
lam_next = half_lambda[i + 1].expand(batch_size)
|
| 196 |
+
h = (lam_next - lam_t).to(torch.float32)
|
| 197 |
+
phi_1 = torch.expm1(-h)
|
| 198 |
+
|
| 199 |
+
sigma_ratio = (s_next / s_t).to(torch.float32)
|
| 200 |
+
|
| 201 |
+
if i == 0 or x0_prev is None:
|
| 202 |
+
# First-order step
|
| 203 |
+
state = (
|
| 204 |
+
sigma_ratio.view(-1, *([1] * (state.dim() - 1))) * state
|
| 205 |
+
- broadcast_time_like(a_next, state).to(torch.float32)
|
| 206 |
+
* broadcast_time_like(phi_1, state).to(torch.float32)
|
| 207 |
+
* x0_hat
|
| 208 |
+
)
|
| 209 |
+
else:
|
| 210 |
+
# Second-order step
|
| 211 |
+
lam_prev = half_lambda[i - 1].expand(batch_size)
|
| 212 |
+
h_0 = (lam_t - lam_prev).to(torch.float32)
|
| 213 |
+
r0 = h_0 / h
|
| 214 |
+
d1_0 = (x0_hat - x0_prev) / broadcast_time_like(r0, x0_hat)
|
| 215 |
+
common = broadcast_time_like(a_next, state).to(
|
| 216 |
+
torch.float32
|
| 217 |
+
) * broadcast_time_like(phi_1, state).to(torch.float32)
|
| 218 |
+
state = (
|
| 219 |
+
sigma_ratio.view(-1, *([1] * (state.dim() - 1))) * state
|
| 220 |
+
- common * x0_hat
|
| 221 |
+
- 0.5 * common * d1_0
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
x0_prev = x0_hat
|
| 225 |
+
|
| 226 |
+
return state
|
ir_diffae/straight_through_encoder.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PixelUnshuffle-based patchifier (no residual conv path)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from torch import Tensor, nn
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Patchify(nn.Module):
|
| 9 |
+
"""PixelUnshuffle(patch) -> Conv2d 1x1 projection.
|
| 10 |
+
|
| 11 |
+
Converts [B, C, H, W] images into [B, out_channels, H/patch, W/patch] features.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
def __init__(self, in_channels: int, patch: int, out_channels: int) -> None:
|
| 15 |
+
super().__init__()
|
| 16 |
+
self.patch = int(patch)
|
| 17 |
+
self.unshuffle = nn.PixelUnshuffle(self.patch)
|
| 18 |
+
in_after = in_channels * (self.patch * self.patch)
|
| 19 |
+
self.proj = nn.Conv2d(in_after, out_channels, kernel_size=1, bias=True)
|
| 20 |
+
|
| 21 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 22 |
+
if x.shape[2] % self.patch != 0 or x.shape[3] % self.patch != 0:
|
| 23 |
+
raise ValueError(
|
| 24 |
+
f"Input H={x.shape[2]} and W={x.shape[3]} must be divisible by patch={self.patch}"
|
| 25 |
+
)
|
| 26 |
+
y = self.unshuffle(x)
|
| 27 |
+
return self.proj(y)
|
ir_diffae/time_embed.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sinusoidal timestep embedding with MLP projection."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import Tensor, nn
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _log_spaced_frequencies(
|
| 12 |
+
half: int, max_period: float, *, device: torch.device | None = None
|
| 13 |
+
) -> Tensor:
|
| 14 |
+
"""Log-spaced frequencies for sinusoidal embedding."""
|
| 15 |
+
return torch.exp(
|
| 16 |
+
-math.log(max_period)
|
| 17 |
+
* torch.arange(half, device=device, dtype=torch.float32)
|
| 18 |
+
/ max(float(half - 1), 1.0)
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def sinusoidal_time_embedding(
|
| 23 |
+
t: Tensor,
|
| 24 |
+
dim: int,
|
| 25 |
+
*,
|
| 26 |
+
max_period: float = 10000.0,
|
| 27 |
+
scale: float | None = None,
|
| 28 |
+
freqs: Tensor | None = None,
|
| 29 |
+
) -> Tensor:
|
| 30 |
+
"""Sinusoidal timestep embedding (DDPM/DiT-style). Always float32."""
|
| 31 |
+
t32 = t.to(torch.float32)
|
| 32 |
+
if scale is not None:
|
| 33 |
+
t32 = t32 * float(scale)
|
| 34 |
+
half = dim // 2
|
| 35 |
+
if freqs is not None:
|
| 36 |
+
freqs = freqs.to(device=t32.device, dtype=torch.float32)
|
| 37 |
+
else:
|
| 38 |
+
freqs = _log_spaced_frequencies(half, max_period, device=t32.device)
|
| 39 |
+
angles = t32[:, None] * freqs[None, :]
|
| 40 |
+
return torch.cat([torch.sin(angles), torch.cos(angles)], dim=-1)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class SinusoidalTimeEmbeddingMLP(nn.Module):
|
| 44 |
+
"""Sinusoidal time embedding followed by Linear -> SiLU -> Linear."""
|
| 45 |
+
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
dim: int,
|
| 49 |
+
*,
|
| 50 |
+
freq_dim: int = 256,
|
| 51 |
+
hidden_mult: float = 1.0,
|
| 52 |
+
time_scale: float = 1000.0,
|
| 53 |
+
max_period: float = 10000.0,
|
| 54 |
+
) -> None:
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.dim = int(dim)
|
| 57 |
+
self.freq_dim = int(freq_dim)
|
| 58 |
+
self.time_scale = float(time_scale)
|
| 59 |
+
self.max_period = float(max_period)
|
| 60 |
+
hidden_dim = max(int(round(int(dim) * float(hidden_mult))), 1)
|
| 61 |
+
|
| 62 |
+
freqs = _log_spaced_frequencies(self.freq_dim // 2, self.max_period)
|
| 63 |
+
self.register_buffer("freqs", freqs, persistent=True)
|
| 64 |
+
|
| 65 |
+
self.proj_in = nn.Linear(self.freq_dim, hidden_dim)
|
| 66 |
+
self.act = nn.SiLU()
|
| 67 |
+
self.proj_out = nn.Linear(hidden_dim, self.dim)
|
| 68 |
+
|
| 69 |
+
def forward(self, t: Tensor) -> Tensor:
|
| 70 |
+
freqs: Tensor = self.freqs # type: ignore[assignment]
|
| 71 |
+
emb_freq = sinusoidal_time_embedding(
|
| 72 |
+
t.to(torch.float32),
|
| 73 |
+
self.freq_dim,
|
| 74 |
+
max_period=self.max_period,
|
| 75 |
+
scale=self.time_scale,
|
| 76 |
+
freqs=freqs,
|
| 77 |
+
)
|
| 78 |
+
dtype_in = self.proj_in.weight.dtype
|
| 79 |
+
hidden = self.proj_in(emb_freq.to(dtype_in))
|
| 80 |
+
hidden = self.act(hidden)
|
| 81 |
+
if hidden.dtype != self.proj_out.weight.dtype:
|
| 82 |
+
hidden = hidden.to(self.proj_out.weight.dtype)
|
| 83 |
+
return self.proj_out(hidden)
|
ir_diffae/vp_diffusion.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""VP diffusion math: logSNR schedules, alpha/sigma computation, noise construction."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def alpha_sigma_from_logsnr(lmb: Tensor) -> tuple[Tensor, Tensor]:
|
| 12 |
+
"""Compute (alpha, sigma) from logSNR in float32.
|
| 13 |
+
|
| 14 |
+
VP constraint: alpha^2 + sigma^2 = 1.
|
| 15 |
+
"""
|
| 16 |
+
lmb32 = lmb.to(dtype=torch.float32)
|
| 17 |
+
alpha = torch.sqrt(torch.sigmoid(lmb32))
|
| 18 |
+
sigma = torch.sqrt(torch.sigmoid(-lmb32))
|
| 19 |
+
return alpha, sigma
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def broadcast_time_like(coeff: Tensor, x: Tensor) -> Tensor:
|
| 23 |
+
"""Broadcast [B] coefficient to match x for per-sample scaling."""
|
| 24 |
+
view_shape = (int(x.shape[0]),) + (1,) * (x.dim() - 1)
|
| 25 |
+
return coeff.view(view_shape)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _cosine_interpolated_params(
|
| 29 |
+
logsnr_min: float, logsnr_max: float
|
| 30 |
+
) -> tuple[float, float]:
|
| 31 |
+
"""Compute (a, b) for cosine-interpolated logSNR schedule.
|
| 32 |
+
|
| 33 |
+
logsnr(t) = -2 * log(tan(a*t + b))
|
| 34 |
+
logsnr(0) = logsnr_max, logsnr(1) = logsnr_min
|
| 35 |
+
"""
|
| 36 |
+
b = math.atan(math.exp(-0.5 * logsnr_max))
|
| 37 |
+
a = math.atan(math.exp(-0.5 * logsnr_min)) - b
|
| 38 |
+
return a, b
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def cosine_interpolated_logsnr_from_t(
|
| 42 |
+
t: Tensor, *, logsnr_min: float, logsnr_max: float
|
| 43 |
+
) -> Tensor:
|
| 44 |
+
"""Map t in [0,1] to logSNR via cosine-interpolated schedule. Always float32."""
|
| 45 |
+
a, b = _cosine_interpolated_params(logsnr_min, logsnr_max)
|
| 46 |
+
t32 = t.to(dtype=torch.float32)
|
| 47 |
+
a_t = torch.tensor(a, device=t32.device, dtype=torch.float32)
|
| 48 |
+
b_t = torch.tensor(b, device=t32.device, dtype=torch.float32)
|
| 49 |
+
u = a_t * t32 + b_t
|
| 50 |
+
return -2.0 * torch.log(torch.tan(u))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def shifted_cosine_interpolated_logsnr_from_t(
|
| 54 |
+
t: Tensor,
|
| 55 |
+
*,
|
| 56 |
+
logsnr_min: float,
|
| 57 |
+
logsnr_max: float,
|
| 58 |
+
log_change_high: float = 0.0,
|
| 59 |
+
log_change_low: float = 0.0,
|
| 60 |
+
) -> Tensor:
|
| 61 |
+
"""SiD2 "shifted cosine" schedule: logSNR with resolution-dependent shifts.
|
| 62 |
+
|
| 63 |
+
lambda(t) = (1-t) * (base(t) + log_change_high) + t * (base(t) + log_change_low)
|
| 64 |
+
"""
|
| 65 |
+
base = cosine_interpolated_logsnr_from_t(
|
| 66 |
+
t, logsnr_min=logsnr_min, logsnr_max=logsnr_max
|
| 67 |
+
)
|
| 68 |
+
t32 = t.to(dtype=torch.float32)
|
| 69 |
+
high = base + float(log_change_high)
|
| 70 |
+
low = base + float(log_change_low)
|
| 71 |
+
return (1.0 - t32) * high + t32 * low
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def get_schedule(schedule_type: str, num_steps: int) -> Tensor:
|
| 75 |
+
"""Generate a descending t-schedule in [0, 1] for VP diffusion sampling.
|
| 76 |
+
|
| 77 |
+
``num_steps`` is the number of function evaluations (NFE = decoder forward
|
| 78 |
+
passes). Internally the schedule has ``num_steps + 1`` time points
|
| 79 |
+
(including both endpoints).
|
| 80 |
+
|
| 81 |
+
Args:
|
| 82 |
+
schedule_type: "linear" or "cosine".
|
| 83 |
+
num_steps: Number of decoder forward passes (NFE), >= 1.
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
Descending 1D tensor with ``num_steps + 1`` elements from ~1.0 to ~0.0.
|
| 87 |
+
"""
|
| 88 |
+
# NOTE: the upstream training code (src/ode/time_schedules.py) uses a
|
| 89 |
+
# different convention where num_steps counts schedule *points* (so NFE =
|
| 90 |
+
# num_steps - 1). This export package corrects the off-by-one so that
|
| 91 |
+
# num_steps means NFE directly. TODO: align the upstream convention.
|
| 92 |
+
n = max(int(num_steps) + 1, 2)
|
| 93 |
+
if schedule_type == "linear":
|
| 94 |
+
base = torch.linspace(0.0, 1.0, n)
|
| 95 |
+
elif schedule_type == "cosine":
|
| 96 |
+
i = torch.arange(n, dtype=torch.float32)
|
| 97 |
+
base = 0.5 * (1.0 - torch.cos(math.pi * (i / (n - 1))))
|
| 98 |
+
else:
|
| 99 |
+
raise ValueError(
|
| 100 |
+
f"Unsupported schedule type: {schedule_type!r}. Use 'linear' or 'cosine'."
|
| 101 |
+
)
|
| 102 |
+
# Descending: high t (noisy) -> low t (clean)
|
| 103 |
+
return torch.flip(base, dims=[0])
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def make_initial_state(
|
| 107 |
+
*,
|
| 108 |
+
noise: Tensor,
|
| 109 |
+
t_start: Tensor,
|
| 110 |
+
logsnr_min: float,
|
| 111 |
+
logsnr_max: float,
|
| 112 |
+
log_change_high: float = 0.0,
|
| 113 |
+
log_change_low: float = 0.0,
|
| 114 |
+
) -> Tensor:
|
| 115 |
+
"""Construct VP initial state x_t0 = sigma_start * noise (since x0=0).
|
| 116 |
+
|
| 117 |
+
All math in float32.
|
| 118 |
+
"""
|
| 119 |
+
batch = int(noise.shape[0])
|
| 120 |
+
lmb_start = shifted_cosine_interpolated_logsnr_from_t(
|
| 121 |
+
t_start.expand(batch).to(dtype=torch.float32),
|
| 122 |
+
logsnr_min=logsnr_min,
|
| 123 |
+
logsnr_max=logsnr_max,
|
| 124 |
+
log_change_high=log_change_high,
|
| 125 |
+
log_change_low=log_change_low,
|
| 126 |
+
)
|
| 127 |
+
_alpha_start, sigma_start = alpha_sigma_from_logsnr(lmb_start)
|
| 128 |
+
sigma_view = broadcast_time_like(sigma_start, noise)
|
| 129 |
+
return sigma_view * noise.to(dtype=torch.float32)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def sample_noise(
|
| 133 |
+
shape: tuple[int, ...],
|
| 134 |
+
*,
|
| 135 |
+
noise_std: float = 1.0,
|
| 136 |
+
seed: int | None = None,
|
| 137 |
+
device: torch.device | None = None,
|
| 138 |
+
dtype: torch.dtype = torch.float32,
|
| 139 |
+
) -> Tensor:
|
| 140 |
+
"""Sample Gaussian noise with optional seeding. CPU-seeded for reproducibility."""
|
| 141 |
+
if seed is None:
|
| 142 |
+
noise = torch.randn(
|
| 143 |
+
shape, device=device or torch.device("cpu"), dtype=torch.float32
|
| 144 |
+
)
|
| 145 |
+
else:
|
| 146 |
+
gen = torch.Generator(device="cpu")
|
| 147 |
+
gen.manual_seed(int(seed))
|
| 148 |
+
noise = torch.randn(shape, generator=gen, device="cpu", dtype=torch.float32)
|
| 149 |
+
noise = noise.mul(float(noise_std))
|
| 150 |
+
target_device = device if device is not None else torch.device("cpu")
|
| 151 |
+
return noise.to(device=target_device, dtype=dtype)
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fef9fecaafaae0814ebcb1ca060e73c91e7a485c58bbbcbc569b4dfc2a5e8879
|
| 3 |
+
size 483850752
|
technical_report.md
ADDED
|
@@ -0,0 +1,709 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# iRDiffAE v1.0 β Technical Report
|
| 2 |
+
|
| 3 |
+
**i**REPA **Diff**usion **A**uto**E**ncoder = **iRDiffAE**
|
| 4 |
+
|
| 5 |
+
A fast, single-GPU-trainable diffusion autoencoder with spatially structured
|
| 6 |
+
latents for rapid downstream model convergence. Encoding runs ~5Γ faster than
|
| 7 |
+
Flux VAE; single-step decoding runs ~3Γ faster.
|
| 8 |
+
|
| 9 |
+
## Contents
|
| 10 |
+
|
| 11 |
+
1. [VP Diffusion Parameterization](#1-vp-diffusion-parameterization)
|
| 12 |
+
- [Forward Process](#11-forward-process) Β· [Log SNR](#12-log-signal-to-noise-ratio) Β· [Cosine Schedule](#13-cosine-interpolated-schedule) Β· [X-Prediction](#14-x-prediction-objective) Β· [Sampling](#15-sampling)
|
| 13 |
+
2. [Architecture](#2-architecture)
|
| 14 |
+
- [Overview](#21-overview) Β· [DiCo Block](#22-dico-block) Β· [Encoder](#23-encoder) Β· [Decoder](#24-decoder) Β· [AdaLN](#25-adaln-shared-base--low-rank-deltas) Β· [PDG](#26-path-drop-guidance-pdg)
|
| 15 |
+
3. [Design Choices](#3-design-choices)
|
| 16 |
+
- [Convolutional Architecture](#31-convolutional-architecture) Β· [Single-Stride Encoder](#32-single-stride-encoder-with-final-bottleneck) Β· [Diffusion vs GAN Decoding](#33-diffusion-decoding-vs-gan-based-decoding) Β· [Skip Connection & PDG](#34-skip-connection-and-path-drop-guidance) Β· [iREPA](#35-half-channel-representation-alignment-irepa)
|
| 17 |
+
4. [Model Configuration](#4-model-configuration)
|
| 18 |
+
5. [Training](#5-training)
|
| 19 |
+
- [Data](#51-data) Β· [Timestep Sampling](#52-timestep-sampling) Β· [Latent Noise Sync](#53-latent-noise-synchronization-dito-regularization) Β· [Noise Standards](#54-pixel-vs-latent-noise-standards) Β· [Optimizer](#55-optimizer-and-hyperparameters) Β· [Loss](#56-loss)
|
| 20 |
+
6. [Inference](#6-inference)
|
| 21 |
+
- [Sampling Pipeline](#61-sampling-pipeline) Β· [Recommended Settings](#62-recommended-settings) Β· [Usage](#63-usage)
|
| 22 |
+
7. [Results](#7-results)
|
| 23 |
+
- [Interactive Viewer](#71-interactive-viewer) Β· [Inference Settings](#72-inference-settings) Β· [Global Metrics](#73-global-metrics) Β· [Per-Image PSNR](#74-per-image-psnr-db) Β· [Latent Smoothness](#75-latent-space-smoothness)
|
| 24 |
+
|
| 25 |
+
**References:**
|
| 26 |
+
|
| 27 |
+
- **SiD2** β Hoogeboom et al., *Simpler Diffusion (SiD2): 1.5 FID on ImageNet512 with pixel-space diffusion*, [arXiv:2410.19324](https://arxiv.org/abs/2410.19324), ICLR 2025.
|
| 28 |
+
- **DiTo** β Yin et al., *Diffusion Autoencoders are Scalable Image Tokenizers*, [arXiv:2501.18593](https://arxiv.org/abs/2501.18593), 2025.
|
| 29 |
+
- **DiCo** β Ai et al., *DiCo: Revitalizing ConvNets for Scalable and Efficient Diffusion Modeling*, [arXiv:2505.11196](https://arxiv.org/abs/2505.11196), 2025.
|
| 30 |
+
- **SPRINT** β Park et al., *Sprint: Sparse-Dense Residual Fusion for Efficient Diffusion Transformers*, [arXiv:2510.21986](https://arxiv.org/abs/2510.21986), 2025.
|
| 31 |
+
- **Z-image** β Cai et al., *Z-Image: An Efficient Image Generation Foundation Model with Single-Stream Diffusion Transformer*, [arXiv:2511.22699](https://arxiv.org/abs/2511.22699), 2025.
|
| 32 |
+
- **iREPA** β Singh et al., *What matters for Representation Alignment: Global Information or Spatial Structure?*, [arXiv:2512.10794](https://arxiv.org/abs/2512.10794), 2025.
|
| 33 |
+
|
| 34 |
+
---
|
| 35 |
+
|
| 36 |
+
## 1. VP Diffusion Parameterization
|
| 37 |
+
|
| 38 |
+
iRDiffAE uses the variance-preserving (VP) diffusion framework from SiD2
|
| 39 |
+
with an x-prediction objective.
|
| 40 |
+
|
| 41 |
+
### 1.1 Forward Process
|
| 42 |
+
|
| 43 |
+
Given a clean image \\(x_0\\), the forward process constructs a noisy sample at
|
| 44 |
+
continuous time \\(t \in [0, 1]\\):
|
| 45 |
+
|
| 46 |
+
$$x_t = \alpha_t \, x_0 + \sigma_t \, \varepsilon, \qquad \varepsilon \sim \mathcal{N}(0, s^2 I)$$
|
| 47 |
+
|
| 48 |
+
where \\(s = 0.558\\) is the pixel-space noise standard deviation (estimated from
|
| 49 |
+
the dataset image distribution) and the VP constraint holds:
|
| 50 |
+
|
| 51 |
+
$$\alpha_t^2 + \sigma_t^2 = 1$$
|
| 52 |
+
|
| 53 |
+
### 1.2 Log Signal-to-Noise Ratio
|
| 54 |
+
|
| 55 |
+
The schedule is parameterized through the log signal-to-noise ratio:
|
| 56 |
+
|
| 57 |
+
$$\lambda_t = \log \frac{\alpha_t^2}{\sigma_t^2}$$
|
| 58 |
+
|
| 59 |
+
which monotonically decreases as \\(t \to 1\\) (pure noise). From \\(\lambda_t\\) we
|
| 60 |
+
recover \\(\alpha_t\\) and \\(\sigma_t\\) via the sigmoid function:
|
| 61 |
+
|
| 62 |
+
$$\alpha_t = \sqrt{\sigma(\lambda_t)}, \qquad \sigma_t = \sqrt{\sigma(-\lambda_t)}$$
|
| 63 |
+
|
| 64 |
+
where \\(\sigma(\cdot)\\) is the logistic sigmoid.
|
| 65 |
+
|
| 66 |
+
### 1.3 Cosine-Interpolated Schedule
|
| 67 |
+
|
| 68 |
+
Following SiD2, the logSNR schedule uses cosine interpolation:
|
| 69 |
+
|
| 70 |
+
$$\lambda(t) = -2 \log \tan(a \cdot t + b)$$
|
| 71 |
+
|
| 72 |
+
where \\(a\\) and \\(b\\) are computed to satisfy the boundary conditions
|
| 73 |
+
\\(\lambda(0) = \lambda_\text{max}\\) and \\(\lambda(1) = \lambda_\text{min}\\):
|
| 74 |
+
|
| 75 |
+
$$b = \arctan\!\bigl(e^{-\lambda_\text{max}/2}\bigr), \qquad a = \arctan\!\bigl(e^{-\lambda_\text{min}/2}\bigr) - b$$
|
| 76 |
+
|
| 77 |
+
SiD2 also defines a "shifted cosine" variant with resolution-dependent additive
|
| 78 |
+
shifts \\(\Delta_\text{high}\\) and \\(\Delta_\text{low}\\):
|
| 79 |
+
|
| 80 |
+
$$\lambda_\text{shifted}(t) = (1 - t) \cdot [\lambda(t) + \Delta_\text{high}] + t \cdot [\lambda(t) + \Delta_\text{low}]$$
|
| 81 |
+
|
| 82 |
+
iRDiffAE uses \\(\lambda_\text{min} = -10\\), \\(\lambda_\text{max} = 10\\),
|
| 83 |
+
\\(\Delta_\text{high} = 0\\), and \\(\Delta_\text{low} = 0\\) (no resolution-dependent
|
| 84 |
+
shift), so the schedule reduces to the unshifted cosine interpolation.
|
| 85 |
+
|
| 86 |
+
### 1.4 X-Prediction Objective
|
| 87 |
+
|
| 88 |
+
The model predicts the clean image \\(\hat{x}_0 = f_\theta(x_t, t, z)\\)
|
| 89 |
+
conditioned on the encoder latents \\(z\\).
|
| 90 |
+
|
| 91 |
+
**Schedule-invariant loss.** Following SiD2, the training loss is defined as an
|
| 92 |
+
integral over logSNR \\(\lambda\\), making it invariant to the choice of noise
|
| 93 |
+
schedule:
|
| 94 |
+
|
| 95 |
+
$$\mathcal{L}(x) = \int w(\lambda) \, \| x_0 - \hat{x}_0 \|^2 \, d\lambda$$
|
| 96 |
+
|
| 97 |
+
Since timesteps are sampled uniformly \\(t \sim \mathcal{U}(0,1)\\) rather than
|
| 98 |
+
integrated over \\(\lambda\\) directly, the change of variable
|
| 99 |
+
\\(d\lambda = \frac{d\lambda}{dt} \, dt\\) introduces a Jacobian factor:
|
| 100 |
+
|
| 101 |
+
$$\mathcal{L} = \mathbb{E}_{t \sim \mathcal{U}(0,1)} \left[ \left(-\frac{d\lambda}{dt}\right) \cdot w(\lambda(t)) \cdot \| x_0 - \hat{x}_0 \|^2 \right]$$
|
| 102 |
+
|
| 103 |
+
**Sigmoid weighting.** SiD2 defines the weighting function in \\(\varepsilon\\)-prediction
|
| 104 |
+
form as \\(\sigma(b - \lambda)\\) β a sigmoid centered at bias \\(b\\). Converting from
|
| 105 |
+
\\(\varepsilon\\)-prediction to \\(x\\)-prediction MSE via
|
| 106 |
+
\\(\|\varepsilon - \hat{\varepsilon}\|^2 = e^{\lambda} \|x_0 - \hat{x}_0\|^2\\)
|
| 107 |
+
gives:
|
| 108 |
+
|
| 109 |
+
$$\sigma(b - \lambda) \cdot e^{\lambda} = e^b \cdot \sigma(\lambda - b)$$
|
| 110 |
+
|
| 111 |
+
Combining the Jacobian with the weighting, the per-sample weight used in
|
| 112 |
+
training is:
|
| 113 |
+
|
| 114 |
+
$$\text{weight}(t) = -\frac{1}{2} \frac{d\lambda}{dt} \cdot e^b \cdot \sigma(\lambda(t) - b)$$
|
| 115 |
+
|
| 116 |
+
The bias \\(b = -2.0\\) controls the relative emphasis on high-SNR (low-noise) vs
|
| 117 |
+
low-SNR (high-noise) timesteps. A more negative \\(b\\) shifts emphasis toward
|
| 118 |
+
noisier timesteps.
|
| 119 |
+
|
| 120 |
+
### 1.5 Sampling
|
| 121 |
+
|
| 122 |
+
At inference, each timestep \\(t\\) in the schedule is first mapped to logSNR via
|
| 123 |
+
the cosine-interpolated schedule (Section 1.3), then to diffusion coefficients:
|
| 124 |
+
|
| 125 |
+
$$t \;\xrightarrow{\text{schedule}}\; \lambda(t) \;\xrightarrow{\text{sigmoid}}\; \alpha_t = \sqrt{\sigma(\lambda)}, \quad \sigma_t = \sqrt{\sigma(-\lambda)}$$
|
| 126 |
+
|
| 127 |
+
**DDIM.** The default sampler uses a descending time schedule
|
| 128 |
+
\\(t_0 > t_1 > \cdots > t_N\\) with \\(N\\) denoising steps. At each step:
|
| 129 |
+
|
| 130 |
+
1. Predict \\(\hat{x}_0 = f_\theta(x_{t_i}, t_i, z)\\)
|
| 131 |
+
2. Reconstruct \\(\hat{\varepsilon} = \frac{x_{t_i} - \alpha_{t_i} \hat{x}_0}{\sigma_{t_i}}\\)
|
| 132 |
+
3. Step: \\(x_{t_{i+1}} = \alpha_{t_{i+1}} \hat{x}_0 + \sigma_{t_{i+1}} \hat{\varepsilon}\\)
|
| 133 |
+
|
| 134 |
+
**DPM++2M.** Also supported as an alternative sampler, using a half-lambda
|
| 135 |
+
(\\(\lambda/2\\)) exponential integrator for faster convergence with fewer steps.
|
| 136 |
+
|
| 137 |
+
---
|
| 138 |
+
|
| 139 |
+
## 2. Architecture
|
| 140 |
+
|
| 141 |
+
### 2.1 Overview
|
| 142 |
+
|
| 143 |
+
iRDiffAE consists of a deterministic encoder and an iterative VP diffusion
|
| 144 |
+
decoder. The encoder maps an image to a compact spatial latent, and the decoder
|
| 145 |
+
reconstructs the image by iteratively denoising from Gaussian noise,
|
| 146 |
+
conditioned on both the latents and the diffusion timestep.
|
| 147 |
+
|
| 148 |
+
```
|
| 149 |
+
Encoder: x β β^{BΓ3ΓHΓW} β z β β^{BΓCΓhΓw} (deterministic, single pass)
|
| 150 |
+
Decoder: (z, t, x_t) β xΜβ β β^{BΓ3ΓHΓW} (iterative, N diffusion steps)
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
where \\(h = H / p\\), \\(w = W / p\\), \\(p\\) is the patch size, and \\(C\\) is the
|
| 154 |
+
bottleneck dimension.
|
| 155 |
+
|
| 156 |
+
### 2.2 DiCo Block
|
| 157 |
+
|
| 158 |
+
Both encoder and decoder use DiCo blocks (from the [DiCo paper](https://arxiv.org/abs/2505.11196)),
|
| 159 |
+
a convolution-based alternative to transformer blocks. Each block consists of
|
| 160 |
+
two residual paths:
|
| 161 |
+
|
| 162 |
+
**Conv path:**
|
| 163 |
+
|
| 164 |
+
$$y = \text{Conv}_{1 \times 1} \to \text{DWConv}_{k \times k} \to \text{SiLU} \to \text{CCA} \to \text{Conv}_{1 \times 1}$$
|
| 165 |
+
|
| 166 |
+
**MLP path:**
|
| 167 |
+
|
| 168 |
+
$$y = \text{Conv}_{1 \times 1} \to \text{GELU} \to \text{Conv}_{1 \times 1}$$
|
| 169 |
+
|
| 170 |
+
where \\(\text{DWConv}_{k \times k}\\) is a depthwise convolution (default \\(k = 7\\))
|
| 171 |
+
and \\(\text{CCA}\\) is Compact Channel Attention:
|
| 172 |
+
|
| 173 |
+
$$\text{CCA}(y) = y \odot \sigma\bigl(\text{Conv}_{1 \times 1}(\text{AvgPool}(y))\bigr)$$
|
| 174 |
+
|
| 175 |
+
Both paths use channel-wise RMSNorm (without affine parameters) as pre-norm.
|
| 176 |
+
Residual connections use gating:
|
| 177 |
+
|
| 178 |
+
- **Encoder (unconditioned):** learned per-channel gate parameters
|
| 179 |
+
\\(x \leftarrow x + g \cdot y\\), where \\(g\\) is a learnable vector initialized to zero.
|
| 180 |
+
- **Decoder (conditioned):** AdaLN-Zero gating via
|
| 181 |
+
\\(x \leftarrow x + \tanh(g_\text{adaln}) \cdot y\\), where \\(g_\text{adaln}\\) comes
|
| 182 |
+
from the timestep conditioning.
|
| 183 |
+
|
| 184 |
+
### 2.3 Encoder
|
| 185 |
+
|
| 186 |
+
The encoder is deterministic β no variational posterior, no KL loss. Latent
|
| 187 |
+
normalization uses channel-wise RMSNorm without affine parameters, following
|
| 188 |
+
DiTo's finding that this outperforms KL regularization.
|
| 189 |
+
|
| 190 |
+
```
|
| 191 |
+
Input: x β β^{BΓ3ΓHΓW}
|
| 192 |
+
Patchify: PixelUnshuffle(p) β Conv 1Γ1 β β^{BΓDΓhΓw}
|
| 193 |
+
Norm: ChannelWise RMSNorm (affine)
|
| 194 |
+
Blocks: DiCoBlock Γ depth_enc (unconditioned, learned gates)
|
| 195 |
+
Bottleneck: Conv 1Γ1 (D β C)
|
| 196 |
+
Norm out: ChannelWise RMSNorm (no affine)
|
| 197 |
+
Output: z β β^{BΓCΓhΓw}
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
### 2.4 Decoder
|
| 201 |
+
|
| 202 |
+
The decoder predicts \\(\hat{x}_0\\) from noisy input \\(x_t\\), conditioned on
|
| 203 |
+
encoder latents \\(z\\) and timestep \\(t\\).
|
| 204 |
+
|
| 205 |
+
```
|
| 206 |
+
Patchify x_t: PixelUnshuffle(p) β Conv 1Γ1 β β^{BΓDΓhΓw}
|
| 207 |
+
Norm: ChannelWise RMSNorm (affine)
|
| 208 |
+
Upsample z: Conv 1Γ1 (C β D) β RMSNorm β β^{BΓDΓhΓw}
|
| 209 |
+
Fuse: Concat[x_feat, z_up] β Conv 1Γ1 β β^{BΓDΓhΓw}
|
| 210 |
+
|
| 211 |
+
Time embed: t β sinusoidal β MLP β cond β β^{BΓD}
|
| 212 |
+
|
| 213 |
+
Start blocks: DiCoBlock Γ 2 (AdaLN conditioned)
|
| 214 |
+
Middle blocks: DiCoBlock Γ (depth - 4) (AdaLN conditioned)
|
| 215 |
+
Skip fusion: Concat[start_out, middle_out] β Conv 1Γ1
|
| 216 |
+
End blocks: DiCoBlock Γ 2 (AdaLN conditioned)
|
| 217 |
+
|
| 218 |
+
Norm: ChannelWise RMSNorm (affine)
|
| 219 |
+
Output head: Conv 1Γ1 (D β 3Β·pΒ²) β PixelShuffle(p) β xΜβ β β^{BΓ3ΓHΓW}
|
| 220 |
+
```
|
| 221 |
+
|
| 222 |
+
### 2.5 AdaLN: Shared Base + Low-Rank Deltas
|
| 223 |
+
|
| 224 |
+
Timestep conditioning follows the Z-image style AdaLN
|
| 225 |
+
([Cai et al., 2025](https://arxiv.org/abs/2511.22699)): a shared base projection
|
| 226 |
+
plus a low-rank delta per layer, scale-and-gate modulation with no shift, and a
|
| 227 |
+
\\(\tanh\\) on the gate.
|
| 228 |
+
|
| 229 |
+
A single base projector is shared across all decoder layers, and each layer
|
| 230 |
+
adds a low-rank correction:
|
| 231 |
+
|
| 232 |
+
$$m_i = \text{Base}(\text{SiLU}(\text{cond})) + \Delta_i(\text{SiLU}(\text{cond}))$$
|
| 233 |
+
|
| 234 |
+
where \\(\text{Base}: \mathbb{R}^D \to \mathbb{R}^{4D}\\) is a linear projection
|
| 235 |
+
(zero-initialized) and \\(\Delta_i: \mathbb{R}^D \xrightarrow{\text{down}} \mathbb{R}^r \xrightarrow{\text{up}} \mathbb{R}^{4D}\\)
|
| 236 |
+
is a low-rank factorization with rank \\(r\\) (zero-initialized up-projection).
|
| 237 |
+
|
| 238 |
+
The packed modulation \\(m_i \in \mathbb{R}^{B \times 4D}\\) is chunked into four
|
| 239 |
+
vectors \\((\text{scale}_\text{conv}, \text{gate}_\text{conv}, \text{scale}_\text{mlp}, \text{gate}_\text{mlp})\\)
|
| 240 |
+
which modulate the conv and MLP paths (no shift term):
|
| 241 |
+
|
| 242 |
+
$$\hat{x} = \text{RMSNorm}(x) \odot (1 + \text{scale})$$
|
| 243 |
+
$$x \leftarrow x + \tanh(\text{gate}) \cdot f(\hat{x})$$
|
| 244 |
+
|
| 245 |
+
### 2.6 Path-Drop Guidance (PDG)
|
| 246 |
+
|
| 247 |
+
At inference, iRDiffAE supports Path-Drop Guidance β a classifier-free
|
| 248 |
+
guidance analogue that does not require training with conditioning dropout.
|
| 249 |
+
Instead, it exploits the decoder's skip connection:
|
| 250 |
+
|
| 251 |
+
1. **Conditional pass:** run all blocks normally β \\(\hat{x}_0^\text{cond}\\)
|
| 252 |
+
2. **Unconditional pass:** replace the middle block output with a learned
|
| 253 |
+
mask feature \\(m \in \mathbb{R}^{1 \times D \times 1 \times 1}\\) (initialized
|
| 254 |
+
to zero), effectively dropping the deep processing path β \\(\hat{x}_0^\text{uncond}\\)
|
| 255 |
+
3. **Guided prediction:** \\(\hat{x}_0 = \hat{x}_0^\text{uncond} + s \cdot (\hat{x}_0^\text{cond} - \hat{x}_0^\text{uncond})\\)
|
| 256 |
+
|
| 257 |
+
where \\(s\\) is the guidance strength.
|
| 258 |
+
|
| 259 |
+
---
|
| 260 |
+
|
| 261 |
+
## 3. Design Choices
|
| 262 |
+
|
| 263 |
+
### 3.1 Convolutional Architecture
|
| 264 |
+
|
| 265 |
+
iRDiffAE uses a fully convolutional architecture rather than a
|
| 266 |
+
vision transformer. For an autoencoder whose goal is faithful pixel-level
|
| 267 |
+
reconstruction (not global semantic understanding), convolutions offer
|
| 268 |
+
several advantages:
|
| 269 |
+
|
| 270 |
+
- **Resolution generalization.** Convolutions operate on local patches and
|
| 271 |
+
generalize naturally to arbitrary image dimensions without interpolating
|
| 272 |
+
position embeddings or suffering attention distribution shift from
|
| 273 |
+
sequence length changes with global attention. Convolutions are also
|
| 274 |
+
more efficient than sliding window attention for local operations.
|
| 275 |
+
- **Translation invariance.** The built-in inductive bias of weight sharing
|
| 276 |
+
across spatial positions is well matched to reconstruction, where the same
|
| 277 |
+
local patterns (edges, textures, gradients) conditioned on the low-frequency
|
| 278 |
+
latent recur throughout the image.
|
| 279 |
+
- **Locality.** Reconstruction quality depends on preserving fine spatial
|
| 280 |
+
detail. Convolutions are inherently local operators, avoiding the
|
| 281 |
+
quadratic cost of global attention while focusing computation where it
|
| 282 |
+
matters most for reconstruction.
|
| 283 |
+
|
| 284 |
+
Transformers are better suited for image *generation* (where global context
|
| 285 |
+
and long-range dependencies are essential), but convolutions are better
|
| 286 |
+
suited for autoencoders. The DiCo block provides a well-tested,
|
| 287 |
+
strong building block for convolutional diffusion models, combining depthwise
|
| 288 |
+
convolutions with compact channel attention in a design that has been
|
| 289 |
+
validated at scale.
|
| 290 |
+
|
| 291 |
+
### 3.2 Single-Stride Encoder with Final Bottleneck
|
| 292 |
+
|
| 293 |
+
The encoder uses a single spatial stride (via PixelUnshuffle at the input)
|
| 294 |
+
followed by a stack of DiCo blocks operating at constant spatial resolution,
|
| 295 |
+
then a final 1Γ1 convolution to project from model dimension \\(D\\) to
|
| 296 |
+
bottleneck dimension \\(C\\). This differs from classical VAE encoders that use
|
| 297 |
+
progressive downsampling with channel expansion at each stage.
|
| 298 |
+
|
| 299 |
+
The single-stride design ensures that all encoder blocks see the full
|
| 300 |
+
spatial resolution and full channel width simultaneously. The information
|
| 301 |
+
bottleneck is imposed only at the very end, where a single linear projection
|
| 302 |
+
selects which \\(C\\) channels to retain. Progressive compression forces early
|
| 303 |
+
layers to discard information before the full feature representation has been
|
| 304 |
+
computed, which is both computationally heavier and representationally
|
| 305 |
+
suboptimal.
|
| 306 |
+
|
| 307 |
+
### 3.3 Diffusion Decoding vs. GAN-Based Decoding
|
| 308 |
+
|
| 309 |
+
Empirically, diffusion autoencoders produce a much cleaner latent space than
|
| 310 |
+
patch-GAN + LPIPS-driven VAEs. The iterative diffusion process acts as a
|
| 311 |
+
strong structural prior on the decoder, which in turn relaxes the pressure
|
| 312 |
+
on the encoder to encode every pixel perfectly β the latent space can focus
|
| 313 |
+
on semantically meaningful structure rather than adversarial reconstruction
|
| 314 |
+
artifacts. This makes diffusion AE latents easier for a downstream
|
| 315 |
+
latent-space diffusion model to learn.
|
| 316 |
+
|
| 317 |
+
**Training efficiency.** The diffusion AE training objective is a
|
| 318 |
+
straightforward weighted MSE loss with no adversarial component β no
|
| 319 |
+
discriminator, no LPIPS perceptual loss, no delicate GAN balancing. At batch
|
| 320 |
+
size 128, the model uses less than 30 GB of VRAM and runs at 7β10 iterations
|
| 321 |
+
per second, making it trainable on a single RTX 5090 in one to two days.
|
| 322 |
+
By contrast, GAN + LPIPS-based VAEs require many days of H100 time and are
|
| 323 |
+
notoriously difficult to stabilize, with no publicly known working recipe
|
| 324 |
+
for training from scratch at comparable quality.
|
| 325 |
+
|
| 326 |
+
### 3.4 Skip Connection and Path-Drop Guidance
|
| 327 |
+
|
| 328 |
+
The decoder's start β middle β skip-fuse β end architecture is inspired by
|
| 329 |
+
SPRINT's sparse-dense residual fusion. The start blocks process the fused
|
| 330 |
+
input (noised image + latents) at full fidelity, the middle blocks perform
|
| 331 |
+
deeper processing, and the skip connection concatenates the start block
|
| 332 |
+
output with the middle block output before the end blocks.
|
| 333 |
+
|
| 334 |
+
This design serves three purposes:
|
| 335 |
+
|
| 336 |
+
1. **Regularization.** The skip path ensures that even if the middle blocks
|
| 337 |
+
are dropped or poorly conditioned, the end blocks still receive
|
| 338 |
+
meaningful features from the start blocks.
|
| 339 |
+
2. **High-frequency preservation.** The start blocks (which see the input
|
| 340 |
+
most directly) pass fine detail through the skip to the end blocks,
|
| 341 |
+
preventing the middle blocks from washing out high-frequency information.
|
| 342 |
+
3. **Path-Drop Guidance (PDG).** At inference, replacing the middle block
|
| 343 |
+
output with a learned zero-initialized mask feature creates an
|
| 344 |
+
"unconditional" prediction that preserves the skip path but drops the
|
| 345 |
+
deep processing. Interpolating between the conditional and unconditional
|
| 346 |
+
predictions (as in classifier-free guidance) sharpens the output
|
| 347 |
+
distribution β and hence the reconstructed image β without requiring
|
| 348 |
+
any training-time conditioning dropout.
|
| 349 |
+
|
| 350 |
+
### 3.5 Half-Channel Representation Alignment (iREPA)
|
| 351 |
+
|
| 352 |
+
Singh et al. ([iREPA, arXiv:2512.10794](https://arxiv.org/abs/2512.10794)) show
|
| 353 |
+
that **spatial structure** of pretrained encoder representations β not global
|
| 354 |
+
semantic accuracy β drives generation quality when using representation
|
| 355 |
+
alignment to guide diffusion training. Their method aligns internal diffusion
|
| 356 |
+
features with patch tokens from a frozen vision encoder (e.g. DINOv2) using
|
| 357 |
+
patch-wise cosine similarity, with a conv-based projection and spatial
|
| 358 |
+
normalization to preserve local structure.
|
| 359 |
+
|
| 360 |
+
iRDiffAE adopts iREPA but aligns only the **first half** of the bottleneck
|
| 361 |
+
channels (64 of 128) to a frozen DINOv3-S teacher. The rationale: models like
|
| 362 |
+
DINOv3-S are trained for semantic understanding and do not preserve
|
| 363 |
+
high-frequency detail. Aligning all channels biases the encoder toward dropping
|
| 364 |
+
fine detail in favour of semantic structure. By aligning only half, the
|
| 365 |
+
bottleneck decomposes into:
|
| 366 |
+
|
| 367 |
+
- **Channels 0β63 (aligned):** semantic and spatial structure, guided by the
|
| 368 |
+
teacher's patch tokens.
|
| 369 |
+
- **Channels 64β127 (free):** fine detail and high-frequency information,
|
| 370 |
+
driven purely by the reconstruction loss.
|
| 371 |
+
|
| 372 |
+
The alignment operates on the encoder output **after** the final RMSNorm
|
| 373 |
+
(no affine), so the teacher sees unit-RMS normalized features.
|
| 374 |
+
|
| 375 |
+
**Implementation details:**
|
| 376 |
+
|
| 377 |
+
```
|
| 378 |
+
Encoder latents z β β^{BΓ128ΓhΓw} (after RMSNorm)
|
| 379 |
+
β
|
| 380 |
+
z_aligned = z[:, :64, :, :]
|
| 381 |
+
β
|
| 382 |
+
Conv2d 3Γ3 (64 β 384, padding=1) β iREPA conv projection
|
| 383 |
+
β
|
| 384 |
+
student tokens β β^{BΓTΓ384}
|
| 385 |
+
β
|
| 386 |
+
patch-wise cosine similarity with DINOv3-S tokens
|
| 387 |
+
```
|
| 388 |
+
|
| 389 |
+
The teacher's patch tokens are spatially normalized before comparison
|
| 390 |
+
(\\(\gamma = 0.7\\), removing 70% of the global mean) following iREPA's
|
| 391 |
+
prescription. The alignment loss is weighted at 0.5 for most of training,
|
| 392 |
+
reduced to 0.25 toward the end to improve reconstruction fidelity.
|
| 393 |
+
|
| 394 |
+
**Tradeoff.** The alignment costs 2β3 dB of average reconstruction PSNR
|
| 395 |
+
compared to training without it. In exchange, downstream diffusion and flow
|
| 396 |
+
matching models trained on the aligned latent space converge significantly
|
| 397 |
+
faster β empirically validating the iREPA finding that spatial structure of
|
| 398 |
+
the latent representation matters more than raw reconstruction fidelity for
|
| 399 |
+
generation quality.
|
| 400 |
+
|
| 401 |
+
---
|
| 402 |
+
|
| 403 |
+
## 4. Model Configuration
|
| 404 |
+
|
| 405 |
+
| Parameter | Value |
|
| 406 |
+
|---|---|
|
| 407 |
+
| Patch size \\(p\\) | 16 |
|
| 408 |
+
| Bottleneck dim \\(C\\) | 128 |
|
| 409 |
+
| Compression ratio | 6Γ |
|
| 410 |
+
| Model dim \\(D\\) | 896 |
|
| 411 |
+
| Total parameters | 133.4M |
|
| 412 |
+
| Encoder depth | 4 |
|
| 413 |
+
| Decoder depth | 8 |
|
| 414 |
+
| Decoder layout | 2 start + 4 middle + 2 end |
|
| 415 |
+
| MLP ratio | 4.0 |
|
| 416 |
+
| Depthwise kernel | 7Γ7 |
|
| 417 |
+
| AdaLN rank \\(r\\) | 128 |
|
| 418 |
+
| \\(\lambda_\text{min}\\) | β10 |
|
| 419 |
+
| \\(\lambda_\text{max}\\) | +10 |
|
| 420 |
+
| Sigmoid bias \\(b\\) | β2.0 |
|
| 421 |
+
| Pixel noise std \\(s\\) | 0.558 |
|
| 422 |
+
|
| 423 |
+
**Compression ratio** = \\((3 \times p^2) / C\\): the factor by which the latent
|
| 424 |
+
representation is smaller than the raw pixel data. With patch size 16 and 128
|
| 425 |
+
bottleneck channels, the encoder produces a \\(16\times\\) spatial downsampling
|
| 426 |
+
(\\(256\times\\) area reduction) at 6Γ total compression.
|
| 427 |
+
|
| 428 |
+
---
|
| 429 |
+
|
| 430 |
+
## 5. Training
|
| 431 |
+
|
| 432 |
+
### 5.1 Data
|
| 433 |
+
|
| 434 |
+
Training uses ~5M images at various resolutions: mostly photographs, with
|
| 435 |
+
a significant proportion of illustrations and text-heavy images (documents,
|
| 436 |
+
screenshots, book covers, diagrams) to encourage crisp line and edge
|
| 437 |
+
reconstruction. Images are loaded via two strategies in a 50/50 mix:
|
| 438 |
+
|
| 439 |
+
- **Full-image downsampling:** images are bucketed by aspect ratio and
|
| 440 |
+
downsampled to ~256Β² resolution (preserving aspect ratio).
|
| 441 |
+
- **Random 256Γ256 crops:** deterministic patches extracted from images
|
| 442 |
+
stored at β₯512px resolution.
|
| 443 |
+
|
| 444 |
+
This mixed strategy exposes the model to both global scene composition (via
|
| 445 |
+
downsampled full images) and fine local detail (via crops from higher-resolution
|
| 446 |
+
sources).
|
| 447 |
+
|
| 448 |
+
### 5.2 Timestep Sampling
|
| 449 |
+
|
| 450 |
+
Timesteps are drawn via **stratified uniform sampling**, a variance reduction
|
| 451 |
+
technique from Monte Carlo integration. The base distribution is uniform over
|
| 452 |
+
the endpoint-trimmed domain \\([\varepsilon, 1 - \varepsilon]\\). Rather than
|
| 453 |
+
drawing \\(B\\) i.i.d. samples (which can cluster or leave gaps by chance),
|
| 454 |
+
stratified sampling divides the domain into \\(B\\) equal-mass buckets and draws
|
| 455 |
+
exactly one sample per bucket:
|
| 456 |
+
|
| 457 |
+
$$t_i = u_\text{lo} + (u_\text{hi} - u_\text{lo}) \cdot \frac{i + U_i}{B}, \qquad U_i \sim \mathcal{U}(0, 1), \quad i = 0, \ldots, B-1$$
|
| 458 |
+
|
| 459 |
+
where \\(u_\text{lo} = F(\varepsilon)\\), \\(u_\text{hi} = F(1 - \varepsilon)\\), and
|
| 460 |
+
\\(F\\) is the CDF of the base distribution (identity for uniform). This
|
| 461 |
+
guarantees that every batch covers the full timestep range evenly, reducing
|
| 462 |
+
the variance of the per-batch gradient estimate without introducing bias.
|
| 463 |
+
|
| 464 |
+
Endpoint trimming uses \\(\varepsilon = \sigma(-7.5) \approx 5.5 \times 10^{-4}\\),
|
| 465 |
+
keeping \\(|\lambda| \leq 15\\).
|
| 466 |
+
|
| 467 |
+
### 5.3 Latent Noise Synchronization (DiTo Regularization)
|
| 468 |
+
|
| 469 |
+
Following DiTo, encoder latents are regularized via noise synchronization
|
| 470 |
+
during training. With probability \\(p = 0.1\\), a subset of clean latents \\(z_0\\)
|
| 471 |
+
are replaced with noisy versions:
|
| 472 |
+
|
| 473 |
+
$$z_\tau = (1 - \tau_\text{fm}) \cdot z_0 + \tau_\text{fm} \cdot \varepsilon_z, \qquad \varepsilon_z \sim \mathcal{N}(0, I)$$
|
| 474 |
+
|
| 475 |
+
where \\(\tau\\) is sampled uniformly in \\([0, t]\\) (ensuring the latent is never
|
| 476 |
+
noisier than the pixel-space input) and converted to a flow-matching time
|
| 477 |
+
via the logSNR mapping, since downstream latent-space models are expected
|
| 478 |
+
to use flow matching:
|
| 479 |
+
|
| 480 |
+
$$\tau_\text{fm} = \sigma(-\tfrac{1}{2} \, \lambda(\tau))$$
|
| 481 |
+
|
| 482 |
+
This synchronizes the noising process in latent space with pixel space,
|
| 483 |
+
ensuring that the latent representation remains useful when a downstream
|
| 484 |
+
latent diffusion model adds noise during its own forward process.
|
| 485 |
+
|
| 486 |
+
### 5.4 Pixel vs. Latent Noise Standards
|
| 487 |
+
|
| 488 |
+
The model uses different noise standard deviations in pixel space and
|
| 489 |
+
latent space:
|
| 490 |
+
|
| 491 |
+
- **Pixel space:** \\(s = 0.558\\), matching an estimate of the per-channel standard
|
| 492 |
+
deviation of natural images over the training dataset. This ensures that at
|
| 493 |
+
\\(t = 1\\) the noise distribution roughly matches the data distribution scale.
|
| 494 |
+
- **Latent space:** \\(s = 1.0\\), because encoder latents are RMSNorm'd to unit
|
| 495 |
+
scale. Downstream latent diffusion models (which use flow matching)
|
| 496 |
+
operate with this unit-variance assumption.
|
| 497 |
+
|
| 498 |
+
The conversion between pixel-space VP logSNR and latent-space flow-matching
|
| 499 |
+
time uses the sigmoid mapping \\(t_\text{fm} = \sigma(-\frac{1}{2}\lambda)\\),
|
| 500 |
+
which naturally accounts for the different noise scales.
|
| 501 |
+
|
| 502 |
+
### 5.5 Optimizer and Hyperparameters
|
| 503 |
+
|
| 504 |
+
| Hyperparameter | Value |
|
| 505 |
+
|---|---|
|
| 506 |
+
| Optimizer | AdamW |
|
| 507 |
+
| Learning rate | \\(1 \times 10^{-4}\\) |
|
| 508 |
+
| Weight decay | 0 |
|
| 509 |
+
| Adam \\(\varepsilon\\) | \\(1 \times 10^{-8}\\) |
|
| 510 |
+
| LR schedule | Constant (after warmup), halved for last 20% of training |
|
| 511 |
+
| Warmup steps | 2,000 |
|
| 512 |
+
| Batch size | 128 |
|
| 513 |
+
| EMA decay | 0.9999 |
|
| 514 |
+
| Precision | AMP bfloat16 (FP32 master weights, TF32 matmul) |
|
| 515 |
+
| Compilation | `torch.compile` enabled |
|
| 516 |
+
| Training steps | 700k |
|
| 517 |
+
| Training images | ~5M |
|
| 518 |
+
| Hardware | Single GPU |
|
| 519 |
+
|
| 520 |
+
### 5.6 Loss
|
| 521 |
+
|
| 522 |
+
$$\mathcal{L} = \mathcal{L}_\text{recon} + w_\text{repa} \cdot \mathcal{L}_\text{repa}$$
|
| 523 |
+
|
| 524 |
+
\\(\mathcal{L}_\text{recon}\\) is the SiD2 sigmoid-weighted x-prediction MSE
|
| 525 |
+
(Section 1.4) with bias \\(b = -2.0\\), computed in float32 for numerical
|
| 526 |
+
stability.
|
| 527 |
+
|
| 528 |
+
\\(\mathcal{L}_\text{repa}\\) is the iREPA half-channel alignment loss
|
| 529 |
+
(Section 3.5): mean patch-wise negative cosine similarity between the first
|
| 530 |
+
64 encoder channels (projected via 3Γ3 conv) and spatially-normalized
|
| 531 |
+
DINOv3-S tokens. \\(w_\text{repa} = 0.5\\) for the majority of training,
|
| 532 |
+
lowered to 0.25 toward the end to recover reconstruction fidelity.
|
| 533 |
+
|
| 534 |
+
---
|
| 535 |
+
|
| 536 |
+
## 6. Inference
|
| 537 |
+
|
| 538 |
+
### 6.1 Sampling Pipeline
|
| 539 |
+
|
| 540 |
+
Decoding proceeds by iteratively denoising from Gaussian noise
|
| 541 |
+
(\\(\varepsilon \sim \mathcal{N}(0, s^2 I)\\) with \\(s = 0.558\\)). A descending
|
| 542 |
+
time schedule \\(t_0 > t_1 > \cdots > t_{N-1}\\) is generated (linearly spaced
|
| 543 |
+
by default), and at each step \\(t_i\\) is mapped to logSNR and then to diffusion
|
| 544 |
+
coefficients:
|
| 545 |
+
|
| 546 |
+
1. Compute \\(\lambda_i = \lambda(t_i)\\) via the cosine-interpolated schedule
|
| 547 |
+
2. Derive \\(\alpha_i = \sqrt{\sigma(\lambda_i)}\\), \\(\sigma_i = \sqrt{\sigma(-\lambda_i)}\\)
|
| 548 |
+
3. Run the DDIM or DPM++2M update step (Section 1.5)
|
| 549 |
+
|
| 550 |
+
The initial state is \\(x_{t_0} = \sigma_{t_0} \cdot \varepsilon\\) (pure noise
|
| 551 |
+
scaled by the first-step sigma).
|
| 552 |
+
|
| 553 |
+
### 6.2 Recommended Settings
|
| 554 |
+
|
| 555 |
+
**1 DDIM step** with **PDG disabled** is generally recommended β it achieves
|
| 556 |
+
the best PSNR and is extremely fast (a single forward pass through the
|
| 557 |
+
decoder). For images with sharp text or fine line art, 10β20 steps can
|
| 558 |
+
sometimes improve edge crispness.
|
| 559 |
+
|
| 560 |
+
| Setting | Recommended | Sharp text |
|
| 561 |
+
|---|---|---|
|
| 562 |
+
| Sampler | DDIM | DDIM or DPM++2M |
|
| 563 |
+
| Steps | 1 | 10β20 |
|
| 564 |
+
| Schedule | Linear | Linear |
|
| 565 |
+
| PDG | Disabled | Disabled or 2.0 |
|
| 566 |
+
|
| 567 |
+
**Reconstruction PSNR vs. decode steps** (N=2000 images, 2/3 photos + 1/3 book
|
| 568 |
+
covers, EMA weights):
|
| 569 |
+
|
| 570 |
+
| Decode steps | Avg PSNR (dB) |
|
| 571 |
+
|---|---|
|
| 572 |
+
| 1 | 33.71 |
|
| 573 |
+
| 10 | 32.69 |
|
| 574 |
+
| 20 | 32.30 |
|
| 575 |
+
|
| 576 |
+
PSNR decreases slightly with more steps because the model is trained for
|
| 577 |
+
single-step x-prediction; additional sampling steps introduce accumulated
|
| 578 |
+
discretization error. The 128-channel bottleneck preserves enough information
|
| 579 |
+
that a single decoder pass suffices for high-fidelity reconstruction.
|
| 580 |
+
|
| 581 |
+
Multi-step sampling can help recover sharper edges on text and line art.
|
| 582 |
+
PDG (strength 2β4) further increases perceptual sharpness but tends to
|
| 583 |
+
hallucinate high-frequency detail β a direct manifestation of the
|
| 584 |
+
**perception-distortion tradeoff**.
|
| 585 |
+
|
| 586 |
+
**Inference latency** (batch of 4 Γ 256Γ256, bf16, NVIDIA RTX PRO 6000
|
| 587 |
+
Blackwell, 100 iterations after warmup):
|
| 588 |
+
|
| 589 |
+
| Operation | iRDiffAE | Flux.1 VAE | Flux.2 VAE |
|
| 590 |
+
|---|---|---|---|
|
| 591 |
+
| Encode | 2.1 ms | 11.6 ms | 9.1 ms |
|
| 592 |
+
| Decode (1 step) | 8.3 ms | 24.9 ms | 20.0 ms |
|
| 593 |
+
| Decode (10 steps) | 52.7 ms | β | β |
|
| 594 |
+
| Decode (20 steps) | 100.6 ms | β | β |
|
| 595 |
+
| Roundtrip (enc + 1-step dec) | 11.1 ms | 36.4 ms | 29.0 ms |
|
| 596 |
+
|
| 597 |
+
Encoding is ~5Γ faster than Flux.1 and ~4Γ faster than Flux.2. Single-step
|
| 598 |
+
decoding is ~3Γ faster than both Flux VAEs; multi-step decoding trades speed
|
| 599 |
+
for perceptual sharpness.
|
| 600 |
+
|
| 601 |
+
### 6.3 Usage
|
| 602 |
+
|
| 603 |
+
```python
|
| 604 |
+
from ir_diffae import IRDiffAE, IRDiffAEInferenceConfig
|
| 605 |
+
|
| 606 |
+
model = IRDiffAE.from_pretrained("data-archetype/irdiffae-v1", device="cuda") # bfloat16 by default
|
| 607 |
+
|
| 608 |
+
# Encode
|
| 609 |
+
latents = model.encode(images) # [B, 3, H, W] β [B, 128, H/16, W/16]
|
| 610 |
+
|
| 611 |
+
# Decode β PSNR-optimal (1 step, single forward pass)
|
| 612 |
+
cfg = IRDiffAEInferenceConfig(num_steps=1, sampler="ddim")
|
| 613 |
+
recon = model.decode(latents, height=H, width=W, inference_config=cfg)
|
| 614 |
+
|
| 615 |
+
# Decode β perceptual sharpness (10 steps + PDG)
|
| 616 |
+
cfg_sharp = IRDiffAEInferenceConfig(
|
| 617 |
+
num_steps=10, sampler="ddim", pdg_enabled=True, pdg_strength=2.0
|
| 618 |
+
)
|
| 619 |
+
recon_sharp = model.decode(latents, height=H, width=W, inference_config=cfg_sharp)
|
| 620 |
+
```
|
| 621 |
+
|
| 622 |
+
---
|
| 623 |
+
|
| 624 |
+
## Citation
|
| 625 |
+
|
| 626 |
+
```bibtex
|
| 627 |
+
@misc{ir_diffae,
|
| 628 |
+
title = {iRDiffAE: A Fast, Representation Aligned Diffusion Autoencoder with DiCo Blocks},
|
| 629 |
+
author = {data-archetype},
|
| 630 |
+
year = {2026},
|
| 631 |
+
month = feb,
|
| 632 |
+
url = {https://github.com/data-archetype/irdiffae},
|
| 633 |
+
}
|
| 634 |
+
```
|
| 635 |
+
|
| 636 |
+
---
|
| 637 |
+
|
| 638 |
+
## 7. Results
|
| 639 |
+
|
| 640 |
+
Reconstruction quality evaluated on a curated set of test images covering photographs, book covers, and documents. Flux.1 VAE (patch 8, 16 channels) is included as a reference at the same 12x compression ratio as the c64 variant.
|
| 641 |
+
|
| 642 |
+
### 7.1 Interactive Viewer
|
| 643 |
+
|
| 644 |
+
**[Open full-resolution comparison viewer](https://huggingface.co/spaces/data-archetype/disco-diffae-results)** β side-by-side reconstructions, RGB deltas, and latent PCA with adjustable image size.
|
| 645 |
+
|
| 646 |
+
### 7.2 Inference Settings
|
| 647 |
+
|
| 648 |
+
| Setting | Value |
|
| 649 |
+
|---------|-------|
|
| 650 |
+
| Sampler | ddim |
|
| 651 |
+
| Steps | 1 |
|
| 652 |
+
| Schedule | linear |
|
| 653 |
+
| Seed | 42 |
|
| 654 |
+
| PDG | no_path_dropg |
|
| 655 |
+
| Batch size (timing) | 8 |
|
| 656 |
+
|
| 657 |
+
> All models run in bfloat16. Timings measured on an NVIDIA RTX Pro 6000 (Blackwell).
|
| 658 |
+
|
| 659 |
+
### 7.3 Global Metrics
|
| 660 |
+
|
| 661 |
+
| Metric | p16_c128 | Flux.1 VAE | Flux.2 VAE |
|
| 662 |
+
|--------|--------|--------|--------|
|
| 663 |
+
| Avg PSNR (dB) | 31.75 | 32.66 | 34.13 |
|
| 664 |
+
| Avg encode (ms/image) | 2.4 | 63.3 | 45.0 |
|
| 665 |
+
| Avg decode (ms/image) | 5.4 | 135.4 | 90.5 |
|
| 666 |
+
|
| 667 |
+
### 7.4 Per-Image PSNR (dB)
|
| 668 |
+
|
| 669 |
+
| Image | p16_c128 | Flux.1 VAE | Flux.2 VAE |
|
| 670 |
+
|-------|--------|--------|--------|
|
| 671 |
+
| p640x1536:94623 | 30.99 | 31.28 | 33.50 |
|
| 672 |
+
| p640x1536:94624 | 27.21 | 27.62 | 30.03 |
|
| 673 |
+
| p640x1536:94625 | 30.48 | 31.65 | 33.98 |
|
| 674 |
+
| p640x1536:94626 | 28.97 | 29.44 | 31.53 |
|
| 675 |
+
| p640x1536:94627 | 29.17 | 28.70 | 30.53 |
|
| 676 |
+
| p640x1536:94628 | 25.55 | 26.38 | 28.88 |
|
| 677 |
+
| p960x1024:216264 | 40.92 | 40.87 | 45.39 |
|
| 678 |
+
| p960x1024:216265 | 26.18 | 25.82 | 27.80 |
|
| 679 |
+
| p960x1024:216266 | 43.61 | 47.77 | 46.20 |
|
| 680 |
+
| p960x1024:216267 | 37.12 | 37.65 | 39.23 |
|
| 681 |
+
| p960x1024:216268 | 35.75 | 35.27 | 36.13 |
|
| 682 |
+
| p960x1024:216269 | 29.14 | 28.45 | 30.24 |
|
| 683 |
+
| p960x1024:216270 | 32.06 | 31.92 | 34.18 |
|
| 684 |
+
| p960x1024:216271 | 38.73 | 38.92 | 42.18 |
|
| 685 |
+
| p704x1472:94699 | 40.81 | 40.43 | 41.79 |
|
| 686 |
+
| p704x1472:94700 | 29.52 | 29.52 | 32.08 |
|
| 687 |
+
| p704x1472:94701 | 35.01 | 35.43 | 37.90 |
|
| 688 |
+
| p704x1472:94702 | 30.76 | 30.73 | 32.50 |
|
| 689 |
+
| p704x1472:94703 | 28.49 | 29.08 | 31.35 |
|
| 690 |
+
| p704x1472:94704 | 28.68 | 29.22 | 31.84 |
|
| 691 |
+
| p704x1472:94705 | 35.91 | 36.38 | 37.44 |
|
| 692 |
+
| p704x1472:94706 | 31.12 | 31.50 | 33.66 |
|
| 693 |
+
| r256_p1344x704:15577 | 28.10 | 28.32 | 29.98 |
|
| 694 |
+
| r256_p1344x704:15578 | 28.29 | 29.35 | 30.79 |
|
| 695 |
+
| r256_p1344x704:15579 | 29.86 | 30.44 | 31.83 |
|
| 696 |
+
| r256_p1344x704:15580 | 34.01 | 36.12 | 36.03 |
|
| 697 |
+
| r256_p1344x704:15581 | 33.41 | 37.42 | 36.94 |
|
| 698 |
+
| r256_p1344x704:15582 | 29.12 | 30.64 | 32.10 |
|
| 699 |
+
| r256_p1344x704:15583 | 32.61 | 34.67 | 34.54 |
|
| 700 |
+
| r256_p1344x704:15584 | 28.72 | 30.34 | 31.76 |
|
| 701 |
+
| r256_p896x1152:144131 | 30.73 | 33.10 | 33.60 |
|
| 702 |
+
| r256_p896x1152:144132 | 33.13 | 34.23 | 35.32 |
|
| 703 |
+
| r256_p896x1152:144133 | 35.70 | 37.85 | 37.33 |
|
| 704 |
+
| r256_p896x1152:144134 | 31.72 | 34.25 | 34.47 |
|
| 705 |
+
| r256_p896x1152:144135 | 27.34 | 28.17 | 29.87 |
|
| 706 |
+
| r256_p896x1152:144136 | 32.89 | 35.24 | 35.68 |
|
| 707 |
+
| r256_p896x1152:144137 | 29.78 | 32.70 | 32.86 |
|
| 708 |
+
| r256_p896x1152:144138 | 24.86 | 24.15 | 25.63 |
|
| 709 |
+
|