Skip to content

[LFM2-MoE] Support Transformers v5 packed MoE expert weights - #29659

Merged
JustinTong0323 merged 1 commit into
sgl-project:mainfrom
tugot17:lfm2-moe-packed-experts
Jul 2, 2026
Merged

JustinTong0323 merged 1 commit into
sgl-project:mainfrom
tugot17:lfm2-moe-packed-experts

Conversation

@tugot17

@tugot17 tugot17 commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

What

Adds support for loading LFM2-MoE expert weights in the Transformers ≥ v5.0 packed format to lfm2_moe.py's load_weights.

Transformers ≥ 5.0 (huggingface/transformers#41580, shipped in v5.0.0) packs MoE expert weights into a single 3D tensor per projection:

per-expert (pre-v5, on disk) packed (Transformers v5 in-memory)
gate/up …experts.{i}.w1.weight, …experts.{i}.w3.weight …experts.gate_up_proj [E, 2·I, H]
down …experts.{i}.w2.weight …experts.down_proj [E, H, I]

Why we need this

The current loader only understands the per-expert names. When weights arrive in the packed layout — which is what an in-memory Transformers v5 model exposes in its state_dict, i.e. the update_weights_from_tensor / RLHF (verl) weight-sync path — the packed expert tensors match no name in the loader and are silently dropped. The experts stay uninitialised and the model emits garbage, with no error raised.

This is increasingly common: anyone doing RL / online weight updates on LFM2-MoE with a Transformers ≥ 5 training stack hits it. Plain on-disk inference is unaffected (pre-v5 checkpoints are still per-expert), which is why it slips through until the weight-sync path is exercised.

Fix

Map the packed tensors onto the fused FusedMoE params per expert: gate_up_proj → w13_weight (split into w1/w3 halves), down_proj → w2_weight. The existing per-expert path is untouched, so pre-v5 on-disk checkpoints load exactly as before; the new block only triggers on the packed experts.gate_up_proj / experts.down_proj names.

LFM2-MoE packs out-features-major (gate_up_proj as [E, 2·I, H]), which already matches the FusedMoE w13_weight/w2_weight layout, so no transpose is needed (unlike GPT-OSS). Per-expert loading with an explicit integer expert_id is used because the whole-tensor expert_id=None fused path is gated to mxfp4-quantised models only — it would not work for unquantised bf16 LFM2-MoE.

How to reproduce

A public fixture is provided: tugot17/LFM2-8B-A1B-5.2-packed — LFM2-8B-A1B converted to the Transformers v5 packed format (authentic packed shapes: gate_up_proj (32, 3584, 2048), down_proj (32, 2048, 1792)).

python -c "
import sglang as sgl
e = sgl.Engine(model_path='tugot17/LFM2-8B-A1B-5.2-packed', tp_size=1)
print(e.generate(['The capital of France is'], {'temperature': 0, 'max_new_tokens': 16}))
"
  • Without this patch: " – – – – – – – – – – …" (garbage — experts dropped)
  • With this patch: " Paris. It is located in the northern part of the country, along the Seine" — identical to loading the original per-expert LiquidAI/LFM2-8B-A1B.

Backward compatibility

The old per-expert on-disk format was tested to confirm no regression — loading LiquidAI/LFM2-8B-A1B (per-expert) produces byte-identical output with and without this patch (the new block only fires on the packed gate_up_proj/down_proj names, so per-expert checkpoints take the unchanged path):

loader old per-expert ckpt v5 packed ckpt
unpatched main ✅ correct 🔴 garbage
patched (this PR) ✅ correct (identical) ✅ correct

Verified on MI325X / ROCm 7.2 against this branch (sglang 0.5.15.dev). The change itself is device/backend-agnostic — it only remaps weight names during loading.

Co-Authored-By: Changyi Yang [email protected]


CI States

Latest PR Test (Base): ✅ Run #28386441288
Latest PR Test (Extra): ❌ Run #28386441152

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request adds support for loading packed 3D MoE expert weights (gate_up_proj and down_proj) from Transformers >= v5.0 into the fused w13_weight and w2_weight parameters for the LFM2-MoE model. Feedback was provided to explicitly raise a ValueError instead of silently skipping weight loading if the loaded weight tensor does not have exactly 3 dimensions, preventing potential uninitialized weight issues.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread python/sglang/srt/models/lfm2_moe.py Outdated
Comment on lines +633 to +634
if fused_name in params_dict and loaded_weight.dim() == 3:
param = params_dict[fused_name]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

If fused_name is in params_dict but loaded_weight does not have 3 dimensions, the weight loading will be silently skipped, which can lead to uninitialized weights and hard-to-debug runtime issues. It is safer to explicitly raise a ValueError if the dimension is unexpected.

                if fused_name in params_dict:
                    if loaded_weight.dim() != 3:
                        raise ValueError(
                            f"Expected 3D tensor for packed MoE weight {name}, "
                            f"but got {loaded_weight.dim()}D tensor with shape {tuple(loaded_weight.shape)}"
                        )
                    param = params_dict[fused_name]

Comment thread python/sglang/srt/models/lfm2_moe.py Outdated
Comment on lines +662 to +663
if fused_name in params_dict and loaded_weight.dim() == 3:
param = params_dict[fused_name]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

If fused_name is in params_dict but loaded_weight does not have 3 dimensions, the weight loading will be silently skipped. Explicitly raising a ValueError here prevents silent failures and ensures any shape mismatch is caught early.

                if fused_name in params_dict:
                    if loaded_weight.dim() != 3:
                        raise ValueError(
                            f"Expected 3D tensor for packed MoE weight {name}, "
                            f"but got {loaded_weight.dim()}D tensor with shape {tuple(loaded_weight.shape)}"
                        )
                    param = params_dict[fused_name]

Transformers >= v5.0 (huggingface/transformers#41580) packs MoE expert
weights into a single 3D tensor per projection
(`experts.gate_up_proj` / `experts.down_proj`) instead of per-expert
weights (`experts.{i}.w{1,2,3}.weight`). An in-memory Transformers v5
model therefore exposes the packed layout in its state_dict -- this is
the layout seen on the `update_weights_from_tensor` / RLHF weight-sync
path -- and `lfm2_moe.py`'s loader, which only handles the per-expert
format, silently skips those tensors, leaving the experts uninitialized
(garbage output).

Map the packed tensors onto the fused FusedMoE params per expert:
gate_up_proj -> w13_weight (split into w1/w3 halves), down_proj ->
w2_weight. The per-expert path is unchanged, so on-disk pre-v5
checkpoints keep loading as before; the new block only triggers on the
packed names.

LFM2-MoE packs out-features-major (gate_up_proj as
[num_experts, 2*intermediate, hidden]), which already matches the
FusedMoE w13_weight/w2_weight layout, so no transpose is required.

Verified on MI325X with an LFM2-8B-A1B checkpoint converted to the
Transformers v5 packed format: without this patch the packed checkpoint
produces garbage ("- - - -"); with it the output is identical to the
original per-expert checkpoint.

Co-Authored-By: Changyi Yang <[email protected]>
@tugot17
tugot17 force-pushed the lfm2-moe-packed-experts branch from 8c87f27 to 5e3731f Compare June 29, 2026 16:16
@tugot17

tugot17 commented Jun 29, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @gemini-code-assist — good catch. Applied to both the gate_up_proj and down_proj blocks: they now raise a ValueError on a non-3D packed tensor instead of silently skipping. Also ran black to fix the formatting. Pushed in 5e3731f.

@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

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Jun 29, 2026
@JustinTong0323
JustinTong0323 merged commit 26b15a0 into sgl-project:main Jul 2, 2026
261 of 293 checks passed
e-martirosian pushed a commit to e-martirosian/sglang that referenced this pull request Jul 2, 2026
…ject#29659)

Co-authored-by: Piotr Mazurek <[email protected]>
Co-authored-by: Changyi Yang <[email protected]>

return collect_test_items

update
dougyster added a commit to dougyster/sglang that referenced this pull request Jul 17, 2026
…ped in v0.5.15

Ancestry-checked each rolling-:dev model against v0.5.15.post1. Support that
landed in the release moves to the stable tag:
- Baidu Unlimited-OCR (sgl-project#29186), LFM2.5 (sgl-project#29659) -> :latest
- MiniCPM-V-4.6 (sgl-project#24855): :dev -> :latest, :dev-cu12 -> :latest-cu129

Kept on :dev (support NOT in the release cut):
- LongCat-2.0 (FP8 support sgl-project#30275 not in v0.5.15.post1)
- Hy3 (HunyuanV3 NextN/MTP fix sgl-project#30331 not in release; MTP is a headline feature)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Chronostasys pushed a commit to MindLab-Research/sglang that referenced this pull request Aug 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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