Skip to content

Commit 5aeb11a

Browse files
wenscarlb8zhongclaudeDonglin Yang
authored
[Feat] [RUBIN] glm5_3/sm107: GLM-5.2 TP16 bs=1 megakernels and EAGLE v2 step CUDA graph (spec_step) (#19)
* [Feat] [GB300/Rubin] glm_dsa, spec_step: GLM-5 DSA fused verify and NextN draft; EAGLE v2 step CUDA graph - glm_dsa: target verify (4-16 rows) and NextN draft/draft-extend megakernel specs for GlmMoeDsaForCausalLM on SM103 and SM107 (TP8, NVFP4 MoE). - spec_step: one CUDA graph per EAGLE v2 topk-1 decode step plus bitwise- identical spec fusions, installed via HookRegistry behind env switches. * [Fix] spec_step: keep the step graph on torch 2.14 and make lifted.py importable - hooks.py: torch 2.14's `_CUDAGraph` binding reads `keep_graph` in `__init__`, so overriding only `__new__` let a bare `torch.cuda.CUDAGraph()` drop its raw graph at capture end, and decode graph capture failed in cuGraphInstantiate with CUDA_ERROR_INVALID_VALUE. - lifted.py: defer annotations. `Tuple`, `Optional` and `torch` are bound only in the SGLang module each function is rebound into, so the first verify raised `NameError: Tuple`. - lifted.py: `eagle_sample` drops its inline sampler imports, which referenced `_is_npu` (removed from eagle_utils by sgl-project/sglang#45504), and uses eagle_utils' module names. - lifted.py: `_draft_extend_for_decode` passes `sampling_seed=` and `positions=` again, as current SGLang does. Tested on 8x B300, GLM-5.3-NVFP4, TP8, EAGLE 3/1/4, SGLang f4a2df3dac, all spec_step switches on. * [Fix] glm_dsa: accept --speculative-algorithm NEXTN The construction check compared the raw server argument with EAGLE, so a NEXTN launch (the InferenceX GLM-5.3 B300 AgentX recipe) was refused with "speculative algorithm 'NEXTN' is not supported (EAGLE / NEXTN only)". NEXTN resolves to the same EAGLE worker; the spec's requirement and the spec_step runner already accept it. * [Perf] glm_dsa: split the verify path into packages; Rubin round-7 hop scheduling switches Split the GLM-5 DSA verify path into the attention/, boundary/, moe/ and runtime/ packages plus plan.py (runtime.py kept as runtime_legacy.py), and fix two leftovers of the split: a stray @DataClass in moe/__init__.py and a duplicated module header in boundary/__init__.py. The spec's model_disable_reasons now calls eligibility.model_construction_reasons with the HF config and the server arguments. Port two hop scheduling ideas from the TRT-LLM Rubin round-7 branch, both off by default and output-neutral: - SGLANG_NVIDIA_MEGAKERNEL_GLM_HOP_MAX_SHARED_CARVEOUT=1: every hop kernel prefers the maximum shared-memory carveout, so an SM a hop CTA lingers on can host the next layer's large-shared-memory kernels under PDL. - SGLANG_NVIDIA_MEGAKERNEL_GLM_HOP_CTAS_PER_SM=1|2: pad the o_proj consumer hop's launch shared memory (sized from the device's per-SM limits) so at most N CTAs share an SM while polling. Round 7's single-loop 16-slot polling does not apply: at 8 ranks the consumer already polls all sources in parallel. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * [Feat] glm_dsa: serve MTP with 5 draft steps (6 verify rows a request) Port #24's 5 / 1 / 6 support (3889557, 492aa0a, 77015e7) to the GLM-5 DSA specs, which served speculative_num_draft_tokens 4 / speculative_num_steps 3 only. - eligibility: SERVED_TOKENS_PER_REQUEST = (4, 6) and MAX_ROWS = 16; supported_rows(T) gives every whole number of requests up to 16 rows (T 4: 4 / 8 / 12 / 16, T 6: 6 / 12). The executor builds only the widths of the server's speculative_num_draft_tokens; the spec and Tier 1 refuse any other value or a pair with draft tokens != steps + 1, naming 4 / 3 and 6 / 5. - MoE: moe_split groups rows by 4 with the remainder last (6 -> (4, 2) on the two-group engine, 12 -> (4, 4, 4) on the four-group engine). - Draft: the eh_proj shard rows are the draft decode's 1-4 plus the covered widths (T 6: 1, 2, 3, 4, 6, 12). - One request at 6 rows keeps the fast forms: split MoE fold hop (SPLIT_MAX_ROWS 6), plain hops on dense layers (DENSE_MAX_ROWS 6) and the 16-warp sparse MLA up to 6 rows. Kernels unchanged. At T 4 every width, row map, eh row set and kernel form is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * [Fix] glm_dsa: run on released SGLang (megakernel API 2, multi-node TP8) - spec, draft_spec: API_VERSION 2; the built objects offer no EAGLE entries or graph variants (draft_loop, draft_extend, begin_draft_round, graph_variants are None). Restore the target's _Built (widths, summary, plan, forward), which the package split had dropped, so build returns a BuiltMegakernel again. - spec: accept Feature.MULTI_NODE_TP, so TP8 can span the two 4-GPU trays of an NVL72 rack, as the draft spec already does. - spec: drop the DsaView binding-member and EAGLE_DRAFT_CAPTURE_CHECK gates, which only an unmerged SGLang (sgl-project/sglang#46210) passes; the covered step reads the DSA backend through get_attn_backend() and never through those views. - attention: build the AttentionGlue directly (it has no build classmethod). - draft_spec: import the megakernel interface from its new location first. - glm_dsa, spec_step: declare every SGLang import in SGLANG_READS (the stricter contract test); import modules as modules (import a.b.c as c); name reads by the file that defines them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * [Fix] glm_dsa: name the NextN draft's architecture and pin its config fields draft_spec gets ARCHITECTURE and pins the fused draft layer's attention shapes and model_type (Requirements.hf_config), as test/unit/test_glm_dsa_config.py expects: a NextN config that differs in one of them is refused at load, naming it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * [Fix] glm_dsa: repair names lost in the package split (TP8 e2e on Rubin) - draft.py: read TARGET / tp_gather / per_rank from runtime.executor; runtime is now a package and no longer exports them. - attention/step.py, moe/step.py: restore @DataClass on StepContext and MoeRecords (capture failed with "StepContext() takes no arguments"). - moe/step.py, moe/__init__.py: import the shape constants, HIDDEN and MoeGlue where they are used; moe/__init__ re-exports from moe.step. - draft_attention.py: import AttentionGlue / FusedAttention / kernel_rows from attention.fused. Verified on two Rubin trays (TP8, --nnodes 2, dummy weights): the fused verify routes the decode graphs at 4/3/1 (bs 1-4) and 6/5/1 (bs 1-2), generate requests succeed; unit tests 582 passed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * [Feat] glm52/sm107: CuTeDSL megakernels for GLM-5.2 TP16 decode and MTP draft Adds sgl_nvidia_mega/glm52/sm107 (Rubin, sm_107a), enabled with GLM5MK=1 through the plugin. For bs=1 decode on agentx it reaches 1139 tok/s/user against stock SGLang's 352 (about 3.2x): - the 75-layer decoder chain runs as one kernel launched per layer with PDL overlap (MLA attention with the sparse indexer, NVFP4 MoE on tcgen05, cross-rank exchange over Lamport buffers); - dense layers 0-2, the MTP draft step and the fused verify/sampling tail replace the stock paths; - CuTeDSL ops keep the per-step bookkeeping (page table, post-verify, draft pages, tree layout) inside CUDA graph replay. Unit tests cover the hook-up, the kernel-tree import order and the ops against torch implementations. Co-Authored-By: Claude <noreply@anthropic.com> * [Refactor] glm52/sm107: drop the draft diagnostics, ablation and test knobs and the unused non-TMA EH load path Co-Authored-By: Claude <noreply@anthropic.com> * [Refactor] glm5_3/sm107: move the GLM-5.2 Rubin megakernels under glm5_3 Follow the model/<sm> layout of main's glm5_3/sm103: the TP16 bs=1 decode and MTP draft kernels move from glm52/sm107 to glm5_3/sm107. - add glm5_3/__init__.py, byte-identical to main's, so the package ships with setuptools' find_packages and merges with main without a conflict - rename the package, its error messages and the plugin hook-up (GLM52_TP16_ENV -> GLM5_3_SM107_ENV; the switch is still GLM5MK=1) - rename test/unit/test_glm52_sm107.py -> test_glm5_3_sm107.py - point the import-isolation test's PYTHONPATH at the repo root Kernel-internal outlined function names (glm52_*_piece) are unchanged so the compiled code stays identical to the validated build. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * [Cleanup] glm_dsa: remove the package superseded by glm5_3 After merging main, GlmMoeDsaForCausalLM and its NextN draft are registered to glm5_3, which covers the same model, GPUs and TP8 verify / draft steps, so nothing loads glm_dsa any more. Remove the package, its config test and its CODEOWNERS line. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * [Feat] glm5_3/sm107: serve TP16 through --enable-nvidia-megakernel The GLM-5.2 TP16 Rubin path is now selected by glm5_3's specs, with --enable-nvidia-megakernel as its only switch: - glm5_3/spec.py admits TP16 (sm_107 only) and dispatches by TP size: config_disable_reasons, model_disable_reasons and build go to sm107 at TP16. The TP8 / TP4 server arguments and environment move from Requirements (one per spec) to config_disable_reasons (per TP size), checked and worded as SGLang checks them. - glm5_3/draft.py: the NextN draft dispatches to sm107 at TP16. - sm107: build_target / build_draft pack the weights at build and bind the KV pools before the runner's CUDA graphs; the built megakernel plans one request's verify step (target) and draft steps (draft). sm107 pins its own validated server arguments and SGLANG_DSA_FUSE_TOPK. - Remove the GLM5MK switch, the sys.meta_path import hooks, the os._exit guards and root/sitecustomize.py. The cubin directory is SGLANG_NVIDIA_MEGAKERNEL_GLM_SM107_CUBINS, refused at argument resolution when unset or incomplete (no /glm5mk default). - Tolerate SGLang without dsa_backend.fused_dsa_target_verify_metadata. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * [Docs] glm5_3/sm107: state the steps the TP16 path does not cover Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * [Lint] Apply pre-commit (ruff, ruff-format, isort, codespell) Formatting only: ruff-format and isort over glm5_3/sm107 (mostly the kernels from #2), spec_step and the sm107 test. No statement changes: the ASTs match apart from import ordering, every module imports the same names, and the sm107 unit tests (including the CuTe DSL / GPU tests and the kernel-tree import order) pass on VR200. codespell: `arith.CmpFPredicate.OLT` (MLIR's ordered less-than) is marked `# codespell:ignore`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * [Test] glm5_3/sm107: ignore __pycache__ in the no-binaries check Any earlier test that imports the package writes git-ignored __pycache__/*.pyc under sm107, which this check flagged in CI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Brayden Zhong <184021590+b8zhong@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Donglin Yang <dongliny@nvidia.com>
1 parent bf98dd9 commit 5aeb11a

54 files changed

Lines changed: 28685 additions & 17 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/CODEOWNERS‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
**/*deepseek_v41* @YAMY1234
77
**/*qwen3_5* @YAMY1234
88
**/*kimi_k3* @leejnau
9+
**/*spec_step* @wenscarl
910
**/*kimi_k31* @Oasis-Git
1011
**/*glm5_3* @nvrohanv
1112
**/*muse_spark* @wenscarl @nvrohanv

‎README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,17 @@ with it; every other step runs SGLang's own code, and every rank logs
2121
| --- | --- | --- | --- | --- |
2222
| DeepSeek-V4.1-Flash | GB300; B300 | 4; 8 (MoE TP4 x EP2) | DSpark target verify and draft | [deepseek_v41](docs/models/deepseek_v41.md) |
2323
| Qwen3.5-397B-A17B (NVFP4) | GB300 | 8 | MTP target verify and EAGLE draft | [qwen3_5](docs/models/qwen3_5.md) |
24-
| GLM-5.3, GLM-5.2 (NVFP4) | B300, GB300, Rubin | 4; 8 | MTP target verify and NextN draft | [glm5_3](docs/models/glm5_3.md) |
24+
| GLM-5.3, GLM-5.2 (NVFP4) | B300, GB300, Rubin | 4; 8; 16 (GLM-5.2 on Rubin) | MTP target verify and NextN draft; at TP16 the whole one-request EAGLE step | [glm5_3](docs/models/glm5_3.md) |
2525
| Kimi K3 (MXFP4) | GB300; B300, B200, GB200 | 8 | Decode and fixed-width verify | [kimi_k3](docs/models/kimi_k3.md) |
2626
| Kimi K3.1 (MXFP4) | GB300; B300, B200, GB200 | 8; 16 | DFlash target verify and DFlash2 draft | [kimi_k31](docs/models/kimi_k31.md) |
2727
| Muse Spark | GB300 | 4 | DFlash target verify | [muse_spark](sgl_nvidia_mega/muse_spark/PORT-NOTES-sm103.md) |
2828

2929
B300, B200 and GB200 (148 SMs) are admitted with `sm148`; the model pages give
3030
the exact row widths, batch sizes and what was validated on each.
3131

32+
Any EAGLE v2 model can also run its topk-1 decode step as one CUDA graph (off by
33+
default, behind its own switches); see [docs/spec_step.md](docs/spec_step.md).
34+
3235
## Installation
3336

3437
Use SGLang's CUDA 13 image, which provides SGLang, FlashInfer, CuTe DSL and the

‎docs/models/glm5_3.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
| GPU | Tensor parallel | Coverage |
44
| --- | --- | --- |
55
| B300 / GB300 (SM103), Rubin (SM107) | 8 (one node, or two trays of one NVLink domain); 4 (one GB300 tray) | TP8: MTP target verify steps of 4 to 16 rows (batch 1 to 4 at 4 rows a request, batch 1 to 2 at 6); TP4: verify steps of up to 48 rows at 4 to 6 rows a request (batch 1 to 8 at 6); the NextN draft step in its captured graphs |
6+
| Rubin (SM107), GLM-5.2 | 16 (four trays of one NVLink domain) | One request, EAGLE 7 steps / topk 1 / 8 draft tokens: the 75-layer decoder chain, dense layers 0-2, the fused NextN draft and the fused verify tail. See [TP16 on Rubin](#tp16-on-rubin) |
67

78
Larger verify steps, prefill and extend run SGLang's standard path, and the NextN draft step runs on its draft spec.
89

@@ -64,6 +65,24 @@ The TP4 split-K GEMMs (`ll.gemm`) run FlashInfer's split-K kernel (`mm_bf16(...,
6465

6566
With the megakernel on, all shipped slots run; none needs to be listed. `SGLANG_NVIDIA_MEGAKERNEL_SLOTS` (comma-separated) overrides that list for tests and bisecting only; a list without a slot another needs (`dnorm` needs `qkv_a_small_m_shared` and `hops`, `qkv_a_small_m_shared` needs `attention`, `draft_rowselect` needs `draft`) stops the server at startup, naming it. Slot `draft` needs embedding replication, which the flag turns on (SGLang sets `SGLANG_ENABLE_EMBED_REPLICATION` when it is unset), greedy draft acceptance and an SGLang whose EAGLE draft graph runners run a draft spec's capture check; the server stops at startup, naming each one that is missing (an explicit `SGLANG_ENABLE_EMBED_REPLICATION=0` too).
6667

68+
## TP16 on Rubin
69+
70+
At TP16 on Rubin (VR200, SM107, four trays), one request, EAGLE 7 steps / topk 1 /
71+
8 draft tokens, the same flag runs `sgl_nvidia_mega/glm5_3/sm107` for GLM-5.2: the
72+
75-layer decoder chain, dense layers 0-2, the fused NextN draft and the fused verify
73+
tail, launched from prebuilt cubins. The GLM-5.3 specs select it by the TP size, and
74+
refuse TP16 on any other GPU. `--enable-nvidia-megakernel` is the only switch. It needs
75+
`SGLANG_NVIDIA_MEGAKERNEL_GLM_SM107_CUBINS` set to the cubin directory
76+
(`{chain,d012,draft,tail}/{entry.cubin,CALL.json}`), `SGLANG_DSA_FUSE_TOPK=0`,
77+
`--kv-cache-dtype fp8_e4m3 --dsa-decode-backend trtllm
78+
--moe-runner-backend flashinfer_trtllm --speculative-algorithm EAGLE
79+
--speculative-num-steps 7 --speculative-eagle-topk 1 --speculative-num-draft-tokens 8`;
80+
a setup that lacks any of them stops the server at startup, naming each reason.
81+
It serves one request at a time. A target verify step it does not cover (more than one
82+
request, grammar, logprobs, penalties, logit bias, a sampling seed, top-k / min-p
83+
sampling) raises instead of falling back (`sm107/verify_tail.py`), so serve it at
84+
concurrency 1 with greedy or temperature / top-p sampling.
85+
6786
## Tests
6887

6988
GLM-5.3 GPU and end-to-end suites are not yet part of the initial CI workflow.

‎docs/spec_step.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Speculative step graph (any EAGLE v2 model)
2+
3+
Off by default; each switch installs its SGLang hooks only when set to `1`.
4+
5+
| Switch | Effect |
6+
| --- | --- |
7+
| `SGLANG_NVIDIA_MEGAKERNEL_SPEC_STEP_GRAPH` | One CUDA graph per topk-1 decode step (draft, target verify, draft extend and the work between them), batch size 1 to 8 |
8+
| `SGLANG_SPEC_STEP_GRAPH_FUSED_INPUT_COPY` | The step graph's input copies in one launch |
9+
| `SGLANG_SPEC_PACKED_VERIFY_BROADCAST` | One TP broadcast of the verify result instead of three |
10+
| `SGLANG_SPEC_LEAN_SAMPLED_VERIFY` | Chain sampled verify without the expanded temperatures and zero-filled draft probs |
11+
| `SGLANG_SPEC_CHUNKED_VERIFY_SAMPLING` | With the lean verify: the sampling passes split over vocabulary chunks |
12+
| `SGLANG_SPEC_FUSED_DRAFT_EXTEND_TAIL` | The topk-1 draft-extend argmax, probs and DSA seed gather in two launches |
13+
| `SGLANG_SPEC_FUSED_RELAY` | The relay stash in one scatter, row views for a single request |
14+
15+
Every fusion's outputs are bitwise identical to the path it replaces.

‎pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,5 @@ include = ["sgl_nvidia_mega*"]
2424
# the kernels' CUDA sources and launch tables ship with the package
2525
[tool.setuptools.package-data]
2626
"*" = ["*.cu", "*.cuh", "*.json"]
27+
"sgl_nvidia_mega.spec_step" = ["csrc/*.cuh", "csrc/include/sgl_nvidia_mega/*.cuh"]
2728
"sgl_nvidia_mega.glm5_3.ll" = ["csrc/**/*.cuh"]

‎sgl_nvidia_mega/glm5_3/draft.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
With slot "draft" the draft's forward runs on the plugin's draft step inside SGLang's
66
draft-decode and draft-extend CUDA graphs: at TP8 ``draft_step.FusedDraft``, at the
77
TP4 profiles the draft composed from the kernel units (``draft_units``); otherwise it
8-
stays SGLang's. SGLang checks a draft spec at load only (its ISA, TP
8+
stays SGLang's. At TP16 (Rubin) the draft is ``glm5_3/sm107``'s fused draft, which
9+
runs inside SGLang's EAGLE v2 draft worker at one request. SGLang checks a draft spec at load only (its ISA, TP
910
size, decode graphs, config and environment, and ``model_disable_reasons``); the
1011
target spec checks the draft's server arguments at argument resolution.
1112
"""
@@ -129,6 +130,10 @@ def forward(self, step, original, *args, **kwargs):
129130

130131
def _model_disable_reasons(model, hf_config) -> list[str]:
131132
"""What the draft step needs beyond the requirements, read at load."""
133+
if target._tp_size() == target.SM107_TP_SIZE:
134+
from sgl_nvidia_mega.glm5_3 import sm107
135+
136+
return sm107.model_reasons(model)
132137
if "draft" not in SLOTS:
133138
return []
134139
from sglang.srt.runtime_context import get_parallel, get_spec
@@ -158,6 +163,10 @@ def need(ok: bool, what: str) -> None:
158163

159164

160165
def _build(model, hf_config, ctx):
166+
if target._tp_size() == target.SM107_TP_SIZE:
167+
from sgl_nvidia_mega.glm5_3 import sm107
168+
169+
return sm107.build_draft(model, hf_config, ctx)
161170
if "draft" not in SLOTS:
162171
return NoDraftStep()
163172
from sgl_nvidia_mega.glm5_3.profile import Profile
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
# SPDX-License-Identifier: Apache-2.0
2+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3+
"""GLM-5.2 at TP16 on Rubin (SM107), one request, EAGLE 7 steps / topk 1 / 8 draft
4+
tokens: the 75-layer decoder chain, dense layers 0-2, the fused MTP draft and the
5+
fused verify tail, launched from prebuilt cubins.
6+
7+
glm5_3's specs serve it. With ``--enable-nvidia-megakernel`` at TP16,
8+
``glm5_3/spec.py`` and ``glm5_3/draft.py`` dispatch here: ``config_reasons`` at
9+
argument resolution, ``model_reasons`` and ``build_target`` / ``build_draft`` at
10+
load. There is no other switch. The cubin directory is configuration, not a switch:
11+
``SGLANG_NVIDIA_MEGAKERNEL_GLM_SM107_CUBINS`` (``ARTIFACTS_ENV``), refused at
12+
argument resolution when unset or incomplete.
13+
14+
The build packs the weights before SGLang sizes the KV cache; the chain and the
15+
draft bind to their runner's KV pools just before that runner captures its CUDA
16+
graphs (``ModelRunner.init_cuda_graphs``).
17+
18+
This package imports without SGLang (the kernel tests); SGLang is imported in the
19+
functions that the specs call.
20+
"""
21+
22+
from __future__ import annotations
23+
24+
import functools
25+
import importlib.util
26+
import os
27+
28+
TP_SIZE = 16
29+
# The directory of the prebuilt cubins, {chain,d012,draft,tail}/{entry.cubin,CALL.json},
30+
# captured from kernels/; config_reasons refuses the setup when it is unset or incomplete
31+
ARTIFACTS_ENV = "SGLANG_NVIDIA_MEGAKERNEL_GLM_SM107_CUBINS"
32+
ARTIFACT_PARTS = ("chain", "d012", "draft", "tail")
33+
ARTIFACT_FILES = ("entry.cubin", "CALL.json")
34+
ISA = "sm_107"
35+
# EAGLE 7 steps, topk 1: one request's verify step is 8 rows
36+
TOKENS_PER_REQUEST = 8
37+
NUM_STEPS = TOKENS_PER_REQUEST - 1
38+
39+
# The server arguments this path was validated with (glm5_3/spec.py checks them the
40+
# way SGLang checks a spec's requirements)
41+
SERVER_ARGS = {
42+
"kv_cache_dtype": frozenset({"fp8_e4m3"}),
43+
"page_size": frozenset({None, 64}),
44+
"attention_backend": frozenset({None, "dsa"}),
45+
"decode_attention_backend": frozenset({None, "dsa"}),
46+
"dsa_decode_backend": frozenset({"trtllm"}),
47+
"moe_runner_backend": frozenset({"flashinfer_trtllm"}),
48+
"moe_a2a_backend": frozenset({None, "none"}),
49+
"dp_size": frozenset({None, 1}),
50+
"moe_dp_size": frozenset({None, 1}),
51+
"ep_num_redundant_experts": frozenset({None, 0}),
52+
"speculative_algorithm": frozenset({"EAGLE", "NEXTN"}),
53+
"speculative_eagle_topk": frozenset({1}),
54+
"speculative_num_steps": frozenset({NUM_STEPS}),
55+
"speculative_num_draft_tokens": frozenset({TOKENS_PER_REQUEST}),
56+
"speculative_adaptive": frozenset({None, False}),
57+
"enable_multi_layer_eagle": frozenset({None, False}),
58+
"speculative_use_rejection_sampling": frozenset({None, False}),
59+
# the kernels read req_to_token as physical KV slots; unified memory translates them
60+
"enable_unified_memory": frozenset({None, False}),
61+
}
62+
# The chain and layers 0-2 compute the DSA top-k themselves; validated with SGLang's
63+
# unfused top-k on every other step
64+
ENV = {"SGLANG_DSA_FUSE_TOPK": False}
65+
66+
# The SGLang names this module reads (test/unit/test_contract.py pins them)
67+
SGLANG_READS = {
68+
"srt/model_executor/model_runner.py": (
69+
"ModelRunner",
70+
"init_cuda_graphs",
71+
"is_draft_worker",
72+
),
73+
"srt/runtime_context.py": ("get_server_args",),
74+
"srt/arg_groups/fields/*.py": ("model_path", "speculative_draft_model_path"),
75+
"srt/kernel_plugins/nvidia/binding.py": ("device_isa",),
76+
"kernels/plugin_kernels/nvidia/spec.py|srt/megakernels/spec.py": ("Step",),
77+
}
78+
79+
80+
def artifact_reasons() -> list[str]:
81+
root = os.environ.get(ARTIFACTS_ENV)
82+
if not root:
83+
return [
84+
f"{ARTIFACTS_ENV} is not set; set it to the directory of the glm5_3/sm107 cubins"
85+
]
86+
missing = [
87+
os.path.join(part, name)
88+
for part in ARTIFACT_PARTS
89+
for name in ARTIFACT_FILES
90+
if not os.path.isfile(os.path.join(root, part, name))
91+
]
92+
if missing:
93+
return [f"{ARTIFACTS_ENV}={root} lacks {', '.join(missing)}"]
94+
return []
95+
96+
97+
def config_reasons(cfg, hf_config) -> list[str]:
98+
"""Every reason the TP16 setup cannot be served, at argument resolution."""
99+
from sglang.srt.kernel_plugins.nvidia.binding import device_isa
100+
101+
from sgl_nvidia_mega.glm5_3.spec import pinned_reasons
102+
103+
reasons = []
104+
isa = device_isa()
105+
if isa != ISA:
106+
reasons.append(f"TP{TP_SIZE} runs on {ISA} (Rubin) only, not {isa}")
107+
reasons += pinned_reasons(cfg, SERVER_ARGS, ENV)
108+
for module, what in (
109+
("cutlass", "CuTe DSL (nvidia-cutlass-dsl)"),
110+
("cuda.bindings", "the CUDA Python bindings"),
111+
):
112+
if importlib.util.find_spec(module) is None:
113+
reasons.append(f"needs {what}")
114+
mode = getattr(cfg, "disaggregation_mode", None) or "null"
115+
if mode != "null":
116+
reasons.append(f"PD disaggregation ({mode} role) is not served at TP{TP_SIZE}")
117+
reasons += artifact_reasons()
118+
return [f"glm5_3/sm107: {r}" for r in reasons]
119+
120+
121+
def model_reasons(model) -> list[str]:
122+
"""This rank's reasons the loaded target or draft cannot run, at load."""
123+
if type(model).__name__ == "GlmMoeDsaForCausalLMNextN":
124+
return []
125+
inner = getattr(model, "model", None)
126+
if type(inner).__name__ != "DeepseekV2Model":
127+
return [
128+
f"glm5_3/sm107: the decoder is {type(inner).__name__}, not DeepseekV2Model"
129+
]
130+
return []
131+
132+
133+
@functools.lru_cache(maxsize=None)
134+
def _step_class():
135+
try:
136+
from sglang.kernels.plugin_kernels.nvidia.spec import Step
137+
except ModuleNotFoundError: # SGLang before sgl-project/sglang#45389
138+
from sglang.srt.megakernels.spec import Step
139+
return Step
140+
141+
142+
class Built:
143+
"""What build_target and build_draft return (SGLang's BuiltMegakernel). The
144+
chain (target) and the fused draft run inside the model's own forward and
145+
SGLang's draft worker, so a covered step calls the original forward."""
146+
147+
draft_sampler = draft_loop = draft_extend = begin_draft_round = graph_variants = (
148+
None
149+
)
150+
speculative_runtime_hooks = None
151+
152+
def __init__(self, what: str, is_draft: bool):
153+
self.what, self.is_draft = what, is_draft
154+
self.widths = (TOKENS_PER_REQUEST,)
155+
156+
def summary(self) -> str:
157+
return f"glm5_3/sm107 {self.what}, TP{TP_SIZE}, one request"
158+
159+
def plan(self, input_ids, forward_batch, *args, **kwargs):
160+
if forward_batch.batch_size != 1:
161+
return None
162+
mode = forward_batch.forward_mode
163+
if self.is_draft:
164+
# one request's draft extend and draft decodes run the fused draft
165+
return (
166+
None
167+
if mode.is_idle()
168+
else _step_class()(mode="decode", rows=int(input_ids.shape[0]))
169+
)
170+
if mode.is_target_verify() and input_ids.shape[0] == TOKENS_PER_REQUEST:
171+
return _step_class()(mode="target_verify", rows=TOKENS_PER_REQUEST)
172+
return None
173+
174+
def forward(self, step, original, *args, **kwargs):
175+
return original(*args, **kwargs)
176+
177+
178+
def _bind_before_graphs() -> None:
179+
"""Bind the engaged chain or draft to its runner's KV pools before that runner
180+
captures its CUDA graphs."""
181+
from sglang.srt.model_executor.model_runner import ModelRunner
182+
183+
if getattr(ModelRunner, "_glm5_3_sm107", False):
184+
return
185+
init_cuda_graphs = ModelRunner.init_cuda_graphs
186+
187+
@functools.wraps(init_cuda_graphs)
188+
def wrapped(self, *args, **kwargs):
189+
from . import draft, target
190+
191+
if getattr(self, "is_draft_worker", False):
192+
draft.bind_runner(self)
193+
else:
194+
target.bind_runner(self)
195+
return init_cuda_graphs(self, *args, **kwargs)
196+
197+
ModelRunner.init_cuda_graphs = wrapped
198+
ModelRunner._glm5_3_sm107 = True
199+
200+
201+
def _check_context(ctx) -> None:
202+
if (
203+
ctx.tokens_per_request != TOKENS_PER_REQUEST
204+
or TOKENS_PER_REQUEST not in ctx.widths
205+
):
206+
raise ValueError(
207+
f"glm5_3/sm107 builds {TOKENS_PER_REQUEST} tokens a request, not "
208+
f"{ctx.tokens_per_request} (widths {list(ctx.widths)})"
209+
)
210+
211+
212+
def build_target(model, hf_config, ctx) -> Built:
213+
from . import target
214+
215+
_check_context(ctx)
216+
_bind_before_graphs()
217+
target.engage(model)
218+
return Built("target: decoder chain + layers 0-2 + verify tail", is_draft=False)
219+
220+
221+
def _model_path(hf_config) -> str:
222+
try:
223+
from sglang.srt.runtime_context import get_server_args
224+
225+
args = get_server_args()
226+
path = args.speculative_draft_model_path or args.model_path
227+
except Exception:
228+
path = getattr(hf_config, "_name_or_path", None)
229+
if not path or not os.path.isfile(
230+
os.path.join(path, "model.safetensors.index.json")
231+
):
232+
raise ValueError(
233+
f"glm5_3/sm107: the draft weights need a local checkpoint directory, not {path!r}"
234+
)
235+
return path
236+
237+
238+
def build_draft(model, hf_config, ctx) -> Built:
239+
from . import draft
240+
241+
_check_context(ctx)
242+
_bind_before_graphs()
243+
draft.engage(model, _model_path(hf_config))
244+
return Built("NextN draft", is_draft=True)

0 commit comments

Comments
 (0)