Skip to content

[Perf] [GB300] deepseek_v41: Megakernel decode attention chain for 1 to 48 rows - #2

Closed
YAMY1234 wants to merge 34 commits into
sgl-project:mainfrom
YAMY1234:deepseek-v41-attention-chain
Closed

YAMY1234 wants to merge 34 commits into
sgl-project:mainfrom
YAMY1234:deepseek-v41-attention-chain

Conversation

@YAMY1234

@YAMY1234 YAMY1234 commented Oct 18, 2026 •

Copy link
Copy Markdown
Collaborator

Based on #1 (f2b69d2); this PR's own changes are commits 89a6fdc, 19d3773, 989e2f6 and b852ad7 (test only). Needs sgl-project/sglang#44945.

How it attaches

Like #1, the package registers its DeepSeek-V4.1 spec with SGLang's sglang.srt.megakernels layer through the sglang.srt.plugins entry point, and SGLang turns it on with --enable-nvidia-megakernel. There is no HookRegistry hook and no environment switch. This PR adds one slot, attn, to the spec's build: with the flag set, every rank's startup line lists it, e.g.

NVIDIA megakernel: active (DeepSeek-V4.1: slots ['attn', 'gate', 'hop_a', 'moe']; hop A at [6] rows, fast gate at [6, 48] rows; weight copies {}; widths [6, 12, 18, 24, 30, 36, 42, 48]; tolerance numerics; built in 6.2 s, 1544.0 MiB; wait deadline 60 s)

SGLANG_NVIDIA_MEGAKERNEL_SLOTS=hop_a,moe,gate (tests and bisecting only) runs #1's attention step instead.

Motivation

With #1, the NVIDIA megakernel runs the DeepSeek-V4.1 decode step for DSpark verify steps of 1 to 8 requests, but its attention step is stock: SGLang's own kernels in SGLang's order. At 1 to 48 rows each of them is latency-bound: the q-LoRA norm and MXFP8 quant, wq_b, FlashMLA on a query padded from 16 to 64 heads, and wo_a, each launched only after the previous kernel has finished.

This PR runs the attention as one chain of programmatic dependent launches (PDL). Each kernel lets the next launch at its own entry, so the next kernel's prologue (weight streaming, KV gather) overlaps it. At 1 to 24 rows the attention itself is a swap-AB sparse attention that takes the 16 local heads unpadded and unroped.

On GB300 TP4 with DSpark (same node, static ISL 8K / OSL 1K), the decode step is 6.7 / 10.8 / 7.9 % shorter at 1 / 2 / 4 requests than #1 (per-user throughput +7.0 / +12.6 / +7.0 %); at 8 requests (48 rows, where FlashMLA still runs the attention) the difference is inside the run-to-run band.

Modifications

What the attention step runs now

