Skip to content

Studio: encode Wan clips while the VAE decodes - #14405

Merged
danielhanchen merged 7 commits into
mainfrom
studio-video-mem-overlap
Oct 20, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
studio-video-mem-overlap

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Studio encodes a Wan clip only after the VAE has decoded every frame, so the libx264 pass sits on the critical path of every video render. This PR encodes the clip while the VAE is still decoding it and keeps the output exact.

What it does

  • core/inference/video_stream_encode.py, wired into VideoBackend.generate next to uint8_video_frames (25 lines in video.py).
  • Wan's untiled decode runs its decoder once per latent frame (1 frame, then 4 per call). A forward hook on the decoder turns each finished chunk into uint8 on the GPU with the same ops the pipeline applies to the whole clip: unpatchify (TI2V-5B), clamp, the video processor's denormalize, then the float32 (x * 255).round() from video_frames. The chunk is copied to pinned host memory on a side stream with an event and handed to a libx264 thread through a bounded queue (depth 8). Encoder settings are the ones encode_x264 uses.
  • The streamed mp4 is used only when every streamed frame equals the exported frames byte for byte. Otherwise the clip is encoded afterwards exactly as before.
  • Falls back (normal encode) on: a tiled decode, the fp16 decode's fp32 rerun, a second decode in one render, a fps or frame count mismatch, audio, NVENC, frame threads off, a decoder not on CUDA, any VAE other than AutoencoderKLWan. Cancel or failure stops the thread and removes the temp file.
  • UNSLOTH_STUDIO_VIDEO_STREAM_ENCODE=0 turns it off.

Results

On/off A/A, Wan2.1-T2V-1.3B VAE with Studio's default decode setup (fp16 decoder, channels_last conv weights, untiled), decoding a real latent captured from a Studio render (832x480, 10 steps). Decode and export only: the denoise runs before the decoder and is the same in both arms. Dedicated Colab T4 (8 vCPUs, load average 1.1 to 2.0, CPU 0.3 to 1.2% busy at the start of each arm), one process, 1 warm-up per arm, then on / off / off / on with 5 renders each:

Frames on (1st arm) off (2nd) off (3rd) on (4th) Encode tail after decode, off vs on
81 33.88 s (33.75 - 33.93) 34.18 s (34.14 - 34.34) 34.27 s (34.23 - 34.35) 33.71 s (33.70 - 33.79) 0.82 - 0.84 s vs 0.39 - 0.41 s
33 13.01 s (12.19 - 13.87) 14.11 s (13.84 - 14.68) 14.09 s (14.01 - 14.22) 14.06 s (13.95 - 14.14) 0.48 s vs 0.34 s (warm-up)

Medians, ranges in brackets.

  • 81 frames: every streamed render (10) is faster than every plain one (10). The off/off spread is 0.09 s and the on/off gap is 0.44 s. That is about 0.43 s off each clip, half the encode tail.
  • 33 frames: the last streamed arm beats both plain arms by 0.03 - 0.05 s against an off/off spread of 0.02 s. The first arm drifts upward through its run as the T4's clock settles.
  • On a T4 the decode itself takes 33 s for 81 frames, so the saving is about 1.3%. On faster cards the decode shrinks and the encode does not, so the same 0.4 s is a larger share (B200: a 1.4 s decode against a 0.4 - 0.7 s encode).
  • Frames identical in every render of both arms (same hash). Torch peak memory 4411 vs 4413 MiB.

Correctness through VideoBackend on a B200, same seeds, 4 prompts of different lengths, frames compared by hash of the uint8 frames given to the encoder (frame-threaded x264 is not byte-deterministic between runs, with or without this PR):

Model, frames Speed mode Streamed Frames equal to =0 New graph breaks / graphs on prompts 2+
Wan2.2-TI2V-5B, 33 default (compiled) 5/5 yes 0 / 0
Wan2.2-TI2V-5B, 81 default 4/4 yes 0 / 0
Wan2.1-T2V-1.3B, 81 default 5/5 yes 0 / 0
Wan2.2-TI2V-5B, 33 eager 5/5 yes 0 / 0
Wan2.2-TI2V-5B, 33 off (tiled) falls back ("tiled decode") n/a 0 / 0

