Skip to content

Studio video: keep per-request residency fitting after the stream step graph is dropped (Wan2.2-TI2V-5B at 8 / 12 GB) - #14937

Merged
danielhanchen merged 12 commits into
mainfrom
studio-video-resident-graph-drop
Oct 23, 2026
Merged

danielhanchen merged 12 commits into
mainfrom
studio-video-resident-graph-drop

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #14865 (resident video streaming, merged). Based on main.

Problem

Wan2.2-TI2V-5B int8 on a 12 GB or 8 GB card still streams all 30 denoiser blocks on every render after #14865. The 12 GB peak is about 5 GiB, and s/call is about 0.10 where resident would be about 0.035. Whether it does depends on a coin flip. On a streamed load, the CUDA graph speed check keeps the step graph only if replay beats eager by 1%. For this model replay and eager land within noise (102.7 vs 104.0 ms in one run, 102.7 vs 129.2 ms in another). When the check drops the graph, two gates in video_stream_residency keep every later request unrecorded:

  1. The request's calibration key is built from the load's state.speed_optims, which still names cuda_graph. _keyed_graphs_live then reports the graph as dropped and refuses to put the peak in the keyed table. Every later request runs eager under that same graph key, so the table stays empty.
  2. The capture that was dropped advanced the card's capture generation, but nothing was recorded, so _open_window marks every later request dirty (_unsloth_video_graphs_clean = False). This happens even though no graph is alive on the card any more. The image probe already treats "no graph alive" as clean (test_another_pipelines_reset_keeps_this_pipes_capture_dirty, last step). The video path did not.

As a result, fit_for_request never sees a measured peak. The flat estimate leaves no room (10112 free - 3712 floor - overhead - estimate <= 0), so every block streams.

Fix

  • Calibration key. video_stream_residency.live_speed_optims(pipe, speed_optims) leaves cuda_graph out of the request's calibration key only when the load's whole-step graphs are off for good. That means every whole-step handle either sits on a placement that declined recording for the load (placement._declined, set by the streamed speed check or a failed stable device range) with an empty graph cache, or is poisoned. A per-key drop (the speed probe running out of memory, or a slower replay on a resident placement) leaves the rest of the load free to capture other shapes, so it keeps the graph key. reset() clears neither state. The video request path builds its key from this, so after such a drop a request keys on the eager step it actually runs. Its peaks are then recorded under that key and read back.
  • What keeps the graph key. Any per-block fallback that is armed (fallback) or engaged (fallback_handle) keeps the graph key, because block graphs then run the next requests. A request-specific eager call keeps it too (a refused argument, the graph cap, a per-call placement refusal), because the wrapper stays armed and a later request can capture. In those cases _keyed_graphs_live refuses the sample, as it did before this PR. A load whose graphs replay keeps its graph key unchanged.
  • Clean window when no graph is alive. _open_window treats a card with no live CUDA graph as clean and re-bases the capture generation, the same rule the image peak probe uses. It reads the generation before and after the live-graph count, and re-bases only when the generation did not move. A capture racing the count therefore leaves the request dirty. If any graph is alive, the previous logic runs unchanged.
  • Block graph count ordering. A block graph now joins the live set (_LIVE_BLOCKS) before note_capture bumps the generation (diffusion_block_graph.py). Every capture path then counts its graph live before the generation moves, which makes that snapshot consistent. Whole-step captures already did this.

No new switch. The existing UNSLOTH_VIDEO_DIT_RESIDENT* switches still turn the residency off.

Tests

Unit (studio/backend/tests/test_video_stream_residency.py, 8 new):

  • test_a_dropped_graph_keys_the_request_on_the_eager_step: real GraphedForward handles. A drop on a declined placement or a poisoned graph removes cuda_graph, and the key then passes _keyed_graphs_live. A load with no handles, or optims without cuda_graph, comes back unchanged.
  • test_a_per_key_drop_keeps_the_graph_key[probe_oom|resident_slower]: a drop that only removes one key, on a placement that has not declined, keeps the graph key.
  • test_a_dropped_step_graph_with_per_block_graphs_keeps_the_graph_key[fallback|fallback_handle]: a drop with the per-block fallback armed or engaged keeps the graph key.
  • test_a_request_specific_eager_call_keeps_the_graph_key: refused arguments, and a placement Refused without a speed verdict, keep the graph key.
  • test_video_request_key_names_the_live_speed_optims: the video request path builds its key from live_speed_optims.
  • test_a_request_after_a_dropped_graph_is_recorded_under_its_key: after a capture whose graph was dropped (no live graph, generation advanced), the next request is clean and its peak reaches the keyed table. A graph still alive from an unrecorded capture keeps the next request dirty, as before.
  • test_a_capture_racing_the_zero_count_keeps_the_request_dirty: a capture landing between the count and the generation read is not re-based over.
  • test_every_capture_is_counted_live_before_its_generation_moves: every note_capture call site counts its graph live first.

test_video_request_key_names_the_live_speed_optims and test_a_request_after_a_dropped_graph_is_recorded_under_its_key fail on #14865's head (the code main now carries). The fallback, request-specific and racing tests fail on the review-round base 0bc87de. The ordering test fails there by construction (the block graph's live-set add came after note_capture); it was not run there. The reworked dropped-graph test passes on both bases. All pass here. The per-key drop test fails on d1d86bd (both cases) and passes on d9ea62e; the residency and CUDA graph suites give 141 passed, 42 skipped on that head. The residency, learned-peaks, block-graph and CUDA graph suites pass after the review round: 291 passed, plus one parallel-run flake (test_capture_then_replay_uses_one_graph_and_copies_statics) that passes alone.

The video / CUDA graph / measured-peak suites (tests/test_video*.py, tests/*cuda_graph*.py, tests/*measured*.py, tests/test_diffusion_learned_peaks.py) fail the same tests on #14865's head and on this branch (pre-existing: test_video_i2v.py class swap / model offload, test_video_ltx25.py, test_video_minimax_h3_vae.py, test_video_stream_encode.py compiled decode, test_video_vae_bf16_decode_rocm.py), apart from two load flakes. test_video_ltx2_vae_tiles.py x2 failed on the base run only, and test_video_routes.py::test_generate_native_crash_points_at_the_log failed on this branch's run only and passes alone on both. 3057 passed here.

Real model, Wan2.2-TI2V-5B int8, 832x480, 33 frames, 8 steps, memory_mode=auto, speed_mode=default, on a B200 capped to 12 / 8 GB (set_per_process_memory_fraction plus a mem_get_info that reports the cap). Each arm is a fresh process with a fresh Studio home, rendering 3-4 different prompts. The graph drop was forced by setting the speed check's required gain to 99%, so the drop path runs every time.

cap arm resident groups per render peak allocated, resident renders frames vs streamed run
12 GB #14865 head, graph dropped 0, 0, 0, 0 / 30 3.6 GiB (all streamed) reference
12 GB this PR, graph dropped 0, 0, 30, 30 / 30 8.3 GiB identical (sha256 per render)
12 GB #14865 head, graph kept (unforced run) 0, 30, 30 / 30 8.8 GiB identical
8 GB #14865 head, graph dropped (unforced) 0, 0, 0 / 30 3.6 GiB reference
8 GB this PR, graph dropped (unforced) 0, 0, 16 / 30 6.2 GiB identical
8 GB #14865 head, graph dropped (forced) 0, 0, 0, 0 / 30 3.6 GiB reference
8 GB this PR, graph dropped (forced) 0, 0, 16, 16 / 30 6.2 GiB identical

With the graph dropped, render 1 runs under the graph key and stays unrecorded, as before. Render 2 records the eager key. Render 3 onward places from it. After the review round (d1d86bd), the forced-drop 12 GB arm again ran 30 / 30 resident on renders 3 and 4 (0.036 s/call on both, 8.3 GiB peak, frames identical, 0 graph breaks / recompiles). 0 graph breaks and 0 recompiles on every render of every arm.

s/call (median DiT forward): streamed 0.10-0.11. Resident 0.034 with the graph kept at 12 GB, about 0.09-0.12 eager at 30 / 30 in the forced-drop run, and 0.066-0.16 at 8 GB (16 / 30). Timings are from shared, loaded cards (host load 450+), so they show the direction only.

Not covered

  • The streamed graph keep / drop decision itself is still a coin flip when replay and eager land within noise (102.7 vs 104.0 ms here). This PR makes residency work either way, but which path a load takes still varies run to run. A hysteresis or keep-on-tie rule in the speed check would remove that variance. Not changed here.
  • Exclusive-card timing, and real consumer 8 / 12 GB cards (PCIe link speed): the cap emulates the planner's view and the allocator limit, not the link.
  • AMD / ROCm, Windows, Mac: the path is CUDA-only (applies requires a CUDA device), and the tests above are CPU unit tests.
  • HunyuanVideo-1.5 under a dropped graph: the same key is used, so the fix applies, but it was not rendered here.

danielhanchen and others added 8 commits October 22, 2026 18:05
…-baseline pad

diffusers' Wan pipelines register transformer_2 = None beside a single DiT
(Wan2.1, Wan2.2-TI2V-5B). stream_window_pad_mib read that slot as a placement
it could not size and returned None, so video_stream_residency kept every
measured request peak out of its keyed table and the store, and the per-request
residency fit only ever had the flat estimate.
… streaming tier too

The per-request residency fit applied only to the group tier. When the text
encoder alone exceeds the card (Wan2.2-TI2V-5B's 10.8 GiB UMT5 on a 12 GB card)
the plan is streaming, which streams the same block-level denoiser groups, so
the fit never ran and the int8 DiT (4.7 GiB) streamed every block every step at
a 5.6 GiB peak.
…t like Wan's

HunyuanVideo-1.5 int8 (13 GiB) on a 16 GB card streamed all 54 groups at a
7.6 GiB peak (0.36-0.39 s per DiT call). With the same per-request fit it keeps
29 groups (7.1 GiB) resident at a 15.0 GiB peak, 0.196-0.198 s per call, and the
frames are byte-identical.
# Conflicts:
#	studio/backend/tests/test_diffusion_peak_pad_empty_slot.py

[skip ci]
… fit from ever measuring

A streamed load whose speed check drops the step graph kept keying every
request on cuda_graph, so _keyed_graphs_live refused its peaks, and the
dropped capture's generation left every later request dirty although no
graph was alive. Key on the live speed optims and treat a card with no live
graph as clean, as the image probe does. Wan2.2-TI2V-5B int8 at 12 GB: 0 ->
30 / 30 blocks resident from render 3 with the graph dropped, frames
identical.
@danielhanchen danielhanchen self-assigned this Oct 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 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-23T08:54:04.826302Z d9ea62e 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.

@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: 0bc87de191

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

return optims
try:
from .diffusion_cuda_graph import live_status
_, live = live_status(None, optims, tuple(getattr(pipe, "_unsloth_cuda_graphs", ()) or ()))

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 Preserve cuda_graph when fallback block graphs remain active

When UNSLOTH_DIFFUSION_BLOCK_GRAPHS=1 is used (or the block fallback is otherwise armed), dropping the whole-step graph installs a live fallback_handle whose per-block graphs execute subsequent requests. live_status only receives the top-level handles here, so never_engaged sees the dropped whole-step cache and removes cuda_graph without inspecting that fallback. The request then reads and records measurements under the eager calibration key even though CUDA graphs are running, mixing incompatible persisted peaks; include nested fallback handles in this liveness decision before stripping the optimization.

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.

Confirmed. _engage_fallback arms per-block graphs once the whole-step graph drops a key. That happens when the module stays resident or UNSLOTH_DIFFUSION_BLOCK_GRAPHS=1 is set. live_status only sees the top-level handle and reports it dropped, so the key lost cuda_graph while block graphs ran the next requests.

Fixed in d1d86bd: the key now drops cuda_graph only when every whole-step handle is off for good with no fallback armed (fallback) or engaged (fallback_handle). Otherwise the request keeps the graph key, and _keyed_graphs_live then refuses the sample, as it did before this PR.

Test: test_a_dropped_step_graph_with_per_block_graphs_keeps_the_graph_key (both attributes) fails on 0bc87de and passes here.

return optims
try:
from .diffusion_cuda_graph import live_status
_, live = live_status(None, optims, tuple(getattr(pipe, "_unsloth_cuda_graphs", ()) or ()))

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 Strip the graph key only after a permanent graph shutdown

If the first render runs eagerly for a request-specific reason such as tensor flattening rejecting one conditioning argument, never_engaged reports the graph as inactive even though the wrapper remains armed and a later request with graphable arguments can capture and replay normally. Because this historical status is consulted before the current render, that later request is tagged without cuda_graph; once it captures, record_request_peak accepts and persists the graph-inclusive peak under the eager key, contaminating subsequent eager residency fits. Restrict this rewrite to permanent dropped/poisoned states rather than all never_engaged outcomes.

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.

Confirmed. never_engaged also returns a reason for request-specific eager calls: a refused non-tensor, float or host-tensor argument, the graph cap, or a per-call placement refusal. The wrapper stays armed after those, so a later request can capture and replay. In that case its graph-inclusive peak could land under the eager key.

Fixed in d1d86bd: live_speed_optims no longer goes through never_engaged. It strips cuda_graph only in the two states a load cannot leave:

  • the speed check's drop (_slower set with an empty cache);
  • poisoned.

reset() clears neither of these. Any other state keeps the graph key.

Test: test_a_request_specific_eager_call_keeps_the_graph_key (refused arguments, and a placement Refused without a speed verdict) fails on 0bc87de and passes here.

Comment on lines +289 to +292
if graphs == 0:
# no live graph (a dropped one freed its pool): nothing unaccounted can remain
module._unsloth_video_graphs = accounted = 0
module._unsloth_video_graph_gen = generation

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 Do not rebase a zero count across a concurrent capture

When another image or video pipeline captures on the same card between the separate _live_graphs and _capture_generation reads, this branch can observe the stale count 0 together with the newly incremented generation. It then advances _unsloth_video_graph_gen and marks the request clean even though a graph became live before peak measurement started, defeating the generation guard that previously rejected this sample and allowing a peak that omits the concurrent graph allocation to be persisted. Recheck the count or otherwise take a consistent count/generation snapshot before rebasing.

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.

Confirmed. The count and the generation were read separately. A capture landing between the two reads could pair a stale 0 with the new generation and rebase over a live graph.

Fixed in d1d86bd: _open_window reads the generation before and after the count. It rebases on a zero count only when the generation did not move. For that snapshot to hold, every capture has to be countable before it bumps the generation:

  • Whole-step captures already were: the cache entry and the capture device are set before note_capture.
  • A block graph's first capture joined _LIVE_BLOCKS only after note_capture, which left a one-statement window. That add now runs first.

So an unchanged generation means the zero count is consistent. If the generation moved, the request stays dirty, as before.

Tests: test_a_capture_racing_the_zero_count_keeps_the_request_dirty and test_every_capture_is_counted_live_before_its_generation_moves fail on 0bc87de and pass here.

…base a zero count only on a stable generation

The eager key now needs every whole-step graph dropped by the speed check or
poisoned, with no per-block fallback armed or engaged; a request-specific
eager call keeps the graph key. _open_window rebases on zero live graphs only
when the capture generation did not move across the count, and a block graph
joins the live set before its capture is counted.

[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: d1d86bd723

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

or getattr(h, "fallback_handle", None) is not None
):
return False
dropped = bool(getattr(h, "_slower", None)) and not getattr(h, "cache", None)

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 Preserve the graph key after a per-key probe OOM

When the speed probe's static input copies OOM, _timed_eager sets _slower but drops only that graph key (diffusion_cuda_graph.py:1319-1323); it does not call placement.decline, so a later request with a different shape can still capture and replay. If the first key left the cache empty and no block fallback is armed, this predicate nevertheless classifies the entire load as permanently eager and removes cuda_graph; that later request can then persist a graph-inclusive peak under the eager calibration key. Fresh evidence relative to the earlier permanent-shutdown finding is that _slower also represents this recoverable, per-key OOM rather than only a load-wide speed-check shutdown.

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.

Agreed, _slower alone was too broad. The probe OOM in _timed_eager and an unpaid replay on a resident (non-streamed) placement each drop a single key and never call placement.decline, so another shape can still capture and replay, yet the predicate treated an empty cache plus _slower as a load-wide shutdown and stripped cuda_graph from the calibration key.

Fixed in d9ea62e: _graphs_off_for_load now counts a handle as off for good only when its placement has _declined set (the streamed speed drop, or a failed stable device range, both of which stop recording for the whole load) with an empty cache, or when the wrapper is poisoned. A per-key drop keeps the graph key.

Test: test_a_per_key_drop_keeps_the_graph_key in studio/backend/tests/test_video_stream_residency.py, parametrized over the probe OOM reason and a resident slower-replay reason, on a real GraphedForward with an OffloadPlacement that is not declined. Both cases fail on d1d86bd and pass now; the existing dropped-graph tests now decline the placement as the streamed speed check does. test_video_stream_residency.py, test_diffusion_cuda_graph.py and test_diffusion_offload_cuda_graph.py: 141 passed, 42 skipped (CPU).

…e graph key

A speed-probe OOM, or an unpaid replay on a resident placement, drops one key;
another shape can still capture. Strip cuda_graph only once the placement
declined recording for the load (the streamed speed drop) or the wrapper is
poisoned.

[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. Chef's kiss.

Reviewed commit: d9ea62e31d

ℹ️ 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 598ea6a into main Oct 23, 2026
3 of 42 checks passed
@danielhanchen
danielhanchen deleted the studio-video-resident-graph-drop branch October 23, 2026 16:57
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