Skip to content

Studio diffusion: carry the next forward's first offload groups into the idle copy tail - #15088

Merged
danielhanchen merged 5 commits into
mainfrom
studio-cross-forward-prefetch
Oct 24, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-cross-forward-prefetch

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Under block offload, each denoiser forward starts cold: the top-level group and block 0 have to land before any compute runs, while the copy engine sat idle for the last ~20 ms of the previous forward. The order of offload groups is the same on every denoise step, so this change copies the next forward's first groups during the current forward's tail, into window bytes that are already free. The next forward then starts on resident weights.

Outputs are bit-identical (same weights, same kernels). Bytes in flight stay under the existing prefetch window, and the step's peak allocation is unchanged: while the last streamed block still runs (its activations are allocated) at most one group is carried, and the rest of the depth is carried only after that block is offloaded, when the forward's activations are freed.

Changes

  • diffusion_offload_prefetch.py
    • GroupPrefetcher._fill wraps past the end of the recorded order and carries the next forward's first groups, under the same depth and byte-window checks as the normal lookahead. Carrying starts at the last onload of the order with one group (TAIL_CARRY_GROUPS); the rest of the depth follows the last block's offload. Carried groups stay in ready across end() only after a forward that ran exactly the recorded order, or one that ran no block at all (a skipped step).
    • Carried copies are dropped (released after their copy lands) in these cases: an off-order forward, a slot ring or step graph being enabled, another prefetcher's forward in the same thread (a second-stage denoiser), an interrupted render, or an unknown step count. begin() refuses to start a capture on carried copies.
    • cross_forward_render(pipe) arms carrying for one pipeline call and drops whatever is left on exit. cross_forward_step(pipe, step_index) runs from callback_on_step_end and reads pipe._num_timesteps. The second-to-last step stops carrying, the last step drops anything still carried, and the decode starts with no streamed weight on the card. Carrying is not armed beside a ControlNet.
    • New stats: carried, carried_hits, carried_dropped. Kill switch: UNSLOTH_DIFFUSION_PREFETCH_CROSS_FORWARD=0.
  • diffusion_cuda_graph.py: OffloadPlacement.install (group mode) holds carrying off and drops carried copies; uninstall releases the hold. A replay bypasses the prefetcher's onloads, so paths that use step graphs or slot rings behave exactly as before.
  • diffusion.py: the image render wraps the pipeline call in cross_forward_render (only when the step callback is installed) and calls cross_forward_step at the end of _on_step, after the cancel flag is set. Other call sites never arm carrying and are unchanged.

Tests

  • New tests/test_diffusion_offload_cross_forward.py (28 tests; all error on the base tree): order wrap, one group while the last block runs, window bound across depths and windows, last-step and skipped-last-step drop, step count from the pipeline, interrupt, exit on error, CFG double forward, kill switch, graph hold and slot ring, capture backstop, two interleaved prefetchers, ControlNet, off-order, skipped forward, short order, resident groups, and real CUDA stream offload (bit-identical, nothing resident at decode, with and without a slow GPU).
  • Related suites (offload prefetch / step graphs / cuda graph / block graph / cold start / background pin / H3 prefetch / learned peaks / measured placement / multigpu / int8 stream): 1113 passed on the first commit. The same 8 tests fail on base and head in this batch: 3 in test_diffusion_qwenimage21_graph.py, plus 5 in test_diffusion_learned_peaks.py that pass when that file runs alone. After the tail change: offload prefetch, step graphs, offload cuda graph, block graph, H3 prefetch, background pin and cold start all pass (260 tests).
  • Real tiny FluxPipeline render (hf-internal-testing/tiny-flux-pipe with 4 double and 8 single random blocks), block offload with the Studio prefetcher, two prompts, base vs head:
    • Output sha256 is identical for every combination of CFG off/on, step graphs off/on and regional compile on/off. Graphs on and off give the same sha too.
    • Decode starts with 0 streamed weights and 0 carried groups on the card. Decode-entry allocation and decode peak match base exactly.
    • Step graphs: 1 capture, 0 invalidations; prompt 2 adds replays only, same as base. Regional compile: 3 unique graphs, 0 recompiles on prompt 2, same as base.
    • Eager head: carried == carried_hits, 0 dropped, 0 missed, and the same copy count as base.

