Skip to content

[HIP] [FlyDSL] dcp topk merge - #5123

Merged
coderfeli merged 2 commits into
mainfrom
ganyi/dcp-topk-merge
Sep 2, 2026
Merged

coderfeli merged 2 commits into
mainfrom
ganyi/dcp-topk-merge

Conversation

@ganyi1996ppo

@ganyi1996ppo ganyi1996ppo commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

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 kernel

Under DCP each rank holds 1/W of the KV and takes a local top-k, so the ranks must
agree on a global top-k before attention. The existing sequence 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
    global ids never have to travel and the caller can exchange scores alone.
  • The slot formula collapses. For local index j the physical slot is
    block_table[j // page] * page + (j % page) — independent of W and of the
    interleave size S. Verified by exhaustive enumeration over 50400 combinations
    of (W, S, page, j), 0 mismatches. So the localize folds into the emit loop
    instead of needing a separate pass.

Allocates no device scratch (the caller owns staging), so it is safe inside a
captured CUDAGraph.

Why the prefix sum lives inside pack

It started as its own grid=(1,) kernel walking the rows on a single thread. That
is 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 pack block now recomputes the prefix it needs, in parallel. The redundancy
is real (rows blocks each scanning rows counts) but a block scan over a few hundred
values is a handful of barriers: pack went 3.3 → 3.5 µs while a whole kernel
launch disappeared. The loop is chunked, so rows > 256 stays correct — verified at
rows ∈ {1, 128, 256, 257, 512}.

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, so
a block spinning on a not-yet-scheduled block deadlocks) or grid=(1,), which would
serialise select by a factor of rows.

Performance

Against the equivalent six-op sequence, at the production shape W=8,
k_loc = topk = 2048:

bs six-op fused speedup
1 166.5 µs 33.9 µs 4.91×
4 173.6 µs 33.8 µs 5.14×
16 165.2 µs 34.3 µs 4.82×
32 167.3 µs 33.6 µs 4.98×
64 174.6 µs 34.3 µs 5.09×
128 167.4 µs 34.0 µs 4.92×

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 a
differential test against the six-op reference, edge cases (topk > n_cand, empty
rows, 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:

  • Bucket-hit test. Every thread reads remaining_k from LDS but only the thread
    owning 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 scan. A fast wave entering the next block_exclusive_prefix_i32 call
    would overwrite scan[warp] while a slow wave was still reading the current call's
    totals. 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_decode

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); 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 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 with 0.0. A 0.0 pad does
not 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 -inf instead.

Measured impact before the fix: at W=8 the disjoint owned-partition collapsed from
256 entries to 30.

The changed line is shared with prefill, but every in-tree prefill caller passes
values=None
(checked all 5), so WRITE_TOPK_VALUES is false there and the store
never executes.


Validation

  • op_tests/flydsl_tests/test_flydsl_dcp_topk_merge.py: 45 passed
  • HIP values: padding == -inf, score == gathered logit, values=None
    bit-identical to before, non-stable path — all pass
  • Gluon fix: 3 previously-aborting shapes compile; reverting the patch reproduces the
    abort on main, so the fix is not a no-op
  • End-to-end: GLM-5.2, TP=8, DCP=8, 65536-token inputs, 8/8 requests succeeded,
    32 prefill batches including the done=[16384] chunk that previously aborted. Zero
    iota_range / proc died / exitcode=-6 in the log.

Not covered

  • The DCP merge has not been validated on real multi-GPU DCP. The all-gather
    itself is untested; the consumer keeps it behind a default-off flag.
  • Tested on one gfx950 machine with Triton 3.7.0.
  • The waves_per_eu timings are 10-iteration wall-clock, not a rigorous benchmark.

@ganyi1996ppo
ganyi1996ppo requested review from a team and a lite review from Copilot August 30, 2026 12:20
@github-actions github-actions Bot changed the title dcp topk merge [Triton/Gluon] [HIP] [FlyDSL] dcp topk merge Aug 30, 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 5123 --add-label <label>

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

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

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 optional values output buffer and fix padded score semantics (-inf instead of 0).
  • Add a gfx950-specific guard in fp8_mqa_logits to avoid an LLVM backend abort by relaxing waves_per_eu under 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.

Comment thread aiter/ops/flydsl/dcp_topk_merge.py Resolved
Comment thread csrc/kernels/topk_per_row_kernels.cu Resolved
Comment thread aiter/ops/topk.py Resolved
@ganyi1996ppo ganyi1996ppo changed the title [Triton/Gluon] [HIP] [FlyDSL] dcp topk merge [HIP] [FlyDSL] dcp topk merge Aug 30, 2026
Copilot AI review requested due to automatic review settings August 31, 2026 00:15
@github-actions github-actions Bot changed the title [HIP] [FlyDSL] dcp topk merge [Triton/Gluon] [HIP] [FlyDSL] dcp topk merge Aug 31, 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.

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_threshold is omitted, the launcher is built with write_threshold=False, so select_kernel never 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

  • values is documented as a float32 tensor with the same shape as indices, but this isn’t enforced. The C++ binding unconditionally casts values.data_ptr() to float*, 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

  • values is forwarded to the C++ binding without validation. Since the binding treats it as a raw float*, incorrect dtype/shape/contiguity can lead to memory corruption. Please validate values (float32, contiguous, same shape/device as indices) before calling _top_k_per_row_decode.
        k,
        workspace,
        stable,
        values,
    )

Comment thread aiter/ops/flydsl/dcp_topk_merge.py Resolved
Comment thread aiter/ops/flydsl/dcp_topk_merge.py Resolved

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

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

  • values is forwarded to the C++ kernel and then unconditionally cast to float* when present. Add Python-side validation (dtype/shape/device) so a mis-typed or mis-shaped values tensor 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 values is provided, it is cast to float* 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 when values.has_value() to enforce fp32, same device as logits, and at least indices.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();

Copilot AI review requested due to automatic review settings August 31, 2026 11:03

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

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_decode now accepts an optional values output, but the implementation unconditionally casts values.data_ptr() to float* 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 when values is present (at minimum fp32, same device, contiguous, and large enough for numRows*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_runs uses a separate-stream load generator noise @ noise with a fixed 8192x8192 fp32 GEMM repeated 3x per iteration (and torch.cuda.synchronize() inside _run waits 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

Copilot AI review requested due to automatic review settings August 31, 2026 11:11

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

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 values output 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")

Comment thread op_tests/test_flydsl_dcp_topk_merge.py Resolved
@wuhuikx
wuhuikx requested review from lirui927 and valarLip September 1, 2026 01: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.

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 values must be float32 and the same shape as indices, but the function currently forwards values without 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

  • values is cast to float* 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();

Copilot AI review requested due to automatic review settings September 1, 2026 07:18

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

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):

Comment thread op_tests/test_flydsl_dcp_topk_merge.py Resolved
Comment thread aiter/ops/flydsl/dcp_topk_merge.py Resolved
@zufayu
zufayu requested a review from junhaha666 September 1, 2026 09:32
@zufayu

zufayu commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Nit (non-blocking): the commented-out mb/ob dispatch block at the tail of top_k_per_row_decode is dead code that predates this PR. Since the function is already being rewritten here, worth dropping it in a follow-up — git history keeps the reference, and leaving it invites rot (uncompiled, unmaintained, but scanned by every future reader to confirm it's unreachable).

     } 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 values correctness — just pre-existing hygiene that this PR's churn makes cheap to clean up.

Copilot AI review requested due to automatic review settings September 1, 2026 10:54
zufayu
zufayu previously approved these changes Sep 1, 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.

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(

Comment thread csrc/kernels/topk_per_row_kernels.cu Resolved
coderfeli
coderfeli previously approved these changes Sep 1, 2026
valarLip
valarLip previously approved these changes Sep 1, 2026
Comment thread op_tests/test_flydsl_dcp_topk_merge.py Resolved
Comment thread op_tests/test_flydsl_dcp_topk_merge.py Resolved
ganyi1996ppo and others added 2 commits September 1, 2026 13:31
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]>
Copilot AI review requested due to automatic review settings September 1, 2026 13:33
@ganyi1996ppo
ganyi1996ppo dismissed stale reviews from valarLip, coderfeli, and zufayu via 450a9e5 September 1, 2026 13:33

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

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),

Comment thread aiter/ops/flydsl/dcp_topk_merge.py Resolved
@coderfeli
coderfeli merged commit ce788f5 into main Sep 2, 2026
56 checks passed
@coderfeli
coderfeli deleted the ganyi/dcp-topk-merge branch September 2, 2026 00:31
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.

6 participants