Skip to content

[Triton/Gluon] [Bugfix] [Perf] Fix non-preshuffle MQA paging and large KV offsets, retune the decode grid, and cut plain-path instruction count - #5614

Merged
azaidy merged 17 commits into
mainfrom
zhiding512/fix-paged-mqa-block-paging-20260917
Oct 13, 2026

Conversation

@zhiding512

@zhiding512 zhiding512 commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Four defects in the paged MQA logits decode path, all silent: no fault, no NaN or Inf, just wrong or missing logits.

The branch has since picked up two pieces of performance work on the same path, both originally reviewed as stacked PRs and now folded in: the decode grid sizing from #5711 and its follow-up, and the two instruction-level changes to the plain kernel from #5700. They are described in their own sections below and neither touches the correctness of the four fixes.

1. Block paging for non-preshuffled multi-token blocks. With Preshuffle=False and KVBlockSize > 1 the Gluon kernel used token positions as page-table columns and always read token 0's K values and scale from each physical block. Compact block tables caused illegal memory accesses; padding the table kept the reads in allocated memory but produced incorrect logits. Resolve the physical block with token_pos // KVBlockSize and add the in-block token offset to both the K and the scale address, in the initial loads and in the prefetch loop. This fixes the failures reproduced in #5591. Related: #5600.

2. KV caches past 2 GiB in the plain kernel. That kernel forms a per-token address from the page table, so physical_block * stride overflowed a 32-bit product and wrapped into another page once the cache crossed 2 GiB. Its KV and scale strides are now 64-bit for every shape and the loads go through global pointers. A size-dependent switch between a 32-bit and a 64-bit variant was considered and dropped: it gives one shape two ABIs behind one AOT directory name, and the measured cost of always using 64-bit is bounded (see Performance).

3. KV caches past 2 GiB in the preshuffle kernel. When ChunkKPerStage % KVBlockSize != 0, which is KVBlockSize=256 at ChunkK=256, the K and scale addresses came from the same 32-bit page-index product. Read them through a global pointer with the index promoted to 64 bits, the way the other branch of that kernel already does.

4. Preshuffle tail store reaching into the next output row. The branch that loads a page index per lane stored its last stage across the whole tile, including the columns past context_length that hold -inf. When the output width equals an unaligned context those columns land in the next row: with context_lengths=(3001, 513) and a compact output, row 1 lost its first 7 logits. Those three stores are now bounded by max_model_len, which the kernel's six other stores already did.

Changes

  • Correct block-table, K and scale addressing for sectioned, non-preshuffled caches, and keep negative positions in the backward-shifted first tile mapped to token 0 of physical block 0 after masking the page-table load.
  • Generate the new address arithmetic only for KVBlockSize > 1, preserving the original scalar-first expressions, code generation and register usage for KVBlockSize=1.
  • Use 64-bit KV and scale strides in the plain kernel unconditionally, and drop the now dead 32-bit load paths.
  • Promote the preshuffle per-stage K and scale addresses to 64 bits.
  • Bound the preshuffle per-lane stores by max_model_len.
  • Extend op_tests/test_pa_mqa_logits_offset.py: 48 paging cases (block sizes 1/16/64/128, chunks 64/256, compact and padded tables, randomized physical pages, per-token scales, short and empty contexts, MTP, multiple prefetch iterations) and 12 large-offset cases (plain B1/B64 and preshuffle B64/B256, each at the 2, 4 and 8 GiB boundaries) against an independent FP32 reference, plus the two existing output-offset cases.

Note for AOT users: the plain kernel's stride arguments changed from i32 to i64, its instruction stream changed again with the two optimizations below, and the preshuffle kernel's instruction stream changed, so cached .hsaco artifacts have to be regenerated from this branch. The grid change does not add to that — SplitKV is a runtime i32 argument, not a constexpr, so it is not part of the compile key.

Decode grid sizing

deepgemm_fp8_paged_mqa_logits derived SplitKV from the batch and rounded SplitKV up to a multiple of five, but the thing that has to line up with the CU count is the grid, and the two differ by a factor of TileQCount. At batch 16/32/64 on 256 CU that landed on 2.5 workgroups per CU, so half the CUs ran three and half ran two and the kernel waited for the deeper half. The grid is now sized directly at two workgroups per CU, clamped so splits that start past the end of the context are not launched.

Two per CU is not enough at the top of the batch range, where each workgroup ends up chewing 128 to 256 chunks with no queue behind it, so a second term raises SplitKV toward 32 chunks per workgroup — by at most 2x, because max_model_len is only an upper bound on the real context and a loose bound must not be able to over-split without limit.

Scoring each candidate rule by how far its pick sits from the best SplitKV measured at each of 42 shapes:

