Repository navigation
feat(models): support Ling-3.0 (BailingMoeV3ForCausalLM) - #3728
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
Load BailingMoeV3ForCausalLM checkpoints, which declare model_type bailing_hybrid, on their own decoder instead of refusing them: Kimi delta attention with a direct lower-bounded gate interleaved with head-gated absorbed MLA, feeding the Bailing group-limited sigmoid MoE, on scheduler-owned layer state. Sanitize accepts the HF, mlx-lm and rapid-mlx layouts, including an affine-quantized kv_b_proj, and the Ling-3.1 variants are refused by name. Part of lablup#2385.
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
Part of #2385: the Ling-3.0 scope. The Ling 3.1 scope extension is left for a follow-up (listed under Limits).
Ling-3.0 checkpoints declare
architectures: ["BailingMoeV3ForCausalLM"]undermodel_type: bailing_hybrid. Until now detection refused them by name. They now load on their own decoder,src/models/bailing_moe_v3.rs, ported from mlx-lm'sbailing_moe_v3(ml-explore/mlx-lm#1711), inmlxcel generateandmlxcel-server.What changed
Detection.
bailing_hybrid_model_typemapsBailingMoeV3ForCausalLMto a newModelType::BailingMoeV3(registry idbailing_moe_v3, categorylinear_attention).BailingMoeV2_5ForCausalLMand an absent list still selectBailingHybrid, and any other architecture is still refused. The twobailing_hybrid_teststhat asserted the old refusal now assert the new dispatch.Model (
bailing_moe_v3.rs).q/k/v_proj, each followed by a depthwise causal short conv and SiLU (Kimi Linear'sShortConv1d);normalize_qk; a per-dimension decay from a directf_projthroughgated_delta_update_with_lower_bound(kda_lower_bound), withA_logas[H, 1]anddt_biasas[H, D]in float32;beta = sigmoid(b_proj(x).astype(f32)); theno_proj(o_norm(y) * sigmoid(g_proj(x).astype(f32)).astype(dtype)).layer_group_size-th layer plus a trailing partial group. These usebailing_hybrid's absorbed MLA (RoPEtraditional = true,q_a/q_bor a directq_proj,embed_q/unembed_out, the latent pair in aKVCache), followed by the per-head gatesigmoid(g_proj(x).f32)beforedense.BailingMoeGatefed a float32 input, with the router weight float32, the selection-onlyexpert_bias,-infgroup fill, and normalization always on (top-1 is not divided by itself). The routed sum is combined in float32 as upstream does, and the shared expert ismoe_shared_expert_intermediate_size * num_shared_expertswide.LayerState::Recurrentwith the same four slots for KDA,LayerState::Kvfor MLA), with a hybrid snapshot spec (bailing_moe_v3). Padded prefill and cache-less chunked prefill are declined, and multi-row decode runs per row (listed underEXPECTED_PER_ROW_FALLBACK).Sanitize accepts three layouts:
[C, 1, K]conv, a KDAattention.dense(transformers 5), a densekv_b_proj;switch_mlp, splitembed_q/unembed_out,[C, K, 1]conv;rapid-mlx/Ling-3.0-tiny-MLX-4bit: pre-stackedmlp.experts.{proj},*_conv1d.conv.weight, and an affine-quantizedkv_b_proj.It also drops MTP layers (
model.layers.N >= num_hidden_layers) and top-levelmtp.*keys.validate_weightschecks every tensor shape againstconfig.jsonbefore any of it reaches MLX. That includes the routed-expert stack in either layout: the pre-stackedswitch_mlp.{proj}must have at leastnum_expertsplanes of the configured widths, and the HF per-expertexperts.{e}.{proj}must be present and correctly shaped for everyebelownum_experts.SwitchGLU::from_weightsstacks per-expert tensors without knowing the declared count, so without this check a stack that is short by one expert would load and the router could index past it.Config defaults. Every optional field takes mlx-lm's
ModelArgsdefault, includinghead_dim128,moe_shared_expert_intermediate_size512 andq_lora_rank256 (an explicitnullstill selects the directq_proj). The layer counts and widths that mlx-lm also defaults, to Ling-3.0-tiny's values, are required here instead, so a config that omits one is refused rather than sized as Ling-3.0-tiny. The published Ling-3.0 configs declare all of these fields, so no checkpoint run depends on the defaults.Refused by name (mlx-lm ignores these):
use_kda_lora/no_kda_lora: false,kda_safe_gate: false,rope_interleave: false,scale_router_input,up_proj_norm,value_norm,use_nGPT,use_mla_nope,norm_topk_prob: false, a non-sigmoidscore_function, agated_attention_proj_granularity_typeother thanhead_wise, and any non-zeroexpert_swiglu_limit_list/share_expert_swiglu_limit_listentry. An all-zero list clips nothing and is accepted.validatealso bounds every sizing scalar, requireskda_lower_boundto be finite and at most 0, and requiresnum_experts_per_tokto fit in the experts thattopk_groupkeeps.Shared code.
bailing_moe's routed-expert check moves into a scalar-argumentvalidate_routed_experts(pub(crate)).bailing_moe::validate_expertsnow delegates to it unchanged, andbailing_moe_v3::validate_weightscalls it.bailing_hybrid's shape validators andis_mtp_layer_keybecomepub(crate), and its YaRN MLA scale moves intomla_attention_scale.ModelArgs::attention_scaledelegates to it unchanged.TokenIdField::idsbecomespub(crate). No behaviour changes for existing families.Used by:comments are updated on every helper the new module calls (gated_delta,kimi_linearShortConv1d/KimiDeltaCache/decompose_kv_b_proj,mla_rope,mla_batched::latent_pair_cache_mode,BailingMoeGate::forward,router_prefix,SwitchGLU::forward/forward_fused_kernel,group_mask_scores_with_fill, coreMultiLinear).Wiring:
ModelType,model_metadata(config-backed),LoadedModel, the memory-estimate family slug, the TP model-type table, the rope-lifting config test.docs/supported-models.mdgets an entry (and the Ling-2.6 entry no longer says V3 is refused).CHANGELOG.mdgets an## [Unreleased]entry.Deviations from the issue
kv_b_proj. The original scope makes it a load error, as mlx-lm does. The checkpoint the acceptance criteria name,rapid-mlx/Ling-3.0-tiny-MLX-4bit, shipskv_b_projaffine-quantized (4-bit, group 64), so it is dequantized and split into denseembed_q/unembed_outwith Kimi Linear'sdecompose_kv_b_proj. That function already bounds the solved group size and bits and refuses a scales-only plane. Re-quantizing the split planes (the Ling 3.1 scope extension, delta 5b) is not done.kv_b_proj, and its pre-stacked experts and.conv.weightkeys do not match the module tree. For that checkpoint the reference is mlx-lm 0.32.2'sbailing_moe_v3model behind a small key adapter: it renames those keys and dequantizeskv_b_projbefore upstream's ownsanitizeruns. Parity was also checked, with no adapter at all, oninclusionAI/Ling-3.0-tiny(bf16) and on a 4-bit mlx-lm conversion of it.norm_topk_prob: falseand a non-sigmoid router are also refused, beyond the issue's list: upstream always normalizes and always uses sigmoid, so loading such a config would ignore it silently.Verification
Hardware: NVIDIA GB10 (sm_121, 121 GB unified memory), CUDA 13. Rust toolchain from
rust-toolchain.toml. Reference: mlx 0.32.4 (mlx-cuda-13), mlx-lm 0.32.2 (mlx_lm/models/bailing_moe_v3.py).Checkpoints:
rapid-mlx/Ling-3.0-tiny-MLX-4bitrevision9ff45b05f51c42631b70f8d2f8e0d9fd4470edfe.inclusionAI/Ling-3.0-tinyrevision9a98e35fe1c9ee255f78dd64771c7ae15a799481(bf16).quant_predicate, 5.248 bits per weight). This runs mlx-lm'sload_model→quantize_model→save_model.mlx_lm.convertitself could not be used: it loads the tokenizer through transformers 5.20'sAutoConfig, whose strictBailingMoeV3config rejects the checkpoint's integerkda_lower_bound: -5.Before (main
517ede2d7)The mlx-lm conversion fails the same way.
Greedy parity against mlx-lm
Setup:
MLXCEL_PRINT_TOKEN_IDS=1 MLXCEL_FUSED_MOE=0 mlxcel generate -m <ckpt> -p "<prompt>" -n N --temp 0. The reference is mlx-lm'sgenerate_stepwith an argmax sampler, run on mlxcel's own prompt ids (identical for every run). Prompts:Leading generated tokens that agree:
Every free-running divergence is a tie in the reference itself. I checked this by scoring both candidate tokens under mlx-lm given the shared prefix:
Teacher-forced over each mlxcel output (mlx-lm run once over prompt + mlxcel's tokens), mlxcel's token is the reference argmax at 126/128, 63/64 and 63/64 positions (rapid), 126/128, 64/64 and 64/64 (conversion), and 128/128, 64/64 and 64/64 (bf16). Every disagreement has a reference log-prob gap of exactly 0.125 nats, one bf16 step at those logit magnitudes.
The revenue acceptance prompt
With the chat template's default
detailed thinking on, the answer comes after the reasoning channel, so 128 tokens end mid-reasoning. With-n 768 --show-reasoning, all three runs below reach $480:MLXCEL_FUSED_MOE=0: EOS after 329 tokens. The reasoning ends withAnswer: $480., the answer starts withThe net revenue is $480., and the output's last line is- Net after refund: $517 − $37 = $480. It has no**Answer:**line.**Answer:** $480.**Answer:** $480before its first<|role_end|>.The fused-default answer text is identical to mlx-lm's up to its first
<|role_end|>. The fused default is not the parity path: its single-token decode combines the routed scores in the activation dtype rather than upstream's float32, which is why its token count differs from theMLXCEL_FUSED_MOE=0run. All parity numbers above useMLXCEL_FUSED_MOE=0.Server
mlxcel-server -m Ling-3.0-tiny-MLX-4bit --host 127.0.0.1 --port 18385, default settings (batch scheduler, prompt cache on):/healthreturns ok.temperature 0,max_tokens 1024) returns 242 chunks,finish_reason: stop, the reasoning and the answer in separate channels, and content ending**Answer:** $480.bailing_moe_v3.Unit tests (
cargo test --profile test-fast --features cuda --lib)bailing_moe_v3: 23 new tests, all pass. Thebailing_moe_v3filter also runs the renamedbailing_hybriddispatch test, so it reports 24.head_dim128, shared-expert width 512,q_lora_rank256, and an explicitnullq_lora_rank), layer kinds including a trailing partial group,layer_group_size1, fewer layers than one group,first_k_dense_replace0/24/25, shared-expert width 0/1/2;kv_b_projdequantize-and-split checked element by element against the dequantized plane; a scales-only plane refused;validate_weightsnaming each mis-shaped tensor;validate_weightson the routed-expert stack: a pre-stackedswitch_mlpplane one expert short (3 of 4) for each projection, a wrong per-expert width on either axis, a 2-D plane, an extra plane (accepted), the complete HF per-expert layout (accepted), the per-expert layout missing the last expert or a middle one, and one per-expert plane of the wrong width;o_normand output gate;Before the fix, on the previous commit's tree with only the new tests added, the
bailing_moe_v3filter gives 22 passed and 2 failed:validate_weights_checks_the_routed_expert_stack: the stack one expert short is accepted (validate_weightsreturnsOk(())).config_defaults_match_upstream:head_dim()is 96 (hidden_size / num_attention_heads), not 128.After the fix both pass.
Related suites, all passing on the final tree:
bailing140 (bailing_moe_v323,bailing_moe50,bailing_moe_linear40,bailing_hybrid24, plus 3 Ming-Image and prompt-cache tests that match the filter),kimi_linear25,kimi_k3119 (1 ignored),gated_delta18 (11 ignored),detection307 (7 ignored),batched_decode_coverage14,rope_parameters_lift5,registry76,memory_estimate77,mla_batched5.Gate and checks
The final commit's tree is
7f3461f8. It differs from tree1770eb69only by a doc comment insrc/models/bailing_hybrid_tests.rs. Everything below names the tree it ran on.Model runs. All of the checkpoint runs above were repeated with
mlxcel/mlxcel-serverbuilt from1770eb69; the doc-comment change does not reach either binary.finish_reason: stop, content ending**Answer:** $480, concurrent equal to alone for both prompts.Checks:
cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings: passes on1770eb69and on7f3461f8. The onlywarning:lines are mlxcel-core's C++ build-script output and the WebUI placeholder note.cargo fmt --all -- --check: the only diff issrc/loading/vlm_lfm3_vl.rs. It fails the same way on unmodified main517ede2d7and is fixed on currentorigin/mainby feat: add a per-step token budget mixing decode and chunked prefill #3717.python3 scripts/ci/check_used_by.py: OK (78 pub fns, 57 annotated, 717 caller-file references).bash scripts/ci/check_used_by_test.sh: all cases pass.python3 scripts/ci/check_cross_repo_refs.py,check_env_var_docs.py,check_windows_reserved_paths.py: OK.Full gate:
make verify-test-cudawith a private 0700TMPDIRon1770eb69(tree hash checked before and after). 207 test binaries: 18,885 passed, 2 failed, 566 ignored. Themlxcellib alone: 14,290 passed, 0 failed, 298 ignored. Both failures also fail on unmodified main517ede2d7:tests/mlx_test_guard_coverage.rs::mlx_evaluating_lib_tests_take_mlx_test_guardnames onlysrc/vision/encoders/nemotron_h_nano_omni_tests.rs:276 pos_embed_resample_runs_in_f32. On main it fails the same way: 5 passed, 1 failed, naming only that test.tests/step3p7_parity.rs::text_decode_delegates_sequence_local_native_batching(assertion failed: !wrapper.supports_padded_prefill()). On main: 7 passed, 1 failed. This change does not touch Step3p7.The gate was repeated on the final tree
7f3461f8(tree hash checked before and after) with the same totals: 207 test binaries, 18,885 passed, 2 failed, 566 ignored. Themlxcellib gives 14,290 passed, 0 failed and 298 ignored. The two failures are the same two. Thebailinglib filter gives 140 passed on that tree.Seeded-bug check, on the first version of this branch: four independent bugs in one build of
bailing_moe_v3.rs:[C, 1, K]conv not transposed.Each one fails its own test:
kda_forward_matches_a_hand_computed_lower_bounded_delta_rule,the_mla_gate_scales_each_head_by_its_own_sigmoid,a_trailing_partial_group_is_all_mlaandsanitize_normalizes_the_rapid_mlx_and_hf_layouts.the_model_reports_the_hybrid_state_contractfails as well, for 18 passed and 5 failed. The routed-expert check has its own fail-before result (see Unit tests). No unit test covers the float32 cast of the router input or ofb_proj, because the fixtures are float32. The bf16 real-checkpoint parity above is what exercises them.Merge:
git merge-tree --write-tree origin/main HEADagainstac5716b8f(#3719) is clean. The merged tree was not tested.Limits
element_wiseand null MLA gates;kv_b_proj;mlp.gate.gate_proj,mtp.*) and its per-module quantization overrides;forward_batched_with_idswithout sequence ids shares one fallback state across all rows, as Kimi Linear does. A legacy caller that sends two different prompts as one id-less batch would mix their state. The scheduler always passes ids.MLXCEL_FUSED_MOE=0.bailing_hybrid(Ling-2.6-flash) has the same gap this PR closes for V3: itsvalidate_weightsdoes not check the routed-expert stack againstnum_experts. That is existing behaviour and is left for a separate change.bailing_hybrid) was not re-run on a real checkpoint. Its code changed only by visibility, comments and the extracted YaRN scale helper, and its unit tests pass.bailing_moe(Ling-lite) was not re-run on a real checkpoint. Its only change is thatvalidate_expertsnow delegates to the extractedvalidate_routed_expertswith the same arguments, and its unit tests (50) pass.