Skip to content

Studio diffusion: run both guidance branches per streamed block upload for Qwen-Image-Edit under a VRAM budget - #15930

Merged
danielhanchen merged 4 commits into
mainfrom
studio-qwen-edit-budget
Oct 29, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-qwen-edit-budget

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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 (Studio diffusion: Qwen-Image denoiser step captures as a CUDA graph #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. Studio diffusion: Qwen-Image denoiser step captures as a CUDA graph #15541 measured 0.35% for fixing it.

@danielhanchen danielhanchen self-assigned this Oct 29, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 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-29T08:28:12.501826Z 1223d31 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

Copy link
Copy Markdown

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

Reviewed commit: 1223d3177e

ℹ️ 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 9c30724 into main Oct 29, 2026
@danielhanchen
danielhanchen deleted the studio-qwen-edit-budget branch October 29, 2026 12:09
danielhanchen added a commit that referenced this pull request Oct 29, 2026
…inned row (#15959)

## Summary

`Mac Unsloth UI + API + Update + Inference CI` fails now and then in
`tests/studio/playwright_mac_tab_capabilities.py` on PRs that do not
touch the sidebar (#15930 at 08:33, #15953 at 11:20 on 2026-10-29; the
other runs that day passed):

```
[mac-tabs] FAIL: Library: nav row library is pinned inline by default but did not render
```

The run's `tab_library.png` shows why: the page was still on the app's
boot `Loading...` screen, with no sidebar at all. Each tab is a full
`page.goto(..., wait_until="domcontentloaded")` followed by a fixed 1.5
s wait, and on a slow macOS runner the app had not mounted by then. The
Library row was never missing from a rendered sidebar; nothing had
rendered yet. So this is the test's timing, not the product.

## What changed

- `drive_tabs` waits up to 30 s for the sidebar shell (any `nav-row-*`;
every pinned row renders in the same pass) before it judges the tab's
row. A shell that never mounts is logged and the pinned-row check still
fails.
- The pinned-row failure now says whether the shell had mounted and
lists every row's state, so a future failure tells "app not booted"
apart from "row missing".

## Verification

- `tests/studio/test_mac_tab_capability_warm_window.py`: 53 passed,
including two new cases on its `FakePage`:
- the sidebar only mounts once the script waits (the boot screen): no
failure, every pinned row seen
- the sidebar mounts without the Library row: still fails, and says
`shell mounted: True`
- With the wait removed from `drive_tabs`, both new cases fail; the
existing "rows never render", "projects stand-in" and "hidden section"
cases keep passing either way.
danielhanchen added a commit that referenced this pull request Oct 29, 2026
…eir 2100 s cap (#15951)

## Summary

`Repo tests (CPU, rest)` is close enough to its 2100 s step cap that
slow runners now hit it. On #15931 (staging) it finished `15282 passed
... in 2092.47s` and was then killed with exit 124, so the job went red
after every test had passed. Across 16 staging runs on 2026-10-29 its
pytest step took 1213 s to 2092 s; on the slower runners it sits at 1700
to 1820 s, 81 to 87% of the cap. This is the same thing #15851 did for
the fsdp2 shard.

## What changed

- `rest` is split into `rest` and a new `rest-2`. `rest-2` takes
`tests/diffusion`, `tests/kaggle`, `tests/security` and the top-level
`tests/test_[dimsu]*.py` files, and `rest` ignores the same paths.
`rest` stays the catch-all, so a new folder or file still lands there
without a workflow edit.
- The cut is from a per-file `--durations` run of the old shard (4
workers, 8 cores): those paths are about 1890 of its 3763 test-seconds,
so each half carries about 50%.
- No `*gloo*` or `test_fsdp2*` file starts with d, i, m, s or u, so the
glob root (which `--ignore` cannot filter) never names a file the gloo
or fsdp2 shards also run.
- The two `test_model_registry.py` deselects move with their file into
`rest-2`.
  - The CLI and Docker feature steps stay on `rest`.
- `gloo` is split the same way. It ran 1331 to 2058 s of the same 2100 s
cap across 17 staging runs on 2026-10-29 (#15930's run took 1953 s), so
it is next. Measured per file (4 workers, 8 cores; 4049 test-seconds),
native tensor parallel plus pipeline parallel are about 51% and move to
a new `gloo-tp-pp` shard (`tests/test_tp_n*gloo*.py`,
`tests/test_pp*gloo*.py`); `gloo` keeps everything else through four
globs that exclude those two. A `*gloo*` file matching neither (a new
`test_t[!p]*` or `test_tp[!_]*` name) is reported as dropped by
`test_no_file_is_dropped_or_run_twice`.
- `tests/test_cli_export_unpacking.py` restores `sys.path`. The first
staging run of the split failed 7 tests and errored 4 in the new `rest`
(`test_tiled_mlp_ddp`, `test_reap_prune`,
`test_gc_skip_auto_dist_cells`), each `spawn` child dying with `No
module named 'tests.<file>'`. A per-test `sys.path` watcher over the
full new `rest` shard named the cause: the CLI export run puts
`studio/backend` first on `sys.path`, `studio/backend/tests` is a
package, and the test never took it back out, so every later `spawn`
child in that xdist worker imported the wrong `tests`. It was
order-dependent on main too; the new file distribution just put a spawn
test after it on the same worker. A new
`test_an_export_run_leaves_sys_path_as_it_found_it` checks the run does
change `sys.path` and that it is restored afterwards.
- `tests/test_ci_repo_cpu_shards.py`: the hub-test deselect check now
asserts the deselect sits in the shard that actually collects
`tests/test_model_registry.py`. Before, it only checked the text
appeared anywhere in the matrix, which would still pass with the
deselect left behind on `rest` after the file moved.
- `tests/studio/test_backend_ci_parallel_isolation.py`: expects 11
parallel runs / 8 repo-root shards, and its path reader expands glob
roots the way bash does (it previously treated
`tests/test_fsdp2_*.py`-style roots as literal paths, so no glob shard
could ever be found collecting a file).

## Verification

- `pytest --collect-only` with the old `rest` selection: 18418 tests.
With the new `rest` plus `rest-2`: 9711 + 8707 = 18418, no test in both,
and the union is identical to the old set. The two deselected registry
tests are not collected.
- Same check for gloo: old selection 173 tests, new `gloo` +
`gloo-tp-pp` 89 + 84, no overlap, identical set.
- `tests/test_ci_repo_cpu_shards.py`,
`tests/studio/test_backend_ci_parallel_isolation.py`,
`tests/studio/test_cache_budget_discipline.py`: all pass.
- A probe file `tests/test_tz_probe_gloo.py` (a name neither gloo shard
globs) makes `test_no_file_is_dropped_or_run_twice` fail with that path.
- `pytest tests/test_cli_export_unpacking.py
tests/test_gc_skip_auto_dist_cells.py` in one process: 24 passed with
the restore. Without it the new guard fails (`1 failed, 9 passed`).
- Moving the two deselects back onto `rest` makes
`test_the_deselected_hub_tests_stay_deselected` fail.
- This PR's own CI run is the timing check: each half of both splits
should land near half of its old shard.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 29, 2026
… of the int8 DiT resident under a VRAM budget (unslothai#15985)

## Summary

When Qwen-Image-2512 text-to-image runs under a VRAM budget, Studio
streamed every offload group of the int8 DiT. Nothing stayed resident.
At 16 GiB the Studio process used 5.4 GiB of the budget, and each
denoising step re-uploaded the whole 31.7 GiB transformer.

The cause is that the `qwen-image` family had no entry in the shipped
activation seed tables. With no seed and no learned peak, which is the
case on a fresh home, `_refine_plan_from_loaded_weights` has no headroom
figure. It returns the flat all-streamed plan. Qwen-Image-Edit had the
same problem, and unslothai#15542 / unslothai#15645 fixed it for that family only.

## Change

- `diffusion_memory.py`:
- `_MEASURED_IMAGE_PEAK_MIB["qwen-image"] = 6032`. This is the
whole-render peak Studio itself recorded for Qwen-Image-2512 on sm_120
(1024x1024, 20 steps, true CFG 4, int8 DiT and int8 encoder). A
returning home learns the same figure.
- `_MEASURED_STREAMED_IMAGE_PEAK_MIB["qwen-image"] = 3824`. This is the
Edit streamed figure. The model uses the same DiT class and the same
VAE, and text-to-image has half the image tokens (no source latents), so
this figure bounds the text-to-image peak.
- Kill switch: `UNSLOTH_DIFFUSION_MEASURED_ACTIVATION_QWEN_IMAGE=0`
drops both seeds for this family only and restores the previous
all-streamed placement.
`UNSLOTH_DIFFUSION_MEASURED_ACTIVATION_STREAMED=0` still drops only the
streamed figure.
- Scope:
- Only torchao int8 / fp8 denoisers on the default and max tiers read
these seeds.
- Dense bf16 (the eager table), GGUF, packed and fp8-stored denoisers
keep their current placement, as does the off tier.
  - A learned peak still raises the seed as before.
- The seed changes which groups stay on the card, not the math.

## Measurements

The base is origin/main `2a7e3a553e`, which already includes unslothai#15930.
Setup:

- Qwen-Image-2512, Studio auto (int8 DiT, int8 encoder), 1024x1024, 20
steps, true CFG 4, empty negative.
- One RTX PRO 6000 Blackwell (sm_120) VM. The budget is held by a VRAM
ballast plus a capped device total.
- Base and head arms are interleaved, each a fresh process with a fresh
Studio home.
- Each arm runs a warm-up, then reports the median s/image over 3 new
prompts.

| budget | base (r1 / r2 / r3) | head (r1 / r2 / r5) | change | head,
kill switch |
|---|---|---|---|---|
| 16 GiB | 12.913 / 12.889 / 12.927 s | **11.466 / 11.381 / 11.339 s** |
-11.7% | 12.984 s (same as base) |
| 12 GiB | 12.891 s | **11.991 s** | -7.0% | |

- A/A spread: base 0.3% (3 repeats), head 1.1% (3 repeats). Both deltas
are far outside the spread.
- Placement:
- 16 GiB: 7101 MiB resident (14 of 61 offload groups), against 0 on
base.
  - 12 GiB: 3319 MiB resident (7 of 61).
- Log line: `measured-activation placement group -> group (7343 MiB of
the 32496 MiB transformer ... stay resident (measured peak 7168 MiB)`.
- Torch profiler, one 16 GiB render:
- host-to-device traffic during denoise falls from 666.4 GiB to 520.8
GiB (33.3 to 24.8 GiB per step);
  - copy time not hidden behind compute falls from 5.75 s to 4.18 s;
  - kernel busy time is unchanged (6.985 vs 6.972 s).
- Peak VRAM of the Studio process at 16 GiB rises from 5.4 to 12.4 GiB,
inside the budget. At 12 GiB it rises from 5.4 to 8.7 GiB.
- No out-of-memory line in any log. At both budgets the VAE prebuild
child is skipped, as on Qwen-Image-Edit, because the streamed placement
still allocates 6229 MiB.
- Both guidance branches still share each streamed block's upload. Every
render on base and head logs `diffusion.cfg_pair: 19 guided step(s) ran
both branches through each streamed block`. With
`UNSLOTH_DIFFUSION_CFG_PAIR=0` the times are 24.481 s on base and 19.702
s on head.
- Output: every PNG is md5-identical across all 13 Studio arms on this
VM: base, head, kill switch, pair off, 12 and 16 GiB, and profiler runs.
- No regression where the DiT already fits: on an A100 40 GB with no
budget, the DiT stays resident and the placement does not change. Base
12.114 / 12.122 s, head 12.138 / 12.113 s, kill switch 12.140 s. All
PNGs are md5-identical.

## Tests

- New `tests/test_diffusion_qwen_image_seed.py` (CPU only, sizes taken
from the 16 / 12 GiB load logs):
  - the seed values and their pixel scaling;
- partial residency at 16 and 12 GiB, never above free memory, with the
encode streaming the resident groups back out;
  - both kill switches;
  - the off / eager tiers and a dense bf16 denoiser keep the flat plan.
- 56 placement, offload, CFG and Qwen suites: head 1525 passed, base
1516 passed. The same 6 tests fail on both, all pre-existing in
`test_diffusion_qwenimage21_vision.py` and
`test_diffusion_qwenimage_rope.py`.

## Not covered

- Measured on sm_120 (16 / 12 GiB budgets) and sm_80 (resident) only. No
consumer 16 GB card was used, and the budget was simulated.
- The streamed figure is borrowed from Qwen-Image-Edit, not measured for
text-to-image. The peaks measured here stay inside the budget at 16 and
12 GiB.
- Requests larger than 1024x1024 were not run. The request guard
re-streams groups for them, as for the other seeded families.
- Qwen-Image (the original release) shares the family but was not run.
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