Repository navigation
[HIP] [FlyDSL] dcp topk merge - #5123
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
PR title tags: |
There was a problem hiding this comment.
Pull request overview
This PR introduces a new FlyDSL-based DCP decode “top-k merge” operation (global threshold select + per-rank owned-slot emission) and aligns the existing per-row top-k decode path to be safe for downstream consumers that rank scores (by padding scores with -inf and optionally returning selected values).
Changes:
- Add FlyDSL DCP top-k merge kernel + Python interface and a comprehensive correctness/determinism test suite.
- Extend
top_k_per_row_decode(C++ + pybind + Python wrapper) with an optionalvaluesoutput buffer and fix padded score semantics (-infinstead of0). - Add a gfx950-specific guard in
fp8_mqa_logitsto avoid an LLVM backend abort by relaxingwaves_per_euunder a constrained condition.
Reviewed changes
Copilot reviewed 8 out of 8 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| op_tests/flydsl_tests/test_flydsl_dcp_topk_merge.py | New test coverage for FlyDSL DCP merge correctness, determinism, and edge cases. |
| csrc/kernels/topk_per_row_kernels.cu | Fix score padding to -inf and add optional decode values output. |
| csrc/include/topk_per_row.h | Update decode API to accept optional values. |
| csrc/include/rocm_ops.hpp | Expose the new values argument through pybind. |
| aiter/ops/triton/attention/fp8_mqa_logits.py | Add gfx950-specific waves_per_eu escape hatch for a compiler/backend abort scenario. |
| aiter/ops/topk.py | Thread optional values through the Python wrapper and add FlyDSL DCP merge entrypoint. |
| aiter/ops/flydsl/kernels/dcp_topk_merge.py | New FlyDSL kernel module implementing threshold select + owned-slot emit + scan/pack. |
| aiter/ops/flydsl/dcp_topk_merge.py | New Python interface + validation and debug hooks for FlyDSL DCP merge. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
ed4b31a to
674304d
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.
Suppressed comments (3)
aiter/ops/flydsl/dcp_topk_merge.py:134
- Docstring is out of sync with the implementation: when
debug_thresholdis omitted, the launcher is built withwrite_threshold=False, soselect_kernelnever writes a threshold anywhere (it doesn’t “scribble into owned_counts”). This can mislead callers trying to debug correctness.
that receives the selected ord threshold per row. The op never allocates
device memory itself (that would put an allocation inside a captured
CUDAGraph decode region); when it is omitted the kernel scribbles the
threshold into `owned_counts[row]`, which the same thread of the same block
overwrites with the real count before the kernel ends.
aiter/ops/topk.py:473
valuesis documented as a float32 tensor with the same shape asindices, but this isn’t enforced. The C++ binding unconditionally castsvalues.data_ptr()tofloat*, so passing a wrong dtype/shape/stride can cause memory corruption. Add lightweight Python-side validation before calling into the extension.
When `values` is given (float32, same shape as `indices`), each selected
index's logit is written alongside it. Rows shorter than k pad the index
with -1 and the score with -inf, so the padding sorts below every real
candidate and a consumer that ranks these scores needs no extra mask."""
aiter/ops/topk.py:493
valuesis forwarded to the C++ binding without validation. Since the binding treats it as a rawfloat*, incorrect dtype/shape/contiguity can lead to memory corruption. Please validatevalues(float32, contiguous, same shape/device asindices) before calling_top_k_per_row_decode.
k,
workspace,
stable,
values,
)
674304d to
0695f16
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 8 out of 8 changed files in this pull request and generated no new comments.
Suppressed comments (2)
aiter/ops/topk.py:493
valuesis forwarded to the C++ kernel and then unconditionally cast tofloat*when present. Add Python-side validation (dtype/shape/device) so a mis-typed or mis-shapedvaluestensor fails fast with a clear error instead of producing incorrect results or a crash in the kernel.
When `values` is given (float32, same shape as `indices`), each selected
index's logit is written alongside it. Rows shorter than k pad the index
with -1 and the score with -inf, so the padding sorts below every real
candidate and a consumer that ranks these scores needs no extra mask."""
# Decode always takes the ob path (see topk_per_row_kernels.cu).
# The original mb dispatch is commented out below for reference:
# if topk_use_mulblocks(numRows, stride0):
# size = topk_mb_workspace_size(numRows, stride0, k, True)
# workspace = get_topk_mb_workspace(logits.device, size)
size = topk_ob_workspace_size(numRows, stride0, k, True)
workspace = get_topk_scratch_workspace(logits.device, size)
return _top_k_per_row_decode(
logits,
next_n,
seqLens,
indices,
numRows,
stride0,
stride1,
k,
workspace,
stable,
values,
)
csrc/kernels/topk_per_row_kernels.cu:2969
- When
valuesis provided, it is cast tofloat*without validating dtype/device/size. A wrong dtype (e.g. fp16) or CPU tensor would lead to invalid reads/writes in the kernel. Add explicit checks whenvalues.has_value()to enforce fp32, same device aslogits, and at leastindices.numel()elements.
float* logits_ptr = static_cast<float*>(logits.data_ptr());
int* indices_ptr = static_cast<int*>(indices.data_ptr());
int* seq_lens_ptr = static_cast<int*>(seqLens.data_ptr());
float* values_ptr = values.has_value() ? static_cast<float*>(values.value().data_ptr()) : nullptr;
const bool write_vals = values.has_value();
0695f16 to
58eb588
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 8 out of 8 changed files in this pull request and generated no new comments.
Suppressed comments (2)
csrc/kernels/topk_per_row_kernels.cu:2969
top_k_per_row_decodenow accepts an optionalvaluesoutput, but the implementation unconditionally castsvalues.data_ptr()tofloat*when provided and never checks dtype/device/contiguity/size. Passing a non-fp32 or non-contiguous tensor can lead to silent corruption or crashes. Add explicit validation whenvaluesis present (at minimum fp32, same device, contiguous, and large enough fornumRows*k).
constexpr bool select_min = !is_largest;
size_t buf_size = 0;
HipDeviceGuard device_guard(logits.device_id);
const hipStream_t stream = aiter::getCurrentHIPStream();
const int batch = static_cast<int>(numRows);
op_tests/flydsl_tests/test_flydsl_dcp_topk_merge.py:253
test_deterministic_across_runsuses a separate-stream load generatornoise @ noisewith a fixed 8192x8192 fp32 GEMM repeated 3x per iteration (andtorch.cuda.synchronize()inside_runwaits for it). This can make the unit test suite unnecessarily slow on fp32-limited paths. Consider making the noise size/repeats configurable (defaulting to a smaller matrix) while keeping the stress intent.
# Saturate the GPU from a second stream. Whether waves of one block get
# skewed enough to expose a missing LDS barrier is a scheduling accident;
# co-resident load makes that accident reliable instead of rare.
noise = torch.randn(8192, 8192)
noise_stream = torch.cuda.Stream()
for rank in range(world):
want_slots, want_counts = ref_dcp_merge(
scores, local_idx, bt, rank, k_loc, topk, page
)
ref = None
for it in range(200 // world):
with torch.cuda.stream(noise_stream):
for _ in range(3):
noise @ noise
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.
Suppressed comments (2)
aiter/ops/topk.py:493
- The new
valuesoutput is forwarded directly into the HIP kernel, which unconditionally treats it as float32. If a caller passes the wrong dtype/shape/device, this can lead to silent memory corruption or wrong results. Add lightweight validation (and make contiguous) in the Python wrapper before calling into the extension.
When `values` is given (float32, same shape as `indices`), each selected
index's logit is written alongside it. Rows shorter than k pad the index
with -1 and the score with -inf, so the padding sorts below every real
candidate and a consumer that ranks these scores needs no extra mask."""
# Decode always takes the ob path (see topk_per_row_kernels.cu).
# The original mb dispatch is commented out below for reference:
# if topk_use_mulblocks(numRows, stride0):
# size = topk_mb_workspace_size(numRows, stride0, k, True)
# workspace = get_topk_mb_workspace(logits.device, size)
size = topk_ob_workspace_size(numRows, stride0, k, True)
workspace = get_topk_scratch_workspace(logits.device, size)
return _top_k_per_row_decode(
logits,
next_n,
seqLens,
indices,
numRows,
stride0,
stride1,
k,
workspace,
stable,
values,
)
aiter/ops/flydsl/dcp_topk_merge.py:117
- The output buffer size check is overly strict when topk_tokens < k_loc. Per row, a rank can emit at most min(k_loc, topk_tokens) slots, so requiring rows * k_loc can reject valid caller buffers sized to rows * topk_tokens and unnecessarily forces larger allocations.
# Each rank owns at most k_loc KV slots per row (its own plane size).
if idx_numel < rows * k_loc:
raise ValueError("out_kv_indices too small for the worst case")
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
Suppressed comments (2)
aiter/ops/topk.py:473
- The docstring specifies that
valuesmust be float32 and the same shape asindices, but the function currently forwardsvalueswithout validating dtype/shape/device/contiguity. A mismatched tensor can cause undefined behavior in the underlying kernel.
When `values` is given (float32, same shape as `indices`), each selected
index's logit is written alongside it. Rows shorter than k pad the index
with -1 and the score with -inf, so the padding sorts below every real
candidate and a consumer that ranks these scores needs no extra mask."""
csrc/kernels/topk_per_row_kernels.cu:2975
valuesis cast tofloat*based only on presence, with no dtype/contiguity/size/device validation. Passing a non-fp32 or non-contiguous tensor here will lead to incorrect writes or memory corruption.
float* logits_ptr = static_cast<float*>(logits.data_ptr());
int* indices_ptr = static_cast<int*>(indices.data_ptr());
int* seq_lens_ptr = static_cast<int*>(seqLens.data_ptr());
float* values_ptr = values.has_value() ? static_cast<float*>(values.value().data_ptr()) : nullptr;
const bool write_vals = values.has_value();
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.
Suppressed comments (3)
aiter/ops/flydsl/dcp_topk_merge.py:124
- flydsl_dcp_topk_merge calls torch.cuda.get_device_properties(gathered_scores.device.index) without validating that all tensors are CUDA/HIP tensors on the same device; on CPU tensors (or mixed-device inputs) this will raise a non-actionable exception and could also compile/launch against the wrong device.
_validate(
tuple(gathered_scores.shape),
gathered_scores.dtype,
tuple(local_idx.shape),
local_idx.dtype,
aiter/ops/flydsl/kernels/dcp_topk_merge.py:465
- The comment says the launcher has a "Fixed launcher signature: 8 tensors", but the launch signature takes 7 tensors (plus rows/rank/stream). This is misleading when auditing ABI stability.
# Fixed launcher signature: 8 tensors
op_tests/test_flydsl_dcp_topk_merge.py:336
- The chunked prefix-sum path in the pack kernel is intended to handle rows > 256 (e.g., 257), but the pytest parameterization here only goes up to 256. Add at least one >256 case to prevent regressions in the chunking logic.
@pytest.mark.parametrize("mode", CASE_MODES)
@pytest.mark.parametrize("rows,world,page", [(1, 8, 64), (17, 4, 16), (256, 2, 128)])
def test_modes(rows, world, page, mode):
|
Nit (non-blocking): the commented-out } else {
aiter::ob::dispatch_topk_oneblock<float, int, 1024, false, aiter::ob::Phase::Decode>(
ws_ptr, buf_size, logits_ptr, static_cast<int*>(nullptr),
batch, stride0,
/*rowStarts=*/nullptr, /*rowEnds=*/seq_lens_ptr,
kTopK, /*out=*/nullptr, indices_ptr,
select_min, stream, /*sorted=*/true, static_cast<int>(next_n));
}
-
- // --- Original mb/ob dispatch (commented out for reference) ---
- // Both branches take the caller-provided `workspace` (no device allocation
- // here); the mb buffer is zeroed + self_reset by the kernel (prezeroed=true).
- // if (aiter::should_use_mulblocks(batch, stride0)) {
- // aiter::mb::standalone_stable_radix_topk<float, int, false, true, aiter::mb::Phase::Decode>(
- // ws_ptr, buf_size, logits_ptr, batch, stride0,
- // /*rowStarts=*/nullptr, /*rowEnds=*/seq_lens_ptr,
- // kTopK, /*out=*/nullptr, indices_ptr,
- // is_largest, stream, static_cast<int>(next_n), /*prezeroed=*/true);
- // } else {
- // aiter::ob::dispatch_topk_oneblock<float, int, 1024, false, aiter::ob::Phase::Decode>(
- // ws_ptr, buf_size, logits_ptr, static_cast<int*>(nullptr),
- // batch, stride0,
- // /*rowStarts=*/nullptr, /*rowEnds=*/seq_lens_ptr,
- // kTopK, /*out=*/nullptr, indices_ptr,
- // select_min, stream, /*sorted=*/true, static_cast<int>(next_n));
- // }
}Unrelated to the |
ea522e4 to
4e7affd
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
Suppressed comments (1)
aiter/ops/flydsl/dcp_topk_merge.py:122
- flydsl_dcp_topk_merge does not validate that tensors are CUDA, on the same device, contiguous, or that the 1D output buffers (out_kv_indices/out_kv_indptr/owned_counts) are actually 1D. Because _validate() is lru_cache’d on shapes/dtypes only, adding these checks inside _validate would be unsafe; doing them here avoids cached false positives and prevents confusing JIT failures or incorrect strided writes when a non-contiguous view is passed.
_validate(
Under Decode Context Parallel each rank holds 1/W of the KV and takes a
local top-k, so the ranks must agree on the global top-k before attention.
The existing path reconstructs that global set on every rank and then drops
the ~(W-1)/W of it the rank does not own -- W times the work, most of it
discarded.
This op emits only the rank's OWNED physical KV slots, already localized and
compacted, plus the kv_indptr attention needs. Two kernels: a per-row radix
select for the global threshold, then a per-row pack that also computes the
cross-row prefix sum. Two properties make the fusion possible:
* ownership is positional -- candidate column c came from rank c // k_loc --
so gids never have to travel and the caller can exchange scores alone;
* the block-table slot formula collapses to
block_table[j // page] * page + j % page, independent of W and of the
interleave size, so the localize folds into the emit loop.
The prefix sum lives in pack rather than in its own kernel: a grid=(1,) scan
walking the rows on a single thread cost 37% of the op at rows=128 (15.7 of
42.3 us) to sum 128 integers. Each pack block instead recomputes the prefix it
needs in parallel -- rows blocks each scanning rows counts is redundant, but a
block scan over a few hundred values is a handful of barriers, and it removes
both the serial loop and a launch. Chunked, so rows > 256 stays correct.
That is also why select and pack cannot merge further: pack needs
kv_indptr[row], which depends on every OTHER row's count. Closing that gap
needs either a cross-block barrier (unsafe -- block scheduling order is not
guaranteed) or grid=(1,), which would serialise select by rows.
Allocates no device scratch (the caller owns `staging`), so it is safe inside
a captured CUDAGraph.
Measured against the equivalent six-op sequence at W=8, k_loc=topk=2048:
4.82-5.14x across bs in [1,4,16,32,64,128], and half the exchange payload.
The curve is flat -- 33.6-34.3 us end to end regardless of bs -- where the
six-op path and the earlier three-kernel form both grew with rows.
Co-Authored-By: Claude <[email protected]>
top_k_per_row_decode now takes an optional `values` tensor and writes each selected index's logit alongside it, mirroring top_k_per_row_prefill. The one-block kernel already supported this -- WRITE_TOPK_VALUES is a template parameter of dispatch_topk_oneblock -- but the decode entry point hardcoded it to false with /*out=*/nullptr. Wiring it through the header, the pybind arg list and the Python wrapper is the whole change; the default path compiles to the same instantiation as before. This lets a DCP decode indexer skip the separate gather whose only job was to read these same scores back out of the logits. Also fixes the padding value for short rows: where the index is padded with -1, the score was padded with 0.0. A score that pads to 0.0 does not sort below real ones -- logits are routinely negative, so the padding outranks them, and a consumer that ranks these scores (a DCP merge across ranks) lets padding steal real candidates' slots. Pad with -inf instead. Both short-row pads are changed, not just decode's. The one-block and the multi-block kernels each have one, and which of the two runs is a perf heuristic (should_use_mulblocks) -- leaving them disagreeing would give the same call two different paddings across a batch-size boundary. The line is shared with prefill. aiter's own prefill caller (sampling.py:_select_topk) does pass a real `values` tensor, so WRITE_TOPK_VALUES is true there; the short-row branch is nonetheless unreachable for it, because that fast path requires vocab >= 65536 and k <= 256, so row_len <= k never holds. An earlier version of this message claimed all prefill callers pass values=None -- that was wrong, and would have cleared the change for the wrong reason. Co-Authored-By: Claude <[email protected]>
450a9e5
4e7affd to
450a9e5
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
Suppressed comments (1)
aiter/ops/flydsl/dcp_topk_merge.py:123
- The kernel is launched on
gathered_scores.device(current_stream bound to that device). If any of the other tensors are on a different device, this becomes an invalid launch or can write to the wrong address space. Add an explicit same-device check early to fail fast with a clear error.
_validate(
tuple(gathered_scores.shape),
Three related changes for the Decode Context Parallel path of the DeepSeek-V3.2-style
sparse indexer. The first two are what GLM-5.2 DCP decode needs; the third is an
independent crash fix found while bringing that path up, and is useful on its own.
1.
[FlyDSL] Add DCP decode TopK merge kernelUnder DCP each rank holds
1/Wof the KV and takes a local top-k, so the ranks mustagree on a global top-k before attention. The existing sequence reconstructs that
global set on every rank and then drops the
~(W-1)/Wof it the rank does notown — W times the work, most of it discarded.
This op emits only the rank's owned physical KV slots, already localized and
compacted, plus the
kv_indptrattention needs. Two kernels: a per-row radixselect for the global threshold, then a per-row pack that also computes the
cross-row prefix sum.
Two properties make the fusion possible:
ccame from rankc // k_loc, soglobal ids never have to travel and the caller can exchange scores alone.
jthe physical slot isblock_table[j // page] * page + (j % page)— independent ofWand of theinterleave size
S. Verified by exhaustive enumeration over 50400 combinationsof
(W, S, page, j), 0 mismatches. So the localize folds into the emit loopinstead of needing a separate pass.
Allocates no device scratch (the caller owns
staging), so it is safe inside acaptured CUDAGraph.
Why the prefix sum lives inside
packIt started as its own
grid=(1,)kernel walking the rows on a single thread. Thatis O(rows) serial work sandwiched between two parallel kernels, and it showed —
37% of the op's runtime at rows=128 (15.7 of 42.3 µs) to prefix-sum 128
integers.
Each
packblock now recomputes the prefix it needs, in parallel. The redundancyis real (rows blocks each scanning rows counts) but a block scan over a few hundred
values is a handful of barriers:
packwent 3.3 → 3.5 µs while a whole kernellaunch disappeared. The loop is chunked, so
rows > 256stays correct — verified atrows ∈ {1, 128, 256, 257, 512}.
That is also why
selectandpackcannot merge further:packneedskv_indptr[row], which depends on every other row's count. Closing that gap needseither a cross-block barrier (unsafe — block scheduling order is not guaranteed, so
a block spinning on a not-yet-scheduled block deadlocks) or
grid=(1,), which wouldserialise
selectby a factor of rows.Performance
Against the equivalent six-op sequence, at the production shape
W=8,k_loc = topk = 2048:The curve is flat — 33.6-34.3 µs regardless of bs — where the six-op path grows
with rows. Plus half the all-gather payload (
[rows, k_loc]instead of[2, rows, k_loc]) and 2 kernels instead of ~16.This is a single-op measurement. It has not been attributed against a full decode
step, so the wall-clock share depends on how often the indexer runs per forward.
Correctness
op_tests/flydsl_tests/test_flydsl_dcp_topk_merge.py— 45 passed. Covers adifferential test against the six-op reference, edge cases (
topk > n_cand, emptyrows, all-padding rows), a shape sweep, and tie-heavy inputs where the equal-to-
threshold admission rule is what decides the partition.
Two GPU races were found and fixed during development, each with a reproducible
before/after:
remaining_kfrom LDS but only the threadowning the k-th element writes it. Without a barrier between the two, a fast writer
updates it while a slow thread is still reading, the slow thread then satisfies the
hit condition against the new value and writes a second bucket — a corrupted
threshold.
block_exclusive_prefix_i32callwould overwrite
scan[warp]while a slow wave was still reading the current call'stotals. Fixed with a trailing barrier.
The second one I initially dismissed as a non-race based on 40 clean iterations of a
single shape. It reproduced later under a different shape. A race is structural, not
a property of one observed schedule — recording that here because the first ruling
was wrong.
2.
[HIP] Add optional score output to top_k_per_row_decodetop_k_per_row_decodenow takes an optionalvaluestensor and writes each selectedindex's logit alongside it, mirroring
top_k_per_row_prefill. The one-block kernelalready supported this (
WRITE_TOPK_VALUESis a template parameter ofdispatch_topk_oneblock); the decode entry point hardcoded it to false with/*out=*/nullptr. Wiring it through the header, the pybind arg list and the Pythonwrapper is the whole change — the default path compiles to the same instantiation
as before.
This lets a DCP decode indexer drop the separate gather whose only job was to read
these same scores back out of the logits.
Also: a padding-value fix
Where the index is padded with
-1, the score was padded with0.0. A0.0pad doesnot sort below real scores — logits are routinely negative, so the padding
outranks them, and a consumer that ranks these scores (a DCP merge across ranks) lets
padding steal real candidates' slots. Pad with
-infinstead.Measured impact before the fix: at
W=8the disjoint owned-partition collapsed from256 entries to 30.
The changed line is shared with prefill, but every in-tree prefill caller passes
values=None(checked all 5), soWRITE_TOPK_VALUESis false there and the storenever executes.
Validation
op_tests/flydsl_tests/test_flydsl_dcp_topk_merge.py: 45 passedvalues: padding== -inf, score==gathered logit,values=Nonebit-identical to before, non-stable path — all pass
abort on
main, so the fix is not a no-op32 prefill batches including the
done=[16384]chunk that previously aborted. Zeroiota_range/proc died/exitcode=-6in the log.Not covered
itself is untested; the consumer keeps it behind a default-off flag.
waves_per_eutimings are 10-iteration wall-clock, not a rigorous benchmark.