Skip to content

Commit fc71c8a

Browse files
committed
added readme
1 parent 03af565 commit fc71c8a

File tree

4 files changed

+413
-168
lines changed

4 files changed

+413
-168
lines changed
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
# Latent Perceptual Loss (LPL) for Stable Diffusion XL
2+
3+
This directory contains an implementation of Latent Perceptual Loss (LPL) for training Stable Diffusion XL models, based on the paper "Boosting Latent Diffusion with Perceptual Objectives" (Berrada et al., 2025). LPL is a perceptual loss that operates in the latent space of a VAE, helping to improve the quality and consistency of generated images by bridging the disconnect between the diffusion model and the autoencoder decoder.
4+
5+
## Overview
6+
7+
LPL addresses a key limitation in latent diffusion models (LDMs): the disconnect between the diffusion model training and the autoencoder decoder. While LDMs train in the latent space, they don't receive direct feedback about how well their outputs decode into high-quality images. This can lead to:
8+
9+
- Loss of fine details in generated images
10+
- Inconsistent image quality
11+
- Structural artifacts
12+
- Reduced sharpness and realism
13+
14+
LPL works by comparing intermediate features from the VAE decoder between the predicted and target latents. This helps the model learn better perceptual features and can lead to:
15+
16+
- Improved image quality and consistency (6-20% FID improvement)
17+
- Better preservation of fine details
18+
- More stable training, especially at high noise levels
19+
- Better handling of structural information
20+
- Sharper and more realistic textures
21+
22+
## Implementation Details
23+
24+
The LPL implementation follows the paper's methodology and includes several key features:
25+
26+
1. **Feature Extraction**: Extracts intermediate features from the VAE decoder, including:
27+
- Middle block features
28+
- Up block features (configurable number of blocks)
29+
- Proper gradient checkpointing for memory efficiency
30+
- Features are extracted only for timesteps below the threshold (high SNR)
31+
32+
2. **Feature Normalization**: Multiple normalization options as validated in the paper:
33+
- `default`: Normalize each feature map independently
34+
- `shared`: Cross-normalize features using target statistics (recommended)
35+
- `batch`: Batch-wise normalization
36+
37+
3. **Outlier Handling**: Optional removal of outliers in feature maps using:
38+
- Quantile-based filtering (2% quantiles)
39+
- Morphological operations (opening/closing)
40+
- Adaptive thresholding based on standard deviation
41+
42+
4. **Loss Types**:
43+
- MSE loss (default)
44+
- L1 loss
45+
- Optional power law weighting (2^(-i) for layer i)
46+
47+
## Usage
48+
49+
To use LPL in your training, add the following arguments to your training command:
50+
51+
```bash
52+
python examples/research_projects/lpl/lpl_sdxl.py \
53+
--use_lpl \
54+
--lpl_weight 1.0 \ # Weight for LPL loss (1.0-2.0 recommended)
55+
--lpl_t_threshold 200 \ # Apply LPL only for timesteps < threshold (high SNR)
56+
--lpl_loss_type mse \ # Loss type: "mse" or "l1"
57+
--lpl_norm_type shared \ # Normalization type: "default", "shared" (recommended), or "batch"
58+
--lpl_pow_law \ # Use power law weighting for layers
59+
--lpl_num_blocks 4 \ # Number of up blocks to use (1-4)
60+
--lpl_remove_outliers \ # Remove outliers in feature maps
61+
--lpl_scale \ # Scale LPL loss by noise level weights
62+
--lpl_start 0 \ # Step to start applying LPL
63+
# ... other training arguments ...
64+
```
65+
66+
### Key Parameters
67+
68+
- `lpl_weight`: Controls the strength of the LPL loss relative to the main diffusion loss. Higher values (1.0-2.0) improve quality but may slow training.
69+
- `lpl_t_threshold`: LPL is only applied for timesteps below this threshold (high SNR). Lower values (100-200) focus on more important timesteps.
70+
- `lpl_loss_type`: Choose between MSE (default) and L1 loss. MSE is recommended for most cases.
71+
- `lpl_norm_type`: Feature normalization strategy. "shared" is recommended as it showed best results in the paper.
72+
- `lpl_pow_law`: Whether to use power law weighting (2^(-i) for layer i). Recommended for better feature balance.
73+
- `lpl_num_blocks`: Number of up blocks to use for feature extraction (1-4). More blocks capture more features but use more memory.
74+
- `lpl_remove_outliers`: Whether to remove outliers in feature maps. Recommended for stable training.
75+
- `lpl_scale`: Whether to scale LPL loss by noise level weights. Helps focus on more important timesteps.
76+
- `lpl_start`: Training step to start applying LPL. Can be used to warm up training.
77+
78+
## Recommendations
79+
80+
1. **Starting Point** (based on paper results):
81+
```bash
82+
--use_lpl \
83+
--lpl_weight 1.0 \
84+
--lpl_t_threshold 200 \
85+
--lpl_loss_type mse \
86+
--lpl_norm_type shared \
87+
--lpl_pow_law \
88+
--lpl_num_blocks 4 \
89+
--lpl_remove_outliers \
90+
--lpl_scale
91+
```
92+
93+
2. **Memory Efficiency**:
94+
- Use `--gradient_checkpointing` for memory efficiency (enabled by default)
95+
- Reduce `lpl_num_blocks` if memory is constrained (2-3 blocks still give good results)
96+
- Consider using `--lpl_scale` to focus on more important timesteps
97+
- Features are extracted only for timesteps below threshold to save memory
98+
99+
3. **Quality vs Speed**:
100+
- Higher `lpl_weight` (1.0-2.0) for better quality
101+
- Lower `lpl_t_threshold` (100-200) for faster training
102+
- Use `lpl_remove_outliers` for more stable training
103+
- `lpl_norm_type shared` provides best quality/speed trade-off
104+
105+
## Technical Details
106+
107+
### Feature Extraction
108+
109+
The LPL implementation extracts features from the VAE decoder in the following order:
110+
1. Middle block output
111+
2. Up block outputs (configurable number of blocks)
112+
113+
Each feature map is processed with:
114+
1. Optional outlier removal (2% quantiles, morphological operations)
115+
2. Feature normalization (shared statistics recommended)
116+
3. Loss calculation (MSE or L1)
117+
4. Optional power law weighting (2^(-i) for layer i)
118+
119+
### Loss Calculation
120+
121+
For each feature map:
122+
1. Features are normalized according to the chosen strategy
123+
2. Loss is calculated between normalized features
124+
3. Outliers are masked out (if enabled)
125+
4. Loss is weighted by layer depth (if power law enabled)
126+
5. Final loss is averaged across all layers
127+
128+
### Memory Considerations
129+
130+
- Gradient checkpointing is used by default
131+
- Features are extracted only for timesteps below the threshold
132+
- Outlier removal is done in-place to save memory
133+
- Feature normalization is done efficiently using vectorized operations
134+
- Memory usage scales linearly with number of blocks used
135+
136+
## Results
137+
138+
Based on the paper's findings, LPL provides:
139+
- 6-20% improvement in FID scores
140+
- Better preservation of fine details
141+
- More realistic textures and structures
142+
- Improved consistency across different resolutions
143+
- Better performance on both small and large datasets
144+
145+
## Citation
146+
147+
If you use this implementation in your research, please cite:
148+
149+
```bibtex
150+
@inproceedings{berrada2025boosting,
151+
title={Boosting Latent Diffusion with Perceptual Objectives},
152+
author={Tariq Berrada and Pietro Astolfi and Melissa Hall and Marton Havasi and Yohann Benchetrit and Adriana Romero-Soriano and Karteek Alahari and Michal Drozdzal and Jakob Verbeek},
153+
booktitle={The Thirteenth International Conference on Learning Representations},
154+
year={2025},
155+
url={https://openreview.net/forum?id=y4DtzADzd1}
156+
}
157+
```

examples/research_projects/lpl/__init__.py

Whitespace-only changes.
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
import numpy as np
2+
import torch
3+
import torch.nn as nn
4+
import torch.nn.functional as F
5+
6+
7+
def normalize_tensor(in_feat, eps=1e-10):
8+
norm_factor = torch.sqrt(torch.sum(in_feat**2, dim=1, keepdim=True))
9+
return in_feat / (norm_factor + eps)
10+
11+
12+
def cross_normalize(input, target, eps=1e-10):
13+
norm_factor = torch.sqrt(torch.sum(target**2, dim=1, keepdim=True))
14+
return input / (norm_factor + eps), target / (norm_factor + eps)
15+
16+
17+
def remove_outliers(feat, down_f=1, opening=5, closing=3, m=100, quant=0.02):
18+
opening = int(np.ceil(opening / down_f))
19+
closing = int(np.ceil(closing / down_f))
20+
if opening == 2:
21+
opening = 3
22+
if closing == 2:
23+
closing = 1
24+
25+
# replace quantile with kth value here.
26+
feat_flat = feat.flatten(-2, -1)
27+
k1, k2 = int(feat_flat.shape[-1] * quant), int(feat_flat.shape[-1] * (1 - quant))
28+
q1 = feat_flat.kthvalue(k1, dim=-1).values[..., None, None]
29+
q2 = feat_flat.kthvalue(k2, dim=-1).values[..., None, None]
30+
31+
m = 2 * feat_flat.std(-1)[..., None, None].detach()
32+
mask = (q1 - m < feat) * (feat < q2 + m)
33+
34+
# dilate the mask.
35+
mask = nn.MaxPool2d(kernel_size=closing, stride=1, padding=(closing - 1) // 2)(mask.float()) # closing
36+
mask = (-nn.MaxPool2d(kernel_size=opening, stride=1, padding=(opening - 1) // 2)(-mask)).bool() # opening
37+
feat = feat * mask
38+
return mask, feat
39+
40+
41+
class LatentPerceptualLoss(nn.Module):
42+
def __init__(
43+
self,
44+
vae,
45+
loss_type="mse",
46+
grad_ckpt=True,
47+
pow_law=False,
48+
norm_type="default",
49+
num_mid_blocks=4,
50+
feature_type="feature",
51+
remove_outliers=True,
52+
):
53+
super().__init__()
54+
self.vae = vae
55+
self.decoder = self.vae.decoder
56+
self.scale = self.vae._internal_dict.scaling_factor
57+
self.shift = self.vae._internal_dict.shift_factor
58+
self.gradient_checkpointing = grad_ckpt
59+
self.pow_law = pow_law
60+
self.norm_type = norm_type.lower()
61+
self.outlier_mask = remove_outliers
62+
63+
assert feature_type in ["feature", "image"]
64+
self.feature_type = feature_type
65+
66+
assert self.norm_type in ["default", "shared", "batch"]
67+
assert num_mid_blocks >= 0 and num_mid_blocks <= 4
68+
self.n_blocks = num_mid_blocks
69+
70+
assert loss_type in ["mse", "l1"]
71+
if loss_type == "mse":
72+
self.loss_fn = nn.MSELoss(reduction="none")
73+
elif loss_type == "l1":
74+
self.loss_fn = nn.L1Loss(reduction="none")
75+
76+
def get_features(self, z, latent_embeds=None, disable_grads=False):
77+
with torch.set_grad_enabled(not disable_grads):
78+
if self.gradient_checkpointing and not disable_grads:
79+
80+
def create_custom_forward(module):
81+
def custom_forward(*inputs):
82+
return module(*inputs)
83+
84+
return custom_forward
85+
86+
features = []
87+
upscale_dtype = next(iter(self.decoder.up_blocks.parameters())).dtype
88+
sample = z
89+
sample = self.decoder.conv_in(sample)
90+
91+
# middle
92+
sample = torch.utils.checkpoint.checkpoint(
93+
create_custom_forward(self.decoder.mid_block),
94+
sample,
95+
latent_embeds,
96+
use_reentrant=False,
97+
)
98+
sample = sample.to(upscale_dtype)
99+
features.append(sample)
100+
101+
# up
102+
for up_block in self.decoder.up_blocks[: self.n_blocks]:
103+
sample = torch.utils.checkpoint.checkpoint(
104+
create_custom_forward(up_block),
105+
sample,
106+
latent_embeds,
107+
use_reentrant=False,
108+
)
109+
features.append(sample)
110+
return features
111+
else:
112+
features = []
113+
upscale_dtype = next(iter(self.decoder.up_blocks.parameters())).dtype
114+
sample = z
115+
sample = self.decoder.conv_in(sample)
116+
117+
# middle
118+
sample = self.decoder.mid_block(sample, latent_embeds)
119+
sample = sample.to(upscale_dtype)
120+
features.append(sample)
121+
122+
# up
123+
for up_block in self.decoder.up_blocks[: self.n_blocks]:
124+
sample = up_block(sample, latent_embeds)
125+
features.append(sample)
126+
return features
127+
128+
def get_loss(self, input, target, get_hist=False):
129+
if self.feature_type == "feature":
130+
inp_f = self.get_features(self.shift + input / self.scale)
131+
tar_f = self.get_features(self.shift + target / self.scale, disable_grads=True)
132+
losses = []
133+
134+
for i, (x, y) in enumerate(zip(inp_f, tar_f, strict=False)):
135+
my = torch.ones_like(y).bool()
136+
if self.outlier_mask:
137+
with torch.no_grad():
138+
if i == 2:
139+
my, y = remove_outliers(y, down_f=2)
140+
elif i in [3, 4, 5]:
141+
my, y = remove_outliers(y, down_f=1)
142+
143+
# normalize feature tensors
144+
if self.norm_type == "default":
145+
x = normalize_tensor(x)
146+
y = normalize_tensor(y)
147+
elif self.norm_type == "shared":
148+
x, y = cross_normalize(x, y, eps=1e-6)
149+
150+
term_loss = self.loss_fn(x, y) * my
151+
# reduce loss term
152+
loss_f = 2 ** (-min(i, 3)) if self.pow_law else 1.0
153+
term_loss = term_loss.sum((2, 3)) * loss_f / my.sum((2, 3))
154+
losses.append(term_loss.mean((1,)))
155+
156+
if get_hist:
157+
return losses
158+
else:
159+
loss = sum(losses)
160+
return loss / len(inp_f)
161+
elif self.feature_type == "image":
162+
inp_f = self.vae.decode(input / self.scale).sample
163+
tar_f = self.vae.decode(target / self.scale).sample
164+
return F.mse_loss(inp_f, tar_f)
165+
166+
def get_first_conv(self, z):
167+
sample = self.decoder.conv_in(z)
168+
return sample
169+
170+
def get_first_block(self, z):
171+
sample = self.decoder.conv_in(z)
172+
sample = self.decoder.mid_block(sample)
173+
for resnet in self.decoder.up_blocks[0].resnets:
174+
sample = resnet(sample, None)
175+
return sample
176+
177+
def get_first_layer(self, input, target, target_layer="conv"):
178+
if target_layer == "conv":
179+
feat_in = self.get_first_conv(input)
180+
with torch.no_grad():
181+
feat_tar = self.get_first_conv(target)
182+
else:
183+
feat_in = self.get_first_block(input)
184+
with torch.no_grad():
185+
feat_tar = self.get_first_block(target)
186+
187+
feat_in, feat_tar = cross_normalize(feat_in, feat_tar)
188+
189+
return F.mse_loss(feat_in, feat_tar, reduction="mean")

0 commit comments

Comments
 (0)