Skip to content

[Spec] Add LFM2 and LFM2-MoE DSpark speculative decoding support - #31041

Merged
kpham-sgl merged 6 commits into
sgl-project:mainfrom
tugot17:piotr/lfm2-dspark-main
Aug 31, 2026
Merged

kpham-sgl merged 6 commits into
sgl-project:mainfrom
tugot17:piotr/lfm2-dspark-main

Conversation

@tugot17

@tugot17 tugot17 commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

What

Adds DSpark speculative-decoding support for the LFM2 hybrid (ShortConv + attention) family: both the dense LFM2 and MoE LFM2-MoE targets. Follow-up to #30261 (DSpark), now that it has landed on main.

Two commits:

  1. Interleaved RoPE in the fused-KV kernel - the fused RMSNorm+RoPE materialization only handled neox rotation. Adds an IS_NEOX constexpr selecting the pairing (neox: (i, i+rotary/2); interleaved/GPT-J: (2i, 2i+1)); no change for existing neox drafts. LFM2 draft exports rotate interleaved and need this.
  2. LFM2 / LFM2-MoE target support - the draft is a DSpark checkpoint (Qwen3-style GQA backbone, markov + confidence heads) exported with interleaved RoPE. It registers as its own Lfm2DSparkDraftModel arch (a thin DSparkDraftModel subclass, mirroring Qwen3DSparkModel) so the LFM2 draft can gain LFM2-specific layers - e.g. ShortConv/conv1d - later without touching the shared classes. Interleaved RoPE and the confidence head come from the checkpoint config; the kernel change handles the rotation. Only the target side needs code beyond that: aux-hidden capture + ShortConv block verify/rollback in lfm2.py/lfm2_moe.py, hybrid-state commit after verify in the DSpark worker (mirrors the DFlash worker so decoding stays lossless), routing the draft KV injector through the fused-KV path, and marking the LFM2 archs eligible for the extra_buffer mamba radix strategy that spec-v2 rollback needs.

Net: 7 files, +422/-23, no changes to existing DSpark behavior.

Base LFM2-MoE serving parity (the attention-backend / radix-cache override tables for Lfm2MoeForCausalLM) is independent of DSpark and is in its own PR: #30780. Pair with it for the 8B target's serving defaults.

Speedup

1xH100 80GB, bs=1, temperature 0, block size 7, accept length / speedup vs the same server minus spec flags:

dataset LFM2.5-1.2B + 5L LFM2.5-8B-A1B + 3L
math500 (chat math) 4.82 / 2.10x 5.42 / 2.21x
aime (competition math) 4.36 / 1.95x 6.20 / 2.42x
humaneval (code) 4.41 / 1.93x -
mbpp (code) 4.45 / 1.95x 4.80 / 1.96x
gsm8k (grade-school math) 3.73 / 1.49x 3.51 / 1.24x
mtbench (multi-turn chat) 2.35 / 1.05x 5.87 / 2.32x

Floor is short chat on the small dense target (~1.05x); ceiling is long reasoning on the MoE (2.3-2.4x, accept near the block-7 limit). Accuracy at parity with baseline on every scoreable bench.

Note: interleaved RoPE (commit 1) is not optional for these drafts. Serving them neox collapses accept length to ~1.9 vs ~5.1 interleaved.

Public draft checkpoints

python -m sglang.launch_server \
  --model-path LiquidAI/LFM2.5-1.2B-Instruct \
  --speculative-algorithm DSPARK \
  --speculative-draft-model-path tugot17/LFM2.5-1.2B-Instruct-DSpark-5L \
  --speculative-draft-attention-backend flashinfer

Testing

Validated in serving on 1xH100 across the benches above (dense + MoE, draft depths 2L/3L/5L). The MoE ShortConv decode uses the same CUDA causal_conv1d_update kernel as dense (an earlier triton swap was removed after confirming identical accept, 5.936 both ways). Happy to add a gated CI test under test/registered/spec/dspark/ against the public checkpoints.

Supersedes #30776, which was opened against the DSpark PR branch before it merged; rebased onto main.


CI States

Latest PR Test (Base): ❌ Run #33310994737
Latest PR Test (Extra): ❌ Run #33310994555
Latest PR Test (AMD ROCm 7.2): ❌ Run #33310994595

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@vincentzed

Copy link
Copy Markdown
Contributor

The lint failure is a one-liner: ruff flags an unused Callable import in python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py.

-from typing import Callable, Optional
+from typing import Optional

(pre-commit run --all-files reproduces/fixes it locally.) Everything else red is just the label-gated suites — once lint is green a /tag-and-rerun-ci should take care of the rest.

@tugot17

tugot17 commented Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

@vincentzed thanks for the pointer - fixed in ffc6308, the unused Callable import is gone and lint is rerunning.

Could you add the run-ci label? I don't have permission to label on this repo, and the pr-gate checks are blocked without it.