rule exact 4x over-estimate 16x 64x
the original formula 7.69% 7.69% 7.69% 7.69%
two per CU (context-free) 0.85% 0.87% 0.89% 0.89%
+ cap 32 chunks/WG, unbounded 0.46% 1.69% 7.45% 20.11%
+ cap 32, at most 2x 0.56% 1.40% 2.87% 4.08%

Against the original formula, at N=131072:

layout batch SplitKV grid before after change
plain 1 520→512 520→512 5.95 5.96 +0.22%
plain 16 40→32 640→512 60.32 51.59 −14.46%
plain 64 10→16 640→1024 274.44 233.42 −14.95%
plain 128 10→8 1280→1024 469.96 456.88 −2.78%
plain 256 10→4 2560→1024 913.21 926.29 +1.43%
preshuffle 16 40→32 640→512 49.54 42.65 −13.92%
preshuffle 64 10→16 640→1024 249.40 220.28 −11.68%
preshuffle 128 10→8 1280→1024 465.27 445.93 −4.16%

Over 48 shapes (batch 1..256, context 8k/32k/128k, next_n 1 and 2, both layouts) the median is −2.01%, 21 shapes improve by more than 5%, the best is −18.90%, and zero mismatches. Batch 256 at a 128k context is the one shape that stays slower: its grid was already an exact 10 per CU so it never paid the quantisation cost, and its curve is a broad plateau on which the old value sat near the middle. Closing the remaining 1.9% would need the real context length, which lives in a device tensor.

The optional SplitKV argument added here is an override in the same spirit as the existing TotalCuCount; it is what lets both arms of the measurements come from a single binary. gfx1250 keeps its own formula, having had no part available to re-tune on.

Correctness for this part: 62 passed, plus a 91-case scan aimed at the split seams — awkward chunk counts, non-uniform context lengths including (8192, 8191, 1, 256, 257, 255, 65536, 3) and (20000, 3001, 513, 131072), contexts of length 1 and 2, exact multiples of ChunkK and one less, and KVBlockSize 1/16/64/256 on both layouts — zero mismatches over the whole output, masked region included.

Plain-path instruction-level optimizations

Two changes to the Preshuffle=False Gluon kernel. Both are unconditional; the shape gate on the first is a correctness condition, not a switch.

1. Hoist the KV block index and in-block offset out of the loop. The kernel recomputed token // KVBlockSize and token % KVBlockSize over a ChunkK-wide vector every iteration. KVBlockSize is a constexpr power of two, so that should be one shift and one AND per register, but it expanded to 64 instructions because context_idx is loop-variant and the compiler cannot fold through it. context_idx advances by ChunkK and the gate requires ChunkK % KVBlockSize == 0, so the modulo is loop-invariant and the quotient grows by a constant. The identity does not require context_idx to be KVBlockSize-aligned, and KVBlockSize > ChunkK leaves the quotient without a constant stride, so those shapes keep the general form.

2. Mask the logits after the head reduce, not before. The kernel wrote -inf into the whole (ChunkQ, ChunkK) accumulator before reducing over heads, one v_cndmask per accumulator register: 32 in the loop and 32 more in the epilogue. Masking the reduced logits needs four and is the same value, since summing ChunkQ copies of -inf is -inf. The preshuffle kernel already masks after its reduce at all four of its store sites. Removing the -inf write also unblocks packed FP32 in the epilogue.

in-loop integer address ops v_cndmask v_mul_f32 v_pk_add_f32 v_pk_mul_f32 v_pk_fma_f32 VGPR
before 168 98 132 35 0 0 186
+ 1 76 98 132 35 0 0 188
+ 2 76 42 68 18 16 16 190

Neither improves register pressure: all three allocate 192 VGPR, so occupancy stays at 2 waves/SIMD.

Measured on top of the grid change above. Three worktrees run back to back inside each round with the arm order rotated, eight rounds; the statistic is the median of the per-round paired ratio, since clocks are not locked here and only pairing cancels the drift. Preshuffle=True is untouched by both, so its paired ratio is the noise floor.

Batch change 1 change 2 both control (noise floor)
16 −0.58% −2.83% −3.57% +0.09%
64 −0.40% −1.02% −1.36% +0.01%
128 −0.12% −0.69% −0.80% +0.06%

Change 2 carries almost all of the gain. Change 1 only just clears the noise floor at batch 16 and sits inside it at batch 128; it is worth keeping because it costs nothing and the instruction count genuinely drops, not because it is a measurable speedup on its own. Batch 1 does not resolve and no claim is made for it: over 16 paired rounds plain moves −0.97% with an IQR of [−3.08%, +0.28%] while the unchanged control moves +0.61% with an IQR of [−0.75%, +9.18%].

Both sides of the HoistKvAddr gate were measured at the same production scale:

