[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
+56 -12
View File
@@ -12,13 +12,15 @@ producer at all. Every GPU worker therefore logs exactly one line::
e2-toggles[PP<p>_TP<t>]: pid=<pid> MERLIN_FULL_K=<raw> MERLIN_QSA_SORT=<raw>
MERLIN_TIE_DET=<raw> MERLIN_TIE_RECENT=<raw> MERLIN_TOPK_EXACT_MEDIUM=<raw>
MERLIN_TOPK_EXACT_DECODE=<raw> MERLIN_TOPK_DET_LARGE=<raw>
MERLIN_TOPK_SORTED_EMIT=<raw>
effective: full_k=<0|1> qsa_sort=<0|1|invalid> tie_det=<0|1> tie_recent=<0|1>
tie_recent_effective=<0|1> exact_medium=<0|1> exact_decode=<0|1>
det_large=<0|1> source=<libc-getenv|os-environ>
det_large=<0|1> sorted_emit=<0|1> source=<libc-getenv|os-environ>
cpp-cache: <full_k=... tie_det=... tie_recent=... tie_recent_effective=...
exact_medium=... exact_decode=... det_large=... source=cpp-cache
| n-a reason=<why>>
python: qsa_sort=<0|1|n-a> source=qsa_indexer._QSA_SORT
exact_medium=... exact_decode=... det_large=... sorted_emit=...
source=cpp-cache | n-a reason=<why>>
python: qsa_sort=<0|1|n-a> sorted_emit_skip=<0|1|n-a>
source=qsa_indexer._QSA_SORT
device: switch=<0|1|n-a> switch_large=<0|1|n-a> source=counter-slots-8-9
(one line in the log). ``<raw>`` is ``unset``, a plain token, or a double-quoted
@@ -42,7 +44,11 @@ WHAT EACH SECTION IS
was first cut against (earlier v2.2 builds, not published) have none.
* ``python:`` -- ``qsa_indexer._QSA_SORT``, the module constant the QSA sort
actually branches on (looked up in ``sys.modules``, never imported here;
``n-a`` if the module was never loaded in this process).
``n-a`` if the module was never loaded in this process), and
``sorted_emit_skip`` -- ``qsa_indexer._kernel_sorted_emit_state``, i.e.
whether the Python sort is being SKIPPED because the kernel reported
MERLIN_TOPK_SORTED_EMIT through ``persistent_topk_toggle_state`` field 6
(``n-a`` until the first QSA top-k has run and latched it).
* ``device:`` -- counter slots [8]/[9], which the counter op fills from the
C++ ``exact_medium_enabled()`` / ``det_large_enabled()`` statics
(topk.cu persistent_topk_exact_counters).
@@ -93,6 +99,7 @@ logger = init_logger(__name__)
# MERLIN_TOPK_EXACT_MEDIUM csrc/libtorch_stable/topk.cu:68-74 (unset -> ON)
# MERLIN_TOPK_EXACT_DECODE csrc/libtorch_stable/topk.cu:103-109
# MERLIN_TOPK_DET_LARGE csrc/libtorch_stable/topk.cu:86-92 (unset -> ON)
# MERLIN_TOPK_SORTED_EMIT csrc/libtorch_stable/topk.cu sorted_emit_enabled
CXX_SWITCHES: tuple[tuple[str, str, bool], ...] = (
("MERLIN_FULL_K", "full_k", False),
("MERLIN_TIE_DET", "tie_det", False),
@@ -100,6 +107,7 @@ CXX_SWITCHES: tuple[tuple[str, str, bool], ...] = (
("MERLIN_TOPK_EXACT_MEDIUM", "exact_medium", True),
("MERLIN_TOPK_EXACT_DECODE", "exact_decode", False),
("MERLIN_TOPK_DET_LARGE", "det_large", True),
("MERLIN_TOPK_SORTED_EMIT", "sorted_emit", False),
)
QSA_SORT_NAME = "MERLIN_QSA_SORT"
RAW_ORDER = (
@@ -110,6 +118,7 @@ RAW_ORDER = (
"MERLIN_TOPK_EXACT_MEDIUM",
"MERLIN_TOPK_EXACT_DECODE",
"MERLIN_TOPK_DET_LARGE",
"MERLIN_TOPK_SORTED_EMIT",
)
EFFECTIVE_ORDER = (
"full_k",
@@ -120,6 +129,7 @@ EFFECTIVE_ORDER = (
"exact_medium",
"exact_decode",
"det_large",
"sorted_emit",
)
CPP_ORDER = tuple(k for k in EFFECTIVE_ORDER if k != "qsa_sort")
@@ -265,21 +275,29 @@ _TOPK_STATE_FIELDS = (
"exact_medium",
"exact_decode",
"det_large",
"sorted_emit",
)
# Known layouts: version -> field count. Layout 2 is layout 1
# plus field 6 (MERLIN_TOPK_SORTED_EMIT); fields 0-5 are unchanged.
_TOPK_STATE_LAYOUTS = {1: 6, 2: 7}
def decode_topk_state(state: int) -> dict[str, str] | str:
"""Unpack ``persistent_topk_toggle_state()``: 2 bits per field (0 off,
1 on, 2 not initialised), field count at bits 48-55 (6), layout version at
bits 56-62 (1). Any other layout is refused with a reason string."""
1 on, 2 not initialised), field count at bits 48-55, layout version at
bits 56-62 -- (1, 6) or (2, 7). Any other layout is refused with a reason
string. A layout-1 build has no sorted emission, reported as ``n-a``."""
version, count = (state >> 56) & 0x7F, (state >> 48) & 0xFF
if version != 1 or count != len(_TOPK_STATE_FIELDS):
if _TOPK_STATE_LAYOUTS.get(version) != count:
return f"unknown-layout-v{version}-{count}-fields"
names = {0: "0", 1: "1", 2: "uninit"}
return {
out = {
key: names.get((state >> (2 * i)) & 3, "invalid")
for i, key in enumerate(_TOPK_STATE_FIELDS)
for i, key in enumerate(_TOPK_STATE_FIELDS[:count])
}
for key in _TOPK_STATE_FIELDS[count:]:
out[key] = "n-a"
return out
def decode_full_k_state(state: int) -> str:
@@ -324,6 +342,17 @@ def qsa_sort_live() -> str:
return "1" if bool(module._QSA_SORT) else "0"
def sorted_emit_skip_live() -> str:
"""``qsa_indexer._kernel_sorted_emit_state``: 1 = the Python sort is being
skipped because the kernel reported sorted emission, 0 = not skipped,
``n-a`` = not latched yet (or the module was never loaded)."""
module = sys.modules.get(_QSA_MODULE)
state = getattr(module, "_kernel_sorted_emit_state", None) if module else None
if state is None:
return "n-a"
return "1" if state else "0"
def device_switches() -> dict[str, str]:
"""Counter slots [8]/[9] (switch / switch_large). One synchronizing read
(topk_counters.read refuses inside a capture), so it is only called from
@@ -350,6 +379,7 @@ def toggles_line(
cpp: dict[str, str] | str,
qsa_live: str,
device: dict[str, str],
sorted_skip: str = "n-a",
) -> str:
parts = [f"e2-toggles[{tag}]: pid={pid}"]
parts += [f"{name}={raw[name]}" for name in RAW_ORDER]
@@ -362,7 +392,12 @@ def toggles_line(
else:
parts += [f"{key}={cpp[key]}" for key in CPP_ORDER]
parts.append("source=cpp-cache")
parts += ["python:", f"qsa_sort={qsa_live}", "source=qsa_indexer._QSA_SORT"]
parts += [
"python:",
f"qsa_sort={qsa_live}",
f"sorted_emit_skip={sorted_skip}",
"source=qsa_indexer._QSA_SORT",
]
parts.append("device:")
parts += [f"{key}={device[key]}" for key in ("switch", "switch_large")]
parts.append("source=counter-slots-8-9")
@@ -402,6 +437,7 @@ def maybe_emit(
cpp_fn: Callable[[], dict[str, str] | str] = cpp_cache,
device_fn: Callable[[], dict[str, str]] = device_switches,
qsa_fn: Callable[[], str] = qsa_sort_live,
sorted_skip_fn: Callable[[], str] = sorted_emit_skip_live,
) -> str:
"""Emit the line at most once per process. One bool check when already
emitted or not yet armed, so it can sit at the head of every execute step.
@@ -431,7 +467,15 @@ def maybe_emit(
cxx_getenv, env_source = getenv_fn()
raw, effective = environ_view(cxx_getenv, os.environ.get)
line = toggles_line(
tag, os.getpid(), raw, effective, env_source, cpp, qsa_fn(), device_fn()
tag,
os.getpid(),
raw,
effective,
env_source,
cpp,
qsa_fn(),
device_fn(),
sorted_skip_fn(),
)
_emitted = True
logger.info("%s", line)