@vincentzed

Copy link
Copy Markdown
Contributor

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Jul 29, 2026
@vincentzed

Copy link
Copy Markdown
Contributor

Lint is green now — thanks. Tagged run-ci, and the full suite surfaced one real failure that belongs to this PR (the rest of the red is the currently repo-wide xeon-gnr / NPU flakiness, also failing on unrelated PRs).

base-a-test-cpu (5) → test/registered/unit/test_model_overrides.py::test_mamba_radix_cache_resolution_pass:

AssertionError: {...'mamba_radix_cache_strategy': 'extra_buffer'}
            != {...'mamba_radix_cache_strategy': 'no_buffer', 'disable_overlap_schedule': True}

Cause: this PR adds Lfm2ForCausalLM / Lfm2MoeForCausalLM to _MAMBA_EXTRA_BUFFER_ARCHS (overrides.py, correctly — DSpark TARGET_VERIFY asserts extra_buffer), but test_model_overrides.py still uses dense Lfm2 as its negative example for the no-extra-buffer branch:

# auto + no extra-buffer support (Lfm2) -> no_buffer + overlap disable
self.assertEqual(
    _mamba_radix_cache_resolution(_view("Lfm2ForCausalLM")),
    {"uses_mamba_radix_cache": True,
     "mamba_radix_cache_strategy": "no_buffer",
     "disable_overlap_schedule": True},
)

Suggested fix — keep the negative branch covered by swapping in an arch that's in _MAMBA_RADIX_CACHE_ARCHS but not _MAMBA_EXTRA_BUFFER_ARCHS (ZayaForCausalLM qualifies on current main), and optionally add a positive Lfm2 case:

# auto + no extra-buffer support -> no_buffer + overlap disable
self.assertEqual(
    _mamba_radix_cache_resolution(_view("ZayaForCausalLM")),
    {"uses_mamba_radix_cache": True,
     "mamba_radix_cache_strategy": "no_buffer",
     "disable_overlap_schedule": True},
)
# Lfm2 now supports the extra buffer (DSpark TARGET_VERIFY requires it)
self.assertEqual(
    _mamba_radix_cache_resolution(_view("Lfm2ForCausalLM")),
    {"uses_mamba_radix_cache": True,
     "mamba_radix_cache_strategy": "extra_buffer"},
)

One other thing: this branch predates #30780 (merged earlier today, d19999b755), which wired Lfm2MoeForCausalLM into these same override tables — worth merging latest main alongside the test fix to avoid a conflict there. CI is also in maintenance mode (#21065), so a main merge is required for check-changes to pass anyway.

@kpham-sgl

Copy link
Copy Markdown
Collaborator

@tugot17 can you rebase with main? I think some changes in this PR is already on main

@tugot17
tugot17 force-pushed the piotr/lfm2-dspark-main branch from 52da142 to 83dd270 Compare August 19, 2026 10:49
@tugot17
tugot17 requested a review from HaiShaw as a code owner August 19, 2026 10:49
@tugot17

tugot17 commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main, two commits now.

You were right that some of it had landed. #32828 added the same post-verify hybrid state commit generically, and their version does a bit more than mine, so I dropped my dspark_worker_v2.py changes entirely. What's left is the LFM2 bits plus the interleaved RoPE kernel support.

I also fixed test_model_overrides.py while I was in there. It used dense Lfm2 as the negative example for the no-extra-buffer branch, which breaks as soon as this PR adds Lfm2 to _MAMBA_EXTRA_BUFFER_ARCHS. Put Zaya there instead and added Lfm2 as a positive case, like @vincentzed suggested. 72/72 locally.

The old head also predated MIN_BASE_SHA: cdff33d, which I think is why pr-gate was red. Should be sorted now.

Re-ran the dense numbers after the rebase to be safe: 1.2B + 5L draft, bs=1, math500, accept 4.98, 2.20x. Same as before.

@kpham-sgl kpham-sgl left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +1537 to +1538
"Lfm2ForCausalLM",
"Lfm2MoeForCausalLM",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think ShortConvAttn (e.g see Inkling) support extra buffer.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, both lines dropped and the test file reverted; forcing extra_buffer on does corrupt (2 of 3 prompts change text at temp 0 on a prefix-cache hit).