Timing on an exclusive B200 with a synthetic Flux-scale DiT (6 double + 12 single blocks, 7.58 GB bf16, depth 2, 2.04 GB window). Each arm ran in a fresh process, arms were interleaved, 3 repeats with 8 steps each. The table shows the median of the per-run medians; the A/A spread is max minus min over the base repeats. Step peak allocation was identical across every repeat of every arm (A/A 0).

tokens CFG resident ms/step base ms/step (A/A spread) head ms/step (spread) delta kill switch ms/step sha base = head = resident = off step peak alloc GB base / head
4096 off 32.7 140.8 (3.6) 138.7 (5.8) -1.4% (within noise) 143.2 yes 2.5439 / 2.5439
16384 off 149.9 181.2 (2.5) 172.5 (2.3) -4.8% 182.6 yes 3.5288 / 3.5288
32768 off 379.7 391.3 (1.1) 380.4 (0.1) -2.8% 391.1 yes 4.8588 / 4.8588
4096 split 65.3 287.7 (37.7) 277.7 (6.5) -3.5% (within noise) 285.8 yes 2.5444 / 2.5444
16384 split 299.3 360.9 (5.4) 348.0 (4.6) -3.6% 366.3 yes 3.5309 / 3.5309
32768 split 759.3 780.1 (0.9) 760.4 (2.8) -2.5% 778.5 yes 4.8630 / 4.8630
16384 batch 304.8 318.9 (0.7) 310.7 (1.2) -2.6% 318.7 yes 4.8595 / 4.8595

The memory allocated after the render, where the decode starts, also matches base in every config.

An earlier version carried the full depth during the last blocks. It was faster at 16384 tokens (-8.8% without CFG, -9.2% with split CFG), but it raised the step peak by 0.05 GB at 16384 tokens and by 0.45 to 0.50 GB at 32768 tokens and with batched CFG: the carried double blocks sat beside the larger activations of the last single blocks. Holding the step peak at base means the second group can only be allocated after the last block's activations are freed, so its copy cannot start before that block's compute ends. That is where the rest of the 16384-token gain went.

…forwards

When the event-fenced GroupPrefetcher's lookahead runs past the last recorded group, copy the next forward's first
groups into the free window bytes so the next forward starts on resident weights instead of waiting for block 0.
Same weights and kernels (bit-identical), bytes in flight stay under the existing window.

Armed per pipeline call (cross_forward_render) and stopped from the step callback (cross_forward_step) so the last
step carries nothing into the decode; dropped on interrupt, unknown step count, off-order or interleaved forwards.
Never under a slot ring or an installed step graph (OffloadPlacement holds it), and a capture never starts on carried
copies. UNSLOTH_DIFFUSION_PREFETCH_CROSS_FORWARD=0 turns it off.
A carried group beside the last block's live activations lifted the step peak above the forward's own (FLUX at
32k tokens / batched CFG: +0.45 to +0.50 GB). Carry one group at the last onload and the rest of the depth only after
the last block is offloaded, when the forward's activations are freed: the step peak now matches the base exactly.
@danielhanchen danielhanchen self-assigned this Oct 24, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 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-24T06:31:14.228044Z 3e29389 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 3e2938901d

ℹ️ 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 a31803a into main Oct 24, 2026
38 of 42 checks passed
@danielhanchen
danielhanchen deleted the studio-cross-forward-prefetch branch October 24, 2026 07:25
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 24, 2026
Extends the cross-forward prefetch carry (merged in unslothai#15088 for image
renders) to Studio's video renders. When the denoiser streams from host
RAM, the first groups of the next forward are already prefetched while
the last streamed block of the current forward runs, instead of waiting
for the next forward to start.