KVBlockSize ChunkK gate b=16 b=128
16 256 on −2.88% −0.66%
64 256 on −3.57% −0.80%
128 256 on −3.95% −0.89%
256 256 on −5.02% −1.38%
128 64 off −2.21% −1.38%
256 128 off −0.58% −0.35%
1 256 off −2.96% —

No shape regresses. The gated-off shapes still gain because change 2 is unconditional. KVBlockSize=1 takes the branch where the logical index is never computed and KVBlockSize > ChunkK takes the branch where it is computed but the hoist is off, so all three paths are exercised; op_tests/test_pa_mqa_logits_offset.py already parametrises block_size ∈ {1, 16, 64, 128} × chunk_k ∈ {64, 256}, which covers the same split for correctness.

Change 1 is bit-identical to its parent. Change 2 is not, because folding a multiply and an add into v_pk_fma_f32 skips the rounding of the intermediate product: 410363 of 2097152 logits move by at most 3.05e-05 on a ±273 range. Against an fp64 reference the two are equally far from the truth (mean absolute error 4.615302e-04 before, 4.615247e-04 after, identical maxima), because the error floor is the fp8 quantisation of q and k, not the fp32 epilogue.

All 430 measurement processes across these campaigns were 0-mismatched against the fp32 reference, with no NaN or Inf.

Testing

Environment: gfx950 (256 CU), ROCm 7.2.4, PyTorch 2.10.0+rocm7.2.4.git3d3aa833, Triton 3.7.0, one physical GPU pinned per process, clocks not locked.

# regression module, JIT gluon kernels
ROCR_VISIBLE_DEVICES=1 PYTHONPATH=. python -m pytest -q op_tests/test_pa_mqa_logits_offset.py
# -> 62 passed

# the original #5591 repro, unmodified
ROCR_VISIBLE_DEVICES=1 PYTHONPATH=. python repro_paged_mqa_logits_preshuffle_false.py
# -> [issue2] allclose=True mismatch=0/6000   (was 5968/6000)
# -> [issue1] no illegal access, exit code 0  (was HIP error 700, exit code 1)

# same repro with AOT loading enabled, after regenerating the artifacts
ROCR_VISIBLE_DEVICES=1 AITER_ENABLE_AOT_GLUON_PA_MQA_LOGITS=1 PYTHONPATH=. \
  python repro_paged_mqa_logits_preshuffle_false.py
# -> mismatch=0/6000, no illegal access
ROCR_VISIBLE_DEVICES=1 AITER_ENABLE_AOT_GLUON_PA_MQA_LOGITS=1 PYTHONPATH=. \
  python -m pytest -q op_tests/test_pa_mqa_logits_offset.py
# -> 2 passed, 60 skipped (the JIT-gated cases skip in AOT mode)

The repro script is PR #5591's file at commit 81d4380.

Defect 4 was also swept outside pytest with the same shape at cache sizes from 1 MiB to 8 GiB, context pairs (3001, 513), (3001, 512), (513, 3001), (513, 1025), (3072, 513) and (3001,), and TotalCuCount of 1, 2, 8, 256 and the default: KVBlockSize=64 and 256 now match the reference everywhere. Before the fix, every case whose first context was not a multiple of the KV block lost the leading logits of the next row.

Cost of the four fixes

This section predates the two performance sections above and is the cost of the correctness fixes alone, measured before the grid change; its absolutes are not comparable with the numbers there.

Decode, N=131072, H=32, D=128, next_n=1, ChunkK=256, WavePerEU=2, one process per point, median of three, accuracy checked over the whole output on every run.

# both files in one directory: the fixed test_mqa_logits.py from #5434 (commit
# 849c7c2) for input generation, packing and the FP32 reference, plus the
# driver below
for round in 1 2 3; do
  for batch in 1 16 64 128; do
    for layout in preshuffle plain; do
      ROCR_VISIBLE_DEVICES=1 PYTHONPATH=. python run_perf.py \
        --batch "$batch" --layout "$layout" --kv-block 64 \
        --output "out/$layout-b$batch-r$round.json"
    done
  done
done

Measured on this branch:

Layout KVBlock Batch KV cache us TFLOPS TB/s mismatch
Preshuffle=False 64 1 0.02 GiB 7.258 147.9 2.457 0/131072
Preshuffle=False 64 16 0.26 GiB 58.647 292.9 4.864 0/2097152
Preshuffle=False 64 64 1.03 GiB 274.822 250.1 4.152 0/8388608
Preshuffle=False 64 128 2.06 GiB 470.838 291.9 4.847 0/16777216
Preshuffle=True 64 1 0.02 GiB 5.004 214.6 3.563 0/131072
Preshuffle=True 64 16 0.26 GiB 50.272 341.7 5.675 0/2097152
Preshuffle=True 64 64 1.03 GiB 250.720 274.1 4.551 0/8388608
Preshuffle=True 64 128 2.06 GiB 463.818 296.3 4.921 0/16777216
Preshuffle=True 256 64 1.03 GiB 237.888 288.9 4.797 0/8388608
Preshuffle=True 256 128 2.06 GiB 451.407 304.5 5.056 0/16777216

Per-change cost, from paired runs that alternate the two versions within each round. These are deltas only; absolute numbers from different sessions are not comparable, since an unchanged control moved by more than 10% between sessions on this unlocked machine.

Unconditional 64-bit strides in the plain kernel, KVBlockSize=64:

Batch conditional unconditional delta
1 5.728 6.677 +16.55%
16 55.701 57.955 +4.05%
64 270.004 274.738 +1.75%
128 418.183 417.427 -0.18%

Batch 128 crosses 2 GiB, so both versions compile the same kernel there; its -0.18% is the noise floor of the setup. With KVBlockSize=1 the unconditional kernel is faster instead: 247.617 -> 95.281 us at batch 16 and 1053.010 -> 463.740 us at batch 64.

Preshuffle 64-bit addressing and the store bound:

KVBlock Batch before after delta accuracy
256 64 250.599 238.254 -4.93% 0 -> 0 mismatched
256 128 449.150 451.121 +0.44% 508281/16777216 -> 0
64 128 464.583 463.802 -0.17% 0 -> 0 mismatched

Folding the page base into a buffer_load pointer fixes the same addressing but pays a descriptor setup per stage: +4.59% at batch 64 and +3.74% at batch 128, against +0.44% and -4.93% for the global-load form that was kept. Rounds did not overlap between arms, e.g. 247.898/250.599/251.677 before against 238.032/238.254/238.422 after at batch 64.

run_perf.py
#!/usr/bin/env python3
"""Decode perf/accuracy driver for one (batch, layout) pair per process.

Reuses the input generation, fp32 reference and packing helpers of the fixed
op_tests/test_mqa_logits.py (PR #5434, commit 849c7c25), and switches both the
KV packing and the interface Preshuffle flag together. Counts mismatches over
the whole output and returns exit code 2 on an accuracy failure.
"""

import argparse
import importlib.util
import json
import os
import sys

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
_spec = importlib.util.spec_from_file_location(
    "fixed_test_mqa_logits", os.path.join(SCRIPT_DIR, "test_mqa_logits.py")
)
fixed = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(fixed)

import torch  # noqa: E402

from aiter import dtypes  # noqa: E402
from aiter.jit.utils.chip_info import get_gfx  # noqa: E402
from aiter.ops.triton.attention.pa_mqa_logits import (  # noqa: E402
    deepgemm_fp8_paged_mqa_logits,
)
from aiter.ops.triton.utils.types import get_fp8_e4m3_dtype  # noqa: E402
from aiter.test_common import run_perftest  # noqa: E402


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--batch", type=int, required=True)
    parser.add_argument("--layout", choices=["preshuffle", "plain"], required=True)
    parser.add_argument("--n", type=int, default=131072)
    parser.add_argument("--heads", type=int, default=32)
    parser.add_argument("--head-dim", type=int, default=128)
    parser.add_argument("--next-n", type=int, default=1)
    parser.add_argument("--kv-block", type=int, default=64)
    parser.add_argument("--chunk-k", type=int, default=256)
    parser.add_argument("--wave-per-eu", type=int, default=2)
    parser.add_argument("--num-iters", type=int, default=101)
    parser.add_argument("--num-warmup", type=int, default=2)
    parser.add_argument("--output", required=True)
    args = parser.parse_args()

    if os.path.exists(args.output):
        sys.exit(f"refusing to overwrite {args.output}")

    preshuffle = args.layout == "preshuffle"

    batch, n, heads, dim = args.batch, args.n, args.heads, args.head_dim
    next_n, kv_block = args.next_n, args.kv_block

    torch.manual_seed(0)
    fp8_dtype = get_fp8_e4m3_dtype()

    rows = batch * next_n
    blocks_per_seq = (n + kv_block - 1) // kv_block
    num_blocks = batch * blocks_per_seq

    q = torch.randn(batch, next_n, heads, dim, dtype=dtypes.bf16)
    q_fp8 = q.to(fp8_dtype)
    del q

    kv = torch.randn(num_blocks * kv_block, dim, dtype=dtypes.bf16)
    kv_q, kv_sf = fixed._pertoken_cast_to_fp8(kv, fp8_dtype)
    del kv
    kv_q = kv_q.view(num_blocks, kv_block, dim)
    kv_sf = kv_sf.view(num_blocks, kv_block)

    weights = torch.randn(rows, heads, dtype=dtypes.fp32)
    context_lens = torch.full((batch,), n, dtype=dtypes.i32)
    block_tables = torch.randperm(num_blocks).to(dtypes.i32).view(batch, blocks_per_seq)

    ref, inside = fixed.run_torch_decode(
        q_fp8.float(), kv_q, kv_sf, weights, context_lens, block_tables, n
    )

    kv_cache = fixed._pack_paged_kv(kv_q, kv_sf, preshuffle=preshuffle)
    out_logits = torch.full((rows, n), -float("inf"), dtype=dtypes.fp32)

    def run_triton():
        deepgemm_fp8_paged_mqa_logits(
            q_fp8,
            kv_cache,
            weights,
            out_logits,
            context_lens,
            block_tables,
            n,
            Preshuffle=preshuffle,
            KVBlockSize=kv_block,
            ChunkK=args.chunk_k,
            WavePerEU=args.wave_per_eu,
        )
        return out_logits

    total_ctx = int(context_lens.sum().item())
    flops = 2.0 * heads * dim * next_n * total_ctx
    read_bytes = q_fp8.nbytes + total_ctx * (dim + 4) + weights.nbytes
    nbytes = read_bytes + rows * n * 4

    out, us = run_perftest(
        run_triton,
        num_iters=args.num_iters,
        num_warmup=args.num_warmup,
        num_rotate_args=fixed._rotate_args(read_bytes),
    )

    close = torch.isclose(out, ref, rtol=1e-2, atol=1e-2)
    mismatch = int((~close).sum().item())
    total = out.numel()
    inside_mismatch = int((~close[inside]).sum().item())
    nan_inf = int((~torch.isfinite(out[inside])).sum().item())

    record = {
        "gfx": get_gfx(),
        "batch": batch,
        "layout": args.layout,
        "n": n,
        "heads": heads,
        "head_dim": dim,
        "next_n": next_n,
        "kv_block": kv_block,
        "chunk_k": args.chunk_k,
        "wave_per_eu": args.wave_per_eu,
        "num_iters": args.num_iters,
        "num_warmup": args.num_warmup,
        "us": us,
        "TFLOPS": flops / us / 1e6,
        "TB/s": nbytes / us / 1e6,
        "mismatch": mismatch,
        "total": total,
        "inside_mismatch": inside_mismatch,
        "inside_total": int(inside.sum().item()),
        "nonfinite_inside": nan_inf,
        "kv_bytes": num_blocks * kv_block * (dim + 4),
        "aot": os.environ.get("AITER_ENABLE_AOT_GLUON_PA_MQA_LOGITS", "0"),
    }
    with open(args.output, "w") as f:
        json.dump(record, f, indent=2, sort_keys=True)
    print(json.dumps(record, sort_keys=True))

    if mismatch:
        print(f"ACCURACY FAILURE: {mismatch}/{total} mismatched", file=sys.stderr)
        sys.exit(2)


if __name__ == "__main__":
    main()

@zhiding512
zhiding512 requested review from a team and a lite review from Copilot September 17, 2026 03:28
@github-actions github-actions Bot changed the title [Bugfix] Fix block paging in non-preshuffle MQA logits [Triton/Gluon] [Bugfix] Fix block paging in non-preshuffle MQA logits Sep 17, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
multigpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 5614 --add-label <label>

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to opt this PR out.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The documented AOT/stub path still uses unfixed addressing, and zero-length context coverage is missing.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Fixes non-preshuffled Gluon MQA logits block addressing for multi-token KV blocks and adds regression coverage.

Changes:

  • Corrects page-table, K, and scale addressing.
  • Preserves optimized block-size-1 addressing.
  • Adds paging, correctness, and memory-safety tests.
File summaries
File Summary
op_tests/triton_tests/attention/test_pa_mqa_logits.py Adds parameterized paging and memory-safety regression tests.
aiter/ops/triton/gluon/pa_mqa_logits.py Implements corrected block and token-offset addressing.
Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 2
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread aiter/ops/triton/gluon/pa_mqa_logits.py Resolved
Copilot AI review requested due to automatic review settings September 17, 2026 06:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Empty-context coverage is missing, and the regression tests should be relocated.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (1)

op_tests/test_pa_mqa_logits_offset.py:149

  • The new regression matrix still contains only positive context lengths, so it never exercises the split_context_length <= 0 early-return path for an empty sequence even though empty contexts are part of the claimed coverage. Add a mixed batch containing a zero-length context to verify that the kernel leaves that row at -inf without touching the page table or output guards.
@pytest.mark.parametrize(
    "context_lengths,next_n,heads,hidden_dim",
    [
        pytest.param((997, 63, 1), 1, 32, 128, id="decode"),
        pytest.param((3000, 257, 3, 0), 3, 64, 128, id="mtp"),
        pytest.param((511, 7), 1, 64, 64, id="dim64"),
    ],
  • Files reviewed: 2/2 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread op_tests/test_pa_mqa_logits_offset.py Resolved
Copilot AI review requested due to automatic review settings September 17, 2026 06:37

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Kernel addressing changes and a test-matrix count discrepancy warrant final human review.

Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread op_tests/test_pa_mqa_logits_offset.py Resolved
This reverts commit de3c504.

Routing non-preshuffled KVBlockSize>1 to the Triton kernel in AOT mode makes
the Gluon addressing fix of a7e2cd2 unreachable on that path, and silently
selects a kernel whose latency was not measured. On runtimes before Triton
3.4 that path is the only way to reach the Gluon kernel at all.

AOT directory names encode only shape and layout, never a kernel revision or
signature variant, so a cached binary can go stale for any kernel in this
file. That belongs in the cache key rather than in a per-shape dispatch
carve-out, which also leaves no way back once artifacts are rebuilt.

The accompanying test cases asserted the fallback instead of exercising the
fixed Gluon kernel, so the JIT parametrization is restored as well.

Signed-off-by: zhimding <[email protected]>
Copilot AI review requested due to automatic review settings September 17, 2026 12:25

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

AOT routing and corresponding regression coverage do not yet protect against stale unsafe Gluon binaries.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (1)

aiter/ops/triton/gluon/pa_mqa_logits.py:224

  • This updates only the JIT Gluon source, but the AOT path still enters enable_gluon_pa_mqa_logits in aiter/ops/triton/attention/pa_mqa_logits.py, compiles this same Gluon function under the existing paged_mqa_logits...B{KVBlockSize}... cache key, and never routes non-preshuffle KVBlockSize > 1 to the block-aware Triton kernel. With AITER_ENABLE_AOT_GLUON_PA_MQA_LOGITS=1, an old cached artifact therefore remains unsafe despite this source change. Add the KVBlockSize > 1 and not Preshuffle selection before AOT loading (or otherwise version/invalidate the artifact).
    if KVBlockSize > 1:
        logical_kv_idx_next = (
            split_context_start
            - residual_context
            + gl.arange(0, ChunkK, layout=gl.SliceLayout(1, layout_kv))
  • Files reviewed: 2/2 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread op_tests/test_pa_mqa_logits_offset.py Resolved
Copilot AI review requested due to automatic review settings September 17, 2026 12:49
@zhiding512 zhiding512 changed the title [Triton/Gluon] [Bugfix] Fix block paging in non-preshuffle MQA logits [Triton/Gluon] [Bugfix] Fix non-preshuffle MQA paging and large KV offsets Sep 17, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Affected AOT inputs may still load unsafe cached kernels, and the intended AOT fallback tests are skipped.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (1)

op_tests/test_pa_mqa_logits_offset.py:265

  • This skip condition excludes every new regression case whenever AOT mode is enabled, because enable_jit_gluon_pa_mqa_logits_kernel is false in that mode. Consequently the promised AOT-fallback coverage (and protection against loading an unsafe cached Gluon binary) never runs; allow the cases on these architectures and let the wrapper select either the JIT Gluon or Triton fallback path.
    get_gfx() not in ("gfx942", "gfx950") or not enable_jit_gluon_pa_mqa_logits_kernel,
  • Files reviewed: 4/4 changed files
  • Comments generated: 1
  • Review effort level: Lite

The 2 GiB threshold gave one shape two ABIs: a 32-bit stride kernel for
small caches and a 64-bit one past the buffer descriptor range, told apart
only by a _kv64 suffix on the AOT directory. Compile the non-preshuffle
kernel with 64-bit KV and scale strides for every shape instead, so one
shape maps to one binary again and the dead 32-bit load paths go away.

Measured on gfx950 at N=131072, H=32, D=128, ChunkK=256, WavePerEU=2,
median of three processes per point, arms alternating within a round.
With KVBlockSize=64 the unconditional kernel costs +16.6% at batch 1
(5.728 -> 6.677 us), +4.1% at 16, +1.8% at 64, and -0.2% at 128, where
the cache already crossed 2 GiB and the kernel is unchanged, which puts
the noise floor of that setup near 0.2%. KVBlockSize=1 moves the other
way: 247.6 -> 95.3 us at batch 16 and 1053.0 -> 463.7 us at batch 64.

The preshuffle kernels keep 32-bit stride arguments; their addressing is
handled separately.

Signed-off-by: zhimding <[email protected]>
…kernel

Two defects in _gluon_deepgemm_fp8_paged_mqa_logits_preshuffle, both silent
until the KV cache is large or the context lengths are unaligned.

When ChunkKPerStage % KVBlockSize != 0, which is KVBlockSize=256 at
ChunkK=256, the K and scale addresses came from a 32-bit page-index product,
so a cache past 2 GiB wrapped into another page. Read them through a global
pointer with the index promoted to 64 bits, the way the per-lane branch
already does. Folding the page base into a buffer_load pointer also fixes the
addressing but costs a descriptor setup per stage, so it is not used here.

The per-lane branch stored its last stage across the whole tile, including
the columns past context_length that hold -inf. With an output width equal to
an unaligned context those columns land in the next row: context lengths
(3001, 513) lost the first 7 logits of row 1. Bound those three stores by
max_model_len, which the kernel's other stores already do.

Measured on gfx950 at N=131072, H=32, D=128, ChunkK=256, median of three
processes per point, arms alternating within a round:

  KVBlockSize=256, batch 128, 2.06 GiB cache: 508281/16777216 mismatched
      logits -> 0, and 449.150 -> 451.121 us (+0.44%)
  KVBlockSize=256, batch 64, 1.03 GiB cache: clean before and after, and
      250.599 -> 238.254 us (-4.93%)
  KVBlockSize=64, batch 128, 2.06 GiB cache: clean before and after, and
      464.583 -> 463.802 us (-0.17%)

The large-KV regression test now covers the preshuffle layout for
KVBlockSize=64 and 256 at the 2, 4 and 8 GiB boundaries. Its unaligned
context lengths and compact output width also cover the tail store.

Signed-off-by: zhimding <[email protected]>
Copilot AI review requested due to automatic review settings September 17, 2026 15:50

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical AOT lookup issues and unresolved specialization and test-coverage problems remain.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (5)

aiter/ops/triton/gluon/pa_mqa_logits.py:270

  • This unconditionally replaces the non-preshuffle buffer_load path with 64-bit gl.load addressing. There is no KV64 compile-time/host selection in this change, so ordinary caches below 2 GiB also take the slower global-load/i64 specialization, contradicting the claimed byte-identical small-cache path and adding overhead to the common case. Keep the existing buffer-load/i32 path for small extents and select the global/i64 path only for large caches.
    # The KV strides are 64-bit, so a cache past the 2 GiB buffer descriptor
    # range still addresses correctly. Global pointers, not buffer loads.
    k_next = gl.load(KV_buffer + kv_offsets)

op_tests/test_pa_mqa_logits_offset.py:282

  • [verified] This parameterization creates 4 layout/block-size pairs × 3 boundary values = 12 large-input cases, so with 48 paging cases and 2 existing offset cases it yields 62 tests, not the stated 6/56. The validation summary and expected CI count are therefore inaccurate. Author must update the validation counts or reduce the parameterization to the claimed cases.
@pytest.mark.parametrize("boundary_bits", [31, 32, 33], ids=["2GiB", "4GiB", "8GiB"])
@torch.inference_mode()
def test_paged_mqa_logits_large_kv_offsets(

op_tests/test_pa_mqa_logits_offset.py:267

  • [verified] This test excludes gfx1250, but the diff changes the IS_GFX1250 preshuffle path from buffer loads to flat gl.load at the corresponding kernel sites. The new tests therefore cannot catch an arch-specific compile or address regression in that path. Author must add a gfx1250-compatible preshuffle case or split the unsupported plain cases so the preshuffle path is exercised there.
@pytest.mark.skipif(
    get_gfx() not in ("gfx942", "gfx950") or not enable_jit_gluon_pa_mqa_logits_kernel,
    reason="Requires the CDNA Gluon JIT paged MQA kernel",

op_tests/test_pa_mqa_logits_offset.py:37

  • This new preshuffle helper import bypasses the arch-aware aiter.ops.triton.utils.shuffle.shuffle_weight, which is the shared shuffle entry point for Triton code. Use that helper here rather than importing the legacy base implementation directly, so the test does not encode a layout that becomes wrong if this coverage is enabled for gfx1250.
from aiter.ops.shuffle import shuffle_weight

op_tests/test_pa_mqa_logits_offset.py:144

  • The new Gluon kernel coverage is being added to a flat op_tests/ module, while the repository's attention tests are organized under op_tests/triton_tests/attention/ (for example test_fp8_mqa_logits.py). Please move this new coverage into that category directory rather than extending the root-level legacy regression file.
@pytest.mark.skipif(
    get_gfx() not in ("gfx942", "gfx950") or not enable_jit_gluon_pa_mqa_logits_kernel,
    reason="Requires the CDNA Gluon JIT paged MQA kernel",
)
@pytest.mark.parametrize("block_size", [1, 16, 64, 128])
@pytest.mark.parametrize("chunk_k", [64, 256])
@pytest.mark.parametrize("padded_table", [False, True], ids=["compact", "padded"])
  • Files reviewed: 4/4 changed files
  • Comments generated: 3
  • Review effort level: Lite

@k50112113

Copy link
Copy Markdown
Contributor

@zhiding512 please resolve conflicts

Keep the hoisted KV address math together with main's prefetch masks, and keep both the page-8 coverage and the gfx1250 block_size==1 gate.

Co-authored-by: Cursor <[email protected]>
Copilot AI lite review requested due to automatic review settings October 8, 2026 10:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Persistent scheduling lacks required correctness and benchmark coverage, the new kernel needs specialization metadata, and explicit SplitKV values require validation.

17 open findings

🧠 Review effort: Lite


Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.

@zhiding512
zhiding512 requested a review from k50112113 October 9, 2026 07:14
…tage

The non-persistent preshuffle kernel applies the causal mask only to the
last stage of each window and, on the large-page path, to the stage-0
stores. The window end is rounded up -- to a whole page when a stage holds
whole pages, to a whole chunk otherwise -- so when the padding nears a
stage, the first columns past an MTP row's causal end fall in the stage
before it, which the loop stores unmasked. Those columns get a finite logit
instead of -inf, and top-k can pick a future token. Page 64, ChunkK 128,
next_n 3 and context_length % 64 == 1 is one such case.

main has the same gap: its kernel fails at context 12801 with that config.
test_paged_mqa_logits_preshuffle only started catching it here because the
retuned grid runs TotalCuCount=1 as one split instead of ten, so the
257-token MTP row is one window rather than three one-chunk splits.

In the non-persistent path, rewrite those columns with -inf after the final
store. The rewrite uses the layout and offsets of the store that wrote them,
so the same lane performs both stores in program order. The persistent path
already masks every stage. The varctx kernel rounds its window the same way
and is not changed here.

Masking every loop stage instead also fixes it, but it reshuffled the
loop's s_waitcnt placement and cost up to 4.7% on MTP shapes. This keeps
the hot loop instruction-for-instruction identical. On gfx950, paired A/B
over page/ChunkK 64/128, 64/256 and 256/256, batch 16/128, next_n 1/3 and
context 32K/128K gives a median ratio of 0.9997; an A/A control stays
within 0.16%.

op_tests/test_pa_mqa_logits_offset.py: 125 passed. A random sweep over
page 8-256, ChunkK 128/256, next_n 1-4, SplitKV None/1/3/10 and contexts
near page and chunk boundaries passes 168/168; the previous kernel fails 7.

Co-authored-by: Cursor <[email protected]>
Copilot AI lite review requested due to automatic review settings October 9, 2026 07:48

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@k50112113
k50112113 self-requested a review October 12, 2026 15:03
k50112113
k50112113 previously approved these changes Oct 12, 2026

@cagrikymk cagrikymk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you address the comments?

Also, is this a replacement of varctx schedule? Or both have uses currently?

zhiding512 and others added 2 commits October 13, 2026 06:12
batch_size and slots were constexpr, so every new decode batch size built
another schedule binary. A batch 1-512 sweep on gfx950 compiled 512
variants, about 156 s on a cold cache and 0.3 s per new batch size. As
runtime arguments the same sweep compiles 16: one per power-of-two
BLOCK_B, plus Triton's default integer specialization.

The constexpr only turned the uniform branch's divisors into compile-time
constants, worth about 0.1-0.3 us per launch on a 2-11 us kernel that runs
once per decode step. The tables match the constexpr kernel bit for bit
over 1092 shape and context cases, including int64 context lengths and
explicit NumCTAs.

Co-authored-by: Cursor <[email protected]>
Replace the -(-a // b) ceil-divisions with triton.cdiv, and the hard-coded
2 workgroups per CU with WavePerEU, which is what it stood for:
waves_per_eu is passed to LLVM as both the minimum and the maximum, so one
residency wave is WavePerEU 4-warp workgroups per CU. The grid is unchanged
at the default WavePerEU=2; other values scale it again, as main's formula
did.

Co-authored-by: Cursor <[email protected]>
Copilot AI lite review requested due to automatic review settings October 13, 2026 06:13
@zhiding512

zhiding512 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

@cagrikymk Thanks for the review. The three inline comments are addressed in 46740ac and d66a223; details are in the threads.

Also, is this a replacement of varctx schedule? Or both have uses currently?

The persistent schedule was added for Kimi. I'm not sure whether other customers still use the varctx schedule, so I'd like to keep it for now.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Unresolved persistent-path correctness, coverage, API validation, kernel representation, and gfx1250 test compatibility issues remain.

1 open finding
16 resolved since last review
Previously missed (1)

In code that hasn't changed since last review

Medium severity Split or document the persistent scheduling API

aiter/​ops/​triton/​attention/​pa_mqa_logits.py:500

This diff introduces a separate public persistent-CTA scheduling API and a new persistent execution ABI, but the PR description only scopes the nonpersistent SplitKV grid retune, paging fixes, and plain-path instruction changes. That independent runtime surface increases review/AOT risk and is not part of the stated fix. Author must split the persistent scheduler into a follow-up PR or document its production contract and validate it separately.

🧠 Review effort: Lite

@azaidy azaidy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@azaidy
azaidy merged commit cb332f3 into main Oct 13, 2026
@azaidy
azaidy deleted the zhiding512/fix-paged-mqa-block-paging-20260917 branch October 13, 2026 15:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants