[TopK] In-kernel canonical emission (MERLIN_TOPK_SORTED_EMIT)

Emits the selected indices in canonical ascending order inside the kernel so
the Python QSA sort can be skipped. Output-equivalent to the Python sort;
reference model, property tests and GPU arms included. Default off in this
commit.

Co-Authored-By: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-09 20:04:37 +07:00
co-authored by Hinata
parent a4aecf9ec7
commit eeea036c12
5 changed files with 444 additions and 32 deletions
@@ -50,17 +50,84 @@ _DECODE_BLOCK_N = 64
# ---------------------------------------------------------------------------
_QSA_SORT = envs.MERLIN_QSA_SORT
# ---------------------------------------------------------------------------
# MERLIN_TOPK_SORTED_EMIT: persistent_topk emits
# every row in the canonical order below by itself (sorted_emit_row() in
# csrc/libtorch_stable/persistent_topk.cuh), so the Python sort is skipped.
#
# The decision is NOT a Python parse of the variable. The C++ getter
# (topk.cu sorted_emit_enabled) is the single source of truth and publishes
# what it cached into persistent_topk_toggle_state() field 6; that is read
# once, host-side, right after this process's first persistent_topk launch
# (the static is filled by then) and latched. So the sort is dropped only when
# the kernel that actually ran says it sorted; an older build (layout 1, no
# field 6) or an absent op keeps the Python sort. cooperative_topk (SM90+) has
# no sorted emission and always keeps the Python sort.
#
# MERLIN_TOPK_SORTED_EMIT_CHECK=1 (debug, default off): instead of trusting
# the kernel, assert on device that the row already equals its canonical form.
# torch._assert_async is capture-safe (no host sync); a violation is a device
# assert, i.e. a dead context -- which is the point of a debug check.
# ---------------------------------------------------------------------------
_SORTED_EMIT_CHECK = envs.MERLIN_TOPK_SORTED_EMIT_CHECK
_kernel_sorted_emit_state: bool | None = None # None: not read yet
def _qsa_canonicalise(block_indices: torch.Tensor) -> None:
"""Sort selected block indices ascending, padding last. In place, same shape."""
if not _QSA_SORT:
return
def _canonical(block_indices: torch.Tensor) -> torch.Tensor:
"""Ascending, padding last as -1 -- THE definition of the canonical order,
shared by the Python sort and the debug check (and the reference the
kernel's sorted emission is tested against)."""
big = torch.iinfo(block_indices.dtype).max
tmp = torch.where(
block_indices < 0, torch.full_like(block_indices, big), block_indices
)
tmp = torch.sort(tmp, dim=-1).values
block_indices.copy_(torch.where(tmp == big, torch.full_like(tmp, -1), tmp))
return torch.where(tmp == big, torch.full_like(tmp, -1), tmp)
def _qsa_canonicalise(block_indices: torch.Tensor) -> None:
"""Sort selected block indices ascending, padding last. In place, same shape."""
if not _QSA_SORT:
return
block_indices.copy_(_canonical(block_indices))
def kernel_sorted_emit() -> bool:
"""True iff this process's persistent_topk emits canonical order.
Host-only (a tensor-free query op; no CUDA call), so it is safe inside a
capture. Latches once the C++ static is known; an uninitialised static
(no launch yet) answers False without latching.
"""
global _kernel_sorted_emit_state
if _kernel_sorted_emit_state is not None:
return _kernel_sorted_emit_state
op = getattr(torch.ops._C, "persistent_topk_toggle_state", None)
if op is None:
_kernel_sorted_emit_state = False
return False
from vllm.v1.worker.e2_toggles import decode_topk_state
decoded = decode_topk_state(int(op()))
if isinstance(decoded, str) or "sorted_emit" not in decoded:
# Unknown layout, or layout 1 (no field 6): this build cannot sort.
_kernel_sorted_emit_state = False
return False
value = decoded["sorted_emit"]
if value == "uninit":
return False # not latched: ask again after a launch
_kernel_sorted_emit_state = value == "1"
return _kernel_sorted_emit_state
def _check_sorted_emission(block_indices: torch.Tensor) -> None:
"""Debug only: device-side assert that the kernel's row is canonical."""
if not _SORTED_EMIT_CHECK:
return
torch._assert_async(
torch.eq(block_indices, _canonical(block_indices)).all(),
"MERLIN_TOPK_SORTED_EMIT: persistent_topk row is not in canonical order",
)
@triton.jit
@@ -608,6 +675,11 @@ def _topk(
block_topk,
logits.shape[1],
)
# MERLIN_TOPK_SORTED_EMIT: the kernel already emitted the canonical order,
# so the Python sort would be a no-op -- skip it (optionally check it).
if not use_cooperative_topk and kernel_sorted_emit():
_check_sorted_emission(block_indices)
return
_qsa_canonicalise(block_indices)