Torch peak VRAM is unchanged in every B200 configuration (for example TI2V-5B at 81 frames: 22983 MiB denoise, 25609 MiB decode, both arms).

Testing

  • tests/test_video_stream_encode.py: 7 tests on a tiny CPU AutoencoderKLWan, with and without patch_size: the streamed frames equal the exported frames and the mp4 decodes to the full clip; a tiled decode, a restarted decode, one differing byte, a different fps and a short clip all fall back; a failure inside the render closes the session and removes the temp file; the switch and the engagement gates.
  • With the video backend, frames, encode, NVENC, stream residency and H3 offload suites: 614 passed, 13 skipped.

Not verified: LTX-2 and other non-Wan VAEs (never engaged by design), Wan I2V and the two-expert Wan 14B, ROCm, macOS and Windows.

Each untiled decoder chunk becomes uint8 on the GPU with the pipeline's own ops, is copied to pinned memory on a side stream and fed to a libx264 thread through a bounded queue. The streamed mp4 is used only when its frames equal the exported frames byte for byte; anything else (tiled decode, fp32 rerun, fps or frame mismatch, audio, NVENC) encodes as before. UNSLOTH_STUDIO_VIDEO_STREAM_ENCODE=0 turns it off.
# Conflicts:
#	studio/backend/core/inference/video.py
@danielhanchen danielhanchen self-assigned this Oct 20, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T20:46:44.688820Z 038f1b4 Manual request
🔒 Security Review ⚠️ Failed 2026-10-20T20:11:23.156361Z
We couldn’t complete this review. Comment @codex security review to try again.
b0a76e4 PR opened
ℹ️ 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: b0a76e4fb5

ℹ️ 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".

[skip ci]
…lds the clip

The streamed encode bypassed VideoBackend._encode_mp4, so anything wrapping the export (the in-process bench captures the frames there) saw no clip. The session is now offered to the thread and claimed inside _encode_mp4, which stays the single export path. A streamed file is used only when it demuxes to the clip's size and frame count.

