Skip to content

Studio: key the int8 CUTLASS race cache on the race code, not the whole GEMM file - #18797

Merged
danielhanchen merged 2 commits into
mainfrom
studio-int8-cutlass-race-key
Nov 21, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-int8-cutlass-race-key

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

The int8 CUTLASS race cache key hashed diffusion_int8_gemm.py and diffusion_int8_cutlass.py byte for byte. Any Studio update that touched either file re-raced every int8 weight shape on the next load, including changes to install routes, the SwiGLU fusion, logging or a docstring. On an L4 that race costs about 6 s per weight shape, so a full model pays it again after every such update. It also does not give the same answer twice: on the L4 run below, a re-race with nothing changed but a new helper function picked different tiles for some shapes than the first race did.

Change

_sources_digest now hashes only the code that decides a race verdict. Each piece is hashed as parsed code (ast.unparse, docstrings dropped), so comments and formatting do not reach the key either. The keyed code, listed in _RACE_SOURCES:

  • Today's path the race runs against: the Triton kernels (_kernels), _launch, _launch_or_ref, tile_for, _aligned, the eager reference, and _prefetch_fix_key.
  • The plan and the race: _cutlass_plan, _cutlass_tile, _huge_race_fits, plus the race points, row buckets, _MARGIN, short and sustained timing, sustained_decides, the candidate filter (has_kernel, eligible) and the probe that decides which tiles are candidates (probed_tiles, _probe_tile, _PROBE_SHAPES, _scale_dtypes, tiles, tie_operands) and how a cached entry is read back (slot, large_slots).
  • The prebuilt kernels: launch, _bind, ABI_VERSION, reference_native, and native_prepare (the T4 native-epilogue race shares this key).
  • The sm_8x Triton prefetch fix: keyed on its salt, _TRITON_PREFETCH_SALT, which is bumped with any change to the codegen it patches.

The key also gains two fields:

  • The Triton tile today's path runs on this card, plus its shape rules and the prefetch fix state. device_config has already settled these before any plan. An edit to the arch table, a shape rule or an unlisted-card Triton race re-races only the cards whose tile it moves.
  • UNSLOTH_DIFFUSION_INT8_CUTLASS mode. force keeps the fastest CUTLASS tile even when it loses to today's path. Before this change it shared a key with auto, so each mode read back the other's verdicts.

These fields stay unchanged: library bytes (the tile set and the kernels themselves), card name, capability, torch / CUDA / Triton versions, the tiles and unlisted env vars, and the sustained timing mode.

_RACE_FORMAT forces a re-race on purpose, for a change outside the keyed code that still moves race results. A name in _RACE_SOURCES that no longer exists is hashed as <missing>, and a test fails on it, so a renamed function cannot silently drop out of the key.

The first load after this lands re-races once, because the key format changed. Correctness never depended on the key: probed_tiles proves every tile bit-exact in every process, and a cached winner that is not among this process's probed tiles is raced again.

Numbers (Colab L4, one VM, fresh process per step, one Studio home per tree)

The 10 int8 Linear shapes are FLUX.3 klein and Qwen-Image sized, with 3 race points each.

step main: raced points main: plan wall this branch: raced points this branch: plan wall
cold home 30 63.2 s 30 62.9 s
again, no edit 0 1.3 s 0 1.4 s
new helper function appended to diffusion_int8_gemm.py 30 62.7 s 0 1.4 s
_MARGIN 0.02 to 0.021 in diffusion_int8_cutlass.py 30 62.8 s 30 62.9 s

After the unrelated edit, this branch reads back the first race's plan exactly. Main's re-race chose different tiles for some shapes. The key on the card was ...|cutlass=auto|today=(256, 128, 128, 8, 8, 3)+()+fix=True|<digest>, which shows the real Triton tile and prefetch fix state were read.

Tests

  • tests/test_diffusion_int8_cutlass_race_key.py (new, CPU, 19 cases). It works on temp copies of the three modules and a fake card.
    • These edits keep the cached verdict: a new helper function, an install-path edit, a comment in the Triton launch, the race docstring, a reformatted race constant, and a native runtime helper.
    • These edits invalidate it: the Triton kernel body, the Triton launch options, today's path pick, the race margin, the race points, the sustained window, the prebuilt kernels' launch, the prefetch fix salt, and a new library build.
    • Also covered: today's tile and the prefetch fix state are part of this card's key (another card's tile is not), force does not reuse auto verdicts, every keyed name still exists, and the real sources give a stable key across processes.
  • tests/test_diffusion_int8_cutlass_lib_digest.py: the last test now checks the digest against the keyed code plus the library bytes, instead of the whole files.
  • test_differential.py against the merge base: DISCRIMINATING, 9 FIXED, 0 head-only failures.
  • The diffusion int8, CUTLASS and prefetch test files were run against base and head: 1198 unchanged, 9 fixed. 66 tests fail on both trees on this CPU host (attention dispatch, families, fused, and similar); none are in the CUTLASS or GEMM test files.

Not proven here

  • Only an L4 ran. The T4 native-epilogue cache shares this key but was not run on a T4.
  • The plan was timed through _cutlass_plan on torchao Linears, not through a full model load.

…MM file

The int8 CUTLASS race cache key hashed diffusion_int8_gemm.py and
diffusion_int8_cutlass.py byte for byte, so any Studio update touching
either file (install routes, SwiGLU fusion, logging, docstrings) re-raced
every int8 weight shape on the next load, about 20 s per model on an L4.

The key now hashes, as parsed code with docstrings and comments dropped,
only what decides a verdict: the Triton kernel and launch that today's
path runs, the tile pick, the eager epilogue, the plan, the race points,
timing, margin and candidate filter, the prebuilt kernels' launch and the
sm_8x prefetch fix salt. It adds the Triton tile today's path runs on
this card (so an arch table or unlisted-card race edit re-races only the
cards it moves) and the CUTLASS force/auto mode, which picked winners
differently under one key. Library bytes, card, toolchain and env fields
stay. _RACE_FORMAT forces a re-race on purpose.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 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-21T19:12:46.603721Z d8f2d7d Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 64e24b8cb6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: d8f2d7d69c

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

## Summary

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

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

## Evidence

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

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

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

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

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

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

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

## Tests

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

## Not covered

- No real FLUX.2 model load was timed end to end. The L4 numbers come
from the image processor with the real kernels, on a pipe placed on the
GPU.
- sm86 was not run on hardware. The case for it rests on the identical
compiled defines above.
- Windows was not run. Nothing here is OS specific.
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…ntion plan keys, CUTLASS live race key, step-skip sample= shape (#18981)

Four small fixes from a recheck of the merged FLUX.1 ConvRot GELU
(#18766), INT8 attention sink fold (#18786), CUTLASS race key (#18797)
and SDXL static step skip (#18826) changes. Each one is its own commit
with a test that fails before it and passes after.

## Changes

1. **FLUX.1 ConvRot GELU gate traces on torch 2.10 / 2.11**
(`diffusion_convrot_quant.py`). `convrot_gelu_act_quant` chose its row
threshold with `rows[prefix is None]`. Dynamo on torch 2.10 and 2.11
cannot trace a tuple indexed by a bool. With `fullgraph=True` the
compile raises `Unsupported`; without it, every armed FF / single-block
down projection graph-breaks. torch 2.6 and 2.12+ accept it. The index
is now `1 if prefix is None else 0`, which selects the same entry.
2. **INT8 attention launch plans follow the kernel switches**
(`diffusion_int8_attention.py`). `_plan` reads
`UNSLOTH_DIFFUSION_INT8_ATTENTION_RESID_FOLD`, and `kernel_variant`
reads the sink order and native P switches, when a plan picks its
kernels. The warm lookup in `_find_plan` did not key on them. Flipping
the fold off in a running process therefore left warm shapes on the
folded kernel until `forget_plans`. The plan key now includes the three
switches as set. That costs three env reads, about 1.7 us of host time
per call, and nothing under CUDA graph replay.
3. **CUTLASS race key covers the live row race**
(`diffusion_int8_gemm.py`). `_live_row_race` decides which calls race
and applies the `force` pick. It also writes its winner into the same
disk entry that `_cutlass_plan` reads back on the next load. Neither it
nor `live_race_enabled` was in `_RACE_SOURCES`, so an edit confined to
the live race kept old verdicts. Both are keyed now. This applies
cleanly on top of the open race-key closure change, whose closure test
still passes with both applied.
4. **Step skip reads `sample=`** (`diffusion_step_skip.py`). The reuse
key took the latent from `hidden_states` or the first positional
argument. A `UNet2DConditionModel` called with `sample=` was therefore
keyed with shape `None`, and a skipped step after a latent shape change
returned the previous output at the old size. The stock SDXL pipeline
passes the latent positionally, so Studio's own renders were not
affected.

## Tests (CPU, base = parent commit, head = this branch)

| Test | Base | Head |
|---|---|---|
| `test_diffusion_convrot_gelu_route_trace.py` on torch 2.10.0 / 2.11.0
| 2 failed, 1 passed | 3 passed |
| same on torch 2.6.0 / 2.12.1 / 2.13.0 / 2.14.1 | n/a | 3 passed |
|
`test_diffusion_int8_attention_resid_fold.py::test_a_warm_plan_follows_the_kill_switch`
| failed (warm plan reused) | passed |
| `test_diffusion_int8_cutlass_race_key.py` (3 new live race cases) | 3
failed, 27 passed | 30 passed |
|
`test_diffusion_step_skip_unet.py::test_a_skipped_step_never_returns_another_latent_shape[True]`
| failed (width 8 for a width 12 latent) | passed |

The surrounding INT8 attention, CUTLASS, GEMM, step skip and FLUX.1 GELU
suites have the same results on both arms. 8 FLUX.1 GELU tests fail on
both base and head when they run in the same process after the step skip
and INT8 suites, and they pass when that file runs alone. That failure
predates this change.

## Not covered here

- No GPU run. The four changes are host-side keys and gates, and each
one is checked on CPU against the real module code.
- The `+1.7 us` host cost per INT8 attention call was measured on CPU,
not as end-to-end render time.
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