Skip to content

Studio diffusion: native probability round and pack in the INT8 attention kernel on sm89 / sm120 - #18870

Merged
danielhanchen merged 4 commits into
mainfrom
studio-int8-attn-occ2
Nov 22, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-int8-attn-occ2

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Summary

The int8 attention kernel rounds each softmax probability to a byte before P.V. Until now it did that with a float trick: clamp at 255, add 2^23 + 2^22 so the add rounds to an integer, then pack four keys with shifts and adds. That costs a clamp, an add and part of a pack for every key.

With native_p: 1 (set for head dim 128 on sm89 and sm120) the kernel rounds with cvt.rni.s32.f32 and packs with cvt.pack.sat.u8.s32.b32. ptxas fuses the pair into one F2IP.U8.F32 per two keys. The saturating pack replaces the clamp. The output does not change by a single bit: the same bits on every input, including +-Inf scales.

UNSLOTH_DIFFUSION_INT8_ATTENTION_NATIVE_P=0 (also off, false, no) turns it off: the kernel is compiled without native_p, so it runs the old path under another kernel key, and the switch is part of the race namespace.

The scores and the P.V sums stay in the magic-constant frame. Reading their bits as floats costs nothing, and a score converted with I2F rounds differently: in an exact-arithmetic check, 99.2% of 200k sampled scores came out with different bits.

Why the bytes are identical

Rounding to nearest even and then saturating at 255 gives the same byte as clamping at 255 and then rounding:

  • below 255 nothing saturates or clamps;
  • from 255 up, both give 255, including the tie at 255.5, which rounds to 256 and then saturates.

An exhaustive GPU sweep feeds the kernel's own prob / pack4 and prob_rn / pack4_sat every one of the 2^32 fp32 bit patterns of the exponent, in each of the four byte slots of a word. The other slots hold a 0.5 tie, about 3, and 512.

check L4 RTX PRO 6000
mismatching words, non-NaN inputs 0 0
ties (2^x = k + 0.5) and clamps covered 74 / 1,048,587,842 74 / 1,048,587,842
truncating conversion instead (negative control) 847,771,276 mismatches 847,771,276 mismatches

NaN is the only input where the two differ on their own: the clamp turns it into 255, the conversion into 0. The only NaN exponent the kernel can form comes from an infinite score scale. The quantisers' amax uses fmaxf, so a NaN element never reaches a scale, and the scale is floored at 1e-30. A +-Inf in a Q row or a K group does reach the scale, and then every exponent of that key group is NaN. The old path gives those keys 255. Without a guard the conversion would give them 0, which makes l = 0 and the output non-finite for an Inf in Q, and gives the keys weight 0 for an Inf in K. So the native path gives such a group an offset of +inf (one compare and one select per row and key group). Its keys, whose bits read as a float are always above 2^22, then saturate to 255. Its padded keys (-3e38) give NaN, which converts to the 0 the old path gives them.

Non-finite oracle, native_p 1 and 2 against native_p 0, B1 H24 D128, 4176 tokens (the last key group holds padded keys), bf16 and fp16, sink path and plain path. Every cell compares the raw bits, so NaN outputs compare too:

input dtype path native_p 1 / 2 = 0, L4 native_p 1 / 2 = 0, RTX PRO 6000 non-finite rows (both arms) without the guard
q[0,5,0,0] = +inf bfloat16 sink yes yes 0 of 100224 same bits (no infinite scale on this path)
q[0,5,0,0] = +inf bfloat16 plain yes yes 0 of 100224 differs (128/128 elements, 1/1 non-finite rows)
q[0,5,0,0] = +inf float16 sink yes yes 1 of 100224 same bits (no infinite scale on this path)
q[0,5,0,0] = +inf float16 plain yes yes 0 of 100224 differs (128/128 elements, 1/1 non-finite rows)
k[0,17,3,0] = +inf bfloat16 sink yes yes 0 of 100224 same bits (no infinite scale on this path)
k[0,17,3,0] = +inf bfloat16 plain yes yes 0 of 100224 differs (534364/534387 elements)
k[0,17,3,0] = +inf float16 sink yes yes 4176 of 100224 same bits (no infinite scale on this path)
k[0,17,3,0] = +inf float16 plain yes yes 0 of 100224 differs (534518/534525 elements)
q[0,9,1,3] = -inf bfloat16 sink yes yes 0 of 100224 same bits (no infinite scale on this path)
q[0,9,1,3] = -inf bfloat16 plain yes yes 0 of 100224 differs (128/128 elements, 0/1 non-finite rows)
q[0,9,1,3] = -inf float16 sink yes yes 1 of 100224 same bits (no infinite scale on this path)
q[0,9,1,3] = -inf float16 plain yes yes 0 of 100224 differs (128/128 elements, 1/1 non-finite rows)
q[0,5,0,0] = NaN bfloat16 sink yes yes 0 of 100224 -
q[0,5,0,0] = NaN bfloat16 plain yes yes 0 of 100224 -
q[0,5,0,0] = NaN float16 sink yes yes 0 of 100224 -
q[0,5,0,0] = NaN float16 plain yes yes 0 of 100224 -
k[0,17,3,0] = NaN bfloat16 sink yes yes 0 of 100224 -
k[0,17,3,0] = NaN bfloat16 plain yes yes 0 of 100224 -
k[0,17,3,0] = NaN float16 sink yes yes 0 of 100224 -
k[0,17,3,0] = NaN float16 plain yes yes 0 of 100224 -
v[0,33,2,7] = NaN bfloat16 sink yes yes 0 of 100224 -
v[0,33,2,7] = NaN bfloat16 plain yes yes 0 of 100224 -
v[0,33,2,7] = NaN float16 sink yes yes 0 of 100224 -
v[0,33,2,7] = NaN float16 plain yes yes 0 of 100224 -

All 48 comparisons per card are bitwise equal, and every row is finite or non-finite the same way in both arms. In the fp16 sink path an Inf in Q leaves its row non-finite and an Inf in K leaves its head's 4176 rows non-finite on the old path too; that comes before the probabilities and is unchanged here. "Without the guard" is native_p 1 with the +inf offset removed, compiled under its own key: on the plain path it changes the output (an Inf in Q makes that row non-finite in bf16), and these inputs never make a sink-path scale infinite, so it matches there. The 18-cell oracle and the 2^32 sweep were rerun with the guard on both cards: 18 of 18 cells bitwise equal (native_p 1 and 2), 0 non-NaN mismatches, and the truncating control fails as before.

Whole-kernel oracle, native_p 1 against native_p 0 with torch.equal:

  • sink path (fold on) and plain path;
  • 4176 tokens (B1), 333 tokens (B2, one partial key tile), 1101 tokens;
  • input gains 1 and 5, V with and without far-out sink rows;
  • bf16, fp16 and fp32.

Result: 18 of 18 cells bitwise equal on each card (18 of 18 for native_p: 2 as well). A kernel built with truncating conversion differs in all 18, and a 1 + 2^-7 scaling of the output is detected.

SASS (sm89, shipped config, NVRTC)

kernel tile loop before tile loop after whole kernel before / after
sink path 1146 1002 3320 / 3176
plain 1196 1053 2736 / 2592

The +-Inf guard costs 16 instructions of the loop (without it: 986 / 1036). Per tile loop: FMNMX 84 -> 20, FADD 70 -> 6, IMAD 83 -> 40, IADD3 69 -> 52, plus 32 F2IP. The IMMA, MUFU, FFMA and FMUL counts, the 168 registers and the one block per SM do not change; the per-thread stack stays at 8 bytes (sink path) and drops from 24 to 16 bytes (plain). sm120 changes the same way (1257 -> 1113 sink path, 1240 -> 1100 plain).

A second variant (cvt.rni.sat.u8.f32 plus prmt packing, native_p: 2) is also bitwise identical. It compiles to two F2IP per two keys plus permutes, 1146 instructions in the loop with the guard, and is slower, so no card uses it.

Micro benchmark (L4, B1 H24 D128, sink path, ms per call, sustained)

Shipped config with native_p 0 (A) and 1 (B), interleaved A B B A, three blocks per length on one VM. The A/A spread is the largest gap between the two A slots of a block.

