Skip to content

Studio diffusion: multi-GPU component placement and CFG-parallel - #13725

Merged
danielhanchen merged 59 commits into
mainfrom
studio-diffusion-multigpu
Oct 20, 2026
Merged

danielhanchen merged 59 commits into
mainfrom
studio-diffusion-multigpu

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

Summary

Studio collapsed any multi-card selection to the single card with the most free VRAM; a second GPU sat idle. This adds generic multi-GPU support for diffusion and video at component and denoiser-call boundaries. It needs no NCCL, and model forwards are untouched.

New module studio/backend/core/inference/diffusion_multigpu.py; begin_load passes every selected card to the load (image and video), and the existing most-free-VRAM pick stays the primary. With one card selected nothing changes.

  • Device probe: card name (cached per process) and free memory. A card this process cannot address, or of a lower compute capability than the primary, takes no component.
  • Component split: the planner moves the companions (text encoders and VAE, or the text encoders alone) to a second card only when that keeps the DiT resident on the primary and the companions fit, using the same reserve rules as the one-card planner. If placement fails it falls back to the one-card plan.
  • Second denoiser: a two-expert model (Wan A14B transformer_2) can keep one expert per card.
  • CFG-parallel: when guidance runs separate cond / uncond denoiser calls on the same latent and both cards can hold the DiT, every odd branch runs on a replica on the second card from its own worker thread. The next step's odd branch is launched ahead and accepted only if the real call passes identical tensors (otherwise it is recomputed). The replica copies weights card to card, re-applies the recorded torch.compile settings, drops offload machinery, and is rebuilt if weights, LoRA or adapter scales change. It does not arm for U-Nets (they batch both branches), two-expert models, whole-model offload, step-cache hooks, or guidance-distilled models.
  • Kill switches: UNSLOTH_DIFFUSION_MULTIGPU=0 and UNSLOTH_DIFFUSION_CFG_PARALLEL=0 (force on either forces it on for testing). status()["multi_gpu"] reports the placement, replica call counts and why CFG-parallel declined.

Automatic GPU placement (#8235)

The GPU picker sends no gpu_ids on Automatic, which is the default and the only multi-card choice the UI offers, so on its own the layer above never engaged for a Studio user. An unpicked load now hands every parent-visible CUDA card to it, with the automatically ranked card (or the current one) as the primary:

  • Only the companion split runs, and only when the one-card plan would offload to system RAM. A plan that already fits one card is unchanged.
  • CFG-parallel stays opt-in (a multi-card gpu_ids pick, or UNSLOTH_DIFFUSION_CFG_PARALLEL=force), since a replica takes a whole denoiser's worth of another card.
  • Other cards are sized from nvidia-smi rows (same trust rules as automatic ranking), so no CUDA context opens on a card that gets no component. nn.Module.compile is left unpatched.
  • One GPU, ROCm, XPU, MPS and CPU fail the existing ranking gate and keep the old path; UNSLOTH_DIFFUSION_MULTIGPU=0 turns it off.
  • With Keep multiple models loaded on (fit / always), every image or video load stays on one card, picked or automatic, since the residency arbiter prices and claims one card per media load.

Kaggle T4x2, FLUX.2-klein-4B, Automatic, main vs this branch: the one-card plan offloads (group) on both and a T4 cannot hold the DiT under Studio's flat sm75 activation reserve, so the split correctly declines. Warm arms are bit-identical to main (same image hash, 2687 MiB on card 0 after load, 3 MiB on card 1, so no context on the second card). On cards where the DiT fits one card (the 2 x 24 GB case in #8235), the planner tests show the text encoders and VAE moving to the second card instead of offloading.

Fixes #8235

Results

Kaggle T4x2 (two real 15 GB T4s on PCIe, no peer access), FLUX.2-klein-base-4B, 1024x1024, 12 steps, CFG 4, ABBA order:

Arm s/step s/image Card 0 peak alloc, util Card 1 peak alloc, util
main, 1 card 4.72, 4.84 58.2, 58.9 10103 MiB, 95% idle
this PR, 2 cards 2.65, 2.68 34.9, 34.6 10103 MiB, 81% 8011 MiB, 83%
this PR, kill switch 4.78 58.6 10103 MiB, 95% idle

1.78x per step and 1.68x end to end. All images are bit-identical across every arm. 36 of 39 predicted branches hit; the 3 misses are the first step of each new image.

On 2x B200 (shared cards, correctness only): Wan2.2-TI2V-5B at 832x480x25 and 1280x704x49 is bit-identical across one card (resident and offloaded), CFG-parallel, the kill switch, and a run where the text encoder moved to the second card on its own. A tiny Qwen-Image pipeline with forced split plus CFG-parallel is bit-identical to one card.

2x B200 through Studio's own backend, exclusive cards, eager, FLUX.2-klein-base-4B, 12 steps, CFG 4, 2 prompts, 3 repeats, ABBA (the host CPU was heavily loaded, so the 1024 timings are indicative):

Arm 1024 s/step 2048 s/step 2048 s/image Card 1 peak Images
main, 1 card 0.101 0.453 5.87 0 reference
this PR, CFG-parallel 0.102 to 0.128 0.232 3.65 8021 MiB (1024) / 9559 MiB (2048) bit-identical
this PR, UNSLOTH_DIFFUSION_CFG_PARALLEL=0 / UNSLOTH_DIFFUSION_MULTIGPU=0 0.110 / 0.103 0.453 5.86 0 bit-identical

1.96x per step and 1.61x per image at 2048; no gain at 1024 on this host. The replica ran 77 of 84 steps (the first step of each image runs on the primary) with 71 predicted hits and 0 misses. With each card held at 43.7 GiB free, main offloads (group) while this PR keeps the DiT resident and puts the text encoder and VAE on card 1, on a two-card pick and on Automatic, with identical images. When one card fits, Automatic is identical to main and opens no context on card 1 (0 MiB). Wan2.2-TI2V-5B at 832x480x25 writes byte-identical mp4 files on one card, two cards and both kill switches.

One card, base vs head (FLUX.2-klein-4B, FLUX.2-klein-base-4B at CFG 4, FLUX.3 klein FP8, Wan2.2-TI2V-5B): bit-identical images with deterministic settings, byte-equal peak allocated memory, s/step within the A/A band, multi_gpu null, and no device probe or nvidia-smi read. Spoofed device probes (21 cells x 4 picks x image and video, 168 comparisons): 136 identical, 32 widened (two or more cards), 0 narrowed.

Tests

  • CPU-only tests in test_diffusion_multigpu.py, test_diffusion_multigpu_wiring.py and test_video_multigpu_wiring.py (107), including a run against real diffusers group offloading. Reverting any one of the 26 functional hunks fails at least one of them.
  • Existing suites that touch the changed code: the only other failures (test_diffusion_offload_keep_cpu.py GGUF cases and two test_training_offload_layers.py cases) fail identically on main.

Not covered: a T4 time saving from the component split (on sm75 Studio reserves a flat activation estimate, so even klein's DiT alone does not fit a T4 and the planner correctly stayed on one card); the two-expert placement on hardware; idle-host timings; compiled-mode CFG-parallel equality with compiled single card; pipelines that pass cache objects with tensors inside, or edit embeds in place between branches; ROCm and Windows runs; LTX two-stage.

Text encoders and VAE move to a second card when that keeps the denoiser resident on
the first, a two-expert denoiser can keep one expert per card, and guidance branches
run on a denoiser replica on the second card (CFG-parallel). Placement happens at the
component and denoiser-call boundaries, needs no NCCL, and falls back to one card.
UNSLOTH_DIFFUSION_MULTIGPU=0 and UNSLOTH_DIFFUSION_CFG_PARALLEL=0 turn it off.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 14, 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-20T12:51:17.019893Z f5f58af New commits
🔒 Security Review ⚠️ Failed 2026-10-14T13:17:59.911166Z 29b74c8 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 3 commits October 14, 2026 13:38
…ails

A failed split fell back to whole-module offload unconditionally, which a torchao
denoiser cannot take. The split plan now carries the plan one card would have used
and applies it on the primary.
A hook function is shared by the source denoiser and its replica, so a captured
list, dict, set, tensor or object is state both branches mutate concurrently. Only
immutable captures are accepted now.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 6 commits October 14, 2026 14:27
…lel replica

A step cache installed on the source at generate time left the replica running
uncached for the odd branches. The per-step staleness check now also declines
when the source gained hooks a replica cannot share.
…d plan after load

The post-load fit can use the tiled decode headroom, so clearing VAE tiling could
let an untiled decode exceed what either card was budgeted for.
…ride of its source

The router took the root forward slot, so the copy fell back to the class forward
while the primary branch kept a bound override. The override is now rebound to the
replica (offload wrappers are peeled off), and anything else declines.
…ting the result

A tensor edited in place after the prediction was launched kept its identity, so
the stale replica output was accepted. The launch-time copies are now compared
with the sources at the real call (one sync); any difference recomputes the branch.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 4 commits October 14, 2026 15:56
…a per call

Root hooks run only on the source and can write per-call state onto its submodules
(the HunyuanVideo-1.5 null-mask flag). That _unsloth_* scalar state is now copied to
the replica before each replica call, and a predicted branch is accepted only when
the source state for the real call matches what the replica saw.
A split reports offload policy none while its fit priced only the base pipeline, so a
ControlNet added at generate time loaded whole onto the primary. It now streams as it
would under the single-card offload plan.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… the VAE's card for untiled decode

A two-expert video split now charges the denoise activations on each card
that runs an expert, apart from any decode on the same card. The untiled
VAE decode reads free memory on the card the VAE lives on when a split put
it on another CUDA card; one card and an offloaded VAE keep the latent's.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 5cac0540c7

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

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 22b82045c6

ℹ️ 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 and others added 4 commits October 20, 2026 01:19
…d probes

- _tile_for_verdict / _guard_vae_card undid the VAE tiling on any
  exception before re-raising, so generate()'s fail-open branch then
  rendered untiled where the guard said only a tiled decode fits. A
  refusal still undoes it; a broken probe now logs and keeps the tiling,
  as generate() did before the helpers.
- The host-to-card and card-to-card bandwidth and peer-access probes
  were measured (64 MiB pinned plus 64 MiB per card) and never read:
  probe_devices now reports name and memory only. The uncalled
  as_public_dict helpers and the probe cache reset go too.
- make_selection skips the capability probe when there is no second card.
- The test helper skips only when diffusers cannot be imported, not on a
  missing symbol.
- The multi_gpu status field documents the declined entry of a
  multi-card load that stayed on one card.
Drive the real begin_load, load_pipeline, generate and status of the image
and video backends on the fake runtimes and check that they reach the
multi-GPU layer: the picked cards reach the load thread through
with_load_selection, a load refines its plan and arms CFG-parallel, a split
video load records its per-card floors and passes the sidecar check,
generate takes the VAE-card tile decision and ends the CFG render, and
status carries multi_gpu. Also pin that a failed deferred profile drops the
CFG replica and that the untiled video decode sizes the VAE's card.
…e card

- make_selection drops cards this process's torch cannot address:
  nvidia-smi can list a card a later mask hides, which then became a
  secondary that every later check had to decline.
- _split_home returns at once until this process has placed a split, so
  a one-card generate no longer walks the pipeline's components on every
  guarded render. Two tests that set the split marker by hand now say so
  instead of relying on an earlier test having placed one.

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 819fa28235

ℹ️ 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 and others added 3 commits October 20, 2026 01:56
…estore what the router and boundaries replaced

- the replica fingerprint covers registered buffers (packed NVFP4 weights and scales) and PEFT's _active_adapter
- the replica shares the source's NVFP4 step controller, so both branches of a step run the same GEMM
- a root hook from outside Studio declines the replica (its per-call state cannot be mirrored)
- an unpredicted replica call copies its inputs after the primary branch instead of reusing the prefetch
- the replica's compiled blocks get their own compile guard and the block-0 restride, like the source's
- the router runs on the source during a forced-eager render and on the background compile thread
- an uninstalled router left inside a wrapper is a passthrough; removal restores instance forward overrides
- unload uninstalls the router; begin_load resolves several cards only when multi-GPU is on

[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. More of your lovely PRs please.

Reviewed commit: 17edc218dd

ℹ️ 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 811c08e into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-multigpu branch October 20, 2026 13:55
danielhanchen added a commit that referenced this pull request Oct 20, 2026
…st memory (#13787)

When the denoiser does not fit the card and streams from host memory,
every guided step uploads the weights twice: once for the conditional
branch and once for the unconditional one. This PR runs both branches as
one doubled forward, so the weights upload once per step.

This replaces the earlier version of this PR. The CFG-parallel link
pricing and device probing are withdrawn: multi-GPU placement is in
#13725 (merged), and this PR is only the single-card batching, in its
own module.

## What it does

- `core/inference/diffusion_cfg_batch.py`, installed next to
`install_cfg_parallel` and released at the end of each render next to
`end_cfg_render` (5 lines each in `diffusion.py` and `video.py`).
`status()["cfg_batch"]` reports whether it is armed, why it declined,
and the batched / hit / miss counts.
- Own switch, independent of multi-GPU:
`UNSLOTH_DIFFUSION_CFG_BATCH=0|auto|force`. `0` keeps the exact two-call
path. `UNSLOTH_DIFFUSION_MULTIGPU=0` no longer turns batching off.
- `auto` arms only for a denoiser Studio streams from host memory (group
/ streaming / model offload), for FLUX.1, FLUX.2, Qwen-Image and
single-expert Wan. `force` also batches a resident denoiser and unlisted
classes, as ComfyUI does.
- Step 1 warms up, step 2 times a plain pair, and from step 3 the
branches run as one call when the timed batched pair (merge, forward,
split and verification included) beats the plain pair for that request
shape. There is no device or link probing, so no CUDA context opens on
another card.
- The second branch's inputs are checked bitwise against what was
batched. A mismatch reruns that branch plain, and 3 misses in a row turn
batching off for that shape. A third call in one step turns it off for
the load.
- Declined when it cannot be exact by construction or would fight
another layer: per-call activation scaling (ComfyUI's dynamic NVFP4,
torchao `NVFP4Tensor`), armed CUDA graphs, an installed step cache, a
denoiser compiled whole, two experts. A displaced router passes calls
through, and install never fails a load.

## Fixes over the earlier version

- Qwen-Image never batched: its `img_shapes` list was refused, and so
were unequal positive / negative prompt lengths. The list is joined per
sample (which `zero_cond_t` also needs) and the shorter prompt is padded
with masked zeros.
- Z-Image was listed although its pipeline already batches CFG; removed.
- Timing synchronised the current device instead of the latent's card.
- The profitability timer started after the merge and stopped before
verification; it now times the whole pair.
- Request-path work ran on every render even with everything off; with
nothing armed it is one weak-dict lookup.
- When guidance ends mid-render, at most one doubled call is wasted.

## Results

FLUX.2-klein-base-4B, 1024x1024, 12 steps, guidance 4, one B200 with
memory capped so the DiT streams (`streaming` offload), multi-GPU off in
every arm, exclusive card, 2 prompts x 2 repeats per arm:

| Arm | s/step (median per render) | s/image | Images |
|---|---|---|---|
| base (#13725 head) | 0.286 - 0.291 | 3.65 - 4.23 | reference |
| `UNSLOTH_DIFFUSION_CFG_BATCH=0` | 0.286 - 0.287 | 3.53 - 3.74 |
identical hashes |
| batching on (two runs) | 0.149 - 0.154 | 2.07 - 2.30 | identical
hashes |

1.88x per step and about 1.7x per image. All 54 batched steps hit, 0
misses. Torch peak memory rose by about 200 MiB (2647 to 2859 MiB).

The images were bit-identical in this run, but batching changes the
batch size the kernels see, so other models or cards can pick different
kernels: an earlier A100 run of the previous version measured LPIPS
0.0087. Treat `auto` as a tolerance mode and `0` as the exact path.

## Testing

- `tests/test_diffusion_cfg_batch.py`: 11 tests (Qwen-Image unequal
prompt lengths and `img_shapes`, per-sample list joins, declines, the
switch being independent of multi-GPU, device sync on the latent's card,
guidance ending mid-render).
- With the multi-GPU, wiring, video wiring and memory suites: 278
passed, 6 skipped.

Not verified: video (Wan 2.1) on GPU, consumer PCIe cards, ROCm, macOS
and Windows.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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 21, 2026
)

## Summary

Studio can now split one diffusion denoiser across several GPUs by block
ranges when it does not fit on any single selected card. Until now a
denoiser that was too big for one card fell back to host RAM offload,
even with a second card sitting idle. With this PR the blocks are cut
into contiguous ranges, one range per card, and the activations hop
across the card boundaries. The output is bit-identical to one card in
eager mode, and the split keeps the speed paths: regional compile,
per-card CUDA graphs, the step cache and the int8 kernels.

This builds on the multi-GPU placement from #13725 (component placement
and CFG-parallel), which is already in main.

## What it does

- `diffusion_layer_split_plan.py` is the planner. It prices every
selected card from its free memory, the block working set and the
per-card reserve, keeps at least one block on the primary, cuts two
denoisers (Wan 2.x A14B) jointly when only some pair of cuts fits, and
picks where the text encoders go (a card that has room, else streamed
from host RAM, since they run once per prompt and the denoiser runs
every step). When nothing fits it records why, and the status shows that
reason.
- `diffusion_layer_split.py` is the engine. It moves each block to its
card, swaps the block class for a same-named subclass whose `__call__`
moves the inputs to the block's card, and routes the outputs. Families
whose forward passes one block's output straight to the next block route
lazily (one copy per card boundary): FLUX.1/2/3, Qwen-Image / 2.1,
Z-Image, HunyuanImage, HiDream, Wan, LTX-2, HunyuanVideo-1.5, Krea2,
Lumina2, MiniMax-H3 and Ideogram4. Others, and any call with a residual
input such as ControlNet or VACE hints, run eager (outputs come back to
the primary after every block). Unload undoes the split.
- Speed paths on a split:
- The speed layer, the compile cache key and the int8 kernels are set up
for the split placement, not for the one-card offload plan the split
replaces. Before, a split denoiser compiled without `fullgraph` and kept
the int8 GEMM in its streaming mode.
- Regional compile follows main's `PROMPT_LENGTH_POLICY`. Qwen-Image
also arms its prompt-length sources on the default tier, so a new prompt
length does not recompile.
- Per-card CUDA block graphs, and per-card segment graphs (a run of
blocks on one card recorded as one graph, only on a lazily routed
forward, breaking if a handed-on tensor was rewritten in place). Block
and segment graphs key on the root's branch flag
(`_unsloth_graph_key_extra`), as the whole-step graph does. For a family
whose text length follows the prompt, they record only the first
render's prompt lengths per image scope (main's sealing for the
whole-step graph, applied per card). A later new length runs compiled
without graphs.
- The First-Block-Cache goes back on after placement. Its residuals are
copied between the head and tail cards, around main's FLUX.2
mixed-stream tail.
- The int8 GEMM, the fused int8 / QKV records and the Qwen-Image /
Qwen-Image-2.1 / Z-Image fused RoPE paths run per card. Each block uses
its own card's kernels and probes
(`diffusion_int8_gemm.after_layer_split`).
- A quantized DiT on a split is compiled. When the one-card plan
offloads, Studio picks the torchao-free int8 scheme (W8A8
`torch._int_mm`), and the rule that forces compile for a quantized DiT
skipped that scheme, so a split that kept it resident ran eager. Both
backends now compile it once the DiT stays resident: on one card, on a
layer split, or on a companion split that keeps it whole on the primary.
ROCm and Apple keep their own native path.
- Video gets the same treatment: the same split-aware speed setup, the
step cache back after placement, and the per-card int8 binding. When a
split it expected falls back to the one-card offload plan at placement,
the compile moves below the offload hooks, as on the image backend (a
full-graph block compile over group offload hooks fails to trace and
drops the whole DiT to eager).
- The generate-time check on a card that holds only blocks scales that
card's working set with the request size and charges its fixed reserve
once, so a large render is not refused on a card where it fits.

## How the auto planner picks a placement

For each load, in this order:

1. **One card.** The denoiser and its companions fit the primary card:
nothing changes from today.
2. **Companion split** (#13725). The denoiser fits the primary once the
text encoders and/or the VAE move to a second card: they move, and the
denoiser stays whole on the primary.
3. **Layer split** (this PR). Nothing fits on one card, but the denoiser
blocks fit across the selected cards. Fewest cards first: the primary,
then the secondaries from largest to smallest.
4. **Offload.** Nothing fits: the one-card offload plan stays as it is
today, and the status says why the split declined.

A layer split is CUDA only (ROCm declines with a reason), needs a
denoiser with a sequential block list the engine can cut, and is skipped
for explicit offload memory modes and unified memory. CFG-parallel does
not arm on a split denoiser.

## Kill switches

| Variable | Effect |
| --- | --- |
| `UNSLOTH_DIFFUSION_MULTIGPU=0` | every multi-GPU placement off
(companion split, layer split, CFG-parallel) |
| `UNSLOTH_DIFFUSION_LAYER_SPLIT=0` | layer split off; `force` splits
even a denoiser that fits one card |
| `UNSLOTH_DIFFUSION_SEGMENT_GRAPHS=0` | per-card segment graphs off
(per-block graphs stay) |
| `UNSLOTH_DIFFUSION_BLOCK_GRAPHS=0` | per-block CUDA graphs off |
| `UNSLOTH_DIFFUSION_CFG_PARALLEL=0` | CFG-parallel off |

## Results

All numbers are on a B200 pair. Image runs use 1024x1024, 8 steps and
guidance 4. LTX-2 uses 768x512, 33 frames and 8 steps. "One card" means
`UNSLOTH_DIFFUSION_MULTIGPU=0`. "Split" means
`UNSLOTH_DIFFUSION_LAYER_SPLIT=force` across two cards, except the last
table, where the planner chose the split itself. Image timings ran on
exclusive cards. The LTX-2 timings ran on shared cards, so treat those
as rough.

**Eager (speed off): the split is bit-identical to one card**

| Model | One card s/step | Split s/step | Image hashes, 2 prompts x 2
repeats |
| --- | --- | --- | --- |
| FLUX.2-dev bf16 | 0.313 | 0.304 | identical (`1e7585a4`, `6976052b`) |
| Qwen-Image bf16 | 0.219 | 0.219 | identical (`2cfafe27`, `325b36eb`) |
| LTX-2 (shared cards) | 0.86 to 0.90 | 0.64 to 0.69 | identical
(`ea1c175a`, `1c355af5`) |

**Compiled (speed default)**

| Model | One card s/step | Split s/step | Graphs on the split |
| --- | --- | --- | --- |
| FLUX.2-dev bf16 | 0.221 | 0.203 | 3 per-card segment graphs per step |
| Qwen-Image bf16 | 0.145 | 0.132 | 2 per-card segment graphs per
forward |
| LTX-2 (shared cards) | 0.36 to 0.59 | 0.29 to 0.30 | none (video
families do not record graphs) |

On LTX-2 the compiled split is also bit-identical to the compiled
single-card run (`399f4a65`, `7e445ae0`, `ed4e8d71`).

**Prompts of different lengths, new seed each, no separate warm-up**

| Model | Split: setup on generations 2 and 3 | One card: setup on
generations 2 and 3 |
| --- | --- | --- |
| FLUX.2-dev | 0 recompiles, 0 graph captures | 0 recompiles, 0 graph
captures |
| LTX-2 | 0 recompiles, 0 graph captures | 0 recompiles, 0 graph
captures |
| Qwen-Image | 0 recompiles, 0 graph captures (new lengths run
ungraphed: 0.134 vs 0.131 s/step) | 0 recompiles, 0 graph captures
(main's sealing) |

FLUX.2 pads the prompt to 512 tokens. Qwen-Image does not pad it, so its
graphs record only the first render's lengths. A length recorded there
replays later (generation 4 above), and a new one runs compiled without
graphs, on one card and on the split alike.

**Quantized DiT on a planner-chosen split** (LTX-2, int8, both cards
capped to 44 GiB free, shared cards, speed left at off)

| Build | Speed engaged | s/step |
| --- | --- | --- |
| main + split, before the compile fix | off (eager) | 0.89 / 1.23 |
| this PR | default (forced, like torchao int8) | 0.33 / 0.33 |
| this PR, speed default, prompts of 5 / 26 / 69 words | default | 0.32
/ 0.31 / 0.35, 0 compiles and 0 captures on generations 2 and 3 |
| one card, torchao int8, speed default (reference) | default | 0.26 /
0.26 / 0.25 |

**Compiled runs are reproducible across processes, and the compiled
split matches compiled one card**

Exclusive B200 pair, speed default (compiled), every row a fresh process
with no compile cache, 2 prompts:

| Model | One card, process 1 / 2 | Split, process 1 / 2 | s/step one
card / split |
| --- | --- | --- | --- |
| Qwen-Image | `0408ab61`, `aa0de448` / same | `0408ab61`, `aa0de448` /
same | 0.143 / 0.130 |
| FLUX.2-dev | `1c50b74e`, `0d8f3a55` / same | `1c50b74e`, `0d8f3a55` /
same | 0.224 / 0.202 |

Two sources of per-process variation had to go, and neither came from
the split. A split compiles its blocks once per card, so it made them
easy to see:

- **Qwen-Image:** inductor benchmarks near-tied norm-reduction configs
in each process, and they sum in different orders. Before this PR, four
fresh one-card processes rendered four different images, 42 / 26 dB
apart (the same gap seen between two split processes). Studio already
pins these reductions for Qwen-Image on A100 / L4 / RTX PRO 6000; this
PR adds B200 for Qwen-Image and its edit / layered siblings.
- **FLUX.2-dev:** `cudnn.benchmark` picks the VAE conv algorithm per
process. Seven fresh processes on shared cards rendered five variants of
one seed, on one card and on the split alike, 58 to 59 dB apart.
FLUX.2-dev now keeps `cudnn.benchmark` off, like FLUX.1, Qwen-Image,
Z-Image and SDXL already do. That costs about 0.01 s per 1024x1024 image
(1.83 vs 1.82 s).

**Planner-chosen split**

FLUX.2-dev bf16 at speed default, with both cards capped to about 70 GiB
free so that one card would need `group` offload. The planner picked the
split ("transformer cut over 2 cards ... single card would use
'group'"). The run compiled and recorded per-card graphs, ran at 0.205
s/step, and showed no recompile or capture on generations 2 to 4. It
also loaded the same compile cache bundle as the single-card resident
compile. Before this PR, the planner-chosen split compiled under the
one-card offload plan's settings and used a different bundle.

## Tests

- CPU unit suites (layer split, split speed paths, load order,
prompt-length policy, dynamic text, multi-GPU, memory, measured
placement, CUDA / block graphs, step cache, compile config / cache /
regional compile, int8 GEMM / fused, native quant, Qwen-Image /
Qwen-Image-2.1 / Z-Image fused paths, image and video backends): 2830
passed. The one failure
(`test_unpinned_torchao_host_copy_is_a_distinct_wrapper_over_the_same_data`)
fails the same way on main.
- Every diffusion / video / offload / multi-GPU test file on CPU, main
vs this branch: no new failing test IDs. The failures on main (LM Studio
diffusion chat, training offload layers, three VAE tiling files that
time out under load) fail the same way here.
- On two real CUDA cards: `test_diffusion_layer_split_cuda.py` and
`test_diffusion_multigpu_cuda.py`, 3 passed.

## Not covered

- PCIe consumer cards. Every run here was on B200s, where the boundary
copies are cheap.
- ROCm, which declines the split with a reason, and Windows / macOS /
MLX, which have no split.
- More than two cards, on real models.
- Wan 2.x A14B (two experts), HunyuanImage, HiDream, Z-Image, FLUX.1 and
FLUX.3 were not re-run on this branch at full size. The HunyuanImage
lazy routing was measured on an earlier build of the split: identical
images, 0.163 vs 0.18 to 0.19 s/step eager. HiDream routing lazily is
checked on a tiny random HiDream split over two real cards with several
blocks per stream per card: bitwise equal to one card, one hop per card
boundary, and one segment graph per card per stream
(`tests/test_diffusion_layer_split_cuda.py`).
- Families that keep `cudnn.benchmark` on (FLUX.1-Kontext, FLUX.2-klein,
FLUX.3, HiDream, HunyuanImage-2.1, Ideogram-4, Krea-2, Lumina-2,
MiniMax-H3, Qwen-Image-2.1, Qwen-Image-Edit / Layered) were not checked
for per-process VAE variants. Neither were FLUX.1 and Z-Image for the
B200 reduction race.
- The torchao int8 split paths (per-card int8 GEMM, fused records, the
Qwen-Image-2.1 / Z-Image fused paths) and the First-Block-Cache across
cards are covered by CPU tests only here, with no real-model run on this
branch. The int8 run above uses the torchao-free scheme, which needs no
per-card swap. The auto-int8 load time on a split was not re-measured.
- On the image backend the text encoders are quantized after the speed
layer, so a companion split that fits only once they are quantized is
not previewed, and a torchao-free int8 DiT placed that way still runs
eager unless speed is on.
- The torchao-free int8 split (0.33 s/step) is still slower than a
resident torchao int8 build on one card (0.26 s/step).

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codex-converged# new-feature# security# Moves a security boundary: sandbox, allowlist, permission or network guard >3000#

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Studio: diffusion budgets against one GPU, so a multi-GPU host offloads to RAM instead of using the second card

1 participant