Skip to content

Studio: fuse the int8 ConvRot rotation into its producers on FLUX.2 / FLUX.3 (ConvRot cost +8.7% to +0.5%) - #17230

Merged
danielhanchen merged 6 commits into
mainfrom
studio-int8-convrot-fused
Nov 9, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
studio-int8-convrot-fused

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Summary

Follow-up to #17209 (int8 ConvRot by default for FLUX.2 klein and FLUX.3 klein), and the open item from #14982.

On the int8 GEMM path every rotated Linear quantized its own input with rotq_h16: the producer kernel wrote the bf16 activation, and rotq_h16 read it back, rotated it (group-256 Hadamard) and quantized it. This PR removes that second pass where it costs the most, without changing a single code or scale:

  • Shared rotation + act quant. Linears reading the same activation quantize it once: Q / K / V in the FLUX.2 double blocks (image and text streams), and Q / K / V plus the MLP input in every FLUX.3 block (they all read the same modulated input). Same op on the same tensor, so this is exact.
  • rotq_h16x: the rotation runs in front of the producer's own loads. It is rotq_h16 (same 16 x 16 two-stage rotation, amax, bf16 rounding of scale and product) with the loads of the tensors the producer would have combined:
    • the MLP down projection reads the two SwiGLU halves straight from the linear_in output (strided, no copy), so the SiLU product is never written;
    • the FLUX.2 single-block output projection (12288 wide, about 57% of the rotation bytes) reads the attention output in the layout the attention backend returned (any strides) plus the SwiGLU halves, so neither the product nor the concat is written.
  • The shared int8 paths now engage inside torch.compile. _swapped_rec checked forward.__func__ is _linear_forward, which Dynamo resolves to False, so every shared path fell back to stock in the compiled forward (also the existing Qwen-Image-2.1 shared Q / K / V and SwiGLU paths and MiniMax-H3's shared Q / K / V). The swap now stores the bound forward it installs and the traced check compares by identity.
  • Probe verdicts persist per card and toolchain. The rotation probes cost about 50 s per fresh process on an L4 even with a warm Triton cache (the new producer probe another 14 s). A passing device's verdicts are stored next to diffusion_probe_cache's file, keyed by its fingerprint (torch, CUDA, driver, Triton, torchao, card UUID, the UNSLOTH_DIFFUSION_* switches) plus the kernel sources; any mismatch probes again.

Folding the rotation into the previous Linear's weights (QuaRot style) is not exact here: every rotated input comes from LayerNorm + modulation, SwiGLU or attention, none of which commute with a block Hadamard, and the producing Linears are themselves int8 (rotating their output channels changes their per-channel scales). So the fusion is in the kernels instead.

Each patch checks its Linears per call (swapped rotated int8, no hook, stock diffusers body by fingerprint) and otherwise runs the stock code; any device whose probe fails keeps the current path. Kill switches: UNSLOTH_DIFFUSION_FLUX_CONVROT_FUSED=0 (all of it), UNSLOTH_DIFFUSION_INT8_ROTQUANT_PRODUCER=0 (keeps only the shared quants), UNSLOTH_DIFFUSION_PROBE_CACHE=0 (probe every load).

Parity

rotq_h16x against the current compiled path (Inductor writes the bf16 product / concat with Studio's emulate_precision_casts, then rotq_h16), FLUX.2 / FLUX.3 klein shapes at 1024x1024, v1 and v2 quant, A100 and L4 (torch 2.14.1, Triton 3.8):

case M x K codes equal scales equal
FLUX.2 single-block output projection (attention + SwiGLU) 4608 x 12288 100% 100%
same, batch 2, head-major attention output 2200 x 12288 100% 100%
MLP down projection, image / text stream 4096 / 512 x 9216 100% 100%
FLUX.3 MLP down projection 4608 x 9216 100% 100%

On real activations (every producer-fused call outside a CUDA graph capture recomputed the current way, in the render itself): klein 90 of 90 calls and FLUX.3 79 of 79 calls with identical codes and scales, on L4 and A100.

Whole renders: FLUX.2 klein and Qwen-Image-2.1-Turbo are bit-identical to the merge base (16 of 16 images, both cards for klein). FLUX.3 klein renders are not bit-reproducible across processes even on the merge base: unlike flux.2-klein, the FLUX.3 families do not pin Inductor's reduction configs, so each process picks its own. A/A on A100 (8 renders per arm, fresh process each):

pair LPIPS mean / max identical
merge base vs merge base (second process) 3e-5 / 4e-5 0 / 8
this PR vs this PR (second process) 3e-5 / 5e-5 0 / 8
this PR vs merge base 3e-5 / 5e-5 0 / 8
this PR (second process) vs merge base (second process) 0 / 0 8 / 8
kill switch vs merge base 3e-5 / 4e-5 0 / 8

So the difference is the merge base's own process-to-process spread; when the two processes picked the same configs the renders were identical. On some L4 VMs that spread is far larger: on one, two merge-base processes differed by LPIPS 0.0131 mean (0.039 max) and this PR vs the merge base by 0.0115 (0.036), with every producer-fused call still identical to the current path (79 / 79).

Accuracy

16 renders (8 prompts x 2 seeds, 1024x1024), LPIPS (alex) against the bf16 render. plain is the ConvRot kill switch (plain int8), #17209 the merge base, this PR the head; every int8 arm quantizes at load.

model card plain int8 #17209 this PR this PR vs #17209
FLUX.2 klein 4B L4 0.0977 0.0421 0.0421 identical (16 / 16)
FLUX.2 klein 4B A100 0.0923 0.0410 0.0410 identical (16 / 16)
FLUX.3 klein L4 0.0538 0.0182 0.0182 LPIPS 3e-5 mean, 9e-5 max
FLUX.3 klein A100 0.0465 0.0161 0.0161 LPIPS 4e-5 mean, 1e-4 max (kill switch arm: the same)

Speed

Colab, compiled default speed mode with CUDA graphs, resident, torch 2.10. Three fresh processes per arm, alternating, median per-step time; A/A spread is max - min over the three.

model card plain int8 #17209 this PR ConvRot cost before / after A/A spread
FLUX.2 klein 4B (4 steps) L4 0.4122 s 0.4403 s 0.4204 s +6.8% / +2.0% <= 0.9%
FLUX.2 klein 4B A100-40 0.1238 s 0.1280 s 0.1256 s +3.4% / +1.5% <= 0.5%
FLUX.3 klein (16 steps) L4 0.5361 s 0.5827 s 0.5387 s +8.7% / +0.5% <= 0.7%
FLUX.3 klein A100-40 0.1556 s 0.1661 s 0.1569 s +6.8% / +0.9% <= 0.6%
Qwen-Image-2.1-Turbo (8 steps, hosted ConvRot file) A100-40 0.2343 s 0.2254 s -3.8% vs #17209 <= 0.4%

Per image: FLUX.3 klein on L4 is 8.88 s plain int8, 9.64 s with #17209 and 8.93 s with this PR; on A100 2.60 / 2.77 / 2.62 s.

Per-kernel GPU time for one render (torch profiler, ms; inductor is every Inductor-generated kernel):

model / card arm rotq_h16 rotq_h16x inductor all kernels
klein / L4 plain 127.6 1929.7
#17209 108.8 (404 calls) 270.0 2024.9
this PR 26.0 (204) 123.3 (120) 151.6 1952.3
klein / A100 plain 66.7 548.3
#17209 44.2 (404) 73.5 566.3
this PR 12.1 (204) 47.2 (120) 51.7 558.4
FLUX.3 / L4 plain 536.3 8676.7
#17209 795.3 (3168) 1262.4 9474.3
this PR 173.2 (1056) 478.4 (528) 669.2 8743.0
FLUX.3 / A100 plain 167.7 2506.0
#17209 310.2 (3168) 323.2 2676.4
this PR 78.3 (1056) 172.5 (528) 227.2 2526.4

What is left on A100 is the rotation's own arithmetic (the 16 x 16 two-stage rotation is compute bound there; on L4 the fused kernel is bandwidth bound and beats the plain int8 producer kernel at the same shape). The remaining rotated inputs are the LayerNorm + modulation outputs (one shared quant per block); fusing the rotation into that kernel too is the next step.

All arms: 0 graph breaks, 0 recompiles, the same number of compiled graphs. Each process ran the fused kernels (klein: 120 rotq_h16x calls and 204 instead of 404 rotq_h16 calls per render; FLUX.3: 528 and 1056 instead of 3168), and with UNSLOTH_DIFFUSION_FLUX_CONVROT_FUSED=0 none.

Load

With the persisted verdicts, the second start on an L4 reaches its first klein image in 31 s instead of 73 s (first image, 1024x1024, cold Inductor cache in both); the merge base takes 61 s every start. The first start pays the probes once (about 12 s more than the merge base for the producer probe).

Tests

studio/backend/tests/test_diffusion_flux_convrot_fused.py:

  • each patched FLUX.2 / FLUX.3 block equals stock bit for bit with the int8 pieces replaced by the plain modules, eager and under torch.compile(fullgraph = True), and counts one shared quant / one producer call where expected;
  • unswapped Linears never reach the int8 paths; a drifted diffusers body keeps stock; uninstall restores every patched attribute; the kill switch;
  • _swapped_rec sees a swapped Linear inside a compiled block and not a forward replaced after the swap (fails on the merge base);
  • the probe verdict cache round-trips and misses on a changed fingerprint;
  • GPU: rotq_h16x equals the current path bit for bit (v1 / v2, one-pass, two-pass, padded, concat, batch 2), declines what it cannot read, and its switch.

On an A100 (torch 2.10) the ConvRot / int8 GEMM / autoopt test files fail the same 3 tests by ID on the merge base and on this branch (pre-existing); the new file passes. The related CPU subset passes.

Not covered here

  • Folding the rotation into the LayerNorm + modulation kernel (the inputs of Q / K / V and the MLP); measured cost left: +2.0% klein L4, +1.5% klein A100.
  • MiniMax-H3: its shared Q / K / V path now also engages under compile (the _swapped_rec fix) but was not run here. Qwen-Image-2.1 was run only as Turbo on A100 (bit-identical, -3.8% per step).
  • Cards other than L4 and A100-40 (no T4 path changes: fp16 cards do not use this kernel), FLUX.3 klein base, offloaded loads (the shared paths decline hooked modules by design), LoRA (declines, stock path).
  • The kernel's FMA flip check did not flip: with enable_fp_fusion on, the outputs were still bit-identical on these shapes, so that guard is unproven here.

…on FLUX.2 / FLUX.3

The rotated int8 Linears quantized their own input with rotq_h16, so every
producer wrote its bf16 activation and the rotation kernel read it back.

- Q / K / V (and on FLUX.3 also the MLP input) share one rotation + act
  quant of their common input (shared_rotq_linears).
- rotq_h16x: rotq_h16 with the producer's loads in front. The MLP down
  projection reads the two SwiGLU halves straight from the linear_in
  output, and the FLUX.2 single-block output projection reads the
  attention output in its native layout plus the SwiGLU halves, so the
  product and the concat never reach HBM. Same rotation, amax and
  rounding as rotq_h16: bit-identical codes and scales.
- Probed per device; any miss keeps the stock path. Kill switches:
  UNSLOTH_DIFFUSION_FLUX_CONVROT_FUSED=0 (all of it) and
  UNSLOTH_DIFFUSION_INT8_ROTQUANT_PRODUCER=0 (shared quants only).
_swapped_rec checked forward.__func__ is _linear_forward, which dynamo
resolves to False, so every shared rotation + act quant path (and the new
producer fusion) fell back to stock in the compiled forward. The swap now
stores the bound forward it installs and the traced check compares the
instance forward with it by identity. The FLUX gates compare classes
instead of functions for the same reason; the block tests also run each
patched block under torch.compile(fullgraph=True).
The rotq / h16 / SwiGLU / producer probes took about 50 s + 14 s in every
fresh process on an L4, also with a warm Triton cache. A passing device's
verdicts are stored next to diffusion_probe_cache's file, keyed by its
fingerprint (torch, CUDA, driver, Triton, torchao, card UUID, the
UNSLOTH_DIFFUSION_* switches) plus the kernel sources; any mismatch probes
again. UNSLOTH_DIFFUSION_PROBE_CACHE=0 turns it off.
@danielhanchen danielhanchen self-assigned this Nov 9, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 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-09T12:58:48.800791Z 026178a 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: eadb419d53

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

Copy link
Copy Markdown
Member Author

Source lint is red on this PR only. The risky-loader gate flags the new helper:

1 risky loader call site(s) not in the baseline:
  studio/backend/core/inference/diffusion_flux_convrot_fused.py:118  [dynamic-import] import_module

_module(name) calls importlib.import_module(name) on a parameter, so the gate cannot see what gets imported. If every caller passes a fixed diffusers module path, importing those modules by literal name, or keeping a small table of allowed names, clears the gate without a baseline entry. Otherwise, python scripts/lint_risky_loaders.py --update plus a written reason in scripts/risky_loaders_baseline.json records it as trusted.

@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: 026178ad92

ℹ️ 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 f4d17f4 into main Nov 9, 2026
@danielhanchen
danielhanchen deleted the studio-int8-convrot-fused branch November 9, 2026 13:57
oobabooga pushed a commit to oobabooga/unsloth that referenced this pull request Nov 10, 2026
…n forward (unslothai#17337)

## Summary

FLUX.3 klein runs 28 of its 33 blocks as joint blocks
(`Flux3SingleTransformerBlock`). unslothai#17230 made each FLUX.3 block quantize
its modulated input once for Q / K / V and the MLP input together. On
current main that sharing never engages for the joint blocks:

- `diffusion_cond_blocks.prepare` installs its span-aware joint block
forward at load (one modulation row per span for reference images),
before the regional compile;
- `diffusion_flux_convrot_fused` then looks for the stock diffusers body
on `Flux3SingleTransformerBlock.forward`, finds the span forward
instead, and declines (`patches {... 'f3_single': False}` in the load
log).

So every joint block quantizes its input twice per step: once for Q / K
/ V and once more for `ff.linear_in`. On an L4 that is one extra
`rotq_h16` pass of about 0.24 ms per joint block per step (28 x 16 = 448
extra launches per 16 step image).

This PR:

- applies the joint block patch to the stock forward that the span
forward calls whenever a render has no reference span (the text to image
path), kept in `diffusion_cond_blocks._PATCHED_SINGLE`;
- for renders with a reference span, the span body now asks one helper
for the attention and MLP outputs (`JOINT_ATTN_FF`, set by
`diffusion_flux_convrot_fused` while it is installed). It returns None,
and the stock modules run, whenever the block is not on the swapped int8
ConvRot Linears.

Both paths run the same rotation and act quant on the same tensor as
before, so the codes and scales are identical. Uninstall restores the
recorded stock forward and clears the hook. Kill switch:
`UNSLOTH_DIFFUSION_FLUX3_SPAN_FUSED=0` keeps the separate MLP-input
quant (`UNSLOTH_DIFFUSION_FLUX_CONVROT_FUSED=0` still turns off all of
it).

## Results

Colab L4, torch 2.13 / Triton 3.7.1, compiled default speed mode with
CUDA graphs, resident, hosted int8 ConvRot checkpoint (what an INT8 pick
loads). One VM for every row; each process is a fresh load, main and
this PR alternating, median of 3 renders per process.

FLUX.3 klein, 1024x1024, 16 steps:

| | s/img per process | median | s/step median | A/A spread (s/img) |
|---|---|---|---|---|
| main | 9.087 / 9.118 / 9.087 | 9.087 | 0.5478 | 0.34% |
| this PR | 8.948 / 8.948 / 8.960 | 8.948 | 0.5392 | 0.13% |

-0.14 s per image (-1.5%); the slowest PR process is faster than the
fastest main process. Torch peak allocated memory is unchanged (11.64
GiB).

Kernel census, one profiled render each on the same VM: `rotq_h16` goes
from 1504 to 1056 launches (350 to 230 ms); the int8 GEMM (3168 launches
each), attention, `rotq_h16x` and the Inductor kernels are within 0.3%.
The load log now reports `'f3_single': True`. 0 graph breaks, 0
recompiles, 3 compiled graphs in every process.

Accuracy, 16 renders (8 prompts x 2 seeds), LPIPS (alex) against the
bf16 render on the same VM:

| arm | mean | max |
|---|---|---|
| main | 0.0175 | 0.106 |
| main, second process | 0.0175 | 0.106 |
| this PR | 0.0159 | 0.088 |
| this PR, `UNSLOTH_DIFFUSION_FLUX3_SPAN_FUSED=0` | 0.0166 | 0.103 |

Paired, this PR minus main: -0.0015 (95% CI -0.0057 to +0.0023). Every
producer-fused call checked against the current path on the real
activations matched (79 / 79 calls, codes and scales). FLUX.3 renders
are not bit-reproducible across processes (each process picks its own
Inductor reduction configs, as noted in unslothai#17230): the kill switch arm,
which runs exactly main's path, differs from main by LPIPS 0.0077 mean,
the same as this PR (0.0079).

No change on the other int8 ConvRot families sharing these paths (same
VM):

| model | main s/img | this PR s/img | A/A spread | images vs main |
|---|---|---|---|---|
| FLUX.2 klein 4B (4 steps) | 2.089 | 2.086 | <= 0.8% | identical (16 /
16) |
| Qwen-Image-2.1-Turbo (8 steps) | 6.743 | 6.742 | <= 0.4% | identical
(16 / 16) |

## Tests

`studio/backend/tests/test_diffusion_flux_convrot_fused.py`, with the
span forward installed first (as the load does):
- a joint block with and without a reference span, eager and under
`torch.compile(fullgraph = True)`, equals stock bit for bit and makes
one shared quant call covering Q, K, V and the MLP input;
- install reports `f3_single`, is idempotent, and uninstall restores the
recorded stock forward and clears the hook;
- the kill switch keeps the separate quant.

All 6 new tests fail on main and pass here. The rest of the file and the
FLUX.3 / cond blocks test files fail the same tests by ID on main and on
this branch (CPU, missing optional deps).

## Not covered here

- Budgeted loads that stream the denoiser blocks: their Linears carry
offload hooks and the shared paths decline hooked modules by design, so
nothing changes there.
- Renders with reference images (the span path) are covered by the CPU
tests only, not by a GPU render.
- Cards other than the L4 (A100, RTX PRO 6000, B200) and FLUX.3 klein
base were not run.
danielhanchen added a commit that referenced this pull request Nov 11, 2026
…aced per arch (FLUX.3 klein INT8 -19.8% on L4) (#17486)

## Summary

Studio's INT8 ConvRot diffusion path runs its int8 GEMM on a Triton
kernel (`i8mm_dq`) where the arch gate allows it, and on cuBLAS
`_int_mm` plus a separate dequant everywhere else. That leaves three
gaps:

- Turing (T4) never gets a fused GEMM: Triton cannot lower the int8 dot
on sm75, and the swap only takes bf16 input.
- Every sm8x card falls back to cuBLAS on Triton 3.8 (torch 2.14), by
design (#17036, triton-lang/triton#12486 register spills). Colab now
ships torch 2.14.1 + Triton 3.8.0, so this is the default there today.
- Where Triton does run, it trails a compiled CUDA GEMM: on A100 the
Triton kernel is at 89-94% of a CUTLASS fused-epilogue GEMM, and on L4
the baseline's CUTLASS GEMM is the largest part of its per-image lead on
FLUX.3 klein INT8.

This PR adds a prebuilt (ahead-of-time) CUTLASS 2.x int8 GEMM with
torchao's dequant epilogue fused into it, for sm75 (fp16 out) and sm80 /
sm86 / sm89 (bf16 out). It works the same whatever Triton is installed,
is checked bit for bit against today's reference on every card before
use, and is raced per weight shape against today's path, so auto mode
never picks it where it is slower.

## What it is

- `studio/native_kernels/int8_gemm/`: one CUTLASS 2.x s8 x s8 -> s32
GEMM per tile, with an epilogue visitor that reproduces torchao's
epilogue op for op: `c * x_scale` in the x_scale dtype (int32 -> fp32 ->
bf16 rounds twice, as torch does; an fp16 x_scale computes in fp32, as
torchao does), the cast, `* w_scale` (rounded to the output dtype only
when the scale has it), `+ bias`, the final cast. Every product and sum
uses `__fmul_rn` / `__fadd_rn`, so nothing contracts into an FMA.
- sm80 family: 15 tiles, SASS for sm_80, sm_86 and sm_89, bf16 out,
x_scale bf16 / fp32, w_scale bf16 / fp32, with and without bias.
- sm75 family: 7 tiles, SASS for sm_75, fp16 out, x_scale fp16 / fp32,
w_scale fp16 / bf16 / fp32, with and without bias.
- The sm75 family also carries the epilogue of Studio's native W8A8
Linear (`diffusion_native_quant`), the module fp16-only cards load
FLUX.3 INT8 into: `(c * x_scale) * w_scale` in fp32, then one cast to
fp16.
  - No PTX: other archs never JIT it and keep their current path.
- The host side is a plain C ABI (`ui8_abi_version`, `ui8_num_tiles`,
`ui8_tile_info`, `ui8_has_kernel`, `ui8_gemm`), linked against the
static CUDA runtime, libstdc++ and libgcc. The Linux library needs only
glibc. There is no torch or Python ABI in it, so one binary per OS
serves every torch minor. It is built with CUDA 12.8, so it also runs on
CUDA 13 drivers.
- `diffusion_int8_cutlass.py` loads it with ctypes and launches it on
torch's current stream, so CUDA graph capture works. Absent, unloadable,
wrong ABI, ROCm or CPU torch, or `UNSLOTH_DIFFUSION_INT8_CUTLASS=0`:
today's path, unchanged.

## Numerics and the fail-closed probe

Every tile is probed once per card for every scale-dtype pair it serves.
The probe uses ragged M and N tails, K below and above one tile, with
and without bias, M = 1, and int32 products one or two units off a
16-bit rounding midpoint (both signs). Output is compared with
`torch.equal` against the generic torchao reference, which matches
`diffusion_int8_gemm.reference()` bit for bit for bf16 (unit test). A
tile that fails any case is never used. A failed launch at runtime drops
the prebuilt kernel on that card and runs the same math on today's path.

## Selection

When the int8 Linears are swapped, every distinct weight shape (N, K,
scale dtypes, bias) is timed on random operands at M = 512 and M = 4096
against today's path:

- the Triton kernel where Studio runs it today;
- otherwise cuBLAS `_int_mm` plus one read of its int32 output. This is
a lower bound on the stock cost, because the stock epilogue fuses into
its consumer under torch.compile.

A tile replaces today's path only when it is at least 2% faster. A
Linear whose large-M race keeps today's path is not touched, so it keeps
the Inductor-fused stock epilogue. Winners persist per card, torch,
CUDA, Triton, library build and source hash.

Kill switches:

- `UNSLOTH_DIFFUSION_INT8_CUTLASS=0`: the whole lever, and the install
step.
- `=1`: skip the race and always take the fastest probed tile.

On fp16-only cards, the native W8A8 Linear races its weight shapes on
its first eager forward, before any CUDA graph capture. Its eager
`_int_mm` path, the one CUDA graphs record, then runs the won tile in
place of `_int_mm` plus the fp32 epilogue. Its own rotation and
activation quant are untouched, and so is its compiled path.

The fused ConvRot rotation and activation quant (#17230) stay in front
of it unchanged. `rotq_h16` / `rotq_h16x` produce the same codes and
scales, and only the GEMM behind them changes. On sm75, where neither
the rotation kernel nor Triton runs, a won Linear runs the module's own
rotation and torchao's own fp16 activation quant, then the fp16 kernel.

## Distribution

- `.github/workflows/prebuilt-int8-gemm.yml`, dispatch only, in the same
shape as `prebuilt-cuda-wheels.yml`. It builds
`unsloth_studio_i8gemm-1.0.0-py3-none-manylinux_2_28_x86_64.whl` (in the
manylinux_2_28 container, CUDA 12.8 from NVIDIA's rhel8 repo) and
`...-py3-none-win_amd64.whl` (NVIDIA's Authenticode-checked installer,
MSVC x64, static runtime). It smoke-loads each wheel the way Studio does
on a GPU-less runner, signs with Sigstore under the `release-signing`
environment, and uploads to `prebuilt-wheels-cu13` only when `publish:
true`.
- `install_python_stack._ensure_int8_gemm()` runs after flash-attn. It
installs the wheel (about 3.3 MB, `--no-deps`) for an NVIDIA CUDA torch
on x86_64 Linux and Windows when the release carries it. Otherwise it
does nothing: no published asset, ROCm, macOS, no torch, or
`UNSLOTH_STUDIO_SKIP_I8GEMM_INSTALL=1`. Failures only warn.
- Windows: the same source builds with nvcc + MSVC; the baseline ships
CUTLASS 2.x int8 kernels on Windows from the same headers. The DLL has
no dependent DLLs (static CUDA runtime and MSVC runtime), and the loader
looks for `unsloth_i8gemm.dll`. The Windows wheel build has not run yet
(see below).

## Results

Microbench, held (power-settled) CUDA-graph timings at the hot shapes.
"Raced" is the per-step int8 GEMM time with the race applied, relative
to today's path on that card.

| card | stack | today's path | FLUX.3 klein | Qwen-Image-2.1 |
MiniMax-H3 |
|---|---|---|---|---|---|
| A100-40GB | torch 2.14.1, Triton 3.7.1 | Triton `i8mm_dq` | 0.924 |
0.929 | 0.953 |
| A100-40GB | torch 2.14.1, Triton 3.8.0 | cuBLAS | 0.723 | 0.763 |
0.771 |
| L4 | torch 2.14.1, Triton 3.7.1 | Triton `i8mm_dq` | 0.959 | 0.986 |
1.000 (no shape won) |
| L4 | torch 2.14.1, Triton 3.8.0 | cuBLAS | 0.808 | 0.832 | 0.959 |
| T4 (Kaggle) | torch 2.11.0 | cuBLAS + epilogue | 0.956 vs `_int_mm` +
one read; 0.588 vs `_int_mm` + eager epilogue | 0.930 / 0.644 | not run
|

Correctness in the same runs: 6.6 to 8.2 billion output elements per
card, compared bitwise against the reference. Every probed tile, every
scale-dtype pair, with and without bias, ragged and special-value cases:
0 mismatches. The 1-ulp negative control was caught on every card. On
A100 and L4 the Triton kernel also matched the same reference: 0
mismatches.

End to end, FLUX.3 klein INT8, 1024x1024, base (merge base 57a486b)
vs head, each in a fresh process, interleaved:

Colab L4, each arm a fresh process (fresh Studio home, so every head run
pays its race), base and head interleaved, 6 to 8 images per run:

| stack | today's path | base s/image (4 runs) | head s/image (4 runs) |
per image | s/step base -> head |
|---|---|---|---|---|---|
| torch 2.14.1, Triton 3.8.0 (Colab default) | cuBLAS | 10.53 / 10.53 /
10.59 / 10.54 | 8.45 / 8.46 / 8.35 / 8.45 | -19.8% | 0.640 -> 0.510 |
| torch 2.13.0, Triton 3.7.1 (fresh CUDA 13 install) | Triton `i8mm_dq`
| 8.89 / 8.87 / 8.88 / 8.88 | 8.55 / 8.60 / 8.50 / 8.60 | -3.6% | 0.535
-> 0.516 |

- A/A noise: base2, a second base process, landed at 10.54 and 8.84
s/image, inside 0.6% of base.
- Head on Triton 3.8 (8.45 s) is faster than base on Triton 3.7 (8.88
s), so a torch 2.14 install no longer loses the fused path.
- The race won all 3 of FLUX.3's weight shapes on L4 (3072x3072,
18432x3072, 3072x9216), at both M buckets, against both baselines. 1542
prebuilt-kernel calls per run, no graph breaks, no recompiles.
- The race costs about 3.5 s on a cold first load (time to first image
102 -> 106 s on Triton 3.7). It is cached per card and toolchain after
that.
- Kill switch: headks (`UNSLOTH_DIFFUSION_INT8_CUTLASS=0`) gives 10.53
s/image, 0 prebuilt calls, and images identical to base (8 of 8).

Bit-exactness in the product flow: every prebuilt-kernel output during a
real FLUX.3 render was compared with the eager reference on the same
inputs (`I8_VERIFY`): 750 of 750 calls, 0 mismatching elements, in each
of two head processes. Studio's forced Triton kernel gave 598 checked
calls, 0 mismatching elements.

Images are not bitwise reproducible across processes on this stack, even
for the same arm: two head processes differ by LPIPS 0.0055 (max 0.011),
and two base processes on torch 2.13 by 0.0061. So head vs base cannot
be judged by image identity. Head vs base LPIPS (0.0057 on torch 2.13)
is inside that A/A spread.

On torch 2.14.1, with four processes (two head, two with Studio's own
Triton kernel forced on):

- The two forced-Triton processes differ from each other by LPIPS
0.0066.
- One head process and one Triton process came out at LPIPS 0.00001.
- Every layer was bit-exact in every process.

The image-level drift is in the stack, not in either GEMM. On that stack
the cuBLAS base was reproducible across processes (8 of 8 images
identical), and so was the kill switch against it.


Kaggle T4, torch 2.11.0, FLUX.3 klein INT8, four base and four head
processes interleaved:

- base: 47.15 / 47.21 / 47.16 / 47.17 s/image.
- head: 47.18 / 47.10 / 47.12 / 47.15 s/image.

No change. FLUX.3 on fp16-only cards loads into Studio's native W8A8
Linear. Its eager forward runs the compiled `_w8a8_rows` function, which
keeps cuBLAS and lets Inductor fuse the epilogue into one pass. Against
that path the microbench margin on Turing is about 4% of GEMM time, and
the prebuilt kernel is not on it.

The prebuilt kernel takes the uncompiled `_int_mm` path:

- CUDA graph capture;
- hosts with no Inductor runtime (for example Windows without Triton),
where the microbench shows 0.59x of the eager epilogue.

On T4 the probe, the race (551 launches, all bit-exact against the
native reference) and the GPU unit tests pass. Images match base at the
A/A level: LPIPS 0.00001 for both head vs base and base2 vs base.

## Tests

- `tests/test_diffusion_int8_cutlass.py` (CPU): family and switch gates,
broken or missing library, ROCm, and the wheel found without importing
it. It checks that the generic reference matches Studio's bf16 reference
and the fp16 fused path's torchao epilogue bit for bit. It also covers
op-body dispatch (winner, lost small-M race, failed launch dropping the
plan), the per-card and per-bias plan keys, the race margin, and that
the build generator and loader agree on ABI and dtype codes.
- With `UNSLOTH_DIFFUSION_INT8_CUTLASS_LIB` set on a GPU: bit-exact
launch per probed tile, and launch inside a CUDA graph.
- Existing `test_diffusion_int8_gemm*.py`,
`test_diffusion_int8_fused.py` and `test_diffusion_fp16_card_int8.py`:
unchanged results.

## Not covered here

- Windows: the `win_amd64` wheel build and a Windows GPU run did not
run. The build steps follow the existing Windows CUDA jobs, and the
library is plain C ABI with static runtimes.
- The workflow itself (manylinux container build, signing, publish) has
not run in CI. The same `build.py` / `make_wheel.py` built and loaded
locally (glibc, no GPU) and built on Colab L4 / A100 and Kaggle T4 with
nvcc 13.0 for the measured runs. The measured binaries were built on the
VMs, not by the workflow.
- sm86 (RTX 30) and sm87: no card in the pool. They run the sm_86 SASS,
or the sm_80 SASS on sm87, behind the same probe and race. Not measured.
- A100 end to end; Qwen-Image-2.1 and MiniMax-H3 end to end. Microbench
only.
- L4 deep-K shapes (K >= 9216 at large M; FLUX.3's own shapes all won):
the prebuilt tiles trail the Triton kernel by up to 26%, so the race
keeps Triton there. MiniMax-H3 on L4 with Triton 3.7 gets no gain.
- T4 end to end: no gain (above). Wiring the kernel into the compiled
native function is left for a follow-up.
- Image identity across processes: not reproducible for the fused arms
on these stacks (above). Bit-exactness is shown per layer in the product
flow and per tile in the probe and microbench.
- `test_no_compiled_variant_spills_to_local_memory` fails on the L4 GPU
leg (torch 2.14.1, Triton 3.8.0). It forces the existing Triton kernel,
which spills there (triton-lang/triton#12486). Not re-run on the base
tree.
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