From f185d9bb5de5f33cd4de9993cc0365724e6bf81f Mon Sep 17 00:00:00 2001 From: Oasis-Git Date: Sun, 22 Nov 2026 19:01:13 -0800 Subject: [PATCH] [Refactor] [GB300] kimi_k31: Settle the seven scoped levers on the GB300 results #80 left seven levers on best_default pending GPU data. With the results in, none of them stays scoped, so kimi_k31/k3/default_scope.py goes too: - K31MK_MLA_VALUE_EARLY_TRIGGER: the sparse verify MlaValue always releases the o-proj at entry. The dense MlaValue keeps its late trigger. - K31MK_AUX_SIDE_STREAM: the DFlash capture layers' aux mixture always runs on the side stream; ClusterAttnRes no longer launches AuxMixture itself. - K31MK_EXPERTS_COOPERATIVE: the routed experts always launch without the cooperative attribute. check_residency still requires a co-resident grid. - SGLANG_K31_DRAFT_MK: the draft chain (with M1b) always builds where the draft spec admits it (TP16, 8-row blocks); max_rows is always 8. The aux and head follow K31MK_DFLASH_RUNTIME alone. - K31MK_OPROJ_NORM_FOLD: the o-proj consumers always fold the final-norm exchange when there are saved blocks. The fold is per token inside the 7-CTA cluster, so the TP16 condition was not a kernel limit and is gone, with the consumer's separate final-norm exchange. - K31MK_MLAQ_AFTER_SCORING: deleted with its reorder path (no gain). - K31MK_INDEX_SPLIT_MIN: the split threshold is the measured crossover, 320000. DCP and an unusable merge still decline; the explicit-env raises are gone. Co-Authored-By: Claude Opus 5.5 --- docs/models/kimi_k31.md | 11 +-- sgl_nvidia_mega/kimi_k31/draft/serving.py | 46 +++++----- sgl_nvidia_mega/kimi_k31/dsa/split.py | 8 +- sgl_nvidia_mega/kimi_k31/dsa/verify.py | 85 +++---------------- sgl_nvidia_mega/kimi_k31/k3/default_scope.py | 57 ------------- .../kimi_k31/sm103/k3/attn_res/kernel.py | 8 +- .../kimi_k31/sm103/k3/attn_res/prepared.py | 21 ++--- .../kimi_k31/sm103/k3/moe/experts.py | 24 ++---- .../kimi_k31/sm103/k3/moe/experts_runtime.py | 5 -- .../kimi_k31/sm103/k3/oproj/consumer.py | 67 +++++---------- .../kimi_k31/sm103/k3/oproj/prepared.py | 42 +-------- sgl_nvidia_mega/kimi_k31/verify_executor.py | 28 +----- test/unit/test_kimi_k31_split_merge.py | 64 ++++++++++++++ 13 files changed, 146 insertions(+), 320 deletions(-) delete mode 100644 sgl_nvidia_mega/kimi_k31/k3/default_scope.py diff --git a/docs/models/kimi_k31.md b/docs/models/kimi_k31.md index d0c5c72d..cee7e7f5 100644 --- a/docs/models/kimi_k31.md +++ b/docs/models/kimi_k31.md @@ -5,13 +5,8 @@ | GB300 (SM103); 148-SM B300 (SM103) and B200/GB200 (SM100) with `sm148` | 16 (one NVLink domain); 8 | DFlash target verify steps of 8 rows a request (7 drafted tokens and the anchor) at 1 to 8 requests, without DCP or with DCP equal to TP, also as the decode role of a PD-disaggregated deployment; the DFlash2 draft decoder layers at one request. Served and measured end to end at TP16, one request; on GB200 (TP16 over four trays, `sm148`) served and measured end to end at one to four requests | The Kimi K3.1 megakernel (`sgl_nvidia_mega/kimi_k31`) runs the DFlash target verify -step and, behind `SGLANG_K31_DRAFT_MK`, the DFlash2 draft's decoder layers. It needs -an SGLang with the Kimi K3.1 host bindings (sgl-project/sglang#48414); on an older -SGLang its spec refuses every configuration with that reason. It builds on its own +step and the DFlash2 draft's decoder layers. It needs an SGLang with the Kimi K3.1 +host bindings (sgl-project/sglang#48414); on an older SGLang its spec refuses every +configuration with that reason. It builds on its own copy of the Kimi K3 base (`kimi_k31/k3` and its kernels in `kimi_k31/sm103/k3`), so `sgl_nvidia_mega/kimi_k3` and the Kimi K3 path are unchanged. - -`kimi_k31/k3/default_scope.py` turns a set of tuned options on by default only in -the configuration they were measured in: TP16, no DCP, 8 draft tokens and -`--max-running-requests 1`. Elsewhere an unset option keeps its other default, and -a set environment variable always wins. diff --git a/sgl_nvidia_mega/kimi_k31/draft/serving.py b/sgl_nvidia_mega/kimi_k31/draft/serving.py index 6556dd53..ea85075d 100644 --- a/sgl_nvidia_mega/kimi_k31/draft/serving.py +++ b/sgl_nvidia_mega/kimi_k31/draft/serving.py @@ -1,16 +1,15 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the SGLang project -"""K3.1 DFlash2 draft layers on the megakernel chain in serving (stage 1; ``SGLANG_K31_DRAFT_MK``). +"""K3.1 DFlash2 draft layers on the megakernel chain in serving (stage 1, with M1b). -Stage 1 with M1b is on by default in the GB300 BEST scope (kimi_k31/k3/default_scope.py), off elsewhere; -``SGLANG_K31_DRAFT_MK`` set to 0 / 1 turns it off / on. With it, the chain also builds the head (2a) and the aux -(2b) for the K3.1 DFlash runtime, unless ``K31MK_DFLASH_RUNTIME=0`` (no runtime runs them). A stage the setup -does not support declines with one INFO line. +The chain also builds the head (2a) and the aux (2b) for the K3.1 DFlash runtime, unless +``K31MK_DFLASH_RUNTIME=0`` (no runtime runs them). A stage the setup does not support declines with one INFO +line. The draft graph's forward of one B1 x 8-row TARGET_VERIFY block runs ``DraftChain`` (chain.py) in place of SGLang's decoder layers; the chain's attention hook (M1a) is SGLang's own MLA sublayer up to W_UV, so the block's KV write, RoPE and sliding window stay SGLang's. Every other draft forward (other widths, prefill) -runs SGLang's. ``SGLANG_K31_DRAFT_MK=0``: ``max_rows`` 0, so SGLang never wraps the draft's forward. +runs SGLang's. M1b: the attention sublayer runs on MK blocks as well (``DraftAttention``: fused_a, DraftMlaQuery's FP8 query + the block's KV insert at its out_cache_loc slots, DraftMlaValue); only the @@ -55,7 +54,6 @@ from sgl_nvidia_mega.kimi_k31 import spec as target from sgl_nvidia_mega.kimi_k31.dflash.protocol import DRAFT_CHAINS, RUNTIME -from sgl_nvidia_mega.kimi_k31.k3.default_scope import best_default # The SGLang names this module reads, by file under the sglang package; test/unit/test_contract.py pins them. SGLANG_READS = { @@ -139,12 +137,9 @@ logger = logging.getLogger(__name__) -ENV = "SGLANG_K31_DRAFT_MK" -ENABLED = best_default(ENV, "1", "0") not in ("", "0") -# Stage 2b: the worker's decode aux append (context features into the draft KV) on MK blocks too, and -# stage 2a: the draft graph's proposal (candidate top-k over the target lm_head + the selector walk, greedy +# Stage 2b (``RUNTIME``): the worker's decode aux append (context features into the draft KV) on MK blocks too, +# and stage 2a: the draft graph's proposal (candidate top-k over the target lm_head + the selector walk, greedy # or sampled per request); both run through the K3.1 DFlash runtime, so both build with it. -AUX = HEAD = ENABLED and RUNTIME ROWS = 8 # one DFlash block per request; stage 1 serves B1 MLA_ROW = 576 # bytes per draft KV slot: 512 FP8 latent | 64 FP8 rotated k_pe @@ -207,7 +202,7 @@ def __init__(self, model, hf_config, ctx): cos_sin = model.layers[0].self_attn.rotary_emb.cos_sin_cache if not INSTANCES: raise RuntimeError( - f"{ENV}: no K3.1 verify executor to check the draft mailboxes against" + "draft MK: no K3.1 verify executor to check the draft mailboxes against" ) targets = (*INSTANCES, self._ar_fusion_buffers(), group.ca_comm) self.chain = DraftChain( @@ -226,8 +221,7 @@ def __init__(self, model, hf_config, ctx): self._stream: Optional[int] = None self._layers = len(weights) logger.info( - "NVIDIA megakernel: DFlash2 draft layers on the MK chain (%s, B1 x %d rows, %d layers, TP%d)", - ENV, + "NVIDIA megakernel: DFlash2 draft layers on the MK chain (B1 x %d rows, %d layers, TP%d)", ROWS, self._layers, shapes.tp, @@ -237,21 +231,20 @@ def __init__(self, model, hf_config, ctx): self.chain.target_buffers, ) self.device = device - self.aux = self._build_aux(model, shapes, comm, cos_sin) if AUX else None + self.aux = self._build_aux(model, shapes, comm, cos_sin) if RUNTIME else None self.draft_aux_rows = (ROWS,) if self.aux is not None else () self._pools: Optional[torch.Tensor] = None self._pool_ptrs: tuple[int, ...] = () self._caches: Optional[list] = None self.draft_head_requests = ( - (1,) if HEAD and self._head_serves(model) else () + (1,) if RUNTIME and self._head_serves(model) else () ) # the chain's head serves B1 - self.m1b = ENABLED + self.m1b = True # False once the draft KV pool declines (``_kv``) # The target's DFlash runtime (dflash/runtime.py) serves only a draft chain built here. DRAFT_CHAINS.append(self) - if self.m1b: - logger.info( - "NVIDIA megakernel: draft MK M1b: attention on MK blocks, core = SGLang's sliding-window MLA" - ) + logger.info( + "NVIDIA megakernel: draft MK M1b: attention on MK blocks, core = SGLang's sliding-window MLA" + ) @staticmethod def _head_serves(model): @@ -387,7 +380,7 @@ def attn(i, x): ) if state[1] != AttnForwardMethod.MLA: raise RuntimeError( - f"{ENV}: the draft attention runs {state[1]}, not MLA" + f"draft MK: the draft attention runs {state[1]}, not MLA" ) module.o_proj = _NoOproj() return module.forward_core(state) @@ -477,11 +470,11 @@ def forward( self._stream = stream elif stream != self._stream: raise RuntimeError( - f"{ENV}: a draft hop from a second stream (all-reduce program order)" + "draft MK: a draft hop from a second stream (all-reduce program order)" ) if input_embeds is None or input_embeds.shape != self.out.shape: raise RuntimeError( - f"{ENV}: input_embeds {None if input_embeds is None else tuple(input_embeds.shape)}" + f"draft MK: input_embeds {None if input_embeds is None else tuple(input_embeds.shape)}" ) x0 = input_embeds # The head proposes from the block's rows 1..7; row 0 is the anchor (a no-copy view at B1). @@ -603,8 +596,7 @@ def _build(model, hf_config, ctx) -> DraftLayersOnChain: ), features=frozenset({Feature.SPECULATIVE_DECODING}), numerics=NUMERICS, - # 0 (unset flag): SGLang does not wrap the draft's forward - max_rows=ROWS if ENABLED else 0, + max_rows=ROWS, build=_build, api_version=target.SPEC.api_version, ) diff --git a/sgl_nvidia_mega/kimi_k31/dsa/split.py b/sgl_nvidia_mega/kimi_k31/dsa/split.py index bcdadf3c..0b422d0d 100644 --- a/sgl_nvidia_mega/kimi_k31/dsa/split.py +++ b/sgl_nvidia_mega/kimi_k31/dsa/split.py @@ -14,8 +14,6 @@ import torch -from sgl_nvidia_mega.kimi_k31.k3.default_scope import best_default - # Names read from SGLang. A contract test checks these before GPU use. SGLANG_READS = { "kernels/ops/attention/dsa/paged_mqa_logits.py": ("_restore_row_stride",), @@ -25,9 +23,9 @@ PAGE, PAGE_BITS, TOPK = 64, 6, 2048 # Context guard: split a forward only when its longest causal length reaches this; below it the replicated -# path is faster (the split's local logits + top-k + merge are a fixed cost). 320000 by default in -# the GB300 BEST scope, kimi_k31/k3/default_scope.py; 0 (the default elsewhere): never split. -SPLIT_MIN = int(best_default("K31MK_INDEX_SPLIT_MIN", "320000", "0")) +# path is faster (the split's local logits + top-k + merge are a fixed cost). Measured crossover: 16-rank merge +# unit B1 on GB300: +5.8 us/layer at 134K, ~0 at 338K, -13 us/layer at 600K; prepare-early moved it to 320000. +SPLIT_MIN = 320000 # Rows longer than this run the clustered candidate top-k (16384 beats 8192 at 8.4K local). CLUSTER_FLOOR = 16384 # The clustered top-k's coarse bin width. At 10 bits ~5 % of real AgentX local rows overflow the 2048-entry tie diff --git a/sgl_nvidia_mega/kimi_k31/dsa/verify.py b/sgl_nvidia_mega/kimi_k31/dsa/verify.py index 18a710f7..ebd6bf14 100644 --- a/sgl_nvidia_mega/kimi_k31/dsa/verify.py +++ b/sgl_nvidia_mega/kimi_k31/dsa/verify.py @@ -25,7 +25,6 @@ from sglang.srt.distributed.parallel_state import in_the_same_node_as from sglang.srt.runtime_context import get_parallel -from sgl_nvidia_mega.kimi_k31.k3.default_scope import best_default from sgl_nvidia_mega.kimi_k31.sm103.k3.common.host import fake, layout, stream, to_cute from sgl_nvidia_mega.kimi_k31.sm103.k3.mla.value import MlaValue @@ -107,11 +106,11 @@ def _direct_query_state(group, device): @cache -def _padded_value( - rows, heads, pitch, weight_layout, device, q, latent_heads=16, early=False -): +def _padded_value(rows, heads, pitch, weight_layout, device, q, latent_heads=16): """Read the real heads directly from the sparse core's ``latent_heads``-head output - (16: the padded DCP1 core; ``heads``: the merged DCP rows).""" + (16: the padded DCP1 core; ``heads``: the merged DCP rows). MlaValue releases its PDL + dependent (the o-proj) at entry, so the o-proj's whole weight preload overlaps the core + (bitwise: the o-proj still waits for MlaValue's grid).""" latent = fake((rows, heads, 512), (latent_heads * 512, 512, 1)) weight = fake(*weight_layout) gate = fake((rows, heads * 128), (pitch, 1)) @@ -119,7 +118,7 @@ def _padded_value( output = fake((rows, heads * 128)) with torch.accelerator.device_index(device): return cute.compile( - MlaValue(heads, rows, q, early_trigger=early), + MlaValue(heads, rows, q, early_trigger=True), latent, weight, gate, @@ -200,19 +199,6 @@ def validate(self, *, auxiliary_width=None): # multicast each rank's 12 FP8 heads directly into the core's 128-head layout. DSA_DIRECT_QAG = os.environ.get("K31MK_DSA_DIRECT_QAG", "0") == "1" _DIRECT_QAG_LOGGED = [] -# ``K31MK_MLAQ_AFTER_SCORING`` (off by default; 1 = on), DCP1 steps on the stock scoring only -# (not DCP, not the context-split indexer): the MLA query waits for the indexer scoring (DeepGEMM paged logits) and -# runs beside the top-k instead of beside the logits. The logits launch one persistent CTA per SM on a static schedule, -# so the MLA query's resident CTAs held some of them back (on VR200 the logits ran slower beside it than alone); the -# query is off the chain and ends before the top-k (a shorter span per layer). Same kernels and inputs: a -# reorder; the MLA query still precedes the query copy and the sparse core in main's program order. -MLAQ_AFTER_SCORING = os.environ.get("K31MK_MLAQ_AFTER_SCORING", "0") == "1" -_MLAQ_AFTER_LOGGED = [] -# ``K31MK_MLA_VALUE_EARLY_TRIGGER`` (on by default in the GB300 BEST scope, kimi_k31/k3/default_scope.py; 0 = off): the sparse verify MlaValue releases its PDL dependent (the o-proj) at entry, -# so the o-proj's whole weight preload overlaps the core instead of a part of it (bitwise: the o-proj still -# waits for MlaValue's grid); 0 triggers after MlaValue's own wait. -VALUE_EARLY_TRIGGER = best_default("K31MK_MLA_VALUE_EARLY_TRIGGER", "1", "0") != "0" -_VALUE_TRIGGER_LOGGED = [] def dcp_layout(): @@ -261,11 +247,10 @@ def row_table(self, table, q): rows.view(b, q, pages).copy_(table.unsqueeze(1).expand(b, q, pages)) return rows - def run(self, query, gates, cache, table, step, scored=None, collective_after=None): - """``scored``: an event recorded on the current stream once the scoring is enqueued, before the top-k (the - stock scoring only; the caller passes None on the context-split path). ``collective_after``: DCP only, an - event the cross-rank selection waits for after the scoring is enqueued (K31MK_DSA_EARLY_QAG: the query - all-gather on main), so every rank issues its DCP collectives in the same order.""" + def run(self, query, gates, cache, table, step, collective_after=None): + """``collective_after``: DCP only, an event the cross-rank selection waits for after the scoring is enqueued + (K31MK_DSA_EARLY_QAG: the query all-gather on main), so every rank issues its DCP collectives in the same + order.""" import deep_gemm from sglang.kernels.ops.attention.dsa.paged_mqa_logits import ( _restore_row_stride, @@ -294,8 +279,6 @@ def run(self, query, gates, cache, table, step, scored=None, collective_after=No clean_logits=False, ) scores = _restore_row_stride(scores) - if scored is not None: - scored.record() if step.dcp_size > 1: if collective_after is not None: torch.cuda.current_stream(scores.device).wait_event(collective_after) @@ -367,7 +350,6 @@ def __init__(self, base, weights, rows, max_context, split=None, *, scratch=None self.sparse_values = {} self.index_cache = None self.step = None - self._scored = torch.cuda.Event() if MLAQ_AFTER_SCORING else None # DCP: every rank's core runs all TP x heads over the keys it owns, then the rows # LSE-merge back to their head owners (built when the attention group is DCP). self.dcp_size = dcp_layout()[0] @@ -407,19 +389,6 @@ def __init__(self, base, weights, rows, max_context, split=None, *, scratch=None def __getattr__(self, name): return getattr(self.base, name) - def _query_after_scoring(self, mq, query_args, s): - """K31MK_MLAQ_AFTER_SCORING: the MLA query on the main stream behind the scoring's event, so it runs beside the - top-k; it still precedes the query copy and the sparse core (and its KV rows the core reads) in main's program - order.""" - torch.cuda.current_stream(self.base.device).wait_event(self._scored) - mq(*query_args, s) - if not _MLAQ_AFTER_LOGGED: # use-time, once per process - _MLAQ_AFTER_LOGGED.append(True) - logger.info( - "NVIDIA megakernel: K31MK_MLAQ_AFTER_SCORING engaged (the MLA query waits for the indexer " - "scoring and runs beside the top-k; DCP1 sparse verify)" - ) - @property def latent(self): if self.step is not None and self.step.sparse: @@ -441,15 +410,7 @@ def prepare_cache(self, cache, *, prepare_base=True): layout(self.base.weights[4]), self.base.device.index, q, - early=VALUE_EARLY_TRIGGER, ) - if ( - VALUE_EARLY_TRIGGER and not _VALUE_TRIGGER_LOGGED - ): # once per process, not per layer - _VALUE_TRIGGER_LOGGED.append(True) - logger.info( - "NVIDIA megakernel: sparse verify MlaValue releases the o-proj at entry (opt-in)" - ) if self.cp_mla is not None: # the merged rows hold this rank's heads only self.cp_values[rows, q] = _padded_value( rows, @@ -459,7 +420,6 @@ def prepare_cache(self, cache, *, prepare_base=True): self.base.device.index, q, latent_heads=self.base.heads, - early=VALUE_EARLY_TRIGGER, ) return self @@ -570,14 +530,7 @@ def run( # The packed writer runs ahead of the index query on the index stream; otherwise the gate stream writes the gate. if not self.packed_index_gate: self.index_stream.wait_stream(self.gate_stream) - # DCP and the context-split indexer keep today's order (their collectives and gathers are untouched). - after = ( - MLAQ_AFTER_SCORING - and not dcp - and not (self.selection.split is not None and step.split) - ) - if not after: - mq(*args, *b.query_views, s) + mq(*args, *b.query_views, s) early = dcp and self.early_gather(rows) if early: # main: right behind the MLA query it gathers; overlaps the indexer chain below self.gather_query(b.query_scratch[:rows], rows) @@ -594,7 +547,6 @@ def run( self.index_cache, block_table, step, - scored=self._scored if after else None, collective_after=self._q_gathered if early else None, ) if dcp and not early: @@ -602,8 +554,6 @@ def run( # collective at a time (no concurrent NCCL fallbacks on the group). self.index_stream.wait_stream(main) self.gather_query(b.query_scratch[:rows], rows) - if after: # before the query copy below, which reads the MLA query's output - self._query_after_scoring(mq, (*args, *b.query_views), s) if not dcp: # Copy before joining the indexer, so this independent work overlaps it. self.mla.prepare_query(b.query_scratch[:rows]) @@ -777,12 +727,10 @@ def __init__(self, weights, deadline_s): def _build_split(self, device, context_length): """The context-split indexer (a collective: every TP rank builds the merge's symmetric buffer), or {} - (an empty split keeps every step on the replicated indexer): K31MK_INDEX_SPLIT_MIN=0, a context length - below it, and by default DCP or no usable 16-rank merge, which an explicit K31MK_INDEX_SPLIT_MIN refuses.""" + (an empty split keeps every step on the replicated indexer): a context length below SPLIT_MIN, DCP (it + scores the replicated index-K cache) or no usable 16-rank merge.""" from .split import SPLIT_MIN, LocalIndexer, SplitMerge - if not SPLIT_MIN: - return {} if context_length < SPLIT_MIN: # no forward reaches it logger.info( "NVIDIA megakernel: sparse verify context split off: context length %d < %d", @@ -790,12 +738,7 @@ def _build_split(self, device, context_length): SPLIT_MIN, ) return {} - explicit = "K31MK_INDEX_SPLIT_MIN" in os.environ if dcp_layout()[0] > 1: - if explicit: - raise RuntimeError( - "K31MK_INDEX_SPLIT_MIN needs the replicated index-K cache; it is set under DCP" - ) logger.info( "NVIDIA megakernel: sparse verify context split off: DCP (it scores the replicated " "index-K cache)" @@ -806,10 +749,6 @@ def _build_split(self, device, context_length): group = get_tp_group() merge = SplitMerge(group, max(self.widths)) if not merge.usable(max(self.widths)): - if explicit: # the arm must not run the replicated path unnoticed - raise RuntimeError( - "K31MK_INDEX_SPLIT_MIN is set but the 16-rank DCP top-k merge is unavailable" - ) logger.info( "NVIDIA megakernel: sparse verify context split off: the 16-rank DCP top-k merge is " "unavailable (TP %d)", diff --git a/sgl_nvidia_mega/kimi_k31/k3/default_scope.py b/sgl_nvidia_mega/kimi_k31/k3/default_scope.py deleted file mode 100644 index 0feabe0e..00000000 --- a/sgl_nvidia_mega/kimi_k31/k3/default_scope.py +++ /dev/null @@ -1,57 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Where the GB300 BEST levers are on by default: the configuration the GB300 BESTs ran (AgentX and 8K), -TP16, DCP1, DFLASH Q8 and one running request, so every verify step is one 8-row request. Elsewhere an unset lever -keeps its earlier default; a set env always wins. Read from SGLang's published config, which the plugin's modules see -when the worker imports them at the megakernel build; without it (tools, tests) out of scope.""" - -from __future__ import annotations - -import os - -# Names read from SGLang. A contract test checks these before GPU use. -SGLANG_READS = { - "srt/runtime_context.py": ( - "get_context", - "get_parallel", - "get_schedule", - "get_spec", - ), -} - -_SCOPE: list = [] # [in scope], once the config is published - - -def in_scope() -> bool: - if _SCOPE: - return _SCOPE[0] - try: - from sglang.srt.runtime_context import ( - get_context, - get_parallel, - get_schedule, - get_spec, - ) - - if not all( - get_context().is_config_namespace_published(n) for n in ("schedule", "spec") - ): - return False - parallel = get_parallel() - scope = ( - int(parallel.tp_size) == 16 - and int(parallel.attn_dcp_size or 1) == 1 - and int(get_spec().speculative_num_draft_tokens or 0) == 8 - and int(get_schedule().max_running_requests or 0) == 1 - ) - except Exception: # noqa: BLE001 no SGLang context in this process - return False - _SCOPE.append(scope) - return scope - - -def best_default(name: str, best: str, default: str) -> str: - """``os.environ[name]`` when set, else ``best`` in scope, else the earlier ``default``.""" - value = os.environ.get(name) - if value is not None: - return value - return best if in_scope() else default diff --git a/sgl_nvidia_mega/kimi_k31/sm103/k3/attn_res/kernel.py b/sgl_nvidia_mega/kimi_k31/sm103/k3/attn_res/kernel.py index 57e1d10a..68e9d24b 100644 --- a/sgl_nvidia_mega/kimi_k31/sm103/k3/attn_res/kernel.py +++ b/sgl_nvidia_mega/kimi_k31/sm103/k3/attn_res/kernel.py @@ -28,7 +28,6 @@ wait, zeros, ) -from .aux import AuxMixture @cute.jit @@ -81,15 +80,12 @@ def __init__( final=False, deadline_ns=0, aux_mixture=False, - aux_launch=True, ): self.nb, self.slots, self.has_delta = nb, slots, has_delta self.write, self.final = write, final self.deadline_ns = deadline_ns + # With saved blocks the caller runs AuxMixture for the aux rows (PreparedAttnRes.bind_aux, a side stream). self.aux_mixture = aux_mixture - self.aux_launch = ( - aux_launch # False: the caller launches AuxMixture itself (side stream) - ) self.npre = 2 * nb self.npost = 2 if nb else 1 self.kpre = 1 << max(self.npre - 1, 0).bit_length() @@ -98,8 +94,6 @@ def __init__( @cute.jit def __call__(self, *args): launch(self.kernel, args, (7, args[1].shape[0], 1), 128, 7) - if cutlass.const_expr(self.aux_mixture and self.nb > 0 and self.aux_launch): - AuxMixture(self.nb)(*args) @cute.jit def exchange( diff --git a/sgl_nvidia_mega/kimi_k31/sm103/k3/attn_res/prepared.py b/sgl_nvidia_mega/kimi_k31/sm103/k3/attn_res/prepared.py index dcd8ccf2..b7337816 100644 --- a/sgl_nvidia_mega/kimi_k31/sm103/k3/attn_res/prepared.py +++ b/sgl_nvidia_mega/kimi_k31/sm103/k3/attn_res/prepared.py @@ -58,7 +58,6 @@ def compile_consumer( deadline_ns, aux=False, mixture=False, - aux_launch=True, ): kernel = ClusterAttnRes( nb, @@ -68,7 +67,6 @@ def compile_consumer( final=final, deadline_ns=deadline_ns, aux_mixture=mixture, - aux_launch=aux_launch, ) args = _consumer_args(slots, cap, aux) return cute.compile(kernel, *args, make_fake_stream(), options=f"--gpu-arch={arch}") @@ -98,10 +96,10 @@ def __init__(self, weights, key, eps, deadline_ns): None # (plain, ring) AuxMixture codes when it runs on a side stream ) - def _compile(self, slots, cap, aux=False, mixture=False, aux_launch=True): + def _compile(self, slots, cap, aux=False, mixture=False): arch = architecture(self.device) return compile_consumer( - *self.key, slots, cap, arch, self.deadline_ns, aux, mixture, aux_launch + *self.key, slots, cap, arch, self.deadline_ns, aux, mixture ) @classmethod @@ -123,17 +121,20 @@ def bind_ring(self, mailbox): shape = tuple(mailbox.shape[:2]) self.ring = self._compile(*shape), to_cute(mailbox), shape - def bind_aux(self, *, mixture=False, side=False): - """Variants that also store the updated prefix rows (a stock aux stream). ``side``: a - mixture over saved blocks runs on a side stream after the main kernel (``join_aux``).""" - side = side and mixture and self.key[0] > 0 + def bind_aux(self): + """Variants that also store the DFlash capture layer's aux row: the stock FP32 aux mixture + (AuxMixture) of the updated prefix row and the saved blocks. With saved blocks the mixture runs + on a side stream after the main kernel, since the next in-projection does not read it; it is + joined (``join_aux``) before the next writer of the rows it reads (the o-proj's fused AttnRes, + the next consumer) and at the end of the step. Same kernels and inputs: bitwise.""" + side = self.key[0] > 0 arch, ring, side_ring = architecture(self.device), None, None if self.ring is not None: slots, cap = self.ring[2] - ring = self._compile(slots, cap, True, mixture, not side) + ring = self._compile(slots, cap, True, True) if side: side_ring = compile_aux_mixture(self.key[0], slots, cap, arch) - self.aux = self._compile(0, 0, True, mixture, not side), ring + self.aux = self._compile(0, 0, True, True), ring if side: self.aux_side = compile_aux_mixture(self.key[0], 0, 0, arch), side_ring diff --git a/sgl_nvidia_mega/kimi_k31/sm103/k3/moe/experts.py b/sgl_nvidia_mega/kimi_k31/sm103/k3/moe/experts.py index 663bc126..74b10b47 100644 --- a/sgl_nvidia_mega/kimi_k31/sm103/k3/moe/experts.py +++ b/sgl_nvidia_mega/kimi_k31/sm103/k3/moe/experts.py @@ -9,8 +9,6 @@ import cutlass.cute as cute from cutlass import Float32, Int8, Int16, Int32, Int64, Uint8, Uint32, Uint64 -from sgl_nvidia_mega.kimi_k31.k3.default_scope import best_default - from ..common.primitives import ( acquire_tensormap, alloc, @@ -183,18 +181,6 @@ def plan_b8(tp, batch): return tp == 8 and batch == 8 -# vLLM's copy of this engine (nightly e4a5b55) launches without the cooperative attribute -# to keep the PDL prologue overlap ("1-2% decode at B4-B8" in its docstring); the grid -# must still be co-resident, which ``PersistentExperts.prepare`` checks. Read when a -# kernel is compiled; dropped by default in the GB300 BEST scope (default_scope.py), ``K31MK_EXPERTS_COOPERATIVE=1`` -# keeps it. -COOPERATIVE = "K31MK_EXPERTS_COOPERATIVE" - - -def cooperative(): - return best_default(COOPERATIVE, "0", "1") != "0" - - @cute.jit def plan_chunk(plan, token, chunk, words, fp32: cutlass.Constexpr = False): """Write 8-element ``chunk`` (four BF16x2 ``words``) of ``token`` as MXFP8 into @@ -330,9 +316,10 @@ def fc2_pairs(tp, capacity, streamed): class ExpertsKernel(ExpertsGeometry): """The engine for one capacity and persistent grid. CTAs wait on other clusters' - partials (``load_hidden``, ``partials``, ``finalize``), so the grid launches - cooperatively (unless ``COOPERATIVE`` is 0) and ``PersistentExperts.prepare`` checks - it is co-resident. + partials (``load_hidden``, ``partials``, ``finalize``), so ``PersistentExperts.prepare`` + checks the grid is co-resident. It launches without the cooperative attribute, as vLLM's + copy of this engine (nightly e4a5b55) does, to keep the PDL prologue overlap; a co-resident + grid cannot deadlock on those waits. ``publish`` stages FC2 rows for ``finalize``: routing weights replace the output arg, and (latent multicast, parity, rank) follow the SiTU scalars; ``"twoshot"``: (receive slots [3 x TP, 64, 3584/TP], their owners' bases, parity x TP + rank) of @@ -362,7 +349,6 @@ def __init__( self.grain, self.zone, self.victims = (1 if self.paired else 3, 8, 3) self.threads = 384 self.capacity, self.experts, self.grid = (capacity, experts, grid) - self.launch_options = {"cooperative": True} if cooperative() else {} self.publish = publish assert not self.grouped or grid >= capacity <= 64 # CTAs [0, MAX_CTAS - grid) also advance entries [grid, MAX_CTAS) of the per-CTA @@ -1504,7 +1490,7 @@ def epilogue(self, sm, workspace, output, tmem, ranges, batch, parity, scalars): @cute.jit def __call__(self, *args): - launch(self.kernel, args, self.grid, 384, cluster=1, **self.launch_options) + launch(self.kernel, args, self.grid, 384, cluster=1) @cute.jit def initialize(self, sm, maps, batch): diff --git a/sgl_nvidia_mega/kimi_k31/sm103/k3/moe/experts_runtime.py b/sgl_nvidia_mega/kimi_k31/sm103/k3/moe/experts_runtime.py index 4de582b7..a325a633 100644 --- a/sgl_nvidia_mega/kimi_k31/sm103/k3/moe/experts_runtime.py +++ b/sgl_nvidia_mega/kimi_k31/sm103/k3/moe/experts_runtime.py @@ -23,14 +23,12 @@ ExpertsGroupKernel, ExpertsKernel, ExpertsPlanKernel, - cooperative, fc2_pairs, plan_b8, ) logger = logging.getLogger(__name__) _PLAN_B8_LOGGED = [] -_NONCOOP_LOGGED = [] _PREWAIT_LOGGED = [] @@ -223,9 +221,6 @@ def prepare( if planned_b8 and not _PLAN_B8_LOGGED: # once, not per layer _PLAN_B8_LOGGED.append(True) logger.info("NVIDIA megakernel: TP8 B8 routed experts read the plan") - if not cooperative() and not _NONCOOP_LOGGED: # engagement tag for A/B runs - _NONCOOP_LOGGED.append(True) - logger.info("NVIDIA megakernel: routed experts launch non-cooperatively") if not grouped and not _PREWAIT_LOGGED: _PREWAIT_LOGGED.append(True) logger.info( diff --git a/sgl_nvidia_mega/kimi_k31/sm103/k3/oproj/consumer.py b/sgl_nvidia_mega/kimi_k31/sm103/k3/oproj/consumer.py index 0c0e7c42..8dc3ad8e 100644 --- a/sgl_nvidia_mega/kimi_k31/sm103/k3/oproj/consumer.py +++ b/sgl_nvidia_mega/kimi_k31/sm103/k3/oproj/consumer.py @@ -5,10 +5,11 @@ consumer. With ``twoshot`` the mailbox is the one-slot gather row of ``common.twoshot``: the threads owning this rank's columns first reduce their receive slots into it (args 11-13: receive view, gather multicast address, rank). -With ``norm_fold`` (``K31MK_OPROJ_NORM_FOLD``, AttnRes layers) the -final RMS norm comes from exchange 1 instead of its own cluster exchange: exchange 1 -also carries |mix|^2 and , and |final|^2 = a^2 |mix|^2 + 2 a e -+ e^2 |prefix|^2 for final = a mix + e prefix (exact in real arithmetic, not bitwise).""" +With saved blocks (nb > 0) the final RMS norm comes from exchange 1 instead of its own +cluster exchange: exchange 1 also carries |mix|^2 and , and |final|^2 = +a^2 |mix|^2 + 2 a e + e^2 |prefix|^2 for final = a mix + e prefix (exact in +real arithmetic, not bitwise). The fold is per token within the 7-CTA cluster, so it holds +for any TP.""" import cutlass import cutlass.cute as cute @@ -42,7 +43,6 @@ ) from ..common.primitives import wait_phase_zero_cluster as wait_phase_zero from ..common.primitives import ( - warp_sum, zeros, ) from ..common.twoshot import reduce @@ -122,7 +122,6 @@ def __init__( groups=4, twoshot=False, deadline_ns=0, - norm_fold=False, ): if not 0 <= nb <= 8: raise ValueError("Output-projection AttnRes supports zero to eight blocks") @@ -130,8 +129,7 @@ def __init__( self.groups, self.twoshot = groups, twoshot self.deadline_ns = deadline_ns self.kpre = 1 << max(0, (2 * nb - 1).bit_length()) - self.norm_fold = norm_fold and nb > 0 # nb == 0 has no second exchange - self.npost = 4 if self.norm_fold else 2 if nb > 0 else 1 + self.npost = 4 if nb > 0 else 1 @cute.jit def wait_exchange(self, barrier): @@ -145,18 +143,15 @@ def allocate(self): blk = alloc(smem, Float32, 16) post = alloc(smem, Float32, (7, 4, 4)) total = alloc(smem, Float32, 4) - bars = alloc(smem, cutlass.Uint64, 3, 8) + bars = alloc(smem, cutlass.Uint64, 2, 8) parts = alloc(smem, Float32, (max(1, self.groups - 1), 2, 128, 4)) lean = self.groups == 1 # above B8: rows for this nb only (co-residency) pf = alloc(smem, Uint32, (4 + self.nb if lean else 12, 128, 4)) - norm_post = alloc(smem, Float32, (7, 4)) - norm_total = alloc(smem, Float32, 1) - return wpre, pre, blk, post, total, bars, parts, pf, norm_post, norm_total + return wpre, pre, blk, post, total, bars, parts, pf @cute.jit def setup(self, bars): - final_norm = self.nb > 0 and not self.norm_fold - arm_exchanges(bars, (2 * self.nb, 4 * self.npost, 4 if final_norm else 0)) + arm_exchanges(bars, (2 * self.nb, 4 * self.npost)) cute.arch.cluster_arrive_relaxed() @cute.jit @@ -303,8 +298,7 @@ def publish(self, output, xmoe, hints, token, h, values): @cute.jit def post(self, args, state, block_mix, rank, token): mailbox, prefix, _, _, _, _, output, xmoe, hints, eps, out_eps = args[:11] - _, _, _, post, total, bars, parts, pf = state[:8] - norm_post, norm_total = state[8:] + _, _, _, post, total, bars, parts, pf = state mix, maximum, exponent_sum, qpart = block_mix thread, _, _ = cute.arch.thread_idx() group, tid = thread // 128, thread % 128 @@ -361,9 +355,8 @@ def post(self, args, state, block_mix, rank, token): weight = self.combined_weight(pf, tid) partial[0] = dot8(prefix_value, prefix_value) partial[1] = dot8(prefix_value, weight) - if cutlass.const_expr(self.norm_fold): - partial[2] = qpart # dot8(mix, mix) from ``pre`` - partial[3] = dot8(mix, prefix_value) + partial[2] = qpart # dot8(mix, mix) from ``pre`` + partial[3] = dot8(mix, prefix_value) else: partial[0] = dot8(prefix_value, prefix_value) idx = reduce_scatter(partial, self.npost, lane) @@ -398,32 +391,12 @@ def post(self, args, state, block_mix, rank, token): p = pair_op((ep, ep), two(prefix_value, j), op="mul") value = pair_op((alpha, alpha), two(mix, j), p, op="fma") final[2 * j], final[2 * j + 1] = value[0], value[1] - if cutlass.const_expr(self.norm_fold): - # |a mix + e prefix|^2 from exchange 1's cluster sums; clamped at 0 - # (rounding under strong mix / prefix cancellation). - cross = mul_rn(Float32(2), mul_rn(alpha, ep)) - quad = fma(cross, total[3], mul_rn(mul_rn(ep, ep), total[0])) - quad = fma(mul_rn(alpha, alpha), total[2], quad) - norm_sq = cute.arch.fmax(quad, Float32(0)) - else: - square = warp_sum(dot8(final, final)) - if lane == 0: - for peer in cutlass.range_constexpr(7): - push_float( - at(norm_post, rank, warp), - square, - bars.iterator + 2, - peer, - ) - self.wait_exchange(bars.iterator + 2) - if tid == 0: - sums = [Float32(0)] * 4 - for peer in cutlass.range_constexpr(7): - for w in cutlass.range_constexpr(4): - sums[w] = add_rn(sums[w], norm_post[peer, w]) - norm_total[0] = tree_reduce(sums, add_rn) - named_barrier() - norm_sq = norm_total[0] + # |a mix + e prefix|^2 from exchange 1's cluster sums; clamped at 0 + # (rounding under strong mix / prefix cancellation). + cross = mul_rn(Float32(2), mul_rn(alpha, ep)) + quad = fma(cross, total[3], mul_rn(mul_rn(ep, ep), total[0])) + quad = fma(mul_rn(alpha, alpha), total[2], quad) + norm_sq = cute.arch.fmax(quad, Float32(0)) inverse = cute.arch.rcp_approx(den) scale = mul_rn( inverse, @@ -460,10 +433,10 @@ def kernel(self, args): class OprojFused: - def __init__(self, nb, *, has_delta=True, norm_fold=False): + def __init__(self, nb, *, has_delta=True): self.producer = OprojProducer(768, staged_blocks=0) # TP16 requires prefix/blocks to be ready at launch. - self.consumer = OprojConsumer(nb, has_delta=has_delta, norm_fold=norm_fold) + self.consumer = OprojConsumer(nb, has_delta=has_delta) @cute.jit def __call__(self, *args): diff --git a/sgl_nvidia_mega/kimi_k31/sm103/k3/oproj/prepared.py b/sgl_nvidia_mega/kimi_k31/sm103/k3/oproj/prepared.py index f0a56da8..c9f75849 100644 --- a/sgl_nvidia_mega/kimi_k31/sm103/k3/oproj/prepared.py +++ b/sgl_nvidia_mega/kimi_k31/sm103/k3/oproj/prepared.py @@ -7,10 +7,9 @@ At ``twoshot_batches``, given ``TwoShot`` buffers, the all-reduce is ``common.twoshot`` (chunks pushed to their column owner, owner sums + multicasts, all Lamport-polled), so each GPU receives ~2 x 14 KB per token instead of TP x 14 KB. -``K31MK_OPROJ_NORM_FOLD=1`` (TP16; default off, not bitwise) folds AttnRes's final-norm -cluster exchange into the first one (``OprojConsumer``'s norm_fold).""" +The consumers fold AttnRes's final-norm cluster exchange into the first one (not bitwise; +``consumer``'s docstring).""" -import logging from functools import cache from typing import Any @@ -20,8 +19,6 @@ import torch.distributed._symmetric_memory as symm_mem from cutlass.cute.runtime import make_fake_stream -from sgl_nvidia_mega.kimi_k31.k3.default_scope import best_default - from ..common.host import dynamic_fake, dynamic_view, fake, stream, to_cute from ..common.policy import batch_table from .consumer import OprojConsumer, OprojFused @@ -79,33 +76,6 @@ def staged_blocks(batch, tp, mla): return 4 if mla or batch == 1 else 8 -logger = logging.getLogger(__name__) -_ENGAGED = set() - - -def _engaged(key, text): - """The engagement line of an opt-in knob, once per process (not per layer).""" - if key not in _ENGAGED: - _ENGAGED.add(key) - logger.info(text) - - -# On by default in the GB300 BEST scope, kimi_k31/k3/default_scope.py (0 = off), not bitwise: the AttnRes final norm from exchange 1. -OPROJ_NORM_FOLD = "K31MK_OPROJ_NORM_FOLD" - - -def norm_fold(tp): - """Whether the consumers fold the final-norm exchange (``OPROJ_NORM_FOLD``; TP16).""" - on = best_default(OPROJ_NORM_FOLD, "1", "0") not in ("", "0") and tp == 16 - if on: - _engaged( - "fold", - "NVIDIA megakernel: o-proj AttnRes final norm folded into exchange 1 " - "(K31MK_OPROJ_NORM_FOLD, not bitwise)", - ) - return on - - def producer(k, batch, tp, mla, twoshot=False, kind=None): """B<=8: one mma.sync pass staging ``staged_blocks`` of the K blocks in SMEM. Above B8 (``kind`` overrides ``engine``): the tcgen05 engine, or 2-tile warps over 8 K @@ -132,12 +102,10 @@ def compile_oproj( cap=64, twoshot=False, deadline_ns=0, - fold=False, ): """Producer, consumer or fused kernel over a [TP, cap, 7168] parity view; ``front``: the consumer also publishes x_moe [1, 4, 7168] and the epoch hint. - ``twoshot``: the two-shot pair (arguments as ``TwoShot.views``). ``fold``: the - consumers' final-norm fold (``norm_fold``), a compile key like every other knob.""" + ``twoshot``: the two-shot pair (arguments as ``TwoShot.views``).""" box = fake((1 if twoshot else tp, cap, 7168), (cap * 7168, 7168, 1)) x, w = fake((batch, k), (k, 1)), fake((7168, k), (k, 1)) mc, slot, eps = cutlass.Int64(0), cutlass.Int32(0), cutlass.Float32(1e-6) @@ -158,12 +126,11 @@ def compile_oproj( groups=groups, twoshot=twoshot, deadline_ns=deadline_ns, - norm_fold=fold, **options, ) extra = (recv, mc, slot) if twoshot else () return cute.compile(kernel, box, *rows, *extra, make_fake_stream()) - kernel = OprojFused(nb, has_delta=has_delta, norm_fold=fold) + kernel = OprojFused(nb, has_delta=has_delta) return cute.compile(kernel, x, w, box, mc, slot, *rows, make_fake_stream()) @@ -218,7 +185,6 @@ def __init__( 64, twoshot, deadline_ns, - norm_fold(tp) and kind != "producer", ) for kind in kinds ) diff --git a/sgl_nvidia_mega/kimi_k31/verify_executor.py b/sgl_nvidia_mega/kimi_k31/verify_executor.py index e4de8682..e6dc9baf 100644 --- a/sgl_nvidia_mega/kimi_k31/verify_executor.py +++ b/sgl_nvidia_mega/kimi_k31/verify_executor.py @@ -3,24 +3,15 @@ from __future__ import annotations -import logging from functools import partial import torch -from sgl_nvidia_mega.kimi_k31.k3.default_scope import best_default - from .sm103.k3.attn_res.prepared import join_aux from .sm103.k3.mla.verify_overlap import VerifyMlaIndexOverlap from .verify_binding import VerifyStepView from .verify_contract import verify_keys -logger = logging.getLogger(__name__) -# ``K31MK_AUX_SIDE_STREAM`` (on by default in the GB300 BEST scope, kimi_k31/k3/default_scope.py; 0 = off): at the DFlash capture layers the stock FP32 aux mixture (AuxMixture) -# runs on a side stream instead of between the AttnRes and the next in-projection, which -# does not read it; joined before the layer's o-proj (its fused AttnRes rewrites the prefix row the -# mixture reads), the next AttnRes, and the end of the step. Same kernels and inputs: bitwise. -AUX_SIDE_STREAM = best_default("K31MK_AUX_SIDE_STREAM", "1", "0") != "0" # The process's live executors: the buffer owners the draft chain's build checks its mailboxes against # (draft/serving.py, chain.DraftComm.assert_disjoint). INSTANCES: list = [] @@ -55,14 +46,8 @@ def __init__( consumer = ( resources.final if layer_id == 92 else resources.before[layer_id + 1] ) - consumer.bind_aux( - mixture=True, **({"side": True} if AUX_SIDE_STREAM else {}) - ) + consumer.bind_aux() self.capture_consumers[layer_id] = consumer - if AUX_SIDE_STREAM and self.capture_layers: - logger.info( - "NVIDIA megakernel: verify aux mixture on a side stream (K31MK_AUX_SIDE_STREAM)" - ) # Q rows use generic routing/dispatch even at c1. SmallBatchChain consumes # a B1-specific producer mailbox and cannot represent one Q-token request. for _, feed in resources.feed_forward.items(): @@ -126,10 +111,7 @@ def run(self, embeddings: torch.Tensor, view: VerifyStepView): core.run( projected, local, pools=self.kda_pools[layer_id], step=view.kda ) - if AUX_SIDE_STREAM: - join_aux( - torch.cuda.current_stream() - ) # the o-proj rewrites the prefix row + join_aux(torch.cuda.current_stream()) # the o-proj rewrites the prefix row attn.output.run(local, prefix, blocks, second) if attn.kind == "mla" and overlap is not None: # feed.run may overwrite first, including through fused consumers. @@ -148,8 +130,6 @@ def run(self, embeddings: torch.Tensor, view: VerifyStepView): first, second = second, first if not ready: res.final.run(hidden, prefix, blocks, output, aux=self._aux(view, 92)) - if AUX_SIDE_STREAM: - join_aux( - torch.cuda.current_stream() - ) # the draft reads aux_hidden after the step + # The draft reads aux_hidden after the step. + join_aux(torch.cuda.current_stream()) return output, view.aux_hidden diff --git a/test/unit/test_kimi_k31_split_merge.py b/test/unit/test_kimi_k31_split_merge.py index bc1b2f12..810d82ac 100644 --- a/test/unit/test_kimi_k31_split_merge.py +++ b/test/unit/test_kimi_k31_split_merge.py @@ -86,6 +86,70 @@ def test_declined_factory_remains_unusable(self): merge.run(None, None, None, None) +class SplitArming(unittest.TestCase): + """``BuiltSparseVerify._build_split``: the split arms from the measured crossover on; below it, under DCP + and without a usable merge it declines (an empty split).""" + + def build_split(self, context_length, dcp=1, usable=True): + node = next( + n + for n in ast.parse((ROOT / "verify.py").read_text()).body + if isinstance(n, ast.ClassDef) and n.name == "BuiltSparseVerify" + ) + method = next(n for n in node.body if getattr(n, "name", "") == "_build_split") + from sgl_nvidia_mega.kimi_k31.dsa import split as real + + built = [] + split = types.ModuleType("split_test.dsa.split") + split.SPLIT_MIN = real.SPLIT_MIN + split.LocalIndexer = lambda device, **kw: built.append(kw) or "local" + merge = types.SimpleNamespace(usable=lambda rows: usable) + split.SplitMerge = lambda group, rows: built.append(rows) or merge + group = types.SimpleNamespace(world_size=16, rank_in_group=3) + host = types.ModuleType("sglang.srt.distributed.parallel_state") + host.get_tp_group = lambda: group + scope = { + "__package__": "split_test.dsa", + "logger": types.SimpleNamespace(info=lambda *a: None), + "dcp_layout": lambda: (dcp, 0), + } + exec( + compile(ast.Module(body=[method], type_ignores=[]), "verify.py", "exec"), + scope, + ) + owner = types.SimpleNamespace(widths=(8, 16), query_width=8) + modules = { + "split_test": types.ModuleType("split_test"), + "split_test.dsa": types.ModuleType("split_test.dsa"), + split.__name__: split, + host.__name__: host, + } + with patch.dict(sys.modules, modules): + return scope["_build_split"](owner, "cuda:0", context_length), built + + def test_the_threshold_is_the_measured_crossover(self): + from sgl_nvidia_mega.kimi_k31.dsa.split import SPLIT_MIN + + self.assertEqual(SPLIT_MIN, 320000) + + def test_it_arms_from_the_crossover_and_declines_where_it_cannot_run(self): + armed, built = self.build_split(320000) + self.assertEqual(sorted(armed), [8, 16]) + self.assertEqual(armed[8][0], "local") + self.assertEqual(built[0], 16) # the merge is sized for the widest step + self.assertEqual( + [(kw["requests"], kw["world"], kw["rank"]) for kw in built[1:]], + [(1, 16, 3), (2, 16, 3)], + ) + for name, args in { + "below the crossover": (319999,), + "DCP": (320000, 8), + "no usable merge": (320000, 1, False), + }.items(): + with self.subTest(name): + self.assertEqual(self.build_split(*args)[0], {}) + + if __name__ == "__main__": unittest.main()