[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. Keep them coming!

Reviewed commit: 038f1b4ba0

ℹ️ 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 ffd64b1 into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the studio-video-mem-overlap branch October 20, 2026 21:56
danielhanchen added a commit that referenced this pull request Oct 20, 2026
…f hanging the render (#14413)

Follow-up to #14405. If the streaming encoder fails during its final
flush (for example the disk fills up while libx264 drains its last
frames), the render hangs for good.

## What was broken

`StreamEncode._encode` takes the stop marker off the queue, then flushes
the encoder. When `stream.encode()` or `container.mux()` raises during
that flush, the exception handler drains the queue until it sees another
stop marker. `_join` has already put the only one and is blocked in
`thread.join()`, so neither the fallback encode nor cancel cleanup can
finish.

## The fix

`_encode` records that it already took the stop marker and only drains
the queue when it has not. `_failed` is still set, so `take()` returns
None and the clip is encoded the normal way.

## Tests

- New `test_a_failed_final_flush_falls_back_without_hanging`: a fake
container whose flush raises `OSError(28)`. On main `take()` never
returns (the test fails on its 60 s join); with the fix it returns None
and `close()` removes the temp file.
- `tests/test_video_stream_encode.py`: 10 passed.

Found by an outside review of #14405, which reproduced the hang with the
production `_encode` / `_join` and an encoder that fails only on flush.
danielhanchen added a commit that referenced this pull request Oct 21, 2026
… in the CFG routers, and test fixes (#14420)

## Summary

Follow-up fixes for the recently merged Studio diffusion work: two
runtime fixes (the VAE OOM ladder under a multi-GPU component split, and
bitwise comparison of expanded timesteps in the CFG routers) and five
test fixes. Each change is its own commit.

### 1. VAE OOM step (a) frees only what sits on the VAE's card (#13802
with #13725)

**What was broken.** Under a component split the VAE decodes on a
secondary card while the denoiser stays resident on the primary. When
that decode ran out of memory, `DecodeSession.free_others` reset the
denoiser's CUDA graphs on the primary card and counted that as
"released". The ladder then retried the same untiled decode on the
secondary card, which ran out of memory again before it reached the
tiled rung, and the denoiser lost its captured graphs for nothing.
`_release_groups` had the same problem with resident offload groups on
the primary card. A failed re-pin was also deferred against the VAE's
card instead of the groups' own card.

**Fix.** Graph handles are filtered to the VAE's card, using the card
the graph was recorded on (or its module's card when nothing has been
recorded yet). Resident-group modules are filtered by
`_unsloth_resident_device`. This is the same filtering
`_hook_torchao_resident` and `_move_components` already do with
`_placement(comp, self.device)`. `release_resident_groups` takes an
optional `device` filter. It is only passed when the pipeline has
resident groups on more than one card, so single-card calls are
unchanged. Anything whose card cannot be read is still freed, as before.

**Tests** (`test_diffusion_vae_oom.py`, all fail on main):
- `test_split_vae_oom_leaves_the_other_cards_graphs_alone`: a decode on
cuda:1 with graphs on cuda:0 goes straight from the untiled decode to
the tiled one, and no graph is reset.
- `test_split_vae_oom_still_drops_graphs_on_its_own_card`: only the
cuda:1 handle is reset.
- `test_split_vae_oom_releases_only_groups_on_its_own_card`: groups on
cuda:0 are left alone and nothing is deferred against them. With groups
on both cards, the release is limited to cuda:1.
- `test_release_resident_groups_device_filter`: the new filter releases
only the matching card's groups, and with no filter every card's groups
are released.

### 2. Expanded scalars compare bitwise in the CFG routers (#13725,
#13787)

**What was broken.** `_bitwise_equal` in `diffusion_multigpu.py`
flattens both tensors, calls `contiguous()` and views them as `uint8`.
WanPipeline passes `timestep = t.expand(batch)`. For a one-element
tensor `contiguous()` is a no-op whatever the stride, so the stride-0
timestep reached `view(torch.uint8)`, which raised, and the comparison
returned False for two equal timesteps. #13787 CFG batching uses it
through `_record_template`, `_matches` and the branch merge. On Wan it
missed three times in a row and turned itself off. CFG-parallel's
prediction check uses the same helper.

**Fix.** A small `_as_bytes` helper takes a dense copy only when the
flattened tensor still has a non-unit stride. `_bitwise_equal` and
`_unchanged_since_launch` both use it. Bitwise semantics are unchanged:
equal NaN bits match, and -0.0 and 0.0 do not. The CFG batcher's three
call sites all go through `_bitwise_equal`, so they are covered by the
same fix.

**Tests** (both fail on main):
- `test_bitwise_equal_on_an_expanded_scalar`
(`test_diffusion_multigpu.py`): `torch.tensor(941).expand(1)` against a
clone and a fresh expand, plus NaN, signed zero and
`_unchanged_since_launch`.
- `test_wan_expanded_timesteps_serve_the_second_branch`
(`test_diffusion_cfg_batch.py`): a Wan-style loop that passes
`t.expand(batch)` to each branch. It matches the two-call reference with
4 hits, 0 misses, and batching stays on. On main it gets 0 hits.

### 3. Seeded denoiser cancel test pins the text encoder (#13715)

**What was broken.** On a CUDA host, an unset `text_encoder_quant` also
plans the hosted FP8 Wan text encoder. The load then fetched two
artifacts and
`test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event`
failed its exact single-fetch assertion. It passed only with the GPU
hidden.

**Fix.** The test passes `text_encoder_quant = "off"`, so it checks only
what it is about: the denoiser fetch carries the load's cancel event.

**Test.** Fails on main with a GPU visible and passes after. It passes
both ways with the GPU hidden.

### 4. FLUX.2 FBCache test invalidates the child registry cache (#14401)

**What was broken.** On diffusers 0.39 and 0.40, `enable_cache` does not
drop the child-registry list that an earlier uncached render cached.
`test_fbcache_on_flux2_skips_and_matches_the_full_pass` then failed with
`ValueError: No context is set`. Production already calls
`_invalidate_child_registry_cache` after `enable_cache` in
`apply_step_cache`. Only the test helper skipped it. diffusers 0.41
invalidates the list itself.

**Fix.** The test's `_render` helper calls
`dc._invalidate_child_registry_cache(model)` after `enable_cache`.

**Test.** With diffusers 0.39.0 the test failed before and the whole
file passes after (7 passed). It also passes on the pinned diffusers.

### 5. Stream encode tests skip when diffusers cannot import the Wan VAE
(#14405)

**What was broken.** `pytest.importorskip("diffusers")` succeeds on the
lazy top-level module. The next line, `from diffusers import
AutoencoderKLWan`, can then raise `RuntimeError` (for example with a
broken bitsandbytes), which aborted collection of the whole pytest run.

**Fix.** Catch `ImportError` and `RuntimeError` on those imports and
skip the module, as the other diffusion tests do.

**Test.** In an environment with a broken bitsandbytes, collection
errored before and the module is skipped after. In the Studio
environment all 9 tests still run and pass.

### 6. Multi-GPU planner tests pin the host facts they read (#13725,
#13793)

**What was broken.** On a host with one GPU, 11 tests in
`test_diffusion_multigpu.py` failed. `make_selection` drops ordinals at
or above the real `torch.cuda.device_count()` and cards below the
primary's capability, so `make_selection(0, [0, 1])` returned None on a
one-card machine. An AMD Strix Halo CI runner (one integrated gfx1151)
showed exactly these 11. `test_diffusion_fp8_unit_scale.py` gated on
`get_device_capability() >= (8, 9)`, which passes on ROCm because ROCm
reports the gfx version (gfx1151 gives (11, 5)), and torchao then
refuses fp8 there.

**Fix.** Tests only. The autouse fixture pins the card count and the
capability check (tests that probe those filters still override them),
and the fp8 GPU gate returns False on a HIP torch, matching Studio,
which already declines torchao fp8 on ROCm. New test
`test_two_discrete_rocm_cards_split_like_cuda`: with HIP set and two
cards at capability (11, 0), the planner selects both and splits onto
card 1, as on CUDA.

**Tests.** Spoofed host (HIP + one integrated card, HIP + two discrete
cards, one CUDA card without HIP): 11 failed before, 114 passed after on
each. Normal CPU host: 133 passed, 1 skipped.

### 7. The ROCm APU pool discount applies only to HIP device snapshots
(#14379)

**What was broken.** `_rocm_linux_apu_os_room_outside_pool`
(`diffusion_memory.py`) gave any unified-memory reading the smaller
Linux ROCm APU reserve on a ROCm build, without checking the snapshot's
device. On a ROCm host, a mocked Apple (`mps`) snapshot in
`test_diffusion_unified_load_override.py` got that reserve, so two
refusal tests failed. A real ROCm build never produces an `mps` reading,
so the user impact is close to zero.

**Fix.** The discount now requires a `cuda` device snapshot (`cuda` or
`cuda:N`). `test_flux3_prompt_upsampler.py` also pins
`torch.__version__` in the tests that stand in for a CUDA build (Studio
reads `+rocm` there too) and pins the card count in its warm fixture,
which read the real host.

**Tests.** The new `mps` / `cpu` reserve test fails without the fix and
passes with it. Prompt upsampler: 164 passed on a spoofed APU, two
discrete ROCm cards, two CUDA cards and plain CPU.

## Tests

Base is origin/main and head is this branch. Same host and same Studio
venv (diffusers 0.41 dev, torch 2.13). Failing test IDs were compared,
not counts.

- CPU, GPU hidden: test_diffusion_vae_oom.py,
test_diffusion_vae_oom_faults.py, test_diffusion_measured_placement.py,
test_diffusion_offload_cuda_graph.py, test_diffusion_learned_peaks.py,
test_diffusion_int8_gemm.py, test_video_stream_residency.py,
test_diffusion_offload_prefetch.py,
test_diffusion_small_host_prefetch.py,
test_diffusion_fbcache_mixed_stream.py, test_video_stream_encode.py,
test_diffusion_multigpu.py. Base: 3912 passed, 125 skipped, 0 failed.
Head: 3916 passed (the 4 new tests), 125 skipped, 0 failed. No failing
IDs on either side.
- One GPU visible: test_video_prequant.py. Base: 1 failed
(`test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event`),
85 passed. Head: 86 passed.
- CPU, GPU hidden: test_diffusion_cfg_batch.py,
test_diffusion_multigpu.py, test_diffusion_multigpu_wiring.py,
test_video_multigpu_wiring.py. Base: 128 passed. Head: 130 passed (the 2
new tests). No failures on either side.
- test_diffusion_fbcache_mixed_stream.py on diffusers 0.39.0: 1 failed
before, 7 passed after.

Wan2.1-T2V-1.3B end to end on a Kaggle T4 capped at 7.25 GiB (streamed
offload, fp32, 480x320, 17 frames, 6 steps, guidance 5, seed 1234). Base
and head ran on the two T4s of one kernel, each on its own CPU slice:

| Run | s/step | CFG batch |
|---|---|---|
| base, CFG batching off | 5.96 | not armed |
| base, auto | 8.55 | 0 hits, 3 misses (timestep 941 vs 941), then off |
| head, CFG batching off | 5.58 | not armed |
| head, auto | 5.55 | 2 hits, 0 misses, then off: measured no gain
(batched pair 5.42 s vs plain pair 5.39 s) |

- The 43% slowdown on base is gone. On this streamed T4 placement a
batched pair is no faster than two plain calls, so the batcher's own
timing gate turns it off, as designed.
- The batching-off latents are identical on base and head
(`829b889b587d13f6`), so the plain path is unchanged. The two batched
steps are not bit-exact, as documented for CFG batching.

## Not verified

- CFG-parallel on two real cards: test_diffusion_multigpu_cuda.py needs
two CUDA cards in one process and was skipped.

- No real two-GPU decode that runs out of memory. The split case is
covered by CPU tests that use real `torch.device("cuda", N)` indices
with fake graph handles and resident modules.
- diffusers 0.40.0 was not run. Its source lacks the same invalidation
as 0.39.0.
danielhanchen added a commit that referenced this pull request Oct 22, 2026
…14653)

## Problem

On ROCm gfx11 / gfx12 (Strix Halo, RDNA3, RDNA4), Studio decodes the Wan
VAE in bf16 by default (`install_rocm_vae_bf16_decode`, 6x faster per
clip than fp32 on gfx1151). The wrapper runs the decoder in bf16 and
hands the pipeline the fp32 widening of its output, so diffusers'
postprocess runs in fp32.

The overlapped video encode (#14405) converts each decoder chunk to
uint8 inside a forward hook, from the raw chunk. On this path the raw
chunk is bf16, so the hook postprocessed in bf16 while the exported
frames were postprocessed in fp32. The rounding differed, `_matches`
never passed, and every clip did all of the streamed work and then
encoded again. A gfx1151 default Wan render logs:

```
video.stream_encode: fallback (frames differ)
```

on every clip.

## Change

`StreamEncode` checks whether the VAE carries the ROCm bf16 decode
(`vae._unsloth_bf16_decode_mode`, set by the installer, so it survives
the untiled-when-fits layer Studio puts on top). When it is, the hook
widens each chunk to fp32 before the clamp and postprocess, which is
what the pipeline does with the widened output. Unpatchify and clamp are
exact in either dtype, so the chunks now equal the exported frames bit
for bit.

Paths left as they are:

- NVIDIA's fp16 decode returns fp16, so its postprocess already runs in
fp16 and its chunks already match.
- A plain fp32 decoder is unaffected (the widen is a no-op there).

## Results

AMD CI, Radeon 8060S (gfx1151), Linux, torch 2.11.0+rocm7.13.0. Base and
head ran in the same job on the same machine, run
[39753304821](https://github.com/oobabooga/unsloth/actions/runs/39753304821):

- base = main `7fd4988b11`;
- head = base plus this diff;
- Wan2.2-TI2V-5B, all defaults, 832x480, 49 frames, 6 steps, family CFG,
2 prompts;
- `wan_stream_off` sets `UNSLOTH_STUDIO_VIDEO_STREAM_ENCODE=0`, and
every arm ran twice in fresh processes (A/A).

| cell | base: encode | head: encode | base steady s/clip | head steady
s/clip |
|---|---|---|---|---|
| `wan_auto` | fallback (frames differ) | streamed (49 frames) | 42.20 |
42.43 |
| `wan_auto_repeat` | fallback (frames differ) | streamed (49 frames) |
42.53 | 42.15 |
| `wan_stream_off` | off | off | 42.51 | 42.31 |
| `wan_stream_off_repeat` | off | off | 42.27 | 42.08 |

Verdict CONFIRMED: the base reproduces the fallback, and the head
streams on every default clip.

- **Pixels:** the exported frames have the same sha256 in every arm and
at both states.
- **Peak memory:** unchanged (26.08 GiB).
- **Speed:** at this clip size, the wall-clock difference between
streaming and not is inside the A/A spread (0.3-0.7%). Encoding 49
frames at 832x480 is well under a second of a 42 s render, so the change
removes duplicated work (a full streamed encode thrown away, then a
second encode) rather than buying a measurable speedup here. The saving
scales with encode time (longer or larger clips).

The first version of this change keyed the widen on the outermost
`vae.decode`. Its gfx1151 run
([39743742573](https://github.com/oobabooga/unsloth/actions/runs/39743742573))
still fell back, because Studio's untiled-when-fits decode wraps the
bf16 decode from outside. The final version reads the mode the bf16
install records on the VAE.

## Tests

New `test_rocm_bf16_decode_streams_the_exported_frames` in
`tests/test_video_stream_encode.py`. It installs the real
`install_rocm_vae_bf16_decode` (forced mode) on a tiny
`AutoencoderKLWan`, with and without patchify, with and without an outer
decode layer like Studio's untiled-when-fits wrapper, and requires the
session to stream:

| | main | this branch |
|---|---|---|
| `tests/test_video_stream_encode.py` | 1 failed (`frames differ`), 10
passed | 11 passed |
| new test on the first version (decode-attribute check only) | failed
(`frames differ`) | - |

## Not covered

- Discrete RDNA3 / RDNA4 cards, which take the same bf16 decode path,
were not run.
- Windows ROCm was not run.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 23, 2026
…ender end (unslothai#15036)

## Summary

A Wan render pins its clip twice in host memory: once as the uint8
frames from `device_uint8` (`video_frames.py`) and once as the streamed
encode's per-chunk copies (`video_stream_encode.py`, unslothai#14405). When those
tensors are freed, torch's caching host allocator keeps the page-locked
blocks, rounded up to a power of two. Nothing empties that cache until
the model is unloaded, so every resident video model kept about 3x its
largest clip pinned while Studio was idle.

`VideoBackend.generate` now drops its last references to the clip at the
end of the render, after the stream session is closed, and calls the
existing `release_pinned_host_memory()` (`torch._C._host_emptyCache`,
present since torch 2.6, guarded with `getattr`). This happens on
success, failure and cancel. Nothing changes inside the denoise or
decode loop, and the output is unchanged.

## Details

Setup: tiny random `AutoencoderKLWan` on CUDA, decoding a
`1x4x21x60x104` latent to 81 frames at 480x832 (a 92.5 MB uint8 clip)
through `uint8_video_frames` plus `StreamEncode`, the same calls
`generate` makes. torch 2.14.1+cu130. Memory comes from
`torch.cuda.host_memory_stats()`: `allocated_bytes.current` is the
page-locked memory the host allocator holds, and `active_bytes.current`
is the part still in use.

| | before | after |
|---|---|---|
| Pinned host memory held after the render, idle (4 to 6 renders, every
run) | 290.0 MB | 0.0 MB |
| Pinned memory still in use after the render | 0 MB | 0 MB |
| Process RSS when idle | 2.20 to 2.29 GB | 1.91 to 1.99 GB |
| sha256 of the frames | `7a359e5840921104...` | `7a359e5840921104...` |
| sha256 of the mp4 | `4750003984323fab...` | `4750003984323fab...` |

The 290 MB is the 128 MB block for the whole clip plus 21 decoder chunks
at 8 MB each. That is roughly 3.1x the clip. At 720p and 81 frames the
same arithmetic gives about 580 MB.

Per-render time, 3 interleaved runs per arm, 6 renders per run, median
of renders 1 to 5 in each run:

| arm | run 1 | run 2 | run 3 | median |
|---|---|---|---|---|
| before | 1.590 s | 1.818 s | 1.329 s | 1.590 s |
| after | 1.456 s | 1.776 s | 1.393 s | 1.456 s |

The spread between repeated runs of the unchanged code (A/A) is 0.49 s,
and both arms fall inside it. The work this adds is a fresh
`cudaHostAlloc` of the clip's buffers on each render: about 23
allocations and 160 to 230 ms per render for this clip, according to the
allocator's `host_alloc_time`. It also adds about 60 to 80 ms of
`cudaFreeHost` at the end of the render. Both are small next to a real
Wan render. Only the free can synchronize, and it runs after the render
has finished.

ComfyUI does not pin VAE output at all. The only pinning in
`comfy/model_management.py` is for model weights, done with
`cudaHostRegister` against a `MAX_PINNED_MEMORY` budget and released
with `cudaHostUnregister`. So pinned memory there never outlives its use
without a bound.

## Tests

- New `test_a_render_returns_its_pinned_clip_to_the_driver[False|True]`
in `tests/test_video_backend.py`. It checks that each render empties the
host cache exactly once, after the stream session is closed. On success
it also checks that the clip is no longer referenced at that point. On
main both cases fail (2 failed); on this branch both pass.
- `tests/test_video_backend.py`, `test_video_stream_encode.py`,
`test_video_frames.py`, `test_video_encode.py` and
`test_video_stream_residency.py`: 571 passed, 7 skipped on this branch,
compared with 569 passed, 2 failed (the new test), 7 skipped on main.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 25, 2026
…too (unslothai#15173)

## Summary

unslothai#14405 encodes a Wan clip while the VAE decodes it. A forward hook on
the decoder turns each finished chunk into frames, and a libx264 thread
encodes them during the decode. `open_stream_encode` only accepted a
decoder whose weights were already on CUDA when the render started.
Model and sequential offload keep the VAE on the host between renders,
so every offloaded Wan render (`low_vram`, the 14B / A14B models on
smaller cards, T4) never streamed and paid the whole encode after the
decode.

## Changes

- The gate also accepts a VAE parked on the host when the pipeline
executes on CUDA. The offload hooks bring it onto the card for the
decode, the same way the MiniMax-H3 session already handles it.
- Unchanged:
- the per-frame check (the streamed mp4 is used only when every frame
matches the final export);
  - every fallback;
  - the kill switch `UNSLOTH_STUDIO_VIDEO_STREAM_ENCODE=0`.

## Results

Exclusive B200, real weights, default size, frames and steps. One
warm-up, then off / on / on / off / off / on in one process. Medians of
3, seconds.

| config | post-sampling, off -> on | encode tail, off -> on | peak VRAM
|
|---|---|---|---|
| Wan2.2-TI2V-5B 1280x704x121, `low_vram` (newly streams) | **3.568 ->
2.740 (-23%)**, every on run below every off run | 0.899 -> 0.363 |
10019 MiB both |
| Wan2.1-1.3B 832x480x33, `low_vram` (newly streams) | 0.863 -> 0.762
(inside the off spread) | 0.551 -> 0.374 | 4223 MiB both |

- **Base check:** on the base tree the `low_vram` VAE sits on `cpu` with
the execution device `cuda:0`, and the render reports `streamed: false`.
- **Host RAM:** rises by the pinned chunk copies, about 300 MB at
1280x704x121.

## Output identity

- **Frames:** the frames fed to the encoder are identical, and so are
the x264 settings string, SPS / PPS, frame rate, time base, and frame
and packet counts.
- **Same mp4 bytes:** TI2V-5B `low_vram` and Wan2.1-1.3B `low_vram`
produced the same mp4 bytes in every run of both arms.
- **Bitstreams can still differ:** libx264 frame threads, which the
stock export also uses, are timing dependent. The stock path alone,
under heavy host load, produced 3 different files from identical frames.
PSNR against the input frames is identical in both arms (39.8655 dB on
every TI2V `low_vram` file).

## Tests

- New test in `tests/test_video_stream_encode.py`: a host-parked decoder
opens a session only when the pipeline executes on CUDA (not with no
execution device or a CPU one), and the kill switch still turns it off.
- `tests/test_video_*.py`: 2611 passed, 105 skipped.

## Limits

- Sequential offload and A14B / I2V-14B were not run end to end. They
use the same gate and VAE class.
- No T4 numbers. There the saving is capped at about 0.4-1 s per render,
against decodes of tens of seconds.
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