### Changes

- `video.py`: renders run `pipe(**kwargs)` inside `cross_forward_render`
(`_carried_call`, armed only when the pipeline takes
`callback_on_step_end`). It is armed on the render thread, since the
interleave check is per thread.
- `video.py`: the step callback calls `cross_forward_step(p, step_index,
timestep=timestep)`, also on the cancel path.
- `diffusion_offload_prefetch.py`: two-expert pipelines (Wan2.2-A14B
high / low noise) carry only into a forward of the same expert.
- `_expert_router` reads which expert runs a step the way the pipeline's
loop does: `t >= boundary_ratio * num_train_timesteps`, on one host copy
of the schedule per render, with no per-step sync.
- The step before a switch carries nothing, and an expert that does not
run next drops its carried copies.
- **When the next module cannot be known, nothing is carried:**
- a timestep that is not the scheduler's own schedule entry (checked by
address, no device read);
  - a step-count mismatch;
- a second denoiser under any loop other than diffusers' Wan pipelines,
including subclasses that override `__call__`.
- **Paths that are not armed:** pipelines without a step callback
(HunyuanVideo-1.5, MiniMax-H3, which has its own prefetch) and LTX-2.5's
two-stage render. Resident, step-graph and slot-ring paths are
unchanged.
- **Kill switch:** the same as for images,
`UNSLOTH_DIFFUSION_PREFETCH_CROSS_FORWARD=0`.

### Results

Exclusive B200, random-weight Wan2.1-T2V-14B DiT from the real config
(40 blocks, bf16), Studio group offload with the group prefetcher,
regional compile. 480x832, 8 steps, CFG 5.0. Three interleaved repeats
per arm, each in a fresh process, timing prompts 2-3.

| frames | tokens | base ms/step (A/A spread) | this PR | delta | kill
switch 0 | step peak GB (all arms) |
|---|---|---|---|---|---|---|
| 17 | 7800 | 1052.8 (1.8) | 1039.5 | -1.3% | 1050.9 | 3.1263 |
| 33 | 14040 | 1064.8 (2.5) | 1041.8 | -2.2% | 1063.0 | 3.5297 |
| 81 | 32760 | 2622.2 (4.0) | 2614.1 | -0.3% | 2623.0 | 4.7397 |

- **Peak memory:** step peak is identical in every arm and repeat, and
memory allocated at decode entry matches base.
- **Outputs:** latents sha256 match across base, this PR and the kill
switch for all frame / prompt pairs.
- **Compile:** 0 recompiles and 0 new graphs on prompts 2-3 in every
arm.
- **Carry:** 750 carried, 750 read, 0 dropped, 0 missed. The copy count
is unchanged.
- **Wan2.2-A14B (two random 14B experts, boundary 0.875, switch after
step 2):**
  - sha256 is identical across base, this PR and the kill switch.
- Each expert's carries were all read, with nothing carried across the
switch and nothing left on the card at decode.

### Tests

- New `tests/test_video_offload_cross_forward.py`. It covers:
  - a switch at steps 1 / 2 / 4 / 5, with and without CFG;
  - an unreadable schedule;
  - other loops and overriding subclasses not being armed;
  - no-boundary pipelines and a re-read schedule;
  - the wiring and the kill switch;
  - a CUDA two-expert streaming run checked bit-identical.
- `test_video_offload_cross_forward.py`,
`test_diffusion_offload_cross_forward.py`, `test_video_backend.py` pass.

### Not covered

- The 81-frame gain is small (8 ms against a 4 ms spread): the step is
compute-bound there.
- The bench drives diffusers `WanPipeline` with Studio's offload
installers rather than a full `VideoBackend.generate` with real weights.
- LTX-2 and Wan I2V / VACE are wired but were not run on a GPU.
- Wan2.2-A14B timing has one repeat.
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