Skip to content

Fix KL reduction for video VAE posteriors - #15471

Open
taking-lying-flat wants to merge 1 commit into
huggingface:mainfrom
taking-lying-flat:fix-video-vae-kl-event-dimensions
Open

taking-lying-flat wants to merge 1 commit into
huggingface:mainfrom
taking-lying-flat:fix-video-vae-kl-event-dimensions

Conversation

@taking-lying-flat

@taking-lying-flat taking-lying-flat commented Dec 3, 2026 •

Copy link
Copy Markdown

What does this PR do?

Fix DiagonalGaussianDistribution.kl() to sum every non-batch dimension in both the standard-prior and kl(other) branches. The fixed axes [1, 2, 3] leave the width axis unreduced for video posteriors [B,C,T,H,W], returning [B,W] instead of [B]. If training uses posterior.kl().mean() for total KL per video averaged over the batch, its loss and encoder gradients are consequently scaled by 1/W.

Reproduced through AutoencoderKLWan.encode() with the official Wan-AI/Wan2.1-T2V-1.3B-Diffusers VAE at revision 0fad780a534b6463e45facd96134c9f345acfa5b, CPU FP32, PyTorch 2.11.0+cu128, and Diffusers main 12d5c7a53a7c. Input [2,3,5,32,48] yields posterior [2,16,2,4,6]:

Implementation KL shape Batch mean KL encoder.conv_out.weight gradient norm
Before [2,6] 1160.8806 2492.0862
PyTorch Independent(Normal, 4) reference [2] 6965.2832 14952.5049
After [2] 6965.2832 14952.5049

Multiplying the original gradient by 6 matches the reference with relative L2 error 1.38e-7; after the fix, the error is 4.23e-8. The kl(other) branch has the same width-dependent scaling bug. Callers already using .kl().sum()/batch_size obtain the correct scalar loss; image posteriors retain the same reduction.

Reproduce

import torch
from torch.distributions import Independent, Normal, kl_divergence
from diffusers import AutoencoderKLWan

torch.set_num_threads(2)
vae = AutoencoderKLWan.from_pretrained(
    "Wan-AI/Wan2.1-T2V-1.3B-Diffusers", subfolder="vae",
    revision="0fad780a534b6463e45facd96134c9f345acfa5b", torch_dtype=torch.float32,
).eval()
video = torch.rand(2, 3, 5, 32, 48, generator=torch.Generator().manual_seed(0)) * 2 - 1
q = vae.encode(video).latent_dist
actual = q.kl()
reference = kl_divergence(
    Independent(Normal(q.mean, q.std), 4),
    Independent(Normal(torch.zeros_like(q.mean), torch.ones_like(q.std)), 4),
)
weight = vae.encoder.conv_out.weight
g_actual = torch.autograd.grad(actual.mean(), weight, retain_graph=True)[0]
g_reference = torch.autograd.grad(reference.mean(), weight)[0]
print(actual.shape, reference.shape)
print(actual.mean().item(), reference.mean().item())
print(g_actual.norm().item(), g_reference.norm().item())

Self-review

Used Codex and the repository's self-review skill. READY: no blocking or non-blocking findings, no added dead code or dependencies. The change is limited to KL event-dimension reduction.

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Hi @taking-lying-flat, thanks for the PR! It does not appear to link an issue it fixes.

  • If this PR addresses an existing issue, please add a closing keyword (e.g. Fixes #1234) to the PR description so the issue is linked.
  • If you are the author of the model/pipeline this PR relates to, or part of the team we work with on it, tick the Are you the author (or part of the team we work with) of the model/pipeline this PR relates to? box in the PR description (if you removed the template, paste that line back, checked). This reminder then no longer applies.
  • Otherwise there is nothing you need to do: a maintainer will look at the PR and add the no-issue-needed label to silence this reminder if it should stay open without an issue.

See the contribution guide for more details.

Please note that PRs without a linked issue are likely to be automatically closed 10 days after this notice.

Once the PR links an existing issue, the author box is ticked, or the no-issue-needed label is added, you can ignore this message — it stays here as a comment, but it no longer applies.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant