Repository navigation
feat(models): port GraniteMoE (granitemoe, GraniteMoeForCausalLM) - #3745
Open
Jaeyeong-CHOI wants to merge 1 commit into
Open
Jaeyeong-CHOI wants to merge 1 commit into
Jaeyeong-CHOI wants to merge 1 commit into
Conversation
IBM's Granite 3.0 / 3.1 sparse-MoE checkpoints were refused as an unsupported model type. The block is the dense Granite block with the MLP replaced by a top-k softmax router and SwitchGLU experts, mirrored from mlx-lm's granitemoe.py; the original release's fused input_linear is split into gate/up at load. Pinned against mlx-lm on 4-bit exports of granite-3.0-1b-a400m and granite-3.1-3b-a800m.
This branch has not been deployed
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.
Summary
Closes #3743.
Ports IBM GraniteMoE (
model_type: granitemoe,GraniteMoeForCausalLM), the Granite 3.0 / 3.1 sparse-MoE decoders that #245 deferred for lack of an MLX checkpoint. Onmainsuch a checkpoint is refused:With this change
granite-3.0-1b-a400m-instructandgranite-3.1-3b-a800m-instructload inmlxcel generateandmlxcel-serverand are listed bymlxcel arch, and they track mlx-lm on 4-bitmlx_lm.convertexports (greedy continuations teacher-forced, and full logit traces).What changed
src/models/granitemoe.rs(new). The block is the dense Granite block with the MLP replaced byblock_sparse_moe, so it reusesgranite::ModelArgs(flattened) andgranite::Attentionunchanged (the four scalar multipliers;attention_multiplieris the SDPA scale) and the sharedSwitchGLU. The router mirrors mlx-lm v0.32.2granitemoe.py:argpartitiontop-k, a softmax over only the selected logits in float32, and a float32 weighted sum cast back to the expert dtype. Sanitize splits the original release's fusedblock_sparse_moe.input_linear[E, 2F, H]along axis 1 (gate rows first) and renamesoutput_lineartoswitch_mlp.down_proj; anmlx_lm.convertexport already shipsswitch_mlp.*and passes through. A quantized fusedinput_linearis a load error, since it cannot be sliced (the same rulegranitemoehybridfollows).ModelArgs::validaterefuses configs that would otherwise abort inside MLX:num_experts_per_tokof 0 or abovenum_local_experts, zero experts, zero heads, heads not a multiple of KV heads, and a non-defaultrope_scaling(every published GraniteMoE config hasrope_scaling: null). Native batched decode through the shared split-attention path.ModelType::GraniteMoe, detection ofgranitemoe, the registry / metadata / loaded-model tables,memory_estimate, the tensor-parallel fallback name (not shardable: the generic plan names neither the router norswitch_mlp; the refusal comes fromvalidate_supported_runtime, whoseruntime_kind_forhas no GraniteMoe arm), and the batched-decode coverage pins.Used by:annotations onSwitchGLU::from_weights,SwitchGLU::check_input_widthsandmamba::parse_eos_token_ids; the last two also lacked existing callers (Omoikane forcheck_input_widths; Falcon-H1, PLaMo 2 and GraniteMoeHybrid forparse_eos_token_ids).docs/supported-models.md: a GraniteMoE entry, which says only the 4-bit exports are validated; the "not yet ported" sentence in the Granite 4 entry is gone. No CHANGELOG entry: that is written at release time.src/models/granitemoe_tests.rs: config parsing of the published 1b-a400m config and of a transformers-5rope_parametersblock;validateat top-k 0, 1, E and E + 1, zero experts, uneven KV heads, scaled RoPE and a missing field; sanitize split order and its two refusals; the MoE block against a host reference at fan-outs 1, 2 and E (E = 4); an untied head; native batched decode against sequential decode at different offsets; last-row logits against a full and a chunked prefill; a one-layer forward (four tokens, so RoPE and the causal softmax both matter) against a host reference with distinct values for the four multipliers (embedding 0.5, attention 2.0, residual 0.4, logits scaling 2.5), which also checks that replacing any one multiplier by its neutral value (1, or1/sqrt(head_dim)for attention) moves the host reference far outside the tolerance.src/models/detection_tests.rs:granitemoeis detected apart fromgraniteandgranitemoehybrid, andgranitemoeshared(which adds a shared expert this port does not load) staysUnsupported model type.tests/granitemoe_parity.rs: the real-checkpoint gate below.Verification (NVIDIA GB10, sm_121, CUDA 13; mlx-lm 0.32.2, mlx 0.32.5; Rust 1.97.1)
Checkpoints:
ibm-granite/granite-3.0-1b-a400m-instruct(revisionffec3c35, 32 experts, top-8, 24 layers, tied head) andibm-granite/granite-3.1-3b-a800m-instruct(revisiona0278068, 40 experts, top-8, 32 layers, tied head), each converted withmlx_lm.convert -q(4-bit, group 64; mlx-lm'squant_predicatekeeps the router,o_projand the expertdown_projat 8 bits, so the exports are mixed-width).Reference ids: mlx-lm greedy decode on the same export from the same prompt ids (one prefill, then single-token argmax steps with no EOS stop), on a 26/77-token chat prompt and a 534/585-token one (the 3.1 template adds a default system turn).
tests/granitemoe_parity.rson this branch (MLX_ENABLE_TF32=0 MLXCEL_REQUIRE_MODELS=1 MLXCEL_TEST_GRANITEMOE_A400M_DIR=... MLXCEL_TEST_GRANITEMOE_A800M_DIR=... cargo test --profile test-fast --features cuda --test granitemoe_parity -- --test-threads=1 --nocapture), teacher-forced over all 64 reference tokens:The same numbers on the final tree of this PR, except that one of three runs of the 585-token case measured 0.125 at step 12 instead of 0.25.
The gate is not vacuous. With the top-k renormalisation of the gates removed (softmax over all experts, then the top-k weights kept as they are; a local edit, not part of this PR) and the test rebuilt, both cases fail on their short prompt: the 1b-a400m keeps mlx-lm's token as argmax at 32 of 64 steps with the largest deficit 12.125 (step 19), the 3b-a800m at 16 of 64 with 20.86 (step 39).
Free-running greedy against the same references matches 64/64 tokens on the 1b long prompt and parts at steps 32 (1b short), 46 (3b short) and 12 (3b long), each at a step where mlx-lm's token is not mlxcel's argmax in the teacher-forced run above.
Teacher-forced logit traces over
docs/architecture.md(scripts/mlx_lm_logit_trace.pyvs thelogit_traceexample, compared withscripts/compare_logit_traces.py):mlxcel generate -m <export> -p "Explain in three sentences why the sky is blue during the day and red at sunset." -n 64 --temp 0prints a coherent answer on both exports ("The sky appears blue during the day due to a particular type of scattering called Rayleigh scattering. ...").mlxcel archlists "GraniteMoE (Granite 3.x sparse MoE)" under Granite.mlxcel-server -m <1b export>answers a/v1/chat/completionsrequest for the same question at temperature 0 with the same opening sentence (26 prompt tokens, 48 completion tokens).Gates. The full suite ran on an earlier revision of this branch; the final revision adds only tests, comments and documentation on top of it: the one-layer multiplier unit test, the
granitemoesharedassertion in the detection test, the measured values in theMAX_REFERENCE_DEFICITcomment, theUsed by:line ofSwitchGLU::check_input_widths, the tensor-parallel arm's comment, the mlx-lm link in the module doc (pinned to v0.32.2), and thedocs/supported-models.mdwording (the CHANGELOG hunk of the gated revision was dropped). No non-test code differs from the gated revision.cargo fmt --all -- --checkclean;cargo clippy --locked --workspace --all-targets --features cuda -- -D warningsclean;python3 scripts/ci/check_used_by.pypasses (used-by: OK, 78 top-level pub fn in 2 shared files, 57 annotated).--profile test-fast --features cuda,--test-threads=1) filtered bygranitemoe(35 passed, including the tenmodels::granitemoetests and the detection test),models::detection(118 passed),batched_decode_coverage(14 passed) anddistributed::tensor_parallel(368 passed, 4 ignored);tests/granitemoe_parity.rswith both checkpoints (2 passed, numbers above) and without them (2 passed, both skip). The new multiplier test matches the host reference within 1e-4, and replacing one multiplier by its neutral value moves the host reference by 0.0227 (embedding), 0.0155 (attention), 0.0471 (residual) and 0.282 (logits scaling), against a 0.01 bound.bashof eachscripts/ci/*_test.sh(17 scripts): all pass excepthelm_chart_package_test.sh, which needs ahelmbinary the test machine does not have.make verify-test-cudasuite (cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1), run one test target at a time with the same profile, features and flags (themlxcelandmlxcel-corelib targets split into groups by top-level module,--exact), totals summed from libtest's per-target summaries: 200 targets, 18,898 passed, 2 failed, 568 ignored (19,468, the number of listed tests); doctests 3 passed, 10 ignored. The two failures aretests/mlx_test_guard_coverage.rs::mlx_evaluating_lib_tests_take_mlx_test_guard(it flagssrc/vision/encoders/nemotron_h_nano_omni_tests.rs:276) andtests/step3p7_parity.rs::text_decode_delegates_sequence_local_native_batching(assertion failed: !wrapper.supports_padded_prefill()). Both fail identically on unmodifiedmain(9402cf8); they are the two stale tests test: fix two stale tests that keep make verify-test red #3720 fixes.git merge-tree --write-tree origin/main <branch>: clean against 9402cf8.Limits
docs/supported-models.md; whichever lands second needs a trivial rebase.