Skip to content

Studio diffusion: Automatic partner card, FLUX batch split, LoRA scale mirror, CFG batching fallback - #16682

Merged
danielhanchen merged 27 commits into
mainfrom
mg3-auto-multigpu-policy
Nov 5, 2026
Merged

danielhanchen merged 27 commits into
mainfrom
mg3-auto-multigpu-policy

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

The last pieces of automatic multi-GPU placement: which card to pair on any card count, using the second card for batches of distilled models, and keeping the second-card copy alive across LoRA weight changes and failures.

Change

  • automatic_partner: a pure decision over the card list. The partner must be the same card model, at most 1 GiB used and 5% busy, and the copy must fit; ties go to the most free memory, then a P2P link, then the lowest ordinal. One partner per load on 2-8 cards (a step has at most two guidance branches and a batch splits in two, so a third copy would have no work). A mixed pair (different card models) is never paired automatically.
  • FLUX.1 / FLUX.2 batch split: an even batch (batch size x runs) runs half on each card. Odd batches, unknown inputs and whole-compiled modules stay whole. Kill switch UNSLOTH_DIFFUSION_BATCH_SPLIT=0.
  • A LoRA weight-only change mirrors the adapter scales onto the replica instead of dropping it (a changed adapter set still rebuilds).
  • A replica that fails at render time finishes that render on one card, then hands over to CFG batching from the next render, once, never mid-render.
  • 22 tests.

Evidence

  • SDXL batch 2: 55.83 -> 27.97 s (2.0x).
  • FLUX.2-klein-4B batch 2 with the copy: 22.61 -> 12.74-13.40 s (1.69-1.77x), LPIPS 0.0007.
  • LoRA weight change: the replica is kept (3 rebuilds instead of 4 over the test sequence), every render bitwise against one card and a fresh load, 0 recompiles.

Stack

This is one of four stacked PRs that make every decision to use a second GPU automatic, merged in order:

  1. U-Net CFG-parallel (SDXL)
  2. Automatic arms CFG-parallel on an idle card of the same model
  3. CFG-parallel for a group-offloaded denoiser
  4. Automatic partner card, FLUX batch split, LoRA scale mirror, CFG batching fallback

Results for the whole stack, Kaggle 2x T4, same VM per row, base A/A first:

model one card s Automatic s speedup output vs one card
SDXL 1024, CFG 7 23.13 13.18 1.75x LPIPS 0.003, >= 39.97 dB (kill switch bitwise)
SDXL, compiled 20.12-20.16 11.06-11.29 1.79x LPIPS 0.0040 (one-card A/A 0.0043)
SDXL, batch 2 55.83 27.97 2.00x LPIPS 0.0042
Qwen-Image-2.1, CFG 4 256-280 164-165 1.63x bitwise
Wan2.2-TI2V-5B, CFG 5, per clip 211.10 144.49 1.46x LPIPS 0.0025 (kill switch bitwise)
FLUX.2-klein-4B, batch 2 22.61 12.74-13.40 1.69-1.77x LPIPS 0.0007
  • 0 graph breaks and 0 recompiles or CUDA-graph captures on every follow-up render. The first compiled image is 25-30 s slower on two cards, paid once per load while the second card compiles its copy.
  • AMD gfx1151 (Linux, one real GPU plus a faked second device) and Windows 11 CPU: no regressions (same failures on base and head). No change touches a Triton / CUDA kernel.
  • Not covered: no run on more than 2 cards (the 3-8 card rule is unit-tested only); NVLink pairs; a Windows GPU run.

A U-Net pipeline sends both guidance branches through one call at batch 2B, so
CFG-parallel declined it ('no DiT denoiser') and the second card stayed idle.
UnetCfgParallelRouter cuts that call in half along the batch, runs the second
half on the replica card through run_pair, and concatenates. Odd batches,
unknown tensor inputs and replica failures stay on the source card.
UNSLOTH_DIFFUSION_CFG_PARALLEL_UNET=0 turns it off.
The primary half goes through _primary_noting (waits on a cold replica, marks its
signature warm); a module compiled whole after the router was installed, or a call
under torch.compile, runs whole on the source; PAG-style processors that chunk the
batch themselves keep the U-Net off the router.
…same model

With no gpu_ids (the UI's Automatic) CFG-parallel always declined, so a guided
render on a two-card box left the second card idle unless the user picked both
cards. Automatic now arms it when a secondary is the same card model and idle at
load (at most 1 GiB in use); a busy or different card is never borrowed.
UNSLOTH_DIFFUSION_CFG_PARALLEL_AUTO=0 restores the old behaviour.
Record compile arguments under Automatic too (a compiled denoiser's replica needs
them), and re-check at replica build time that the card Automatic borrowed is
still idle.
…tner per load, utilisation-aware) and batch split for distilled FLUX denoisers
…ks already wrap it) and records why a batch did not split
… change (mirror the scales) and fall back to CFG batching after a render-time replica failure
…eights sit in host memory

cfg_parallel_decline read the denoiser's first parameter device, so a group-offloaded
DiT whose first group lives in host memory between calls (Wan2.2-TI2V-5B on a 15 GiB
card) was refused as 'not on a CUDA card' while one whose first group stayed resident
(Qwen-Image-2.1) armed. The execution device now falls back to the offload groups'
onload card: the primary branch keeps streaming, the replica runs resident on the
second card.
An automatic load on the current card onloads its offload groups to bare 'cuda'
(no index), so the CFG-parallel replica search found no card model to compare
and declined every secondary as 'a different model'.
@danielhanchen danielhanchen self-assigned this Nov 4, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 4, 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-11-04T23:25:51.894609Z 2f3acd7 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. Breezy!

Reviewed commit: 4b29ab0444

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

…utilisation too

A card under 1 GiB of memory but computing for another process passed the
memory-only recheck; the 5% utilisation limit the selection applies now holds
at build time as well.

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…build

The replica is built lazily during generation, after the load's selection
scope ended, so the scoped reader answered None and a busy card passed.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… after a LoRA scale mirror

A batch split gives each half its own activation amax under per-call NVFP4 scaling, so it is
refused like CFG batching. Mirrored Python-valued scales guard compiled regions: the warm sets
are cleared so the next calls compile one side at a time.

[skip ci]
danielhanchen added a commit that referenced this pull request Nov 4, 2026
# Conflicts:
#	studio/backend/tests/test_diffusion_auto_multigpu_policy.py

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: ffd3c28267

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

…orchao check

peft caches is_torchao_available() per process, so a True left by an earlier LoRA test on the
same xdist worker sent its torchao dispatcher into the blocked import (Backend CI a-f).
[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…stead of capturing it

The router is the value of a weak-keyed map on the pipeline, so a fallback partial holding the
pipeline kept a load rolled back before publication alive. Image and video loads alike.

[skip ci]
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 4, 2026
@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: 8af43e1e3b

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

Comment on lines +3526 to +3527
if pick is not None:
candidates = [pick]

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 Exclude occupied cards before choosing the automatic partner

On a system with at least three matching GPUs, if the idle card with the most free memory already holds a split pipeline component, narrowing candidates to [pick] causes the subsequent occupied filter to remove the sole candidate. CFG-parallel is then declined even when another idle, unoccupied card can hold the replica. For example, with a small text encoder on cuda:1 and slightly less free memory on an otherwise eligible cuda:2, installation incorrectly reports that the only replica card holds split components. Previously, the occupied-card filter retained cuda:2. Filter occupied cards before calling automatic_partner, or retry selection among the remaining eligible cards.

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.

Fixed in 2f3acd7: the occupied set is computed first and cards holding the split's components are left out of the list automatic_partner chooses from, so the next idle card takes the replica (test_automatic_partner_skips_a_card_holding_the_splits_components, your three-card case; fails on the previous head).

… Automatic picks the partner

With three or more cards, the idlest card could hold a split component; narrowing to it first
left no candidate although another idle card could take the replica.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 2f3acd7dfa

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

Base automatically changed from mg3-cfg-parallel-streamed-primary to main November 5, 2026 03:27
@danielhanchen
danielhanchen merged commit 4a86327 into main Nov 5, 2026
@danielhanchen
danielhanchen deleted the mg3-auto-multigpu-policy branch November 5, 2026 03:27
danielhanchen added a commit that referenced this pull request Nov 5, 2026
…over a layer split for FLUX when the primary holds the whole denoiser (#16687)

## Summary

For FLUX.1 / FLUX.2 on two cards, Automatic used the layer split even
when the main card can hold the whole denoiser. The split runs at the
speed of whichever card holds most of the blocks, and it blocks the
second-card copy, so an even batch could not use the batch split from
#16682.

## Change

- `layer_split_or_plan` (Automatic only; explicit splits are unchanged):
for FLUX.1 / FLUX.2, when the primary card holds the whole denoiser
resident (nothing streams) and an idle same-model partner can hold a
copy, keep one card plus the copy instead of the layer split. The copy
serves only even batches and guided steps; placement never changes per
request.
- When any of the denoiser would stream from host memory on the primary,
the layer split stays exactly as on main, so single images are never
slower than main.
- Every other family keeps main's placement.

## Evidence

Kaggle 2x T4, same VM per row, outputs bit-identical to one card:

| case | one card s | main Automatic s | this PR, Automatic s |
placement |
|---|---|---|---|---|
| FLUX.2-klein-4B, batch 2 | 23.12 | (layer split) | **12.66** (1.83x) |
one card + copy |
| FLUX.2-klein-4B, 1 image | 11.76 | | 12.26 (renders 11.3-12.7 s on
both) | one card + copy |
| FLUX.2-klein-9B, 1 image | 25.76 | 21.74 | 21.22 | layer split, as
main |
| FLUX.2-klein-9B, batch 2 | 46.03 | 47.45 | 46.77 | layer split, as
main |
| Z-Image-Turbo 512 | 18.27 | 8.72 | 8.51 | layer split, as main (path
unchanged) |

FLUX.1-dev on a T4 streams part of its denoiser, so it keeps main's
split.

## Tests

- The multi-GPU, placement and CFG-parallel suites pass; the one failure
(`test_execution_device_reports_the_primary_of_a_split_pipeline`) fails
identically on main.
- AMD and Windows CI ran on the stack with an earlier version of this
rule (no regressions); this version adds one condition on a path that
returns early on ROCm.

## Stack

This is one of five stacked PRs that make every decision to use a second
GPU automatic, merged in order:
1. U-Net CFG-parallel (SDXL)
2. Automatic arms CFG-parallel on an idle card of the same model
3. CFG-parallel for a group-offloaded denoiser
4. Automatic partner card, FLUX batch split, LoRA scale mirror, CFG
batching fallback
5. FLUX: one card plus a copy over the layer split when the primary
holds the whole denoiser

Results for the whole stack, Kaggle 2x T4, same VM per row, base A/A
first:

| model | one card s | Automatic s | speedup | output vs one card |
|---|---|---|---|---|
| SDXL 1024, CFG 7 | 23.13 | 13.18 | 1.75x | LPIPS 0.003, >= 39.97 dB
(kill switch bitwise) |
| SDXL, compiled | 20.12-20.16 | 11.06-11.29 | 1.79x | LPIPS 0.0040
(one-card A/A 0.0043) |
| SDXL, batch 2 | 55.83 | 27.97 | 2.00x | LPIPS 0.0042 |
| Qwen-Image-2.1, CFG 4 | 256-280 | 164-165 | 1.63x | bitwise |
| Wan2.2-TI2V-5B, CFG 5, per clip | 211.10 | 144.49 | 1.46x | LPIPS
0.0025 (kill switch bitwise) |
| FLUX.2-klein-4B, batch 2 | 22.61 | 12.74-13.40 | 1.69-1.77x | LPIPS
0.0007 |

- 0 graph breaks and 0 recompiles or CUDA-graph captures on every
follow-up render. The first compiled image is 25-30 s slower on two
cards, paid once per load while the second card compiles its copy.
- AMD gfx1151 (Linux, one real GPU plus a faked second device) and
Windows 11 CPU: no regressions (same failures on base and head). No
change touches a Triton / CUDA kernel.
- Not covered: no run on more than 2 cards (the 3-8 card rule is
unit-tested only); NVLink pairs; a Windows GPU run.
oobabooga pushed a commit to oobabooga/unsloth that referenced this pull request Nov 5, 2026
…2.1x, fp-order only) (unslothai#16786)

## Summary

With two cards selected, an even batch rendered without guidance
branches (a distilled model, or guidance 1) runs half the batch on each
card at the same time (unslothai#16682, unslothai#16687). That batch split only covered
FLUX.1 and FLUX.2, because the gate checks argument shapes: every
per-sample input has to be a dim-0 tensor.

This adds `Lumina2Transformer2DModel` with its exact keyword set:
`hidden_states`, `timestep`, `encoder_hidden_states`,
`encoder_attention_mask`, `return_dict`. Any other input, including
non-empty `attention_kwargs`, keeps the call whole on the source card,
as before. The kill switch is unchanged:
`UNSLOTH_DIFFUSION_BATCH_SPLIT=0`.

Lumina 2 pads each sample's caption to the batch's longest caption under
its own mask. A half pads to its own longest caption, and the extra
positions are masked out of every attention. The math is the same, and
only floating-point order changes.

## Audit of the other DiT classes

| class | per-sample inputs | verdict |
|---|---|---|
| `Lumina2Transformer2DModel` | all dim-0 tensors (latents, timestep,
caption states, caption mask) | added |
| `QwenImageTransformer2DModel` | dim-0 tensors plus `img_shapes`, a
Python list with one entry per prompt. With `zero_cond_t` (Edit 2511) it
builds a per-sample index from that list, so a half would need the list
cut too | not added: needs list-aware splitting, and a 20B replica
cannot be timed on any pair available here |
| `HiDreamImageTransformer2DModel` | `encoder_hidden_states_llama3`
carries the batch on dim 1 (layers first) | unsafe for a dim-0 split,
not added |
| `ZImageTransformer2DModel` | per-sample lists | already has its own
split (`diffusion_zimage_cfg_split`) |
| `SD3Transformer2DModel`, `ChromaTransformer2DModel` | all dim-0
tensors, ids unbatched like FLUX | split-safe on tiny models (below),
but neither is a Studio family, so not added |

## Evidence

**Tiny random diffusers models, Studio's real `CfgParallelRouter` across
two cards** (Kaggle 2x T4, cuda:0 + cuda:1). Each model runs a 4-step
loop, compared with the same model called whole on cuda:0. Every case
engaged: 3 of 4 steps split, and step 1 learns there is one call per
step.

| class | fp32 batch 2 | fp32 batch 4 | fp16 batch 2 | fp16 batch 4 |
|---|---|---|---|---|
| Lumina2 (per-sample caption lengths differ) | max abs 2.4e-7 | bitwise
| bitwise | bitwise |
| QwenImage (audit only) | 2.4e-7 | bitwise | 2.0e-3 | bitwise |
| SD3 (audit only) | 2.4e-7 | bitwise | 9.8e-4 | 2.4e-4 |
| Chroma (audit only) | 2.4e-7 | bitwise | bitwise | 4.9e-4 |

**Real render, `Alpha-VLLM/Lumina-Image-2.0`, Kaggle T4x2** (both T4s in
one kernel). Studio was installed with its own `install.sh` (torch
2.13.0+cu130, diffusers 0.42.1). Settings: cards 0,1 selected, 768x768,
12 steps, guidance 1.0, batch 2, three prompts per arm. Studio picked
fp32 on T4, plan `group`. Every arm is a fresh process on the same head
tree. Base is `UNSLOTH_DIFFUSION_BATCH_SPLIT=0`, which is the code path
`main` takes for this class. Values are scheduler-step medians in
s/step.

| kernel | arm | prompt 1 | prompt 2 | prompt 3 |
|---|---|---|---|---|
| 1 | split off r1 / r2 / r3 | 7.854 / 8.001 / 7.973 | 7.941 / 7.980 /
8.015 | 8.532 / 8.531 / 8.532 |
| 1 | split on r1 / r2 / r3 | 4.614 / 4.630 / 4.660 | 4.408 / 4.405 /
4.427 | 4.051 / 4.056 / 4.083 |
| 2 | split off r1 / r2 | n/a | 8.463 / 8.488 | 9.116 / 9.179 |
| 2 | split on r1 / r2 | 5.078 / 5.092 | 4.820 / 4.937 | 4.321 / 4.334 |
| 3 | split off | 6.885 | 6.887 | 7.412 |
| 3 | split on | 3.970 | 3.968 | 3.768 |

(The kernel 2 notebook log lost the first prompt's line for the off
arms.)

- A/A spread inside a kernel: off 1.9% at most, on 2.4% at most.
Speed-up per prompt is 1.72x to 2.11x on every kernel, far outside that
spread.
- Engagement: the second card holds the replica (peak 10.4 GiB on cuda:1
with the split on, 0 with it off). A guidance-1 render shows no guidance
branches, and only the batch split builds that replica.
- Output: each arm is deterministic (the same image hashes on every
repeat and kernel). Split on against off, all six images: not
bit-identical, max difference 1 (of 255) per channel, at most 0.01% of
pixels differ, PSNR 91.5 to 96.8 dB. That is floating-point order, from
batch-1 against batch-2 kernels.

Tests (`tests/test_diffusion_auto_multigpu_policy.py` +
`tests/test_video_stream_residency.py`, CPU):

| tree | result | failing IDs |
|---|---|---|
| base (main + this test file) | 2 failed |
`test_lumina2_batch_splits_with_per_sample_masks_and_matches_one_card`,
`test_lumina2_attention_kwargs_and_kill_switch_stay_whole` |
| head | all passed (6 CUDA-only skips) | none |

## Not covered

- Lumina 2 with guidance runs two calls per step. CFG-parallel already
pairs those, and that path is unchanged. Only guidance-1 or
truncated-guidance steps take the new split.
- Only T4 (fp32) was timed. bf16 cards and the reference runtime were
not run.
- Automatic placement: a class in this table also counts as able to
serve every request type in the automatic layer-split vs streamed choice
(`_hidden_stream_reason`). For Lumina 2 that choice was not measured,
because on T4x2 the layer split declined on its own (it did not fit).
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