Skip to content

Studio multi-GPU: layer split fit retry, per-card graph probes, INT8 checks on every card, per-card cast-cache streams - #17790

Merged
danielhanchen merged 5 commits into
mainfrom
studio-multi-gpu-int8-fixes
Nov 15, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-multi-gpu-int8-fixes

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Multi-GPU fixes for Studio's diffusion and video paths with the INT8 attention route, found by auditing the layer split, CFG-parallel, the companion split and the per-card INT8 checks, then run end to end on Kaggle 2x T4.

  1. Layer split refused Wan2.2-TI2V-5B on 2x T4 ("short by about 1787 MiB"). The split's primary was held to 85% of its safe budget and then charged the 2 GiB overhead, the stems, the VAE and the default clip's 7839 MiB of activations, which left it no room for a single block. A one-card resident plan is priced at the full safe budget. The split is still planned at 85% first, so every placement main makes is unchanged; only after a fit decline is it retried with the primary at its full safe budget. Secondaries keep the 85% margin (measured below: it is what covers their blocks' activations at the default clip).
  2. INT8 GEMM and ConvRot latency probes captured CUDA graphs on the first card's capture stream. torch.cuda.graph keeps one default capture stream per process. A probe on cuda:1 after one on cuda:0 raised cudaErrorStreamCaptureInvalidated on 2x T4 (a bare capture there replays nothing). New card_graph(graph, index) makes the card current and records on that card's own capture stream (the same one the whole-step graphs already use); both probes go through it.
  3. INT8 attention could silently run native attention on the second card. The strided processors (FLUX.3, MiniMax-H3) were accuracy checked on the load's card only, and the op only runs the kernel on a checked card, so CFG replica or layer split blocks on cuda:1 stayed native. Separately, the deferred speed profile re-installs the attention route at the 3rd image outside the load's selection scope, so the dispatch route was rebuilt for the primary card only. Every card the DiT runs on is now checked: the selection's cards during a load, else the armed CFG router's replica card and the cards holding the DiT's weights.
  4. Cast cache reader used one side stream for every card. Under a layer split, a cuda:1 tensor was copied with a cuda:0 stream current, so the copy ran on cuda:1's default stream behind the render. One side stream per card now.

Two-card evidence (Kaggle 2x T4, Wan2.2-TI2V-5B, 832x480, 33 frames, 8 steps, same seed)

INT8 verdict per card (both runs, both cards): ok=True cos=0.99993, 4096 tokens 28.8 ms native vs 9.5 ms INT8.

Arm Tree Placement Wall s Denoise s INT8 calls cuda:0 / cuda:1 Device mismatches Non-finite Peak alloc MiB cuda:0 / cuda:1
Layer split forced main declined ("short by about 1787 MiB"), one card group offload
Single card, CFG batch off head cuda:0, group offload 62.5 34.7 482 / 0 0 no 8338 / 0
Single card, CFG batch on (default) head cuda:0, group offload 59.3 34.1 272 / 0 (batch 2) 0 no 8341 / 0
Layer split forced head blocks 0-2 on cuda:0, 3-29 on cuda:1 61.5 36.8 50 / 434 0 no 6779 / 9089
CFG-parallel head cuda:0 group offload + replica on cuda:1 53.8 28.3 272 / 212 0 no 8338 / 10244
Layer split forced, INT8 off head blocks 0-2 / 3-29 67.5 44.3 0 / 0 0 no 6778 / 9088
Single card, CFG batch off, INT8 off head cuda:0, group offload 65.9 41.0 0 / 0 0 no 8336 / 0

Same-seed output (5 of the 33 frames, every 8th, scored; the uint8 mean over all 33 frames is also equal to the last digit for every pair marked identical):

Pair LPIPS PSNR dB
layer split vs single card (CFG batch off) 0.0 identical
CFG-parallel vs single card (CFG batch off) 0.0 identical
layer split vs CFG-parallel 0.0 identical
layer split vs single card, INT8 off on both 0.0 identical
single card CFG batch on vs off (batch 2 vs batch 1 GEMMs, not multi-GPU) 0.0452 26.24
INT8 off vs on, single card (the route's own effect) 0.0553 25.44

The split and the replica are bit identical to one card running the two guidance branches one at a time. The 0.045 gap a first run showed against the default single card comes from that card batching both branches into one forward, which a split or a replica does not do.

Layer split at the family default clip (1280x704, 121 frames, 3 steps), the size the load is planned for: it ran, 18 / 162 INT8 calls, no device mismatch.

Card Planned required / limit MiB Weights MiB Peak allocated MiB Peak reserved MiB nvidia-smi used MiB (of 15360)
cuda:0 12649 / 12758 2762 8106 13360 13531
cuda:1 10675 / 12580 (first run) or 10693 (final rule, 85%) 8451 11559 12536 12691

The primary allocated 5.2 GiB above its weights against 7.7 GiB charged, so pricing it at its full safe budget holds. cuda:1 held 3.0 GiB above its weights against a 1 GiB working set plus the 1.2 GiB floor, so its 85% margin is load bearing and stays. (This render ran in a first kernel whose rule also priced cuda:1 at its full safe budget, 12580 MiB. The final rule keeps cuda:1 at 85%, 10693 MiB, and makes the same 3 / 27 cut: the second kernel ran it, and the unit test pins it from the recorded sizes.)

CUDA graph capture on the second card (graph_check.py, same process, cuda:0 then cuda:1):

main head
bare torch.cuda.graph on cuda:1 after cuda:0 replays nothing (12288, expected 28672) same (torch behaviour)
INT8 GEMM latency probe cuda:0 14370 us 14710 us
INT8 GEMM latency probe cuda:1 cudaErrorStreamCaptureInvalidated 14839 us

Studio does not capture CUDA graphs or compile the Wan denoiser on T4 (fp16 family stays eager; speed_mode=max arms graphs on 0 modules because the denoiser streams), so the probes above are the capture sites a second card reaches there.

Tests

Each fix has a CPU test that fails on main (fake two-card torch / mocked cards) and real two-card tests that skip below 2 GPUs:

  • tests/test_diffusion_auto_placement.py: Wan 5B forced split on 2x T4 with the recorded sizes; on main it declines with the same "short by about 1787 MiB" text. The Z-Image flat-estimate case now splits too; every card stays within its limit.
  • tests/test_diffusion_graph_second_card.py: both probes record on each card; card_graph makes the card current and reuses one stream per card; real two-card capture.
  • tests/test_diffusion_int8_attention_multigpu_cards.py: strided install checks every card of the selection; outside a load the CFG replica card is kept for both routes; real two-card strided check.
  • tests/test_diffusion_cast_cache_two_cards.py: one side stream per card.

Kaggle 2x T4, head: 216 passed, 2 skipped (Triton-only configs) in the first kernel and 50 passed in the second (final head), including the real two-card tests. CPU, 42 multi-GPU / layer split / INT8 attention / CUDA graph / cast cache suites: main 1721 passed, head 1727 passed, no failing IDs on either side.

Not proven

  • Speed was not a goal here: arm timings above are single runs without A/A spread, so no speed claim is made.
  • Default clip (1280x704, 121 frames) on the split: one 3-step render, peaks recorded, its frames were not checked for non-finite values.
  • speed_mode=max on 2x T4 (fused QKV adds 2.7 GiB, the split then declines, short by 686 MiB) was killed by the host OOM killer (31 GB Kaggle VM) during its one-card group offload render; not a multi-GPU path and not investigated here.
  • The strided INT8 route (FLUX.3, MiniMax-H3) on two real cards ran only as the unit level real two-card test, not a full render.
  • The deferred speed profile re-install reaching a CFG-parallel load end to end on hardware (code path and CPU tests only).
  • sd.cpp layer split ranges were audited by reading only.
  • ROCm, Windows and B200 multi-GPU were not run.

…t after a fit decline

On Kaggle 2x T4, Wan2.2-TI2V-5B with both cards and UNSLOTH_DIFFUSION_LAYER_SPLIT=force was declined as
short by about 1787 MiB. The split's primary was held to 85% of its safe budget (free memory less the
discrete reserve) and then charged the 2 GiB overhead, the stems, the VAE and the default clip's 7839 MiB
headroom, which left it no room for a block. A one-card resident plan is priced at the full safe budget.

The split is still planned at 85% first, so every placement main makes is unchanged (that slack pays for
unpriced reference requests, FLUX.2 klein edits). Only when that try declines for lack of room is it retried
with the primary at the full safe budget. Secondaries keep the 85% margin: their one-block working set does
not grow with the request. Measured on 2x T4 at the default 1280x704 x 121 frame clip: the primary allocated
5.2 GiB above its weights against 7.7 GiB charged; cuda:1's blocks held 3.0 GiB above theirs, which only the
margin covers.
…pture stream

A bare torch.cuda.graph keeps one default capture stream, created on the first card that captured. The
per-card latency probes in diffusion_int8_gemm (_graph_latency) and diffusion_convrot_quant
(_unlisted_latency) captured without a stream, so on a second card the capture switched to the first card's
stream while the kernels ran on their own card. On Kaggle 2x T4 the cuda:1 probe raised
cudaErrorStreamCaptureInvalidated; a bare capture there replays nothing.

Add card_graph (that card current plus its own capture stream, the one GraphedForward already uses) and route
both probes through it.
The strided processors (FLUX.3, MiniMax-H3) ran the accuracy check on the load's card only, and the op runs
the kernel only on a checked card, so CFG replica or layer split blocks on cuda:1 silently ran native
attention. Each other card of the selection now gets the same untimed check (the race stays the primary's).

The deferred speed profile re-installs the route at the 3rd image, outside the load's selection scope, so
the dispatch route was rebuilt for the primary card only and the second card fell back to the incumbent.
Without a selection, the cards the DiT already runs on (an armed CFG router's replica card, a layer split's
block cards) are checked instead.
…tream

The cast cache reader kept one side stream, made on the first device tensor's card. Under a layer split the
same component has blocks on two cards, so a cuda:1 tensor was copied with a cuda:0 stream current and the
copy ran on cuda:1's default stream, behind the render the side stream is there to avoid. Keep one stream per
card.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T04:12:04.126125Z fb32208 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. Keep them coming!

Reviewed commit: fb32208e80

ℹ️ 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 7fbb0ba into main Nov 15, 2026
@danielhanchen
danielhanchen deleted the studio-multi-gpu-int8-fixes branch November 15, 2026 05:45
danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Nov 15, 2026
…ids to the rotary (#2514)

## Summary

The Qwen4Exp sparse attention tests added in #2509 build cos/sin by
calling `Qwen4ExpTextRotaryEmbedding` with 2-D `(batch, seq)` position
ids. That only works on newer transformers, whose rotary does
`position_ids.expand(3, -1, -1)`. On transformers 5.17, which is
unsloth's default pin, the rotary indexes `position_ids[:, :, None, :]`
and expects `(3, batch, seq)`. The result is 29 failures in unsloth's
`Core zoo (HF=default + TRL=default)` job (first seen on
unslothai/unsloth#17790):

```
transformers/models/qwen4_exp/modeling_qwen4_exp.py:128: in forward
    position_ids_expanded = position_ids[:, :, None, :].float()  # shape (3, bs, 1, positions)
E   IndexError: too many indices for tensor of dimension 2
```

unsloth-zoo's own Tests CI stayed green because it runs a newer
transformers.

## Fix

This is a test-only change. Both helpers (`_inputs` in
`tests/test_qwen4_exp_sparse_attn.py` and `_qwen_inputs` in
`tests/test_sparse_attention_review.py`) now pass text positions on all
three mrope grids, `(3, batch, seq)`. That is the shape the model itself
hands the rotary, and every supported transformers version accepts it.
The library code is untouched: `sparse_attention.py` and
`temporary_patches/qwen4_exp.py` consume the model's
`position_embeddings` and never call the rotary themselves.

## Verification

| transformers | before | after |
|---|---|---|
| 5.17.0 (unsloth default) | 29 failed, 26 passed | 55 passed, 9 skipped
|
| 5.23.0 | 53 passed | 53 passed |

On 5.23.0, `(3, batch, seq)` ids give cos/sin bit-identical
(`torch.equal`) to the 2-D ids the tests used before, so the reference
numbers do not change.
danielhanchen added a commit that referenced this pull request Nov 15, 2026
…e them as stock math under compile (#17795)

## Summary

Follow-up to #17618. The MiniMax-H3 row-mod kernels
(`video_minimax_h3_rowmod.py`) launched on whatever CUDA device the
calling thread had current, not on the operands' card.

## Root cause

Triton launches on the current device and its current stream.
`_launch_modulate` and `_launch_gated` called the kernels with no device
scope; only the one-time probe inside `verdict()` ran under
`torch.cuda.device(x.device)`. When a render thread's current device is
not the tensors' card (multi-GPU host, a pooled or unpinned thread), the
launch goes to the wrong device and stream. On two B200s with `cuda:0`
current and the tensors on `cuda:1`, main fails the launch with:

```
ValueError: Pointer argument cannot be accessed from Triton (cpu tensor?)
```

Where the pointer check passes, the kernel would instead run on the
wrong stream, unordered against the producer stream. The sibling kernel
`video_minimax_h3_qknorm.py` already guards its launch.

## Fix

- New `_on_card(t)` helper: returns `torch.cuda.device(index)` when the
operand sits on a card other than the current one, and a null context
otherwise. Single-card renders skip the switch, which saves about 3 us
per launch (the same rule `diffusion_vae_fused._on_card` uses).
- `_launch_modulate` launches under `_on_card(x)`, `_launch_gated` under
`_on_card(residual)`.

## Audit of other Triton launch sites under
`studio/backend/core/inference/`

I enumerated every `kernel[grid](...)` call with an AST walk and checked
the device scope at each one.

Already guarded, no change needed:
- `diffusion_convrot_quant.py`, `diffusion_flux2_rope.py`,
`diffusion_flux3_qk_rope.py`, `diffusion_grouped_int8_gemm.py`,
`diffusion_grouped_int8_triton.py`, `diffusion_int8_fused.py`,
`diffusion_int8_gemm.py`, `diffusion_int8_gemv.py`,
`diffusion_moss_fused.py`, `diffusion_native_w8a8_rdna.py`,
`diffusion_nvfp4_bias.py`, `diffusion_packed_block.py`,
`diffusion_qwenimage21_eager.py`, `diffusion_rocm_fused.py`,
`diffusion_vae_fused.py`, `diffusion_vae_strips.py`,
`video_minimax_h3_qknorm.py`: guarded at the launch.
- `diffusion_fp8_dequant.py` (`launch_triton`): its only caller wraps it
in `torch.cuda.device(codes.device)`.
- `diffusion_nvfp4_act_quant.py`: the `triton_op` is only invoked under
`torch.cuda.device(...)`.
- `video_wan_fused.py`: every launch runs inside `_fused_forward`, which
holds `torch.cuda.device(hidden_states.device)`.
- `video_minimax_h3_vae.py`: launches run inside the encoder / decoder
forwards, which hold `torch.cuda.device(hidden_states.device)`, and
`_int8_linear` switches devices on its own.

Missing the guard, not changed here because other open PRs touch these
files:
- `diffusion_int8_attention_triton.py` (`quantise`, `attend`,
`half_attention`): #17789, #17791, #17790.
- `diffusion_multigpu.py`, `diffusion_cast_cache.py`, and the
`diffusion_int8_gemm.py` / `diffusion_convrot_quant.py` probes: #17790.

## Compile safety (second commit)

Two more issues in the same helpers, both reproduced on CPU with torch
2.14.1:

- `modulate` / `gated_residual` bump the global `STATS` counters inside
the traced region. Dynamo guards on the Python int (`G['STATS']['stock']
== ...`), so compiling either helper recompiled on every call: 5 frames
for 5 identical calls (`CompileCounter`).
- On a cold verdict cache an eligible call reaches `verdict()`, whose
`_LOCK` and timing probe fail `fullgraph=True` with `Unsupported context
manager` (Dynamo cannot enter a `lock`).

Studio's own `UNSLOTH_H3_IMAGE_COMPILE=1` path never installs the
rewrite, so this only bites when an already-patched transformer or the
helpers are compiled directly. Fix: under
`torch.compiler.is_compiling()` both helpers return the stock expression
directly, without touching `STATS` or the verdict cache. After the fix:
1 frame for 5 calls, and cold `fullgraph=True` compiles with the verdict
cache still empty. Eager dispatch is unchanged.

## Tests

Added to `studio/backend/tests/test_h3_row_mod.py`:
- `test_launches_switch_to_the_operand_card` (CPU): patches
`torch.cuda.device` / `current_device` and the kernels to record the
current device at each launch, with operands on a mocked `cuda:1` while
device 0 is current. Both launches must fire on device 1, and device 0
must be current again afterwards.
- `test_launches_on_the_current_card_skip_the_switch` (CPU): same-card
operands never enter `torch.cuda.device`.
- `test_compiling_the_row_ops_does_not_recompile_per_call` (CPU): one
compiled frame across 5 calls of each helper, output equal to the
reference.
- `test_cold_tracing_of_an_eligible_call_compiles_fullgraph` (CPU): CUDA
eligibility simulated, empty verdict cache, `fullgraph=True` compiles
both helpers and the probe never runs.
- `test_kernels_on_a_second_card_while_card_0_is_current` (bf16, fp16;
skips with fewer than 2 GPUs): real tensors on `cuda:1` with
`torch.cuda.set_device(0)`. The fused output must be bit-equal to
`reference_modulate` / `reference_gated_residual`, and `cuda:0` must
still be current after the call.

Each arm imports its own tree (the test file was copied into a checkout
of the merge base).

| Run | main (merge base) | this branch |
| --- | --- | --- |
| CPU, `test_h3_row_mod.py` | 3 failed (device test, `assert 5 == 1`
recompiles, `Unsupported context manager`), 6 passed, 5 skipped | 9
passed, 5 skipped |
| 2x B200, `test_h3_row_mod.py` (first commit) | 3 failed (CPU device
test, plus both two-card tests with `Pointer argument cannot be accessed
from Triton`), 9 passed | 12 passed |
| 1x B200, `test_h3_row_mod.py` (both commits) | not rerun | 12 passed,
2 skipped (two-card tests) |

The existing single-card CUDA tests (bit-exactness of the kernels and
the whole row forward) pass on the branch.
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