tokens A median B median B faster by per block A/A spread B/B spread outputs equal
4176 2.2413 2.1720 3.19% 3.46 / 3.19 / 3.23% 0.43% 0.16% yes
16384 30.015 28.895 3.87% 3.82 / 3.87 / 3.97% 0.41% 0.25% yes
45056 222.98 214.83 3.79% 4.52 / 3.71 / 3.77% 0.35% 0.09% yes

Every B slot is faster than every A slot. The gain is well above the A/A spread, but below the spread + 5% bar we use for a speed claim, so this PR is not sold as a speedup. In short: bitwise identical, the tile loop goes from 1146 to 1002 SASS instructions (986 without the +-Inf guard), the micro gain is about 3-4% but under the bar, and end to end it is a tie.

End to end (FLUX.3 klein base, int8, 1024x1024, 20 steps)

Each arm is a fresh process with a fresh Studio home, warmed up first, 3 renders per arm. The arms are interleaved main / head / head / main / main / head / head / main on one VM.

L4, s/step (median of 3 renders per arm):

arm main head
1 0.94182 0.93302
2 0.94128 0.93466
3 0.93958 0.93619
4 0.93747 0.93469
median (spread) 0.94043 (0.46%) 0.93467 (0.34%)

The head is 0.61% faster per step, and every head arm is faster than every main arm. All 12 head renders are byte-identical PNGs to the matching main renders (LPIPS 0), and all 43 attention modules ran the int8 kernel in every arm. The gain is a small share of the step because attention is only part of the klein base step.

RTX PRO 6000: s/step (median of 3 renders per arm):

arm main head
1 0.15048 0.15017
2 0.15078 0.15017
3 0.15066 0.15014
4 0.15055 0.15018
median (spread) 0.15061 (0.20%) 0.15017 (0.03%)

The head is 0.29% faster, which is about the main-vs-main spread, so this card is a tie end to end: attention is a small part of a klein base step there. All 12 head renders are byte-identical PNGs to the matching main renders (LPIPS 0). All 43 attention modules ran the int8 kernel in every arm, and the head arms launched the native_p kernel.

Scope

  • Only head dim 128 on sm89 and sm120, the cards measured. Every other card and head dim compiles the kernel exactly as before (native_p absent = the old path).
  • No new graph break, launch or host sync. The change is inside the kernel; native_p is part of the compiled-kernel key and of the plan key.
  • Kill switch: UNSLOTH_DIFFUSION_INT8_ATTENTION_NATIVE_P=0.

Tests

  • test_native_p_reaches_the_kernel_as_a_define: the define, and that no card below sm89 sets it.
  • test_native_p_kill_switch_compiles_the_magic_path (CPU): with UNSLOTH_DIFFUSION_INT8_ATTENTION_NATIVE_P set to 0, off, false or no, kernel_defines(128, kernel_variant(cfg, ...)) has no NATIVE_P for either path and the kernel key changes; other values keep it.
  • test_native_p_switch_is_part_of_the_race_namespace (CPU): the switch is in _library_versions().
  • test_native_p_keeps_the_products_and_converts_each_probability_once (NVRTC, CPU): same products, copies and ex2 count, one conversion per probability, and the old path has none.
  • test_native_p_packs_the_same_bytes_for_every_float (GPU): the 2^32 sweep, with the truncating control that must fail.
  • test_native_p_does_not_change_the_output (GPU): sink and plain, 300 and 1039 keys.

The CPU tests pass locally with the whole file (71 passed). The GPU tests passed on L4 and on RTX PRO 6000 before the +-Inf guard; with the guard, the same checks ran through the oracle above on both cards rather than through pytest.

Not covered

sm80, sm86 and sm75 keep the old path and were not timed with the new one. sm90 and sm100 have no int8 attention config, so nothing changes there.

…h conversion instructions on sm89 and sm120

The probability bytes of P.V were rounded by adding 2^23 + 2^22 after a clamp at 255 and packed with a shift-add.
native_p 1 (per card, head dim 128 on sm89 and sm120) rounds with cvt.rni.s32.f32 and packs with
cvt.pack.sat.u8.s32.b32, which ptxas fuses into one F2IP per two keys: the tile loop of the sink-path kernel goes
from 1146 to 986 SASS instructions on sm89. Round to nearest even then saturate at 255 gives the bytes of clamp
then round for every fp32 input but NaN (checked over all 2^32 bit patterns), so the output is bit for bit the same.
The scores and P.V sums keep the magic-constant frame: reading their bits as floats costs nothing, and a converted
score rounds differently.

L4, B1 H24 D128, sustained per call: sink path 3.0-4.1% faster, plain 2.8-3.4%, 4096 to 45056 tokens.
RTX PRO 6000: sink path 1.6-3.0%, plain 0.7-2.5%.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 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-22T11:22:10.480646Z 0838bc1 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

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 606423168a

ℹ️ 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".

…s the int8 attention kernel without native_p

kernel_variant drops native_p from the chosen config when the switch is 0 / off / false / no, so the NATIVE_P
define and the compiled-kernel key change and the MAGIC_F path runs (the same bits). The switch is part of the race
namespace (_library_versions), so a decision made with one setting is not reused with the other.
…e equal on +-Inf score scales

A +-Inf in a Q row or a K group makes the score scale of that key group infinite and every exponent of it NaN. The
MAGIC_F path clamps those to 255; the conversion of the native path gave 0, so an Inf in Q left l = 0 and a non-finite
output row, and an Inf in K gave those keys weight 0. The native path now sets the group's offset to +inf: its keys
(bits as a float always above 2^22) saturate to 255 and its padded keys (-3e38) become NaN and convert to 0, the bytes
of the MAGIC_F path. NaN inputs never reach a scale (amax uses fmaxf, the scale is floored at 1e-30).

One compare and one select per row and key group: the sm89 sink-path tile loop is 1002 SASS instructions (986
without the guard, 1146 on the MAGIC_F path).

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 0838bc1332

ℹ️ 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 ed8dff7 into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the studio-int8-attn-occ2 branch November 22, 2026 17:12
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…*31 guard, CUTLASS race key covers its helpers (#18968)

## Summary

Follow-ups from a kernel-rules pass over the recent INT8 attention,
CUTLASS race cache and FLUX.2 reference preprocessing PRs (#18917,
#18797, #18786). Three commits, one per fix:

1. **FLUX.2 edits: the GPU reference preprocess probe runs at load, not
inside the first edit request (#18917).**
`install()` patches the image processor before placement, so the
per-device probe (Triton compile of the two Lanczos kernels plus two
Pillow comparison images) ran on the first edit request under the module
lock. A new `diffusion_ref_preprocess.warm(pipe)` runs the same probe
for the pipe's execution device right after placement (after the graph
arming, before the load record). It is a no-op for families without the
installed preprocess. The lazy probe stays as the fallback for a device
`warm()` never saw.
2. **FLUX.2 edits: references past 2**31 elements stay off the 32-bit
Lanczos kernels (#18917).**
The kernels index one image with int32 flat offsets. `lanczos_resize`
now refuses a resize whose source, intermediate (either pass order) or
output reaches 2**31 elements, about 715 MP. The FLUX.2 preprocess
checks before it uploads the pixels, so such an image takes the CPU
path.
3. **INT8 GEMM: CUTLASS race verdicts are keyed on the helpers the race
code calls (#18797).**
`_RACE_SOURCES` hashed the listed race functions but not the helpers
they call. An edit to `_xs_dtype` (the activation-scale dtype the race
times), `_payload`, the act quant, the row-bucket bookkeeping or the
race switches therefore kept stale verdicts.
   - Those helpers are now keyed.
- The few left out on purpose are listed in `_RACE_UNKEYED`: the key
builders, the library loader (the library is hashed by its bytes) and
the tile probe's own persistence.
- A new test walks the call closure across the three keyed modules,
including `cut.x` calls, and fails on any helper that is in neither
list.
- Performance only: tile correctness is still the per-card bit-exact
probe. Every card re-races once after this update.

## Evidence

### 1. First edit request, L4 (Colab, torch 2.14.1+cu130, Triton 3.8.0,
diffusers 0.43.0)

Each run is a fresh process with base (main) and head interleaved, 5
runs per arm. The images are 2048x1536 and then 1800x2400, resized to 1
MP and cropped. "Cold" uses an empty Triton cache per process; "warm"
uses a pre-populated one.

| Triton cache | Arm | Load step (install + warm), ms | First request,
ms | Second request, ms |
|---|---|---|---|---|
| cold | main | 0.68 [0.64, 0.70] | 2601.6 [2577.2, 2609.3] | 28.2
[27.4, 28.7] |
| cold | head | 2564.8 [2553.5, 2569.1] | 33.5 [32.9, 34.7] | 28.3
[27.9, 30.0] |
| warm | main | 0.65 [0.63, 0.68] | 1639.4 [1637.0, 1646.5] | 28.1
[27.6, 30.5] |
| warm | head | 1606.5 [1604.1, 1614.7] | 32.7 [32.3, 34.7] | 27.5
[27.2, 27.8] |

- The first request drops from 2.6 s to 34 ms with a cold Triton cache,
and from 1.6 s to 33 ms with a warm one. The base spread is 1.2%, so
this is far outside the noise.
- The same time now lands in the load step.
- The second request is a tie (A/A control).
- Output tensors hash the same on main, on head and on the stock CPU
path, for both images and all 10 runs per arm. `STATS` shows `gpu 2,
fallback 0` in every run, so the GPU path ran.

### 2. Folded sink kernel at head dim 128 on sm80 and sm120 (#18786)

The question was whether the folded sink path is right on cards where it
had only been checked offline. It is, so the code is unchanged.

- **Setup:** current main, fold on vs
`UNSLOTH_DIFFUSION_INT8_ATTENTION_RESID_FOLD=0`, each arm twice. 15
cases: Flux shape, 40 sink keys, long calls, fp16 / fp32, strided, batch
2, no-clip, hd64. Compared against fp32 reference attention.
- **A100-40GB (sm80, qreg 1):**
- Covers both hd128 configs: wpc 4 below 4608 keys and wpc 8 from 4608
on.
- The fold engaged on every clipping hd128 case: one launch instead of
two.
- Fold on vs off differs by at most 0.125 in bf16. The 40-key case
reaches 0.5, which is one bf16 step at those magnitudes.
- The folded output is nearer fp32 in every bf16 clipping case. Flux
shape rel_l2 0.0130402 -> 0.0129988; 8192 keys 0.0085737 -> 0.0085072.
  - Non-clipping and non-sink cases are bit-identical.
- **RTX PRO 6000 (sm120, qreg 0, native probability pack from #18870):**
- Same picture. Flux shape rel_l2 0.0144564 -> 0.0144301; 8192 keys
0.0160356 -> 0.0160310.
- The 40-key case is a tie: 0.0208967 vs 0.0209146, with mean abs error
lower.
- **GPU pytest subset:** 57 passed on both cards in both arms, plus one
failure that is also there with the fold off:
`test_a_plan_whose_sink_path_loses_its_race_runs_torch_attention`.
- **sm86 has no cloud tier.** Its hd128 config compiles the same defines
as the A100 long-call config: HD 128, BN 128, NQ 1, WPC 8, STAGES 2,
QREG 1. The only arch branch in the kernel source is `__CUDA_ARCH__ <
800`, so sm86 runs the same fold code path that passed on A100. It stays
enabled.

## Tests

- `tests/test_diffusion_ref_preprocess.py`:
- The probe runs in `warm()` and not on the first request (the probe is
mocked to raise).
  - An unwarmed device still probes lazily.
  - `warm()` is a no-op without the install.
  - The load calls `warm` after placement.
- The int32 size limit, including that it is checked before the pixel
upload.
- `tests/test_diffusion_int8_cutlass_race_key.py`:
- Every function the keyed race code reaches is keyed or listed as
deliberately unkeyed.
  - The unkeyed names still exist.
- Each new test fails on main.
- Targeted CPU files pass: `test_diffusion_ref_preprocess.py` 34,
`test_diffusion_ref_preprocess_gate.py` 5,
`test_diffusion_int8_cutlass_race_key.py` 29,
`test_diffusion_int8_cutlass_lib_digest.py` 5,
`test_diffusion_int8_cutlass_probe_persist.py` 8.

## Not covered

- No real FLUX.2 model load was timed end to end. The L4 numbers come
from the image processor with the real kernels, on a pipe placed on the
GPU.
- sm86 was not run on hardware. The case for it rests on the identical
compiled defines above.
- Windows was not run. Nothing here is OS specific.
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