Repository navigation
Fix LFM2-MoE sigmoid routing and expert-bias selection - #332
Merged
Merged
Conversation
ykhrustalev
marked this pull request as ready for review
June 6, 2026 14:57
The MoE block applied softmax to the gate and folded expert_bias into the combination weights. LFM2-MoE is sigmoid-gated: the bias steers top-k selection only, and the weights come from the unbiased sigmoid, scaled by routed_scaling_factor. Mirrors ml-explore/mlx-lm#1354.
ykhrustalev
force-pushed
the
ykhrustalev/lfm2.5-8b
branch
from
June 6, 2026 15:13
57ba8d3 to
127d032
Compare
Contributor
Author
|
cc @nastya236 |
davidkoski
reviewed
Jun 10, 2026
| import MLXLMCommon | ||
| import MLXNN | ||
|
|
||
| private let compiledLFM2MoESiluProduct: @Sendable (MLXArray, MLXArray) -> MLXArray = compile( |
Member
There was a problem hiding this comment.
Let's use this:
private let compiledSiluProduct: @Sendable (MLXArray, MLXArray) -> MLXArray = ...from SwichLayers.swift -- identical function. Promote that to public (like the weightedExpertSum next to it).
Other than this small item, looks good!
Promote compiledSiluProduct to public in SwitchLayers.swift and drop the duplicate compiledLFM2MoESiluProduct in LFM2MoE.swift, per review feedback.
mdstaff
added a commit
to mdstaff/mlx-swift-lm
that referenced
this pull request
Jun 12, 2026
…emma-4-12b-local-validation Brings in ml-explore#308 (Gemma 4 MTP speculative decoding, e145aca), ml-explore#333 (cross- layer KV sharing in no-cache forward), ml-explore#337 (prepare() windowSize), ml-explore#331, ml-explore#332. Conflict resolutions: - LMInput.ProcessedAudio: keep features/mask shape (consumed by Gemma4Unified); main's samples variant had no constructors. - Gemma4TextBackbone/Gemma4TextLanguageModel: union of ml-explore#327's tokenTypeIds and ml-explore#308's emitDrafterState threading; tuple return from ml-explore#308. - Gemma4.prepare image path: keep single full-sequence forward with tokenTypeIds (bidirectional vision overlay can't span chunk boundaries); main's chunked text-only prefill retained. - Dropped hasExplicitCache gating orphaned by ml-explore#333. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
dkgv
pushed a commit
to dkgv/mlx-swift-lm
that referenced
this pull request
Jul 30, 2026
* fix: correct LFM2-MoE sigmoid routing and expert-bias selection The MoE block applied softmax to the gate and folded expert_bias into the combination weights. LFM2-MoE is sigmoid-gated: the bias steers top-k selection only, and the weights come from the unbiased sigmoid, scaled by routed_scaling_factor. Mirrors ml-explore/mlx-lm#1354.
div0-space
pushed a commit
to LibraxisAI/mlx-swift-lm
that referenced
this pull request
Nov 29, 2026
…gs in appended text (ml-explore#332) * Format GemmaFunctionParser with swift-format The next commits change this file, and the lint job formats every Swift file a pull request changes. Main has it unformatted, so this commit applies .swift-format to it alone; the other Swift files they change are already formatted on main. No code changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Stream auto tool calls as OpenAI tool_calls fragments A response that began with a tool call had no content until the whole call and the engine terminal were generated, so its time to first token included the entire call. ToolCallProcessor can now expose a call while it is generated for the Gemma, Qwen 3.5, Harmony and framed-JSON formats: the resolved function name first, then only argument JSON that the complete-frame parse must agree with when the frame closes. A call whose name the caller declines, or whose payload cannot be rendered incrementally, still completes in one piece. Without streaming options the visible text and accumulated calls are unchanged. MLXOpenAIService chat streams request these fragments (streamToolCallDeltas) and render them as OpenAI tool_calls deltas: index, id, type and function.name first, then function.arguments pieces. Collected chat completions and Responses keep whole calls. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Stream only marker strings from Gemma tool calls A Gemma frame that leaves the strict grammar anywhere (unconstrained auto output occasionally drops a string's markers) is read by the complete parser's fallback, which keeps marker-quoted strings but turns bare scalars and Gemma-syntax composites into raw strings. A streamed call had already exposed those members as typed JSON, so the complete parse disagreed with them and a valid call failed as diverged. Gemma now streams only marker strings, which both readings agree on; other values complete from the parse when the frame closes. The function name is still exposed first. ToolCallStreamingDifferentialTests renders seeded calls the way each chat template renders them (Gemma format_argument, Qwen 3.5 XML, Hermes JSON, Harmony), with missing markers, stop-token end tags, two calls and leading text, and feeds them in token-like chunks: special tokens whole, other text split at any scalar, several tokens per chunk. Streamed calls must equal what the complete-frame path makes of each frame, with the same visible text, and fail only for a frame that path also rejects. It found the Gemma divergence above. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Find tool-call end tags in the appended text only Every format except Qwen 3.5, MiMo and strict Gemma located a frame's end tag by searching the whole growing buffer for each end tag on every chunk, so a call cost CPU time quadratic in its length. Measured release-mode cost per four-character chunk of one write_file call on main: Gemma 56 / 229 / 1,217 us at 4 / 16 / 64 KB, Harmony 93 / 522 / 2,510 us, framed JSON 35 / 321 / 523 us. A 64 KB Gemma call spent about 20 s of CPU in the forwarding task. The first pass still searches the whole buffer; later passes search only the appended chunk plus the unmatched tail shorter than the longest end tag, the only place a new tag can complete, and map the match by its distance from the end. Each of these formats now costs 1-3 us per chunk at every size. Calls exposed while generated kept a value copy of their exposure state and wrote it back each chunk, which copied the argument text the streamer had accumulated. That state is now a reference. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Drop dead state from the streamed tool-call renderers Behavior-preserving cleanup from the refactor pass: - The Gemma marker-string and Qwen 3.5 string-parameter phases carried the parameter key, which nothing read (the exposed object tracks the open key); the Gemma phase also reassigned itself unchanged. - The Harmony streamer emptied its input slice after copying it into the header, but every later path returns or replaces that slice. - ToolCallProcessor wrote the withheld tail back through the optional callStream, left over from when the exposure state was a value; it now writes through the reference it already bound. - GemmaArgumentValueParser.parseValue is private again: only the type's own parseCompleteValue calls it. - The JSON value lexer uses the streamers' whitespace helper, and two doc comments match their code (processEOSSegments can also fail as diverged; releasedPrefix takes several terminators). The focused suites pass unchanged (ToolCallStreamingTests, ToolCallStreamingDifferentialTests, ToolCallDeltaStreamingTests and the parser suites), and the CPU bench reports the same cost per chunk. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
div0-space
pushed a commit
to LibraxisAI/mlx-swift-lm
that referenced
this pull request
Nov 29, 2026
Brings ml-explore#322 (Flint), ml-explore#324, ml-explore#326-ml-explore#330 (CBv2 paged/MTP/SDPA, GPT-OSS), ml-explore#325 and the Nemotron Super fused MTP verify window: SDK main up to the commit d-inference master pins (889fe3c). Main's later ml-explore#331/ml-explore#332 are left out until the provider adopts ml-explore#332's streamed tool-call type. Package.swift pins the cluster mlx-swift 9fe34405 instead of main's 67dc7528; that was the only conflict. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
div0-space
pushed a commit
to LibraxisAI/mlx-swift-lm
that referenced
this pull request
Nov 29, 2026
…l-explore#333) * Format ServerSurfaceTests with swift-format The next commit changes this file, and the lint job formats every Swift file a pull request changes. Main has it unformatted, so this commit applies .swift-format to it alone. No code changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Build the SSE tool-call index test with OpenAIToolCallDelta ml-explore#332 changed OpenAIChatCompletionChunk.Delta.toolCalls from [OpenAIToolCall] to [OpenAIToolCallDelta], whose initializer takes index first. sseEncoderIncludesToolCallIndex still passed the OpenAIToolCall argument order (id, function, index), so the MLXLMServerTests target stopped compiling with "argument 'index' must precede argument 'id'", and every Fork Tests run on main fails at the build step. The test now builds the complete-call fragment in the new order with the type it had before (type defaulted to "function"), so the encoded entry is unchanged. Its "index":0 check also matched the choice's own index, so it passed with no tool-call index at all. With sorted keys, the tool-call entry encodes id, index and type next to each other; the new check pins the index to that entry and fails when it is missing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Proposed changes
Fix LFM2-MoE routing to match the sigmoid-gated behavior used by LFM2.5 checkpoints.
The current Swift path applies softmax to router logits and folds
expert_biasinto the combination weights. LFM2-MoE uses per-expert sigmoid scores:expert_biasshould affect top-k selection only, while the returned weights stay gathered from the unbiased sigmoid scores, optionally normalized bynorm_topk_prob, then scaled byrouted_scaling_factor.This mirrors the same routing fix in ml-explore/mlx-lm#1354.
This also adds focused routing regression tests for the sigmoid gate, expert-bias selection-only behavior, and top-k normalization.
The dense LFM2-MoE MLP path now compiles the SwiGLU activation product, matching the existing compiled SwitchGLU path used by the MoE experts.
Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes