Skip to content

Studio diffusion: cut the int8 ConvRot overhead (one rotation per shared input, SwiGLU fused into the down quant, factored rotation kernel) - #14982

Merged
danielhanchen merged 8 commits into
mainfrom
studio-convrot-fused-cost
Oct 23, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-convrot-fused-cost

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

A user benchmark against ComfyUI measured Qwen-Image-2.1 1024px on an RTX 6000 Ada (sm89) at 0.319 s/step with the default int8 ConvRot transformer, 0.297 s/step with ConvRot off, and 0.294 s/step for ComfyUI running the same int8 ConvRot weights. On sm89 the fused int8 path was already engaged (fused-dequant GEMM plus the fused rotation + act quant kernel), so the 7-8% was the cost of the engaged ConvRot path itself. This PR removes most of it:

  1. One rotation + act quant per shared input. Q / K / V and the SwiGLU gate / value read the same activation, but each swapped Linear called the fused rotation kernel on its own: 7 kernels per block for 4 distinct inputs. The kernel is an opaque custom op, and Inductor does not merge identical opaque calls in an inference graph (fx_graph_cse only runs in the training partitioner). diffusion_int8_gemm.shared_rotq_linears quantizes once and runs each Linear's GEMM on the shared codes. The Q / K / V helper patch in diffusion_qwenimage21_fused (already fingerprinted for the sm86 / sm90 path) now uses it on the int8 GEMM path too, and the Qwen-Image-2.1 SwiGLU MLP gets a forward that does the same for gate / value. Same codes, so those outputs are bit-identical to the separate calls.
  2. SwiGLU product fused into the down projection's quant. The stock MLP wrote silu(gate) * value (bf16, [M, 12288]) to HBM and the down projection's rotation kernel read it back. With ConvRot off, Inductor fuses that product and the act quant into one kernel, so this round trip was the largest single difference between the two paths. convrot_swiglu_act_quant computes the product inside the rotation kernel (x * sigmoid(x) in fp32, bf16, times value, bf16, as the compiled stock MLP does) and writes only the int8 codes and row scales.
  3. H16 x H16 rotation kernel (rotq_h16). H256 = H16 (x) H16, so a 256-group rotates as H16 . X . H16 on its 16 x 16 view: one bf16 tensor-core dot and one fp32 dot, 32 multiply-adds per element instead of the dense 256 x 256 GEMM's 256. It now runs by default on every device where the dense kernel passed its probe, with its own probe.

Unchanged: GEMM kernels and tiles, CUDA graphs, compile (0 graph breaks, the same 3 graphs, no recompile across 4 renders with new prompts), copies (the same 33 device-to-device copies per forward). The arch tables (_ARCH_CONFIG, _ROTQ_CONFIG) are not touched.

Numerics

  • Shared quant: bit-identical to the per-Linear calls (same kernel, same input).
  • rotq_h16 sums in a different fp32 order than the dense GEMM, so a rotated value can round to the other bf16 neighbour. Measured on L4 against the stock rotation + torchao quant: about 1 code in 10^6 off by one step, no scale differences. Against an exact (fp64) rotation, H16 is slightly closer than the stock path (L4, M 16384, K 4096: 1 vs 5 codes off of 67M; K 12288 after SwiGLU: 44 vs 94 of 201M).
  • The probe gates rotq_h16 and the SwiGLU prologue per device against the stock path with codes_close: every code within two steps (v1's bf16 product can move a code by two), at most 1 in 10^4 codes off on rows whose scale matches, a differing row scale at most one bf16 step off.
  • UNSLOTH_DIFFUSION_INT8_ROTQUANT_H16=0 keeps the dense, bit-identical kernel (and turns the SwiGLU prologue off, since it only exists on H16). UNSLOTH_DIFFUSION_INT8_ROTQUANT_SWIGLU=0 keeps the stock product.

Results

Steady-state transformer forward (one denoise step), Studio in process (DiffusionBackend, Qwen/Qwen-Image-2.1, 1024x1024, 12 steps, cfg 1, cuda graph + compile defaults), median of the 20 steady forwards of renders 2-3, new prompt per render. Arms interleaved in one process each, same VM, main = the merge base. off = UNSLOTH_DIFFUSION_INT8_CONVROT=0 (plain int8 weights).

L4 (sm89, the engaged path of the reported card, ieee second stage), order main, head, off, head, main, head:

arm ms / step vs main vs ConvRot off
main, ConvRot on 823.0 / 854.9 +4.3% / +8.4%
this PR, ConvRot on 786.5 / 804.3 / 802.6 -4.4% (adjacent pair) / -5.9% -0.3% (adjacent) / +2.0%
main, ConvRot off 788.8

The L4 drifts slower across the session (power-capped, main A/A 823.0 vs 854.9), so the adjacent pairs are the comparison: this PR sits at the ConvRot-off level (786.5 next to 788.8), and is 4-6% faster than main next to it.

A100 (sm80, also on the fused GEMM path, tf32x3 second stage), same order:

arm ms / step spread
main, ConvRot on 228.3 / 228.4 0.1
this PR, ConvRot on 215.8 / 215.5 / 216.0 0.5
main, ConvRot off 211.2

ConvRot cost over plain int8 drops from +8.1% to +2.2% (A/A spread 0.1-0.5 ms against a 12.6 ms change).

Profile, per step (torch.profiler, 3 steps): fused rotation kernels 224 -> 128 (4 per block: QKV input, attention output, MLP input, down projection input), the Inductor silu * mul product kernel (32 per step) gone. Compile and graphs unchanged on both: 0 graph breaks, 3 graphs after every render, no recompile on a new prompt.

Per-site kernel time on L4 (L2 flushed between calls), M 4096 (1024px):

site ConvRot off (Inductor-fused quant) main this PR
LayerNorm + modulate -> rotated quant, K 4096 350 us 390 us 359 us
silu(gate) * value -> rotated quant, K 12288 977 us 1901 us 982 us

At M 16384 (2048px) the down-projection site is 3965 / 7831 / 4239 us. Plus, per block, main ran three more rotation kernels on inputs already quantized (K, V, value).

Tests

  • New: test_codes_close_tolerance, test_h16_plan_keeps_every_chunk_full, test_h16_kernel_matches_the_stock_codes_and_the_exact_rotation (v1 / v2, ieee / tf32x3, ragged M, K up to 129 groups), test_h16_is_the_default_and_its_kill_switch_keeps_the_dense_kernel, test_h16_mode_follows_the_arch, test_h16_probe_refusal_keeps_the_dense_kernel, test_swiglu_prologue_matches_the_stock_product_rotation_and_quant, test_swiglu_kill_switch, test_shared_input_linears_quantize_once_and_match_the_separate_calls, test_swiglu_mlp_fuses_the_product_into_the_down_quant_eager_and_compiled (fullgraph, one graph, no recompile on a second input), test_swiglu_mlp_without_the_prologue_still_shares_the_gate_value_quant, test_int8_gemm_path_rotates_each_shared_input_once (a real Qwen-Image-2.1 block: 7 -> 4 rotation calls, Q / K / V bit-identical to the stock helper). They fail on main (the APIs do not exist there).
  • The existing bit-exact tests of the dense kernel now pin it with UNSLOTH_DIFFUSION_INT8_ROTQUANT_H16=0; the shape-coverage test documents that the dense kernel stops at 128 groups while H16 does not.
  • int8 / ConvRot / Qwen-Image-2.1 test files (test_diffusion_int8_gemm, _int8_fused, _int8_runtime_convrot, _int8_stream_torchao17, _stream_int8_gemm, _convrot, _te_int8_convrot, _qwenimage21, _qwenimage21_fused, _qwenimage21_graph, _qwenimage21_math, _qwenimage21_rope) on B200: this branch 504 passed / 4 failed / 2 skipped, main 458 passed / 4 failed / 2 skipped. The 4 failures are the same IDs on both (test_no_compiled_variant_spills_to_local_memory, three test_diffusion_qwenimage21_graph capture tests) and fail on main on this host.

Not covered here

  • The RTX 6000 Ada itself: the end-to-end numbers are L4 (same sm89 kernels and tiles) and A100. L4 and the Ada have a similar fp32-FMA-to-bandwidth ratio, which is what decides the H16 second stage.
  • Qwen-Image-2.1 at 2048px: the resident gap in the user benchmark (+4.4% vs ComfyUI) is this same ConvRot cost (main's per-block excess at M 16384 measured above scales to about 0.09 s/step at the Ada's bandwidth), so this PR addresses it. The extra +0.10 s/step of the 16 GB (DiT partly streamed) cell over the resident one is block-streaming overlap, not ConvRot, and is not changed here.
  • Left in: the LayerNorm + modulate output of the attention and MLP inputs is still written in bf16 and read back by the rotation kernel (ConvRot off fuses the quant into that Inductor kernel). At 1024px it stays in L2 (+9 us per site on L4); at 2048px it is about 0.6% of a step. Fusing it needs the block forward patched.
  • Other ConvRot families on the fused path (MiniMax-H3, Z-Image) get rotq_h16 too (same probe), but were not timed end to end here.
  • sm86 (RTX 3090) still has no fused rotation kernel by default; that arch table is separate work.

On archs where diffusion_int8_gemm swaps the rotated Linears (sm80 / sm89 / sm120),
the ConvRot path cost Qwen-Image-2.1 about 8% per step over plain int8:

- Each rotated Linear ran the fused rotation + act quant on its own input, 7 kernels
  per block for 4 distinct inputs. Inductor does not merge identical opaque custom ops
  in an inference graph. shared_rotq_linears quantizes a shared input once (Q / K / V
  through the fingerprinted QKV helper, gate / value through a SwiGLU MLP forward).
  Same codes, outputs bit-identical to the separate calls.
- The SwiGLU product silu(gate) * value went to HBM as bf16 and was read back by the
  down projection's rotation kernel; with ConvRot off Inductor fuses it into the quant.
  convrot_swiglu_act_quant computes the product inside the rotation kernel.
- rotq_h16 rotates each 256-group as H16 . X . H16 (one bf16 tensor-core dot, one fp32
  dot: FMAs, or tf32x3 on the datacenter parts) instead of a dense 256 x 256 GEMM.
  Probe-gated per device against the stock path (codes_close); closer to the exact
  rotation than the dense GEMM. UNSLOTH_DIFFUSION_INT8_ROTQUANT_H16=0 keeps the dense,
  bit-identical kernel; UNSLOTH_DIFFUSION_INT8_ROTQUANT_SWIGLU=0 the stock product.
@danielhanchen danielhanchen self-assigned this Oct 23, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-23T16:51:31.978327Z f3185d8 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[bot]

This comment was marked as resolved.

…ort shared QKV on the transformer's cards

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… as swap-covered, probe the one-pass H16 branch and reject non-finite scales

- _swiglu_ff_forward takes out(act(gate) * value) when activation_fn has a
  forward hook / pre-hook, a global hook, or an instance forward override
- _swap_card_present uses a positive _swap_covers predicate: NVIDIA CUDA only,
  swap on, fused GEMM or rotq_i8 gated in; failures count as not covered
- the rotq_h16 and SwiGLU probes include 16 / 4 group shapes (one pass)
- codes_close requires finite scales on both sides

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…efore fusing

An activation_fn swapped after install (GELU, a custom module, a SiLU subclass) now runs itself instead of the hard-coded SiLU prologue.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

_swap_covers counted a card whenever the fused GEMM was gated in, but
shared_rotq_linears declines every record without rotq_i8, so with
UNSLOTH_DIFFUSION_INT8_ROTQUANT=0 or UNSLOTH_DIFFUSION_INT8_GEMM_CONVROT=0
(or a failed per-device rotq probe) the helper was installed and fused_qkv
reported while every call took the stock path.

[skip ci]
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@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: f3185d89fc

ℹ️ 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 deleted the studio-convrot-fused-cost branch October 23, 2026 18:06
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 23, 2026
…e factored ConvRot kernel behind a probe and latency check (unslothai#14988)

Builds on unslothai#14982 (merged), which added the `rotq_h16` factored rotation
kernel. This PR adds no kernel; it only routes the archs that kernel
does not reach yet onto it, and composes with it unchanged.

## Problem

A user benchmark against ComfyUI measured Qwen-Image-2.1 (int8 ConvRot,
1024x1024, 25 steps) on an RTX 3090 at 0.570 s/step in Studio and 0.447
s/step in ComfyUI, 22% slower. With `UNSLOTH_DIFFUSION_INT8_CONVROT=0`
Studio ran 0.470 s/step, level with ComfyUI, so the cost is the ConvRot
rotation. ComfyUI runs int8 ConvRot weights too, and its rotation costs
nothing measurable.

The fused rotation + act quant is only reached through
`rotquant_device_config`, which needs a `_ROTQ_CONFIG` tile: sm80, sm89
and sm120. Every other arch (sm86 RTX 30xx / A6000 / A10, sm87, sm90
H100, sm100 / sm103 B200 / B300, sm121) runs the Qwen-Image-2.1 /
Z-Image stock fusions: the rotation as a dense 256x256 bf16 GEMM through
cuBLAS, the rotated activation written to HBM, then a second act quant
kernel. On GA102 (RTX 3090) bf16 with fp32 accumulate runs at 1/8 of the
int8 rate, so that GEMM costs a large share of every int8 Linear.
`rotq_h16` (the parent PR) needs no tile table, but it is still only
probed behind a dense tile.

## Fix

- `diffusion_convrot_quant.unlisted_device_ok`: on a CUDA sm80+ arch
with no `_ROTQ_CONFIG` entry, probe `rotq_h16` directly (`_h16_probe`,
`codes_close`, the parent PR's tolerance), then run a latency check on
the card. `rotq_h16` must not be slower than the two kernels it replaces
(rotation GEMM, then Studio's probed act quant kernel). Both arms are
timed from CUDA-graph replays on a 4096-wide and a 12288-wide
activation, so host launch cost does not count. On success the card's
second-stage mode goes into `_H16_DEVICE` and the existing
`convrot_act_quant_int8` op serves it. Otherwise the card keeps main's
path.
- `diffusion_int8_fused._rotated_act_quant`: the rotated inputs of the
Qwen-Image-2.1 stock fusions (shared QKV input, `to_out`, SwiGLU in and
down) and the ConvRot SwiGLU call that op on an armed card, else the
rotation GEMM + act quant as before. The int8 GEMMs stay cuBLAS
`_int_mm` with torchao's epilogue, as on main.
- Arming happens at install, outside any trace (`arm_rotated`: int8
fused finalize, layer-split relocation, Qwen-Image-2.1 install). The
`q21_convrot_fused` load log says what was decided, with the latency
numbers, for example `rotation fused into the act quant (rotq_h16:
cuda:0 151 vs 417 us stock)` or `fused rotation kept off (...)`.
- sm80 / sm89 / sm120 are untouched: they keep the parent PR's path.
- Switches: `UNSLOTH_DIFFUSION_INT8_ROTQUANT_UNLISTED=0` keeps main's
path (read on every load), and `=1` skips the latency check (the probe
still runs). `UNSLOTH_DIFFUSION_INT8_ROTQUANT_H16=0`,
`UNSLOTH_DIFFUSION_INT8_ROTQUANT=0` and `UNSLOTH_DIFFUSION_INT8_GEMM=0`
turn it off too. The new switch joins the compile cache's graph
switches.

## Results

### End to end, Colab A100 standing in for an unlisted Ampere card

Colab A100-SXM4-40GB, torch 2.12.1+cu130, torchao 0.18.0. Qwen-Image-2.1
int8 ConvRot (Studio's default load), 1024x1024, cfg 1. s/step =
(25-step render - 5-step render of the same prompt and seed) / 20, over
3 new prompts. Each arm is a fresh process with a fresh Studio home and
inductor cache, run in the order base, head, head, base on one VM.

No unlisted card was available for an end-to-end run. Both arms
therefore drop sm80 from the four tile tables in-process, so the A100
takes the route an RTX 3090 takes. Base is the parent PR
(`studio-convrot-fused-cost`), which on such a card runs the rotation
GEMM + act quant. Head is this PR.

| arm | s/step (3 prompts) | median | `rotq_h16` calls |
|---|---|---|---|
| base | 0.2545 / 0.2546 / 0.2550 | 0.2546 | 0 |
| head | 0.2712 / 0.2486 / 0.2487 | 0.2487 | 12160 |
| head | 0.2485 / 0.2485 / 0.2489 | 0.2485 | 12160 |
| base | 0.2543 / 0.2547 / 0.2550 | 0.2547 | 0 |

- **Speed:** head is 2.4% faster per step. The spread between repeats of
the same arm is 0.1% or less (the first prompt of the first head arm,
0.2712, is a one-off outlier).
- **Latency check on head:** the probe picked tf32x3 and timed 130 us
against 152 us for stock. The load log reads `rotation fused into the
act quant (rotq_h16: cuda:0 130 vs 152 us stock)`.
- **Compile and CUDA graphs:** 3 compiled graphs before and after the
timed prompts on every arm, so new prompts trigger no recompile.
`compiled` and `cuda_graph` are on in every arm.
- **Images (same prompt and seed):** each arm reproduces itself pixel
for pixel. Base vs head is 36.3 / 45.7 / 38.0 dB PSNR. For scale, main's
own two A100 paths (dense tile + fused GEMM vs the stock rotation)
differ by 36.8 to 39.6 dB on these prompts.
- **On a 3090:** the A100 is a weak stand-in. Its bf16 rotation GEMM is
cheap (fp32 accumulate at full rate), so the stock path costs less there
than on GA102, where fp32-accumulate bf16 runs at 1/8 of the int8 rate.

### B200 (local, real unlisted arch)

The latency check kept main's path on 4 of 4 runs: `rotq_h16` (tf32x3)
at 68 to 70 us against 35 to 36 us for stock, both from CUDA-graph
replays. B200's cuBLAS runs the dense rotation close to bandwidth, so
B200 renders run exactly what main runs. This was a shared card, so the
numbers are ratios only.

## Tests

- New `tests/test_diffusion_convrot_unlisted.py`.
- Gate tests with mocked capability, run anywhere: the arch table
(exactly one route to the fused rotation per sm80+ arch), the four kill
switches, the forced dense tile taking the listed route, the latency
check (faster, tie, slower, forced), the probed mode and the caller's
act quant reaching the check, a failed probe keeping main's path, listed
archs and sm75 never probing, the kill switch acting on a cached device,
and `arm_rotated` following the gate.
- CUDA tests: `_rotated_act_quant` running `rotq_h16` once armed (4
shapes, `codes_close` against the stock rotation + torchao quant),
main's path on an unarmed card, the latency check repeating within 25%
(graph replay, not host time), and a `fullgraph=True, dynamic=True`
compile with no graph break and one graph across three token counts,
plus CUDA graph capture and replay equal to eager.
- On the parent branch the file fails at import:
`diffusion_convrot_quant` has no `INT8_ROTQUANT_UNLISTED_ENV`.
- `test_diffusion_int8_fused.py` and
`test_diffusion_qwenimage21_fused.py` assert bit equality with the stock
rotation, so their autouse fixtures pin
`UNSLOTH_DIFFUSION_INT8_ROTQUANT_UNLISTED=0`.
- Ran the new file plus `test_diffusion_int8_gemm.py`,
`test_diffusion_convrot.py`, `test_diffusion_int8_fused.py`,
`test_diffusion_int8_runtime_convrot.py`,
`test_diffusion_qwenimage21_fused.py`, `test_diffusion_zimage_fused.py`,
`test_diffusion_stream_int8_gemm.py`,
`test_diffusion_te_int8_convrot.py`,
`test_diffusion_compile_cache_variant.py` and
`test_diffusion_layer_split_speed.py` on B200 (torch 2.14.1, Triton 3.8,
torchao 0.18), the parent branch and this branch under the same GPU
lease.
- Parent: 504 passed, 1 failed. This branch: 540 passed, 1 failed (the
new file's tests, none skipped).
- The one failure is the same test on both:
`test_diffusion_int8_gemm.py::test_no_compiled_variant_spills_to_local_memory`.
The forced fused GEMM spills on sm100 with Triton 3.8. It is not touched
here.

## Not covered

- sm86 (RTX 3090 / A6000 / A10) was not measured: no sm86 card was
available. The latency check is what keeps it safe. On a card where
`rotq_h16` is not faster than the rotation GEMM + act quant, it stays
off and the card runs exactly what main runs.
- H100 (sm90), sm87, sm103 and sm121 were not measured: Colab had no
H100 for this account during this work. They get the same probe +
latency check.
- sm75 (T4) is not covered: `rotq_h16`'s first stage is a bf16
tensor-core dot. Studio's T4 diffusion route runs float32 activations
anyway.
- Rotated Linears that go through `diffusion_int8_gemm`'s own swap on an
unlisted arch (MiniMax-H3) keep main's path, because that swap stays off
on those archs. The parent PR's SwiGLU prologue and shared Q/K/V rotate
+ quant run on the swap path, so they do not reach unlisted archs
either.
- Linux / NVIDIA only. ROCm, CPU and Mac never reach this path.
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 26, 2026
…ge-2.1 denoisers (unslothai#15370)

## Summary

Qwen-Image-2.1 int8 ran about 3% slower per step at 12 / 8 GB VRAM
budgets than at 16 / 24 GB on L4 (0.814 against 0.789 s/step at
1024x1024). The group-offload hooks and the block-streamed step graph
are not the cause: with every group resident, the replayed graph has no
copies and the hooks do not run. The cause is one int8 kernel lever that
the streamed load path dropped.

- At 16 / 24 GB the int8 GEMM swap installs against the resident
weights. Each Qwen-Image-2.1 SwiGLU MLP then runs one shared act quant
for gate / value, and the SiLU product is fused into the down
projection's act quant (`_install_swiglu_ff`, unslothai#14982).
- At 12 / 8 GB the denoiser is placed under group offload, so the swap
installs against the onload device (`install(..., device=...)`) while
the weights are still on the host. `_install_swiglu_ff` kept only MLPs
whose weight already sat on the target card, so all 32 MLPs stayed on
four separate act quants per block.

This change lets the onload-device install patch those MLPs too. The
group hook onloads the whole block before the MLP runs. `_swiglu_down`
and `shared_rotq_linears` already fall back to the stock MLP whenever a
weight is not on the activation's device, so a weight that is still on
the host can never reach the fused kernels. A layer split (several
cards) keeps the per-card filter.

Kill switch: `UNSLOTH_DIFFUSION_INT8_SWIGLU_STREAMED=0` restores the
previous behaviour.

## Results

Colab L4, one VM, base (main 9e44983) and head interleaved per budget
(base, head, head, base). 1024x1024, 25 steps, CFG 1. Each process
renders a cold image, 2 cached-prompt images and 4 new prompts. s/step
is the median of the 4 new prompts.

| budget | base r1 / r2 | head r1 / r2 | change |
|---|---|---|---|
| 12 GB s/step | 0.8140 / 0.8144 | 0.7841 / 0.7879 | -3.5% |
| 8 GB s/step | 0.8274 / 0.8273 | 0.7964 / 0.7974 | -3.7% |
| 16 GB s/step (reference) | 0.7890 | 0.7874 | unchanged |
| 12 GB render total s | 21.906 / 21.944 | 21.215 / 21.273 | -3.1% |
| 8 GB render total s | 22.154 / 22.148 | 21.405 / 21.457 | -3.3% |
| 12 GB own peak (NVML) | 11.684 GiB | 11.164 / 11.166 GiB | lower |
| 8 GB own peak (NVML) | 7.803 GiB | 7.799 GiB | same |

- 12 GB now matches 16 GB per step (0.784-0.788 against 0.787-0.789).
- 8 GB sits about 1% above 16 GB; that remainder is real block
streaming.
- Base A/A spread is 0.0004 s/step at 12 GB and 0.0001 s/step at 8 GB,
so the change is about 75x the noise.
- Every head process logs `one act quant for gate / value on 32 SwiGLU
MLP(s) + the SiLU product fused into the down projection's act quant`.
No base 12 / 8 GB process does.
- Each process captures the step graph once, on its first render. No arm
re-captures on later prompts or hits an out-of-memory.

On B200 (local, emulated 12 / 8 GiB caps), the int8 GEMM and ConvRot
kernels are off by default on sm100, so this change is a no-op there:
same kernels, same images. With the GEMM forced on
(`UNSLOTH_DIFFUSION_INT8_GEMM=1`), at both caps:
- head launches 647 kernels per step against 711, 2 fewer act quants per
block;
- GPU kernel time is 101.2-102.3 ms per step against 102.8-103.8 ms (one
contended base outlier at 132.6 left out);
- images are byte-identical to base in all 5 base / 5 head processes;
- the allocator peak is the same.

## Tests

`studio/backend/tests/test_diffusion_int8_gemm.py`:
- the streamed install patches a host-resident SwiGLU MLP, and the
resident install still does not;
- a MLP whose weight sits on another card is kept stock;
- `_swap` marks only the onload-device install as streamed;
- end to end on CUDA: a group-offloaded block on the host runs the fused
SwiGLU path after its onload, bit-identical to the resident install. The
kill switch keeps it stock.

The new cases fail on main and pass here. The whole file passes: 151
passed.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Nov 9, 2026
…IPS 0.10 to 0.04) (unslothai#17209)

## Summary

Studio's INT8 quantizes every Linear's activation per row. For FLUX.2
klein and FLUX.3 klein, the at-load int8 build on a resident Ampere or
newer card and the hosted int8 files were the only int8 paths that
skipped the group-256 block-Hadamard rotation (ConvRot). Z-Image,
Qwen-Image-2.1 and MOSS-Image already run it by default. Nothing gated
it: the fused rotation + activation-quant kernel already covers sm80 /
sm89 / sm120 and is probe-gated elsewhere. The families simply never had
a table entry. The torchao-free W8A8 path (fp16 cards, ROCm, offloaded
NVIDIA loads) already rotates every int8 Linear for every family, so
until now klein's int8 quality depended on whether the load offloaded.

This PR makes ConvRot the int8 default for `flux.2-klein`,
`flux.3-klein` and `flux.3-klein-base`:

- `ConvRotSpec(group = 256, default_on = True)`. On klein it covers all
101 int8 Linears (15 suffixes). On FLUX.3 it covers all 228 int8 Linears
(6 block suffixes); the FLUX.3 keep-list leaves the rest dense.
- Hosted files follow Qwen-Image-2.1's layout:
`FLUX.2-klein-4B-INT8-ConvRot.safetensors` in
`unsloth/FLUX.2-klein-4B-FP8` and
`flux-3-image-klein-INT8-ConvRot.safetensors` in
`unsloth/flux-3-image-klein-FP8`, both now published. A new
`ConvRotSpec.hosted_plain` marks the families whose older hosted int8
files are unrotated: while ConvRot is on, only the rotated name is
requested, and if it were absent the load would rotate and quantize at
load. The plain file is never read with ConvRot on.
- `flux.3-klein-base` keeps reading its hosted int8 file, which is
already rotated. fp8 is unchanged.
- Kill switch: `UNSLOTH_DIFFUSION_INT8_CONVROT=0` restores the previous
behaviour exactly: plain hosted file, plain at-load build.

FLUX.2-dev and FLUX.1 are left alone (unmeasured).

## Accuracy

Setup: the default resident int8 pick, 1024x1024, 8 prompts x 2 seeds =
16 paired renders, LPIPS (alex) against the dense bf16 render,
10k-resample paired bootstrap. "main" = kill switch (plain hosted file);
"head" = this PR (rotated hosted file through the real resolver). Every
head process was checked to have all Linears rotated with the fused
rotation kernel engaged (101 / 228).

| model, GPU | main LPIPS mean (max) | head LPIPS mean (max) | head -
main [95% CI] | better / worse |
|---|---|---|---|---|
| FLUX.2-klein-4B, A100 40GB | 0.092 (0.197) | 0.038 (0.094) | -0.054
[-0.069, -0.040] | 16 / 0 |
| FLUX.2-klein-4B, L4 | 0.102 (0.420) | 0.044 (0.123) | -0.058 [-0.099,
-0.029] | 16 / 0 |
| FLUX.3 klein, A100 40GB | 0.056 (0.334) | 0.0094 (0.028) | -0.046
[-0.088, -0.017] | 16 / 0 |
| FLUX.3 klein, L4 | 0.045 (0.346) | 0.019 (0.121) | -0.026 [-0.055,
-0.008] | 13 / 3 |

On a T4 (fp16 card, the torchao-free path, which already rotates today),
klein-4B scores 0.103 plain vs 0.037 rotated: -0.066 [-0.086, -0.049],
16 / 0.

## Speed

s/step of the steady renders, 3 fresh processes per arm in alternating
order. An explicit int8 pick runs Studio's default speed path, so this
is the compiled path; speed_mode off gave the same times. Every arm had
0 graph breaks and 0 recompiles.

| model, GPU | bf16 dense | main int8 | head int8 | head vs main (A/A
spread) |
|---|---|---|---|---|
| FLUX.2-klein-4B, A100 40GB | 0.178 | 0.1236 / 0.1236 / 0.1238 | 0.1280
/ 0.1281 / 0.1285 | +3.6% (0.2%) |
| FLUX.2-klein-4B, L4 | 0.751 | 0.431 / 0.435 / 0.436 | 0.463 / 0.464 /
0.475 | +6.6% (1.2%) |
| FLUX.3 klein, A100 40GB | 0.234 | 0.1549 / 0.1552 / 0.1559 | 0.1653 /
0.1661 / 0.1662 | +7.0% (0.5%) |
| FLUX.3 klein, L4 | 0.914 | 0.543 / 0.549 / 0.550 | 0.594 / 0.597 /
0.597 | +8.7% (1.2%) |

Head int8 stays 28-40% faster than bf16. Where the cost comes from (L4
klein, kernel profile of one render):

- With ConvRot off, the int8 activation quant rides inside the producing
Inductor kernel (layer norm + modulate, the single-block concat, the
SwiGLU product): about 134 ms per render.
- With it on, those kernels write bf16 (about 144 ms), and `rotq_h16`
reads the activation back, rotates and quantizes it (112 ms, 404 calls).
The int8 GEMMs are unchanged (964 vs 975 ms).
- The single blocks' 12288-wide `attn.to_out` inputs carry most of that
traffic (an estimated 57% of the rotated elements).
- `rotq_h16` already runs at about 70% of L4's bandwidth, so tiling or
launch settings do not buy the gap back. Sharing one rotation across
Q/K/V (as Qwen-Image-2.1 does) would save about 0.4% of a step.
- The real fix is to rotate inside the producing kernel, which needs the
block forward patched (the item left open in unslothai#14982). That is not in
this PR.

## Load

klein-4B on A100 40GB. Cold = empty HF cache; warm = files cached but a
fresh Studio home, Triton cache and Inductor cache; repeat = second load
on the same machine (same Studio home and caches).

| | main (plain hosted file) | head (rotated hosted file) | at-load
rotation (rotated file missing) |
|---|---|---|---|
| denoiser bytes read | 4.05 GB | 4.05 GB | 7.75 GB (bf16) |
| cold load / first image | 67-69 s / 88 s | 97-100 s / 117-120 s | 82 s
/ 139 s |
| warm load / first image | 20.4 s / 40.4 s | 55.0 s / 74.8 s | 29-50 s
/ 88-109 s |
| repeat load / first image | 12.8-13.3 s / 18.5-21.1 s | 14.3-14.4 s /
18.7-19.2 s | |

- The extra ~35 s of a head load on a fresh machine is the fused
rotation kernels' device probes compiling their Triton kernels
(`_rotq_probe` 12.2 s, `_h16_probe` 11.8 s, `_swiglu_probe` 9.0 s, from
a stack sample of the load), plus about 1 s for the hosted file's
fingerprint check.
- Both are cached per machine, so a repeat load is within about 1 s of
main's.
- L4 shows the same pattern: warm 22 s main vs 62 s head; cold 78-79 s
vs 109-110 s.
- FLUX.3: A100 warm 20.5 s vs 56 s, cold 65-68 s vs 97-99 s; L4 warm 20
s vs 60 s.

## Tests

`studio/backend/tests/test_diffusion_int8_runtime_convrot.py` checks:
- the rotated set equals the int8-quantized set on the real klein and
FLUX.3 layouts;
- the default-on behaviour and the kill switch;
- resolution only ever names the rotated hosted file while ConvRot is
on, and the plain file with the switch off;
- a missing rotated file falls through to the at-load build without
fetching the plain file;
- FLUX.3 base still reads its hosted file;
- the runtime quantize rotates all 101 klein Linears.

The new tests fail on the merge base. The family data freeze fixture was
regenerated, and only these three families changed. On the related CPU
subset (5,800+ tests), head and merge base fail the same tests by ID.

The published rotated files are bit-identical to this PR's at-load
rotated build of the same weights on the same torch / torchao (270 / 587
tensors compared, 0 mismatches, same rotation lists).

## Not covered here

- FLUX.3 klein base was not run on a GPU (its hosted file was already
rotated before this PR).
- On T4, FLUX.3 int8 with the torchao-free path's default rotation hits
a device mismatch in that path's rotation on the merge base too. This PR
does not touch that path; it is tracked separately.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 9, 2026
… FLUX.3 (ConvRot cost +8.7% to +0.5%) (unslothai#17230)

## Summary

Follow-up to unslothai#17209 (int8 ConvRot by default for FLUX.2 klein and FLUX.3
klein), and the open item from unslothai#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), `unslothai#17209`
the merge base, `this PR` the head; every int8 arm quantizes at load.

| model | card | plain int8 | unslothai#17209 | this PR | this PR vs unslothai#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 | unslothai#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 unslothai#17209 | <= 0.4% |

Per image: FLUX.3 klein on L4 is 8.88 s plain int8, 9.64 s with unslothai#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 |
| | unslothai#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 |
| | unslothai#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 |
| | unslothai#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 |
| | unslothai#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.
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