[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:
@@ -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"))
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user