Skip to content

[Perf] Add an eager fast path for FP8 per-token linear ops - #8038

Open
ZLkanyo009 wants to merge 44 commits into
lingzha/tgemm-eager-fast-pathfrom
lingzha/a8w8-eager-fast-path
Open

ZLkanyo009 wants to merge 44 commits into
lingzha/tgemm-eager-fast-pathfrom
lingzha/a8w8-eager-fast-path

Conversation

@ZLkanyo009

@ZLkanyo009 ZLkanyo009 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #8030; review against lingzha/tgemm-eager-fast-path.

FP8 per-token linear layers pay Python dispatch and tensor-conversion costs for both quantization and GEMM. This PR adds guarded direct calls to the already-loaded pybind kernels for plain eager execution. A shared kernel-selection function keeps the registered GEMM route and eager route aligned.

Current head cd40ba1ec75ad86321939a53147a7403a157fa61 normally merges the actual #8030 target dd13d73fd8cca12796b394e6c662f0e3245e79c3. The four-file FP8 delta remains separate from inherited BF16 changes. The single conflict in aiter/ops/gemm_op_a8w8.py preserves both this PR's eager route and the target's new split-K deferred APIs. Independent source review, 14 CPU metadata cases, Black and Ruff passed. GPU evidence below remains bound to 76e7469b; clean native builds, production-path performance and current-head model validation remain unverified.

Changes

  • aiter/ops/gemm_op_a8w8.py: _bpreshuffle_kernel selects the tuned CK, CKTile or FlyDSL row, architecture fallback, or default kernel for both routes. The eager route accepts eligible FP8 CK calls, preserves splitK and output allocation, and invokes the loaded pybind entry. Unsupported cases continue through the registered op, including INT8, bias, unsupported output dtype, K-padded weights, non-2D inputs, and non-CK selections.
  • aiter/ops/quant.py: without a static scale, eligible per_token_quant_hip calls allocate the same quantized output and fp32 scale, set the current HIP stream, and invoke dynamic_per_token_scaled_quant with the existing argument contract.
  • aiter/jit/utils/eager_guard.py: the two FP8 consumers share mode, subclass and autograd checks. Compile/tracing, dispatch/function modes, functorch transforms, relevant overrides, rebound operations, logging/rebuild modes and unresolved first calls retain their registered paths. GEMM also declines while a kernel plugin can serve its routed op. BF16 tuned GEMM does not use this helper.
  • op_tests/test_a8w8_eager.py: exercises numerical equality and route selection, including provider behavior, unsupported inputs, rebound lookups/ops, compile, graph replay and logging. The registered op names and schemas remain available for compiled graphs.

The first call stays on the existing JIT route to load or build the module. The eager path only looks up a pybind entry after that initialization; it does not add a build path.

Current merge validation

At cd40ba1e, the five PR selector/eager function groups (including both definitions of gemm_a8w8_bpreshuffle) preserve their prior ASTs. The target's _bpreshuffle_config and six split-K deferred helpers preserve their target ASTs. The quantization, guard and test changes relative to the target preserve the prior PR's added/removed lines. No additional call is inserted in the eager hot path.

Fourteen CPU scenarios execute the actual extracted selector, registered-path body, eager helper and deferred selector with metadata doubles. They cover missing/CK/CKTile/FlyDSL/unknown rows, padded logical/physical K lookup, valid/rejected INT8 rows, gfx1250 fallback and split-K 2/4/8/1. Configs and lookup order agree, and the eager/deferred paths do not select each other's cases. These are control-flow checks, not Torch/native/GPU execution. Black 26.10.1, Ruff 0.17.6 and staged diff-whitespace checks pass.

The earlier merge 76e7469b incorporated target 6bf2b5cb and retained the then-reviewed FP8 executable behavior. Its fixed-image GPU evidence is retained below with its original revision. It does not establish GPU or model acceptance for this new merge.

GPU correctness at 76e7469b was verified on 2026-11-27 using MI308X/gfx942, Torch 2.10/ROCm 7.2.4 and the fixed e8 image's existing native modules. The unchanged op_tests/test_a8w8_eager.py assertions passed all 24 GEMM cases bit-for-bit plus numerical references, 12 quant cases bit-for-bit plus references, and 41 route checks. Those include first calls, provider/fallback behavior, modes, rebound operations, changed-input CUDA graph replay and logging. The Dynamo check uses a gm.forward backend, not Inductor code generation.

A correctness-only driver ran first-call checks before the numerical matrix and suppressed only the optional timing helpers. All 9,085 source files and the four actually loaded native modules were bound and unchanged before/after; exported evidence and resource release were independently checked. This is not a clean native build, production-path performance or current-head model-accuracy result. The op-test substitutes lookup results, so its timing tables do not establish full production-path performance.

Historical performance and correctness

These results describe earlier revisions only. Setup: MI308X (gfx942, 80 CU), ROCm 7.2.4, Torch 2.10 and prebuilt image modules.

Host time at e68dca887 versus main b9e08daca: four model FP8 shapes at M=2112, tuned CK rows, median of three alternating runs on the same GPU and pinned CPU core; each run uses five rounds of 16-call bursts. Cold calls follow an 8 MiB sweep and unrelated Python work.

microseconds per call quant, main quant, e68dca8 GEMM, main GEMM, e68dca8
warm 30.3 20.1 22.6 14.1
cold 63.4 39.1 45.6 29.1

For 96 GEMMs and 48 quants per prefill, those measurements correspond to 3.6 to 2.3 ms of warm host time and 7.4 to 4.7 ms cold. Quant/GEMM output hashes matched in all recorded runs. These values have not been remeasured on the current base.

Earlier model results compared this PR's first commit 1e08fa73f with #8030 at 74df116e7: TP2/EP2, MTP with three draft tokens, two MI308X, input_ids, max_tokens=1, a prefilled prefix and fresh tails. Every measured wave verified the stated prefix hit. Values are medians of eight measured rounds per run, with alternating server builds; most cells use two runs per build, and the SGLang 10240/concurrency-4 cell uses four.

stack input / prefix hit concurrency 74df116 TTFT (ms) 1e08fa7 TTFT (ms)
SGLang plugin 0.5.22 8192 / 6080 1 213.4 211.0
SGLang plugin 0.5.22 8192 / 6080 4 603.4 603.9
SGLang plugin 0.5.22 10240 / 7104 1 241.8 241.8
SGLang plugin 0.5.22 10240 / 7104 4 933.9 919.0
Native ATOM 8192 / 6080 1 360.9 349.9
Native ATOM 8192 / 6080 4 878.6 863.8
Native ATOM 10240 / 7104 1 548.0 507.5
Native ATOM 10240 / 7104 4 1167.2 1081.8

SGLang differences were within run-to-run spread. Native ATOM was faster in those recorded cells, but the machine was shared and the larger deltas included variance; the two Native 10240/concurrency-1 baseline runs differed by 44 ms. GSM8K 5-shot with 200 questions, temperature 0 and max_gen_toks=4096 was 0.985 flexible/strict for both builds and stacks. MTP acceptance was 0.720/0.719 for SGLang and 0.718/0.726 for Native, baseline/candidate respectively. None of these model results validates the current head.

Historical tests:

  • At dfa2694350 on gfx942, op_tests/test_a8w8_eager.py passed 41 path checks. The former BF16 eager test also passed. pytest -q tests reported 489 passed, 2 skipped, 1 test_layout failure, also present on main 42aab0f75.
  • At 75a407a4ac, the four plugin rows passed; removing the GEMM plugin guard made the test fail because the provider did not run.
  • At e68dca887, three runs of the FP8 eager test passed 24 GEMM cases bit-for-bit, 12 quant cases and 37 path checks. Six guard/argument/stream mutations failed as intended. The recorded kernel-choice grid matched the original route in 168 cases.
  • At e68dca887 versus main b9e08daca, the existing bpreshuffle-out test reported 47 passed/7 skipped; the pad-K test reported 37 passed/14 skipped under pytest and 23 passed/4 skipped as a script. test_quant.py and test_gemm_a8w8.py -q fp8 exited 0. All used prebuilt modules.

The eager profiler currently omits the bypassed aiter:: dispatch events. Graph capture uses the same current-stream launches; the first historical commit message's claim that capture falls back was incorrect. gfx950/gfx1250 native behavior, a clean JIT build and the full op-test matrix remain unverified locally. A synthetic FlyDSL-fallback selection case does not replace hardware validation.

PR Self-Review

Reviewed revision

cd40ba1

Behavior and intent

Reduce host dispatch and descriptor-conversion cost for eligible FP8 per-token quantization and CK GEMM by calling already-loaded native entries. Share GEMM selection with the registered route and retain fallback behavior for unsupported execution modes and inputs. The updated stacked base preserves ordinary BF16 registered dispatch.

Validation and unverified scope

The current cd40ba1e merge has independent AST/diff review, 14 CPU metadata-double scenarios, Black, Ruff and diff-whitespace validation as detailed above. The earlier 76e7469b passed 24 GEMM, 12 quant and 41 route checks on gfx942 using fixed e8 prebuilt modules; those historical results retain that revision. Clean native builds, full production lookup performance, fresh-process compile/fake-first coverage and current-head model accuracy/performance remain open. No new native/GPU/model run is claimed for this merge.

PR-specific question

The FP8 delta adds no dependency or cache/compilation policy. The helper reads Torch execution state; eligible direct calls require the existing JIT path to have initialized the native module, and AITER_REBUILD disables them. Historical existing-cache runs used prebuilt modules and first-call tests exercised the unresolved state. A clean build has not been run. The new base's BF16 metadata/descriptor caches are inherited byte-for-byte and are reviewed in #8030; they are outside this four-file FP8 delta.

Changed op tests

op_tests/test_a8w8_eager.py checks bitwise equality with the registered ops and numerical references, then distinguishes direct execution from fallback for plugin providers, CKTile rows, unsupported dtypes/shapes, bias, grad/static-scale cases, modes/subclasses, rebound operations, compile, graph replay and logging. Existing test_gemm_a8w8.py and test_quant.py check numerical tolerance but do not establish route choice or exact equivalence with the registered op. The FP8 test is byte-identical during this merge. Its original assertions were executed at 76e7469b through the correctness-only driver described above; optional timing was disabled. Earlier passing revisions remain listed above.

ZLkanyo009 and others added 9 commits November 16, 2026 11:05
Outside torch.compile, an unscaled tgemm.mm / gemm_a16w16 /
gemm_a16w16_out whose tuned config is hipBLASLt now calls the hipBLASLt
pybind entry directly. It skips both torch.ops dispatches
(aiter::gemm_a16w16, then aiter::_hipb_mm), the routing in
_gemm_a16w16, the gradlib wrapper and the develop-mode argument
conversion, which together cost more host time than the C++ call.

The config comes from the same lookup _gemm_a16w16 makes, through the
module attribute on every call, so a replacement installed over
get_GEMM_A16W16_config (ATOM's SGLang plugin installs one) is honoured
and its answers are never cached. The solution index and the arguments
are the ones the custom-op path passes, so results are bitwise
identical.

The custom ops still run every call the fast path declines: under
torch.compile or jit tracing, inside dispatch / torch-function modes or
functorch transforms, for tensor subclasses that take over dispatch,
grad-tracked inputs, inputs _gemm_a16w16 does not simply reshape, shape
recording (AITER_TUNE_GEMM) or AITER_LOG_MORE>=2, until the op path has
created the hipBLASLt extension, and for every config that is not
hipBLASLt. AITER_TUNE_GEMM is now read once.

Co-authored-by: Cursor <[email protected]>
Converting B.t() to an aiter_tensor_t is the most expensive argument
conversion of the fast path (the transposed view plus the pybind
constructor). The handle depends only on the tensor's data pointer,
shape, stride, dtype and device and holds no reference to the tensor,
so it is cached under exactly that key: a hit is what a fresh
conversion would build, even for memory that a new tensor reuses.

The cache is a bounded LRU (1024 entries), so callers that pass
activations as B only rotate entries out; weights stay resident.

Co-authored-by: Cursor <[email protected]>
…ration

hipblasLtMatmul_sol_wrapper created three matrix layouts and a matmul
descriptor, looked the algorithm up by solution index and destroyed it
all again on every call, and read HIP_ONLINE_TUNING with getenv each
time. For an unscaled GEMM with a given solution index that work is the
same on every call, so it is now done once per configuration (op_A,
op_B, m, n, k, lda, ldb, ldc, in/out type, solution index, bpreshuffle,
bias, gelu) and reused; only the bias pointer is set per call.

Scaled calls, the heuristic path (solution index < 0) and online tuning
still build descriptors per call. The kept set is bounded (dropped and
rebuilt past 1024 configurations) and released with the extension.
HIP_ONLINE_TUNING is read once.

The descriptor construction moved verbatim into create_matmul_descs(),
so a reused descriptor is the one a fresh call would build and results
are bitwise identical.

Co-authored-by: Cursor <[email protected]>
The plans kept by hipblasLtMatmul_sol_wrapper lived in one global map with
no lock, and a hit sets the bias pointer on the kept descriptor before
hipblasLtMatmul. The pybind binding of hipb_mm holds the GIL, so Python
callers already take turns; a caller that does not hold it (free-threaded
Python, a future binding that releases the GIL) could race on the map or
hand one descriptor two bias pointers.

The map is now thread_local: each thread builds, reuses and, when it
exits, releases its own plans, so no descriptor is ever shared. A
generation counter bumped by hipb_destroy_extension makes every other
thread drop plans built for an older extension before its next lookup;
the calling thread drops its own immediately, as before.

Tests: threads interleaving several configurations (one of them with a
bias per thread) match a single thread bit for bit; a worker thread that
outlives a destroy/create rebuilds its plans; short-lived threads release
theirs.

Co-authored-by: Cursor <[email protected]>
ATOM's PTPC linear layer calls per_token_quant_hip and then
gemm_a8w8_bpreshuffle for every FP8 projection. Both go through
torch_compile_guard custom ops, so each eager call pays for the custom
op dispatch plus the compile_ops wrapper before reaching the kernel.

In plain eager mode, call the pybind kernels directly:

- gemm_a8w8_bpreshuffle looks up the tuned config like before and calls
  the CK kernel with the same splitK. Rows tuned for another libtype,
  bias, non-bf16/fp16 output, padded K and gfx1250 untuned shapes keep
  the op path.
- per_token_quant_hip allocates the same outputs, sets the HIP stream
  and calls dynamic_per_token_scaled_quant. A static scale keeps the
  op path.

Graph capture, torch.compile, fake/functional tensors, dispatch and
function modes, autograd, tensor subclasses, rebound inner ops,
AITER_LOG_MORE>=2 and AITER_REBUILD all fall back to the op. The public
names stay plain functions that end in the original ops, so compiled
graphs still contain aiter.per_token_quant_hip and
aiter.gemm_a8w8_bpreshuffle.

Move the eager checks shared with tuned_gemm into
aiter/jit/utils/eager_guard.py.
test_many_configurations failed on MI35X (gfx950): the first solution
hipb_findallsols returned for the 64x64x64 problem gave different bits
for two freshly built descriptors. Every view there has its own leading
dimension, so both sides of that comparison were fresh builds and no
descriptor was reused; the difference came from the kernel, not from
the reuse.

_solution now returns the first of up to 8 solutions whose results
match across two freshly built extensions, for every input the test
compares, and skips if none does. With that premise checked, the
build-vs-reuse check in test_kept_descriptors_match_fresh_ones asserts
instead of skipping.
@ZLkanyo009

Copy link
Copy Markdown
Contributor Author

Merged the latest #8030 into this branch (f9ddb25, no rebase). It brings be8b061, a test-only fix for the MI35X failure of op_tests/test_hipb_mm_reuse.py::test_many_configurations on #8030 (details there): the bitwise tests now pick a hipBLASLt solution that is deterministic across two fresh builds. The diff of this PR against its base is unchanged (the six files of 1e08fa7).

This PR's base is #8030's branch, not main, so aiter CI reports no checks here; its tests (op_tests/test_a8w8_eager.py and the FP8 / quant tests listed in the description) were run on gfx942 only. Once #8030 merges and this PR is retargeted to main, the MI35X run will cover them on gfx950.

cc @valarLip

ZLkanyo009 and others added 2 commits November 17, 2026 03:20
…t32 reference

be8b061 did not fix test_many_configurations on MI35X (gfx950). The
solution it kept there, 441462, is hipBLASLt's hand-written
Custom_Cijk_Alik_Bljk_BBS_BH_MT256x256x64_MI16x16x1_UserArgs_shortname1_gfx950,
tuned for 4096x4096x8192-class problems. For the test's 64x64x64 it runs
one workgroup with GSU 1 and no workspace, so its arithmetic order is
fixed: it is not a K-splitting kernel. With K equal to its depth (64) it
skips the second iteration's 16 prefetch loads but still waits with
vmcnt(24) and vmcnt(16), thresholds sized for 32 loads in flight, and
never waits for vmcnt(0) before the MFMAs, so it can read LDS before its
direct-to-LDS loads land. Its results then depend on load latency and
stale LDS, with fresh descriptors as much as with kept ones. Two agreeing
runs right after a synchronize said nothing about 1100 back-to-back calls.

- test_many_configurations uses K = 512, which takes the kernel's regular
  prefetch path (the cases in this file with K >= 512 passed on MI35X with
  the same kernel). It also calls the checked views again past the drop,
  so descriptors kept across it and rebuilt after it are both compared.
- Every comparison of kept results goes through _check_reuse. The same
  call on two freshly built extensions decides how to compare: if they
  agree bit for bit, kept results must too, and before failing it takes
  four more fresh samples, since two agreeing ones do not make a kernel
  reproducible. If fresh results vary, kept results are held to a float32
  torch reference instead. Fresh results are always held to that
  reference (atol = rtol = 1e-2). Failures name the solution, its kernel
  and the differing elements.
- _solution still prefers a solution that is reproducible across two
  fresh builds, but falls back to the first one instead of skipping.

Mutation checks on MI308X: leaving the bias pointer unchanged on reuse
fails both bias cases, and leaving ldb out of the plan key fails
test_configurations_do_not_mix and test_many_configurations, both in the
bitwise path and with the tolerance path forced.

Co-authored-by: Cursor <[email protected]>
@ZLkanyo009

Copy link
Copy Markdown
Contributor Author

Merged the latest #8030 into this branch (c8004f4, no rebase). It brings aadb785, a test-only follow-up for #8030's MI35X failure in op_tests/test_hipb_mm_reuse.py (details). This PR's own diff against lingzha/tgemm-eager-fast-path is unchanged. After the merge, on MI308X: test_hipb_mm_reuse.py 11 passed, test_tuned_gemm_eager.py 59 passed.

cc @valarLip

ZLkanyo009 and others added 7 commits November 17, 2026 08:20
…um) lookup

- The fast path read torch._C._len_torch_dispatch_stack,
  _are_functorch_transforms_active and _is_tracing through getattr with a
  None default, and turned itself off for the run when one was missing.
  torch 2.1 and 2.4 have all three (the first is bound in
  torch/csrc/autograd/init.cpp, the third in torch/csrc/jit/python/init.cpp,
  and torch/autograd/function.py calls the second), so that branch could
  not run. They are now called directly.
- `_gemm_a16w16` and the fast path each derived the (gfx, cu_num) the
  tuned-config lookup is keyed on. Both now call `_gemm_gfx_cu`, moved
  out of `_gemm_a16w16` unchanged; the fast path still keeps the result
  per device index (about 0.7 us of host time per call here).
- The str(dtype) cache is gone: 45 ns uncached vs 28 ns cached per call
  on this host, two calls per GEMM.

No change in behaviour. On MI308X (gfx942), op_tests/test_gemm_a16w16.py
-t normal, -t compile and -t out and the tuned-config lookup test give
the same results as at aadb785 (the same two asm accuracy prints in
-t normal, the known asm case in -t out, the same 8 lookup errors).

Co-authored-by: Cursor <[email protected]>
Both files are now plain aiter op tests: module-level helpers and test
functions, a main() with the argument parser and the sweep, a markdown
table per test function, and an arch gate on get_gfx_runtime() in main().
CI runs them as before, as `python3 <file>`.

test_tuned_gemm_eager.py:
- Each shape is routed to hipBLASLt (heuristic solution) by a function
  installed over get_GEMM_A16W16_config, the attribute both paths call
  through. The test no longer depends on the rows of the tuned CSVs, so
  on MI35X it runs the cases that skipped there before.
- Which path ran is read from the profiler: a custom-op call is a
  dispatcher event (aiter::gemm_a16w16 / _out) and the fast path records
  none. The test no longer replaces the module's custom-op attributes.
- The sweep (shapes x dtype x bias x out kind, plus otype and 3-D input)
  compares the fast path with the custom op bit for bit wherever the op
  reproduces itself, and both with a float32 reference. The table carries
  each path's device time, host time per call, TFLOPS, TB/s and error.
- Path checks: the first call of a process, scales, grad, Parameter,
  dispatch / function modes, torch.set_default_device (a function mode,
  so the fast path declines under it), FakeTensor, a non-hipBLASLt
  config, a 3-D input view cannot flatten, a replaced lookup, weight
  handles, torch.compile, CUDA graph replay, a preshuffled weight on
  gfx942, and AITER_TUNE_GEMM=1 in a child process.

test_hipb_mm_reuse.py: the same cases, _solution, _check_reuse and
K = 512 as aadb785, so the MI35X fix stays; the kept call is also
timed.

On MI308X (gfx942): both files pass (34 s and 32 s). Each of these
mutations makes the new tests fail: no grad check, the weight-handle key
without the shape, bias dropped, no torch-function check, no libtype
check (crash), no shape-recording check, and l24's two hipbsolgemm.cu
mutants (stale bias pointer, ldb left out of the plan key). gfx950 is
left to the MI35X CI run.

Co-authored-by: Cursor <[email protected]>
…fast-path

Co-authored-by: Cursor <[email protected]>

# Conflicts:
#	aiter/tuned_gemm.py
#	op_tests/test_tuned_gemm_eager.py
`plain_eager` read torch._C._len_torch_dispatch_stack,
_are_functorch_transforms_active and _is_tracing through getattr with a
None default, and `probes_available` turned the FP8 GEMM and quant fast
paths off when one was missing. torch 2.1 and 2.4 have all three, so that
branch could not run (the same change as #8030's 674d326). The checks
are now called directly, and `probes_available` is gone from the two
callers. `plain_tensor_type` is private: only `plain_eager` uses it.

No change in behaviour. On MI308X (gfx942): op_tests/test_a8w8_eager.py,
test_quant.py, test_gemm_a8w8_bpreshuffle_out.py and
test_gemm_a8w8_bpreshuffle_pad_k.py (84 passed, 21 skipped) pass.

Co-authored-by: Cursor <[email protected]>
Same structure as #8030's test_tuned_gemm_eager.py: plain aiter op test
functions, main() with the parser and the sweeps, a markdown table per
test function, an arch gate on get_gfx_runtime().

- The GEMM shapes are routed by a function installed over
  get_GEMM_config_with_quant_type, the attribute both paths call through:
  each shape runs once as a CK row and once with no row, so the test no
  longer reads the tuned CSVs and runs the same cases on every card. A
  CKTile row and a K-padded weight check that the fast path declines.
- Which path ran is read from the profiler, as in #8030's test.
- GEMM results are compared with the custom op bit for bit and with a
  float32 dequantized product; quant results with the custom op bit for
  bit, their scales with aiter.pertoken_quant, and every dequantized
  value to within one quantization step of the input. The tables carry
  device time, host time per call, TFLOPS / TB/s and error.
- AITER_LOG_MORE=2 is set in a child process instead of patching the
  module.

On MI308X (gfx942) the file passes in 21 s. Host time per call, custom op
vs fast path: GEMM 23.4-24.2 vs 14.7-15.0 us, quant 31.6-32.6 vs
21.1-21.4 us (the 2112-row shapes). Each of these mutations makes it
fail: no grad check in plain_eager, a non-CK row taken as CK, no K
check, a static quant scale ignored, the quant stream not set.

Co-authored-by: Cursor <[email protected]>
…ast-path

Co-authored-by: Cursor <[email protected]>

# Conflicts:
#	aiter/tuned_gemm.py
…fast-path

Co-authored-by: Cursor <[email protected]>

# Conflicts:
#	aiter/tuned_gemm.py
@ZLkanyo009

ZLkanyo009 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

@valarLip Pushed c8004f4..4541de3: two commits from a self-review against the maintainer guidelines, and three merges of #8030 (5a22814, ad156c2, 4541de3) that bring its cleanup, its tests without pytest and main. The diff against lingzha/tgemm-eager-fast-path is still this PR's five files. No review comments are open here.

Self-review against the maintainer guidelines

Finding Commit Change
op_tests/test_a8w8_eager.py was a pytest file. e19e9e5 A plain aiter op test, built like #8030's test_tuned_gemm_eager.py: @benchmark test functions, main() with the parser and the sweeps, a markdown table per test function, an arch gate on get_gfx_runtime().
GEMM cases read the tuned CSVs: the CK rows of the running card, and its CKTile / FlyDSL / asm rows for the declines. e19e9e5 Shapes are routed by a lookup installed over get_GEMM_config_with_quant_type, the attribute both paths call through. Each model shape runs once as a CK row and once with no row, and a CKTile row checks the decline.
The test compared the fast paths only with the custom ops. e19e9e5 GEMM results are also held to a float32 dequantized product. Quant scales are held to aiter.pertoken_quant, and every dequantized value to within one quantization step of the input.
The test patched AITER_LOG_MORE and reset module state to check argument logging and the first call. e19e9e5 AITER_LOG_MORE=2 runs in a child process; the first call is checked first in main(). Which path ran is read from the profiler.
plain_eager read three torch mode checks through getattr(..., None), and probes_available turned both fast paths off when one was missing. c835ee6 torch 2.1 and 2.4 have all three; they are called directly, as in #8030 (674d326). plain_tensor_type is private, since only plain_eager uses it now.

Kept, and why: _a8w8_bpreshuffle_eager repeats the CK branch of _gemm_a8w8_bpreshuffle_into: the lookup, the ck call with the row's splitK, and the untuned default CK kernel outside gfx1250 with its error message. It declines every other branch. To share that function, the fast path would either keep the inner aiter::gemm_a8w8_bpreshuffle_ck dispatch it removes, or the function would need a callable parameter. The test holds the fast path to the custom op's bits for CK rows and for shapes with no row on the card it runs on, so a routing change for those shapes fails it there.

Verification (MI308X, gfx942, at ad156c2 with the image's prebuilt CK and quant modules; #8030's test_tuned_gemm_eager.py again at 4541de3):

  • black 26.10.1 and ruff 0.16.0: clean.
  • python3 op_tests/test_a8w8_eager.py: passes in 20 s (24 GEMM cases, 12 quant cases, 36 path checks). Host time per call, custom op vs fast path, for the 2112-row shapes: GEMM 23.4–24.2 vs 14.7–15.0 µs, quant 31.6–32.6 vs 21.1–21.4 µs.
  • Each of these makes it fail: no grad check in plain_eager, a non-CK row taken as CK, no K check, a static quant scale ignored, the quant stream not set.
  • [JIT] [Perf] Reduce Python overhead in tuned GEMM dispatch #8030's test_tuned_gemm_eager.py and test_hipb_mm_reuse.py, test_quant.py, and test_gemm_a8w8_bpreshuffle_out.py with test_gemm_a8w8_bpreshuffle_pad_k.py (84 passed, 21 skipped): pass.
  • No numeric path changed, so GSM8K was not rerun.

This PR's base is #8030's branch, so aiter CI reports no checks here. These tests have run on gfx942 only; MI35X will cover them once #8030 merges and this PR targets main. The title now carries [Perf].

@ZLkanyo009 ZLkanyo009 changed the title Add an eager fast path for FP8 per-token linear ops [Perf] Add an eager fast path for FP8 per-token linear ops Nov 17, 2026
ZLkanyo009 and others added 7 commits November 17, 2026 08:53
The path checks compared the custom op's torch-path results and the
compiled graph's results with torch.equal. Those run hipBLASLt (through
torch or the heuristic solution) on the CI card, which may pick a kernel
that is not reproducible run to run. They now go through _check_bits like
the rest of the file: the bits must match where the op reproduces itself,
and every result is held to the float32 reference.

MI308X (gfx942): the file passes (32 s), every one of these checks on the
bit-for-bit path.

Co-authored-by: Cursor <[email protected]>
The C++ change in gradlib/csrc/hipbsolgemm.cu (keep the hipBLASLt layouts,
descriptor and algorithm per configuration and per thread) and its test,
op_tests/test_hipb_mm_reuse.py, do not depend on the Python fast path of
this PR, and the fast path does not depend on them. They are now #8116, so
each can be reviewed and reverted on its own; this PR keeps the eager fast
path in aiter/tuned_gemm.py and op_tests/test_tuned_gemm_eager.py.

hipbsolgemm.cu is back to main's version and the test file is removed.
Nothing in aiter/tuned_gemm.py or test_tuned_gemm_eager.py existed only for
the plan reuse, so neither changes.
Main's #6828, merged in with #8030, adds signed-INT8 operands to
gemm_a8w8_bpreshuffle and makes its FP8 path assert that XQ has WQ's dtype.
The fast path checked only WQ's dtype, so an XQ of another dtype with an FP8
WQ ran the CK kernel where the custom op now raises. The fast path now
declines unless XQ and WQ are both FP8. INT8 calls run FlyDSL kernels, which
it never stands in for, and reach the custom op as before.

#6828 also documents the INT8 contract on the custom op's body, which this
PR keeps as the private _gemm_a8w8_bpreshuffle_op, while the public
gemm_a8w8_bpreshuffle had a one-line, FP8-only docstring. The docstring
moves unchanged to the public function.

op_tests/test_a8w8_eager.py: a BF16 XQ with an FP8 WQ reaches the custom op
and its "dtypes must match" assertion. With the new check removed, the call
takes the fast path and the test fails.
… row

check_gemm_declines ran the K-padded call with a CK row routed in, but called
the custom op it compares against outside the routing, where the real table
has no row for the shape and the op takes the default CKTile kernel for a
K-padded WQ. CK and CKTile give the same bits for that input most of the time
(19 of 20 random draws on MI308X), so the check failed now and then. Both
calls now run under the same row, and the two checks in this block compare
through _check_bits, like the rest of the file.
…function

Which kernel a bpreshuffle GEMM runs was decided twice: in
_gemm_a8w8_bpreshuffle_into for the custom op, and again in the eager fast
path, which repeated the FP8 table lookup and the gfx1250 exception for
untuned shapes. #6828 just changed that routing on main (INT8), and every
such change had to be made in both places.

_bpreshuffle_kernel(m, n, k, w_k, q_dtype) now makes the decision and
returns it as data: the tuned row (a CK, CKTile or FlyDSL row runs that
libtype with its splitK) and, without one, the FlyDSL kernel the shape falls
back to (INT8's default 4-wave kernel, the closest fitting one on gfx1250);
with neither, the default CK kernel runs. _gemm_a8w8_bpreshuffle_into
launches what it returns, pads a K-padded XQ, logs the fallback warnings and
wraps default-kernel errors as before. The fast path calls the CK entry
directly for a CK row, or with splitK 0 when there is neither a row nor a
fallback, and declines otherwise; it has no gfx1250 check of its own.

The kernel choice, the warnings and the error text are unchanged: with the
launchers, the table lookup and the arch replaced by recorders, the op path
makes the same calls before and after this commit in all 168 cases of a grid
of rows (CK with and without split-K, CKTile, FlyDSL, an unparsable FlyDSL
name, asm, none) x FP8 / INT8 x K-padded or not x gfx942 / gfx1250 x a
failing CK launch.

Host time of one gemm_a8w8_bpreshuffle call on MI308X, weighted over the
four tuned CK shapes of Qwen3.8-Flash-Next PTPC FP8 at TP2, three
alternating runs each, before -> after this commit: fast path 13.89 -> 14.13
us warm, 29.16 -> 29.11 us cold; custom op through the dispatcher 21.84 ->
22.23 us warm, 44.57 -> 43.96 us cold. The public call on main is 22.59 /
45.56 us.
@ZLkanyo009

Copy link
Copy Markdown
Contributor Author

Pushed 4541de3..e68dca8: a merge of #8030's new head and three commits. #8030 now merges main b9e08da and has moved its C++ plan reuse to #8116, so gradlib/csrc/hipbsolgemm.cu and op_tests/test_hipb_mm_reuse.py leave this branch's base too.

Commit What Verified by
3eb31ca merge #8030 (8985895); no conflicts the diff against the base is the same 5 files
bbc5d21 Follow main's #6828 (INT8 bpreshuffle). Its FP8 path now asserts that XQ has WQ's dtype, and the fast path checked only WQ, so an XQ of another dtype ran the CK kernel where the op now raises. The fast path now declines unless both are FP8 (INT8 runs FlyDSL kernels and goes to the op as before). The INT8 contract #6828 documents on the op's body moves, unchanged, to the public gemm_a8w8_bpreshuffle, whose docstring said FP8 only. new check: a BF16 XQ with an FP8 WQ reaches the op's "dtypes must match"; with the decline removed the test fails
804643b Test fix. The K-padded check ran the call under a routed CK row, but called the op it compares against outside the routing, where the real table has no row and the op takes the default CKTile kernel. CK and CKTile agree bit for bit on that input only most of the time (19 of 20 random draws), so the check could fail now and then. Both calls now run under the same row, through _check_bits. 3 clean runs
e68dca8 One kernel choice. _bpreshuffle_kernel(m, n, k, w_k, q_dtype) returns the tuned row and, without one, the FlyDSL fallback (INT8's default 4-wave kernel, gfx1250's closest fit); the op's _gemm_a8w8_bpreshuffle_into launches what it returns, and the fast path calls CK for a CK row or the default and declines otherwise. It no longer has its own table lookup or gfx1250 check. below

The routing duplicate. My last update (#issuecomment-6943260373) kept the CK routing duplicated in the fast path. #6828 changing that routing on main is exactly the drift a second copy invites, so e68dca8 replaces the copy with one function both paths call.

  • The kernel choice, the warnings and the error text are unchanged. I replaced the launchers, the table lookup and the arch with recorders and drove _gemm_a8w8_bpreshuffle_into before and after e68dca8 through 168 cases: rows CK (split-K 0 and 3), CKTile, FlyDSL, an unparsable FlyDSL name, asm and none, × FP8 / INT8 × K-padded or not × gfx942 / gfx1250 × a failing CK launch. Every case records the same launcher calls, warnings and errors (including the wrapped default-kernel error).
  • Host time per gemm_a8w8_bpreshuffle call (MI308X, the four tuned CK shapes of the model, weighted; three alternating runs per build):
µs per call main b9e08da fast path before e68dca8 at e68dca8
warm 22.6 13.9 14.1
cold 45.6 29.2 29.1

The custom op through the dispatcher goes 21.8 → 22.2 µs warm and 44.6 → 44.0 µs cold across the change. Quant is unchanged (30.3 → 20.1 µs warm, 63.4 → 39.1 µs cold against main). The output SHA-256 of every shape is the same for all three builds.

Verification at e68dca8 (MI308X, gfx942):

  • python3 op_tests/test_a8w8_eager.py: passes in three runs (24 GEMM cases all bit for bit, 12 quant cases, 37 path checks, 21 s).
  • Mutations: no grad check in plain_eager, a non-CK row taken as CK, no K check, no XQ dtype check, a static scale ignored, and the quant stream not set each make it fail. Taking a FlyDSL fallback as CK does not, because no FP8 shape has a fallback on gfx942 / gfx950; on gfx1250 it is covered only by the recorded routing above.
  • Same results as main: python3 -m pytest op_tests/test_gemm_a8w8_bpreshuffle_out.py (47 passed, 7 skipped), op_tests/test_gemm_a8w8_bpreshuffle_pad_k.py (37 passed, 14 skipped; 23 passed, 4 skipped as python3), op_tests/test_quant.py and op_tests/test_gemm_a8w8.py -q fp8 (exit 0). [JIT] [Perf] Reduce Python overhead in tuned GEMM dispatch #8030's test_tuned_gemm_eager.py passes.
  • black and ruff 0.16.0: clean.
  • The description now carries these numbers, each with the revision it was measured on. TTFT and GSM8K are still the ones from 1e08fa7 and were not rerun.

Still waiting for: #8030 to land, and then aiter CI on this PR (it reports no checks while its base is not main).

cc @valarLip

ZLkanyo009 and others added 4 commits November 18, 2026 03:00
test_fallback routes a decode-sized BF16 GEMM (4x64x1024) to the torch,
skinny and Triton backends, checks that the public gemm_a16w16 reaches the
custom op once and gives its bits, and times it against the custom op
wrapper that was the public gemm_a16w16 before the fast path. The
difference is what the declined fast path costs a call: its checks and
its own config lookup.

_host_us takes the median of five rounds, so one slow round does not set
a row.
Brings in f5b8e74, the timing of the BF16 eager fallback to the other
backends.
Conflict in aiter/tuned_gemm.py with ee71544 (#8075), which routes
`_gemm_a16w16` through the kernel plugin interface (op "gemm_a16w16").
Both sides added an import at the same place and code right above
`_gemm_a16w16`: this branch the eager fast path, main the @_route
decorator. Kept both, with the decorator on `_gemm_a16w16`.

The fast path calls hipBLASLt without reaching `_gemm_a16w16`, so it
would skip the route. It now declines while any provider is enabled and
the kill switch is off, and the call goes through the custom op to the
route, which asks the providers and records its decision. It runs only
in the state where the route's dispatch calls the native body and records
nothing: AITER_PLUGINS=0 or nothing enabled by configure(). That is read
from the same config snapshot the dispatch reads, once per call.

op_tests/test_tuned_gemm_eager.py gains check_plugin_route: with a
provider enabled for gemm_a16w16, `tgemm.mm` with and without out= runs
the provider; when it declines, the custom op runs with its bits; with
nothing enabled again the fast path takes the call. Without the new check
in `_hipblaslt_eager` the first of these fails.
Brings in 84f7f18, the merge of main with ee71544 (#8075), which
routes `_gemm_a16w16` and `gemm_a8w8_bpreshuffle` through the kernel
plugin interface.

Conflict in aiter/ops/gemm_op_a8w8.py: main gave the routed inner
`gemm_a8w8_bpreshuffle` its contract docstring, this branch had rewritten
the docstring there. Kept main's; the public wrapper's docstring points
to it.

The a8w8 GEMM fast path calls the CK kernel without reaching the routed
op, so like the BF16 one it now declines while a provider may serve a
routed op. Both read that from `unrouted()` in eager_guard. The quant
ops are not routed, so their fast path is unchanged.

op_tests/test_a8w8_eager.py gains check_plugin_route: with a provider
enabled for gemm_a8w8_bpreshuffle, `gemm_a8w8_bpreshuffle` runs the
provider; when it declines, the custom op runs with its bits; the quant
fast path still takes its call; with nothing enabled again the GEMM fast
path takes the call. Without the new check the first of these fails.
@ZLkanyo009

Copy link
Copy Markdown
Contributor Author

Merged #8030's 84f7f18 (main with #8075) as 75a407a: the a8w8 GEMM fast path now declines while a kernel plugin is enabled, so a provider for the routed gemm_a8w8_bpreshuffle always gets the call, and op_tests/test_a8w8_eager.py checks that; the quant fast path is unchanged because quant is not routed.

Conflict in aiter/tuned_gemm.py with a3d7388 (#7514): main added
`_opus_reads_layout` right above `_gemm_a16w16`, where this branch has
`_gemm_gfx_cu`. Kept both.

#7514 changes what the tuned lookup returns on gfx1250 (96-CU OPUS rows,
the strict id's kid check) and, in `_gemm_a16w16`, sends an OPUS row whose
operands OPUS cannot read to Triton or torch. The fast path asks the same
lookup with the same (gfx, cu_num) key and runs only hipBLASLt rows, so it
declines every OPUS row and the custom op makes those choices.

op_tests/test_tuned_gemm_eager.py gains check_gfx1250_opus: with the device
key stubbed to a 96-CU gfx1250 and the OPUS and Triton backends stubbed,
the real lookup gives #7514's OPUS rows for two Kimi-K2 shapes; each call
reaches the custom op, the fast path and the op ask the lookup with the
same key, and the op runs OPUS with that row, or Triton when B is not
K-contiguous. Keying the fast path's lookup by the runtime arch or by the
256-CU table, or dropping the layout fallback, makes it fail.
Brings in 1243b4b, the merge of main with a3d7388 (#7514), and its
check that the BF16 fast path declines gfx1250 OPUS rows to the custom op.
No conflict; main did not change the a8w8 or quant paths.
@ZLkanyo009

Copy link
Copy Markdown
Contributor Author

Merged #8030's 1243b4b (main with #7514, gfx1250 a16w16 OPUS tuning) as dfa2694 without a conflict; main did not touch the a8w8 or quant paths, and op_tests/test_a8w8_eager.py and pytest -q tests give the same results as before.

Keep main's CPU Torch fallback and FP32 CPU accumulation from #8251,
using the existing shared architecture helper inside the guarded lookup.
Retain #8099's rejection of borrowed OPUS rows on gfx1250-strict.

The eager launch body is unchanged. CPU source-body checks cover 48
numerical/out-buffer cases against main and a Torch reference, the
CPU eager decline, invalid output dtype, and architecture error
propagation. Provider interface/contracts: 145 passed with GPUs hidden.
Black, Ruff and diff-check pass. No new GPU or performance run.
Merge #8030 at be6286d, which incorporates main 2eb9ef3
and retains the CPU Torch fallback through the shared arch helper.

The five-file patch against the stacked base has the same stable patch
ID as before this merge. CPU GEMM resolution and Torch fallback bodies
are identical to the validated #8030 parent. Black, Ruff, AST parsing
and diff-check pass. No GPU or performance rerun; this remains stacked
on lingzha/tgemm-eager-fast-path.
@ZLkanyo009

Copy link
Copy Markdown
Contributor Author

@valarLip Updated the stacked base after #8030's conflict resolution.

Merged #8030 at be6286d7d8498c5d01709bd3f8ad8a63a4a409b5 in 8218d84b29fcd7f95a2df66259b7d06a8169519f, without conflicts. The base branch remains lingzha/tgemm-eager-fast-path. This brings main 2eb9ef365777, including its CPU Torch fallback and strict-architecture OPUS lookup fix.

The five-file diff against the stacked base has the same stable patch ID before and after this merge. The CPU GEMM resolution and Torch backend bodies are identical to the validated #8030 parent. AST parsing, Black, Ruff and diff-check pass. No new GPU or performance run was made; the earlier measurements keep their original revision labels. This PR still has no CI checks while stacked on #8030.

Preserve the ordinary BF16 dispatch and cache changes from #8030.
Keep the independent FP8 eager guard and clarify its module scope.

The four-file FP8 delta passed independent source review and
syntax/Black/Ruff/whitespace checks. No new GPU or performance
result is claimed for this merged head.
Mock the actual TDM launcher for persisted gfx1250 policies and check
its transposed operand view and launch arguments. Preserve strict-target
rejection and all legacy assertions across the full 182 subcases.
Align the three affected legacy MoE golden snapshots with the explicit intermediate_pad=0 keyword introduced by #7611. Exact baseline and PR-head CPU snapshots are byte-identical across all four simulated architectures; all 2130 changed records only add this keyword. Preserve frozen tuning inputs, normalization, assertions and gfx1201.
@ZLkanyo009

Copy link
Copy Markdown
Contributor Author

Current-head GPU correctness is now verified for 76e7469b728c261dd53810ffe254a8aa6977e0c7 on MI308X/gfx942 using the fixed e8 image's existing native modules:

  • 24/24 GEMM cases matched the registered op bit-for-bit and passed the numerical reference checks.
  • 12/12 quant cases matched bit-for-bit and passed the reference checks.
  • 41/41 route checks passed, including unresolved first calls, plugin providers, CKTile fallback, execution modes, rebound lookup/ops, changed-input graph replay and argument logging. The Dynamo check uses a gm.forward backend; it does not validate Inductor code generation.

The complete current source tree and four actually loaded native modules were bound and checked before/after the run. The unchanged op-test assertions ran through a correctness-only driver with the optional timing helpers disabled. This closes the current-head correctness gap for that environment; it is not a clean native build or a production-path performance measurement. Model TTFT/accuracy and other hardware remain unverified at this head. No product change or CI retry was needed.

@ZLkanyo009

Copy link
Copy Markdown
Contributor Author

aiter PR #8038 — Add an eager fast path for FP8 per-token linear ops

Calls loaded quantization and CK GEMM entries directly for eligible eager execution, preserving registered fallbacks and sharing GEMM kernel selection.

Review (advisory): ⚠️ NEEDS WORK (not independently refuted)
Validation (deterministic): NOT RUN — REVIEW_AUTO_VALIDATE=0; no exact-head validation_report.json. Existing advisory gfx942 evidence at 76e7469b covers 24 GEMM, 12 quant and 41 route checks with prebuilt modules.
Perf (advisory): NOT RUN — no final-base/head production-lookup comparison; historical results retain their original revisions, and the added harness substitutes GEMM lookup.
Size: 1040 lines / 4 files — over the review bar
Design (advisory): SPLIT -- separate the shared eager guard and mode tests, GEMM selection/direct CK path, and quant direct path with production benchmarks into a small stack.
Human: recommend valarLip review whether #8038 should bypass registered dispatch after warmup and agree on the guard/GEMM/quant split with the two op owners.

⚠️ [inferred] Is default activation covered beyond the recorded gfx942 environment? aiter/ops/gemm_op_a8w8.py:1221 and aiter/ops/quant.py:1027 do not restrict ISA, while accepted current-head evidence uses one gfx942/prebuilt environment and Qwen-shaped operator cases. Shared downstream behavior, gfx950/gfx1250 and clean native builds remain unverified. Current GitHub checks are absent because the PR is stacked on #8030; the main-only downstream workflows cannot be enabled merely by adding a label here. Author must bind the planned affected-architecture and current downstream decode/prefill checks to the final integration head, or narrow activation to the validated scope, preserving the existing accepted results.

⚠️ [inferred] Can the claimed host saving survive the production lookup on the final base? op_tests/test_a8w8_eager.py:186 times both routes inside _routed, which replaces get_GEMM_config_with_quant_type; its registered-versus-eager table is also a within-head comparison. Historical real-lookup results do not measure 6bf2b5cb versus 76e7469b. Author must provide one common-driver before/after benchmark with the real lookup, guards and allocations inside timing, matching outputs and reported sample counts, or equivalent existing final-head evidence.

⚠️ [verified] The default-dispatch changes in aiter/ops/gemm_op_a8w8.py and aiter/ops/quant.py have no recorded owner review. Current reviews are empty; existing @valarLip mentions have no response. Path history and GitHub commit identities identify @solinzby1 for GEMM and @junhaha666 for quant. Their decision matters because numerical equality does not decide whether bypassing registered dispatch and its instrumentation is an acceptable public contract. Reviewer should ask these owners explicitly to review the current bypass contract and record their response before integration.

📝 [inferred] Does compilation work when it is the first call in the process? gemm_op_a8w8.py:1290 and quant.py:1054 resolve native entries after an unresolved registered fallback, including when the fast path declined compilation/fake execution. The test calls check_first_calls before check_compile, so its successful warmed gm.forward check does not answer this case. No failure has been reproduced. Author must add one isolated fresh-process fullgraph/fake-first regression before eager warmup, and change resolver placement only if that exposes a failure.

Pinned source: head 76e7469b728c261dd53810ffe254a8aa6977e0c7; merge target a8c714e3ab7ceef0e17223efc01e0f6a23c52133; AITER main review-pr skill at 163947e790402822e53e4f8defcd1b3a78d1707d. Review/gates completed 2026-12-02 UTC.

The original scanner and gate scripts ran unchanged under Python. The read-only GitHub/Git fetch steps used direct CLI equivalents because Bash is unavailable; fetch.sh itself did not run. REVIEW_AUTO_VALIDATE=0. All eighteen AITER static subcommands completed; their results were then assessed against the actual source and workflows. The semantic review separately examined changed production code, callers, tests and relevant CI. Prior measurements remain bound to their stated sources and do not count as new runtime validation by this scan.

This is a stacked PR targeting lingzha/tgemm-eager-fast-path: GitHub reports baseRefOid=6bf2b5cb076952f767948d9d77758dcf09da8846, while the fetched branch target examined for applicability is a8c714e3ab7ceef0e17223efc01e0f6a23c52133. The skill itself is pinned independently to AITER main 163947e790402822e53e4f8defcd1b3a78d1707d. No absent check is reported as a skipped or failed job.

Actual scanner commands and output (local paths replaced by variables)
$ $PY -I -S -B -X utf8 $SKILL\triage.py rules $WORK\pr.diff [Perf] Add an eager fast path for FP8 per-token linear ops
exit=0
  files=4  types=15  rules=30/68
    [new-routing-value   ] A4 B4 C4
    [dispatch-change     ] A4 B1 B3 B4 A3
    [tier2-dispatch      ] E5 E4 C5
    [api-signature       ] B6 E1 E5
    [fp8-quant           ] C1 C2 D1
    [perf                ] P1 P2 P3 P5 P6
    [async-stream        ] G1 G1b
    [downstream-op       ] E4 E5 A2
    [invariant-removed   ] D4 B7
    [layout-contiguity   ] D8 B7
    [syspath-mutation    ] HK3
    [incomplete-code     ] HK7
    [test-reference-dtype] HK10
    [conditional-binding ] D1b
    [defaulted-param     ] E2

$ $PY -I -S -B -X utf8 $SKILL\triage.py expand $WORK\rules.txt $SKILL\rules.md
exit=0
### A — Coverage Gaps

**A2 — Shared path, no cross-model validation** ⚠️
Changed code shared across model families (not model-specific): validated on all?
Real example (PR#3891): valarLip: "please make sure e2e CI passes before changes to common part."
→ `⚠️ A2: change touches shared path — e2e or cross-model validation needed`

**A3 — Activation condition broader than validated scope** ⚠️
New dispatch condition (e.g., `if is_deepseek():`) enables a kernel for more archs/models than tested.
Real example (vLLM#16435): FusedMoE activated for wrong model families → follow-up restrict PR needed.
→ `⚠️ A3: activation condition [X] enables more than validated scope [Y]`

**A4 — New feature branch in existing kernel without regression test** ⚠️/🔴
A PR adds a new dispatch branch (new activation type, new dtype, new quant path) to an existing kernel but does not test that existing operators' correctness and performance are preserved. Adding a branch often touches shared code: widening a template condition, narrowing a guard, refactoring a shared lambda, changing a scale computation. These side-effects can silently regress every pre-existing path.
Trigger: the diff adds a new `if/elif/else` branch or a new template specialization to an existing kernel, and the new branch shares code (constants, scale logic, store paths, bias conditions) with pre-existing branches.
What to check: (1) every shared constant or condition the PR changes — does the change preserve the old value for old inputs? (2) are existing paths tested in the PR's test plan, or only the new path? (3) for perf-sensitive kernels, is there a before/after benchmark on old paths?
Severity: 🔴 if a shared constant or condition provably changes behavior for existing inputs (wrong scale, skipped reciprocal, dropped bias). ⚠️ if the shared path change is theoretically safe but untested on old inputs.
FP self-check: a new branch that is fully gated by `if constexpr(NewFeature)` and touches no shared code is exempt — it cannot affect old paths. Only fire when the diff modifies code that old paths also execute.
Real examples: PR#5708 narrowed `enable_bias` from `_needs_swiglu_bias_support()` to `activation == Swiglu && _needs_swiglu_bias_support()` — could have regressed Situv2 bias on Opus/FlyDSL paths (analyzed as safe, but not tested). PR#5985 widened `kStoreTakesDivisor` to include `fp16_t` — broke the reciprocal scale on gfx942 fp16 MXFP8 quant (scale_err=55/56 groups), because the software convert path expected the reciprocal but received the raw divisor. PR#5914 added optional fp8 Q output to fused_qk_norm_rope kernel using a runtime pointer check (`if (q_out_fp8 != nullptr)`) instead of a template parameter — VGPR usage rose from 96 to 98 at head_size=512, crossing an allocation granule and dropping occupancy from 5 to 4 waves/SIMD for every existing caller passing nullptr; fixed by introducing a `HAS_Q_FP8` template parameter so the non-fp8 instantiation is byte-identical to the original.
→ `🔴/⚠️ A4: new [feature] branch added to [kernel] — shared [code/constant] changed, verify existing [paths] are not regressed`

---

### B — Silent Bypass

**B1 — Dispatch gate with unchecked parameter** 🔴
New `if/elif/else` branch: for each parameter gated off — is it **asserted** (None/zero) or **forwarded**?
If neither: wrong results, no crash, no error.
Trigger: `dropout_p`, `window_size`, `block_table`, `logits_soft_cap`, `alibi_slopes`, `is_causal`.
Real example (PR#3576): `block_table is not None` False-branch computed dense attention silently.
Real example (PR#3390): `is_causal=True` not forwarded → "fake causal" fmha passed all CI.
→ `🔴 B1: [param] silently ignored in [branch] — assert or forward`

**B3 — String dispatch without normalization** ⚠️
`quant_type == "per_token"` before normalizing: aliases `"fp8_per_token"`, `"per-token"`, `QuantType.per_Token` silently miss the branch.
Real example (PR#3981): raw string compare in `parallel_state.py` — alias callers missed torch-compile fast path.
→ `⚠️ B3: string dispatch [cond] without normalization — aliases fall through to slow path`

**B4 — New dispatch value not handled by all paths, no warning** ⚠️/🔴
When a PR introduces a new routing value to a multi-way dispatch — a new dtype string (`'fp4'`), a new arch string (`'gfx1201'`), a new layout flag (`SWIGLU_INTERLEAVED`), a new constexpr enum value — every reachable dispatch branch must either (a) handle it explicitly, (b) fall through to a documented safe default, or (c) assert/warn before the wrong branch is reached. If any reachable branch silently falls through to behavior that is wrong for the new value, flag it.
Severity: 🔴 if the wrong path produces incorrect output silently (wrong layout, wrong kernel, wrong scale). ⚠️ if the wrong path is a safe-but-suboptimal default (e.g., generic tile depths instead of tuned fp4 depths).
Exception: an upstream assert/raise/isinstance check that prevents the bad value from entering the branch → not B4. A runtime assert that fires for the dangerous combo → not B4.
FP self-check: Is the uncovered branch actually reachable with the new value? Is there a caller contract (documented or asserted) guaranteeing the bad combo never occurs?
Real examples: GGUU flag not wired into gfx950 Triton path — runtime assert guards the explicitly dangerous combo but the remaining gap is silent (aiter#4169); fp4 silently falls through to `in_dtype in ('fp8','int8')` tile table, uses generic preload depths (aiter#3941); cross-attention + mt=1 on gfx1250 falls through to get_heuristic_kernel with no gfx1250 kernel compiled for that combo (aiter#3939).
→ `🔴/⚠️ B4: [new value] reaches [branch] which assumes [old value] — [what wrong thing happens] — add assert or explicit handling`

**B6 — API propagation incompleteness** 🔴/⚠️
When an API surface changes in dimension X, all downstream receivers (Y) must be updated. Unhandled propagation silently falls through to wrong behavior (Z).

| Sub-type | X (what changed) | Y (downstream not updated) | Z (failure) | Sev |
|----------|-----------------|---------------------------|-------------|-----|
| param-discard | new param in signature | function body | value accepted but never used | ⚠️/🔴 |
| param-removed | param removed from signature | all call sites (cross-repo if public) | TypeError at call time | 🔴 |
| repr-key | new Gluon constexpr | kernel repr key list | stale JIT binary served | 🔴 |
| arch-discard | arch-specific kwarg | non-target-arch path | kwarg silently discarded | ⚠️ |
| dispatch-silent | multi-backend fallback | caller logging | backend switch with no diagnostic | ⚠️ |
| rename | public symbol renamed | all importers (cross-repo if public) | AttributeError at import/call time | 🔴 |

Severity (param-discard): 🔴 if param controls output correctness (`expert_mask`, `q_scale`, `kv_scale`); ⚠️ for performance knobs or optional features with working defaults.
**Public-API scope:** if the changed symbol is a public op (`from aiter import X`, or lives in `aiter/ops/*.py` / `aiter/__init__.py`), param-removed and rename break cross-repo consumers (ATOM / SGLang / vLLM), not just same-file call sites — the downstream to check is every repo that imports it. Also apply E1 (is a linked consumer PR mentioned?) and E5 (owner sign-off for a stable core-API contract).
Exception: method override where base class forces the signature but subclass legitimately ignores the param — flag as 📝 (structural discard, not a bug).
FP self-check (rename / param-removed): before firing, confirm the old symbol is NOT preserved by a compatibility shim added in the same PR — a new same-named `def` wrapper (keeps `from aiter import old_name` resolving), an alias, or a binding pin (`@compile_ops(..., fc_name='old_name')` keeps the C++ symbol even when the Python fn is renamed). A rename/removal behind such a shim is backward-compatible — do not fire. Real non-example (aiter#4227): `get_mla_metadata_v1` renamed to `_impl`, but a same-named wrapper + `fc_name='get_mla_metadata_v1'` preserved both the Python and C++ symbols → not B6.
Real examples (param-discard): `expert_mask` accepted but `# return None` commented out → TP expert-parallel callers silently routed wrong; `v_scale` strides never computed — `sc_off` indexes v_scale_ptr using k_scale strides, wrong scale on non-contiguous tensors (aiter#3959); `gate_up` discarded when `is_guinterleave=False` (aiter#4167).
→ `🔴/⚠️ B6-[sub-type]: [what changed] — [downstream not updated] — [failure]`

**B7 — Over-conservative assert blocks valid shapes** ⚠️
`assert M % tileM == 0` when the kernel pads internally and handles non-aligned M.
Real example (PR#3998): wrapper asserted alignment; asm kernel padded — valid small-M shapes rejected at the Python layer.
FP self-check: Does the kernel actually handle non-aligned inputs, or does the assert reflect a real hardware requirement?
→ `⚠️ B7: assert [constraint] may be unnecessary — verify kernel handles non-aligned inputs before removing`

### C — Hardcoded Arch / Dtype Assumptions

**C1 — FP8 fnuz check uses arch name** ⚠️
`if "gfx942" in arch: treat_as_fnuz()` — wrong. Same arch can have both fn and fnuz in flight.
Check IS fnuz: `tensor.dtype == fp8_fnuz`. Gate CONVERSION by arch is OK; inspection must use dtype.
Real example (PR#4073): valarLip: "check _is_fnuz by tensor's DType instead of arch."
→ `⚠️ C1: fnuz check uses arch name — use tensor.dtype comparison`

**C2 — FP8 scale bound hardcoded** ⚠️
`fp8_max = 240.0` → correct for fnuz (e4m3fnuz max=240), wrong for OCP e4m3 (max=448).
Use `get_dtype_max(dtype)` to derive; add a runtime guard if gfx942-only.
FP self-check: if the constant sits on a path already runtime-guarded to a single dtype/arch (e.g. inside an `if arch == 'gfx942':` block), the hardcode is safe there — do not fire; fire only when the path handles multiple fp8 flavors.
Real example (PR#4015): yzhou103: "would break for OCP e4m3 (max=448)."
→ `⚠️ C2: fp8_max hardcoded to [value] — use get_dtype_max(dtype)`

**C4 — New GPU arch string literal in dispatch condition** ⚠️
**FP self-check first (do this before deciding to fire):** Search the unchanged lines of this file for the same arch string (e.g., `'gfx1250'`). If that string already appears on an unchanged line → **do not fire** (pre-existing style, not a new violation). Only proceed if the arch string is genuinely new to this file.
Trigger (only after self-check passes): a new `+` line introduces an arch string literal in a dispatch condition (`if arch == 'gfx1250':`, `if 'gfx950' in arch_name:`), rather than routing through the central kernel registry or a named constant.
Also exempt: arch strings used only in comments, docstrings, or directory path strings; arch strings imported from a central registry module; arch strings used as **capability guards inside a kernel-specific wrapper function** (not in the centralized dispatch layer) — e.g., `get_gfx() == 'gfx1250'` inside `flydsl_flash_attn_batch_func` determines whether the FlyDSL variant is available; that check belongs in the wrapper, not in the central registry, and does not trigger C4 (aiter#3870).
Real examples: `'gfx1250'` new to `fused_mxfp4_quant.py` dispatch logic where no prior arch literals existed (aiter#3937 → fire C4); `'gfx1201'` added to `unified_attention.py` where `'gfx1250'` was already on line 79 (aiter#3956 → skip, pre-existing style); `get_gfx() == "gfx1250"` inside FlyDSL wrapper `flydsl_flash_attn_batch_func` (aiter#3870 → skip, capability guard not centralized dispatch).
C4 judges only the arch literal. Which helper a runtime wrapper calls is C5's question: a newly added runtime `get_gfx()` like the aiter#3870 guard fires C5, even though it skips C4.
→ `⚠️ C4: new arch string '[gfxNNNN]' hardcoded in dispatch — route through arch registry or named constant`

**C5 — Shared chip_info helpers are the ISA gate** ⚠️
Policy: `.github/instructions/aiter-ops-flydsl.instructions.md`. Do not invent a mixed-device, process-global, or first-`rocminfo`-agent finding against `get_gfx_runtime()` / `get_gfx()`.
The context picks the helper. Code that asks which GPU it is running on uses `get_gfx_runtime()`, which detects the live GPU: runtime dispatch (wrappers, launchers, kernel or tuned-config selection), test gates in `main()`, and the card a test records. Build-time codegen (`gen_instances`, AOT, module-level `csrc` selection) uses `get_gfx()`, which follows `GPU_ARCHS` and returns its last entry when that lists several targets, so on a multi-target build it can name an ISA other than the one installed (`GPU_ARCHS='gfx950;gfx942'` gives `gfx942` on an MI355X).
**FP self-check first:** only `+` lines count. `get_gfx()` or `gcnArchName` on unchanged lines is pre-existing style, not a new violation.
FIRE when a `+` line adds (a) a local ISA probe instead of the helpers (`gcnArchName`, `get_device_properties` read for architecture, a `rocminfo` parse), or (b) `get_gfx()` in a runtime dispatch path or a test gate. One such line fires even when other added lines use the right helper.
CLEAR only when every added architecture check uses the helper that fits its context.
Real examples (synthetic): `torch.cuda.get_device_properties(0).gcnArchName` added to `aiter/ops/mha.py` → fire (a); `get_gfx() == "gfx950"` added to kernel selection in an `aiter/ops/flydsl/` launcher → fire (b); `get_gfx()` added to the gate in `main()` of `op_tests/test_flydsl_<op>.py` → fire (b); `get_gfx()` on an unchanged test line → clear; `get_gfx()` added to an AOT target list → clear; `get_gfx_runtime()` added to a wrapper plus a new `gcnArchName` read in another file of the same PR → fire (a).
→ `⚠️ C5: new local ISA probe or get_gfx() in dispatch or a test gate — use get_gfx_runtime() for anything that asks which GPU is running, get_gfx() for build-time codegen`

---

### D — Uninitialized / Boundary State

**D1 — Atomic reduction on uninitialized buffer** 🔴
`atomic_fmax(*ptr, val)` = `*ptr = max(*ptr, val)`. If `*ptr` is uninitialized (from `::empty()`),
garbage dominates the max → corrupted amax → corrupted FP8 descale → silent wrong quantization.
Trigger: `atomic_fmax` / `atomic_max` + `::empty()` or non-zeroed allocation near it.
Severity: 🔴 for atomic accumulation (atomic_fmax, atomicAdd) — garbage propagates into every output element. ⚠️ for partial-sum buffers where a zero-weight coefficient mathematically cancels the contribution (e.g., online softmax with empty batch: `exp(-inf) × garbage = 0`); still flag because `0.0 × NaN = NaN` on IEEE hardware if the allocator returns dirty pages.
Real example (PR#4015): yzhou103: "AiterTensor::empty does not zero-initialize... garbage in v_amax silently corrupts descale."
→ `🔴 D1: [buffer] passed to atomic_fmax not zero-initialized — use ::zero() not ::empty()`

**D1b — Python-side UnboundLocalError from conditional assignment** 🔴
A variable is assigned inside an `if/elif` branch but referenced unconditionally after the block. Python does not detect this statically — `UnboundLocalError` or `NameError` fires only at runtime when the skipped branch is exercised. Silent in test environments that never hit the uninitialized path.
Trigger: new `if/elif` gate assigns a variable (`result = ...`) on some branches; a later line references it without a pre-block default. Check: is there a `var = None` or `var = default_val` before the if-block?
Exception: if there is a definitive `else` branch that also assigns the variable, or if the variable is only ever used inside the branch that assigns it.
Real example (ATOM#860): `needs_independent_noise` returned from `prepare_model()` tuple but assigned only in one branch of `prefill_forward` — other branch paths raised `NameError` when the sampler tried to use it.
→ `🔴 D1b: [var] assigned only inside [branch] but referenced unconditionally — add [var = default] before the if-block`

**D4 — Invariant reversal without citation** 🔴
A documented safety invariant is reversed: old comment says "must X because Y" → new code removes X claiming "X not needed" but no spec/asm/test is cited to prove Y no longer holds.
Trigger: `::zeros() → ::empty()` / `torch.zeros → torch.empty` where old comment mentions "must" / "required" / "read back as zero"; assert deletion without explanation; `.contiguous()` removal; zero-init removal with contradicting justification.
Real example (aiter#4043): old: "trailing pad must read back as zero for the asm reader, so zero-initialise it here" → new: "trailing pad is never read by the asm reader, so no zero-init is needed" — two comments directly contradict; PR cites no spec. Human reviewers missed this, only saw the profiling screenshot.
→ `🔴 D4: [operation] reverses a documented safety invariant — cite the spec/asm/test proving new assumption is safe`

**Evidence:** `$WORK/guards.txt` sorts every deleted guard into moved unchanged, returned
in changed form, or gone, and prints the before/after pair for the changed ones. Start
there: 14.5% of the PRs that trip this family put every guard straight back, and the
changed pairs are where the reversal shows — `AITER_CHECK(p != nullptr)` becoming
`AITER_CHECK(p->size(0) >= n)`, `hidden_size >= (tile_k * split_k) * 2` becoming
`hidden_size >= (tile_k * split_k)`.

**D8 — Kernel wrapper missing contiguous check** ⚠️
Python wrapper passes tensor to C++ / HIP kernel but doesn't assert `.is_contiguous()` or call `.contiguous()`. If the caller passes a strided tensor (slice, `.T`, output of non-contiguous `view()`), the kernel reads from wrong addresses — completely silent wrong result.
Trigger: new Python wrapper that calls a `@compile_ops` or C-extension kernel; check that non-trivially-shaped inputs (anything other than a freshly allocated `torch.empty`) are either asserted contiguous or explicitly made contiguous before the call.
→ `⚠️ D8: [tensor] passed to [kernel] without contiguous check — add .contiguous() or assert .is_contiguous()`

### E — Cross-Repo Sync

**E1 — New aiter symbol or kwarg without linked aiter PR** ⚠️
New `from aiter import X`, new kwargs on aiter calls, new aiter usage: PR description links an aiter PR?
New kwargs may require an aiter version not yet released.
Real example (ATOM#1494): `emit_bf16=True` kwarg added → needed aiter PR first.
→ `⚠️ E1: new aiter usage — corresponding aiter PR not mentioned`

**E2 — New param with backward-compatible default is dead code** 📝
New param added with default that preserves old behavior: the fix only activates when a consumer passes non-default. Who updates the consumer?
Real example (PR#3773): `max_seqlen=-1` added in aiter; fix never activated until ATOM passed actual value.
→ `📝 E2: new API param needs consumer-side update to activate — follow-up tracked?`

**E4 — Downstream CI skipped on a change downstream consumes** 🔴
aiter's downstream tests (ATOM, SGLang, vLLM) are SKIPPED BY DEFAULT and only run when a label is added — `ci:atom` (DeepSeek-R1-0528, GPT-OSS-120B), `ci:sglang` (DeepSeek-R1-MXFP4, Qwen 3.5), `ci:vllm` (GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5), `ci:all` (all of the above), or `ci:atom_full` (ATOM accuracy suite; only for FlyDSL/Triton upgrades). A PR that changes an op a downstream consumes can pass every *aiter* check with the downstream job skipped, merge green, and break the downstream silently — visible only after merge.
**Staleness guard:** the label→model mapping here is a snapshot. Before quoting a specific model for a label, confirm the current `ci:*` definitions in `.github/workflows/*.yaml` — the model roster rotates, and a stale mapping produces a confidently-wrong label recommendation.
Which label (be precise, do not reflexively pick `ci:all`):
1. **Dispatch reachability** — is the changed/new kernel wired into a default dispatch path? A pure-additive, arch-gated kernel not in any default path is unreachable by downstream → exempt, no label needed.
2. **Map activation → model** — if reachable, read the branch's activation condition (arch × dtype × shape × model gate) and map it to a model (e.g. 128-head fp8 MLA decode on gfx950 → DeepSeek-V4).
3. **Minimal label set** — DeepSeek is exercised by atom+sglang+vllm (≈ `ci:all`); Qwen 3.5 → `ci:sglang` only; Kimi-K2.5 → `ci:vllm` only; GPT-OSS-120B → `ci:atom`+`ci:vllm`.
Fallback: if you cannot trace the activation to a specific model but the diff changes the behavior of an mla/fused_moe/attention/quant/gemm/jit-core path, default to `ci:all` — a wasted CI run is far cheaper than a broken downstream.
Check: in the PR's statusCheckRollup, if `Atom Test` / `Kimi Downstream` / `Sglang Downstream` is `skipped` AND the diff touches a downstream-consumed op, coverage is missing.
Real example (aiter#3459): a DeepSeek-V4 128-head MLA decode kernel passed Aiter Test (success) with Atom Test SKIPPED and no `ci:*` label; after merge the Atom Test went red — the MLA change broke ATOM, invisible pre-merge.
→ `🔴 E4: [op] is consumed by [ATOM/SGLang/vLLM] but its downstream CI is skipped — add ci:all (or the minimal ci:atom/sglang/vllm) and require it green before merge`

**E5 — Stable core-API change needs owner sign-off, not just CI + one approve** 🔴
Modifying the BEHAVIOR / SIGNATURE / DEFAULT DISPATCH / NUMERIC SEMANTICS of a long-lived, widely-consumed API — `fused_moe.py`, `mla.py`, `ops/attention.py`, `ops/mha.py`, `ops/quant.py`, `gemm_op_a8w8.py`, `moe_op.py`, `jit/core.py` — must not be self-merged by a contributor or landed on a single reviewer's approval. These are downstream contracts; green CI (even `ci:all`) only covers the models/shapes it knows, not every downstream version or call path — necessary but not sufficient.
Trigger: diff changes the behavior/signature/default-path of a Step-4 Tier-1/Tier-2 file — NOT a pure-additive, arch-gated, behavior-preserving change (those are exempt; see E4 step 1).
Who signs off: aiter has **no CODEOWNERS file**, so ownership is de-facto — the top committer of the path is the effective gatekeeper:
`git log --format='%an' -- <file> | sort | uniq -c | sort -rn | head`
For `fused_moe.py` / core MoE dispatch this is currently @valarLip (top committer, and the maintainer who reverted #3593 and gates MoE PRs). Re-derive per file — MLA / attention / quant may have a different top committer.
**The reviewer must proactively notify the owner — do not wait for them to notice the PR.** Post a PR comment that @-mentions them (e.g. `@valarLip`) with a one-line summary of the contract change and an explicit request to approve before merge. Passive "someone should sign off" is not enough; the finding is not resolved until the owner has been actively pinged and has responded. Do not settle for a revert after merge.
Real example (aiter#3593): a `fused_moe.py` env knob merged on CI + one approval, then reverted by a maintainer within the hour — it should have had owner sign-off before merge.
→ `🔴 E5: [file] is a stable downstream-facing contract — do NOT self-merge. **Reviewer must @-mention the de-facto owner (git top-committer; @valarLip for fused_moe) in a PR comment requesting explicit sign-off** before merge, on top of ci:all`

---

### G — Multi-Stream Synchronization

**G1 — Missing HIP/CUDA stream synchronization** 🔴
HIP/CUDA streams execute concurrently by default. A tensor produced on stream A and consumed by a kernel on stream B without an explicit sync between them causes the consumer to read garbage — no crash, no error, silent wrong output.
Trigger: diff introduces a non-default `torch.cuda.Stream`, passes an explicit `stream=` argument to a kernel, or prepares buffers/weights on a side stream that are later consumed during forward pass on the compute stream. Check: is there `stream.synchronize()`, `stream.wait_stream(other)`, `hipEventRecord` + `hipStreamWaitEvent`, or `torch.cuda.current_stream().wait_stream(other)` between the last write on stream A and the first read on stream B?
→ `🔴 G1: [tensor] written on [stream A] consumed on [stream B] without sync — add stream.wait_stream() or hipStreamWaitEvent`

**G1b — Blocking queue.get() without timeout in production serving code** ⚠️
`queue.get()` without `timeout=` in a worker or service thread that depends on an external producer (decode loop, stream consumer, request handler). If the producer exits abnormally, the worker blocks forever — no crash, no log, hung process.
Trigger: `queue.get()` or `asyncio.Queue.get()` inside a `while True:` worker loop in production serving paths (entrypoints, engine loop, scheduler) without `timeout=` and without a corresponding `except queue.Empty` / `asyncio.TimeoutError` handler or a `done` flag.
Exception: test code, CLI tools, or one-shot scripts where a hang is detectable (CI timeout, interactive TTY).
→ `⚠️ G1b: [worker] blocks on queue.get() without timeout — add timeout= and handle Empty/TimeoutError to survive producer failure`

---

### Performance Evidence (always check)

**P1 — Perf PR without benchmark numbers** ⚠️
Trigger words: perf, optimize, fuse, faster, improve, +X%, replace kernel, OOM fix that changes algo.
Description must have numbers with units (ms, tokens/s, TFLOPS, %, speedup). Screenshots ≠ numbers.
Exception: PRs adding benchmarks/tests for existing ops without claiming improvement.
→ `⚠️ P1: perf claimed — no benchmark numbers with units`

**P2 — Benchmark covers only toy shapes** ⚠️
Numbers exist but only for M≤256, only 1 token, or one model.
Production: DSv4 E=385/topk=7, GPT-OSS 120B, Kimi-K2.5; token range 1→16384.
Staleness guard: the production config list is a snapshot — verify current E/topk/hidden and the model roster from the model registry or a recent benchmark before asserting what counts as "production".
→ `⚠️ P2: benchmark missing production shapes — [what's absent]`

**P3 — Perf claim not reproducible** ⚠️
Missing: test script, ROCm version, GPU model, TP config, model checkpoint.
→ `⚠️ P3: perf claim missing reproduction info — [what's absent]`

**P5 — Benchmark hides a cost real users pay on every call or cold start** ⚠️
The perf claim is measured with the timing window drawn so a *recurring* production cost is excluded: a first-call JIT compile on a path that is NOT cached across calls, or a setup step that runs on the live stream inside the timed region on every cold start. If that cost is real and recurring, omitting it can turn a net regression into an apparent speedup.
Do NOT fire on a genuinely one-time, amortizable setup that production pays once at model init — excluding weight shuffle/preshuffle, model weight loading, or a first-call JIT whose result is cached forever from steady-state per-call latency is CORRECT methodology, not deception. `warmup_iters` before a steady-state loop is standard and by itself is not P5.
FP self-check (do this before firing): is the excluded cost paid **once per deployment** (amortizable → do NOT fire) or **again on every call / every cold start / inside the timed stream** (→ fire)? If you cannot show it recurs, do not fire.
Counter-example (does NOT trigger P5): aiter#4166 preshuffles the static weight once outside the timing loop and honestly reports a geomean 0.69x result — a correct steady-state benchmark, not a hidden cost. Charging that one-time shuffle against a single call to manufacture a "regression" is itself the false positive this rule must avoid.
→ `⚠️ P5: timing window excludes [cost] that recurs per call / per cold start — re-run including it, or confirm it is one-time amortizable`

**P6 — Kernel change whose cost nobody measured** ⚠️
P1–P5 all grade the numbers *the PR supplies*. None of them produces a number, so a kernel PR can clear the whole Performance block on the strength of a table nobody re-ran. Correctness evidence does not cover this: `correctness_repo_tests: pass` means the kernel computes the right values and says nothing about how long it takes.

**Where the measurement now comes from.** The validator has a `perf` stage. When it runs, it times the target on base and on head back to back on the same locked GPU — base with the patch reversed out on the same worktree — and reduces the pair to `median_ratio`, the head speedup over base, oriented so `<1` is always a regression. That is a deterministic result, not an advisory one: below `threshold` (default 0.95, over ≥3 matched rows, both sides exiting cleanly) it writes a `should-fix` finding and the report's verdict becomes `NEEDS_WORK`. Read it out of `stages.perf`; do not re-derive it.

Trigger: Step 1's triage printed `perf triage: REQUIRED` — i.e. the PR changes runtime surface — **and** the head-matched report carries no usable `stages.perf` (absent, or `status: skip`). That is the gap P6 exists to name. If `stages.perf` is `pass` or `fail`, the measurement happened; report the number and do not fire.

Why the stage skips, and what each case means for the card:
- **no benchmark entry point in the target** — the honest common case (26 of aiter's 123 `op_tests/` targets have no timing harness at all). Fire P6, and say the target cannot be timed as written.
- **the PR adds the target** — base has nothing to compare against. Fire P6 with that reason; a head-only number is not a comparison.
- **nonzero exit on either side** — deliberately never a regression, because a truncated log yields a meaningless ratio. Fire P6 and treat the crash as the more interesting finding.
- **fewer than 3 matched rows / no shared timing column** — the two sides measured different things. Fire P6.

**The measurement that counts is base vs head, on this box, back to back.** Running only head against whatever baseline the PR chose reproduces the PR's own comparison; it cannot show a regression, and it silently inherits any staleness in that baseline. When the stage could not run, Step 1 prints the exact two-command manual form for the triaged target.
What to report: the shapes measured, both sides' numbers with units, and the delta. If nothing ran, say why — no idle GPU, no benchmark entry point, arch not available here — and mark every perf statement in the card `[inferred]`.
FP self-check: do NOT fire when the triage says NOT REQUIRED (no runtime surface), when `stages.perf` is `pass`/`fail`, when a manual measurement was taken and reported, or when the PR's own harness is the thing under test and has no steady state to measure. A single sample on a shared box is weak evidence — report the spread or the sample count rather than one number.
Real example (aiter#4538): a FlyDSL kernel whose entire justification was perf was reviewed to `Validation: PASS` with zero timing data; the perf finding stopped at "reviewer should ask", and a maintainer had already posted on the PR that a competing kernel beat it. Measuring afterwards took two `--scenario bench` runs and showed the fused path is where the PR's gain comes from — which the review should have carried in the first place. That gap is what the `perf` stage now closes automatically.
→ `⚠️ P6: kernel changed and no base-vs-head timing exists — [why the perf stage could not run]; measure [target] on both sides, or mark the perf findings [inferred]`

---


### Housekeeping (quick scan)

| Check | Trigger | Flag |
|---|---|---|
| Test reference dtype promotion | New test reference impl uses Python float literal (`1.0 + weight`, `0.5 * x.float()`) or explicit upcast (`.to(torch.float32)`, `.double()`) promoting to fp32 while kernel runs in bf16/fp8 — comparison calibrated against wrong-precision baseline | `⚠️ HK10: reference [fn] promotes to fp32 — cast back to [kernel dtype] before comparison` |
| `sys.path` at module level | `sys.path.insert(` / `sys.path.append(` in non-test `.py` | `⚠️ HK3: sys.path mutation — use relative imports` |
| TODO/stub in new path | `# TODO`, `# FIXME`, `raise NotImplementedError`, lone `pass` on a `+` line inside a new branch | `⚠️ HK7: [location] — incomplete implementation in new code path` |

(30 rule bodies)

$ $PY -I -S -B -X utf8 $SKILL\triage.py commentonly $WORK\pr.diff
exit=0
not a comment-dominated diff

$ $PY -I -S -B -X utf8 $SKILL\triage.py perfclaims $WORK\pr_meta.json
exit=0
ok For 96 GEMMs and 48 quants per prefill, those measurements correspond to 3.6 to 2.3 ms of warm host 
ok SGLang differences were within run-to-run spread. Native ATOM was faster in those recorded cells, bu

$ $PY -I -S -B -X utf8 $SKILL\triage.py citest $WORK\pr.diff $BASE
exit=0
every new test file lands where a CI job will run it
warning: reading $BASE, but this skill ships from $REVIEW_ROOT\aiter\source-163947e79040.
         given: a8c714e3a 2026-11-27
         skill: 163947e79 2026-12-02
         Forensics answer questions about the merge target; a second checkout answers them about itself.

$ $PY -I -S -B -X utf8 $SKILL\triage.py twins $WORK\pr.diff $BASE
exit=0
no new file closely mirrors an existing one
warning: reading $BASE, but this skill ships from $REVIEW_ROOT\aiter\source-163947e79040.
         given: a8c714e3a 2026-11-27
         skill: 163947e79 2026-12-02
         Forensics answer questions about the merge target; a second checkout answers them about itself.

$ $PY -I -S -B -X utf8 $SKILL\triage.py testquality $WORK\pr.diff
exit=0
op_tests/test_a8w8_eager.py  (new file)
  test functions added : 2  test_gemm, test_quant
  assertion primitives : 34
  tolerances           : 1e-3

$ $PY -I -S -B -X utf8 $SKILL\triage.py kerneltest $WORK\pr.diff
exit=0
KERNEL TESTS: no new kernel file without a collectible test

$ $PY -I -S -B -X utf8 $SKILL\triage.py siblings $WORK\pr.diff $HEAD
exit=0
VARIANT SIBLING STILL CARRIES A CHANGED LINE -- 3 pair(s). A1 is the rule;
divergence can be correct, so this is the pair to judge, not a finding.
  aiter/ops/gemm_op_a8w8.py: gemm_a8w8_bpreshuffle -> _gemm_a8w8_bpreshuffle_into
      is_int8 = XQ.dtype == dtypes.i8
  aiter/ops/gemm_op_a8w8.py: _gemm_a8w8_bpreshuffle_into -> gemm_a8w8_blockscale
      libtype = config["libtype"]
  aiter/ops/gemm_op_a8w8.py: _gemm_a8w8_bpreshuffle_into -> _gemm_a8w8_blockscale_bpreshuffle_native
      libtype = config["libtype"]
warning: reading $HEAD, but this skill ships from $REVIEW_ROOT\aiter\source-163947e79040.
         given: 76e7469b7 2026-11-26
         skill: 163947e79 2026-12-02
         Forensics answer questions about the merge target; a second checkout answers them about itself.

$ $PY -I -S -B -X utf8 $SKILL\triage.py flydslbounds $WORK\pr.diff $HEAD
exit=0
FLYDSL BOUNDS: no unbounded buffer resource or descriptor on an added line
warning: reading $HEAD, but this skill ships from $REVIEW_ROOT\aiter\source-163947e79040.
         given: 76e7469b7 2026-11-26
         skill: 163947e79 2026-12-02
         Forensics answer questions about the merge target; a second checkout answers them about itself.

$ $PY -I -S -B -X utf8 $SKILL\triage.py guards $WORK\pr.diff
exit=0
GUARDS DELETED -- 1 returned unchanged, 0 returned in changed form, 0 gone.
  moved unchanged: 1 line(s); the invariant still holds somewhere

$ $PY -I -S -B -X utf8 $SKILL\triage.py symbols $WORK\pr.diff $BASE
exit=0
IMPORTS RESOLVED: every first-party import the diff adds exists in the merge target or in this diff
warning: reading $BASE, but this skill ships from $REVIEW_ROOT\aiter\source-163947e79040.
         given: a8c714e3a 2026-11-27
         skill: 163947e79 2026-12-02
         Forensics answer questions about the merge target; a second checkout answers them about itself.

$ $PY -I -S -B -X utf8 $SKILL\triage.py structabi $WORK\pr.diff $BASE
exit=0
no struct with a pinned layout changed shape
warning: reading $BASE, but this skill ships from $REVIEW_ROOT\aiter\source-163947e79040.
         given: a8c714e3a 2026-11-27
         skill: 163947e79 2026-12-02
         Forensics answer questions about the merge target; a second checkout answers them about itself.

$ $PY -I -S -B -X utf8 $SKILL\triage.py aotpair $WORK\pr.diff $HEAD $BASE
exit=0
AOT PAIRING: no new ops-side contract that aiter/aot/flydsl/ was left unaware of
warning: reading $HEAD, but this skill ships from $REVIEW_ROOT\aiter\source-163947e79040.
         given: 76e7469b7 2026-11-26
         skill: 163947e79 2026-12-02
         Forensics answer questions about the merge target; a second checkout answers them about itself.
warning: reading $BASE, but this skill ships from $REVIEW_ROOT\aiter\source-163947e79040.
         given: a8c714e3a 2026-11-27
         skill: 163947e79 2026-12-02
         Forensics answer questions about the merge target; a second checkout answers them about itself.

$ $PY -I -S -B -X utf8 $SKILL\triage.py reviewers $WORK\pr_meta.json $BASE
exit=0
BingYuan.Zhou
Elton
zufayu
kyle-256
Fyzyukk
Kristian Sikiric
HaonanWang98
yzhou103
la
Mikko Tukiainen
Fangzhou-Ai
xiaofei-zheng
LuweiZhou2025
Yu-Yun Chang
honglie
Sergey Shlyapnikov
valarLip
Ao Li
Shantipriya Parida
Xin Huang
Jessie
XiaobingZhang
Double Young
Zheng Gong
Felix Li
Alexandra Sidorova
Shao-Chun Lee
ZhangLirong
Bingxu Chen
carlushuang

$ $PY -I -S -B -X utf8 $SKILL\triage.py evidence $WORK\pr.diff $HEAD\aiter\jit\utils\eager_guard.py $HEAD\aiter\ops\gemm_op_a8w8.py $HEAD\aiter\ops\quant.py $HEAD\op_tests\test_a8w8_eager.py
exit=0
=== XQ on head ===
  gemm_op_a8w8.py:141: XQ: Tensor,
  gemm_op_a8w8.py:182: XQ: Tensor,
  gemm_op_a8w8.py:262: XQ: Tensor,
  gemm_op_a8w8.py:309: XQ: Tensor,
  gemm_op_a8w8.py:343: XQ: Tensor,  # A:[M, K] i8
  gemm_op_a8w8.py:356: XQ: Tensor,
  test_a8w8_eager.py:296: assert "must match" in str(err), "BF16 XQ: not rejected by the custom op"
  test_a8w8_eager.py:297: rows.append(_row("GEMM, BF16 XQ with an FP8 WQ", calls, True))
  test_a8w8_eager.py:307: # The custom op zero-pads XQ to a K-padded weight's K.
  test_a8w8_eager.py:466: def run(XQ, WQ, x_scale, w_scale, bias, dtype, check):
  test_a8w8_eager.py:467: return torch.full((XQ.shape[0], WQ.shape[0]), 7.0, dtype=dtype, device="cuda")


$ $PY -I -S -B -X utf8 $REVIEW_ROOT\aiter\source-163947e79040\.claude\skills\validate-kernel-pr\scan_index_width.py --diff $WORK\pr.diff
exit=0
== index x stride in DEVICE code, reaching pointer arithmetic, no 64-bit widening: 0 distinct expressions in 0 files ==


== same shape in HOST code (4) -- normally not D9; check only if one of these computes a device offset ==
  op_tests/test_a8w8_eager.py:184  (m * k + n * k) * xq.element_size()
  op_tests/test_a8w8_eager.py:184  m * n * ref.element_size()
  op_tests/test_a8w8_eager.py:184  m * k
  op_tests/test_a8w8_eager.py:184  n * k

== runtime kernel parameters added with no width annotation: 3 ==
  op_tests/test_a8w8_eager.py: k, m, n

Actual eight-gate output, including any retained artifact-format correction

Earlier malformed or incorrectly encoded local review artifacts, if present, remain in the log below. Only affected gate commands were rerun after correcting artifact format. The final card contains the findings recognized by the final card gate; no product code was changed by these corrections.

$ $PY -I -S -B -X utf8 $SKILL\triage.py answers $WORK\answers.txt
exit=0
ANSWERS COMPLETE: 6/6

$ $PY -I -S -B -X utf8 $SKILL\triage.py diagnostic $WORK\ai_diagnostic.txt
exit=0
DIAGNOSTIC COMPLETE: 6/6

$ $PY -I -S -B -X utf8 $SKILL\triage.py corefiles $WORK\core_files.txt $WORK\pr.diff $BASE
exit=0
CORE FILES ASSESSED: 2/2 backbone files (0 tier-1), 2 gap(s)
warning: reading $BASE, but this skill ships from $REVIEW_ROOT\aiter\source-163947e79040.
         given: unreachable
         skill: unreachable
         Forensics answer questions about the merge target; a second checkout answers them about itself.

$ $PY -I -S -B -X utf8 $SKILL\triage.py ledger $WORK\rules.txt $WORK\verdicts.txt $WORK\pr.diff
exit=0
LEDGER COMPLETE: 30/30 rules adjudicated with evidence

$ $PY -I -S -B -X utf8 $SKILL\triage.py card $WORK\card.md $WORK\verdicts.txt $WORK\ai_diagnostic.txt $WORK\answers.txt $WORK\pr.diff $WORK\late_findings.txt
exit=0
CARD NAILED DOWN: 4 findings, each traced to an adjudication and anchored in a changed file; every FIRE accounted for

$ $PY -I -S -B -X utf8 $SKILL\triage.py refutations $WORK\refutations.txt $WORK\pr.diff $WORK\card.md
exit=0
REFUTATIONS COMPLETE: 8 attempted, 4 survived, 4 killed before reaching the card

$ $PY -I -S -B -X utf8 $SKILL\triage.py independent $WORK\independent.txt $WORK\card.md
exit=0
INDEPENDENT REFUTATION: none available (No reader blind to this reasoning is available in the assign); the card says so

$ $PY -I -S -B -X utf8 $SKILL\triage.py design $WORK\design.txt $WORK\card.md $WORK\reviewers.txt $WORK\pr_meta.json $WORK\pr.diff
exit=0
DESIGN ROUTED: size 1040 lines / 4 files -- over the review bar

Preserve the a8w8 eager selector and target split-K deferred APIs when
resolving gemm_op_a8w8.py. Keep the stacked PR base branch unchanged.
@ZLkanyo009

Copy link
Copy Markdown
Contributor Author

The stacked-base conflict is resolved at cd40ba1e. This is a normal merge of the actual #8030 target dd13d73f into 76e7469b; the PR still targets lingzha/tgemm-eager-fast-path.

The only manually resolved file is aiter/ops/gemm_op_a8w8.py. It retains the existing shared selector/eager path and the target's split-K deferred/config APIs. Independent review verified both sets of function ASTs, including both registered/public GEMM definitions; the other three FP8 file deltas are preserved. Fourteen CPU metadata scenarios cover lookup order, FP8/INT8 and padded-K routing, fallbacks and split-K eligibility. Black/Ruff and diff-whitespace checks pass.

The description now separates this merge validation from the fixed-image GPU results at 76e7469b. Clean native builds, production lookup performance, fresh-process compile/fake-first coverage and current-head model validation remain open; no new GPU or model result is claimed. Independent merge-review digest: 9d2f277470af542b2c79fe67c6104b6140c530fa48816b1bb397709d051adc1d.

@ZLkanyo009

Copy link
Copy Markdown
Contributor Author

Current-head validation stopped at the CKTile build deadline. On cd40ba1e in the fixed e8 image, the first four native-module workers exited 0 and produced artifacts. The fifth, module_gemm_a8w8_bpreshuffle_cktile, reached its 1,200-second work limit and was terminated. Its final ELF and dependency closure are absent; the ABI stage did not start.

All 428 raw files (214,363,748 bytes) and the complete archive were retained on host25 and their integrity was independently checked. The owned container and resources were released at 21:55:14 UTC. Full clean-build, ABI, normal package/cache resolution, fake-first and real Inductor acceptance remain pending.

Next: retain the four completed artifacts and original failure evidence, inspect the existing Ninja/object state, and prepare a bounded CKTile-only continuation before finishing dependency-closure and ABI checks. The original executor owns this continuation; the four completed modules will be reused.

@ZLkanyo009
ZLkanyo009 force-pushed the lingzha/tgemm-eager-fast-path branch from d6ceec6 to d0b7855 Compare December 3, 2026 09:34

This branch has not been deployed

No deployments
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