Skip to content

[FlyDSL] Allocate split-K scratch buffers from a private MemPool - #5430

Merged
XiaobingSuper merged 5 commits into
ROCm:mainfrom
XiaobingSuper:fix/splitk-buffers-cuda-graph
Sep 21, 2026
Merged

XiaobingSuper merged 5 commits into
ROCm:mainfrom
XiaobingSuper:fix/splitk-buffers-cuda-graph

Conversation

@XiaobingSuper

@XiaobingSuper XiaobingSuper commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem

FlyDSL's split-K preshuffle GEMM reduces through a workspace guarded by an
atomic semaphore. Both are cached and reused across launches, keyed on
(device, stream) and allocated lazily on the first miss for that key:

@functools.lru_cache(maxsize=128)
def _get_preshuffle_split_buffers(device, stream):
    workspace = torch.empty(...)
    semaphore = torch.zeros(...)

A CUDA graph capture always runs on a freshly created stream, so that key is
always new and the first capturing GEMM always misses — allocating inside the
capture region, where memory is served from the graph's private mempool and can
land on the address of an intermediate the same capture already freed. Keying on
the stream is also why the cache cannot be pre-warmed: the capture stream does
not exist until the capture begins.

The failure surface is the semaphore, not the workspace. Three things have
to line up:

  1. the buffers are allocated inside a capture and inherit a freed
    intermediate's address;
  2. some graph sharing that pool is replayed and writes those bytes — the
    allocation alone is harmless, because during capture the producing kernel is
    only recorded, never run;
  3. the GEMM graph reading them is an lru hit. Only the graph that missed
    recorded torch.zeros' memset, so only that one re-zeroes the semaphore on
    every replay. Every later graph shares the buffer with no memset of its own.

splitk_reduce_epilogue counts relatively: each CTA does atomic_add(sem, +1),
the one that sees arrival == split_k - 1 reduces, and it restores with
atomic_add(sem, -split_k) rather than storing 0. A dirty slot therefore never
matches, the reduction never runs, and that tile's output keeps whatever it
held. The workspace being clobbered is harmless by comparison — every launch
rewrites the planes it is about to reduce.

Reproduction

Pure torch, no aiter, no model — the buffer is an lru cache keyed like aiter's:

@functools.lru_cache(maxsize=128)
def get_scratch(device, stream):
    return torch.zeros(N, device=device)

get_scratch(dev, torch.cuda.current_stream(dev))        # eager warmup: another key

with torch.cuda.graph(decoy, pool=pool, stream=side):
    t = src * 2.0; t_ptr = t.data_ptr(); t.sum(); del t  # freed; its kernel stays

with torch.cuda.graph(g1, pool=pool, stream=side):
    out1.copy_(src + get_scratch(dev, side))             # MISS: allocates, records memset
with torch.cuda.graph(g2, pool=pool, stream=side):
    out2.copy_(src + get_scratch(dev, side))             # HIT: same buffer, no memset

assert get_scratch(dev, side).data_ptr() == t_ptr
decoy.replay(); g1.replay()      # out1 = 3.0  -- g1's own memset reruns
decoy.replay(); g2.replay()      # out2 = 9.0  -- nothing cleans it
plain    cache 2 miss/1 hit  aliased=True   g1=3.0  g2=9.0  <- WRONG
MemPool  cache 2 miss/1 hit  aliased=False  g1=3.0  g2=3.0

9.0 = 3.0 + 6.0, the decoy's own intermediate. The same three-graph shape
driving the real kernel (M=1 N=2048 K=2048 split_k=4) gives 64/2048 wrong
outputs with max_err=778.5 — one dirty semaphore slot x tile_n=64 columns —
and 0/2048 with this branch.

Why it needs a specific snapshot to show up

Reaching the defect needs a capture on a stream the cache has never seen:

Condition Where it comes from
The FULL-graph capture runs on a stream no warmup ran on, so the cache always misses inside the capture vLLM's V2 model runner called torch.cuda.graph(graph, self.pool) with no stream=, which puts the capture on torch's process-wide singleton default_capture_stream — a different stream from the one graph_capture() runs warmup on. Fixed upstream by vllm-project/vllm#53818; older snapshots still have it. PIECEWISE capture was never affected: it captures on the current stream.
The split-K scratch is allocated lazily on that first miss this PR

vLLM captures every batch size into one shared graph_pool and replays them in
turn during decode, so conditions 2 and 3 above are met by construction once the
first one is.

Fix

Take the buffers from a per-device torch.cuda.MemPool, which is not part of
the graph private pool's reuse chain, so the address cannot be inherited from a
freed intermediate:

with persistent_alloc(device):
    workspace = torch.empty(...)
    semaphore = torch.zeros(...)

Cache keys, kernels, the split-K protocol, tuned configs and the steady-state
path are unchanged. The pool is entered only on a cache miss — once per
(device, stream) — so the hot path is bit-identical.

The same lazy-allocation pattern guards five sibling scratch caches, which take
the same helper: the a16w16 split-K semaphore/signal buffers (gfx950 and its
gfx1250 twin), the ASM a16w16 counter, the a8w8 zero-bias buffer, and topk's MoE
workspace. mla_reduce's _get_splitk_scratch is deliberately left alone — its
key carries no stream, so a first miss inside a capture needs a shape
combination no eager launch has used; its docstring now says so instead of
claiming to be capture-safe.

The a8w8 zero-bias buffer is the one with no protocol behind it: the kernel only
reads it, so nothing hands it back at zero and a clobbered one silently adds the
intermediate's values as bias on every replay. Unfixed, an lru-hit graph reads
6.0 there; fixed, 0.0.

Replaces the ASM a16w16 mechanism from #4916

That PR fixed this hazard on the ASM path by giving every recorded launch its
own ring slot and recording a zero_ per launch, so a replay starts from zero
whatever the counter held. Measured here, that node costs 2.2–2.4 us per
launch
— independent of the counter's size, so it is the node itself, not the
bytes — plus a fixed 16 MiB per device allocated whether or not the process ever
captures a graph. On a 10.9 us decode GEMM that is +20%.

Both kernels hand the counter back at zero on their own (verified: 0/1024 and
0/256 nonzero after six launches), so nothing has to re-zero it between
launches. What neither survives is another graph in the same pool owning the
counter's address — which is what this PR removes instead of tolerating.

check_graph dirtied the counter with fill_(2) from outside to stand in for
that state. The workspace belongs to the GEMM and nothing outside it writes
there, so the decoy graph it now uses produces the dirt the way a capture
actually does. #4916's own repro command passes:

$ python3 op_tests/test_gemm_a16w16.py --graph -mnk 64,256,5120 32,512,8192 -d bf16 -o fp32
graph dim: (64, 256, 5120)  replay vs eager: [checkAllclose atol=0.01 rtol=0.01 passed~]
graph dim: (32, 512, 8192)  replay vs eager: [checkAllclose atol=0.01 rtol=0.01 passed~]
all graph capture/replay checks passed

@JohnQinAMD — flagging this for your review since it reworks your fix.

torch floor. use_mem_pool can only win inside a capture on torch 2.10 or
newer: older allocators scan captures_underway in registration order, so the
graph pool registered at capture begin always wins, while 2.10 scans it in LIFO
order (c10/cuda/CUDACachingAllocator.cpp::get_pool). On an older torch the
helper warns once per device when it is entered during a capture, and the
capture test is skipped rather than failed. Thanks to @valarLip for measuring
what that looks like on 2.9.1.

Verification (gfx950, torch 2.10.0+rocm7.2.4)

Check Result
Three-graph repro driving the real GEMM unfixed: g2 64/2048 wrong, max_err=778.5. This branch: 0/2048.
Pure-torch repro above unfixed: g2=9.0. This branch: g2=3.0.
op_tests/test_graph_alloc.py 3 passed
Every cached accessor's segment_pool_id is the private pool's 6/6; dropping any one site's wrapper fails the test by name
#4916's repro command (test_gemm_a16w16.py --graph) passes
Cost of a recorded per-launch memset node 2.2–2.4 us, same for a 1 KiB and a 4 KiB counter
Pool is one per device under 16 concurrent first callers 1 pool
Pool routing when the buffer's device is not the current device without device=: 0 bytes routed. With device=: routed.
4 graphs sharing one pool, split-K a8w8 GEMM whose buffer first misses inside capture, 40 cross-replays rel_err 0.0013–0.0016, no NaN/inf, identical to the eager result

op_tests/test_graph_alloc.py is a plain pytest regression on allocator /
CUDA-graph pointer semantics -- there is no kernel, no shape sweep and nothing
to time, so it does not follow the op-test benchmark template.

🤖 Generated with Claude Code

@XiaobingSuper
XiaobingSuper requested review from a team and a lite review from Copilot September 11, 2026 01:55

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@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 5430 --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.

@github-actions github-actions Bot changed the title Fix split-K scratch buffers shared across CUDA graphs [FlyDSL] Fix split-K scratch buffers shared across CUDA graphs Sep 11, 2026
@XiaobingSuper
XiaobingSuper marked this pull request as draft September 11, 2026 02:13
@XiaobingSuper
XiaobingSuper force-pushed the fix/splitk-buffers-cuda-graph branch from 6a815af to 1cd2e68 Compare September 15, 2026 07:24
@XiaobingSuper XiaobingSuper changed the title [FlyDSL] Fix split-K scratch buffers shared across CUDA graphs [FlyDSL] Allocate split-K scratch buffers from a private MemPool Sep 15, 2026
@XiaobingSuper
XiaobingSuper force-pushed the fix/splitk-buffers-cuda-graph branch 2 times, most recently from b10afa6 to 13a16a8 Compare September 15, 2026 11:31
@XiaobingSuper
XiaobingSuper marked this pull request as ready for review September 15, 2026 11:52
Copilot AI review requested due to automatic review settings September 15, 2026 11:52

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@zufayu

zufayu commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Advisory review (static + hand-run; not a merge gate). Validation/Perf ran no GPU stage — reasons are on their lines below. Findings tagged [verified] are traced to code/repro.

Routes the three lazily-cached split-K scratch/semaphore buffer sets (preshuffle split-K, gfx950 a16w16 split-K, ASM a16w16 splitK) through a new per-device private torch.cuda.MemPool, so a buffer first allocated on a cache miss inside a CUDA graph capture can no longer inherit the address of an intermediate the same capture freed.

Review (advisory): 🔴 HIGH RISK
Validation (deterministic): NOT RUN — no validation report supplied and auto-validation disabled (REVIEW_AUTO_VALIDATE=0); the single test target op_tests/test_graph_alloc.py was run by hand in this review on gfx942/torch 2.9.1 (1 failed, 1 passed — see the first finding)
Perf (advisory): NOT RUN — the triaged target exposes no benchmark entry point (an allocator-semantics regression test with nothing to time); the changed path executes once per (device, stream) cache miss, so the steady-state hot path is untouched by construction

🔴 [verified] The fix silently no-ops on torch 2.9.x: during a capture the use_mem_pool routing loses to the capturing graph's private pool — torch 2.9.1's get_pool scans captures_underway forward so the graph-pool entry registered at capture-begin wins, while 2.10.0 scans in reverse so the persistent_alloc entry wins (read from the v2.9.1 and v2.10.0 tags of c10/cuda/CUDACachingAllocator.cpp). Verified on gfx942 + torch 2.9.1: this PR's own regression test fails (buffers aliased graph intermediates: [0, 1, 2, 3]), and a direct A/B shows a persistent_alloc allocation inside a capture still lands on the freed intermediate's address. torch 2.9.1 sits inside aiter's stated floor (setup.py: "upgrade torch to 2.9.1 or later") while CI pins torch 2.10.0, so a 2.9.x user keeps the original capture NaN bug with no error and a red test. Author must state and enforce the torch floor for this fix — skip/xfail test_graph_alloc.py below 2.10 or document the requirement — or switch to a mechanism that also works on 2.9.x.
⚠️ [verified] The lazy-cached-buffer-first-miss-inside-capture hazard this PR fixes is left live at four sibling sites: get_zero_bias_buf_keyed (aiter/ops/gemm_op_a8w8.py:395, keyed (device, stream, out_shape) — the bias=None default of the same a8w8 bpreshuffle family the PR body debugs), _get_topk_mb_workspace_keyed (aiter/ops/topk.py:335, MoE routing topk), _split_k_counters (aiter/ops/flydsl/gemm_a16w16_gfx1250.py:85 — the gfx1250 twin of the gfx950 site fixed in gemm_a16w16_gfx950.py), and _get_splitk_scratch (aiter/ops/flydsl/kernels/mla_reduce.py:1167, whose docstring claims "capture-safe" on the premise this PR corrects). Each can first-miss inside a capture, inherit a freed intermediate's address, and be overwritten on every replay — an aliased zero-bias buffer silently adds the intermediate's values as bias on every replay. Author must sweep these sites with the same persistent_alloc helper or state why each cannot first-miss inside a capture.
⚠️ [verified] persistent_alloc (aiter/utility/graph_alloc.py) computes the target device's index but calls torch.cuda.use_mem_pool(pool) without the device argument, so the thread-pool routing registers on torch.cuda.current_device() — when the GEMM's tensors sit on another GPU (buffers on cuda:1 while the current device is 0), the scratch allocation is not routed to the private pool at all and the fix silently no-ops inside a capture. Verified on the 8-GPU box: with current device 0 and target cuda:1 the allocation missed the private pool while the current==target control hit it. Author must pass device=index to use_mem_pool (the parameter exists) so the routing lands on the buffer's device.
📝 [inferred] torch.zeros first allocated inside a capture records its fill kernel as a graph node instead of executing it, so a semaphore from _get_preshuffle_split_buffers (gemm_kernels.py) or get_split_k_buffers (gemm_a16w16_gfx950.py) holds dirty pool memory from capture end until the first replay; an eager split-K launch on that same capture stream inside that window reads a garbage arrival counter. The mechanism follows from documented graph-capture semantics, the window is pre-existing (the fill node was captured before this PR too), and the reachability was not reproduced on this box. Reviewer should ask whether an eager launch on the capture stream between capture and first replay is reachable in the vLLM flows this PR targets.
📝 [verified] test_graph_alloc.py covers the helper's allocator semantics but never exercises the three call sites it was added for, so a future edit dropping a persistent_alloc wrapper — or scoping it wrong, as the cross-device case already is — still passes the suite; the end-to-end evidence (rel_err 0.0013–0.0016 over 40 cross-replays) is a manual gfx950/torch-2.10 run outside it. With the AI-generation footer and two structural checks fired (the gfx1250 twin left unadapted, the "not part of that reuse chain" docstring holding only on torch 2.10 or newer), this PR warrants thorough manual verification of the capture-path coverage. Reviewer should ask for an integration regression where a split-K GEMM's scratch first misses inside a capture.

Copilot AI review requested due to automatic review settings September 17, 2026 03:31

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@XiaobingSuper

Copy link
Copy Markdown
Contributor Author

Thanks — three of these changed the code (b39a8c5).

torch 2.9.x no-op. Confirmed from source: get_pool() scans captures_underway forward in v2.9.1 (line 2910) and in LIFO order in v2.10.0 (line 3011, with the comment spelling it out). Entries are always emplace_back-ed, so the graph pool registered at capture begin necessarily wins on 2.9.x and use_mem_pool is ignored inside a capture. Went with the version gate: ROUTES_INSIDE_CAPTURE, a one-shot warning when the helper is entered during a capture on an older torch, and a skipif on the capture test instead of a red test. Noted in the PR body.

Missing device=. Real, fixed. One correction to the repro path: torch.cuda.stream(s) switches the current device to the stream's device, so a harness that opens a stream context on the target device masks the bug — both arms pass. Probing the pool snapshot directly with no stream context shows it: current=0, target=cuda:1 → 0 bytes routed into the private pool; with device=index → routed.

Sibling sites. Took the two that share the failure mode most directly: _split_k_counters in gemm_a16w16_gfx1250.py (the twin of the gfx950 site already fixed here) and get_zero_bias_buf_keyed in gemm_op_a8w8.py. Leaving topk.py and mla_reduce.py for a follow-up — _get_splitk_scratch is keyed (num_slots, K, Dv, device_index) with no stream, so a first miss inside a capture needs a shape combination never seen eagerly, which is a different reachability argument than the stream-keyed sites.

On the memset window: not reachable in the vLLM flow this targets. The capture stream is torch's process-wide default_capture_stream; eager launches never run on it, and the buffers are keyed (device, stream), so no eager launch can hit the entry created during capture before the first replay.

Comment thread aiter/ops/gemm_op_a16w16.py Resolved
@zufayu

zufayu commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Re-review of the updated head (a84bd36, after the fixes in b39a8c5). Thanks for turning three of the earlier findings into code — re-checked on this box (gfx942, torch 2.9.1):

  • device= now threaded through use_mem_pool — verified: a cross-device alloc (current=cuda:0, buffer=cuda:1) now lands in segment_pool_id=(0,1), the private pool, vs (0,0) before. Fixed.
  • Two of the four sibling sites wrapped (gemm_op_a8w8.py, gemm_a16w16_gfx1250.py).

Advisory re-review (static + hand-run; not a merge gate). Findings tagged [verified] are traced to code/repro. The updated card:


Routes five lazily-cached split-K/semaphore/zero-bias scratch allocations (preshuffle split-K, gfx950 and gfx1250 a16w16 split-K, ASM a16w16, a8w8 zero-bias) through a new per-device private torch.cuda.MemPool so a buffer first allocated on a cache miss inside a CUDA graph capture can no longer inherit a freed intermediate's address, with a torch-version gate that warns and skips the regression test below torch 2.10.

Review (advisory): ⚠️ NEEDS WORK
Validation (deterministic): NOT RUN — no validation report supplied and auto-validation disabled (REVIEW_AUTO_VALIDATE=0); the single test target op_tests/test_graph_alloc.py was run by hand in this review on gfx942/torch 2.9.1 (1 skipped — the capture test, correctly gated below 2.10 — and 1 passed)
Perf (advisory): NOT RUN — the triaged target exposes no benchmark entry point (an allocator-semantics regression test with nothing to time); the changed path executes once per (device, stream) cache miss, so the steady-state hot path is untouched by construction

⚠️ [verified] The capture-aliasing hazard this PR fixes is still live at two sibling lazy-cache sites it does not touch: _get_topk_mb_workspace_keyed (aiter/ops/topk.py:335, lru-cached torch.zeros keyed (device, stream, size)) and _get_splitk_scratch (aiter/ops/flydsl/kernels/mla_reduce.py:1167, lru-cached torch.empty pair whose docstring claims "(capture-safe)"). Both can first-miss inside a capture under the PR body's own trigger table (full-graph capture on a stream no warmup ran on), inherit a freed intermediate's address, and be overwritten on every replay; the persistent_alloc wrapper this PR adds alongside aiter/ops/gemm_op_a8w8.py is absent at both. Impact: in the same vLLM capture scenario that motivated the PR, MoE top-k atomic counters or MLA split-K partials can read clobbered memory — wrong expert routing or attention output, silently. Author must wrap these two sites with the same helper or state why each cannot first-miss inside a capture.
⚠️ [verified] The PR carries only the FlyDSL label, so the opt-in downstream jobs (ci:atom/ci:sglang/ci:vllm, label-gated in .github/workflows/vllm_benchmark.yaml) all skip, yet the rerouted zero-bias path in aiter/ops/gemm_op_a8w8.py is the default fp8 GEMM path those frameworks consume and the defect this PR fixes only manifests under downstream CUDA-graph capture — aiter's own CI (torch 2.10.0 per ci-config.yaml, op_tests) cannot see a capture-path regression of the kind this change could introduce. Reviewer should ask for ci:all (or at minimum ci:vllm, the framework whose snapshot produced the bug) green before merge.
⚠️ [verified] No test exercises any of the five call sites: op_tests/test_graph_alloc.py tests the helper only, its capture-replay test skips below torch 2.10 (verified on 2.9.1: 1 skipped, 1 passed), and the one test that runs on the floor torch asserts functools.cache identity and cannot fail while the decorator exists. The end-to-end evidence (4-graph split-K replay, rel_err 0.0013–0.0016) is a manual gfx950/torch-2.10 run outside the suite, and the a16w16 sites (aiter/ops/gemm_op_a16w16.py, gfx950, gfx1250) have no e2e validation at all, so a future edit dropping or mis-scoping a persistent_alloc wrapper still passes. With the AI-generation footer and the pool-ownership comment not matching observed behavior, this PR warrants thorough manual verification of the capture-path coverage. Reviewer should ask for an integration regression where a split-K GEMM's scratch first misses inside a capture, or a per-site check that the cached buffer's memory_snapshot segment_pool_id equals the private pool's id (runs on any arch, outside a capture).
📝 [verified] On torch 2.9.x — inside aiter's stated floor (setup.py: "upgrade torch to 2.9.1 or later") — the capture-aliasing defect itself remains: verified on gfx942/torch 2.9.1 that a persistent_alloc (aiter/utility/graph_alloc.py) allocation inside a capture still lands on the freed intermediate's address. The PR converts the silent no-op into a once-per-process warning (verified the warning fires) plus a skipped test and documents the floor in the body, which is what the prior review asked for. Reviewer should confirm the warning-only mitigation is acceptable for 2.9.x users, or enforce the 2.10 floor for capture use.
📝 [verified] _persistent_pool (aiter/utility/graph_alloc.py) relies on functools.cache to own the pool, but functools.cache permits duplicate concurrent first-miss execution — verified: 8 concurrent callers received 8 distinct MemPool objects — so two threads first-missing the same device can allocate the call-site-cached buffer from a pool object that is not the cached one and is then garbage-collected. On torch 2.9.1 the allocated block survives pool GC (verified: segment and tensor stayed valid after cache_clear plus gc), so no dangling was reproduced; the module's own comment, however, asserts destroying a MemPool frees its memory and dangles pointers. Author must guard pool creation with a lock or correct the comment to the observed semantics.


Biggest remaining blast radius is the two sibling sites still bare, not the torch-2.9.x path. The 2.9.x defect is now behind a once-per-process warning + skipped test + a documented floor (mitigated, though the underlying aliasing is unchanged there — re-confirmed aliased [0,1,2,3] on 2.9.1). But topk.py (_get_topk_mb_workspace_keyed) and mla_reduce.py (_get_splitk_scratch) are the same capture-time-first-alloc class on hotter paths — MoE routing and MLA split-K reduce, which serving stacks capture on the decode hot path; _get_splitk_scratch's own docstring even says "capture-safe". Fixing the GEMM path while leaving those two is an incomplete fix-then-sweep. Author: please wrap topk.py / mla_reduce.py in persistent_alloc too, or say why those two are exempt.

@valarLip

Copy link
Copy Markdown
Collaborator

Reproduced the defect and then tested this branch against it on 8x MI355X (gfx950), torch 2.9.1+rocm7.1.1 — i.e. below the 2.10 floor documented in the description. Posting the numbers since the PR states the limitation but doesn't show what it looks like in practice.

The harness is your minimal demonstration wired into an lru-cached scratch, with three arms sharing one graph pool: a decoy graph whose intermediate is freed during capture, then g1 (cache miss, allocates inside the capture) and g2 (cache hit, no memset of its own). Each arm replays decoy, g1, decoy, g2 and reads out2; 3.0 is correct, 9.0 means the scratch was clobbered by the decoy's kernel.

torch 2.9.1+rocm7.1.1.git351ff442
ROUTES_INSIDE_CAPTURE = False
[aiter] torch 2.9.1+rocm7.1.1.git351ff442 cannot route an allocation out of a
        CUDA graph capture; scratch buffers first allocated during capture may be
        overwritten on replay. Upgrade to torch 2.10 or later.

  plain             aliased=True  g1=3.0 g2=9.0  <- WRONG
  raw MemPool       aliased=True  g1=3.0 g2=9.0  <- WRONG
  persistent_alloc  aliased=True  g1=3.0 g2=9.0  <- WRONG

aliased=True is the scratch's data_ptr() matching the decoy's freed intermediate exactly, so use_mem_pool is not merely losing a race — the allocation lands on the same address with or without it. Repeated 3x with and without an eager warmup on a different stream; identical every time.

So on this torch the branch is inert: the warn-once fires, and the buffer is still served from the graph private pool. That matches what the description says rather than contradicting it — the point is just that below 2.10 the failure mode goes from silent to logged, not from broken to fixed, and the op_tests/test_graph_alloc.py capture case skips rather than covering it.

Two small things that follow from that, take or leave:

  • The floor check relies on torch.__version__ being a TorchVersion (which overloads comparison). A plain str comparison of "2.9.1+rocm7.1.1" >= "2.10" returns True, so if that value ever reaches ROUTES_INSIDE_CAPTURE as a bare str the gate silently inverts on exactly the versions it is meant to catch. A packaging.version.Version comparison would be immune.
  • The warning is functools.cached with no arguments, so it fires once per process across all devices and call sites. On a box where only one of several cached buffers first misses inside a capture, the one line doesn't identify which.

Happy to rerun any of this if it would help, or to test on a 2.10 build if you can point me at one.

Copilot AI review requested due to automatic review settings September 20, 2026 02:53

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@XiaobingSuper

Copy link
Copy Markdown
Contributor Author

Thanks both — all of this changed the code (5a351da).

@valarLip: the string-comparison trap is real and worse than a str slipping through. As plain strings every 2.x sorts above "2.10" ('9' > '1' decides it at the third character), so "2.8.0" >= "2.10" is True too — the gate would be inverted for every version it exists to catch, not just some. Now Version(torch.__version__.split("+")[0]) >= Version("2.10"); packaging is already an aiter runtime dependency. The warning is keyed on the device index and names it. Thanks for running it on 2.9.1 and posting the numbers — aliased=True even with use_mem_pool is the sharpest statement of what the floor means, and it is now in the description.

@zufayu: functools.cache confirmed — 16 concurrent callers, 16 pools. The comment was also wrong in the other direction: I measured that a block allocated from a pool stays valid after the pool object is dropped and gc'd (tensor readable, data_ptr unchanged, address not reissued), so the failure mode is duplicate segment sets, not dangling pointers. Pool creation is now a double-checked lock and the comment says what was measured.

topk.py wrapped — it is keyed (device, stream, size), the same shape as the sites already covered, so there was no exemption argument to make. mla_reduce.py deliberately not: its key is (num_slots, K, Dv, device_index) with no stream, so a first miss inside a capture needs a shape combination no eager launch has used. Its "(capture-safe)" docstring was asserting more than that, and now states the reachability argument instead.

Took your segment_pool_id suggestion as the per-site test — it needs no capture and no particular arch, so it runs on the floor torch where the capture test skips. It walks all six accessors and fails by name; dropping topk's wrapper as a negative control gives topk_mb_workspace[0]: (0, 0) against the expected (0, 1). Added ci:vllm.

Separately: the mechanism in the description was wrong and has been rewritten. The reduction does not read unwritten workspace slots — it never runs. Only the graph that missed the cache records torch.zeros' memset, so it re-zeroes the semaphore on every replay and heals itself; every later graph is an lru hit sharing the buffer with no memset, and since the epilogue restores with atomic_add(sem, -split_k) rather than storing 0, a dirty slot never matches split_k - 1. The clobbered workspace is harmless — every launch rewrites the planes it reduces. A pure-torch repro and the same three-graph shape driving the real kernel (64/2048 wrong, max_err=778.5, one dirty slot x tile_n=64) are both in the description.

Copilot AI review requested due to automatic review settings September 20, 2026 02:58
@XiaobingSuper
XiaobingSuper force-pushed the fix/splitk-buffers-cuda-graph branch from 5a351da to 6df66dc Compare September 20, 2026 02:58

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI review requested due to automatic review settings September 20, 2026 12:45

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@XiaobingSuper

Copy link
Copy Markdown
Contributor Author

@JohnQinAMD — this reworks the ASM a16w16 counter you fixed in #4916, so flagging it for your review.

The question I want your read on is whether the counter's workspace is GEMM-private. If it is, nothing outside the GEMM writes there, and the only way it goes into a capture dirty is by inheriting an address some other graph in the pool owns. This PR removes that inheritance (a per-device torch.cuda.MemPool outside the graph pool's reuse chain), and the kernel already hands the counter back at zero — 0/1024 nonzero after six eager launches — so nothing has to re-zero it per launch. That drops the recorded zero_, which measures 2.2–2.4 us per launch here (same for a 1 KiB and a 4 KiB counter, so it is the node, not the bytes), and the 16 MiB per device.

Your repro passes on this branch:

$ python3 op_tests/test_gemm_a16w16.py --graph -mnk 64,256,5120 32,512,8192 -d bf16 -o fp32
all graph capture/replay checks passed

but only after one change I would rather you agree with than not: check_graph dirtied the counter with get_semaphore_workspace(...).fill_(2) before capturing, and with that line kept this branch deadlocks — removing the aliasing stops accidental writes, not deliberate ones from outside. I replaced it with a decoy graph that frees a transient into the same pool, which is how a capture actually produces that state, plus assertions that the counter neither inherits the transient's address nor changes when the decoy replays. It still fails on an unfixed build.

So: is there a writer outside the GEMM I should be accounting for? Concretely — the counter you caught holding 2 under rocgdb, was that an intermediate's bytes landing on it? If yes, both PRs were chasing the same root cause. If it came from somewhere else, that writer is one I have not reproduced, the per-launch re-zero is load-bearing, and I will drop this part and keep the PR to the flydsl/a8w8/topk sites. You have the production trace; I do not.

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@JohnQin-llm

Copy link
Copy Markdown
Contributor

LGTM

JohnQin-llm
JohnQin-llm previously approved these changes Sep 21, 2026
XiaobingSuper and others added 5 commits September 21, 2026 00:41
The split-K semaphore and workspace are cached per (device, stream) and
allocated lazily on the first miss. When that first miss happens inside a CUDA
graph capture, the allocation is served from the graph's private mempool, where
it can inherit the address of an intermediate tensor the same capture already
freed. The kernel producing that intermediate is a node in the graph, so every
replay overwrites the semaphore and the reduction reads workspace slots the
launch never wrote.

Take the buffers from a per-device torch.cuda.MemPool instead, which is not
part of that reuse chain. Cache keys, kernels, the split-K protocol and the
steady-state path are unchanged; the pool is entered only on a cache miss.

Co-Authored-By: Claude Opus 5 <[email protected]>
use_mem_pool() was called without device=, so the routing registered on
torch.cuda.current_device(). When the buffers live on another GPU the
allocation bypassed the private pool entirely and the fix silently did
nothing inside a capture.

torch < 2.10 scans captures_underway in registration order, so the graph
pool registered at capture begin always wins and use_mem_pool cannot route
out of a capture at all; 2.10 scans it in LIFO order. Expose the version
gate, warn once when a capture is hit on an older torch, and skip the
capture test there instead of failing it.

The same lazy-allocation hazard applies to the gfx1250 twin of the a16w16
split-K counters and to the a8w8 zero-bias buffer, so both take the helper.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The version gate compared torch.__version__ against "2.10" and only worked
because TorchVersion overloads the comparison: as plain strings every 2.x
release sorts above "2.10", so the gate inverts on exactly the versions it
exists to catch. Parse both sides instead.

functools.cache does not stop concurrent first callers from each building a
MemPool -- sixteen threads got sixteen pools -- so the comment claiming the
cache owns the pool was wrong. Blocks stay valid after their pool object is
dropped, but a second pool still hands out a second set of segments, so
creation is serialized and the comment now says what was measured.

topk's workspace is keyed (device, stream, size), the same shape as the
scratch caches already covered, so it takes the helper too. mla_reduce's
key carries no stream; its "capture-safe" docstring now says why that is a
different reachability argument rather than asserting safety.

The new test asks every one of the six cached accessors whether its buffer's
segment_pool_id is the private pool's. It needs no capture and no particular
arch, so it runs on the torch floor where the capture test is skipped, and it
fails if any site loses its wrapper.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
ROCm#4916 fixed the same capture hazard on this path by handing every recorded
launch its own ring slot and recording a zero_ per launch, so a replay starts
from zero whatever the counter held. That tolerates a dirty counter rather
than preventing one, and the recorded node costs 2.2-2.4 us per launch --
measured, and independent of the counter's size -- plus 16 MiB per device
allocated whether or not the process ever captures a graph.

The kernel already hands the counter back at zero, so nothing has to re-zero
it between launches; what it cannot survive is another graph in the same pool
owning its address. Route the allocation through persistent_alloc like the
other scratch caches and the address is never one a graph writes.

check_graph dirtied the counter from outside to stand in for that state. The
workspace belongs to the GEMM, so nothing outside it writes there; the decoy
graph this uses instead produces the dirt the way a capture actually does, and
still fails on an unfixed build.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Below torch 2.10 use_mem_pool is ignored inside a CUDA graph capture, so
the buffer still comes from the graph's private pool and can inherit the
address of an intermediate that every replay overwrites. A warning there
is easy to miss until the result is already wrong, so fail at the
allocation instead.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings September 21, 2026 05:42
@XiaobingSuper
XiaobingSuper force-pushed the fix/splitk-buffers-cuda-graph branch from b50400a to cf9bb17 Compare September 21, 2026 05:42

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

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