Skip to content

fix(pa): support block_id > 65535 in ASM paged-attention kernels (#3062) - #3211

Merged
valarLip merged 15 commits into
mainfrom
chefang_pa_block
Jun 14, 2026
Merged

valarLip merged 15 commits into
mainfrom
chefang_pa_block

Conversation

@fangche123

@fangche123 fangche123 commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Use min-based anchor rebase in K_V_window_rebase to allow pages within the same wave to span different 65536 windows, as long as max_page_id - min_page_id < 65536. This removes the previous constraint that all pages in a load group must share the same high-16-bit window.

Changes:

  • Replace v_mul_u32_u24 with v_mul_lo_u32 to remove 24-bit truncation
  • Update K/V buffer descriptor num_records for full offset range
  • Update all 36 PA kernel .co binaries (gfx942 + gfx950)
  • Add test_pa_block_id_truncation.py regression test

Motivation

Technical Details

Test Plan

Test Result

test_pa.py
image
test_pa_mtp.py
image

MI355X (gfx950), bf16, 8 KV heads, head_dim=128, block_size=16, ctx_len=256
HSA_NO_SCRATCH_RECLAIM=1 python op_tests/test_pa_block_id_truncation.py
image

Submission Checklist

Use min-based anchor rebase in K_V_window_rebase to allow pages within
the same wave to span different 65536 windows, as long as
max_page_id - min_page_id < 65536. This removes the previous constraint
that all pages in a load group must share the same high-16-bit window.

Changes:
- Replace v_mul_u32_u24 with v_mul_lo_u32 to remove 24-bit truncation
- Update K/V buffer descriptor num_records for full offset range
- Update all 36 PA kernel .co binaries (gfx942 + gfx950)
- Add test_pa_block_id_truncation.py regression test
@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:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
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 3211 --add-label <label>

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.

Pull request overview

Fixes an ASM paged-attention bug where block_ids ≥ 65,536 were silently narrowed to 16 bits because of a v_mul_u32_u24 truncation and an undersized K/V buffer descriptor num_records. The kernel's K_V_window_rebase now uses min-based anchor rebase to allow pages within a wave to span different 64K windows. The host-side KernelArgs ABI is extended with an mtp field and all 36 precompiled .co kernels (gfx942 + gfx950) are regenerated to match.

Changes:

  • Insert a new unsigned int mtp slot (with padding) into the KernelArgs struct and zero-initialize the struct; populate args.mtp = max_qlen - 1.
  • Add a Python regression test (test_pa_block_id_truncation.py) that exercises both decode and MTP kernels across block_ids that straddle the 65,535 boundary.
  • (Out of diff: assembly source replacements and binary .co rebuilds, per PR description.)

Reviewed changes

Copilot reviewed 2 out of 74 changed files in this pull request and generated 6 comments.

File Description
csrc/py_itfs_cu/asm_pa.cu Extends KernelArgs ABI with mtp field, zero-inits the args struct, and passes max_qlen-1 to the kernel.
op_tests/test_pa_block_id_truncation.py New regression test for the >65,535 block_id truncation, parameterized across decode and MTP kernel families.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread op_tests/test_pa_block_id_truncation.py Outdated
Comment on lines +228 to +260
# # Cross-window test: pages within the same wave have block_ids
# # spanning different 65536 windows.
# CROSS_SIG = 0.25
# cross_cases = [
# ([0, 120, 65536, 65700], "mixed_low_high"),
# ([65534, 65535, 65536, 65537], "boundary_span"),
# ([100, 200, 65536, 67000], "wide_span"),
# ([65536, 65536, 65536, 65536], "all_high_same"),
# ]
# print("=== cross_window_in_wave (block_ids in different 65536 windows) ===")
# for blocks, label in cross_cases:
# for bid in blocks:
# k_cache[bid].fill_(CROSS_SIG)
# v_cache[bid].fill_(CROSS_SIG)
# bt = (blocks * 4)[:16] # repeat to fill 16 entries
# block_tables = torch.tensor([bt], dtype=torch.int32, device="cuda")
# context_lens = torch.full(
# (1,), BLOCK_SIZE * 16, dtype=torch.int32, device="cuda"
# )
# cu_seqlens_q = torch.tensor([0, 1], dtype=torch.int32, device="cuda")
# query = torch.ones(
# 1, NUM_Q_HEADS, HEAD_DIM, dtype=torch.bfloat16, device="cuda"
# )
# out = aiter.pa_fwd_asm(
# query, k_cache, v_cache, block_tables, context_lens,
# block_tables.stride(0), max_qlen=1,
# K_QScale=None, V_QScale=None, out_=None,
# qo_indptr=cu_seqlens_q, high_precision=0,
# )
# actual = out.float().mean().item()
# ok = "OK" if abs(actual - CROSS_SIG) < 0.01 else "FAIL"
# print(f" [{ok}] {label:20s} blocks={blocks} actual={actual:.4f} (expect {CROSS_SIG:.4f})")
# print() No newline at end of file
Comment thread op_tests/test_pa_block_id_truncation.py Outdated
import torch

import aiter
from aiter import dtypes
Comment on lines +39 to +43
Run:
pytest /root/aiter/op_tests/test_pa_block_id_truncation.py -v -s

Or as a script:
python /root/aiter/op_tests/test_pa_block_id_truncation.py
Comment thread op_tests/test_pa_block_id_truncation.py Outdated
Comment on lines +177 to +184
def test_pa_fwd_asm_block_id_no_truncation(
block_id, expected_sig, label, max_qlen, kernel_label
):
"""Output for a single-block sequence must match that block's fingerprint
regardless of whether block_id is below or above 65,535. Run for both
qlen=1 (non-MTP decode kernel) and qlen=4 (MTP kernel)."""
k_cache, v_cache = _build_kv_cache()
actual = _run_pa_fwd_asm(k_cache, v_cache, block_id, max_qlen=max_qlen)
Comment on lines +111 to +115
# V layout: [num_blocks, num_kv_heads, head_dim, block_size]
v_cache = torch.zeros(
NUM_BLOCKS, NUM_KV_HEADS, HEAD_DIM, BLOCK_SIZE,
dtype=dtype, device="cuda",
)
Comment thread csrc/py_itfs_cu/asm_pa.cu
Comment on lines +40 to +45
unsigned int mtp;
p3 _p18;
unsigned int GQA;
p3 _p19;
void* ptr_QTP;
p2 _p19;
p2 _p20;
fangche123 and others added 14 commits May 15, 2026 04:55
Rebuild all 36 PA kernel .co files from updated SP3 sources that use
min-based anchor rebase instead of the previous direct offset approach.

Performance (test_pa.py, bf16, batch=128):
- ctx_len=128:  12.17-12.22 us (vs 12.51-12.58 in v1, vs 11.73-11.78 baseline)
- ctx_len=257:  18.10-18.17 us (vs 18.52-18.82 in v1)
- ctx_len=4097: 161.16-162.33 us (vs 160.27-160.49 baseline, <1% delta)

Short-context regression reduced from ~7-9% to ~3-5% vs baseline.
Long-context effectively neutral (<1%).
- Reformat multiline function args per black style
- Remove unused imports (dtypes, time)
- Remove extra blank line
- Add trailing newline
@valarLip
valarLip merged commit b847e4d into main Jun 14, 2026
66 of 68 checks passed
@valarLip
valarLip deleted the chefang_pa_block branch June 14, 2026 13:06
Boss2002n added a commit that referenced this pull request Sep 15, 2026
Six tracked files that nothing reads and nothing will read again, plus the
workflow fix that stops two of them returning.

CI scratch the bot committed. update-split-tests.yaml wrote
split-tests-update-summary.md and then pr-body.md into the workspace and
handed them to peter-evans/create-pull-request, which commits every new and
modified file when add-paths is unset. Both reached the repo root that way in
#5131, and the tracked copies were stale the moment they landed because the
workflow regenerates them on every run. The job only ever means to change one
file, so add-paths now names .github/scripts/split_tests.sh, and both scratch
files move to the runner temp directory so they are never dirty workspace
files in the first place. The .gitignore entries remain as a backstop for
local runs, where --summary-path still defaults to the working directory.

Merge and POC leftovers that ship in the wheel.
hsa/gfx950/pa/pa_bf16_noquant_gqa8_1tg_4w.co.orig and .co.poc_kl_merg
arrived with #3211 next to the real .co. Nothing references either by name,
and the ASM loaders build .co paths explicitly rather than globbing the
directory, so neither is reachable. They are not merely inert: setup.py
copies all of hsa/ into aiter_meta and MANIFEST.in grafts it, so 48 KB of
scratch binaries go out in every wheel. *.orig is now ignored so the next
conflicted merge does not leave another one behind.

One-off files their PRs forgot. probe_noqa_check.py is a single line, x = 1,
added in #4403 to confirm the pinned ruff config flagged it.
REPO_CLEANUP_PLAN.md is a pull request description from #2167 in March. Its
Phase 1 shipped -- the .pt test data is gone from main and the size rules are
in .gitignore -- and its Phase 2 history rewrite needs a coordinated force
push that has not happened in the six months since. Neither file is
referenced anywhere in the tree.

Left alone: scripts/download_test_data.sh, a no-op stub from that same plan,
because docs/tutorials/index.rst still points readers at it. Retiring the
script and the doc together is a separate change.
Boss2002n added a commit that referenced this pull request Oct 2, 2026
Six tracked files that nothing reads and nothing will read again, plus the
workflow fix that stops two of them returning.

CI scratch the bot committed. update-split-tests.yaml wrote
split-tests-update-summary.md and then pr-body.md into the workspace and
handed them to peter-evans/create-pull-request, which commits every new and
modified file when add-paths is unset. Both reached the repo root that way in
#5131, and the tracked copies were stale the moment they landed because the
workflow regenerates them on every run. The job only ever means to change one
file, so add-paths now names .github/scripts/split_tests.sh, and both scratch
files move to the runner temp directory so they are never dirty workspace
files in the first place. The .gitignore entries remain as a backstop for
local runs, where --summary-path still defaults to the working directory.

Merge and POC leftovers that ship in the wheel.
hsa/gfx950/pa/pa_bf16_noquant_gqa8_1tg_4w.co.orig and .co.poc_kl_merg
arrived with #3211 next to the real .co. Nothing references either by name,
and the ASM loaders build .co paths explicitly rather than globbing the
directory, so neither is reachable. They are not merely inert: setup.py
copies all of hsa/ into aiter_meta and MANIFEST.in grafts it, so 48 KB of
scratch binaries go out in every wheel. *.orig is now ignored so the next
conflicted merge does not leave another one behind.

One-off files their PRs forgot. probe_noqa_check.py is a single line, x = 1,
added in #4403 to confirm the pinned ruff config flagged it.
REPO_CLEANUP_PLAN.md is a pull request description from #2167 in March. Its
Phase 1 shipped -- the .pt test data is gone from main and the size rules are
in .gitignore -- and its Phase 2 history rewrite needs a coordinated force
push that has not happened in the six months since. Neither file is
referenced anywhere in the tree.

Left alone: scripts/download_test_data.sh, a no-op stub from that same plan,
because docs/tutorials/index.rst still points readers at it. Retiring the
script and the doc together is a separate change.
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.

4 participants