Skip to content

Cache the MLA split count, not the split indptr tensor - #5194

Merged
jamestangg merged 1 commit into
ROCm:mainfrom
peizhang56:ds_v4_flash_0731_vllm_2_rebase
Nov 3, 2026
Merged

jamestangg merged 1 commit into
ROCm:mainfrom
peizhang56:ds_v4_flash_0731_vllm_2_rebase

Conversation

@peizhang56

@peizhang56 peizhang56 commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

aiter/mla.py::get_meta_param is @functools.lru_cache'd and returns a CUDA tensor it allocates, num_kv_splits_indptr. The cache entry is that tensor's only owner, which makes it unsafe to capture into a CUDA/HIP graph: a capture that hits the cache records only a pointer with no producing kernel, so once the LRU evicts the entry the storage is recycled and replay reads garbage.

Eviction is routine on the decode path. total_kv is part of the cache key and changes almost every decode step, while entries captured into a graph are never looked up again (replay runs no host code), so captured entries are exactly what an LRU discards first.

This PR narrows the cache back to the scope it was introduced with, rather than removing an intended optimization. #322 added @lru_cache() when the function returned (num_kv_splits, mgc), two plain integers. #1233 added the torch.arange, at the call site and outside the cache. #1390 folded the arange into the cached function and simultaneously tightened the decorator to maxsize=1. #1445 then widened maxsize=1 back to the default 128, which is what makes eviction of a captured entry likely rather than rare.

Technical Details

Split the function in two:

  • _get_num_kv_splits() keeps @functools.lru_cache. The split-count heuristic is pure host-side arithmetic and is what the cache was originally added for.
  • get_meta_param() is now uncached and rebuilds the indptr with torch.arange on every call.

torch.arange on CUDA is a fill kernel, so built inside a captured region it is recorded into the graph and re-runs on every replay. The buffer is re-initialised regardless of what the caching allocator did with the storage in between, which makes this correct by construction rather than by allocator luck.

No measurable cost on the decode path, because the cache was not hitting there. Over 2000 decode steps at bs=480 with total_kv growing one token per sequence per step, the old cache took 0 hits and 2000 misses, i.e. it was already rebuilding the arange every step: 6.65 us/call before, 6.69 us/call after. The cache only pays on a repeating key, 0.15 us/call against 4.71 us/call, and a repeating key is exactly the graph-capture case, where the arange is recorded once and costs nothing at replay. The one case where the cache wins is the case where giving it up is free, and it is also the case that corrupts memory.

Alternatives considered and rejected: raising maxsize only delays eviction, since captured keys are never looked up again and any bound eventually discards them; holding a module-level reference leaks one tensor per distinct key, unbounded.

Rebuilding also drops a latent multi-device bug. The cached tensor was allocated on the then-current device with no device in the cache key, so a second device could be handed the first one's tensor.

No behavioural change to the returned values, and the added torch.arange is on the non-persistent path only.

Follow-up, deliberately not in this PR to keep it minimal: _get_num_kv_splits still takes total_kv in its key even when ignore_total_kv=1, where it provably cannot affect the result, so the surviving cache still thrashes at close to a 0% hit rate on that path.

Test Plan

Adds op_tests/test_mla_split_indptr_cudagraph.py. It warms the cache, captures a graph over a cache hit, churns the cache past its maxsize to force eviction, replays an unrelated graph in the same pool to reclaim the storage, then replays the first graph and compares the indptr against a freshly built one.

The test runs both as a plain script, which is how .github/scripts/aiter_test.sh invokes everything in op_tests/, and under pytest. Run against unpatched main and against this branch:

git checkout main -- aiter/mla.py    # keep the new test, drop the fix
python3 op_tests/test_mla_split_indptr_cudagraph.py   # exits 1
git checkout HEAD -- aiter/mla.py    # restore the fix
python3 op_tests/test_mla_split_indptr_cudagraph.py   # exits 0

Environment: MI355X (gfx950), single GPU, torch 2.10.0+rocm7.2.4, HIP 7.2.53211. A single GPU is sufficient; no model or checkpoint is needed.

The test does the bs=8 and bs=480 passes in one test function, in that order, releasing the small pass before the large one. Only bs=480 reproduces, and only once bs=8's churn and freed graph pool have left blocks of the right size class in the allocator. Splitting them into separate tests makes the failure depend on test ordering, which is why they are one test.

Test Result

Unpatched main, 3/3 runs, exit 1:

[PASS] split indptr survives graph replay (bs=8)
AssertionError: split indptr corrupted after replay (bs=480, splits=8):
  [3072, 3080, 3088, 3096, ...] != [0, 8, 16, 24, ...]

With the fix, 3/3 runs, exit 0:

[PASS] split indptr survives graph replay (bs=8)
[PASS] split indptr survives graph replay (bs=480)

black --check and ruff check clean on both changed files.

What led us here, offered as an open lead and not as a closed root cause: we hit a Memory access fault by GPU node-N ... Reason: Unknown on a TP8 graph-capturing MLA decode workload, and the faulting wavefront's address decoded to byte 0x7800000 = 480816*512, one element past the end of Mid_O at the same bs=480 / splits=8 / nhead=16 geometry this test uses. That is suggestive, not conclusive. The test demonstrates the indptr corruption, not the fault; the same fault signature still reproduces on a TP1 configuration with this fix applied; and we have not shown that a production run actually evicts a captured entry. This PR is offered on the correctness of the caching bug alone, independent of that crash.

Submission Checklist

@peizhang56
peizhang56 requested a review from a team September 2, 2026 00:44
@github-actions

github-actions Bot commented Sep 2, 2026

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 5194 --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.

@peizhang56

Copy link
Copy Markdown
Contributor Author

Trying to resolve #5193

@stefanskiasan

Copy link
Copy Markdown
Contributor

Confirmed on aiter 0.1.19 (prebuilt wheel, gfx950 / 8x MI355X, ROCm 7.2.3, torch 2.12.0): the regression test from this PR fails on the unpatched mla.py

AssertionError: split indptr corrupted after replay (bs=480, splits=8): [1024, 1032, 1040, ...] != [0, 8, 16, ...]

and passes after porting the change (cache only the split count in _get_num_kv_splits, build the arange per call) onto 0.1.19:

[PASS] split indptr survives graph replay (bs=8)
[PASS] split indptr survives graph replay (bs=480)

Why it matters for us: vLLM's ROCm sparse-MLA decode path (GLM-5.3 glm_moe_dsa, TP4, FULL cudagraphs, MTP k=3) calls mla_decode_fwd with num_kv_splits=None, so every decode step goes through this cache. +1 for merging; since vLLM's Dockerfile.rocm_base still pins 0.1.19, a backport to the release branch would help.

@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Oct 7, 2026
@zufayu
zufayu requested review from fangche123 and removed request for amd-ruitang3 October 15, 2026 08:45
@zufayu
zufayu requested a review from amd-ruitang3 October 15, 2026 08:45
@github-actions github-actions Bot removed the stale The PR hasn't been updated in 2 weeks label Oct 16, 2026
fangche123
fangche123 previously approved these changes Nov 3, 2026
get_meta_param() was wholly @functools.lru_cache'd, so it returned a cached
device tensor for num_kv_splits_indptr. A CUDA graph capturing a cache hit
records only a pointer and no producing kernel, so once the LRU drops that
entry (it was the tensor's only owner) the storage is recycled and replay
reads garbage. Eviction is routine: total_kv is in the key and changes almost
every decode step, while captured entries are never looked up again.

This restores the cache to its original scope rather than removing an
optimization. ROCm#322 added the decorator when the function returned two plain
integers; ROCm#1233 added the torch.arange at the call site, outside the cache;
ROCm#1390 folded it in and tightened the decorator to maxsize=1; ROCm#1445 widened
that back to 128.

Split the function. The split-count heuristic is pure and stays cached as
_get_num_kv_splits(); get_meta_param() is now uncached and rebuilds the indptr
with torch.arange, which is a fill kernel and so is recorded into the graph and
re-runs on replay. This also drops a latent multi-device bug: the cached tensor
was allocated on the then-current device with no device in the key.

Costs nothing on the decode path, where the old cache took 0 hits in 2000
steps and was already rebuilding the arange every step (6.65 -> 6.69 us/call).
It only paid on a repeating key, which is the graph-capture case, where the
arange is recorded once and is free at replay.

Verified locally with a throwaway capture/evict/replay harness (not added to
the tree, per review): on the old code bs=480 replays a corrupted indptr
(reads 3072, 3080, ... instead of 0, 8, 16, ...); with this fix bs=8 and
bs=480 both replay the correct values.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: pei.zhang <[email protected]>
@aiter-bot

Copy link
Copy Markdown

NOT READY FOR HUMAN REVIEW

PR Self-Review

Revision be470c2b1c3e · mode shadow

Waiting for the PR author. The readiness report will appear after the self-review answers are complete for this revision.

Questions to answer in the PR description

  1. What behavior does this PR change, and why is the existing behavior insufficient?
  2. What did you validate, and what remains unverified? Include commands, hardware/configuration and results.
  3. What is the most important boundary or failure mode introduced by this change, and what evidence covers it?
  4. For every changed op_tests/ file, what behavior does it cover and why is it not redundant? Write None if no op test changed.

Edit the PR Self-Review section in the PR description. Include the current revision SHA; this comment refreshes automatically.

Missing or invalid answers

  • FAIL — missing ### Reviewed revision in the PR description
  • FAIL — missing ### Behavior and intent in the PR description
  • FAIL — missing ### Validation and unverified scope in the PR description
  • FAIL — missing ### PR-specific question in the PR description
  • FAIL — missing ### Changed op tests in the PR description
  • FAIL — Reviewed revision must contain at least the first 7 characters of the current head SHA
  • FAIL — Behavior and intent has no substantive answer
  • FAIL — Validation and unverified scope has no substantive answer
  • FAIL — PR-specific question has no substantive answer

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

@jamestangg
jamestangg merged commit efdda17 into ROCm:main Nov 3, 2026
shantipriya-amd pushed a commit to shantipriya-amd/aiter that referenced this pull request Nov 18, 2026
…#5194)

get_meta_param() was wholly @functools.lru_cache'd, so it returned a cached
device tensor for num_kv_splits_indptr. A CUDA graph capturing a cache hit
records only a pointer and no producing kernel, so once the LRU drops that
entry (it was the tensor's only owner) the storage is recycled and replay
reads garbage. Eviction is routine: total_kv is in the key and changes almost
every decode step, while captured entries are never looked up again.

This restores the cache to its original scope rather than removing an
optimization. ROCm#322 added the decorator when the function returned two plain
integers; ROCm#1233 added the torch.arange at the call site, outside the cache;
ROCm#1390 folded it in and tightened the decorator to maxsize=1; ROCm#1445 widened
that back to 128.

Split the function. The split-count heuristic is pure and stays cached as
_get_num_kv_splits(); get_meta_param() is now uncached and rebuilds the indptr
with torch.arange, which is a fill kernel and so is recorded into the graph and
re-runs on replay. This also drops a latent multi-device bug: the cached tensor
was allocated on the then-current device with no device in the key.

Costs nothing on the decode path, where the old cache took 0 hits in 2000
steps and was already rebuilding the arange every step (6.65 -> 6.69 us/call).
It only paid on a repeating key, which is the graph-capture case, where the
arange is recorded once and is free at replay.

Verified locally with a throwaway capture/evict/replay harness (not added to
the tree, per review): on the old code bs=480 replays a corrupted indptr
(reads 3072, 3080, ... instead of 0, 8, 16, ...); with this fix bs=8 and
bs=480 both replay the correct values.

Signed-off-by: pei.zhang <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
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.

5 participants