@@ -84,6 +183,24 @@ def inject_target_hidden(
return

with torch.inference_mode():
if self._fused_kv_helper is not None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will introduce a regression for Qwen3 Dspark drafters. Previous it takes _build_fused_kv_write_bundle → one F.linear + one fused_kv_norm_rope_write that stores directly into the KV pool. Now it replaces that with torch.mm into a workspace, a separate norm/rope kernel, then a per-layer set_kv_buffer pass that reads the workspace back — an extra full write+read of K/V plus N launches per verify step.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reverted, so Qwen3 keeps the bundle path; taught the write kernel the interleaved pairing instead, and IS_NEOX=True is bit-identical to the current kernel.

_build_fused_kv_write_bundle bailed on interleaved-rotary drafts, so
they fell back to the per-layer eager KV path. Teach the write kernel
both rotation pairings instead: neox pairs dims (i, i + D/2),
interleaved pairs (2i, 2i + 1), and the cos/sin cache layout is the same
for both. Since the cache is identical either way, the existing
cross-layer cache check cannot catch a style mismatch, so check the
style per layer too.

The neox path is unchanged: IS_NEOX=True is bit-identical to the
previous kernel on random inputs.
Adds the TARGET_VERIFY short-conv path (per-step conv windows recorded
into the speculative tape so the state can roll back to the accept
boundary), the DFlash aux-hidden capture hooks, and a dedicated
Lfm2DSparkDraftModel arch so the LFM2 draft can later diverge from other
DSpark drafts without touching shared classes.

Current LFM2 draft checkpoints are attention-only Qwen3-style GQA with
interleaved RoPE, so the draft model itself is a thin subclass.
@tugot17
tugot17 force-pushed the piotr/lfm2-dspark-main branch from 83dd270 to c26ae04 Compare August 24, 2026 13:05
@tugot17

tugot17 commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

Rebased on main, down to 5 files and +221/-16; the write kernel handles both pairings now, and dspark.py checks the style per layer since the cos/sin cache is the same either way.

@kpham-sgl

Copy link
Copy Markdown
Collaborator

/rerun-test test_dspark_stacked_ctx_kv_parity.py test_dspark_kernel_parity.py test_basic_sanity_dspark.py

@github-actions

github-actions Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Results for /rerun-test test_dspark_stacked_ctx_kv_parity.py test_dspark_kernel_parity.py test_basic_sanity_dspark.py:

🚀 1-gpu-5090 (2 tests): ✅ View workflow run

cd test/ && python3 registered/spec/dspark/test_dspark_stacked_ctx_kv_parity.py
cd test/ && python3 registered/spec/dspark/test_dspark_kernel_parity.py

🚀 1-gpu-h100 (1 test): ✅ View workflow run

cd test/ && python3 registered/core/test_basic_sanity_dspark.py

@kpham-sgl

kpham-sgl commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

@tugot17

tugot17 commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor Author

@kpham-sgl Looks unrelated. The failing file is test_gpt_oss_4gpu_mxfp4.py on a non-speculative server:

AssertionError: 0.0 not greater than or equal to 0.58
{'chars': 0.0, ..., 'score': 0.0}
Subprocess scheduler_1 crashed with exit code -6
CUDA coredump(s) detected (4 file(s))

chars: 0.0 means it emitted nothing rather than scoring low, and #36456 is fixing an OOB read in mxfp4 MoE weight scales on Hopper, which is the same path. The other two files in that job passed.

@kpham-sgl

kpham-sgl commented Aug 27, 2026 •

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci one

@kpham-sgl
kpham-sgl merged commit 0464544 into sgl-project:main Aug 31, 2026
128 of 163 checks passed
StevenChenSE pushed a commit to StevenChenSE/sglang that referenced this pull request Sep 6, 2026
adityaGoCT added a commit to adityaGoCT/mojo-adreno that referenced this pull request Nov 7, 2026
… token, the same tokens

LiquidAI/LFM2.5-2.6B-DSpark (@458cedab, 327.7M bf16, downloaded by the phone, read in place) drafts 7 tokens a step
from the target's residual streams after layers 2, 9, 17, 21, 27; the target checks them in one 8-row pass and keeps
the longest matching prefix plus its own next token, rewinding the conv states to the last accepted position. On the
Galaxy Z Fold, 64 tokens after the 415-token prompt: 19.92 / 19.90 / 19.91 ms/token against plain greedy decode's
27.52 / 27.77 / 27.53 (interleaved, idle phone), 4.5 tokens a target pass, the same 64 tokens in every run.

- lfm2/dspark_ref.py: the drafter in PyTorch from SGLang's implementation (sgl-project/sglang#31041); --simulate
  gives the acceptance along a recorded run (the phone's accepts match it step for step), --export its manifest.
- lfm2/dspark.mojo, lfm2/kernels/dsk.mojo: the drafter on the GPU, the target's verify, the few-row products: 8 weight
  rows a workgroup, 4 groups of 16 lanes splitting x's rows, FMA chains (0.69 ms for gate/up at 8 rows, against 2.35 on
  cooperative matrices and 0.38 for decode's 1 row; lfm2/bench_rows.mojo); an int8 copy of the Q6_K head for them.
- lfm2/model.mojo: verify(), commit(), taps; lfm2/lfm2.mojo: LFM2_DSPARK (speculate()); lk.short_conv keeps a
  verify's B x rows; lfm2/stage_phone.sh re-stages a wiped lab phone; android/build.py lfm2bench.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

jit-kernel run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants