Skip to content

Studio: INT8 attention on by default where it wins per card (T4 Klein 18% and Z-Image 14% faster, G4 Klein 6%) - #18004

Merged
danielhanchen merged 33 commits into
mainfrom
studio-int8-attention-defaults
Nov 16, 2026
Merged

danielhanchen merged 33 commits into
mainfrom
studio-int8-attention-defaults

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Studio's INT8 attention kernel was off by default for FLUX.3 Klein and Z-Image, and on T4 it never engaged when Speed was left unset. This turns it on by default where it is measured to be faster and accurate on that card, and keeps every other path exactly as it is:

card, 1024 px model main s / image this PR s / image change LPIPS vs main
T4 FLUX.3 Klein 36.37 30.97 17% faster 0.004
T4 (high-RAM Colab) Z-Image-Turbo (8 steps) 28.55 25.07 14% faster 0.034
T4 Qwen-Image-2.1, plain defaults 78.0 67.5 about 13% faster 0.0005
G4 FLUX.3 Klein 1.453 1.371 6% faster 0.008
L4 FLUX.3 Klein 8.82 8.61 2.5% faster 0.010
G4 Qwen-Image-2.1-Turbo 1.014 1.014 same 0 (bit-identical)
A100 FLUX.3 Klein 2.559 2.558 same compile variance, see below
A100 Qwen-Image-2.1-Turbo 1.899 1.900 same 0 (same path)

Three interleaved repeats per side unless noted (T4 Qwen-Image-2.1: two). The spread of repeated runs on one side is 0.1% to 2.2%. The T4 FLUX.3 Klein and Z-Image-Turbo rows are measured on this PR's final code; the other rows on the branch before the review fixes (lost-race give-back, non-finite errors, the CUDA-only check on the actual verdict, the sink path scoped to these three families, sink decisions learned per plan, forced requests kept on INT8, no race after a CUDA graph capture), which do not change the winning path on these cards. GPU pytest of the INT8 attention tests at the final code: 232 passed, 0 failed on both T4 and G4 (6 two-GPU tests skipped).

Change

  • Per-card decision, per shape. For FLUX.3 Klein, Z-Image and Qwen-Image-2.1, the first call at each shape runs an accuracy check, then races the INT8 attention paths against torch attention. INT8 stays only where it wins. The decision is shared across prompts whose token counts fall in the same 256-token bucket.
  • Attention sinks. A shape whose keys carry sinks races the sink-aware INT8 path, the previous INT8 kernels and torch attention.
    • The previous kernels only qualify if their error is within 1.15x of the sink path's.
    • Where they qualify, the sink path must beat them by 2%, the same margin the other races use.
    • A near tie keeps the previous kernels, so Qwen-Image-2.1-Turbo stays bit-identical to main on G4. Klein and Z-Image keep the sink path, since without it their error doubles.
  • Losing the race hands back exactly what main runs. When torch attention wins on a card, every raced processor hands back the processor main would have installed, before any CUDA graph is captured. FLUX.3 also keeps main's fused Q/K processor.
  • Speed left unset. INT8 attention now races when Speed is left unset and no deferred speed profile follows (on T4 that is the default; elsewhere it also covers loads that skip compile, such as Windows without Triton or a quantized DiT), for the three families above only. The per-card accuracy check and race still decide. An explicit Speed Off still gives bit-identical output, and Wan and other families behave exactly as on main.
  • MiniMax-H3-Image no longer turns INT8 attention on by itself; UNSLOTH_DIFFUSION_INT8_ATTENTION_KERNEL=1 still forces it. LTX-2.5 stays opt-in.
  • Graph capture safety. The race and the sink path's event waits run only while no other thread is recording a CUDA graph.

A100 FLUX.3 Klein image difference

A100 Klein images differ from main by LPIPS 0.0046 on average. This is cold-compile variance, not this change:

  • Two cold compiles of unchanged main differ from each other by the same per-prompt amounts (0.0006 to 0.0145), and reusing a warm compile cache reproduces main exactly.
  • One cold compile of this PR was bit-identical to main.
  • After the race, all 43 attention modules carry the same processor class and attributes as main, and global attention flags match.
  • With compile off, this PR equals main bit for bit.

LoRA

INT8 attention keeps a LoRA's effect. The LoRA is sent with every request, LPIPS is the mean over prompts, and the noise control adds a deterministic perturbation of INT8's per-call size to native attention:

L4 Klein L4 Z-Image T4 Qwen-Image-2.1 T4 Z-Image
INT8 vs native, no LoRA 0.0040 0.0255 0.0025 0.0373
INT8 vs native, with LoRA 0.0030 0.0307 0.0023 0.0384
noise control vs native, no LoRA to with LoRA 0.0046 to 0.0030 0.0189 to 0.0277
LoRA effect, native / INT8 0.045 / 0.047 0.079 / 0.083 0.050 / 0.051 0.094 / 0.097
weight 0 vs no LoRA identical (INT8 Klein 0.00006) identical identical identical

Z-Image's INT8 gap grows 1.2x with a LoRA on L4. A non-INT8 perturbation of the same per-call size grows 1.46x, so the growth comes from the LoRA's trajectory, not INT8; INT8's per-call error barely moves (0.026 to 0.028).

Tests

  • New tests/test_diffusion_int8_attention_auto.py (17) and additions to the INT8 attention, dispatch, speed, FLUX.3 strided attention and Q/K tests. Every fix has a test that fails before it.
  • GPU pytest on G4 at this head: 253 passed, 7 skipped, 0 failed.
  • CPU, all tests/test_diffusion_*.py, this PR vs main: every test that fails only on this PR in the parallel run passes when rerun on its own on both trees, apart from two test_diffusion_backend.py stubs that did not take the new speed_unset_only argument (updated here). test_diffusion_backend.py now fails only the test main also fails (a missing gguf module in the test environment).

Not covered

  • Wan and LTX were not measured, and both keep main's behaviour.
  • AMD and compute-sanitizer were not run; ROCm is excluded from these kernels.
  • Turbo was checked against main's images, not against a separate native reference.

FLUX.3 Klein and Klein Base never raced the INT8 kernel with the switch unset:
the strided processors ran it only when unsloth_int8 was requested by name or
the env switch forced it (install_requested), so every default load kept the
incumbent and the race was never timed.

install_auto now races the strided processors of a DiT listed in AUTO_DITS
the way the dispatch route does (accuracy check, card race, 2048 / long
races, MIN_TOKENS floor), only when the load left the attention pick to
Studio, speed is on and the card is NVIDIA. The 80-token text-mode calls stay
on the incumbent through the floor. Flux3Transformer2DModel joins AUTO_DITS;
its strided processors are skipped by the dispatch route as before.
A few V keys 60-85x the median key norm in most channels (the first text
tokens of a joint sequence: Z-Image caption tokens 1-2, FLUX.3 text token 1)
set every channel's range over all keys. They draw under 1% of the attention,
but every other key lost its resolution: on captured Z-Image and FLUX.3 calls
V quantisation carried 90%+ of the kernel error (module output rel L2
0.031-0.043). Clipping them is no fix (0.29-0.67): their exact value matters.

The stats pass now also records each chunk's largest |v| and its key. A head
whose full range is more than 8x its range without the chunk holding its
largest |v| quantises with that robust range (x1.5, never past the full
range), clips that chunk in place, and a residual job lists the clipped keys
in key order with the part clipped off; the attention epilogue adds each one
times its exact P from the main loop's own int8 score. Every other head keeps
the full range bit for bit. Emulated on the captured calls: 0.0425 -> 0.0128
(Z-Image layer 26), 0.0312 -> 0.0072 (layer 17), 0.0367 -> 0.0092 (FLUX.3
single block 3); calls without sinks unchanged. CUDA kernel only: the Triton
kernel keeps the range over every key.
The strided install's verdict line gained the 2048 / long race field without a
format slot, so with a logger (Studio always passes one) the log call raised
after the processors were flagged: the kernel ran but the install reported 0
and the load showed the incumbent backend. Test the install with a logger.
The synthetic sinks are 120 out and the bound is 2.5x the sink-free error:
the range over every key gives 4.5x or more there, the clipped range with the
exact residual at most 2.4x (fp64 model, 24 cases). Check the error before the
operands, so the test also fails on a kernel without the residual.
…e CUDA kernel

Their accuracy was measured on the CUDA kernel, whose V range handles
attention sinks; the Triton stand-in (no NVRTC) keeps the range over every
key. With the switch unset such a card keeps the incumbent for them; a
request by name or the env switch still routes, and Qwen-Image / Wan keep
racing the stand-in as before.
With V kept resolved past its attention sinks (caption tokens 1-2), the
kernel's per-step error on Z-Image-Turbo is within that of its shipped INT8
weights: median / max rel L2 vs bf16 0.022 / 0.048 against 0.024 / 0.073
(0.034 / 0.100 before), teacher-forced over 8 prompts x 3 steps on an RTX
PRO 6000. The card race still decides; LTX-2 stays opt-in.
Each key the epilogue adds back costs about a fifth of a key tile, and the
card race (Gaussian probes, no sinks) does not see it: on FLUX.3 the clipped
chunk holds the 80 text tokens, up to 45 keys a head went there and the A100
load came out 0.6% slower than native while the race said faster. The robust
range is now widened 2x and only keys clipped by more than 0.25 of the gain
go to the epilogue (the sink and a few keys near it: 1-13 a head on FLUX.3,
2-5 on Z-Image); emulated module error on the captured calls 0.0103 / 0.0141
/ 0.0080 (FLUX.3 block 3 / Z-Image layers 26 / 17) against 0.037 / 0.043 /
0.031 with the range over every key.
The clip test now asks for at least half the channels to have a full range
more than 2x their range without the chunk of the head's largest |v|: real
sinks are far out in 63-95% of the channels (FLUX.3, Z-Image captures),
heavy-tailed V with no sink (log-normal, Student-t) in at most 9%, where the
old 'any channel above 8x' test clipped and dropped small residuals (cos
0.9988 on the log-normal padded-keys probe). Calls without sinks keep the
full range bit for bit, Qwen-Image-2.1 included.
…unch

The residual loop in the attention kernel's epilogue changed how the
compiler allocated the whole kernel: head dim 64 spilled 32-56 bytes on
sm75 / sm80 / sm120 where it spilled none or less before (T4: attention
6.5% slower at head dim 64), for every call, sinks or not. The kernel
now only writes the row maximum and normaliser of each row after its
output, and unsloth_i8resid (a warp per row, the same int8 score, exact
P and frame as before) adds the clipped keys to the rows of the heads
that have any; heads without them return at once. The main loop is the
base kernel's again (same registers and stack on every shipped config
except 8 bytes stored once and loaded once outside the loop on sm120
head dim 128). The sink test bound is 4x the sink-free error: the fp64
model itself reaches 3.1x on the fp16 T4 case, the full range 5.5x.
…as before

The sink path cost every call 1-3% on sm120 head dim 128 (the
attention kernel's schedule moves with any added code, measured
against an A/A arm), plus a residual launch and the robust V range,
also where no head ever clips (Wan, Qwen-Image, LTX-2.5, H3).

The CUDA sources now compile the sink path only with SINKS defined;
without it they give the PTX of the kernels before the sink path,
byte for byte, on every shipped config and architecture. A launch
plan's first 64 calls take the sink path and copy their clipped-key
counts to pinned memory behind the quantisers; at its 128th call a
plan none of them clipped switches to the kernels without the path
(the same bits: no head of it clips), and one with sinks keeps it.
The decision depends only on those calls, never on timing, and a
CUDA graph capture keeps what the plan has decided.
The races time on probe inputs, which have no attention sinks; inside
_median_ms every kernel call now takes the kernels a plan without
sinks runs and counts toward no plan's decision, so the race verdicts
of the families without sinks are the ones from before the sink path.
SINK_MIN 1/4 let keys just outside the robust range stay clipped by up
to a quarter of the gain: on the FLUX.3 capture the V error of the
clipping heads was 16% above that of an exact residual for every
clipped key, and one head ended worse than with the full range. At
1/16 it is 0.4% above it, with 2-25 keys a head (FLUX.3, Z-Image).
unsloth_i8resid now stages those keys' K rows, residuals and scales in
shared memory (32 at a time, once where there are no more) instead of
reading them per row from the L2 cache.
The launch plans are keyed by shapes, so a pipeline loaded after
another one with the same attention shapes inherited what the first
one's calls decided about attention sinks. apply_attention_backend now
drops the plans on every load with a target; the next calls decide
again.
The card race times on probe inputs without attention sinks, so it
cannot see what the sink path costs: on A100 FLUX.3 Klein at 1024^2
won the race at 4096 tokens by 3% and then rendered 1.2% slower than
torch's attention. A plan that decides it has sinks now times the sink
path against torch's attention on that call's own inputs (interleaved,
median, RACE_MARGIN, logged) and runs torch's attention from then on
where the path loses. Plans without sinks are unchanged.
…recorded

A denoiser forward recorded as a CUDA graph replays without calling the
kernel's Python, so a launch plan still learning at the capture kept
the sink path for good and never raced it (FLUX.3 Klein on A100 stayed
1% slower than torch's attention). Plans now learn over 32 calls and
decide at their 48th, within the three eager warm-up forwards.
… it, share decisions per bucket, drop losing buckets from the routes
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 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-16T20:12:12.090678Z 1c8ef05 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: feb6263fe8

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

"impl": implementation(_device_index(dev), head_dim),
"error": "CUDA kernel only",
}, None
return dispatch._card_floor(dev, dt, heads, head_dim, fn, name, False, False)

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 Recheck CUDA-only eligibility after the card verdict

On a card whose CUDA kernel has not been tried yet, implementation() optimistically returns "cuda", so this guard passes even if NVRTC is missing or compilation subsequently fails. _card_floor() calls verdict(), which explicitly retries with Triton after such failures and can return a winning Triton verdict. This then automatically enables INT8 attention for FLUX.3 despite its AUTO_CUDA_ONLY restriction, bypassing the sink-aware CUDA implementation on which automatic eligibility was validated. The dispatch install has the same pre-verdict check for Z-Image. Check the returned verdict's implementation before accepting either automatic route.

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.

Agreed: the CUDA-only rule now checks the implementation the verdict actually ran with, so a CUDA attempt that fails and falls back to a winning Triton verdict refuses the automatic route on both the FLUX.3 strided and the Z-Image dispatch paths, and the module keeps its original processor. Fix and a fails-before test in the next push.

… replaced

install_auto swapped FLUX.3's stock processors to the strided class before the
race and left them there when torch won or the accuracy check failed, so the
fused Q/K processor main installs never replaced them. Give the stock processor
back for every module that did not engage, and keep the dispatch route from
racing it again.
_pick_path compared errors with <=, so a NaN sink-path error skipped the
slack rule and left the sink path first in line: a broken output on the
deciding call was kept whenever it timed faster than torch. A non-finite
error now disqualifies its path; with neither finite, torch's attention.
implementation() reads "cuda" on a card whose kernel was not tried yet, so
the CUDA-only guard passed before the verdict; verdict() then fell back to
Triton when NVRTC was missing or the compile failed, and a winning Triton
verdict engaged FLUX.3 (strided) and Z-Image (dispatch) automatically. Check
the implementation the verdict ran on; the refused modules keep their own
processor. Forced and by-name requests are unchanged.
…s measured on

Every CUDA kernel call took the attention-sink path for a plan's first calls
and could race it against torch afterwards, so existing routes (Wan, LTX,
MiniMax, forced requests on any family) changed numerics on heads with
sinks. A route now carries a mode: FLUX.3, Z-Image and Qwen-Image-2.1 run
the sink path with its race; every other route, and the probes, run the
kernels as before it, with the same call into the op. The sink routes
trace into a second op so the main op keeps its schema.
…he sink race

A request by name or the env switch for FLUX.3, Z-Image or Qwen-Image-2.1
raced its sink path against torch's attention like the automatic route, and
could run torch's attention for a shape with sinks. Forced routes now race
the INT8 paths only (same error slack and margin), with the kernels from
before the sink path where neither error is finite or the race runs out of
memory.
…out sinks

A new prompt length in a decided 256-token bucket took that bucket's verdict
at once, so a plan whose first calls had no sinks could hand its kernels
without the sink path to a shape that has them. Each plan now learns its own
first calls; the bucket's verdict is keyed on whether they had sinks and only
saves the race.
… is recorded

A plan decided after a capture could hand its calls (and through the routes,
the module's processor) to torch's attention while the recorded graph kept
replaying the kernel. Once a sink-route call is recorded, an undecided plan
with sinks keeps the sink path the graph recorded, with no race and no
route change; a new pipeline races again.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 1c8ef05ff5

ℹ️ 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 b2ad0b4 into main Nov 16, 2026
@danielhanchen
danielhanchen deleted the studio-int8-attention-defaults branch November 16, 2026 21:56
danielhanchen added a commit that referenced this pull request Nov 16, 2026
…on mode (diffusion red since #18004) (#18035)

## Summary

#18004 (INT8 attention on by default) gave `quantise` and
`_cuda_attention` in `core/inference/diffusion_int8_attention.py` a new
`mode` argument.
`studio/backend/tests/test_diffusion_int8_attention_long_probe.py` (from
#17796) replaces both with CPU stand-ins that still take the old
arguments. All 7 tests in the file fail on main, which makes `(Python
3.13, diffusion)` red for every PR based on `b2ad0b4493` or later:

```
TypeError: _fake_card.<locals>.quantise() takes from 4 to 5 positional arguments but 6 were given
KeyError: 'long'
assert (False)
```

The `KeyError` and the failed asserts follow from the same `TypeError`:
the card check catches the error from the stand-in and reports a failed
check, so the assertions about what it verified fail. With only the
stand-ins updated, all 7 pass.

The change in #18004 is fine. The test's fakes did not follow it.

## Change

- The fake `quantise` takes `mode` (default `MODE_MAIN`), and the
`_cuda_attention` stand-in becomes a function with the same parameters
as the real one and passes `mode` through.
- `_fake_card` now checks that each stand-in takes exactly the real
function's parameters, by name. The next signature change then fails
every test with `update the fake quantise: it takes [...]`, instead of a
`TypeError` that the card check swallows and turns into confusing
assertion failures.

No production code changes.

## Verification

- `tests/test_diffusion_int8_attention_long_probe.py`: 7 failed on main,
7 passed with this change.
- Adding a parameter to the real `quantise` makes all 7 fail with the
`update the fake quantise` message.
- `tests/test_diffusion_int8*.py` and
`tests/test_diffusion_attention*.py`: 1044 passed, 307 skipped.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 17, 2026
…-1.5 where it wins per card (unslothai#18085)

## Summary

These families call diffusers' `dispatch_attention_fn` but were never
raced for INT8 attention while the switch is unset:
- FLUX.1 (dev, schnell, Kontext);
- FLUX.2 (klein, dev);
- HunyuanVideo-1.5.

This PR adds them to `AUTO_DITS`, `AUTO_CUDA_ONLY` and the
attention-sink set (`SINK_DITS`). The two FLUX classes also go into
`SPEED_UNSET_DITS`, which T4 uses by default. The per-card accuracy
check and race then decide, as for FLUX.3, Qwen-Image-2.1, Wan and
Z-Image.

HunyuanVideo-1.5 also needed a fix. Studio's padded-text trim processor
captured `dispatch_attention_fn` in a closure, so the route never saw
its calls: 0 modules routed on main, even when forced. It now reads the
function from diffusers' module at call time, with the same call and
arguments.

**Staying off:**
- **Qwen-Image (v1 / Edit / 2512):** stays request-only on accuracy. On
G4, the per-step error max is 0.031 against 0.0125 for its INT8 weights,
and 50-step images are LPIPS 0.145 from native.
- **HunyuanImage-2.1 and Krea-2:** they attend with a text padding mask
on every call, so there is nothing to route.

## Results

Colab, main vs this branch, 3 interleaved repeats each. Error is
teacher-forced per-step rel L2 against bf16 weights with native
attention, the same gate unslothai#18004 uses.

| family | GPU | main | branch | delta | A/A spread | per-step error
(kernel vs INT8 weights) | LPIPS mean / max | engaged |
|---|---|---|---|---|---|---|---|---|
| FLUX.2 klein 4B | T4 | 11.876 s | 10.305 s | +15.3% | 3.07% | 0.029 /
0.043 | 0.010 / 0.028 | 25 modules |
| FLUX.2 klein 4B | L4 | 2.002 s | 1.886 s | +6.1% | 1.35% | 0.049 /
0.064 | 0.017 / 0.042 | 25 modules |
| FLUX.2 klein 4B | G4 | 0.355 s | 0.345 s | +2.9% | 1.27% | 0.034 /
0.048 vs 0.046 / 0.062 | 0.025 / 0.051 | 25 modules |
| FLUX.1 schnell | T4 High-RAM | 24.834 s | 21.364 s | +16.2% | 1.04% |
0.025 / 0.134 | 0.050 / 0.104 | 57 modules |
| FLUX.1 schnell | L4 | 4.885 s | 4.58 s | +6.7% | 2.4% | max 0.21 |
0.083 / 0.174 | 57 modules |
| FLUX.1 schnell | G4 | 0.696 s | 0.643 s | +8.2% | 0.36% | 0.028 /
0.104 vs 0.057 / 0.169 | 0.077 / 0.172 | 57 modules |
| HunyuanVideo-1.5 480p, 61 frames | G4 | 53.475 s/clip | 40.964 s/clip
| +30.5% | 0.17% | 0.0087 / 0.0113 vs 0.019 / 0.024 | see below | 54
modules |

- **Error columns:** G4 rows show the gate (kernel alone vs INT8 weights
alone, both against bf16). T4 and L4 rows are this branch against main
at that card's defaults.
- **FLUX.2:** races picked the attention-sink path on every card;
without it the error was 1.2 to 1.3x higher.
- **HunyuanVideo-1.5 LPIPS cannot test the 0.05 video bar here.** Main
is not repeatable on G4: main against itself gives 0.16 to 0.29, while
this branch against itself gives 0. The per-step error (0.0087,
including a 0.0059 native-to-native floor) is the accuracy evidence. It
is under half the INT8-weight error.

## Testing

- **CPU:** new `test_diffusion_int8_attention_families.py`, 25 tests
plus 4 CUDA ones. It covers which families race when unset, the
speed-unset rule, a lost race keeping the incumbent, the kill switches,
Qwen and the masked families staying off, and the HunyuanVideo-1.5 trim
route.
- The exact-set assertions in
`test_diffusion_int8_attention_dispatch.py` are updated.
  - Main: 8 fail.
  - This branch: the INT8 suites pass (169 passed).
- **GPU:** pytest on T4 (sm75) and G4 (sm120) passes: 256 passed, 6
skipped (two-GPU tests).
- **Not covered:**
  - A100 was not measured; the per-card race decides there.
- FLUX.1 dev / Kontext, FLUX.2 dev / klein 9B and HunyuanVideo-1.5 at
720p or i2v follow the same per-class rule, but were not measured
directly.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 17, 2026
…ded cuDNN admits only the probed dtype, fused int8 takes plain SYMMETRIC only, `_int_mm` fallback stays on the operand's card (unslothai#18140)

Fixes from a re-check of recent Studio INT8 kernel PRs.

1. **CFG replicas lose the INT8 sink mode (unslothai#18004, route from unslothai#17758).**
`Int8Route.__reduce__`
(`studio/backend/core/inference/diffusion_int8_attention_dispatch.py`)
rebuilt the route from its constructor arguments only, so
`copy.deepcopy` (Studio's CFG-parallel replica builder), `copy.copy` and
pickle reset the sink kernel mode chosen at install to 0. With CFG split
across two cards, the replica ran the plain INT8 path while the primary
ran the sink path, so the guided output depended on the card count. The
reduce tuple now carries the mode as state.
2. **Qwen-Image-2.1 strided cuDNN (unslothai#18083).** The `StridedCudnn` marker
kept only the probed card ids, so a bf16 probe also sent fp16 calls (an
autocast, or a later cast of the pipe) down the strided path. The marker
now carries the probed dtype, `plain_qkv` declines other dtypes, and a
re-install at a new dtype probes that dtype. The INT8 dispatch race
named the strided incumbent `dispatch:_native_cudnn`, the same key as
the contiguous cuDNN call, so cached verdicts crossed over; it now races
as `dispatch:_native_cudnn:strided`. The GPU no-copy check asserted
`flatten(2, 3).is_contiguous()`, which also holds when flatten copies;
it now checks the flatten shares storage.
3. **Fused act quant and exact ConvRot take plain SYMMETRIC weights only
(unslothai#17114, unslothai#17617).** `_plain_int8_weight` accepted any mapping containing
SYMMETRIC, so a torchao weight with `SYMMETRIC_NO_CLIPPING_ERR`
activation quant reached kernels that always divide amax by 127.5.
Studio's own loaders build plain SYMMETRIC only, so this narrows a path
no Studio load takes.
4. **`_int_mm` off-grid fallback returns on the operand's card (unslothai#17613,
inherited from torchao).** For K or N not a multiple of 8 the safe
`_int_mm` wrapper (Studio `diffusion_torchao_patches.py` and the copy in
`unsloth/import_fixes.py`) ran the matmul on the CPU and moved the
result with `.to(input.device.type)`, which is the current card. With
the operands on cuda:1 and cuda:0 current, the int32 result landed on
cuda:0. It now moves back to `input.device`.
5. **FLUX.3 strided attention: a test for the no-copy claim (unslothai#17180).**
No test checked it: restoring diffusers' `.contiguous()` copies passed
every test. The new test spies on `scaled_dot_product_attention` and
asserts Q / K / V arrive as the permuted views. Test only.

### GPU results, base (main 62d66cb) vs this branch

CFG sink mode, Kaggle 2x T4 (sm75), torch 2.11.0+cu130, diffusers
0.42.1. Tiny FLUX.1 transformer with random weights at the real head dim
(128), fp16, one attention-sink key; Studio's `CfgParallelRouter` with
the replica built by `build_replica` on cuda:1; INT8 attention installed
with the sink kernels (mode 2, NVRTC CUDA kernel) on both cards; guided
3-step render, cond on cuda:0 and uncond on the replica.

| | base | this branch |
|---|---|---|
| sink mode, primary (cuda:0) | 2, 2 | 2, 2 |
| sink mode, replica (cuda:1) | **0, 0** | **2, 2** |
| kernel path on cuda:1 | plain x4 | sink x4 |
| final latent, CFG split vs single card | rel L2 4.82e-4, max abs
3.9e-3 | bitwise equal |
| uncond step 2, CFG split vs native attention | rel L2 6.43e-4 (single
card 6.11e-4) | 6.11e-4, same as single card |

`_int_mm` fallback, same Kaggle 2x T4: int8 operands on cuda:1, cuda:0
current, both copies of `_make_safe_int_mm` with the real `out_dtype`.

| case (Studio and core copies alike) | base | this branch |
|---|---|---|
| K=65 (off grid) | result on cuda:0 (values exact); the next op with a
cuda:1 tensor raises "Expected all tensors to be on the same device" |
result on cuda:1, exact |
| N=36 (off grid) | result on cuda:0, same error | result on cuda:1,
exact |
| K=64, N=32 (cuBLAS, control) | cuda:1 | cuda:1 |

L4 (sm89), Colab, torch 2.12.1+cu130, cuDNN 9.20.0, torchao 0.17.0:

| fix | check | base | this branch |
|---|---|---|---|
| strided cuDNN | tiny QwenImage21, bf16 probe at install, then the pipe
cast to fp16 | fp16 call takes the strided path (marker has no dtype) |
fp16 call goes to diffusers; marker records bf16 |
| strided cuDNN | fp16 output vs diffusers cuDNN | equal (on L4 the fp16
strided call happens to be correct; the defect is the admission) | equal
|
| plain SYMMETRIC | Int8Tensor FeedForward 256 to 1024,
`SYMMETRIC_NO_CLIPPING_ERR` weights | fused, identical to the SYMMETRIC
result, differs from torchao in 106941 of 153600 elements (max abs
0.086) | stays on torchao, bitwise equal |
| plain SYMMETRIC | plain SYMMETRIC weights | fused, bitwise equal to
torchao | same, same hash as base |
| no-copy test | real cuDNN, bf16, head dim 128 | SDPA gets the views |
SDPA gets the views; with the copies restored it gets contiguous tensors
and the new test fails |

### Tests

-
`studio/backend/tests/test_diffusion_int8_attention_dispatch.py::test_route_copies_keep_the_sink_mode[1|2]`:
fails on main.
- On the T4 pair: `test_diffusion_int8_attention_dispatch.py` base 2
failed (`test_route_copies_keep_the_sink_mode[1|2]`) / 46 passed, this
branch 48 passed with the two-card tests included.
-
`studio/backend/tests/test_torchao_int_mm_transposed.py::test_off_grid_fallback_returns_on_the_operand_card`:
fails on main; on the T4 pair base 1 failed / 9 passed, this branch 10
passed (including the CUDA transposed `_int_mm` exactness cases).
- `studio/backend/tests/test_diffusion_qwenimage21_strided_attn.py`:
`test_marker_admits_only_its_probed_dtype`,
`test_reinstall_at_a_new_dtype_probes_it`,
`test_strided_incumbent_races_under_its_own_name` fail on main; on the
L4 base 3 failed / 14 passed, this branch 17 passed, and the GPU bitwise
test ran in both arms.
-
`studio/backend/tests/test_diffusion_int8_fused.py::test_only_plain_symmetric_activation_quant_is_eligible[SYMMETRIC_NO_CLIPPING_ERR-False]`:
fails on main; on the L4 this branch 101 passed / 1 skipped (a torchao
>= 0.18 case).
-
`studio/backend/tests/test_diffusion_flux3_strided_attn.py::test_strided_processor_hands_sdpa_the_projection_views`:
passes on main, fails with the copies restored.
- CPU (torch 2.14.1) on this branch: the five files pass (100 passed, 78
skipped, running the Qwen-Image-2.1 file in its own process). Running
the Qwen-Image-2.1 file in one pytest process with the others,
`test_real_processor_decode_call_takes_the_strided_path` hits a
RecursionError on main and on this branch alike (test-order interaction,
not touched here).

### Not covered

- No real checkpoint or decoded image: the CFG check compares DiT
latents of a tiny random model, and the auto (raced) route was not
exercised (the dropped field is the same for any non-zero mode).
- sm80 and sm120 cards; the strided cuDNN and SYMMETRIC fixes ran on L4
only, the CFG and `_int_mm` checks on T4 only.
- torchao 0.18 for the SYMMETRIC narrowing.
- The GPU runs used main 62d66cb; the branch was then rebased onto
main 142c398 and only the CPU tests were rerun there.
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