Skip to content

Studio: INT8 attention kernel for diffusion DiTs (NVIDIA sm75 to sm120, AMD gfx1151) - #17718

Merged
danielhanchen merged 30 commits into
mainfrom
studio-diffusion-int8-attention
Nov 14, 2026
Merged

danielhanchen merged 30 commits into
mainfrom
studio-diffusion-int8-attention

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Summary

An INT8 attention kernel for Studio's diffusion DiTs (MiniMax-H3 / H3-Image, FLUX.3 klein, and the video DiTs that route through the same op), for NVIDIA sm75 / sm80 / sm86 / sm89 / sm120 and AMD gfx1151 (Strix Halo, Linux and Windows).

  • Q.K^T runs in INT8 after a 16-point Hadamard rotation, a K mean shift and per-row Q / per-32-key K scales; P is quantised per tile and P.V runs on centred INT8 V (CUDA) or fp16 V (ROCm).
  • CUDA: PTX mma.sync kernels compiled at runtime with NVRTC, plus CUDA quantisers over every key. sm75 gets its own path (8x8x16 products, plain loads for key tiles, Q operands from global memory to fit 64 KB of shared memory).
  • ROCm gfx1151: a Triton kernel (WMMA iu8 for Q.K^T, f16 for P.V on a channel-major V copy, unmasked full key tiles). Other AMD archs keep native attention.
  • Exposed as the custom op unsloth_studio::int8_attention_nhd with a fake implementation, so it traces under torch.compile with no graph breaks.

Engagement and safety

  • Per card and dtype, the kernel must pass an accuracy gate against native attention (cosine >= 0.999 plus a sharpened-attention probe) before any block routes to it.
  • In the default mode a single interleaved block race (7 rounds, alternating order, decided on per-round ratios with a 2% margin) picks between native, SageAttention and the kernel, and the kernel only takes blocks where it wins. Forcing the kernel (UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL=1) skips the race; =0 turns it off.
  • Calls that need gradients keep native attention.
  • Short sequences (below the per-card min_tokens) and padded keys are handled exactly: padded keys get no weight even when the score scale underflows, and the V range is taken over every key.

Results

End to end (Colab, fresh processes, ABBA, seed-matched, 95% bootstrap CIs)

FLUX.3 klein at 2048: LPIPS against native, and the paired s/img change (log ratio) vs native and vs SageAttention:

Card LPIPS mean 2048 s/img vs native vs SageAttention
RTX PRO 6000 (sm120) 0.026 -22.8% -24.5% (Sage does not engage on sm120)
A100-80 0.032 -15.2% -7.0%
L4 0.034 -22.6% +0.17% (Sage slightly faster)

MiniMax H3-Image, ours forced:

Card 2048 s/img vs native edit (2720x1536) vs native LPIPS vs bf16
RTX PRO 6000 (sm120) -6.4% -12.2% tie with native
A100-80 -3.5% -9.0% tie with native (0.075 vs 0.074)
L4 race default: -1.5% vs SageAttention (incumbent) -1.1% vs SageAttention tie

Load time: forced loads now run no backend race; the default mode runs one block race instead of two. Cold attention install on A100 drops from 4.63 s to 1.37 s (forced) and 7.04 s to 4.35 s (default).

Per call (eager, quantisers included, A/A-checked)

  • Faster than native everywhere except H3 at 1024 px (about 1k tokens) on A100 / L4 / RTX PRO 6000, where the race keeps native.
  • T4: 0.16 to 0.54 of native.
  • gfx1151: 0.42 to 0.52 of what Studio runs on ROCm today (Linux), 1.15 to 2.7x faster on Windows.

Accuracy

  • Error is flat with key count (rel L1 vs fp64 0.00141 at 300k keys).
  • 16-token refiner calls: cosine 0.996 (exact V range and K statistics over every key).
  • Output on every NVIDIA card goes through the same instruction sequence; sm75 is bit-identical to the sm80 path on B200.

Checks

  • compute-sanitizer memcheck and initcheck: 0 reports (B200, both paths).
  • torch.compile: 0 graph breaks, 0 recompiles on the second pass (RTX PRO 6000, A100, L4, T4, B200).
  • Tests: each fix has a test that fails without it. CPU: test_diffusion_int8_attention.py, test_diffusion_int8_attention_rocm.py and the H3-Image race tests. GPU tests passed on RTX PRO 6000, A100-80, L4, T4 and B200; the gfx1151 card tests pass on Linux and Windows.

Not covered

  • sm86 has no card here; its config mirrors sm80.
  • H100 / sm90 and CDNA (MI300 / MI355) were not run; they keep native attention.
  • B200 has no tuned config and keeps native attention.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Configs for both head dims, measured on a T4 with fp16 operands. A load that
asks for the kernel without naming a dtype is checked in fp16 on sm75.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 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-14T00:11:34.148048Z 0f60d57 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: daea21e018

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

Comment thread studio/backend/core/inference/video.py Outdated
Comment on lines +12744 to +12748
# by name or by its env switch: the strided processors run Studio's INT8 attention kernel
if (
int8_attention.requested(attention_backend)
or int8_attention.mode() == "force"
) and int8_attention.install_int8_attention(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Install requested H3 INT8 attention without requiring a fused backend

For MiniMax-H3 video on a T4, requesting attention_backend="unsloth_int8" never reaches this installation: select_attention_backend() returns None because cuDNN attention requires SM80+, and the enclosing strided_install_backend(attention_engaged) check rejects None. The same problem occurs on gfx1151 when the automatic selection keeps native SDPA. Both devices have configurations in the new kernel tables, but the explicit request silently runs ordinary attention without even performing the accuracy check. Install the required strided processors for an explicit INT8 request independently of the incumbent backend, and allow their INT8 route to operate when the incumbent is default SDPA.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dbc0461. An explicit unsloth_int8 request (or the env switch) now installs the H3 strided processors even when the incumbent is default SDPA, with the stock q/k norm + RoPE in that case. The processor takes the INT8 route over a default SDPA pick. Calls it does not route run plain SDPA with no kernel pinned. The kill switch still wins. test_strided_processor_routes_flagged_calls_to_the_op now covers the default-SDPA case: it fails without the processor change and passes with it.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dbc046178f

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

Comment on lines +207 to +209
if int8_attention.mode() == "force" and int8_attention.install_int8_attention(
transformer, device = dev, dtype = dtype, force = True, logger = logger
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Install forced H3-Image INT8 attention over default SDPA

For H3-Image on a T4, setting UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL=1 never reaches this installation: select_attention_backend() returns None, while the enclosing condition requires _native_cudnn or _native_flash before installing strided processors. The same issue occurs on gfx1151 when selection retains default SDPA. Neither install_requested() (which only ensures FLUX.3 processors) nor the later checkpoint installation creates the missing H3 processors, so the forced request silently keeps ordinary attention despite both devices having kernel configurations. Install H3-Image's strided processors independently of the incumbent fused backend when INT8 is forced, retaining stock norm/RoPE where needed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 0f60d57. With UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL=1, H3-Image now installs its strided processors even when the pick is default SDPA (with the stock q/k norm + RoPE there), then engages the kernel on them. Without the switch, or with it at 0, nothing changes on those cards. test_forced_int8_attention_installs_over_a_default_sdpa_pick covers all three settings. Its forced case fails without the change.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 0f60d57579

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

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

[skip ci]
@danielhanchen
danielhanchen merged commit fdf806f into main Nov 14, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-int8-attention branch November 14, 2026 03:54
danielhanchen added a commit that referenced this pull request Nov 14, 2026
…ad on NVIDIA (#17726)

## Studio INT8 attention: Triton fallback when the CUDA kernel cannot
load on NVIDIA

Follow-up to #17718. On NVIDIA, Studio's INT8 attention runs a CUDA C++
kernel that is compiled at runtime with NVRTC (found through ctypes) and
loaded with the driver API. If NVRTC is missing, or the compile,
`cuModuleLoadData` or the first launch fails, the accuracy check used to
fail and the card stayed on native attention. The likeliest place for
that is Windows: a Windows install may have no NVRTC DLL that the loader
can find. Every Windows x64 / ARM64 install already has Triton
(unsloth's pyproject pulls in `triton-windows`, and torch ships Triton
on Linux), and Studio already has a Triton INT8 attention kernel for
ROCm. So when the CUDA kernel cannot load, the same calls now go to that
Triton kernel.

### Routing

| card / state | before | after |
|---|---|---|
| NVIDIA, CUDA kernel loads | CUDA kernel (accuracy check + race) |
unchanged |
| NVIDIA sm80 / sm86 / sm89 / sm120, CUDA kernel cannot load (no NVRTC,
compile, module load or first launch error) | native | Triton kernel,
after its own accuracy check and race |
| NVIDIA sm75, CUDA kernel cannot load | native | native (Triton cannot
compile an int8 `tl.dot` on sm75, see below) |
| no Triton importable, or no Triton config for the capability | native
| native |
| ROCm gfx1151 | Triton | unchanged |
| `UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL=0` | native | native |

- A failure inside the CUDA check (an exception, not an accuracy miss)
is recorded for that card and head dim, and the check runs again on the
Triton kernel. Verdicts and the verified set are keyed by
implementation, so a CUDA pass never stands in for Triton or the other
way round.
- When the Triton kernel stands in, it has to win the race against the
incumbent even if the load asked for `unsloth_int8` by name. The CUDA
kernel keeps its forced semantics, and the env switch `1` still skips
the race.
- New knob `UNSLOTH_DIFFUSION_INT8_ATTENTION_IMPL=auto|cuda|triton`
(default `auto`). `cuda` never runs Triton; `triton` skips the CUDA
kernel, which is how the path was tested on Linux.
- The status dict, the install log line and the H3-Image race record
name the engaged implementation (`cuda` / `triton`), the CUDA failure
reason, and keep timed races apart from untimed checks. Op call counts
gain a `triton` counter.
- The kill switch and the gradient guard are unchanged.
- The Triton attention kernel installs the sm_8x 8-bit prefetch fix from
#17669 (`diffusion_triton_prefetch`) before it compiles, and carries it
in its cache key the same way the INT8 GEMM does. On an A100 with Triton
3.8, the compile of the attention kernel went through the fix with the
prefetch pass skipped. The quantiser kernels, which have no 8-bit dot,
kept the pass.

### Triton configs (NVIDIA)

Tuned with the Triton path forced on A100 (sm80), L4 (sm89) and RTX PRO
6000 (sm120), head dims 128 and 64. The grid covered block M, block N,
warps, stages and P.V mode, under Triton 3.8 (torch 2.14.1), and the top
configs were re-timed under Triton 3.7 (torch 2.13). Every pick is
16-bit P.V reading V in place, with only Q.K^T in int8; int8 P.V was
slower on every card. sm80 uses the tile that stays close to native on
both Triton releases: the Triton 3.8 winner was 1.49x native under
Triton 3.7. sm86 uses the sm80 entry, which fits sm86's 99 KB of shared
memory.

### Tests

`tests/test_diffusion_int8_attention_triton_fallback.py` (CPU, faked
card) covers:
- an NVRTC load failure, a `cuModuleLoadData` failure and a first-launch
failure each route to Triton on sm80 / sm86 / sm89 / sm120 when Triton
and a config are there, and to native when they are not; sm75 keeps
native;
- `IMPL=cuda` never runs Triton, and `IMPL=triton` never compiles the
CUDA kernel;
- the kill switch wins under `auto` and `triton`;
- a CUDA verdict is never accepted for Triton, and the other way round;
- the race times the Triton kernel, and a requested stand-in still has
to win it;
- the prefetch fix is installed before the Triton kernel compiles.

Two tests run on the card: the forced Triton path through the registered
op, with strided views and the gradient guard. The new test file fails
without the change. The existing INT8 attention tests were updated for
the implementation-keyed verified set.

### GPU verification (Colab: A100-40GB, L4, RTX PRO 6000 Blackwell, T4)

All runs below are eager, one fresh process per measurement, in ABBA
order with a flash A/A spread. "triton" is the product op with the
Triton path forced (`IMPL=triton`); "cuda" is the #17718 kernel. Each
Triton measurement asserted that the op ran the Triton kernel.

Triton ms over native ms, torch 2.14.1 / Triton 3.8 (below 1 = faster):

| shape (tokens, heads x dim) | A100 vs flash | L4 vs flash | L4 vs
cuDNN | RTX PRO 6000 vs flash | RTX PRO 6000 vs cuDNN |
|---|---|---|---|---|---|
| H3 1024 (1039, 56x128) | 1.329 | 1.124 | 1.052 | 1.067 | 1.198 |
| H3 2048 (4112, 56x128) | 1.104 | 0.835 | 0.816 | 0.863 | 0.920 |
| H3 edit (10011, 56x128) | 1.068 | 0.780 | 0.764 | 0.822 | 0.871 |
| FLUX.3 klein 1024 (4176, 24x128) | 1.130 | 0.830 | 0.808 | 0.888 |
0.980 |
| FLUX.3 klein 2048 (16464, 24x128) | 1.069 | 0.763 | 0.753 | 0.815 |
0.863 |
| LTX-like (6144, 32x64) | 1.015 | 0.839 | 0.873 | 0.922 | 0.894 |
| Wan 480p (32760, 40x128) | 1.032 | 0.758 | 0.746 | 0.801 | 0.848 |
| Wan 720p (75600, 40x128) | 1.030 | 0.747 | 0.734 | 0.793 | 0.841 |

- The A/A spread was at most 2.3% on L4 and at most 1.3% on the others.
- Torch 2.13 / Triton 3.7 gives the same picture: L4 0.79-0.86 and RTX
PRO 6000 0.83-0.91 vs flash from 4k tokens, A100 0.99-1.07.
- The CUDA kernel stays faster than Triton on long sequences, by
1.11-1.47x. Matching it was not a goal.
- On short calls (about 1000 tokens) Triton loses: its four launches
cost more than they save. The race checks 1024 and 4096 tokens, so it
engages from 2560 tokens on L4 and RTX PRO 6000 and never on A100.

Simulated NVRTC failure (and `cuModuleLoadData` failure) in a fresh
process, default settings, a fake DiT with 24x128 and 32x64 strided
attention:

| card | raced (INT8 checkpoint) | asked for by name | serves |
|---|---|---|---|
| A100 | 0 of 3 modules (Triton 1.75 ms vs flash 1.51 ms at 4096 tokens)
| 0 (stand-in raced) | native |
| L4 | 3 of 3, from 2560 tokens (2.50 ms vs 2.83 ms at 4096 tokens) | 3
| Triton |
| RTX PRO 6000 | 2 of 3 (head dim 128 from 2560 tokens; head dim 64
lost) | (raced, same verdict) | Triton / native |
| T4 | 0 (no Triton config) | 0 | native, reason "NVRTC not found ..." |

Other settings on the same harness:
- `IMPL=cuda`: native.
- Kill switch `0`: native.
- No failure: the CUDA kernel, as before.

fp64 oracle with the Triton path forced:
- Inputs: the #17718 stress set (lengths 1..4104, cross attention,
strides, storage offsets, ties, outliers, padding, huge / tiny / NaN /
inf inputs, up to 314,437 keys) plus real H3-Image q/k/v captures (11
full-size calls, taken on the RTX PRO 6000).
- Every normal case passes the product gate (cos >= 0.999, rel L1 <=
0.05) except `gain5`, which the CUDA kernel also fails.
- On real captures the Triton path reached a worst rel L1 of 0.0070, a
1st-percentile row cosine of 0.9998 and a worst-row cosine of 0.9993.
The CUDA kernel on the same captures: 0.0105 / 0.9988 / 0.9944.
- The sm80 and sm89 tiles give the same numbers on those captures.

Studio tests on the card:
- A100 and L4: 127 passed. The forced Triton GPU tests pass.
- One test fails:
`test_strided_processor_routes_flagged_calls_to_the_op`, an H3 processor
bitwise check on CPU. It fails the same way at the base commit with the
PyPI diffusers, so it is not from this change.
- T4: Triton cannot compile the int8 `tl.dot` on sm75 under Triton 3.7
or 3.8 (`TritonGPUAccelerateMatmul` fails), so sm75 has no Triton
config.

### Not verified

- No Windows machine with an NVIDIA card was available. The Windows case
was simulated on Linux by hiding NVRTC (every library candidate fails to
load) and by failing `cuModuleLoadData`; triton-windows itself was not
run.
- No sm86 card (RTX 30xx, A10) was available. sm86 runs the sm80 config
untimed.
- Real full-size H3-Image q/k/v captures were only taken on the RTX PRO
6000. A100 and L4 used the synthetic stress cases and three short real
captures.
danielhanchen added a commit that referenced this pull request Nov 14, 2026
…atch fixture without diffusers (#17737)

## Summary

Two failures from #17718 (INT8 attention kernel for diffusion DiTs) that
show up in the backend CPU job, now that `test_diffusion*` runs in its
own shard:

```
tests/test_diffusion_rocm_tag_detect.py::test_no_diffusion_or_video_gate_reads_version_hip_directly
    AssertionError: use core.inference.rocm_bf16.is_rocm_torch(torch): AMD SDK / Radeon wheels leave torch.version.hip unset.
    Raw reads: {'diffusion_int8_attention_triton.py': [506]}

tests/test_diffusion_int8_attention.py  (4 errors at setup)
    _active_backend: ModuleNotFoundError: No module named 'diffusers'
```

1. `prefetch_fix()` in `diffusion_int8_attention_triton.py` decides
"NVIDIA build of torch" with `torch.version.hip is None`. AMD SDK /
Radeon wheels leave `torch.version.hip` unset and only carry `rocm` in
`torch.__version__`, so on those builds the NVIDIA sm_8x prefetch patch
would be installed on an AMD device. The guard is right and the read is
a real bug. `diffusion_int8_attention.py` already uses `is_rocm_torch`;
the Triton module now does too.
2. The `_active_backend` fixture imports
`diffusers.models.attention_dispatch` directly. The test bodies already
skip without diffusers through `_h3()`, but the fixture runs first, so
the tests error at setup instead of skipping. It now uses
`pytest.importorskip`.

## Testing

- `test_diffusion_rocm_tag_detect.py`: fails on main (the raw read
above), passes here.
- With `diffusers`, `unsloth_zoo` and `trl` hidden from import (the
backend job's environment), `test_diffusion_int8_attention.py` and
`test_diffusion_rocm_tag_detect.py`: 4 errors on main, all pass or skip
here.
- With diffusers installed: the INT8 attention tests pass as before.
danielhanchen added a commit that referenced this pull request Nov 14, 2026
…nt the diffusion shard (#17736)

## Summary

Follow-up to #17723, which moved `test_diffusion*` into its own `(Python
3.13, diffusion)` backend shard. Two things went red once that shard ran
(seen on a staging run against current main):

1. `Repo tests (CPU, studio)` and `workflow-trigger lint`:

   ```

tests/studio/test_backend_ci_parallel_isolation.py::test_the_command_scan_sees_the_parallel_run_and_the_serial_steps
AssertionError: expected fourteen parallel pytest runs, four shards of
the backend matrix and ten of repo-cpu-tests ... assert 15 == 14
   ```

That test pins the number of parallel pytest runs on purpose, so a new
shard has to be stated there. #17723 updated
`test_ci_backend_pytest_shards.py` but missed this one. My mistake.

2. `(Python 3.13, diffusion)`: five tests in
`studio/backend/tests/test_diffusion_lm_studio.py` fail with
`PackageNotFoundError: No package metadata was found for unsloth_zoo`:
   - `test_frame_relay_throttles_and_never_raises_into_the_sampler`
- `test_frame_relay_sends_zero_based_steps_and_honours_stop_sequences`
   - `test_frame_relay_cuts_frames_at_the_first_eos`
   - `test_diffusion_eos_ids_match_the_sampler_cut`
-
`test_chat_diffusion_load_refuses_an_unmarked_model_and_keeps_the_token_boundary`

They import `core.inference.inference`, which imports `unsloth`, and the
backend job installs neither `unsloth_zoo` nor `trl`. They only passed
in the old a-f shard because an earlier file on the same worker
(`test_audio_chat_load.py`, `test_chat_prompt_bos.py`) had already
imported that module with its own `unsloth` stubs and left it cached. In
a shard of only `test_diffusion*` files that never happens. So these
tests have depended on xdist scheduling since #13593; the split only
made it deterministic.

## Change

- `tests/studio/test_backend_ci_parallel_isolation.py`: 15 parallel
runs, 5 backend shards.
- `studio/backend/tests/test_diffusion_lm_studio.py`: a small
`inference_mod` fixture the five tests now take.
- When `unsloth_zoo` is installed, or the module is already imported, it
returns the real module. Nothing changes there.
- Otherwise it stubs `unsloth` and `unsloth.chat_templates` (the same
two names the other backend tests stub) through `monkeypatch`, and also
drops the freshly imported `core.inference.inference`. So no later test
inherits a module bound to these stubs.
- The tests keep running in the backend job instead of being skipped
there.

## Testing

- Locally, with `diffusers`, `unsloth_zoo` and `trl` hidden from import
(the backend job's environment): `test_diffusion_lm_studio.py`,
`test_diffusion_int8_attention.py` and
`test_diffusion_rocm_tag_detect.py` on their own. The five tests fail on
main with the same error and pass here. They also pass with the real
packages installed.
- The same files in one process, before and after
`test_audio_chat_load.py` and `test_chat_prompt_bos.py`: 78 passed, 33
skipped in both orders.
- Every test that reads `studio-backend-ci.yml` (15 files): 341 passed,
3 skipped. The isolation test fails on main.
- `test_backend_tests_stub_heavy_imports.py` and
`test_sibling_imported_tests_import_their_helpers_top_level.py`: pass.

The other failures on the new shard come from #17718 and are fixed in
#17737.
danielhanchen added a commit that referenced this pull request Nov 14, 2026
…an 2.2) (#17758)

## Summary

Studio's INT8 attention kernel (#17718, Triton fallback #17726) only ran
in families with their own strided
attention processors (MiniMax-H3 video, MiniMax-H3-Image, FLUX.3). This
PR sends the attention of every family whose
DiT processors call diffusers' `dispatch_attention_fn` to the same op,
without a processor per family, and turns it
on by default for Qwen-Image-2.1 / 2.1-Turbo and Wan 2.2 wherever the
on-card check and race say so. Z-Image-Turbo and
LTX-2 / 2.5 route on request.

- `diffusion_int8_attention_dispatch.py` (new): `install(pipe, target,
requested=...)` gives each routable
processor an `Int8Route` as its `_attention_backend`. The route is a
`str` equal to the incumbent backend's name,
so code that reads the attribute without knowing it
(`AttentionBackendName(...)`, `.value`, comparisons) still sees
the incumbent. A wrapper installed over the module-level
`dispatch_attention_fn` of the loaded diffusers and Studio
modules sends the calls it can take to
`torch.ops.unsloth_studio.int8_attention_nhd` (the kernel's own `[B, S,
H, D]`
layout, so nothing is copied) and passes every other call, with the real
incumbent backend, to diffusers.
- Calls that keep the incumbent: any `attn_mask`, `is_causal`, dropout,
a non-default scale, GQA, LSE or other extra
arguments, context parallel, gradient calls, a dtype or head dim the
card check did not pass, another card, and
calls with fewer query or key tokens than the race's floor. So
Qwen-Image text masks, Z-Image's padded batches,
LTX-2's masked text cross-attention and its short audio streams, and
Wan's 512-token text cross-attention all stay
on the incumbent; full unmasked self-attention (and Qwen-Image-2.1's
unmasked cached decode, target queries against
  prefix + target keys) routes.
- Gate and race: the existing `verdict` (accuracy check against fp32
attention, sharp probe, per-card race against
the processor's own backend with the 2% margin). No call under 1024
tokens routes, forced or not (text refiners,
audio streams and short text cross-attention lose to every incumbent;
126 tokens: 6x slower). Where the kernel wins
at 4096 but not 1024, a race at 2048 sets the floor at 1536 or 3072.
Where it loses at the race's sizes but wins at
video lengths (A100 against SDPA), a race at 16384 / 8192 tokens routes
only the calls from that length on.
- Eager calls cache the route decision per call signature (shapes,
dtypes, devices, flags), so an eager family pays
one dictionary lookup per call; compiled blocks trace the checks once as
guards.
- Multi-GPU loads: a layer split or a CFG replica puts DiT blocks on the
selection's other cards after the attention
pick, so the check and the race run on every card of the load's
selection and the route keeps a token floor per
card that passed. A call on any of those cards reaches the kernel; a
call whose tensors span two cards keeps the
  incumbent.
- Switches: `UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL=0` never routes;
`=1` or a load that asks for `unsloth_int8`
routes every routable DiT wherever the check passes (no race, except the
Triton stand-in);
`UNSLOTH_DIFFUSION_INT8_ATTENTION_DISPATCH=0` turns off only this route.
Unset races the classes in `AUTO_DITS`.
- `apply_attention_backend` installs the route after the backend pick
and reports `unsloth_int8` when it engaged (so
the compile cache keys apart). The video loader now passes the load's
attention request through.
- Z-Image-Turbo and LTX-2 are not in `AUTO_DITS`. Z-Image's
teacher-forced error with the kernel is 1.4x its shipped
INT8 weight error (below its FP8 error); LTX-2.5's video output is
within its INT8 weight error but its audio
output is 1.3x. Both route only on request, though they are 5-18%
(Z-Image) and 3.5-5.8% (LTX-2.5) faster.

No change to the kernel, its configs, the strided processors or
`diffusion_int8_attention.py`.

## Results

Studio defaults per card (the bare-click load: the shipped weight
quantisation, offload tier and attention pick),
fresh process per arm, order A B B A (A = merge base and head with the
switch at 0, B = head unset), 8 prompts with
matched seeds, timed after one warm render. Accuracy: one denoiser
forward at the native arm's saved inputs
(teacher forced) at 15 / 50 / 85% of the steps, relative L2 against
native attention on the same weights; the bar
is the same metric for Studio's FP8 and INT8 weights against bf16
weights (both with native attention).

Speed (s per image or clip, median of 16 renders per side, 8 on the L4
Wan row; A/A = the two native processes, which agree to within
the spread shown; "routed" = INT8 calls per render, 0 = the race kept
native):

| family | card | default weights / attention / offload | native | auto
| speed-up | A/A | INT8 calls |
|---|---|---|---|---|---|---|---|
| Qwen-Image-2.1 1024^2, 25 steps | G4 | int8 / cuDNN / none | 3.146 |
2.931 | +7.3% | 0.8% | 768 |
| Qwen-Image-2.1 | L4 | int8 / SDPA / group | 19.80 | 18.72 | +5.8% |
1.0% | 768 |
| Qwen-Image-2.1 | A100-40 / 80 | int8 / SDPA / none | 5.530 / 5.575 |
5.542 / 5.579 | tie (kept native) | 0.3% / 0.0% | 0 |
| Qwen-Image-2.1-Turbo 1024^2, 8 steps | G4 | int8 / cuDNN / none |
1.087 | 1.022 | +6.3% | 0.4% | 224 |
| Qwen-Image-2.1-Turbo | L4 | int8 / SDPA / group | 6.990 | 6.696 |
+4.4% (inside the 4.5% A/A) | 4.5% | 224 |
| Qwen-Image-2.1-Turbo | A100-40 / 80 | int8 / SDPA / none | 1.910 /
1.941 | 1.913 / 1.946 | tie (kept native) | 0.0% / 0.5% | 0 |
| Wan 2.2 TI2V-5B 1280x704x121, 20 steps | G4 | int8 / cuDNN / none |
58.18 | 46.76 | +24.4% | 0.1% | 630 |
| Wan 2.2 TI2V-5B | A100-80 | int8 / SDPA / none | 99.45 | 83.83 |
+18.6% | 0.0% | 630 |
| Wan 2.2 TI2V-5B | A100-40 | int8 / SDPA / none | 99.29 | 84.38 |
+17.7% | 0.1% | 630 |
| Wan 2.2 TI2V-5B (4 prompts) | L4 | int8 / SDPA / group | 386.3 | 308.2
| +25.3% | 0.0% | 630 |
| LTX-2.5 1280x704x121, 8 steps (by name only) | G4 | int8 / cuDNN /
none | 8.142 | 7.694 | +5.8% | 0.2% | 528 |
| LTX-2.5 (by name only) | A100-80 | int8 / SDPA / none | 14.672 |
14.175 | +3.5% | 0.9% | 144 |
| Qwen-Image-2.1-Turbo | T4-HM, fp16 | fp16 / SDPA / group | 38.80 |
35.05 | +10.7% | 0.3% | 224 |
| Z-Image-Turbo 1024^2, 8 steps (by name only) | T4 | int8 / SDPA /
group | 27.27 | 23.12 | +18.0% | 1.4% | 256 |
| Z-Image-Turbo (by name only) | G4 / L4 | int8 | 1.050 / 6.305 | 0.998
/ 5.950 | +5.3% / +6.0% | 0.1% / 0.3% | 256 |
| Z-Image-Turbo | A100-40 / 80 | int8 / SDPA | 1.839 / 1.823 | 1.840 /
1.822 | tie (race kept native) | 0.0% | 0 |

The Z-Image and LTX-2.5 rows were measured before they were taken off
the default list; they are what `unsloth_int8`
by name or the env switch gives. On A100 the race at 4096 tokens keeps
SDPA; the second race routes from 6144 tokens, so Wan and
LTX-2.5's 14k-token stage route and 1024^2 images do not (A100-40
Qwen-Image-2.1-Turbo with the route installed and
no call taken: 1.913 against 1.910 s, inside the 0.18% B/B spread). Peak
memory (allocated / reserved / nvidia-smi) and
host RSS are unchanged within 0.2 GiB in every pair.

Accuracy, teacher forced (median / max relative L2 of the denoiser
output over 8 prompts x 3 steps):

| family | INT8 attention, bf16 weights | INT8 weights (shipped default)
| FP8 weights | verdict |
|---|---|---|---|---|
| Qwen-Image-2.1 (G4 / A100-80) | 0.0067 / 0.012, 0.0063 / 0.011 |
0.0082 / 0.011, 0.0076 / 0.011 | 0.019 / 0.034 | within |
| Qwen-Image-2.1-Turbo (G4) | 0.0081 / 0.019 | 0.0084 / 0.27 | 0.020 /
0.29 | within |
| Wan 2.2 TI2V-5B (G4 / A100-80) | 0.0088 / 0.019, 0.0089 / 0.012 |
0.0135 / 0.031, 0.0136 / 0.022 | 0.0146 / 0.035 | within |
| LTX-2.5 video (G4) | 0.044 / 0.089 | 0.046 / 0.090 | 0.122 / 0.228 |
within |
| LTX-2.5 audio (G4) | 0.010 / 0.028 | 0.008 / 0.022 | 0.044 / 0.107 |
above INT8: off by default |
| Z-Image-Turbo (G4 / A100-80) | 0.035 / 0.092, 0.031 / 0.090 | 0.024 /
0.073, 0.024 / 0.071 | 0.056 / 0.167 | above INT8: off by default |

On the shipped weights, auto against native (same card): Qwen-Image-2.1
0.009 / 0.013 (G4, L4), Turbo 0.010 / 0.031,
Wan 0.013 / 0.030 (native A/A on the same probe: 0.004 G4, 0.012 A100,
where Wan's own run-to-run variation is that
large), LTX-2.5 0.058 / 0.104 (G4). End of trajectory against the native
render (same seed): LPIPS 0.018 / PSNR 36.1
dB Qwen-Image-2.1 G4, 0.033 Turbo, 0.19 Wan G4 (Wan's own A/A on A100:
0.11-0.12), 0.21 LTX-2.5 G4 / 0.027 A100-80
(audio relative L2 0.29), 0.057 Z-Image; the native A/A is bit-identical
everywhere except Wan on A100.

Kill switch: `UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL=0` gives 0 routed
modules and 0 INT8 calls on every card, and the
same pixels as the merge base (LPIPS 0, PSNR 99 dB on every family
except Wan on A100, whose base A/A is not
deterministic either). T4 standard (12.7 GB host RAM) could not load
Z-Image at Studio's defaults on the base either
(killed), so T4 numbers are from T4-HM.

## Tests

- `tests/test_diffusion_int8_attention_dispatch.py` (43, 3 of them
CUDA): the route marker (incumbent semantics, copies, pickle),
every fallback reason, the wrapper passing the real incumbent, module
patching, real Wan / Z-Image / LTX-2
processors (masked and unmasked calls), the token floor, the long race,
kill switches, gate failure, no kernel for
the card, Triton stand-in race, ROCm auto off, the
`apply_attention_backend` hook, a compiled Wan block with
`fullgraph=True` holding two INT8 ops and no graph break, a masked call
staying in one graph; CUDA: a Wan DiT
routes and matches native, compiled and CUDA-graph-replayed dispatch
call.
- CPU: 40 passed on diffusers 0.40 / torch 2.12 and diffusers 0.41 /
torch 2.14; the existing attention and INT8
  attention suites (980 tests) still pass.
- GPU: the new file plus the INT8 attention suites on T4 at this head
(164 passed, 3 skipped: the two-card test and
  two Triton cases) and on G4 at the first commit (159 passed) on Colab;
B200 (no kernel config): the route keeps native in every switch setting
and the DiT output is bit-identical.

## Not covered

- Wan 2.2 T2V-A14B, Qwen-Image-2.1 at its other presets, LTX-2.5 on L4 /
A100-40 / T4 and Wan on T4 were not run.
- The A100 long race was shown on video; an image above 6144 tokens on
A100 (e.g. 1344^2) was not timed.
- B200 has no kernel config: correctness only (everything stays native,
outputs bit-identical); no timing.
- Every arm ran with Studio's default compile; whether a captured CUDA
graph replays the op in these families is
covered by the unit test, not end to end (the per-render INT8 call
counts were counted on the Python side).
- AMD / ROCm, Windows and macOS: not run; the unset switch never routes
on ROCm.
danielhanchen added a commit that referenced this pull request Nov 15, 2026
…layout (#17798)

## Summary

Follow-up to #17718. The INT8 attention op
`unsloth_studio::int8_attention_nhd` registers a fake that returns
`v.new_empty(q.shape)`, a contiguous `[B, S, H, D]` tensor. Inductor
treats the fake's strides as part of the op contract and asserts them on
the real output. The kernels allocate a fresh contiguous `[B, S, H, D]`
output, so they match. The native fallback did not: it returns
`scaled_dot_product_attention(...).permute(0, 2, 1, 3)`, which keeps
SDPA's `[B, H, S, D]` layout whenever SDPA returns one (math SDPA, or
inputs that are views of a heads-first buffer).

So a compiled graph that reached the fallback failed at runtime:

```
AssertionError: expected size 11==11, stride 64==192 at dim=1; expected size 3==3, stride 704==64 at dim=2
Error in op: torch.ops.unsloth_studio.int8_attention_nhd.default
```

This reproduces with default `torch.compile`, `fullgraph=True`, and
`fullgraph=True, dynamic=True`. `torch.library.opcheck` passes, because
it never runs a compiled graph end to end, so only a real Inductor
execution catches it.

## Fix

The op body now returns `int8_attention_impl(q, k, v).contiguous()`.
This makes every real output use the fake's layout:

- Kernel outputs (CUDA and Triton) are already contiguous, so the call
is a no-op for them.
- SDPA backends that hand back a BSHD-contiguous result (flash,
efficient or cuDNN on contiguous BSHD inputs, which is how the
processors call the op) also skip the copy.
- The copy only happens when SDPA returned the permuted layout.

The fake is unchanged. The dispatch route in
`diffusion_int8_attention_dispatch.py` calls the same op and registers
no op or fake of its own, so this fix covers it too.

The copy goes in the op body rather than only in compiled graphs. Eager
and compiled calls both run the same body, and the body cannot tell
which one called it. Keeping one layout for every real output is the
only way the real and fake outputs stay consistent.

This adds no work in eager either. Every caller flattens the result
right away (`out.flatten(2, 3)` in the Flux3 and H3 strided processors,
and in the diffusers processors behind the dispatch route). On the
permuted layout that `flatten` already did the copy, as an `aten.clone`.
With this change `.contiguous()` does the copy and `flatten` becomes a
view. A dispatch-mode op count on CPU shows exactly one copy before and
after, for every combination of SDPA backend and input layout.

## Tests

`test_the_native_fallback_keeps_the_fake_layout_under_inductor` (CPU)
compiles a graph that calls the op on the native fallback and runs it
with Inductor. It covers `fullgraph=True` with static and dynamic
shapes, contiguous BSHD inputs and heads-first-backed strided inputs,
and default SDPA and math SDPA, at several sequence lengths. It checks
that the fallback really ran, that the compiled output matches eager,
and that the eager op output is contiguous and equal to
`native_attention`.

- On `main`: 6 of 8 cases fail with the Inductor stride assertion above.
The 2 cases that pass are contiguous BSHD inputs with default SDPA,
where the CPU SDPA result is already BSHD-contiguous.
- On this branch: 8 of 8 pass.
- INT8 suites on CPU (`test_diffusion_int8_attention.py`,
`test_diffusion_int8_attention_dispatch.py`,
`test_diffusion_int8_attention_triton_fallback.py`): 125 passed, 76
skipped (the CUDA-only tests).

On an NVIDIA L4 (torch 2.14.1+cu130, diffusers 0.42.1), comparing `main`
(f490069) with `main` plus this patch:

- INT8 suites: 188 passed, 12 skipped, 1 failed on this branch, and 180
passed, 12 skipped, 1 failed on `main` (the 8 extra passes are the new
test). The one failure is `test_video_load_passes_the_request` on both
sides, a missing `structlog` in the test venv, and it is unrelated to
this change.
- The same compiled fallback graph on CUDA (head dim 80, so no kernel
config and the native path runs), `fullgraph=True`, static and dynamic
shapes: 6 of 8 cases fail on `main` with the same stride assertion, and
8 of 8 pass here.
- A tiny Wan transformer with the dispatch route engaged (4 modules
routed, the kernel ran on all 4 attention calls), compiled with the
default settings, `fullgraph=True`, and `fullgraph=True, dynamic=True`:
0 graph breaks, and the output is bit-identical to `main` (eager and
compiled).
- Eager cost of `op(q, k, v).flatten(2, 3)` on the forced native
fallback, median of 3 x 300 timed calls per arm, two passes per arm:
with default SDPA every delta is inside the run-to-run spread, for both
input layouts, at 126-token audio, 512-token text, 4096x512 text
cross-attention and 1024-token image shapes. With math SDPA pinned,
deltas are -11 to +126 us on 0.5 to 20 ms calls (under 1%), and the
ranges mostly overlap.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant