Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 3 additions & 8 deletions docs/models/kimi_k31.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
46 changes: 19 additions & 27 deletions sgl_nvidia_mega/kimi_k31/draft/serving.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand All @@ -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,
Expand All @@ -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):
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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,
)
8 changes: 3 additions & 5 deletions sgl_nvidia_mega/kimi_k31/dsa/split.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",),
Expand All @@ -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
Expand Down
85 changes: 12 additions & 73 deletions sgl_nvidia_mega/kimi_k31/dsa/verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -107,19 +106,19 @@ 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))
lengths = fake((rows // q,), (1,), torch.int32, 4)
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,
Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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:
Expand All @@ -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,
Expand All @@ -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

Expand Down Expand Up @@ -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)
Expand All @@ -594,16 +547,13 @@ 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:
# After the selection's candidate gather on this stream: one DCP-group
# 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])
Expand Down Expand Up @@ -777,25 +727,18 @@ 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",
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)"
Expand All @@ -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)",
Expand Down
Loading
Loading