Repository navigation
Studio INT8 attention: compile the kernel once per machine and cut the per-call CPU cost, same output bits - #17791
Conversation
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.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
|
@codex review |
There was a problem hiding this comment.
💡 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".
| and not torch.compiler.is_compiling() | ||
| and not _tracing() | ||
| ): | ||
| return int8_attention_impl(q, k, v) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…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.
…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.
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)sm_XYwithnvrtcGetCUBIN, 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.<studio>/cache/int8-attention).UNSLOTH_DIFFUSION_INT8_ATTENTION_CACHEoverrides the directory, and0turns the disk cache off.os.replace. A rename refused while another process holds the file open (Windows) is ignored, since that copy is the same image.nvrtcGetCUBINalso keeps the PTX.cuModuleLoadDatasays 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) orCUDA_ERROR_UNSUPPORTED_PTX_VERSION(222)..ptx-onlymarker. 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.UNSLOTH_DIFFUSION_INT8_ATTENTION_CACHEpoints 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 onefstatwhen it is first read, so calls after the first never touch the disk.st_uiddo 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)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 undertorch.compile(opaque, no graph break), dispatch modes, functorch transforms and tensor subclasses.int8_attention_implreads the device facts once per call. Before, it looked up the serving implementation and config four times.quantise+attendnow run as one pass: one plan lookup, one stream lookup, no operand views.unsupported_reason,implementation,device_config,quantise,attendand the explicitint8_attentionpath behave as before.Results
Colab T4, L4, A100 and G4, plus Kaggle T4x2. Studio was installed by
install.shwith 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.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.
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
tests/test_diffusion_int8_attention_cache.py):int8_attention_calltakes the op undertorch.compile(fullgraph=True)and under a dispatch mode.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.Not covered
GetModuleFileNameW), beyond the unit tests;