Skip to content

Studio INT8 attention: compile the kernel once per machine and cut the per-call CPU cost, same output bits - #17791

Merged
danielhanchen merged 8 commits into
mainfrom
studio-int8-attention-compile-cache
Nov 15, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-int8-attention-compile-cache

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

Summary

The Studio INT8 attention kernel and its two quantisers were compiled with NVRTC in every process and again on every card. Main loaded the result as PTX, so the driver also compiled PTX to machine code on each load. A first call cost 1.0 to 2.3 s per card, and the second card of a multi-GPU load paid the same again. This PR makes that a one-time cost per machine and trims the per-call CPU work in front of the three launches. Output bits do not change.

1. Compiled-image cache (diffusion_int8_attention_cuda.py)

  • Image. NVRTC builds machine code for sm_XY with nvrtcGetCUBIN, the same whole-program compile a PTX load runs. The register cap (sm89 / sm120 hd128) is passed only to NVRTC's PTX compiler (--ptxas-options=--maxrregcount=N). The PTX stays byte for byte the PTX main capped with .maxnreg; a unit test checks this against the real NVRTC.
  • Once per process. Each image is made once per process per (architecture, defines, register cap) and shared by every card of that architecture. The module load stays per card.
  • On disk. Images live under Studio's cache root (<studio>/cache/int8-attention). UNSLOTH_DIFFUSION_INT8_ATTENTION_CACHE overrides the directory, and 0 turns the disk cache off.
    • Key: a hash of the kernel source, arch, defines, register cap, NVRTC version and library file, the driver's CUDA version, and a format number.
    • Each file carries a sha256 checksum. A torn or corrupt file, or one in another format, is removed and rebuilt.
    • Writes go to a temp file in the same directory, then os.replace. A rename refused while another process holds the file open (Windows) is ignored, since that copy is the same image.
    • There is one directory per code version. The 3 most recently used are kept, with at most 64 images each. Pruning only touches names this module creates.
  • When NVRTC is older than the driver. There the cache keeps NVRTC's PTX instead and the driver compiles it at load, as on main, through its own ComputeCache. The reason: with NVRTC 12.8 on a CUDA 13.1 driver, NVRTC's machine code kept the output bits but allocated registers differently from the driver's compile of the same PTX.
  • Fallbacks. An NVRTC without nvrtcGetCUBIN also keeps the PTX.
  • Load failures. A cubin falls back to the PTX only when cuModuleLoadData says the image itself cannot run here: CUDA_ERROR_INVALID_IMAGE (200), CUDA_ERROR_NO_BINARY_FOR_GPU (209), CUDA_ERROR_INVALID_PTX (218), CUDA_ERROR_JIT_COMPILER_NOT_FOUND (221) or CUDA_ERROR_UNSUPPORTED_PTX_VERSION (222).
    • The cubin is then dropped, and the PTX is stored under its own key with a .ptx-only marker. Later processes load that PTX directly and never compile or try the cubin again. If the PTX gets pruned, the marker still sends them straight to a PTX compile.
    • Any other result (out of memory, not initialized, a bad context) is raised as before and leaves the disk cache alone.
  • Cache trust (POSIX). Directories are created with mode 0o700 and files with 0o600. Images are read only when the cache root, its version directory and the file itself belong to the current user and are not group- or world-writable. Otherwise, for example when UNSLOTH_DIFFUSION_INT8_ATTENTION_CACHE points at a shared directory, the kernels are compiled in memory and one warning is logged. Each directory is checked once per process; a file is checked with one fstat when it is first read, so calls after the first never touch the disk.
    • On Windows nothing changes: mode bits and st_uid do not reflect the ACLs that control writes there, and the default root sits under the user's own profile.

2. Per-call CPU path (diffusion_int8_attention.py, the strided processors, the dispatch route)

  • Eager calls skip the custom op. Processors and the dispatch route call int8_attention_call. In eager it runs the op's body directly, which saves the custom-op dispatcher (about a fifth of a short call). The op is still used under torch.compile (opaque, no graph break), dispatch modes, functorch transforms and tensor subclasses.
  • Fewer repeated checks and lookups. int8_attention_impl reads the device facts once per call. Before, it looked up the serving implementation and config four times. quantise + attend now run as one pass: one plan lookup, one stream lookup, no operand views.
  • Behaviour kept. unsupported_reason, implementation, device_config, quantise, attend and the explicit int8_attention path behave as before.

Results

Colab T4, L4, A100 and G4, plus Kaggle T4x2. Studio was installed by install.sh with torch 2.13.0+cu130 and NVRTC 13.0, on driver 580.x (CUDA 13.0). Each arm ran in a fresh process. Per-call numbers use ABBA order with 3 runs per arm; the bracket is the spread across runs.

First call in a fresh process, ms (attention + quantisers at hd 128). "Driver cache" is the driver's ComputeCache; "off" means CUDA_CACHE_DISABLE=1. "Cold" is the first process on empty caches, "warm" the second process on the same caches.

card main, cold main, warm (driver cache on) main, warm (driver cache off) head, cold head, warm (driver cache on) head, warm (driver cache off)
T4 1976 75 2344 1313 4.3 4.5
L4 1935 53 1928 1306 3.8 3.7
A100 2046 54 2034 1363 4.2 4.0
G4 (sm120) 950 26 949 658 1.7 1.8
  • Driver cache. The ComputeCache already makes main's second process fast (26 to 75 ms). The image cache takes that to 2 to 5 ms, and still holds with the ComputeCache disabled, where main pays the full compile in every process.
  • Cold path. Cold is faster too, because the driver no longer compiles PTX after NVRTC.
  • Two cards. On Kaggle T4x2 with the driver cache off, the second card's first call in the same process cost 2041 ms on main (a full compile again) and 2.6 ms on head (module load only). NVRTC ran 4 compiles per process (attention + quantisers at hd 128 and hd 64), shared by both cards. Outputs were bit-equal across the cards.

Per-call wall time, us. Eager is 400 back-to-back calls then one sync. Graph is one call captured and replayed. Cells are main -> head.

card 1039x24 eager 1039x24 graph 1024x56 eager 2048x56 eager 126x32 eager 126x32 graph
T4 720 -> 722 716 -> 720 1431 -> 1434 4195 -> 4195 150 -> 112 (-25%) 26 -> 25
L4 247 -> 246 246 -> 245 691 -> 688 1939 -> 1941 157 -> 117 (-26%) 16 -> 16
A100 162 -> 138 (-15%) 127 -> 127 249 -> 249 682 -> 682 155 -> 117 (-25%) 19 -> 19
G4 61 -> 61 58 -> 58 105 -> 104 347 -> 347 41 -> 29 (-29%) 14 -> 14
  • Where the CPU cut shows. It shows where a call is CPU bound (126x32 everywhere, and 1039x24 on A100). Elsewhere eager is within a few us of the graph replay, so the GPU is the limit.
  • Graph time. Graph replay time is unchanged on every card. The attention kernel reports the same registers and local bytes as main on all five cards.
  • CPU cost breakdown. On one host, the eager call fell from 86 to 90 us to 47 to 52 us of CPU per call.

Bit equality. Main and head outputs are byte-identical on every card, for every shape, eager and graph, and for every first-call output.

Load-failure and cache-trust change. Rechecked on a Colab L4 (driver 580.82.07) against the commit before it, 2 runs per arm in fresh processes. Cold first call at hd 128: 1280 to 1306 ms before, 1291 to 1308 ms after. Warm: 3.7 to 4.0 ms before, 3.6 to 4.6 ms after (hd 64: 2.2 to 2.5 ms before, 1.8 to 2.0 ms after). Outputs, registers and per-call times were unchanged, and the INT8 suites passed on both trees.

Tests

  • New CPU tests (tests/test_diffusion_int8_attention_cache.py):
    • cache hit and miss, plus the memory hit;
    • the key changes with source, arch, defines, register cap, NVRTC version, NVRTC library and driver version;
    • corrupt-entry recovery (torn, flipped checksum, flipped image, empty, foreign file);
    • an unwritable cache and a refused rename;
    • paths with spaces and non-ASCII names;
    • pruning of old version directories and extra images;
    • the Studio cache-dir setting and the off switch;
    • two processes writing and reading one cache;
    • two cards of one architecture compiling once (mocked);
    • the load fallback to PTX for each unusable-image result, with the PTX and marker reused by the next process;
    • transient load results (out of memory, not initialized, bad context) raised with the cubin kept;
    • group- or world-writable and foreign-owned cache directories and files refused, with compilation still working;
    • the modes of created directories and files;
    • the NVRTC vs driver version rule;
    • with real NVRTC, that the capped machine code comes from the same PTX.
  • Other new tests: int8_attention_call takes the op under torch.compile(fullgraph=True) and under a dispatch mode.
  • CPU runs: the INT8 suites (test_diffusion_int8_attention*.py, test_diffusion_backend.py) pass. The one failure, test_mirrored_base_still_trips_the_flux2_shape_guard, fails the same way on main.
  • GPU runs: the INT8 pytest suites ran on T4, L4, A100, G4 and T4x2 for both trees, with no failures on either.

Not covered

  • Not tested:
    • Windows itself (rename, GetModuleFileNameW), beyond the unit tests;
    • H100;
    • NVRTC 12.x on GPUs other than one local check;
    • drivers other than 580.x and 590.x.
  • Unrelated failure seen while benchmarking: freeing a captured CUDA graph and then capturing another op call segfaulted on main as well. This was not investigated.

The kernel and its quantisers were compiled with NVRTC in every process and
on every card, and loaded as PTX, so the driver compiled them to machine
code again on each load (0.4 to 1.9 s per kernel per card).

Now NVRTC makes the machine code (nvrtcGetCUBIN for sm_XY, the same
whole-program compile a PTX load runs; the register cap goes to its PTX
compiler alone through --ptxas-options, so the PTX is unchanged), and the
image is kept:

- once per process per architecture, shared by every card of it (the
  module load stays per card);
- on disk under Studio's cache root (int8-attention, or
  UNSLOTH_DIFFUSION_INT8_ATTENTION_CACHE; 0 turns it off), keyed by the
  source, defines, register cap, architecture and NVRTC, with a checksum,
  written through a temporary file and a rename;
- one directory per code version, the three most recently used kept, at
  most 64 images each.

Where NVRTC cannot make machine code, the capped PTX is kept instead (its
compute_XY PTX is byte for byte the sm_XY PTX); machine code that will not
load falls back to the PTX, as before, and is dropped.
A short call is mostly CPU work before its three launches. Measured on one
host, the guarded op spent about 88 us per call, of which the custom-op
dispatcher was about 18 us and the guards about 23 us (the serving
implementation and its config were looked up four times per call).

- Processors and the dispatch route call int8_attention_call: the custom
  op while torch.compile traces (still opaque, no graph break) and under
  dispatch modes, functorch transforms or tensor subclasses; its body
  directly otherwise.
- int8_attention_impl reads the device facts once per call (_call_route)
  and runs quantise + attend as one pass (_cuda_attention: one plan
  lookup, one stream lookup, no operand views).
- unsupported_reason, implementation, device_config, quantise and attend
  keep their behaviour; the explicit int8_attention path is unchanged.

Outputs are bit-identical: the same plans, kernels and arguments.
NVRTC's machine code is the code a PTX load runs only where NVRTC is at
least as new as the driver. With NVRTC 12.8 on a CUDA 13.1 driver the
machine code kept the output bits but used other registers than the
driver's own compile of the same PTX, so there the cache keeps NVRTC's
PTX and the driver compiles it at load, as before (its own cache then
makes that a one-time cost). The driver's CUDA version joins the key.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 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-15T04:12:05.648185Z 5cf6328 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.

…ivate cache dirs

A cubin load falls back to the PTX only for results that mean the image itself
cannot run on this driver or GPU (200, 209, 218, 221, 222). The PTX is then kept
on disk with a marker so later processes skip the cubin. Transient results such
as out of memory are raised and leave the cache alone.

On POSIX the cache directories are made 0o700 and images are only read from
directories and files owned by this user and not writable by others; anything
else compiles in memory, with one warning. Checked once per process per
directory.

The kernel sources are hashed once per process, so the extra marker lookup
keeps a warm first call as cheap as before.
[skip ci]
@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: f52cea9b55

ℹ️ 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 +858 to +861
and not torch.compiler.is_compiling()
and not _tracing()
):
return int8_attention_impl(q, k, v)

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 Preserve the custom op during TorchScript tracing

When torch.jit.trace traces a processor on a verified CUDA device, its inputs are ordinary torch.Tensor objects, torch.compiler.is_compiling() is false, and neither check in _tracing() detects the TorchScript tracer. This therefore executes _cuda_attention directly: tensor allocations are recorded, but the ctypes CUDA launches that populate the output are not. Replaying the traced model consequently returns uninitialized attention output instead of executing attention. Keep the custom-op route when torch.jit.is_tracing() is true, as the previous unconditional custom-op call did.

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 5cf6328: the eager shortcut now also checks torch.jit.is_tracing(), so a TorchScript trace records the custom op. Added test_torchscript_tracing_records_the_op, which fails on the previous head.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 5cf6328bac

ℹ️ 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 added a commit that referenced this pull request Nov 15, 2026
…e them as stock math under compile (#17795)

## Summary

Follow-up to #17618. The MiniMax-H3 row-mod kernels
(`video_minimax_h3_rowmod.py`) launched on whatever CUDA device the
calling thread had current, not on the operands' card.

## Root cause

Triton launches on the current device and its current stream.
`_launch_modulate` and `_launch_gated` called the kernels with no device
scope; only the one-time probe inside `verdict()` ran under
`torch.cuda.device(x.device)`. When a render thread's current device is
not the tensors' card (multi-GPU host, a pooled or unpinned thread), the
launch goes to the wrong device and stream. On two B200s with `cuda:0`
current and the tensors on `cuda:1`, main fails the launch with:

```
ValueError: Pointer argument cannot be accessed from Triton (cpu tensor?)
```

Where the pointer check passes, the kernel would instead run on the
wrong stream, unordered against the producer stream. The sibling kernel
`video_minimax_h3_qknorm.py` already guards its launch.

## Fix

- New `_on_card(t)` helper: returns `torch.cuda.device(index)` when the
operand sits on a card other than the current one, and a null context
otherwise. Single-card renders skip the switch, which saves about 3 us
per launch (the same rule `diffusion_vae_fused._on_card` uses).
- `_launch_modulate` launches under `_on_card(x)`, `_launch_gated` under
`_on_card(residual)`.

## Audit of other Triton launch sites under
`studio/backend/core/inference/`

I enumerated every `kernel[grid](...)` call with an AST walk and checked
the device scope at each one.

Already guarded, no change needed:
- `diffusion_convrot_quant.py`, `diffusion_flux2_rope.py`,
`diffusion_flux3_qk_rope.py`, `diffusion_grouped_int8_gemm.py`,
`diffusion_grouped_int8_triton.py`, `diffusion_int8_fused.py`,
`diffusion_int8_gemm.py`, `diffusion_int8_gemv.py`,
`diffusion_moss_fused.py`, `diffusion_native_w8a8_rdna.py`,
`diffusion_nvfp4_bias.py`, `diffusion_packed_block.py`,
`diffusion_qwenimage21_eager.py`, `diffusion_rocm_fused.py`,
`diffusion_vae_fused.py`, `diffusion_vae_strips.py`,
`video_minimax_h3_qknorm.py`: guarded at the launch.
- `diffusion_fp8_dequant.py` (`launch_triton`): its only caller wraps it
in `torch.cuda.device(codes.device)`.
- `diffusion_nvfp4_act_quant.py`: the `triton_op` is only invoked under
`torch.cuda.device(...)`.
- `video_wan_fused.py`: every launch runs inside `_fused_forward`, which
holds `torch.cuda.device(hidden_states.device)`.
- `video_minimax_h3_vae.py`: launches run inside the encoder / decoder
forwards, which hold `torch.cuda.device(hidden_states.device)`, and
`_int8_linear` switches devices on its own.

Missing the guard, not changed here because other open PRs touch these
files:
- `diffusion_int8_attention_triton.py` (`quantise`, `attend`,
`half_attention`): #17789, #17791, #17790.
- `diffusion_multigpu.py`, `diffusion_cast_cache.py`, and the
`diffusion_int8_gemm.py` / `diffusion_convrot_quant.py` probes: #17790.

## Compile safety (second commit)

Two more issues in the same helpers, both reproduced on CPU with torch
2.14.1:

- `modulate` / `gated_residual` bump the global `STATS` counters inside
the traced region. Dynamo guards on the Python int (`G['STATS']['stock']
== ...`), so compiling either helper recompiled on every call: 5 frames
for 5 identical calls (`CompileCounter`).
- On a cold verdict cache an eligible call reaches `verdict()`, whose
`_LOCK` and timing probe fail `fullgraph=True` with `Unsupported context
manager` (Dynamo cannot enter a `lock`).

Studio's own `UNSLOTH_H3_IMAGE_COMPILE=1` path never installs the
rewrite, so this only bites when an already-patched transformer or the
helpers are compiled directly. Fix: under
`torch.compiler.is_compiling()` both helpers return the stock expression
directly, without touching `STATS` or the verdict cache. After the fix:
1 frame for 5 calls, and cold `fullgraph=True` compiles with the verdict
cache still empty. Eager dispatch is unchanged.

## Tests

Added to `studio/backend/tests/test_h3_row_mod.py`:
- `test_launches_switch_to_the_operand_card` (CPU): patches
`torch.cuda.device` / `current_device` and the kernels to record the
current device at each launch, with operands on a mocked `cuda:1` while
device 0 is current. Both launches must fire on device 1, and device 0
must be current again afterwards.
- `test_launches_on_the_current_card_skip_the_switch` (CPU): same-card
operands never enter `torch.cuda.device`.
- `test_compiling_the_row_ops_does_not_recompile_per_call` (CPU): one
compiled frame across 5 calls of each helper, output equal to the
reference.
- `test_cold_tracing_of_an_eligible_call_compiles_fullgraph` (CPU): CUDA
eligibility simulated, empty verdict cache, `fullgraph=True` compiles
both helpers and the probe never runs.
- `test_kernels_on_a_second_card_while_card_0_is_current` (bf16, fp16;
skips with fewer than 2 GPUs): real tensors on `cuda:1` with
`torch.cuda.set_device(0)`. The fused output must be bit-equal to
`reference_modulate` / `reference_gated_residual`, and `cuda:0` must
still be current after the call.

Each arm imports its own tree (the test file was copied into a checkout
of the merge base).

| Run | main (merge base) | this branch |
| --- | --- | --- |
| CPU, `test_h3_row_mod.py` | 3 failed (device test, `assert 5 == 1`
recompiles, `Unsupported context manager`), 6 passed, 5 skipped | 9
passed, 5 skipped |
| 2x B200, `test_h3_row_mod.py` (first commit) | 3 failed (CPU device
test, plus both two-card tests with `Pointer argument cannot be accessed
from Triton`), 9 passed | 12 passed |
| 1x B200, `test_h3_row_mod.py` (both commits) | not rerun | 12 passed,
2 skipped (two-card tests) |

The existing single-card CUDA tests (bit-exactness of the kernels and
the whole row forward) pass on the branch.
@danielhanchen
danielhanchen merged commit d4a2089 into main Nov 15, 2026
@danielhanchen
danielhanchen deleted the studio-int8-attention-compile-cache branch November 15, 2026 08:46
danielhanchen added a commit that referenced this pull request Nov 15, 2026
…ll back to the short one (#17796)

## Summary

Follow-up to #17769. Some INT8 attention kernel configs carry a
`long_keys` / `long` override (sm80 hd128 and sm89 hd64 switch to
`wpc=8` from 4608 keys; ROCm gfx1151 hd128 from 8000). `select_config`
turns that into a second compiled kernel, but the install-time check
never reached it: the accuracy probe uses about 1000 tokens and the race
uses `RACE_TOKENS = (4096, 1024)`. Two problems followed:

1. The long kernel was compiled on the first real call with at least
4608 keys (FLUX at 1024x1024 is exactly 4608). That call could be under
CUDA graph capture, and that kernel never passed the cosine check that
sets `_VERIFIED`.
2. If that compile or launch failed, the `except` in
`int8_attention_impl` added `(index, head_dim)` to `_BROKEN`. That also
turned off the verified short kernel for the rest of the process.

## Changes

`studio/backend/core/inference/diffusion_int8_attention.py`:

- `_long_check`: when the card's config has `long_keys`, the install
check (`_check`, so also `verdict`) compiles and checks the long variant
once per (card, head dim, dtype, impl). It runs eagerly, outside any
capture, on the cheapest probe that selects it: batch 1, 2 heads, 1000
queries against `long_keys + 100` keys (the last key tile is ragged).
The probe uses the same plain and sharp accuracy bars as the short
check. A pass goes into `_LONG_VERIFIED`. The result shows up as `long`
in the verdict and in `status()["verdicts"]`, and the install log line
gets `long_ok=...`.
- `_run`: when no explicit config is passed, a call long enough for the
long variant runs it only if that variant was verified (and has not
failed since). Otherwise the call runs the short config. The short
config is a valid kernel at any length, just slower on long calls, and
the output is the same either way: the block shape does not change any
output bit (`test_long_overrides_do_not_change_the_output`). An explicit
`config=` is still run exactly as given.
- `int8_attention_impl`: a runtime failure in a call that ran the long
variant now adds `(index, head_dim, impl)` to `_LONG_BROKEN`. That call
runs native attention, and later long calls go back to the short kernel.
A failure in a short-kernel call still marks `(index, head_dim)` broken,
as before.
- If the long variant fails its check or fails to load, the card keeps
INT8 with the short kernel for every call. `ok` is unchanged.
- Configs without `long_keys` behave exactly as before: no extra probe,
no extra compile, same call path.

## Tests

New `studio/backend/tests/test_diffusion_int8_attention_long_probe.py`
(CPU, a faked sm89 card with the compile / launch mocked):

| test | main | this PR |
|---|---|---|
| the card check compiles and verifies the long variant | FAIL | pass |
| a long variant that fails its check leaves long calls on the short
kernel | FAIL (the long call raises, so the card goes native: `kernel
failed, native attention from here on`) | pass |
| a long variant that misses the accuracy bar is not used | FAIL | pass
|
| a long call that fails at runtime disables only the long variant |
FAIL | pass |
| a short kernel failure still turns the card off | pass | pass |
| a config without long_keys is checked and run as before | pass | pass
|
| an explicit config is run as given | pass | pass |

The existing INT8 suites (`test_diffusion_int8_attention.py`,
`_dispatch`, `_triton_fallback`, `_rocm`) pass on CPU on both trees: 126
passed, 93 skipped on this branch; main fails only the 4 new tests.

## GPU evidence (Colab L4 sm89 and A100 sm80, torch 2.14.1+cu130, main
at f490069 vs this branch)

INT8 GPU suites (`test_diffusion_int8_attention.py`, `_dispatch`,
`_triton_fallback`, and the new file) on each card: 197 passed, 6
skipped on this branch. Main fails only the 4 new tests (193 passed).
The 6 skips need two CUDA cards.

The long variant is verified at install, as recorded in the verdict:

- L4 hd64: `{'ok': True, 'keys': 4708, 'cos': 0.99996, 'rel_l1': 0.0077,
'sharp_cos': 0.9971}`, `_LONG_VERIFIED = [(0, 64, bf16, cuda)]`
- A100 hd128: `{'ok': True, 'keys': 4708, 'cos': 0.99996, 'rel_l1':
0.0081, 'sharp_cos': 0.9970}`, `_LONG_VERIFIED = [(0, 128, bf16, cuda)]`
- L4 hd128 and A100 hd64 have no `long_keys`: no long verdict, no extra
kernel.

Output and per-call time through the registered op, bf16, 24 heads, 8
fresh processes in ABBA order (main head head main head main main head).
The A/A noise is the spread across the 4 main runs:

| card | tokens | head dim | wpc run | sha main = head | main ms | head
ms | delta | A/A |
|---|---|---|---|---|---|---|---|---|
| L4 | 4608 | 64 | 8 / 8 | yes | 1.6566 | 1.6462 | -0.63% | 4.38% |
| L4 | 4608 | 128 | 12 / 12 | yes | 2.9600 | 2.9398 | -0.68% | 2.52% |
| L4 | 16384 | 64 | 8 / 8 | yes | 17.7035 | 17.5745 | -0.73% | 2.41% |
| L4 | 16384 | 128 | 12 / 12 | yes | 31.7831 | 31.6264 | -0.49% | 3.42%
|
| A100 | 4608 | 64 | 4 / 4 | yes | 0.6966 | 0.6975 | +0.13% | 0.07% |
| A100 | 4608 | 128 | 8 / 8 | yes | 1.4826 | 1.4840 | +0.10% | 7.33% |
| A100 | 16384 | 64 | 4 / 4 | yes | 7.6951 | 7.6963 | +0.02% | 0.02% |
| A100 | 16384 | 128 | 8 / 8 | yes | 12.6990 | 12.6990 | 0.00% | 0.02% |

Both trees run the same kernel (same `wpc`) at every shape, the outputs
are bit-identical, and every call engaged INT8. One row is above its A/A
spread: A100 4608 / hd64, about 1 us per call. That config has no
`long_keys`, so the GPU work is the same kernel. On the host the only
addition there is one dict lookup in `_run`.

## Install-time cost

Median of 3 fresh processes per arm. "Fresh driver cache" is a new
`CUDA_CACHE_PATH`; "warm driver cache" is a second process on the same
path. "In-process" means the verdict caches were dropped but the
compiled kernels kept, so it measures the probes only.

| card, head dim with long_keys | fresh driver cache | warm driver cache
| in-process |
|---|---|---|---|
| L4 hd64, main / head | 2249 / 3548 ms (+1.3 s) | 62 / 110 ms (+48 ms)
| 8.6 / 25.1 ms (+17 ms) |
| A100 hd128, main / head | 2224 / 3332 ms (+1.1 s) | 264 / 322 ms (+58
ms) | 14.5 / 48.3 ms (+34 ms) |

This is a cost moved, not added, wherever a long call follows. On main,
the first 4608-key call pays the long compile. For L4 hd64 that first
call is 1258 to 1276 ms on main vs 1.7 ms on head with a fresh driver
cache, and 30.8 ms vs 1.7 ms with a warm one. On A100 hd128 the first
4608-key call is 2112 to 6942 ms on main vs 1075 to 1100 ms on head.
Both arms include about 1 s of first-op-call setup there, which also
appears on cards without `long_keys`. Cards and head dims without
`long_keys` do not change (L4 hd128: 2162 vs 2159 ms; A100 hd64: 2225 vs
2239 ms). Only a process that never makes a call at or above `long_keys`
pays the extra compile and gets nothing for it.

With #17791's disk compile cache (now on main), measured on this head
with a fresh driver cache and a fresh kernel cache per arm: the long
compile moves from the first long call to install (L4 hd64: about 2330
ms vs 2360 ms total, first long call 840-853 ms down to 1.7 ms; A100
hd128: about 3325 ms vs 3375 ms, first long call 1785 ms down to about
1080 ms). What is added is the long accuracy probe itself, about 18 ms
on L4 and 33 ms on A100, once per card, head dim and dtype per process.

## Not covered

- H100, sm75 and sm120 were not run (their configs have no `long_keys`
on the CUDA path).
- The ROCm gfx1151 hd128 `long_keys = 8000` entry goes through the same
`_long_check` / `_run` code, but it was not run on AMD hardware here.
- A real compile failure of the long kernel on hardware was not
reproduced. That path is covered by the CPU tests only.
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