[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
+26
View File
@@ -602,6 +602,26 @@ if TYPE_CHECKING:
# unless MERLIN_TOPK_LARGE_FAULT_INJECT names a CTA.
MERLIN_TOPK_LARGE_FAULT_KIND: str | None = None
#
# MERLIN_TOPK_SORTED_EMIT -- persistent_topk
# emits every row in the canonical order MERLIN_QSA_SORT imposes
# (ascending index, padding last as -1), and qsa_indexer.py then skips its
# Python sort. Same classification as the kernel switches above: resolved
# ONCE per process by a std::getenv in csrc/libtorch_stable/topk.cu
# (sorted_emit_enabled) -- the single source of truth -- and the resolved
# value reaches the GPU as a kernel launch argument AND removes three torch
# ops from the captured sequence, so a cudagraph bakes it in. CAPTURE: yes.
# AOT: not established for the kernel half; hashed conservatively (a fork
# env knob must be a compile factor: an os.environ knob that is not
# registered is not in the cache key). Raw passthrough: Python never parses
# it to decide anything -- qsa_indexer.py reads the C++ cache through
# persistent_topk_toggle_state() field 6. Not in ignored_factors.
MERLIN_TOPK_SORTED_EMIT: str | None = None
# Debug companion, a REAL Python read site (qsa_indexer._SORTED_EMIT_CHECK,
# read once at import): when the kernel sorted, assert on device that the
# row equals its canonical form instead of trusting it. Adds ops to the
# captured sequence, so it is hashed too. Default off.
MERLIN_TOPK_SORTED_EMIT_CHECK: bool = False
#
# NOT REGISTERED, deliberately: MERLIN_TOPK_EXACT_TRAP. It is a
# preprocessor define consumed by `#ifndef` in persistent_topk.cuh at
# BUILD time (-D), not a process environment variable -- nothing in the
@@ -2692,6 +2712,12 @@ environment_variables: dict[str, Callable[[], Any]] = {
"MERLIN_TOPK_LARGE_FAULT_KIND": lambda: os.getenv(
"MERLIN_TOPK_LARGE_FAULT_KIND", None
),
# In-kernel canonical emission and its debug check; see the
# declaration block. Both hashed: both change the captured sequence.
"MERLIN_TOPK_SORTED_EMIT": lambda: os.getenv("MERLIN_TOPK_SORTED_EMIT", None),
"MERLIN_TOPK_SORTED_EMIT_CHECK": lambda: bool(
int(os.getenv("MERLIN_TOPK_SORTED_EMIT_CHECK", "0"))
),
}