Rows q-LoRA norm + quant, wq_b Query Sparse attention Inverse RoPE + wo_a
1–24 PDL norm + quant, wq_b on the low-latency MXFP8 GEMM 16 heads, unroped swap-AB, PDL, narrow combine fused, early trigger
25–48 same SGLang's (roped, 64-head pad) SGLang's FlashMLA fused, early trigger
49+ stock stock stock stock
  • q-LoRA norm + MXFP8 quant (sm103/attention/q_norm_quant.py). One kernel writes the BF16 normed row (for the indexer) and wq_b's MXFP8 input. It triggers its dependent at entry, so wq_b launches and streams its weights while the norm runs. Scales are FlashInfer's 128×4 swizzle up to 8 rows and per-8-row tiles beyond.
  • wq_b on FlashInfer's low-latency MXFP8 GEMM (sm103/mxfp8_ll.py) with a pinned tactic per row bucket; its output is bitwise to SGLang's MXFP8 GEMM on the same input. Which of these kernels a layer uses is decided at build and logged once per rank.
  • Swap-AB sparse attention (sm103/attention/swapab.py, swapab_gluon.py). One CTA per (row, 64-key tile) gathers the window and the compressed keys through the sparse indices, with the KV rows on the MMA M dimension and the 16 heads on N. It applies the query RoPE as it loads the query, so wq_b's output goes to attention unroped and without the 64-head pad. Its narrow combine (one warp per 128 columns) folds the attention sink once and triggers wo_a at entry.
  • Fused inverse RoPE + wo_a + MXFP8 (sm103/attention/src/wo_a_fused.cu, wo_a.py) up to 48 rows, built with NVRTC; it triggers wo_b at entry.
  • Where it plugs in. attention/chain.py gives [Feat] [GB300] deepseek_v41: NVIDIA megakernel plugin for DeepSeek-V4.1 decode on GB300 #1's stock attention step (attention/step.py) the chain's query ops, its own cache and index resolution for swap-AB, and the fused wo_a. Every per-step choice reads host state only (rows, forward mode, the attention metadata's type, the KV layout), so all ranks agree and a captured graph replays the choice made at capture.
  • Slot attn. It joins the shipped slots (runtime.SHIPPED_SLOTS). The spec's build reports each requested slot as built or not through runtime.built_slots, which now includes attn (built when any layer has the chain). The first version of this PR lacked that entry, so a server with the flag stopped at build with KeyError: 'attn'; a CPU test now requires the table to cover every shipped slot.
  • Build. The spec's build runs at the end of SGLang's ModelRunner.initialize, before the KV cache is sized. The low-latency wq_b GEMM, the fused wo_a and the norm + quant compile there for every served width (+4 s; no measurable build memory: 1,544 MiB per rank with or without attn). The swap-AB kernels specialize on the KV pool's page geometry and the step's index widths, which exist only after KV sizing; they compile in SGLang's warm-up runs before graph capture.
  • Numerics. The spec's declared numerics (deepseek_v41/spec.py) carry four new bounds: attn.wq_b.max_abs 0, attn.q_lora.bf16_ulp 1, attn.wo_a.fp8_steps 1, attn.out.rel 2e-2 (measured below).
  • Follow-ups (not in this PR):
    • wqkv_a on the low-latency GEMM: split-K moves about 2e-5 of the FP8 KV-cache bytes by one FP8 step (measured); it needs a declared KV tolerance.
    • Gathering the KV before the PDL wait on the low-ratio layers, once a captured graph shows the side-stream joins are full edges.
    • Compiling the swap-AB kernels from a hook after KV sizing, for deployments without decode CUDA graphs.

Accuracy Tests

Each result names what it ran on. The kernel tests call the kernels directly. The per-layer parity ran the attention step through a test-only per-layer hook on plain SGLang 5cbe2371a53, before the framework. The product-path results run --enable-nvidia-megakernel on the megakernels framework.

  • Kernel tests on GB300 (test/kernels):
    • swap-AB with PDL, narrow combine and entry trigger: bitwise to the same kernel without PDL at 1–24 rows, and to SGLang's own swap-AB at 1–8 rows without compressed keys; with compressed keys the narrow combine differs from SGLang's wide combine by at most one BF16 ulp in 0–4 elements per output, inside the float64 reference bound; CUDA-graph replay equals eager;
    • query RoPE in attention: bitwise to SGLang's query RoPE kernel followed by the stock call, at 1–64 rows, eager and in graph replay;
    • PDL norm + quant: bitwise to itself without PDL at 1–48 rows and to SGLang's at 1–8 rows; its BF16 row is within one ulp of FlashInfer's RMSNorm;
    • fused wo_a: bitwise to SGLang's fused kernel at 1–32 rows (the largest SGLang serves); at 33–48 rows within one FP8 step of a float64 reference (≥ 99.99 % of codes and all scales bitwise); graph replay equals eager;
    • row-tile norm + quant at 9–48 rows: codes bitwise to FlashInfer's quantize and each 8-row tile's scales bitwise to FlashInfer's quantize of that tile;
    • wq_b on the low-latency GEMM: bitwise to SGLang's MXFP8 GEMM at 1–48 rows.
    • poisoned-memory regression test (test_deepseek_v41_poisoned_scales.py): the unwritten scale-atom bytes of the row-tile quantize and the GEMM's output buffer are never consumed. With every torch.empty and the allocator's free blocks filled with NaN patterns (0xFF, 0x7F), the outputs at 1–48 rows are bitwise equal to a zero-memory run, eager and in a CUDA-graph replay (40 / 40 on GB300). The test asserts that the poison landed.
  • Attention step vs SGLang, per layer, same eager step (GB300 TP4, SGLang 5cbe2371a53, test-only per-layer hook, CUDA graphs off, sorted sparse indices in both arms, all four ranks, every target layer; DSpark verify steps of 6–48 rows):
    • [Feat] [GB300] deepseek_v41: NVIDIA megakernel plugin for DeepSeek-V4.1 decode on GB300 #1's stock step: the wo_b output and the window-KV cache bytes are bitwise in 2,000 of 2,000 calls.
    • With this PR's chain (1,075 calls): the KV cache is unchanged; the wo_b output differs from SGLang's by at most 1.8e-2 of the layer's output peak (12–24 rows, swap-AB against SGLang's FlashMLA), at most 6.1e-3 at 25–48 rows, and is bitwise or within 5.6e-3 at 6 rows (both arms run swap-AB there).
  • Product path on the framework (GB300 TP4; SGLang's megakernels framework at 1746944440e, before the last review round of [Feat] [NVIDIA] megakernels: Add --enable-nvidia-megakernel and a layer for NVIDIA megakernel plugins sglang#44945, whose head is now 58fb997cb59; this PR at 989e2f6; --enable-nvidia-megakernel): the startup line above on 4 of 4 ranks with attn, and SGLang's capture check "runs the decode graphs of batch sizes [1, 2, 3, 4, 5, 6, 7, 8] (8 of 27)" on 4 of 4; 0 server error lines.
  • Serving (product path, framework; same tree and head as the boot above, one launch): GSM8K-200 with real acceptance 196 / 200 at 8 concurrent requests (accept length 4.270) and 196 / 200 at 1 (4.245); lc2 needle 24 / 23 / 26 / 25 / 26 of 27 over 5 passes; 0 server error lines. [Feat] [GB300] deepseek_v41: NVIDIA megakernel plugin for DeepSeek-V4.1 decode on GB300 #1 on the same framework (no attn): 196 / 196, accept length 4.253 / 4.224; [Feat] [GB300] deepseek_v41: NVIDIA megakernel plugin for DeepSeek-V4.1 decode on GB300 #1 with the megakernel off: 197 / 196, 4.289 / 4.245.

Speed Tests and Profiling

The test ran on one node (GB300, TP4), SGLang's megakernels framework at 1746944440e (before the last review round of sgl-project/sglang#44945) and this PR at 989e2f6, with --enable-nvidia-megakernel in every launch. The setup was static ISL 8K / OSL 1K with DSpark (synthetic acceptance 3.51), batch sizes 1, 2, 4 and 8, two passes per launch (forward and reversed).

There were four fresh launches in the order this PR, #1, #1, this PR. #1's arms set SGLANG_NVIDIA_MEGAKERNEL_SLOTS=hop_a,moe,gate, so the only difference between the arms is the attn slot. The startup lines show slots ['attn', 'gate', 'hop_a', 'moe'] vs ['gate', 'hop_a', 'moe'] on 4 of 4 ranks, and there were 0 server error lines.

Each value is the mean of 4 runs (2 launches × 2 passes), p50 of each run:

Requests Rows Step, #1 (ms) Step, this PR (ms) Step Tokens/s per user, #1 This PR Throughput
1 6 4.362 4.068 −6.7 % 804.8 861.0 +7.0 %
2 12 5.252 4.687 −10.8 % 660.6 744.1 +12.6 %
4 24 6.117 5.637 −7.9 % 558.6 597.7 +7.0 %
8 48 7.874 7.844 −0.4 % 377.4 382.6 +1.4 %
  • At 1 to 24 rows the swap-AB attention and the PDL chain run.
  • At 48 rows FlashMLA runs the attention, and only the norm + quant, the low-latency wq_b and the fused wo_a change; that difference is inside the run-to-run band (about 1 %), so it is not a result.
  • Time to first token is unchanged (173–177 ms at 1 request).

Checklist

  • CPU tests (test/unit) against the megakernels framework (1746944440e): 117 passed; pre-commit clean.
  • Kernel tests on GB300: 333 passed, 0 failed (64 SGLang-reference cases above 32 rows skipped, covered by the float64 reference).
  • Attention-step parity above.
  • Product-path boot on the framework: active on 4 of 4 ranks with attn; capture check.
  • Serving accuracy (GSM8K-200, needle, accept length) on the framework.
  • Same-node speed above.

Registers the backend nvidia with SGLang's monokernel framework through the
sglang.srt.plugins entry point. Its specs serve DeepSeek-V4.1-Flash DSpark verify
steps of 1 to 48 rows on SM103 at TP4, and the DSpark draft stages, with the
flashmla attention backend and an FP8 KV cache. Every other step runs SGLang's
standard path, and nothing beyond the entry point is imported without the flag.

A routed step rebuilds SGLang's own step from SGLang's modules and stage
boundaries, and fills three slots with this package's kernels:
- at 1 to 8 rows, wo_b's GEMM epilogue publishes into a Lamport mailbox on every
  rank, and a Lamport consumer runs the attention all-reduce with the mHC post,
  combine and RMSNorm as the attention post's fused reduction;
- at 1 to 48 rows, the routed experts run on a route kernel and a pair of 8-row
  tcgen05 block-scaled GEMMs inside SGLang's dual-stream MoE;
- at 1 to 8 and 48 rows, the router's top-k runs in one CTA per row, bit for
  bit SGLang's fused gate.
Each slot is probed at build and stays off, with the reason logged, on an SGLang
without its seam.

The mailbox, the kernels for every routed width and their tactics are built and
compiled at startup, before the KV cache is sized. Every wait on another GPU has
a deadline below SGLang's watchdog and faults at address 0x0 when missed.

Tests: CPU contract tests pin every SGLang name the package reads; kernel tests
on GB300 check each kernel against SGLang's or FlashInfer's op and the fail-stop
deadline.
test/e2e launches DeepSeek-V4.1-Flash servers with and without the monokernel
backend: GSM8K across the largest covered width, KL of covered steps and of long
prompts against the normal prefill path, a passkey past the indexer's candidate
span, and fail-stop when one rank skips a hop, stops or dies. benchmark/ holds the
static ISL 8K / OSL 1K client behind the speed table and its protocol.
With SGLang running MXFP8 linears at 1-8 rows on FlashInfer's low-latency GEMM,
its wo_b takes the autotuner's cached tactic for the shape. The publishing GEMM
looks that tactic up on eager steps (graph warm-up included) and publishes with
it, so its partial equals wo_b's; before tuning it keeps the tactic precompile
fixed. A capture replays the last eager choice, so nothing compiles inside it.
SGLang serves DeepSeek-V4.1-Flash's block-FP8 wo_b on FlashInfer's
persistent CuTe DSL MXFP8 GEMM with a pinned tactic, not on the
low-latency GEMM, so there is no autotuned low-latency wo_b tactic to
follow. The lookup only read whatever FlashInfer's autotune cache held for
the publish GEMM's shape. Keep the tactic precompile fixed per row count.

This reverts commit da109a8.
SGLang now declares enable_decoder_swa_bounded_replay as Optional[bool] and
resolves None at startup. The slots serve with replay on or off, so the spec
accepts None as well.
…ck step stubs

The covered step now runs the plugin's executor (runtime/) instead of SGLang's
decoder layers: the embedding, the Engram hashes and the mHC broadcast, then per
layer Engram and the capture on the materialized streams and
boundary.pre -> attention.step -> boundary.post("attn") -> moe.step ->
boundary.post("ffn"), then the head and the logits. StepState carries the step
between the step functions.

Each package (boundary/, attention/, moe/, engram/, logits/) has its interface
and a stock implementation. engram/ and logits/ call SGLang's lower-level parts;
boundary/, attention/ and moe/ still call SGLang's stage boundaries, attention and
MoE modules in the order the decoder layer does, until their ports land. Every
kernel slot is off (plan.Facts() builds nothing); the kernels stay in sm103/. The
DSpark draft runs SGLang's own path, so its spec is no longer registered.
…es in the runtime

SGLANG_NVIDIA_MEGA_PARITY_SORT_TOPK (test only) moves with the executor from the
removed forward.py to runtime/parity.py, unchanged: build installs it.
…d by SGLANG_ENABLE_NVIDIA_MEGAKERNEL

The megakernel needs no SGLang interface of its own. plugin.register() (the
sglang.srt.plugins entry point) registers two hooks when
SGLANG_ENABLE_NVIDIA_MEGAKERNEL=1, and nothing otherwise:
- after ModelRunner.load_model: for the DeepSeek-V4.1 target, check the setup on
  every rank (requirements.py; an unsupported setup stops the server listing every
  reason) and build the executor before the KV cache is sized;
- around DeepseekV4ForCausalLM.forward: MegakernelDecode.plan covers a DSpark
  verify step of a built width from host state alone, and runs it; every other
  step runs SGLang's forward.

The slot plan routes a width when the MoE step built its GEMM pair. spec.py and
draft.py go with the framework they plugged into; the DSpark draft runs SGLang's
own path. The contract test resolves every hook target. Prose, logs and variables
say megakernel (SGLANG_NVIDIA_MEGAKERNEL_SLOTS, _PARITY, _PARITY_SORT_TOPK).
…the SGLANG_NVIDIA_MEGAKERNEL_ prefix

The fault injection (test only) and the serving tests' variables follow the
switch's naming: SGLANG_NVIDIA_MEGAKERNEL_FAULT_INJECT and
SGLANG_NVIDIA_MEGAKERNEL_E2E_*.
moe.step(layer, m_in, st) runs a covered decode step's FFN the way
DeepseekV2MoE.forward does for the covered configuration, calling the block's
own gate, top-k, routed experts and shared expert: the dual-stream order at
CUDA graph capture, the eager order otherwise. It returns what the decoder
layer hands the FFN post (the unmerged pieces, or the deferred finalize). A
CPU test runs SGLang's forward and the step on the same stubbed block and
compares every call, its stream and its arguments, and the output.
…e MoE step

The MoE package builds PR sgl-project#1's routed-expert GEMM pair for every MoE layer
(slot moe) and its fast top-k (slot gate), reading SGLang's loaded MXFP4
experts in place; every rank agrees or none is built. At widths whose plan
routes, the step runs the dual-stream order with the pair: the fast gate takes
the top-k on SGLang's router logits, the pair replaces the routed call and
returns the deferred-finalize output, and the gate, the routed-input quant
stream and the shared expert on the alternate stream stay as SGLang issues
them.
…nature

A CPU test calls the slot against an autospec of RoutedExpertGemm: with the
fast top-k the launcher gets the routed input's event and the row count, and
joins the input itself; with SGLang's top-k the slot joins it before the pair.
A change in the launcher's signature fails on CPU, not at the first routed
step on a GPU. Public functions of the MoE package gain type hints.
…'s resolved spec config

The server argument speculative_num_draft_tokens is unset under DSpark until
SGLang resolves it (block size + 1); build reads get_spec(), as SGLang's runners
do. The kernel runner's messages say "NVIDIA megakernel".
…y covered width

A GB300 serving test: the megakernel on with every slot off, eager verify steps at
1, 2, 4 and 8 requests (6 to 48 rows), the parity switch running SGLang's forward
and the megakernel's on each; every logged step must show no difference in the
logits and the hidden states.
…ce the forward per instance

From the design review, each checked against SGLang 5cbe2371a53:
- The one hook is AFTER ModelRunner.initialize, not load_model: the post-load
  transforms, LoRA, batch-invariant mode and the KV dtype run after load_model;
  both points come before the scheduler sizes the KV pool.
- The megakernel's forward is installed on the target model instance
  (functools.wraps keeps the signature SGLang reads), not as an AROUND hook on
  DeepseekV4ForCausalLM.forward, so no other instance or subclass is touched; an
  instance whose forward is already replaced is refused.
- Every rank logs "NVIDIA megakernel: active (...)" once installed (SGLang logs and
  swallows a plugin's load errors, so tests assert this line).
- Refused: deterministic inference, hierarchical sparse attention, decode CUDA
  graphs other than FULL or disabled, SGLANG_RAGGED_VERIFY_MODE other than static.
- The model declares _derived_weight_cache_error, so online weight updates refuse
  instead of serving stale derived state.
- The build's memory is measured from free device memory (symmetric memory
  bypasses the caching allocator).
boundary/stock.py runs the boundaries between a covered step's sublayers as
SGLang's stage boundary does for DeepSeek-V4.1 with the pre-mix carried from
the previous sublayer: pre forks the mHC stats stream and collapses the
streams into the sublayer's input (or takes the one the previous post built);
post reduces the sublayer's TP-partial output in SGLang's fused all-reduce +
mHC post with the same next boundary (the FFN norm after attention; the next
layer's input norm after the MoE, none before an Engram layer or after the
last one). Past the push plane the attention rows are summed on the attention
TP group before a plain post, as SGLang's transport does.
…blished wo_b

boundary/hop_a.py owns PR sgl-project#1's hop-A unit for the executor: the Lamport
mailbox, the publishing wo_b GEMM precompiled for each width up to 8 rows,
and the consumer. The attention step publishes through
Boundaries.publish_wo_b; the attention post then collects a published partial
with the triplet SGLang's post computes and the FFN norm, in place of SGLang's
fused collective. Off unless the hop_a slot is on; any other partial takes
SGLang's post. The boundary module is renamed boundaries.py.
… compiled it for

Slots.hop_a follows the boundary's built hop: on at its compiled widths (1-8 rows,
those the publishing GEMM takes), off with the boundary's reason otherwise.
…tion step

At hop-A widths the attention step runs wo_b through the boundary's publishing
GEMM, which stores the TP-partial rows into the Lamport mailbox, and returns the
partial the attention post then collects. Where the GEMM declines the rows, wo_b
stays SGLang's with the deferred all-reduce. Adds the attention package's CPU
tests: the prepare path is SGLang's choice, and the publish contract.
… settings; review fixes

From the PR review, each checked against SGLang 5cbe2371a53:
- With the megakernel on, every slot this package ships runs (hop_a, moe, gate).
  SGLANG_NVIDIA_MEGAKERNEL_SLOTS is an override for tests and bisecting; its names
  are stripped and validated (gate needs moe), a requested slot that builds at no
  width stops the server, and the startup line reports the slots built and their
  widths. The serving tests launch the default and assert the built slots.
- The setup checks and the build read SGLang's resolved settings (the published
  config namespaces, else resolution's view), not raw ServerArgs: the raw decode
  CUDA graph config is still unset when the model runner is prepared.
- The test-only sorted sparse indices are an AROUND hook registered through SGLang's
  HookRegistry (plugin.TEST_HOOKS), not an assignment on SGLang's class.
- Files adapted from SGLang's model code name their origin; NOTICE lists SGLang.
- StepState drops unused fields; one log prefix ("NVIDIA megakernel: "); the
  serving tests read SGLANG_NVIDIA_MEGAKERNEL_E2E_MODEL_PATH.
…fuse a late build; drop dead step state

- The startup line's 'gate' slot comes from the MoE build's own result, not only
  from the plan.
- The build refuses a model runner that already sized its KV cache or captured its
  decode graphs (the hook must run inside ModelRunner.initialize).
- StepState drops 'hidden' and 'layer', which nothing read.
…e-nvidia-megakernel

The switch is SGLang's server flag (ServerArgs.enable_nvidia_megakernel), not an
environment variable. plugin.register() always registers its hook after
ModelRunner.initialize; the hook returns at once unless the server was started with
the flag, so a server without it, or an SGLang that has no such flag, runs
untouched. Its name lives in plugin.FLAG / plugin.FLAG_CLI. The startup refusals,
the weight-update error, the serving tests, the README and the benchmark README say
--enable-nvidia-megakernel; SGLANG_ENABLE_NVIDIA_MEGAKERNEL is gone. The
SGLANG_NVIDIA_MEGAKERNEL_* test variables stay.
…framework

SGLang now runs the megakernel through sglang.srt.megakernels: with
--enable-nvidia-megakernel it checks the setup at argument resolution, builds
the registered spec after ModelRunner.initialize and installs its forward. The
plugin no longer hooks SGLang's code: plugin.register() registers
DeepseekV4ForCausalLM's spec (deepseek_v41/spec.py), and only the parity test
keeps its hook.

deepseek_v41/spec.py holds what requirements.py held as data for SGLang's
checks (TP 4, SM103, 152 SMs, bfloat16, the server arguments, the HF config,
the declared numerics) plus the toolchain and FlashInfer GEMM checks; the
generic feature probes, the resolved-config reader and the wait deadline are
SGLang's now. runtime.build takes SGLang's BuildContext, and the executor
returns SGLang's Step and reports its slots through summary(). The step code
and kernels are unchanged.
…refusals at launch

The verify test now counts SGLang's "NVIDIA megakernel: active (...)" line, once per
TP rank with every shipped slot and widths 6 to 48, and the capture line for the
decode graphs of 1 to 8 requests. A new e2e test launches with the flag and checks
that argument resolution stops the server before the weights load: when
SGLANG_PLUGINS leaves the plugin out, and with an unsupported setup, whose reasons
are all listed. The benchmark README's startup check follows the new line.
…esolution

- spec.API_VERSION pins the sglang.srt.megakernels contract the spec is written
  against; the spec took SGLang's own constant, so SGLang's version check could
  never refuse it.
- The requirements state the decode CUDA graph backends the covered step is
  tested with (FULL or none) instead of relying on SGLang's default.
- SGLANG_NVIDIA_MEGAKERNEL_SLOTS is checked with the toolchains at argument
  resolution (config_disable_reasons), before the weights load; the model checks
  stay after the load.
- The spec tests run SGLang's resolution step on the spec the plugin registers
  and also name: no DSpark, overlapped weight loading, breakable decode graphs,
  ragged verify, the dtype, the GPU and a bad slot list; the plugin tests check
  the entry point against SGLang's name and an SGLang without the framework.
- The contract pins the entry point name and the BuiltMegakernel members SGLang
  reads; the package docstring and README say when the checks run.
The kernels the attention step uses at 1-48 rows, each tested on GB300:
- swap-AB sparse attention with programmatic dependent launch (PDL), the query
  RoPE applied as the query loads, KV gathered before the PDL wait, and a narrow
  combine that triggers its dependent at entry (adapted from SGLang's swap-AB
  attention);
- the q-LoRA RMSNorm + MXFP8 quant with PDL, up to 128 rows (adapted from
  SGLang's MXFP8 norm epilogue);
- the fused inverse RoPE + wo_a + MXFP8 kernel at up to 48 rows with an early PDL
  trigger, built with NVRTC (adapted from SGLang's fused wo_a kernel);
- wqkv_a and wq_b on FlashInfer's low-latency MXFP8 GEMM at 1-64 rows with a
  pinned tactic per row bucket.
@YAMY1234
YAMY1234 force-pushed the deepseek-v41-attention-chain branch from 0f18d25 to 989e2f6 Compare October 18, 2026 05:20
…cale bytes the row-tile quantize leaves unwritten

The q-LoRA norm + quant past 8 rows writes 32 of each 512-byte scale atom.
Poison the memory (0xFF / 0x7F, filled after allocation or through the
allocator and graph pool) at 1-48 rows, eager and in a graph replay: the
output must be bitwise the zero-memory run's.
@YAMY1234 YAMY1234 closed this Oct 19, 2026
YAMY1234 pushed a commit that referenced this pull request Nov 23, 2026
…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 <[email protected]>

* [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 <[email protected]>

* [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 <[email protected]>

* [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 <[email protected]>

* [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 <[email protected]>

* [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 <[email protected]>

* [Refactor] glm52/sm107: drop the draft diagnostics, ablation and test knobs and the unused non-TMA EH load path

Co-Authored-By: Claude <[email protected]>

* [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 <[email protected]>

* [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 <[email protected]>

* [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 <[email protected]>

* [Docs] glm5_3/sm107: state the steps the TP16 path does not cover

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [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 <[email protected]>

* [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 <[email protected]>

---------

Co-authored-by: Brayden Zhong <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Donglin Yang <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant