Repository navigation
Studio: skip Triton's sm_8x prefetch pass for 8-bit dots and run the int8 GEMM on A100 / L4 again - #17669
Conversation
…riton-lang/triton#12486) From Triton 3.8 the sm_8x prefetch pass carries an 8-bit dot's next K slice across the loop one byte per register, so int8 / fp8 tl.dot loops spill and run slower than on 3.7.1. The NVIDIA backend's make_ttgir is wrapped so the pass is skipped only for TTIR modules with an 8-bit tt.dot on sm_8x, on Triton 3.8 / 3.9 whose pipeline still adds it. Every other kernel, card and Triton version compiles as before. Installed when Studio builds its int8 GEMM kernels. UNSLOTH_TRITON_8BIT_PREFETCH_FIX=0 keeps the stock pipeline.
…tch fix is installed With the 8-bit prefetch skipped the sm_8x int8 tiles compile spill-free again, so the Triton >= 3.8 gate only keeps sm_8x stock when the fix is off or unavailable.
…y point and in Inductor's compile workers Default-on from Triton 3.8 for as long as the installed pipeline still adds the sm_8x prefetch pass (no version ceiling). Studio's diffusion, video and diffusion-training entry points install it as Triton and Inductor's compile pool import. Inductor compiles Triton kernels in a sidecar that forks its workers, so the pool is handed a pickler from this module: the sidecar imports it by name and installs the fix before forking. The pickler is only swapped when the sidecar can import the module.
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. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d65b7a8c6e
ℹ️ 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".
|
|
||
| """Skip Triton >= 3.8's sm_8x prefetch pass for 8-bit tt.dot modules (triton-lang/triton#12486: spills, ~7x slower). | ||
|
|
||
| The cache key ignores the skip; harmless since only load timing changes, never output. |
There was a problem hiding this comment.
Include the prefetch fix in compilation cache keys
On sm_8x systems with kernels cached before this fix was installed, Triton can reuse the existing spilling cubins without running patched_make_ttgir at all. Inductor's persistent artifacts can likewise bypass the patched compilation stage. This is not harmless for a performance fix: existing users retain the slowdown, and _triton38_sm8x() now permits the Studio GEMM merely because the wrapper is installed, even when the cached kernel was compiled without it. Include the effective fix mode/revision in the relevant Triton and Inductor cache identities, and test enabling the fix against a cache populated with it disabled rather than only forcing recompilation or using fresh caches.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 29b12bb for Studio's own kernel: i8mm_dq takes a PREFETCH_FIX constexpr set from whether the fix is installed, so a cubin compiled without it (an older Studio that ran this tile on sm_8x before #17036, or the fix switched off) is a different Triton cache entry from the fixed route. Inductor's 8-bit kernels are left as is: a stale cached one is the same kernel base runs today, so it costs no speed against base.
|
@codex review |
1 similar comment
|
@codex review |
|
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". |
…share one skip flag Two threads installing at once could leave make_ttgir wrapped with one thread's flag and add_prefetch with another's. The fix then reported itself installed while never skipping the pass, so sm_8x routed to the spilling Triton GEMM. 31 of 1000 four-thread installs hit this on Triton 3.8.0; 0 of 1000 with the lock.
…er launch _prefetch_fix_key re-ran the fix install on every launch whenever the fix was not installed (Triton 3.7, the kill switch, a Triton that moved the pass): about 6 us per Linear on Triton 3.7.1, 1.4 us under the kill switch and 33 us when inspect.getsource ran each time. _kernels() has already tried the install before any launch, so the first answer holds.
Any earlier test that reaches a Studio diffusion entry point (the torchao wiring tests, test_diffusion_speed) installs the prefetch fix, which wraps SubprocPool.__init__ for the rest of the process. The worker test then saved the wrapped __init__, so _cover_inductor_workers returned False and the test failed depending on order. Start from __wrapped__ when the pool is already covered.
[skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
# Conflicts: # studio/backend/tests/test_diffusion_int8_gemm.py [skip ci]
…and fused residual / GELU when compiled (#17680) ## Summary Offloaded int8 video DiTs (LTX-2.5 at Studio's defaults on a 24 GB card, and the other families read as native int8 Linears) spent a large part of every compiled denoise step around their int8 GEMMs: a bf16 rotation GEMM, an fp32 amax and quantise pass, cuBLAS `_int_mm` with an int32 output, then Inductor kernels that dequantise, add the gated residual and apply the GELU. Q, K and V repeated the quant on the same input. This PR (built on #17669, now merged, which makes the Triton int8 GEMM usable on sm_8x again) runs, for those Linears in a compiled forward: - the rotation and the activation quant as one Triton kernel, bit-identical to the Linear's own eager maths, shared by Q, K and V; - the int8 GEMM on #17669's Triton kernel with the Linear's own epilogue (`acc * x_scale * w_scale + bias`, bf16 out), bit-identical to the cuBLAS path in eager; - the block's gated residual (`residual + out * gate`) and the MLP's tanh GELU inside that GEMM's epilogue. ## Results LTX-2.5 INT8 at Studio's defaults (1280x704x121, distilled two-stage, 8 + 3 steps), one Colab L4 VM, one process per arm, 2 clips per arm. Base is #17669's head (the measurement predates its merge; this branch is the same change replayed onto main); K is head with `UNSLOTH_NATIVE_INT8_ROTQ=0`. | arm | s/clip (2 clips) | median | denoise s | |---|---|---|---| | base, run 1 | 60.80 / 58.36 | 59.58 | 48.9 / 47.4 | | base, run 2 | 60.87 / 58.55 | 59.71 | 49.1 / 47.6 | | head, kill switch (K) | 59.89 / 57.83 | 58.86 | 48.3 / 47.1 | | head, run 1 | 56.84 / 54.82 | 55.83 | 45.4 / 44.1 | | head, run 2 | 57.03 / 55.43 | 56.23 | 45.5 / 44.3 | | head, GELU fold off | 56.63 / 54.66 | 55.65 | 45.2 / 44.0 | | head, residual fold off | 56.82 / 54.86 | 55.84 | 45.1 / 43.9 | | head, both folds off | 57.08 / 55.20 | 56.14 | 45.6 / 44.4 | - Head is 3.7 s per clip faster than base (about 6%); the three base-maths runs spread 0.85 s. - The two epilogue folds are below that spread end to end (about 0.3 s per clip). Measured alone on a real-config LTX-2.5 block on the same card they take 2% off the block (157.4 vs 160.6 ms at 14080 rows, 28.4 vs 29.0 ms at 3520 rows, medians of 5). - K's frames equal base's on every frame of both clips, so the switch restores base. With the GELU fold off the frames equal head's (that epilogue is bit-identical); with the residual fold off they equal "both folds off". Profiled render (2 denoise steps, all kernels, same VM): | kernels | base | head | |---|---|---| | activation quant + norm (the quant, and the Inductor epilogue / residual / norm / AdaLN / GELU / Q-K norm kernels) | 6.92 s | 2.99 s | | the same plus every other Inductor kernel (some move there once the epilogue leaves them) | 8.64 s | 5.71 s | | GEMM (int8 incl. its epilogue on head, bf16 rotation, bf16 dense) | 13.77 s | 13.19 s | | attention | 10.55 s | 10.95 s | | all kernels | 38.35 s | 35.32 s | Frames against a bf16 render of the same prompts (A100-40 with a 16 GiB budget, so the int8 DiT streams as native Linears and takes this route; LPIPS, lower is closer): | arm | clip 1 | clip 2 | |---|---|---| | base int8 | 0.1939 | 0.0431 | | head int8 | 0.1932 | 0.0379 | | head, both folds off | 0.1937 | 0.0398 | ## Cause - On an L4, LTX-2.5 INT8 at Studio's defaults does not fit on the card, so it loads as `NativeWeightOnlyLinear` (W8A8, ConvRot group 256), with the blocks streamed and compiled below their offload hooks. The torchao int8 GEMM swap never sees these Linears. - Compiled, each Linear traced `_rotate` (a `[rows * K/256, 256] @ [256, 256]` bf16 matmul) and `_int_mm_rows` (amax, scale, reciprocal, round, clamp), then `_int_mm` into an int32 `[rows, N]` buffer that the next Inductor kernel read back to dequantise. - Profiled base render on an L4 (2 denoise steps of the default clip): rotation GEMMs 1.82 s, quant kernels 1.37 s, int8 GEMMs 9.36 s, the dequant + residual + norm + AdaLN kernels 2.87 s. ## Change - `diffusion_convrot_quant.rotq_i8` gets a `native` mode that reproduces `_int_mm_rows` exactly: scale `max(amax, 1e-12) * fp32(1/127)` (ATen's CUDA divide by a scalar multiplies by the fp32 reciprocal), fp32 reciprocal and product, round half to even, clamp to +-127. - New `diffusion_native_w8a8_cuda`: opaque custom ops around that kernel and around #17669's GEMM with the native epilogue, each probed once per card against the eager maths (codes, scales and outputs must be equal on ragged rows, a zero row, outliers, K from 768 to 32768, and the bf16 tie operands). `NativeWeightOnlyLinear.forward` takes them only inside a compiled forward, for bf16 CUDA activations on a probed card. An uncompiled denoiser does not change. - The GEMM is probed on the native epilogue alone, so it does not depend on the torchao route's own probe; it still needs that route's arch tile (`arch_config`), so sm_8x takes it only with #17669's Triton prefetch fix installed. - The native bias epilogue uses one fused multiply-add, as `addcmul` does on CUDA (a separate multiply and add differed from cuBLAS + `addcmul` in about 1 output in 50,000). - An Inductor post-grad pass (`ShareRotqPass`), installed only when the route engages and the slot is free: - merges quant calls that read the same tensor (Q, K and V quantise once); - re-points `residual + linear(x) * gate` (gate per batch or per token) at the GEMM with the residual in its epilogue (`fma(bf16(out), gate, residual)`, one bf16 round); - re-points a tanh GELU whose input is only a native GEMM's output at the GEMM with the GELU in its epilogue (bit-identical to the GEMM followed by Inductor's decomposition). - An RMSNorm + AdaLN prologue for the quant kernel is included but off by default: on an L4 it cost about what it saved (`UNSLOTH_NATIVE_INT8_FUSE_NORM=1` opts in). A tanh GELU prologue in the quant was slower than the separate kernel and was dropped for the GEMM epilogue. - `diffusion_speed._compile_repeated_blocks` probes the denoiser's card before the compile traces the blocks (resident and streamed blocks alike). - Generic: any native W8A8 ConvRot Linear compiled on NVIDIA sm80+ takes it (LTX-2.x, Wan, HunyuanVideo-1.5 offloaded int8 loads; ROCm keeps its own RDNA kernels). The folds match the decomposed graph, not a model class. - Kill switches, each read per load: - `UNSLOTH_NATIVE_INT8_ROTQ=0`: everything here off, stock rotation GEMM + quant + cuBLAS (also under `UNSLOTH_DIFFUSION_INT8_ROTQUANT=0` / `UNSLOTH_DIFFUSION_INT8_GEMM=0`); - `UNSLOTH_NATIVE_INT8_GEMM=0`: keep cuBLAS `_int_mm` and the traced epilogue (the folds need the GEMM); - `UNSLOTH_NATIVE_INT8_ROTQ_SHARE=0`: one quant per Linear; - `UNSLOTH_NATIVE_INT8_FUSE_RESIDUAL=0`, `UNSLOTH_NATIVE_INT8_FUSE_GELU=0`: keep those ops in Inductor. ## Numerics The fused quant and the GEMM equal the Linear's eager maths bit for bit. Inductor's compiled version of the same maths does not (on an L4 about 1 code in 13,000 differs from eager), so frames differ from base while staying as close to the eager maths as base is. The residual epilogue reads the gate as the bf16 tensor eager computes; Inductor keeps it in fp32 when it fuses `table + temb` into the residual kernel, so that fold moves values by at most a bf16 step of the gate. Frame scores against a bf16 render are above. ## Tests - `studio/backend/tests/test_diffusion_native_w8a8_cuda.py`, 31 CPU tests: the references equal the Linear's own rotation + quant and epilogue, the routed forward equals the stock traced maths, the forward gate (compiled only, bf16, CUDA, probed card, no input grad, row floor, group and K), every kill switch and default, install and probe placement, the share pass, the three folds on a decomposed LTX-2.5 style graph (match, per-token modulation, replaced ops leave the graph, other users and missing probes keep the stock graph, output within int8 noise), the GEMM probe without the torchao route, and the kernel flags. All 31 fail on the base tree and pass on head. - Neighbouring suites (native quant, native fused, RDNA, convrot, int8 GEMM incl. TMA and unlisted, streamed int8 GEMM, speed, H3 native, video native quant on device, the #17669 prefetch fix, Flux ConvRot fused, runtime ConvRot, per-layer rotation): 821 passed on base, 852 on head (the 31 new), with the same pre-existing failure and errors on both (`test_unpinned_torchao_host_copy_is_a_distinct_wrapper_over_the_same_data`; two errors in `test_video_native_quant_on_device.py`). - On main (replayed, same 6-file diff), B200 torch 2.14.1: `test_diffusion_native_w8a8_cuda.py` 31 passed; with `test_diffusion_int8_gemm.py` in the same run 205 passed, and the 4 failures are the same 4 that main itself fails on a B200 (`test_no_compiled_variant_spills_to_local_memory`, the two rotquant switch tests, `test_failed_shape_tile_probe_keeps_its_shapes_on_the_default`). - GPU (L4, Triton 3.8, torch 2.14; and B200): every probe passes; the residual and GELU epilogues equal their references on LTX-2.5 shapes (3520 and 14080 rows, K 4096 and 16384), and a real-config LTX-2.5 block compiles with 4 folds per block and the expected op counts. ## Not proven - Only LTX-2.5 at Studio's default settings was run end to end, on an L4 (timing) and an A100 (frames); Wan and HunyuanVideo-1.5 offloaded int8 loads take the same code but were not rendered. - The GELU and residual folds are proven on a block, not end to end: their gain is inside the run-to-run spread above. - The RMSNorm + AdaLN prologue (off by default) was only measured on a block. - At 3520 rows (the 8 stage-1 steps) the L4 arch tile is about 15% slower than a 128x128x64 tile and than bare cuBLAS on a 4096 x 4096 GEMM; a per-shape tile for the native route was not tried. - Frame scores cover 2 prompts. - No sm_120 or Hopper run; on sm_100 the int8 GEMM gate keeps cuBLAS (the GEMM, folds and probes were checked there with the gate forced).
…ad on NVIDIA (#17726) ## Studio INT8 attention: Triton fallback when the CUDA kernel cannot load on NVIDIA Follow-up to #17718. On NVIDIA, Studio's INT8 attention runs a CUDA C++ kernel that is compiled at runtime with NVRTC (found through ctypes) and loaded with the driver API. If NVRTC is missing, or the compile, `cuModuleLoadData` or the first launch fails, the accuracy check used to fail and the card stayed on native attention. The likeliest place for that is Windows: a Windows install may have no NVRTC DLL that the loader can find. Every Windows x64 / ARM64 install already has Triton (unsloth's pyproject pulls in `triton-windows`, and torch ships Triton on Linux), and Studio already has a Triton INT8 attention kernel for ROCm. So when the CUDA kernel cannot load, the same calls now go to that Triton kernel. ### Routing | card / state | before | after | |---|---|---| | NVIDIA, CUDA kernel loads | CUDA kernel (accuracy check + race) | unchanged | | NVIDIA sm80 / sm86 / sm89 / sm120, CUDA kernel cannot load (no NVRTC, compile, module load or first launch error) | native | Triton kernel, after its own accuracy check and race | | NVIDIA sm75, CUDA kernel cannot load | native | native (Triton cannot compile an int8 `tl.dot` on sm75, see below) | | no Triton importable, or no Triton config for the capability | native | native | | ROCm gfx1151 | Triton | unchanged | | `UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL=0` | native | native | - A failure inside the CUDA check (an exception, not an accuracy miss) is recorded for that card and head dim, and the check runs again on the Triton kernel. Verdicts and the verified set are keyed by implementation, so a CUDA pass never stands in for Triton or the other way round. - When the Triton kernel stands in, it has to win the race against the incumbent even if the load asked for `unsloth_int8` by name. The CUDA kernel keeps its forced semantics, and the env switch `1` still skips the race. - New knob `UNSLOTH_DIFFUSION_INT8_ATTENTION_IMPL=auto|cuda|triton` (default `auto`). `cuda` never runs Triton; `triton` skips the CUDA kernel, which is how the path was tested on Linux. - The status dict, the install log line and the H3-Image race record name the engaged implementation (`cuda` / `triton`), the CUDA failure reason, and keep timed races apart from untimed checks. Op call counts gain a `triton` counter. - The kill switch and the gradient guard are unchanged. - The Triton attention kernel installs the sm_8x 8-bit prefetch fix from #17669 (`diffusion_triton_prefetch`) before it compiles, and carries it in its cache key the same way the INT8 GEMM does. On an A100 with Triton 3.8, the compile of the attention kernel went through the fix with the prefetch pass skipped. The quantiser kernels, which have no 8-bit dot, kept the pass. ### Triton configs (NVIDIA) Tuned with the Triton path forced on A100 (sm80), L4 (sm89) and RTX PRO 6000 (sm120), head dims 128 and 64. The grid covered block M, block N, warps, stages and P.V mode, under Triton 3.8 (torch 2.14.1), and the top configs were re-timed under Triton 3.7 (torch 2.13). Every pick is 16-bit P.V reading V in place, with only Q.K^T in int8; int8 P.V was slower on every card. sm80 uses the tile that stays close to native on both Triton releases: the Triton 3.8 winner was 1.49x native under Triton 3.7. sm86 uses the sm80 entry, which fits sm86's 99 KB of shared memory. ### Tests `tests/test_diffusion_int8_attention_triton_fallback.py` (CPU, faked card) covers: - an NVRTC load failure, a `cuModuleLoadData` failure and a first-launch failure each route to Triton on sm80 / sm86 / sm89 / sm120 when Triton and a config are there, and to native when they are not; sm75 keeps native; - `IMPL=cuda` never runs Triton, and `IMPL=triton` never compiles the CUDA kernel; - the kill switch wins under `auto` and `triton`; - a CUDA verdict is never accepted for Triton, and the other way round; - the race times the Triton kernel, and a requested stand-in still has to win it; - the prefetch fix is installed before the Triton kernel compiles. Two tests run on the card: the forced Triton path through the registered op, with strided views and the gradient guard. The new test file fails without the change. The existing INT8 attention tests were updated for the implementation-keyed verified set. ### GPU verification (Colab: A100-40GB, L4, RTX PRO 6000 Blackwell, T4) All runs below are eager, one fresh process per measurement, in ABBA order with a flash A/A spread. "triton" is the product op with the Triton path forced (`IMPL=triton`); "cuda" is the #17718 kernel. Each Triton measurement asserted that the op ran the Triton kernel. Triton ms over native ms, torch 2.14.1 / Triton 3.8 (below 1 = faster): | shape (tokens, heads x dim) | A100 vs flash | L4 vs flash | L4 vs cuDNN | RTX PRO 6000 vs flash | RTX PRO 6000 vs cuDNN | |---|---|---|---|---|---| | H3 1024 (1039, 56x128) | 1.329 | 1.124 | 1.052 | 1.067 | 1.198 | | H3 2048 (4112, 56x128) | 1.104 | 0.835 | 0.816 | 0.863 | 0.920 | | H3 edit (10011, 56x128) | 1.068 | 0.780 | 0.764 | 0.822 | 0.871 | | FLUX.3 klein 1024 (4176, 24x128) | 1.130 | 0.830 | 0.808 | 0.888 | 0.980 | | FLUX.3 klein 2048 (16464, 24x128) | 1.069 | 0.763 | 0.753 | 0.815 | 0.863 | | LTX-like (6144, 32x64) | 1.015 | 0.839 | 0.873 | 0.922 | 0.894 | | Wan 480p (32760, 40x128) | 1.032 | 0.758 | 0.746 | 0.801 | 0.848 | | Wan 720p (75600, 40x128) | 1.030 | 0.747 | 0.734 | 0.793 | 0.841 | - The A/A spread was at most 2.3% on L4 and at most 1.3% on the others. - Torch 2.13 / Triton 3.7 gives the same picture: L4 0.79-0.86 and RTX PRO 6000 0.83-0.91 vs flash from 4k tokens, A100 0.99-1.07. - The CUDA kernel stays faster than Triton on long sequences, by 1.11-1.47x. Matching it was not a goal. - On short calls (about 1000 tokens) Triton loses: its four launches cost more than they save. The race checks 1024 and 4096 tokens, so it engages from 2560 tokens on L4 and RTX PRO 6000 and never on A100. Simulated NVRTC failure (and `cuModuleLoadData` failure) in a fresh process, default settings, a fake DiT with 24x128 and 32x64 strided attention: | card | raced (INT8 checkpoint) | asked for by name | serves | |---|---|---|---| | A100 | 0 of 3 modules (Triton 1.75 ms vs flash 1.51 ms at 4096 tokens) | 0 (stand-in raced) | native | | L4 | 3 of 3, from 2560 tokens (2.50 ms vs 2.83 ms at 4096 tokens) | 3 | Triton | | RTX PRO 6000 | 2 of 3 (head dim 128 from 2560 tokens; head dim 64 lost) | (raced, same verdict) | Triton / native | | T4 | 0 (no Triton config) | 0 | native, reason "NVRTC not found ..." | Other settings on the same harness: - `IMPL=cuda`: native. - Kill switch `0`: native. - No failure: the CUDA kernel, as before. fp64 oracle with the Triton path forced: - Inputs: the #17718 stress set (lengths 1..4104, cross attention, strides, storage offsets, ties, outliers, padding, huge / tiny / NaN / inf inputs, up to 314,437 keys) plus real H3-Image q/k/v captures (11 full-size calls, taken on the RTX PRO 6000). - Every normal case passes the product gate (cos >= 0.999, rel L1 <= 0.05) except `gain5`, which the CUDA kernel also fails. - On real captures the Triton path reached a worst rel L1 of 0.0070, a 1st-percentile row cosine of 0.9998 and a worst-row cosine of 0.9993. The CUDA kernel on the same captures: 0.0105 / 0.9988 / 0.9944. - The sm80 and sm89 tiles give the same numbers on those captures. Studio tests on the card: - A100 and L4: 127 passed. The forced Triton GPU tests pass. - One test fails: `test_strided_processor_routes_flagged_calls_to_the_op`, an H3 processor bitwise check on CPU. It fails the same way at the base commit with the PyPI diffusers, so it is not from this change. - T4: Triton cannot compile the int8 `tl.dot` on sm75 under Triton 3.7 or 3.8 (`TritonGPUAccelerateMatmul` fails), so sm75 has no Triton config. ### Not verified - No Windows machine with an NVIDIA card was available. The Windows case was simulated on Linux by hiding NVRTC (every library candidate fails to load) and by failing `cuModuleLoadData`; triton-windows itself was not run. - No sm86 card (RTX 30xx, A10) was available. sm86 runs the sm80 config untimed. - Real full-size H3-Image q/k/v captures were only taken on the RTX PRO 6000. A100 and L4 used the synthetic stress cases and three short real captures.
…e (sm_8x) (#17793) ## Summary #17669 skips Triton's sm_8x prefetch pass for 8-bit `tt.dot` modules by wrapping `CUDABackend.make_ttgir`. A compiler-stage patch does not enter Triton's cache key, so with the persistent `<studio root>/cache/triton` directory: - kernels compiled without the skip (an older Studio, or `UNSLOTH_TRITON_8BIT_PREFETCH_FIX=0`) keep being loaded with the fix on, so sm80 / sm89 keep running the spilling kernel; - kernels compiled with the skip keep being loaded after the kill switch turns it off. Studio's own int8 GEMM already carries a `PREFETCH_FIX` constexpr for this; Inductor-generated and other Triton kernels do not. ## Why the key ignores it - Triton 3.8 / 3.9 `compiler.py` `compile()` builds `key = get_cache_key(src, backend, options, env_vars)` from `triton_key()`, `src.hash()`, `backend.hash()`, `options.hash()` and the cache-invalidating env vars, then returns the cached `CompiledKernel` on a metadata hit before `backend.add_stages` runs. A patched stage never runs on a hit. - `CUDABackend.hash()` (`backends/nvidia/compiler.py`) is `f"{ptxas_version}-{target.arch}"`. - Inductor's `FxGraphHashDetails` (`torch/_inductor/codecache.py`, torch 2.10 through main) hashes `triton_key()` but not the backend hash, and stores `torch.compiler.config.cache_key_tag`. An FX graph cache hit can reload bundled kernels without a Triton cache lookup. - Triton 3.7 is unaffected: its pipeline adds the pass for every capability, so the fix never installs. ## Fix - While the fix is installed, `CUDABackend.hash()` appends a salt for sm_8x targets unless the kill switch is set. The salt is applied before the stage swap, and also to an install left by an older copy of this module. - On import of `torch._inductor.codecache`, `FxGraphHashDetails` appends the same salt to its `cache_key_tag` when the fix is installed, the current CUDA device is sm_8x, and the kill switch is off. ROCm is skipped. This gives one cache entry per fix state. sm_9x / sm_10x / sm_12x keys are unchanged, and the kill switch maps back to the stock key and finds the stock entries again, so nothing outside sm_8x recompiles. On sm_8x each kernel recompiles once with the fix on. No cache directory is moved or wiped. ## Tests `studio/backend/tests/test_triton_8bit_prefetch_fix.py`: 10 new cases, all failing on main and passing here. - Real Triton (CPU cross-compile, sm89 / sm90), warm cache. Compiling with the fix off and then installing the fix gets a new hash and 0 `prmt.b32` (352 before). sm90 keeps its hash. The kill switch finds the stock entry again. - The backend hash is salted only on sm_8x, only with the fix on, never twice, and also on an earlier unsalted install. - The FX graph tag covers each case: installed or not, capability, kill switch, user tag. A real `compiled_fx_graph_hash` changes with the salt and returns to stock under the kill switch. Cross-compile check, warm cache, `hash[:12]` / `prmt.b32`: | Triton | Stale entry (fix off) | Fix on, main | Fix on, this branch | Kill switch, this branch | |---|---|---|---|---| | 3.8.0 | `4c1a6aefd815` / 352 | `4c1a6aefd815` / 352 | `fec229049be7` / 0 | `4c1a6aefd815` / 352 | | 3.9.0 | `4ee39f9d5d70` / 352 | `4ee39f9d5d70` / 352 | `baef9a4de4d0` / 0 | `4ee39f9d5d70` / 352 | GPU, Colab L4 (sm89), Triton 3.8.0, torch 2.14.1+cu130. A 4096^3 int8 `tl.dot` GEMM (128x128x64 tile, 4 warps, 3 stages), one process per row, one shared `TRITON_CACHE_DIR`; output checked against a CPU matmul in every row: | Step | Hash | New compile | Spills | Regs | ms | |---|---|---|---:|---:|---:| | Fill the cache with the fix off | `bb6b0c885581` | yes | 146 | 255 | 7.19 | | main, fix on, that cache | `bb6b0c885581` | no | 146 | 255 | 7.23 | | this branch, fix on, that cache | `e158c16fab21` | yes | 0 | 234 | 1.31 | | this branch, fix on, again | `e158c16fab21` | no | 0 | 234 | 1.31 | | this branch, kill switch | `bb6b0c885581` | no | 146 | 255 | 7.18 | | main, fix on, fresh cache | `bb6b0c885581` | yes | 0 | 234 | 1.31 | | main, kill switch after that | `bb6b0c885581` | no | 0 | 234 | 1.31 | | this branch, kill switch after a fixed fresh cache | `bb6b0c885581` | yes | 146 | 255 | 7.24 | Not covered: an A100 (sm80) run, and an end-to-end Inductor FX graph cache hit on a GPU. The FX tag is covered by the CPU key test only.
Summary
From Triton 3.8, int8 and fp8
tl.dotloops on sm_8x (A100, A10, RTX 30xx, L4) spill registers and run several times slower than on 3.7.1 (triton-lang/triton#12486). The sm_8x prefetch pass carries the next K slice of an 8-bit operand across the loop one byte per register. Studio worked around this by keeping its Triton int8 GEMM off on sm_8x with Triton 3.8 and newer, so those cards ran cuBLAS_int_mmplus torchao's eager dequant epilogue.This PR skips that prefetch pass for exactly the kernels it breaks, then lets the int8 GEMM run on sm_8x again.
Scoped prefetch skip (new
diffusion_triton_prefetch.py). The NVIDIA backend'smake_ttgiris wrapped. The pass is skipped only when all of these hold:tt.dotwith 8-bit operands.Every other kernel, card and Triton version compiles through the untouched stock function. The skip flag is thread-local and lives on the installed pass wrapper, so a concurrent compile in another thread is never affected.
Default-on in every Studio diffusion process. The diffusion, video and diffusion-training entry points install it through the hook they already call (
install_torchao_int_mm_patch). Nothing is imported eagerly: Triton and Inductor's compile pool are patched as they import, or right away if they already are.Inductor's compile workers.
torch.compilecompiles Triton kernels in a sidecar process that forks the workers. A fix installed only in the parent leaves those kernels alone, and the parent then loads the sidecar's spilling cubin. The sidecar imports the pickler class it is given by name, so Inductor's pool is handed this module's pickler, a plainSubprocPicklersubclass. Importing it in the sidecar installs the fix before the workers fork. The pickler is only swapped when the sidecar can import the module from the path it inherits, and never when the caller passes its own pickler.sm_8x int8 GEMM gate.
_triton38_sm8xkeeps sm_8x on the stock route only when the fix is off or unavailable.Kill switch for all of it:
UNSLOTH_TRITON_8BIT_PREFETCH_FIX=0.forcealso applies the skip on a Triton older than 3.8.Unsloth core is not changed. Its only 8-bit Triton kernel (
_w8a8_block_fp8_matmul) compiles to byte-identical PTX with and without the skip on every target.Results
Compile matrix (CPU only, cross-compiled per target)
The issue's repro kernel, fp16 / bf16 / fp32 / int8 / fp8 e4m3 / fp8 e5m2 operands, 4 tiles, sm_80 / 86 / 89 / 90 / 100 / 120, plus a reduction kernel without a dot. Each Triton version was compiled with and without the fix in separate processes:
Every changed cell loses its spills, for example (registers / stack bytes /
prmtbyte repacks):i8mm_dq, sm_89 L4 tilei8mm_dq, sm_80 A100 tileThese match the issue's 3.7.1 numbers. Studio's
i8mm_dqis PTX-identical on sm_90 / 100 / 120. Skipping the pass globally would have been wrong: fp16 128x128x64 then spills on sm_89, which is why the skip is per module.A100 40GB (Colab), Triton 3.8.0, torch 2.14.1
Studio's int8 GEMM against today's sm_8x route (
stock_gemm: cuBLAS_int_mmin the TN layout plus torchao's epilogue). Each arm ran in its own process with its own Triton cache. Values are medians of 3do_benchmedians. The stock arm was run twice (A/A), and the range covers both runs.torch.compile int8 matmul through Inductor's compile workers (A100 40GB, Colab)
torch.compile(lambda x, y: torch._int_mm(x, y.t()), mode="max-autotune-no-cudagraphs")with the Triton GEMM backend at 4096x4096x4096, using the default subprocess compile pool (4 workers). Each arm ran in a fresh process with fresh Triton and Inductor caches. The kernels were read back from the caches (prmtbyte repacks / stack bytes / registers):The output is byte-identical across the three arms and equal to eager
_int_mm. The middle row is why the workers need the fix: the parent autotunes on clean candidates, then loads the worker's spilling build of the winner.L4 (Colab), Triton 3.8.0, torch 2.14.1
The same GEMM comparison as on the A100. The stock arm was run twice (A/A).
The same
torch.compileint8 matmul through the compile workers on L4. Inductor only offers its Triton GEMM templates on cards with at least 68 SMs (L4 has 58), so the run forces them withis_big_gpu. Without that, Inductor on L4 uses cuBLAS for these matmuls and never emits an 8-bittl.dot. The fix-on arm was run twice; its repeat is in brackets:With the fix, none of the 11 autotune candidates repack bytes. One has 8 B of stack at 48 registers; with the fix off it has 0 B and 105 registers. With the fix off, 2 candidates spill (608 and 632 B). The output is byte-identical across arms and equal to eager
_int_mm.Tests
tests/test_triton_8bit_prefetch_fix.py(CPU):force, a moved pass, idempotent install, the flag restored after a failing compile, no leak to another thread, no Triton at all;test_diffusion_int8_gemm.py: the Triton 3.8 gate test is parametrized over the fix.test_diffusion_int8_gemm.py,test_triton_8bit_prefetch_fix.py,test_torchao_intmm_patch_wiring.py: all pass.GPU,
test_diffusion_int8_gemm.pywith this PR's base (base) and with this PR (head), on the same VM with torch 2.14.1, Triton 3.8.0 and torchao 0.18.0.headalso runstest_triton_8bit_prefetch_fix.py:test_no_compiled_variant_spills_to_local_memorytest_h16_is_the_default_and_its_kill_switch_keeps_the_dense_kernelandtest_h16_probe_refusal_keeps_the_dense_kernelThe spill test now passes on sm_8x. The two h16 failures on A100 and the four on B200 fail the same way on the base.
Not covered
UNSLOTH_TRITON_8BIT_PREFETCH_FIX=0turns it off.TORCHINDUCTOR_WORKER_START=spawnworkers are not covered;subprocess(the default) andforkare. Infork, the workers inherit the parent.