Skip to content

Studio INT8 attention: faster kernel on T4, L4, A100 and RTX PRO 6000, same output bits - #17769

Merged
danielhanchen merged 40 commits into
mainfrom
studio-int8-attention-speed
Nov 14, 2026
Merged

danielhanchen merged 40 commits into
mainfrom
studio-int8-attention-speed

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Makes the Studio INT8 attention kernel faster on T4, L4, A100 and RTX PRO 6000 (sm120) without moving a single output bit. Only diffusion_int8_attention_cuda.py, the config tables in diffusion_int8_attention.py and the tests change; processors and routing are untouched.

What changed

  • Product orderings and spread tile copies (sm120 and sm75, head dim 128). Three compile-time orderings: Q.K^T steps over pairs of key blocks so consecutive products never share an accumulator, P.V does the same over channel blocks, and a thread spreads its copies of the next tile across the product pairs instead of issuing them all after the barrier. Integer sums are exact and every float accumulator sees the same operations, so the output is unchanged. With the orderings off, the PTX of every other config is byte for byte what it was.
  • Two quantiser launches instead of three. unsloth_i8stats_q quantises Q and takes the K mean and the V range; unsloth_i8quant_kv quantises V and K, reading V the second time while it is still in L2. The rotation takes its channel signs from a table. A call with more than 65535 jobs per head splits into several launches.
  • A launch plan per call signature. Padded lengths, layout, grids and scalar arguments are computed once per shape, dtypes, strides, config and scale, and stored with the loaded kernels, so a short call no longer spends more time in Python than in the kernel.
  • Smaller blocks for short sequences. A CUDA config entry may carry long_keys / long overrides (the convention the Triton tables already use). sm80 head dim 128 and sm89 head dim 64 use 4 warps per block below 4608 keys and keep their previous config from there on.
  • Tests on two cards. Each card loads its own kernels and launch plans, the card check counts for its card only, a call on another card launches on that card's current stream (including a side stream), and a CUDA graph captured on another card replays bit-equal to eager.

Results

Kernel time per call, ours / X (below 1 means faster). Fresh process per arm, ABBA order, 3 reps, L2 flushed between calls; a verdict needs the SM clocks matched within 3% and a delta outside the repeated-base (A/A) spread.

card vs main, 4k tokens and up vs main, 1k to 2k tokens vs best exact kernel (flash SDPA, FlashInfer, cuDNN), 4k tokens and up vs SageAttention2
T4 (fp16) 0.91 to 0.99 0.95 to 0.98 0.27 to 0.35 vs SDPA, 0.51 to 0.66 vs FlashInfer not built for sm75
L4 tie 0.93 to 1.04 (see below) 0.55 to 0.76 (raw, clocks rarely matched) 0.86 to 0.99
A100-40 / A100-80 tie 0.56 to 0.98 0.72 to 0.99 0.31 to 0.88
RTX PRO 6000 (G4) 0.94 to 0.96 (head dim 128), tie at head dim 64 0.96 to 1.02 (tie) 0.60 to 0.79 0.83 to 0.98, tie on the three longest video shapes

Shapes come from each model's config: Qwen-Image-2.1 (and Turbo), LTX-2.5 video and audio, MiniMax-H3 video and image, Wan 2.2 5B and A14B, Z-Image (and Turbo), FLUX.3 klein, plus synthetic 1k to 3k token shapes.

  • RTX PRO 6000 vs SageAttention2: on the three longest shapes (h3_video_5s, wan_480p, wan_720p) every kernel sits at the 600 W cap and the FP8 P.V kernels run at a lower SM clock, so wall times converge: 1.004, 0.998, 1.007.
  • Short calls: below about 2k tokens the exact kernels still win in eager mode on A100, L4 and RTX PRO 6000, and at 126 tokens on every card. The dispatch route already keeps those calls native (token floor and per-card race). On RTX PRO 6000 the eager gap closes in a CUDA graph, so it is per-call launch cost.
  • One eager regression vs main: L4, 1039 tokens x 24 heads, 1.039 over 5 pairs (0.981 tie as a CUDA graph). Kernel time is lower than main (267.5 vs 277.0 us), so the extra 12 us is on the launch side.

Correctness

  • Bit check against main: 0 mismatches for head dim 128 and 64 on T4, L4, A100-40, A100-80 and RTX PRO 6000.
  • GPU tests: 146 passed on A100-40, A100-80, L4 and RTX PRO 6000; T4 143 passed, 3 skipped; 2x T4 148 passed, 3 skipped (the two-card tests run).
  • compute-sanitizer memcheck on B200: 0 reports for six variants; the negative control is flagged.
  • CPU: the INT8 attention, dispatch, Triton fallback and backend suites pass after merging main. test_mirrored_base_still_trips_the_flux2_shape_guard fails without the gguf module on main as well.

Note for CUDA graphs on a second card

torch.cuda.graph keeps one default capture stream per process, on the card of the first capture. A later capture on another card without an explicit stream fails with "The CUDA Graph is empty". The two-card graph test passes stream = torch.cuda.Stream(device = 1); any CUDA graph capture on a second card needs the same.

Not covered

  • Mixed-capability two-card pairs (only T4 pairs ran).
  • Timing on B200 (correctness only).
  • End-to-end render speed with routing; the numbers above are per attention call.
  • The cause of the L4 1039 x 24 eager regression.

Q.K^T and P.V on the int8 tensor cores with an fp32 online softmax, on
strided [B, S, H, D] views. The quantisers are Triton (rotated Q / K,
centred K, per-channel V gain); the attention kernel is CUDA source
compiled at first use with NVRTC and launched through the CUDA driver on
torch's context, so there is no build step and no prebuilt wheel.

Per-card configs for sm80 / sm86 / sm89 / sm120 and head dims 64 / 128, an
opaque custom op with a fake, an accuracy check and a timed race against
the incumbent (kept on a tie, 2% margin), and the
UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL switch.
…h_int8)

The H3 and FLUX.3 strided processors run the kernel on unmasked calls once
install_int8_attention flagged them. INT8 H3-Image checkpoints race it on
the DiT blocks against what they would run otherwise (SageAttention, or
native attention where SageAttention cannot engage) and keep the incumbent
unless the kernel is more than 2% faster. attention_backend=unsloth_int8
and UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL=1 engage it by request on the
families with strided processors; =0 is the kill switch.

Tests cover the switches, the per-card configs, the processor route and
its fallbacks on CPU, and on CUDA the kernel against a plain-torch model
of itself, spills, CUDA graph replay and torch.compile.
…ion, interleave the race

The last DiT blocks of H3-Image have score scales large enough that the
largest probability of a key tile could round to 256, which the byte
packing stored as 0 with a carry into the next key: rows of garbage and
non-finite values, black tiles in the image. Probabilities are now
clamped to 255 before they are packed (about 1.5% per call).

The on-card accuracy check runs its probe a second time with q and k
scaled by 5 and requires finite output and cosine >= 0.99, so a kernel
that breaks on sharp attention cannot engage.

The block race times its three variants in interleaved rounds: an A100
changes speed about a second into a load, which let the variant timed
last look faster than it was.
… long-sequence block config, waves_per_eu option
…ients

The INT8 kernel has no backward and the custom op hides it from autograd, so
a call whose query, key or value needs gradients got an output with no graph
behind it. The FLUX.3 and H3 strided processors now route such a call to
native attention at the call site; inference calls are unchanged.

Tests: both processors run the op under no_grad, native attention with a
backward that reaches the input when gradients are wanted, and the op again
once gradients are off.
The set of verified cards was keyed by (device, head dim), so a check that
passed in bf16 also let fp16 and fp32 calls run the kernel unchecked. The key
now carries the dtype, and a call runs the kernel only when the check passed
in the dtype of each of its operands.

Tests: the verified set per dtype on CPU, and on a card an fp16 call stays on
native attention until the check has run in fp16.
… underflows

With q = 0 and k = 0 the Q and K scales sit on their floors and their product
underflows to 0. The padded keys of the last tile carry -3e38 as their score
bits; times a scale of 0 that became 0, the same score as every real key, so
they took a share of the softmax weight (65 keys: 63 padded slots, the output
came out 2x off). The score scale is now floored at 1e-30, which keeps the
padded scores far below any real one.

Test: zero q and k with 65 and 1000 keys against the torch model of the
kernel.
…mulators every 16 tiles

The P.V sums enter the fp32 output accumulators with the int-to-float
constant (1.5 * 2^23) still in them, and it was removed once at the end. The
constant times the tile weights grows with the key count while the sums do
not, so they lost low bits to it: at 65536 keys the kernel was 1.2e-3 away
from its own model in fp32. It now comes off every FLUSH (16) tiles, inside
the rare branch that already rebases the accumulators, which costs under 1%
of the call (a separate block after P.V cost 3-5% on sm80 / sm89).

Test: fp32, 65536 keys, the kernel against its torch model.
…2 keys, 128-key tiles

Quantisers. The four Triton quantisers are replaced by three CUDA kernels
compiled next to the attention kernel (statistics, V, Q and K):

* The V range is taken over every key, in row chunks. It was taken over
  every 8th key, which wrecked short calls (16 text-refiner tokens: keys 0
  and 8 only, rel L1 0.55 against fp64) and missed isolated large values.
* Every element address is 64-bit. The Triton kernels multiplied the batch
  index by the batch stride in int32, so a batch starting 2^31 elements into
  its buffer read out of bounds.
* Q and K are rotated by a Hadamard transform over the whole head dim (it was
  16 channels at a time), and K gets one scale per 32 keys and accumulator
  lane group instead of one per tile and lane group. Both lower the Q.K^T
  error on real FLUX.3 / H3 activations.
* Three launches per call instead of four, vector loads, no host-side copy
  for strided inputs whose rows are 16-byte aligned.

Kernel. Tiles of 128 keys on every card, the Q operand fragments optionally
kept in registers (QREG), and configs retuned per card on the full call with
the quantisers included.

Tests: the statistics plan, a 16-token call with one large V key, an isolated
V value at a key the old sampling skipped, batch offsets past 2^31 elements,
and the quantisers against the fp64 model with the new rotation and scales.
…rocm-v2

# Conflicts:
#	studio/backend/core/inference/diffusion_int8_attention.py
…lock after P.V

Where the removal of the rounding constant from the output accumulators sits
changes the generated code by more than the removal costs: inside the rebase
branch it is the cheapest place on sm80 and sm89 (a block of its own after P.V
cost 3-5% of the call there), while on sm120 the block after P.V is 1-2%
faster than the rebase branch on every shape from 4k tokens up. FLUSH_TAIL
selects the place per config; the sm120 head dim 128 config sets it.

Both placements remove the constant at the same point of the accumulation
(after tile j is before tile j + 1), so the output bits stay the same on
every card.

Tests: the drift test runs both placements, and the two give equal bits.
The check that an input can be read with 16-byte vector loads is written out
(last-dim stride 1, an aligned base, aligned row strides) and the copy for
inputs that fail it is a clone into a fresh allocation. No behaviour change:
aligned inputs are still read in place, misaligned or strided ones still give
the same bits as the aligned call.
sm75 (T4) has int8 tensor cores but only the 8x8x16 product and no cp.async,
so the kernel had no config there and the card ran native attention. On sm75
the kernel now computes each 16x8x32 product as four 8x8x16 ones on the same
operand registers and copies key tiles with plain loads and stores. The
integer sums are the same, so the output bits match every other card (checked
by running the sm75 code on a later card).

The Q operands can be read straight from global memory (qreg 2), which takes
no shared memory: sm75 has 64 KB per SM and one 128-key stage is 36 KB.

Configs for both head dims, measured on a T4 with fp16 operands. A load that
asks for the kernel without naming a dtype is checked in fp16 on sm75.
The compile check runs per config and skips an arch the local NVRTC cannot
target (NVRTC 12.6 has no sm_120). The sm75 bit test compares the sm80
instructions only where they run. The torch.compile and H3 kernel tests use
fp16 and the default SDPA pick on sm75, where Inductor refuses bf16 and cuDNN
attention needs sm80, and the H3 test engages through the load hook with no
dtype named. The routing test sets the registry's active backend itself:
diffusers 0.43 no longer sets it in set_attention_backend.

[skip ci]
…e CUDA kernel

Three compile-time orderings, off by default, that leave every output bit as it was:
- QKW: Q.K^T goes one k step at a time over pairs of key blocks, so consecutive products never share an accumulator.
- PVW: the same for P.V over groups of channel blocks.
- SPREAD: a thread issues its copies of the next tile one chunk per product pair instead of all at once after the barrier.

Integer sums are exact and every float accumulator sees the same operations, so the output does not change.
With the defines off the PTX of every shipped config is byte for byte what it was.
Tests: the orderings compile to the same products and copies, refuse bad combinations, and match the plain order bit for bit on the card.
…oduct orderings

RTX PRO 6000 Blackwell (Colab G4), head dim 128: qkw 1, pvw 8, spread 5. The output bits do not change.
Fresh processes, ABBA order, 3 reps, L2 flushed between calls, SM clocks matched within 3 %:
- against the kernel before: 0.947 to 0.970 eager and 0.942 to 0.961 as a CUDA graph on the eight head dim 128 shapes.
- against SageAttention2 2.2.0 (eager): h3_2048 1.028 -> 0.976, h3_edit 1.040 -> 0.985, klein_2048 0.990 -> 0.942,
  wan_480p 0.992, h3_video_5s 1.003, wan_720p 1.005 (the last three were 4 to 6 % behind on medians).
Head dim 64 keeps its config: its PTX is unchanged.
… product orders

T4, head dim 128: qkw 1, pvw 8 (its one-stage kernel has no next tile to spread). The output bits do not change.
Fresh processes, ABBA order, 3 reps, fp16, against the kernel before (medians, eager / CUDA graph):
h3_1024 0.983 / 0.976, h3_2048 0.957 / 0.969, klein_1024 0.953 / 0.956, h3_edit 0.951 / 0.962, wan_480p 0.944 / 0.941.
The card is power limited and ran the new order at a 3 to 6 % lower SM clock, so most pairs fall outside the 3 % clock
match; where pairs matched the verdict is a win (h3_edit both modes, wan_480p as a graph).
Head dim 64 keeps its config: its PTX is unchanged.
…all signature

A call of about a thousand tokens spent more time in Python and in kernel launches than in the kernel.

- The quantisers are two launches instead of three. unsloth_i8stats_q quantises Q and takes the K mean and the V range, unsloth_i8quant_kv quantises V and K. Each is a grid (heads, jobs) that works through its jobs in an order that reads V the second time while the first read is still in the L2 cache. A call with more than 65535 jobs per head splits into several launches.
- The rotation takes its channel signs from a table and its cross-lane stages as a sign flip and a sum. Same operations per value, fewer instructions.
- The padded query length follows the kernel block only, and the operands are one allocation.
- The launch arithmetic of a call (padded lengths, layout, grids, scalar arguments) is planned once per shape, dtypes, strides, config and scale. The plans live with the loaded kernels.

The output bits do not change.
…ad dim 128) and sm89 (head dim 64)

A card runs one block per SM, so a call of a few thousand tokens is a handful of blocks per SM and its last round leaves SMs idle. Smaller blocks waste less of that round, bigger ones copy each key tile for more rows.

- A CUDA config entry may carry long_keys / long, the convention of the Triton tables: select_config applies the overrides from that many keys on.
- sm80, head dim 128: 4 warps per block below 4608 keys (2 to 10 percent off the kernel on A100-40 and A100-80 from 1039 to 4176 tokens), 8 warps from there on (as before: 3 to 5 percent ahead from 10011 tokens).
- sm89, head dim 64: 4 warps x 2 query tiles below 4608 keys (13 to 20 percent off the kernel on L4 up to 2048 tokens), 8 warps from there on (as before).

The block shape moves no output bit; a test runs both kernels of an entry across the boundary.
Each card loads its own kernels and launch plans, the card check counts
for its card only, a call on another card launches on that card's
stream, and a CUDA graph captured on another card replays the call.
The graph test names a capture stream of that card: torch keeps one
default capture stream per process, on the card of the first capture.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 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-14T16:54:36.779283Z c157b2a 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

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: c157b2a719

ℹ️ 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 20b3b0f into main Nov 14, 2026
@danielhanchen
danielhanchen deleted the studio-int8-attention-speed branch November 14, 2026 16:55
danielhanchen added a commit that referenced this pull request Nov 15, 2026
…ll back to the short one (#17796)

## Summary

Follow-up to #17769. Some INT8 attention kernel configs carry a
`long_keys` / `long` override (sm80 hd128 and sm89 hd64 switch to
`wpc=8` from 4608 keys; ROCm gfx1151 hd128 from 8000). `select_config`
turns that into a second compiled kernel, but the install-time check
never reached it: the accuracy probe uses about 1000 tokens and the race
uses `RACE_TOKENS = (4096, 1024)`. Two problems followed:

1. The long kernel was compiled on the first real call with at least
4608 keys (FLUX at 1024x1024 is exactly 4608). That call could be under
CUDA graph capture, and that kernel never passed the cosine check that
sets `_VERIFIED`.
2. If that compile or launch failed, the `except` in
`int8_attention_impl` added `(index, head_dim)` to `_BROKEN`. That also
turned off the verified short kernel for the rest of the process.

## Changes

`studio/backend/core/inference/diffusion_int8_attention.py`:

- `_long_check`: when the card's config has `long_keys`, the install
check (`_check`, so also `verdict`) compiles and checks the long variant
once per (card, head dim, dtype, impl). It runs eagerly, outside any
capture, on the cheapest probe that selects it: batch 1, 2 heads, 1000
queries against `long_keys + 100` keys (the last key tile is ragged).
The probe uses the same plain and sharp accuracy bars as the short
check. A pass goes into `_LONG_VERIFIED`. The result shows up as `long`
in the verdict and in `status()["verdicts"]`, and the install log line
gets `long_ok=...`.
- `_run`: when no explicit config is passed, a call long enough for the
long variant runs it only if that variant was verified (and has not
failed since). Otherwise the call runs the short config. The short
config is a valid kernel at any length, just slower on long calls, and
the output is the same either way: the block shape does not change any
output bit (`test_long_overrides_do_not_change_the_output`). An explicit
`config=` is still run exactly as given.
- `int8_attention_impl`: a runtime failure in a call that ran the long
variant now adds `(index, head_dim, impl)` to `_LONG_BROKEN`. That call
runs native attention, and later long calls go back to the short kernel.
A failure in a short-kernel call still marks `(index, head_dim)` broken,
as before.
- If the long variant fails its check or fails to load, the card keeps
INT8 with the short kernel for every call. `ok` is unchanged.
- Configs without `long_keys` behave exactly as before: no extra probe,
no extra compile, same call path.

## Tests

New `studio/backend/tests/test_diffusion_int8_attention_long_probe.py`
(CPU, a faked sm89 card with the compile / launch mocked):

| test | main | this PR |
|---|---|---|
| the card check compiles and verifies the long variant | FAIL | pass |
| a long variant that fails its check leaves long calls on the short
kernel | FAIL (the long call raises, so the card goes native: `kernel
failed, native attention from here on`) | pass |
| a long variant that misses the accuracy bar is not used | FAIL | pass
|
| a long call that fails at runtime disables only the long variant |
FAIL | pass |
| a short kernel failure still turns the card off | pass | pass |
| a config without long_keys is checked and run as before | pass | pass
|
| an explicit config is run as given | pass | pass |

The existing INT8 suites (`test_diffusion_int8_attention.py`,
`_dispatch`, `_triton_fallback`, `_rocm`) pass on CPU on both trees: 126
passed, 93 skipped on this branch; main fails only the 4 new tests.

## GPU evidence (Colab L4 sm89 and A100 sm80, torch 2.14.1+cu130, main
at f490069 vs this branch)

INT8 GPU suites (`test_diffusion_int8_attention.py`, `_dispatch`,
`_triton_fallback`, and the new file) on each card: 197 passed, 6
skipped on this branch. Main fails only the 4 new tests (193 passed).
The 6 skips need two CUDA cards.

The long variant is verified at install, as recorded in the verdict:

- L4 hd64: `{'ok': True, 'keys': 4708, 'cos': 0.99996, 'rel_l1': 0.0077,
'sharp_cos': 0.9971}`, `_LONG_VERIFIED = [(0, 64, bf16, cuda)]`
- A100 hd128: `{'ok': True, 'keys': 4708, 'cos': 0.99996, 'rel_l1':
0.0081, 'sharp_cos': 0.9970}`, `_LONG_VERIFIED = [(0, 128, bf16, cuda)]`
- L4 hd128 and A100 hd64 have no `long_keys`: no long verdict, no extra
kernel.

Output and per-call time through the registered op, bf16, 24 heads, 8
fresh processes in ABBA order (main head head main head main main head).
The A/A noise is the spread across the 4 main runs:

| card | tokens | head dim | wpc run | sha main = head | main ms | head
ms | delta | A/A |
|---|---|---|---|---|---|---|---|---|
| L4 | 4608 | 64 | 8 / 8 | yes | 1.6566 | 1.6462 | -0.63% | 4.38% |
| L4 | 4608 | 128 | 12 / 12 | yes | 2.9600 | 2.9398 | -0.68% | 2.52% |
| L4 | 16384 | 64 | 8 / 8 | yes | 17.7035 | 17.5745 | -0.73% | 2.41% |
| L4 | 16384 | 128 | 12 / 12 | yes | 31.7831 | 31.6264 | -0.49% | 3.42%
|
| A100 | 4608 | 64 | 4 / 4 | yes | 0.6966 | 0.6975 | +0.13% | 0.07% |
| A100 | 4608 | 128 | 8 / 8 | yes | 1.4826 | 1.4840 | +0.10% | 7.33% |
| A100 | 16384 | 64 | 4 / 4 | yes | 7.6951 | 7.6963 | +0.02% | 0.02% |
| A100 | 16384 | 128 | 8 / 8 | yes | 12.6990 | 12.6990 | 0.00% | 0.02% |

Both trees run the same kernel (same `wpc`) at every shape, the outputs
are bit-identical, and every call engaged INT8. One row is above its A/A
spread: A100 4608 / hd64, about 1 us per call. That config has no
`long_keys`, so the GPU work is the same kernel. On the host the only
addition there is one dict lookup in `_run`.

## Install-time cost

Median of 3 fresh processes per arm. "Fresh driver cache" is a new
`CUDA_CACHE_PATH`; "warm driver cache" is a second process on the same
path. "In-process" means the verdict caches were dropped but the
compiled kernels kept, so it measures the probes only.

| card, head dim with long_keys | fresh driver cache | warm driver cache
| in-process |
|---|---|---|---|
| L4 hd64, main / head | 2249 / 3548 ms (+1.3 s) | 62 / 110 ms (+48 ms)
| 8.6 / 25.1 ms (+17 ms) |
| A100 hd128, main / head | 2224 / 3332 ms (+1.1 s) | 264 / 322 ms (+58
ms) | 14.5 / 48.3 ms (+34 ms) |

This is a cost moved, not added, wherever a long call follows. On main,
the first 4608-key call pays the long compile. For L4 hd64 that first
call is 1258 to 1276 ms on main vs 1.7 ms on head with a fresh driver
cache, and 30.8 ms vs 1.7 ms with a warm one. On A100 hd128 the first
4608-key call is 2112 to 6942 ms on main vs 1075 to 1100 ms on head.
Both arms include about 1 s of first-op-call setup there, which also
appears on cards without `long_keys`. Cards and head dims without
`long_keys` do not change (L4 hd128: 2162 vs 2159 ms; A100 hd64: 2225 vs
2239 ms). Only a process that never makes a call at or above `long_keys`
pays the extra compile and gets nothing for it.

With #17791's disk compile cache (now on main), measured on this head
with a fresh driver cache and a fresh kernel cache per arm: the long
compile moves from the first long call to install (L4 hd64: about 2330
ms vs 2360 ms total, first long call 840-853 ms down to 1.7 ms; A100
hd128: about 3325 ms vs 3375 ms, first long call 1785 ms down to about
1080 ms). What is added is the long accuracy probe itself, about 18 ms
on L4 and 33 ms on A100, once per card, head dim and dtype per process.

## Not covered

- H100, sm75 and sm120 were not run (their configs have no `long_keys`
on the CUDA path).
- The ROCm gfx1151 hd128 `long_keys = 8000` entry goes through the same
`_long_check` / `_run` code, but it was not run on AMD hardware here.
- A real compile failure of the long kernel on hardware was not
reproduced. That path is covered by the CPU tests only.
danielhanchen added a commit that referenced this pull request Nov 15, 2026
…lan per call, same output bits (#17789)

## 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.py` and its ROCm test file change. The
configs, routing and processors stay as they are.

## What changed

- **Two quantiser launches instead of three (NVIDIA) or four
(gfx1151).** `prep_kernel` does 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_kernel` does 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.
- **A launch plan per call signature.** Padded lengths, grids,
constexprs, launch options and every scalar argument are worked out once
per shapes, dtypes, strides, config and scale. A call then only
allocates and launches. `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.

| card | eager | CUDA graph | host per call | output |
|---|---|---|---|---|
| RTX PRO 6000 (sm120) | 0.86-0.98 (WIN) at 126 tokens, 1k and 2k head
dim 64, 1k head dim 128; TIE from 2k x 56 heads up | 0.95-0.98 (WIN) on
the same four; TIE above | 83-107 -> 75-97 us | same bits, 17/17 shapes
|
| A100 (sm80) | 0.85-0.95 (WIN) at 1k and 2k, both head dims; 0.76 at
126 tokens (TIE: A/A 0.33); TIE from 3k up | 0.90-0.96 (WIN) at 126
tokens and 1k; TIE above | 301-637 -> 275-575 us | same bits, 17/17 |
| L4 (sm89) | 0.90 at 126 tokens (WIN), TIE elsewhere | same | 307-674
-> 272-623 us | same bits, 17/17 |
| gfx1151 Linux (ROCm 7.13, Triton 3.6) | 0.89 at 126 tokens (WIN), TIE
elsewhere | same | 304 -> 267 us | same bits, 17/17 |
| gfx1151 Windows 11 (ROCm 7.14, triton-windows 3.8) | TIE from 6k
tokens up (A/A at most 3%); noise below 6k | same | 150-720 us, no
consistent change (noisy box) | same bits, 17/17 |

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.so` once per process, which
every Triton kernel in the process pays, Inductor's too. In Studio it
lands in the install-time accuracy check. Studio points
`TRITON_CACHE_DIR` at `<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

- Sequence lengths (`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.py`
counts them.
- Batch and head offsets are formed in int64 in all 7 kernels, so a
large batch stride no longer wraps in an i32 multiply.
`test_diffusion_int8_attention_triton_offsets.py` lowers each kernel to
TTIR and rejects an i32 multiply on a stride or index.
- `quantise`, `attend`, `int8_attention` and `half_attention` launch 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.py` covers it with tensors
on a second card.
- Each fix is bit-identical to the commit before it on L4 and RTX PRO
6000 Blackwell over the 17 protocol shapes, with per-call time inside
the base-vs-base spread.

## Tests

- New CPU tests in `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 from `long_keys` keys on, and
falls back to one launch per quantiser past the grid limit.
- CPU, the four INT8 attention files: no failures.
`tests/test_setup_cache_env_containment.py` fails the same 10 tests on
main and head on this host, which is unrelated to this change.
- L4, A100 and RTX PRO 6000: head 200 passed, 17 skipped, 0 failed; main
198 / 17 / 0. The head runs main's tests plus the 2 new ones.
- T4: head 197 passed, 20 skipped, 0 failed; main 195 / 20 / 0.
- On L4, A100 and RTX PRO 6000, main and head ran both in one process at
every shape (q / k gain 1 and 5) and the outputs were bit for bit equal:
34 of 34 on each card.
- gfx1151 Linux (AMD CI): head 132 passed, 1 failed, 84 skipped; main
131 / 1 / 83. The one failure is
`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

- T4: there is no Triton path to time. sm75 has no Triton config,
because Triton cannot compile its int8 dot.
- Windows on NVIDIA (triton-windows) did not run. On gfx1151 Windows the
timing and the bit check ran, but the test suite did not: the venv
lacked `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.
- Triton older than 3.6 did not run on a GPU. We ran 3.8 on NVIDIA, 3.6
on gfx1151 Linux and 3.7 in the CPU interpreter. sm86 was not timed; it
uses the sm80 table.
- These are per-call kernel timings on synthetic DiT-like inputs, with
no end-to-end model runs. CUDA graph capture and replay ran for every
shape on every card, but the replay output was not compared with eager.
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