Skip to content

Studio video: tiny Wan decoder for live previews and an opt-in draft decode - #18780

Merged
danielhanchen merged 6 commits into
mainfrom
nov21-distill-taehv
Nov 21, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
nov21-distill-taehv

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Live previews for every Wan video family now come from a tiny Wan decoder (TAEHV layout, about 11M parameters), and an opt-in draft_decode flag decodes the finished clip with the same decoder instead of the full Wan VAE.

  • Wan2.1 1.3B / 14B and Wan2.2 A14B had no live preview at all (no fitted linear map); they now get one. Wan2.2 TI2V-5B swaps its linear map for a real decode of the first frame.
  • taew2_1 (z=16, Wan2.1 VAE) and taew2_2 (z=48, Wan2.2 VAE) from lightx2v/Autoencoders (Apache-2.0, 23 MB each), fetched once in a background thread. Until the file is cached, or on any load error, previews keep the linear map (or none), so the first render on a fresh machine is never delayed.
  • The final clip is unchanged by default. draft_decode=true on POST /video/generate (or UNSLOTH_VIDEO_DRAFT_DECODE=1) swaps vae.decode for the tiny decoder for that one render and restores it afterwards; the gallery recipe records draft_decode: true. A family without a cached tiny decoder silently keeps the full decode.
  • The decoder runs two latent frames at a time and carries each memory block's last input across chunks, so it matches one pass exactly while the 832x480x49 Wan2.1 decode peak drops from 17.4 to 4.2 GiB on CPU.
  • Kill switch for both: UNSLOTH_VIDEO_TINY_VAE=0.

The decoder module follows the MIT-licensed TAEHV layout (notice kept in the file header); no new dependency.

Numbers

832x480x49, one real clip encoded with each Wan VAE, tiny decode compared with the full VAE decode of the same latent.

decoder PSNR vs full VAE LPIPS vs full VAE first frame LPIPS
taew2_1 (Wan2.1 VAE) 33.8 dB 0.031 0.034
taew2_2 (Wan2.2 VAE) 28.5 dB 0.124 0.090

For scale, the full VAE round trip itself is LPIPS 0.017 to 0.018 against the source frames.

Decode time and memory, 832x480x49:

where decoder full Wan VAE tiny speedup
CPU, 16 threads Wan2.1 VAE 441 s, 9.6 GiB RSS 13.5 s, 4.2 GiB 33x
CPU, 16 threads Wan2.2 VAE 356 s, 11.9 GiB RSS 3.0 s, 2.2 GiB 119x
T4 Wan2.1 VAE 55.8 s fp32 (20.9 s fp16), 7.5 GiB 0.77 s 72x
T4 Wan2.2 VAE 98.1 s fp32 (24.7 s fp16), 8.2 GiB 0.19 s, 2.6 GiB 500x

Tiny CPU times are medians of 3 runs (spread under 1.5 s); the full CPU decodes ran once each, far outside any noise. Live preview cost on a T4 is 55 ms (Wan2.1 latents) and 16 ms (Wan2.2 latents) per snapshot, at most 24 snapshots per render. On the T4 the preview path ran with torch.cuda.set_sync_debug_mode("error"): no host sync, 3 snapshots decoded and published, the latent left bit-identical.

Tests

  • tests/test_video_tiny_vae.py: checkpoint routing by family and latent width, the released key layout, decode shapes and range, causality, chunked decode matches one pass, draft decode off by default, swaps and restores vae.decode, declines a mismatched VAE, background fetch runs once, a bad file falls back, and a CUDA no-sync preview test.
  • tests/test_video_tiny_vae_wiring.py: every Wan family offers live previews on CUDA (fails on main for the three z=16 families), and the request / generate path carries draft_decode defaulting to off.

Screenshots

BEFORE is the merge base (8b7cde7), AFTER is this branch (694a87e). Each side is a separate Studio install on the same Colab T4. Both render Wan-AI/Wan2.1-T2V-1.3B-Diffusers with the same prompt, seed 1234, 8 steps, 832x480 and 33 frames.

Video page live preview at step 6 of 8
Video page at step 6 of 8: before, Wan2.1 has no live preview while denoising. After, the tiny Wan decoder streams a preview of the first frame (7 previews, steps 2 to 8). With UNSLOTH_VIDEO_TINY_VAE=0 the preview goes away again.

Every Wan family now streams live previews through a TAEHV-layout decoder
(taew2_1 for the z=16 Wan2.1 VAE, taew2_2 for the z=48 Wan2.2 VAE; 23 MB,
fetched once in the background from lightx2v/Autoencoders). Until the
weights are cached, and on any failure, previews keep the linear map (or
none). The final clip is unchanged unless draft_decode is requested, which
decodes the finished latent with the same tiny decoder. Kill switch
UNSLOTH_VIDEO_TINY_VAE=0.
Causal MemBlocks carry their last input across chunks, so the frames match
one pass while the 832x480x49 Wan2.1 decode peak drops from 17.4 to 4.1 GiB
on CPU.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T18:44:00.697031Z faf6351 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 694a87e65e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/core/inference/video.py Outdated

try:
with grad_ctx, protect_ctx, progress_ctx(), sigma_ctx:
with grad_ctx, protect_ctx, progress_ctx(), sigma_ctx, draft_ctx:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Install the draft decoder before entering the progress wrappers

When draft_decode engages, entering draft_ctx after progress_ctx() replaces vae.decode outright, bypassing the decode wrappers that progress_ctx() just installed. In particular, media_decode_phase.decode_phase no longer invokes _on_decode(), so the render never reports its decode phase and video_stream_residency.prepare_decode() never returns GPU-resident denoiser groups lent to the denoise. On memory-constrained GPUs using that residency optimization, this unnecessarily retains denoiser weights during the tiny decode and can cause an otherwise avoidable OOM. Enter the draft context before the progress context so the existing boundary and validation wrappers wrap the selected decoder.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in the latest commit. The draft decoder is now entered before progress_ctx(), so the decode-phase hook (and prepare_decode), the finite check and the uint8 conversion wrap whichever decoder runs. The new test checks that the decode-phase hook fires around the tiny decoder and pins the order in the render's with statement.

draft_decode replaced vae.decode after progress_ctx() had wrapped it, so
the decode-phase hook never fired (no decode phase reported, and
video_stream_residency.prepare_decode never returned lent denoiser
groups before the decode), and the finite / uint8 checks were skipped.
The draft context is now entered first, so those wrappers wrap whichever
decoder runs.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e4e9d30b20

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

def _fetch(filename: str) -> None:
try:
from huggingface_hub import hf_hub_download
hf_hub_download(TINY_VAE_REPO, filename)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Route tiny-decoder downloads through the active Studio cache

When a user changes the Hugging Face cache location in Studio Settings, both this download and _cached_path() still use Hugging Face's import-time default because neither passes cache_dir. Studio deliberately keeps its live setting separate from those constants (utils/hf_cache_settings.py), and other video loaders use hub_cache_dir() to honor it. Consequently, cached tiny-decoder weights in the selected location are ignored and downloaded again into the old location; if that location is full or unwritable, previews and draft decoding remain unavailable despite usable cached weights. Pass the active cache root to both the lookup and download.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in the latest commit. The tiny-decoder cache lookup and the background download now both pass Studio's active Hugging Face cache root as cache_dir (from utils.hf_cache_settings.active_hf_hub_cache()), falling back to the hub default outside Studio. A new test points the active cache at a temporary directory and checks that both calls receive it.

The tiny-decoder cache lookup and its background download used
huggingface_hub's import-time default cache, not Studio's active cache
root (utils.hf_cache_settings), so a moved cache downloaded the file
where no other loader looks and never found it again. Both now pass the
active hub cache, as the other video loaders do through hub_cache_dir().

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 32cc7e3b9b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 21, 2026
An OOM (or any error) in the tiny decoder failed the whole render. The
draft now catches it, frees the attempt, and runs the decoder that was
in place before the swap; the render is then not recorded as a draft.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: faf6351051

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 6f4c2a7 into main Nov 21, 2026
@danielhanchen
danielhanchen deleted the nov21-distill-taehv branch November 21, 2026 20:40
danielhanchen added a commit that referenced this pull request Nov 21, 2026
…p dunders spreading the decode-rewrap scan (#18815)

## Problem

`(Python 3.13, diffusion)` fails on `main` and on every PR based on it
(for example #18806) with two failures:

```
test_diffusion_family_data_freeze.py::test_family_data_resolves_identically   AssertionError: tables
test_diffusion_vae_oom.py::test_every_decode_rewrap_site_restores_the_oom_scope  510 sites flagged, first ('diffusion.py', 'DiffusionBackend.__init__')
```

Both reproduce locally on `main` (`d8ff4de6a1`). Running both tests on
each Studio inference commit since the last green `main` attributes
them:

| commit | freeze | decode rewrap |
|---|---|---|
| `8d41610c50` (#18800) | pass | pass |
| `d66aa77cee` (#18779) | fail | pass |
| `6f4c2a7bd9` (#18780) | fail | fail |

## Causes

**Family data freeze (#18779).** #18779 adds the dense FastWan students
as trusted video repos. The frozen table was not regenerated, so the
only difference is two new `trusted_video_repos` entries,
`fastvideo/fastwan2.1-t2v-1.3b-diffusers` and
`fastvideo/fastwan2.2-ti2v-5b-fullattn-diffusers`. The PR is right; the
fixture is behind.

**Decode-rewrap scan (#18780).** The test seeds every function that
assigns `.decode`, then marks any function that calls one of those *by
bare name* as a rewrap helper too, to a fixpoint. #18780's opt-in draft
decode is a context manager, `TinyVaeDraftDecode`, which swaps
`vae.decode` in `__enter__` and restores it in `__exit__`. That made
`__enter__` and `__exit__` seeds, and a bare-name match on `__exit__` /
`__enter__` reaches every function that drives any context manager by
hand, so the fixpoint spread to 510 functions. The draft swap itself is
scoped and restores the previous `decode` on exit, and its fallback
calls the decode it replaced, so the OOM scope is intact. The PR is
right; the scan's name matching is too loose for dunders.

## Fix

Test-only:

- `tests/fixtures/diffusion_family_data_freeze.json`: regenerated with
`UNSLOTH_FREEZE_UPDATE=1`. The diff is exactly the two FastWan repos (2
lines added).
- `test_every_decode_rewrap_site_restores_the_oom_scope`: dunder method
names are not propagated by name. A dunder is reached through `with` or
an object protocol, never by a call to that name, so matching it by name
cannot identify a caller. Named helpers such as `install_untiled_decode`
still propagate as before.

## Verification

- `test_diffusion_family_data_freeze.py`, `test_diffusion_vae_oom.py`,
`test_video_tiny_vae.py`, `test_video_tiny_vae_wiring.py`: 134 passed, 5
skipped.
- Sabotage: adding `def _sabotage_leak(vae):
install_untiled_decode(vae)` to `video.py` fails the rewrap test with
`[('video.py', '_sabotage_leak')]`, so a real unguarded rewrap is still
caught. Restored afterwards.
- The freeze fails on `main` without the regenerated fixture, as on CI.
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…DMD diffusers skip, risky loader lint) (#18824)

## Summary

Four checks are red on `main` itself, so every open PR currently
inherits them in the Backend CI shards and the risky loader lint. Each
was reproduced on a clean `main` checkout before fixing.

| Failing check | Introduced by | Which side was wrong | Fix |
|---|---|---|---|
|
`tests/test_diffusion_rocm_tag_detect.py::test_no_diffusion_or_video_gate_reads_version_hip_directly`
| #18793 (`diffusion_regional_compile.py`) and #18792
(`diffusion_vae_strips.py`) | Code. Both new gates read
`torch.version.hip` directly, which the ROCm tag guard exists to forbid
(a CUDA wheel with a stray `hip` attribute, or a ROCm wheel reporting it
differently, takes the wrong branch). | Route both through the shared
`is_rocm_torch(torch)` helper from `rocm_bf16`. Behaviour on CUDA and
ROCm is unchanged. |
|
`tests/test_h3_quantised_offload.py::test_a_streamed_torchao_render_runs_under_no_grad_and_the_rest_keep_inference_mode`
| #18780 added `draft_ctx` to the denoise `with` | Test. The invariant
(the denoise loop enters `grad_ctx` together with its progress context)
still holds; the test pinned one exact spelling of the `with` line. |
Parse the `with` statements and assert `grad_ctx` and `progress_ctx()`
are entered together, regardless of what other contexts join them.
Verified it still fails when `grad_ctx` is dropped from the statement. |
| `tests/test_video_dmd.py::test_dmd_scheduler_reseeds_per_render`,
`::test_renoise_stream_is_independent_of_the_initial_latent_noise` |
#18779 | Test. `make_dmd_scheduler` builds on a diffusers scheduler, but
these two tests only skipped on missing torch, so they error with `No
module named 'diffusers'` in the shard that runs without diffusers. |
`pytest.importorskip("diffusers")`, matching the existing scheduler test
in the same file. |
| `scripts/lint_risky_loaders.py` (`diffusion_ddp.py:440
[dynamic-import] __import__`) | #18771 | Code. The rank bootstrap
imported two fixed modules through `__import__` in a loop. | Import
`utils.native_tls` and `utils.happy_eyeballs` by name, each in its own
`try`, so a failure in one still does not stop the rank or skip the
other. No baseline entry needed. |

## Testing

- `tests/test_diffusion_rocm_tag_detect.py`,
`tests/test_h3_quantised_offload.py`, `tests/test_video_dmd.py`,
`tests/test_diffusion_ddp.py`, `tests/test_diffusion_training.py`, the
native TLS and happy eyeballs suites, and the regional compile and VAE
strip suites: all pass.
- `tests/test_video_dmd.py` with diffusers blocked from import: 26
passed, 7 skipped (previously 2 errors).
- `python scripts/lint_risky_loaders.py`: all call sites recorded.
- Sabotage: restoring either original `torch.version.hip` read makes the
ROCm tag guard fail; restoring the `__import__` loop makes the risky
loader lint fail.
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