Repository navigation
Studio MiniMax-H3: launch row-mod kernels on the operand's card, trace them as stock math under compile - #17795
Merged
Merged
Conversation
_launch_modulate and _launch_gated called the Triton kernels on whatever device the calling thread had current. On a multi-GPU host a render thread whose current device is not the tensors' card launched on the wrong device and stream. Only the verdict probe was guarded. Wrap both launches in torch.cuda.device(operand.device), skipped when the operand is already on the current device (single-card renders pay no switch). Add a CPU test that records the device at launch and a two-card test that runs the kernels on cuda:1 with cuda:0 current.
modulate and gated_residual bumped the global STATS counters inside the traced region, so Dynamo guarded on the Python int and recompiled on every call (5 frames for 5 identical calls). A cold call on an eligible input also reached verdict(), whose lock and timing probe fail fullgraph=True with an unsupported context manager. Under torch.compiler.is_compiling() both helpers now return the stock expression directly, without touching STATS or the verdict cache, so one graph is compiled and fullgraph tracing succeeds. Eager dispatch is unchanged.
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. 👍 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". |
shimmyshimmer
pushed a commit
to shimmyshimmer/unsloth-staging-4
that referenced
this pull request
Nov 17, 2026
… q/k RoPE int64 offsets, Gemma-4 band route int32 guard (unslothai#18141) Three fixes from a re-check of recent kernel PRs. 1. **Cold probes ask about capture on the operand's card (unslothai#17795, unslothai#17593, unslothai#17637).** The cold `verdict()` of the MiniMax-H3 row-mod kernel (`video_minimax_h3_rowmod.py`), the H3 q/k norm (`video_minimax_h3_qknorm.py`) and the FLUX.3 q/k RoPE (`diffusion_flux3_qk_rope.py`) read `torch.cuda.is_current_stream_capturing()` on the current card before switching to the operand's card. With another card current, the timing / equality probe could start inside a CUDA graph capture on the operand's card, then cache a failure or raise. The query now runs under `torch.cuda.device(x.device)`, with the probe. 2. **MOSS-Image fused q/k norm + RoPE: int64 row offsets (unslothai#17099).** The kernel multiplied the token index by the fused-QKV row stride in int32, which wraps past 2**31 (a 9216-wide row past about 233k tokens). The row index is now int64 before any stride product; output bits are unchanged. 3. **Block compile: the Gemma-4 sliding band route checks the interval kernel's int32 limit (unslothai#17817, unslothai#17860).** The long-band route in `unsloth/models/_block_compile.py` called `large_head_attention` directly and skipped the int32 span check the large-head router applies on its own path (`_shapes_qualify`), so a long enough sliding layer reached the int32-addressed kernel. The band route now keeps masked SDPA past that limit. ### GPU results, base (main 62d66cb) vs this branch Capture probes, Kaggle 2x T4 (sm75), torch 2.11.0+cu130: cuda:0 current, a `torch.cuda.graph` capture active on cuda:1, operand on cuda:1, cold call, probe runs counted. | probe | base | this branch | |---|---|---| | H3 row-mod `verdict` | probe ran inside the capture and cached `{exact: False, use: False}`; the next eager call still returns the cached failure | returns None, no probe, nothing cached; the next eager call computes `{exact: True, use: True}` | | H3 q/k norm `verdict` | probe ran inside the capture and the call raised `Cannot copy between CPU and CUDA tensors during CUDA graph capture` | returns None, no probe; the next eager call computes the real verdict | | FLUX.3 q/k RoPE `verdict` | probe ran inside the capture and cached a RuntimeError failure for cuda:1 for the process | returns None, nothing cached; the next eager call runs the real check | The captured graph itself replayed correctly in both arms; the defect is the probe running inside the capture and the cached failure or raise. MOSS and band route, L4 (sm89), Colab, torch 2.12.1+cu130, Triton 3.7.1: | fix | check | base | this branch | |---|---|---|---| | MOSS int64 offsets | fused kernel engaged (4 launches per arm); 1x4096x24, 2x1029x24, 1x16384x24, 1x37x4 | q / k / v hashes | identical to base; v equal to eager, q / k within 0.03125 of eager in both arms | | band route guard | S600 / w512 / hd256, S2048 / w512 / hd128, S4096 / w1024 / hd256 (kernel route), S256 / w512 (causal SDPA) | routes and output hashes | same routes, identical hashes; max error vs fp32 about 0.008 | ### Tests - `studio/backend/tests/test_diffusion_capture_probe_device.py` and `test_h3_row_mod.py::test_cold_verdict_asks_about_capture_on_the_operand_card`: on the T4 pair base 3 failed / 14 passed, this branch 17 passed (two-card tests included). - `studio/backend/tests/test_diffusion_moss_qk_rope_offsets.py` lowers the kernel to TTIR and rejects i32 row-stride products: fails on main; on the L4 base 1 failed / 8 passed, this branch 9 passed, and the existing MOSS fused GPU tests pass in both arms. - `tests/test_block_compile.py::test_gemma4_long_band_past_int32_keeps_the_plain_route`: fails on main; on the L4 base 1 failed / 83 passed, this branch 84 passed (4 skips, the same version gates in both arms). - CPU (torch 2.14.1) on this branch: 13 passed / 5 skipped in the probe and MOSS files, 74 passed / 14 skipped in `test_block_compile.py`. ### Not covered - The overflow sizes themselves (over 233k MOSS tokens, a band span past 2**31) cannot be allocated; the TTIR and CPU route tests are the evidence there. - A full MOSS-Image render with real weights; the op and its unit tests ran. - On fp16 / sm75 the FLUX.3 q/k RoPE check reports a real bit mismatch, so its fused path stays off on T4 regardless of this change; the capture fix is shown by the probe count, not by the fused path engaging there. - sm80 and sm120 cards; the capture probes ran on T4 only, MOSS and the band route on L4 only. - The GPU runs used main 62d66cb; the branch was then rebased onto main 142c398 and only the CPU tests were rerun there.
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
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_modulateand_launch_gatedcalled the kernels with no device scope; only the one-time probe insideverdict()ran undertorch.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 withcuda:0current and the tensors oncuda:1, main fails the launch with: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.pyalready guards its launch.Fix
_on_card(t)helper: returnstorch.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 rulediffusion_vae_fused._on_carduses)._launch_modulatelaunches under_on_card(x),_launch_gatedunder_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 intorch.cuda.device(codes.device).diffusion_nvfp4_act_quant.py: thetriton_opis only invoked undertorch.cuda.device(...).video_wan_fused.py: every launch runs inside_fused_forward, which holdstorch.cuda.device(hidden_states.device).video_minimax_h3_vae.py: launches run inside the encoder / decoder forwards, which holdtorch.cuda.device(hidden_states.device), and_int8_linearswitches 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): Studio INT8 attention (Triton): two quantiser launches and a launch plan per call, same output bits #17789, Studio INT8 attention: compile the kernel once per machine and cut the per-call CPU cost, same output bits #17791, Studio multi-GPU: layer split fit retry, per-card graph probes, INT8 checks on every card, per-card cast-cache streams #17790.diffusion_multigpu.py,diffusion_cast_cache.py, and thediffusion_int8_gemm.py/diffusion_convrot_quant.pyprobes: Studio multi-GPU: layer split fit retry, per-card graph probes, INT8 checks on every card, per-card cast-cache streams #17790.Compile safety (second commit)
Two more issues in the same helpers, both reproduced on CPU with torch 2.14.1:
modulate/gated_residualbump the globalSTATScounters 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).verdict(), whose_LOCKand timing probe failfullgraph=TruewithUnsupported context manager(Dynamo cannot enter alock).Studio's own
UNSLOTH_H3_IMAGE_COMPILE=1path never installs the rewrite, so this only bites when an already-patched transformer or the helpers are compiled directly. Fix: undertorch.compiler.is_compiling()both helpers return the stock expression directly, without touchingSTATSor the verdict cache. After the fix: 1 frame for 5 calls, and coldfullgraph=Truecompiles 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): patchestorch.cuda.device/current_deviceand the kernels to record the current device at each launch, with operands on a mockedcuda:1while 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 entertorch.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=Truecompiles 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 oncuda:1withtorch.cuda.set_device(0). The fused output must be bit-equal toreference_modulate/reference_gated_residual, andcuda:0must still be current after the call.Each arm imports its own tree (the test file was copied into a checkout of the merge base).
test_h3_row_mod.pyassert 5 == 1recompiles,Unsupported context manager), 6 passed, 5 skippedtest_h3_row_mod.py(first commit)Pointer argument cannot be accessed from Triton), 9 passedtest_h3_row_mod.py(both commits)The existing single-card CUDA tests (bit-exactness of the kernels and the whole row forward) pass on the branch.