Skip to content

Studio diffusion: Qwen-Image denoiser step captures as a CUDA graph - #15541

Closed
danielhanchen wants to merge 1 commit into
mainfrom
studio-vsc3-img-qwen-graph
Closed

danielhanchen wants to merge 1 commit into
mainfrom
studio-vsc3-img-qwen-graph

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

The Qwen-Image denoiser step never captured as a CUDA graph on the edit path. Every Qwen-Image-Edit-2511 load logged:

diffusion.cuda_graph: capture failed on QwenImageTransformer2DModel (RuntimeError: Cannot copy between CPU and CUDA tensors during CUDA graph capture unless the CPU tensor is pinned ...); this load runs eager

The stock QwenImageTransformer2DModel.forward builds device tensors from Python values on every step:

  • modulate_index = torch.tensor(<0/1 per image token>, device = ...) when the config sets zero_cond_t (Qwen-Image-Edit-2511);
  • torch.as_tensor(text_seq_len, device = ...) in compute_text_seq_len_from_mask;
  • under torch.compile, the RoPE tables (pos_embed.pos_freqs / neg_freqs, plain CPU attributes) are copied to the device per call, because the compiled forward traces through their lru_cache.

Each is a copy from pageable host memory, which a capture refuses. Two consequences:

  1. The step ran without its graph.
  2. The render counted a failed capture, so it never recorded a learned activation peak. A returning user therefore placed exactly like a fresh one.

Changes

  • New diffusion_qwenimage_host_consts.py:
    • points the Qwen-Image module's torch global at a copy of the torch namespace whose tensor / as_tensor return a cached device tensor for the same Python value (built by the warm-up forward before a capture, read by the captured one);
    • moves the RoPE tables to the input's device once, in a forward pre-hook before the first forward.
    • Every other call goes to torch unchanged. Values are identical, so renders are bit-identical.
  • Registered in diffusion_autoopt/patches.py as qwenimage_host_consts (pre-compile stage, fused-DiT group, so unload restores the module global).
  • Kill switch: UNSLOTH_DIFFUSION_QWEN_HOST_CONSTS=0 (the registry's UNSLOTH_DIFFUSION_PATCH_QWENIMAGE_HOST_CONSTS=0 also works).

Results

Qwen-Image-Edit-2511, 1024x1024 output, one 1024x1024 source, 40 steps, true CFG 3. Studio auto (int8 DiT, int8 encoder). RTX PRO 6000 Blackwell (G4), one VM, arms B H H B, a warm-up plus 3 new instructions per process.

arm s/image, median [each new instruction] CUDA graph
main r1 / r2 31.893 [31.885, 31.902, 31.893] / 31.904 capture failed, eager
this PR r1 / r2 31.783 [31.932, 31.783, 31.759] / 31.792 captured ... graph 1/4, graph 2/4
  • 0.35% faster per image. The A/A spread is 0.03% (main) and 0.03% (this PR).
  • The learned peak is now recorded: learned activation peak 6046 MiB recorded for qwen-image-edit / ... graphs:step.
  • PNGs are bit-identical to main on every instruction (md5 e1d06ca1, 9180fae9, 7f3a4413 in both trees).
  • At a 16 GiB budget the denoiser streams every block. The graph now captures, then Studio drops it by its existing rule (replay measured within 1% of the eager step ... not worth the memory a streamed recording holds), so that tier is unchanged: 49.35 / 49.39 s against main's 49.21 / 49.23 s, with bit-identical PNGs.

Tests

  • New tests/test_diffusion_qwenimage_host_consts.py:
    • install / uninstall / kill switch;
    • the cache returns the same device tensor for the same value;
    • a forward on a tiny zero_cond_t transformer is bit-identical with the patch;
    • CUDA: the tiny transformer's step captures as a CUDA graph, eager and torch.compiled, with output identical to eager;
    • CUDA: a guard test showing the stock step does not capture.
  • Main: the file fails at import (the module does not exist). This branch: 34 passed (with the registry test).
  • test_diffusion_autoopt_core.py lists the new spec. The autoopt, CUDA-graph, offload-graph and Qwen RoPE test files give 231 passed, 3 failed on both main and this branch. The 3 failures are in test_diffusion_qwenimage21_graph.py and are identical on both trees.

Limits

  • Measured on sm_120 only. The capture fix is device-independent; the speed effect on other cards was not measured.
  • The 16 / 12 GiB loss on this model comes from placement, not graphs. It is addressed separately.

…device-cached modulate_index / text-length constants, device RoPE tables)
@danielhanchen danielhanchen self-assigned this Oct 27, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 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 ⚠️ Failed 2026-10-27T11:28:41.031125Z
We couldn’t complete this review. Comment @codex review to try again.
79762d5 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

Closing this one. The gain is 0.35% per image on a fully resident Qwen-Image-Edit-2511 load. At the 16 and 12 GiB budgets, where the edit model is actually slow, the captured graph is dropped by the existing replay rule. The learned peak it unlocks (6046 MiB) is the same figure #15542 now ships as the seed. That is not worth replacing the Qwen-Image module's torch namespace for.

emaxlele pushed a commit to emaxlele/unsloth_LM_Studio that referenced this pull request Oct 29, 2026
…d for Qwen-Image-Edit under a VRAM budget (unslothai#15930)

## Summary

Qwen-Image-Edit-2511 under a VRAM budget streamed every offloaded block
twice per denoising step, once for the conditional branch and once for
the negative branch. At 16 GiB on an RTX PRO 6000 Blackwell (G4), Studio
read about 58 GB per step over PCIe (53 GB/s for 43.5 s of denoise over
40 steps). ComfyUI v0.43.0 reads about 15 GB per step on the same card
and budget, because it runs both branches in one forward and so uploads
each weight once per step. That copy volume was the whole budget gap:
ComfyUI was 11-12% faster at 16 / 12 GiB while Studio is 17.6% faster
resident.

The existing CFG batcher could not close the gap:

- It merges both branches into one batch-2 call. That doubles the
activation peak (no room at 16 / 12 GiB) and is not always bit-exact.
- It was never armed on this load. The after-placement CUDA graph armed
first (`cfg_batch: not armed (the denoiser replays CUDA graphs)`), then
its capture failed on every edit load (`Cannot copy between CPU and CUDA
tensors during CUDA graph capture ...`). So the load ran eager with
neither lever.

## Change

- New `core/inference/diffusion_cfg_pair.py`. When the denoiser is
block-streamed, the conditional call runs the stock forward, and each
block's own compute (the callable below its offload hook, compiled or
not) also runs the negative branch while that block's weights are on the
card.
- The negative branch's prologue and epilogue come from the stock
forward too, run on a one-block stand-in list: a probe that records the
first block's arguments, then an inject that returns the branch's last
block output.
- Every block call keeps the shapes and inputs of a plain call, so
outputs are bit-identical. Activations are not doubled, so the placement
is unchanged.
- `CfgBatchRouter` gets a pair mode. It reuses the existing second-call
template, prediction and bitwise check: a negative call that differs
from the prediction reruns plain. One plain pair per render records the
template, then every later guided step pairs.
- `arm_graphs_after_placement` leaves the step graph off when pairing
will arm. On a streamed placement the replay was within 1% of eager
(unslothai#15541), and on this model the capture failed anyway.
- Scope: `QwenImageTransformer2DModel` from diffusers (Qwen-Image,
Qwen-Image-Edit, Edit-2509 / 2511), block-level group offload only.
Resident loads, other classes and Qwen-Image-2.1 are unchanged.
- Kill switch: `UNSLOTH_DIFFUSION_CFG_PAIR=0` restores the previous path
(graph armed, CFG batcher declined).

## Results

Qwen-Image-Edit-2511, 1024x1024 output, one 1024x1024 source, 40 steps,
true CFG 4. Studio auto (int8 DiT, int8 text encoder), ComfyUI v0.43.0
with its default graph. All arms ran on one RTX PRO 6000 Blackwell (G4)
VM, interleaved, with the budget simulated by a ballast plus a capped
device total. Each arm is a fresh process with a fresh Studio home: a
warm-up render, then the median of 3 new instructions.

| budget | main (r1 / r2 / r3) | this PR (r1 / r2 / r3) | change |
ComfyUI | Studio vs ComfyUI |
|---|---|---|---|---|---|
| 16 GiB | 43.739 / 43.736 / 43.735 s | **33.030** / 33.222 / 33.022 s |
-24.5% (1.32x) | 39.208 s | Studio 18.7% faster (was 10.4% slower) |
| 12 GiB | 45.647 / 45.649 s | **33.084** / 33.119 s | -27.5% (1.38x) |
41.204 s | Studio 24.5% faster (was 9.7% slower) |
| resident | 31.425 s | 31.449 s | unchanged (pairing does not arm) | |
|
| 16 GiB, `UNSLOTH_DIFFUSION_CFG_PAIR=0` | | 43.740 s | same as main | |
|

- A/A spread (repeats of the same tree): main 0.01% at 16 GiB and 0.004%
at 12 GiB; this PR 0.6% at 16 GiB and 0.1% at 12 GiB. Every delta above
is far outside them.
- Denoise s/step: 16 GiB 1.082 -> 0.813; 12 GiB 1.131 -> 0.817; resident
0.782. The budget tiers now run within 4.5% of resident.
- Torch profiler, one 16 GiB render:
- host-to-device traffic during denoise falls from 1983.9 GiB to 1016.8
GiB (49.6 -> 25.4 GiB per step);
  - copy time not hidden behind compute falls from 11.84 s to 0.79 s;
  - kernel busy time is unchanged (31.47 vs 31.62 s).
- Mean PCIe receive: 53.3 -> 36.5 GB/s at 16 GiB and 58.7 -> 41.7 GB/s
at 12 GiB. ComfyUI: 15.5 and 23.8 GB/s.
- Output: every PNG is bit-identical to main at the same tier: all 3
instructions at 16 GiB (the kill-switch arm and the profile arms
included), at 12 GiB and resident. LPIPS 0, PSNR 99 dB, max abs 0.
- Peak VRAM of the Studio process: 12.15 -> 12.19 GiB at 16 GiB and 9.05
-> 9.09 GiB at 12 GiB. Placement is unchanged: 14 / 7 of 61 offload
groups resident.
- Engagement: `diffusion.cfg_pair: 39 guided step(s) ran both branches
through each streamed block` on every head render (the first step of a
render runs plain to record the template). `capture failed` is gone from
the budget arms. No recompile and no router disable in any log.
- First image (load + cold render) at 16 GiB: 83.6-85.1 s -> 64.2-68.3
s.

## Tests

- New `tests/test_diffusion_cfg_pair.py` (6 tests) on a tiny real
`QwenImageTransformer2DModel` under diffusers block-level group offload,
with `zero_cond_t` on and off:
- paired steps are bit-identical to two plain calls, across two renders;
  - each block runs once per paired step instead of twice;
- a negative prompt swapped mid-render misses, reruns plain and still
matches bitwise;
  - the kill switch keeps the batch router;
  - resident, graph-armed, LoRA-scale and ControlNet calls are refused.
- `test_diffusion_cfg_batch.py`, `test_diffusion_cfg_batch_sync.py`,
`test_diffusion_offload_cuda_graph.py`,
`test_diffusion_offload_prefetch.py`, `test_video_backend.py`: 601
passed, 0 failed on both main and this branch.

## Limits

- Measured on sm_120 (G4) only. The copy halving does not depend on the
card; how much it buys depends on how copy-bound the budget tier was.
- Only `QwenImageTransformer2DModel` (diffusers) with block-level
offload is paired. FLUX / Wan streamed loads keep the existing path.
- The resident CUDA-graph capture on this model still fails (`Cannot
copy between CPU and CUDA tensors ...`), as on main. unslothai#15541 measured
0.35% for fixing it.
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