|
| 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