Repository navigation
Studio multi-GPU: layer split fit retry, per-card graph probes, INT8 checks on every card, per-card cast-cache streams - #17790
Merged
Conversation
…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.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.
torch.cuda.graphkeeps one default capture stream per process. A probe on cuda:1 after one on cuda:0 raisedcudaErrorStreamCaptureInvalidatedon 2x T4 (a bare capture there replays nothing). Newcard_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.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.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):
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.
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):torch.cuda.graphon cuda:1 after cuda:0cudaErrorStreamCaptureInvalidatedStudio does not capture CUDA graphs or compile the Wan denoiser on T4 (fp16 family stays eager;
speed_mode=maxarms 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_graphmakes 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_mode=maxon 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.