Repository navigation
Studio INT8 attention (Triton): two quantiser launches and a launch plan per call, same output bits - #17789
Conversation
…lan per call signature prep_kernel runs everything that reads only the inputs (K mean, V range, Q tiles, the channel-major V copy) in one launch, kv_kernel what needs those statistics (K tiles, INT8 V tiles). Each block runs the code its standalone kernel ran, so the operands and the output are bit for bit the same. Padded lengths, grids and every scalar argument are computed once per call signature. Calls past the grid limit keep one launch per quantiser.
…launch plans Under the Triton interpreter the two quantiser launches and a cached plan give the output of one launch per quantiser bit for bit; a plan is made once per call signature, takes the long config from long_keys keys on and falls back to one launch per quantiser past the grid limit.
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. |
…d kernels' compile key prep_kernel and kv_kernel took the token counts (sq, sk) and block counts (n_qblk, n_kblk) as plain ints, so Triton specialised them on % 16 and == 1 and compiled up to 4 variants each across real sequence lengths. Mark them do_not_specialize so one compile serves every length; the padded sizes and strides stay specialised (always multiples of 16). Adds a CPU test that computes the compile key with Triton's own specialiser over 15 token counts.
The kernels split the (batch, head) program index and multiplied it by the i32 strides in i32 before widening, so b * x_stride_b wrapped once the product passed 2**31 (a batch stride of 2**30 at batch 2 gave -2**31). Widen b, h and bh to int64 before any stride or channel multiply in every kernel: the per-quantiser kernels, the fused prep / kv kernels and the attention kernel. Adds a CPU test that lowers each kernel to TTIR and rejects any i32 multiply taking a stride or the (batch, head) index.
Triton launches on the current device and stream, so quantise, attend, int8_attention and half_attention launched on the wrong card when called directly with tensors on another one. Studio's dispatcher already runs the Triton path under torch.cuda.device(q.device); it now calls the unchecked _int8_attention, so a render pays nothing, and the module's public entry points switch to the operands' card themselves, only when it differs from the current one. Adds a CPU test with fake CUDA tensors on a second card and recording launchers. [skip ci]
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
…an FP8 dequantize conversion (#2512) ## Summary #2508 added `_drop_reverse_fp8_conversions` to the CPU loader. It runs after every load and imports `unsloth.models.loader_utils`, which loads the whole GPU model stack (`unsloth.models`, `unsloth.kernels`, `unsloth.context_parallel`) even for a plain checkpoint. The CPU route is meant to keep that stack unloaded, and unsloth's guards check that it does. They have failed on every unsloth PR that installed zoo at or after `d7605dec`: ``` tests/test_cpu_route_context_parallel.py::test_cpu_route_plain_trainer_skips_gpu_stack tests/test_cpu_route_context_parallel.py::test_cpu_route_forwarded_cp_size_of_one_opts_out[1] tests/test_cpu_route_context_parallel.py::test_cpu_route_forwarded_cp_size_of_one_opts_out[None] tests/test_cpu_backend_tiled_mlp.py::test_cpu_backend_loader_tiles_like_the_gpu_loaders assert kwarg["gpu_only"] == [] ... Left contains 142 more items, first extra item: 'unsloth.kernels' ``` (seen first in `Repo tests (CPU, rest)` on unslothai/unsloth#17789, which does not touch either area). ## Fix The helper only has work to do when one of the model's `_weight_conversions` contains an `Fp8Dequantize` operation. The loader now checks for that first (by operation type name, so it does not import transformers' FP8 integration either) and only then imports the helper. An FP8 checkpoint still gets its reverse conversions dropped exactly as before. ## Tests - `test_reverse_fp8_conversions_are_dropped_after_load` now passes a model that carries an `Fp8Dequantize` conversion, so it still proves the helper runs. - New `test_a_model_without_fp8_dequantize_never_imports_the_gpu_model_stack` (no conversions, empty list, non-FP8 conversion): a meta path finder records any `unsloth.models*` import attempt. It records the attempt rather than relying on the raise, because the loader swallows import errors. Verification: | | unsloth CPU route tests (11) | `tests/test_cpu_loader_prequantized_checkpoint.py` | |---|---|---| | zoo `fc240413` (before #2508) | 11 passed | n/a | | zoo `d7605dec` (#2508) | 4 failed | passes | | this branch | 11 passed | 15 passed | | this branch with the loader change reverted | | 3 new cases fail |
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
…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.
…ngle-GPU hosts too
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
…quantisers' compile key prep_kernel and kv_kernel still specialised n_heads on % 16, so 24 / 30 / 40 / 56 heads and 32 heads compiled two variants per head dim (3 per kernel over the 17 protocol shapes on G4). The head count only feeds the batch / head split of the program id, so one compile per head dim serves every model. The compile-key test now covers the served head counts too.
…ff the real device FakeTensorMode makes a real tensor on a fake tensor's device the first time it sees that device (torch.zeros on ROCm builds), so on a one-GPU ROCm host every device-guard test failed with 'invalid device ordinal' before reaching the module. The launchers are recorded, so the tests now stub that step and need no second card. [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
[skip ci]
… sizes out of the attention kernel's compile key (#17855) ## Summary Follow-up to #17789 for Studio's Triton INT8 attention kernel, the one that serves gfx1151 (Strix Halo) and NVIDIA cards whose CUDA kernel cannot load. Two changes, both in `diffusion_int8_attention_triton.py`. The output does not move a bit at any of the 17 protocol shapes (126 to 75600 tokens) on any card we ran: RTX PRO 6000 Blackwell, L4 and gfx1151. - **Direct launches after the first call per card.** The first call of a launch plan on a card goes through `kernel[grid](...)` as before. Later calls hand the same argument list straight to the compiled kernel's launcher, which is the call `JITFunction.run` makes after its cache lookup. So a call no longer pays Triton's per-argument binding and specialisation on the host. It is taken only while every tensor is 16-byte aligned (as at the first call, since alignment is part of what was compiled), only on the card the launcher was cached for and with the operands on that card, and never under the Triton interpreter. The cached template holds no tensors. Any launcher error switches the process back to regular launches. `UNSLOTH_DIFFUSION_INT8_TRITON_FAST_LAUNCH=0` turns it off. - **Sequence lengths and head count out of the attention kernel's compile key.** #17789 did this for the two quantiser kernels. The attention kernel now gets `do_not_specialize` on `sq`, `sk` and `n_heads` as well, so a new resolution does not compile another variant. ROCm builds keep `sq` / `sk` in the key: on gfx1151 the unspecialised kernel ran Wan 2.2 A14B 720p (75k tokens) 3% slower in two separate runs, while a render keeps one resolution, so the extra variants cost nothing per step there. ## Results Main = 3dd22b6. Three rounds of main / head / head with the direct launch off / head with the direct launch off / head / main, one fresh process each, so 6 processes per arm. A/A = the spread of main's own processes, or the spread within one process if larger. Eager = one call between CUDA events with L2 flushed. Loop = back-to-back calls, which is where host time shows. Host = wall time of one synchronised call. | card | output | device time (eager, CUDA graph) | back-to-back, 126 tokens | host per call | peak memory | |---|---|---|---|---|---| | RTX PRO 6000 (sm120), Triton 3.8 | same bits, 34/34 | TIE at all 17 shapes | 0.0651 -> 0.0461 ms (0.71); 1k head dim 64: 0.72 | 68-90 -> 50-70 us | equal at all shapes | | L4 (sm89), Triton 3.8 | same bits, 34/34 | TIE at 15 shapes; see the note on two 1k shapes | 0.2414 -> 0.1589 ms (0.66); 1k head dim 64: 0.68 | 251-573 -> 173-475 us | equal at all shapes | | gfx1151 Linux (ROCm 7.13, Triton 3.6) | same bits, 14/14 | TIE at all 7 shapes (wan22_a14b 1.002) | 0.1393 -> 0.0903 ms (0.65) | 120-363 -> 66-186 us | equal at all shapes | Compiled attention kernel variants over the 17 shapes go from 8 to 4 on the RTX PRO 6000 and from 9 to 4 on L4 (one EVEN_K pair per head dim). The first call at every shape on an empty Triton cache took 5.7 -> 3.6 s and 19.2 -> 10.7 s (one run each). gfx1151 keeps the same variants as main (6 over its 7 shapes), as intended. L4 note: across processes, two synthetic 1k-token shapes read slower in eager right after the back-to-back loop (1k head dim 64: 1.11, 1k x 24 heads: 1.04), and only with the direct launch on. This comes from the card's clock, not the kernels. With the direct launch on the GPU does about 50% more work per second in the loop, so the L4 drops its SM clock further (1620 vs 1950 MHz after 400 calls at 1k head dim 64). The same calls on a rested card, toggled on and off in one process, take the same time: 0.1864 vs 0.1864 ms and 0.2724 vs 0.2734 ms. No other card shows it. Engagement, 10 steady calls per shape: head 510 direct launches and 0 regular ones on NVIDIA (210 / 0 on gfx1151). Main and the kill switch make 510 regular launches. Host syncs: 0 in every arm. ## Triton versions On L4, main and head ran side by side in one process per version at 5 shapes: - Triton 3.4, 3.5 and 3.6: direct launches engage, and the output is the same bits as main. - Triton 3.2 (torch 2.6): the first direct attempt raises, so the process keeps the regular launch, with the same bits. - Triton 3.3.1 (torch 2.7.1): the attention kernel does not compile on main either (`'tt.join' op failed to infer returned types`), so the op takes the native fallback on both sides. This predates this change and is not fixed here. ## Tests - CPU, all `test_diffusion_int8_attention*.py` files: 240 passed, 88 skipped, 0 failed. - New CPU tests: - The argument template follows the kernel's parameter order and holds no tensors. - A cached launcher never serves another card. - The attention kernel is now in the compile-key test, which uses Triton's own specialiser: one key over 15 lengths x 5 head counts on NVIDIA, more than one on ROCm builds. With the attention kernel's lengths put back in the key, the test fails. - RTX PRO 6000 and L4 on-card pytest: head 310 passed / 20 skipped / 0 failed; main 307 / 20 / 0. - gfx1151 (AMD CI): head 146 passed / 1 failed / 84 skipped; main 143 / 1 / 84. The one failure is `test_the_attention_kernel_compiles_through_the_8bit_prefetch_fix` on both sides, an NVIDIA prefetch test on ROCm. All 10 ROCm card tests pass. The AMD CI verdict is NO_REGRESSION. ## Not covered - Two real Triton-capable cards: cross-card behaviour is covered by the wiring test only. - A100 / sm86 and Windows (gfx1151 or triton-windows) did not run at this head. - On Triton 3.4, direct launches are inferred from zero regular launches and correct output, because that version has no hook chain to count them. - Timings are per call on synthetic DiT-shaped inputs. There were no end-to-end renders.
Summary
Ports the launch-side changes of #17769 to Studio's Triton INT8 attention kernel, the one that serves gfx1151 (Strix Halo) and NVIDIA cards whose CUDA kernel cannot load. The output does not move a bit on any card we ran: L4, A100, RTX PRO 6000 and gfx1151 (Linux and Windows), 17 protocol shapes from 126 to 75600 tokens. Only
diffusion_int8_attention_triton.pyand its ROCm test file change. The configs, routing and processors stay as they are.What changed
prep_kerneldoes everything that reads only the inputs: the K mean, the V range, the Q tiles and, on gfx1151, the channel-major fp16 V copy.kv_kerneldoes what needs those statistics: the K tiles and the INT8 V tiles. The statistics blocks come first in the grid, so the long serial ones start before the short tiles fill the card. Each block runs the same code its standalone kernel ran, so every operand is bit for bit what it was. A call would need more than 65535 blocks in one launch only past about 2M tokens. Such calls keep one launch per quantiser, through the old kernels, which stay.quantise()/attend()keep their signatures.Results (head / main, ABBA, one fresh process per arm, 2 rounds)
Ratio = median over rounds of head / main. A/A = the spread of main's own processes. WIN means at least 2% faster and beyond A/A. Eager = one call between CUDA events, L2 flushed. Graph = the same call replayed from a CUDA graph.
No shape is slower beyond its A/A spread on any card, except one noisy Windows cell: s3k eager 1.07, whose graph ratio is 0.93. On every card the attention kernel itself is 75-99% of the device time from 1k tokens up. The quantisers' share is what moves (torch.profiler, device time per call). At 1k tokens it drops 14-28% on gfx1151 and 17-25% on NVIDIA. From 4k tokens up it moves between -14% (A100) and +6% (gfx1151 at 4k), which is under 1% of the call.
Configs: unchanged
We swept the configs on every card, keeping the key tile size so the output stays the same. The current tables are the best, or within noise of it, at every swept shape. The best alternative gains at most 4% on one 1k shape. On NVIDIA, changing the query rows per warp changes the output bits, while changing the stages does not. On gfx1151 every swept config gives the same bits. One extra lever was tried and dropped: quantising Q inside the attention kernel. It was 1.36-1.47x slower on L4 from 4k tokens, and on RTX PRO 6000 it changed the output bits.
Compile cache
The first call per process with an empty Triton cache took 1.6 s (RTX PRO 6000), 4.3 s (A100), 5.1 s (L4) and 1.7 s (gfx1151). With the cache already on disk, a fresh process takes 0.3 / 1.5 / 1.5 / 0.4 s for the first head dim and 3-8 ms for the second. Most of that warm first call is Triton hashing its own 461 MB
libtriton.soonce per process, which every Triton kernel in the process pays, Inductor's too. In Studio it lands in the install-time accuracy check. Studio pointsTRITON_CACHE_DIRat<studio root>/cache/triton(storage_roots._triton_cache_defaults). Inductor only sets it when it is unset. So the compile is a one-time cost per machine. Head and main are the same here: head writes fewer cache files (25 vs 33 for head dim 128).Follow-up fixes
sq,sk, block counts) are kept out of the fused prep and kv kernels' compile key (do_not_specialize), so one compile serves every token count: 1 variant per kernel instead of 4 across 15 token counts.test_diffusion_int8_attention_triton_compile_key.pycounts them.test_diffusion_int8_attention_triton_offsets.pylowers each kernel to TTIR and rejects an i32 multiply on a stride or index.quantise,attend,int8_attentionandhalf_attentionlaunch on the operands' card when called directly; the op path already held the device and calls an unchecked entry, so it pays nothing extra.test_diffusion_int8_attention_triton_device.pycovers it with tensors on a second card.Tests
tests/test_diffusion_int8_attention_rocm.py. Under the Triton interpreter, the fused launches and a cached plan give the output of one launch per quantiser, bit for bit. A plan is made once per call signature, takes the long config fromlong_keyskeys on, and falls back to one launch per quantiser past the grid limit.tests/test_setup_cache_env_containment.pyfails the same 10 tests on main and head on this host, which is unrelated to this change.test_the_attention_kernel_compiles_through_the_8bit_prefetch_fix, which fails on main too on that runner. All 10 ROCm card tests pass. The AMD CI verdict is NO_REGRESSION, with the same output bits at all 17 shapes at q / k gain 1 and 5.Not covered
httpx, so every test errored in setup at both main and head. Short calls on that box vary 84-94% within one process, so below 6k tokens its timing says nothing. Its head still carried the dropped Q-in-attention code, switched off.