Skip to content

feat(models): support Ling-3.0 (BailingMoeV3ForCausalLM) - #3728

Open
Jaeyeong-CHOI wants to merge 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:feat/2385-ling3-bailing-moe-v3
Open

Jaeyeong-CHOI wants to merge 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:feat/2385-ling3-bailing-moe-v3

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

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"] under model_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's bailing_moe_v3 (ml-explore/mlx-lm#1711), in mlxcel generate and mlxcel-server.

What changed

  • Detection. bailing_hybrid_model_type maps BailingMoeV3ForCausalLM to a new ModelType::BailingMoeV3 (registry id bailing_moe_v3, category linear_attention). BailingMoeV2_5ForCausalLM and an absent list still select BailingHybrid, and any other architecture is still refused. The two bailing_hybrid_tests that asserted the old refusal now assert the new dispatch.

  • Model (bailing_moe_v3.rs).

    • KDA layers: q/k/v_proj, each followed by a depthwise causal short conv and SiLU (Kimi Linear's ShortConv1d); normalize_qk; a per-dimension decay from a direct f_proj through gated_delta_update_with_lower_bound(kda_lower_bound), with A_log as [H, 1] and dt_bias as [H, D] in float32; beta = sigmoid(b_proj(x).astype(f32)); then o_proj(o_norm(y) * sigmoid(g_proj(x).astype(f32)).astype(dtype)).
    • MLA layers: every layer_group_size-th layer plus a trailing partial group. These use bailing_hybrid's absorbed MLA (RoPE traditional = true, q_a/q_b or a direct q_proj, embed_q/unembed_out, the latent pair in a KVCache), followed by the per-head gate sigmoid(g_proj(x).f32) before dense.
    • MoE: the shared BailingMoeGate fed a float32 input, with the router weight float32, the selection-only expert_bias, -inf group 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 is moe_shared_expert_intermediate_size * num_shared_experts wide.
    • State: scheduler-owned layer state, as Kimi Linear uses (LayerState::Recurrent with the same four slots for KDA, LayerState::Kv for 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 under EXPECTED_PER_ROW_FALLBACK).
  • Sanitize accepts three layouts:

    • the HF original: per-expert tensors, raw [C, 1, K] conv, a KDA attention.dense (transformers 5), a dense kv_b_proj;
    • the mlx-lm conversion: switch_mlp, split embed_q/unembed_out, [C, K, 1] conv;
    • rapid-mlx/Ling-3.0-tiny-MLX-4bit: pre-stacked mlp.experts.{proj}, *_conv1d.conv.weight, and an affine-quantized kv_b_proj.

    It also drops MTP layers (model.layers.N >= num_hidden_layers) and top-level mtp.* keys. validate_weights checks every tensor shape against config.json before any of it reaches MLX. That includes the routed-expert stack in either layout: the pre-stacked switch_mlp.{proj} must have at least num_experts planes of the configured widths, and the HF per-expert experts.{e}.{proj} must be present and correctly shaped for every e below num_experts. SwitchGLU::from_weights stacks 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 ModelArgs default, including head_dim 128, moe_shared_expert_intermediate_size 512 and q_lora_rank 256 (an explicit null still selects the direct q_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-sigmoid score_function, a gated_attention_proj_granularity_type other than head_wise, and any non-zero expert_swiglu_limit_list/share_expert_swiglu_limit_list entry. An all-zero list clips nothing and is accepted. validate also bounds every sizing scalar, requires kda_lower_bound to be finite and at most 0, and requires num_experts_per_tok to fit in the experts that topk_group keeps.

  • Shared code. bailing_moe's routed-expert check moves into a scalar-argument validate_routed_experts (pub(crate)). bailing_moe::validate_experts now delegates to it unchanged, and bailing_moe_v3::validate_weights calls it. bailing_hybrid's shape validators and is_mtp_layer_key become pub(crate), and its YaRN MLA scale moves into mla_attention_scale. ModelArgs::attention_scale delegates to it unchanged. TokenIdField::ids becomes pub(crate). No behaviour changes for existing families. Used by: comments are updated on every helper the new module calls (gated_delta, kimi_linear ShortConv1d/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, core MultiLinear).

  • 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.md gets an entry (and the Ling-2.6 entry no longer says V3 is refused). CHANGELOG.md gets an ## [Unreleased] entry.

Deviations from the issue

  • Quantized 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, ships kv_b_proj affine-quantized (4-bit, group 64), so it is dequantized and split into dense embed_q/unembed_out with Kimi Linear's decompose_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.
  • The parity oracle. mlx-lm cannot load the rapid-mlx checkpoint unchanged: it refuses the quantized kv_b_proj, and its pre-stacked experts and .conv.weight keys do not match the module tree. For that checkpoint the reference is mlx-lm 0.32.2's bailing_moe_v3 model behind a small key adapter: it renames those keys and dequantizes kv_b_proj before upstream's own sanitize runs. Parity was also checked, with no adapter at all, on inclusionAI/Ling-3.0-tiny (bf16) and on a 4-bit mlx-lm conversion of it.
  • norm_topk_prob: false and 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-4bit revision 9ff45b05f51c42631b70f8d2f8e0d9fd4470edfe.
  • inclusionAI/Ling-3.0-tiny revision 9a98e35fe1c9ee255f78dd64771c7ae15a799481 (bf16).
  • A 4-bit mlx-lm conversion of it (group 64, affine, the model's own quant_predicate, 5.248 bits per weight). This runs mlx-lm's load_model → quantize_model → save_model. mlx_lm.convert itself could not be used: it loads the tokenizer through transformers 5.20's AutoConfig, whose strict BailingMoeV3 config rejects the checkpoint's integer kda_lower_bound: -5.

Before (main 517ede2d7)

$ mlxcel generate -m Ling-3.0-tiny-MLX-4bit -p "An online store sold 17 keyboards ..." -n 64 --temp 0
Error: this checkpoint declares architectures[0] = BailingMoeV3ForCausalLM under model_type "bailing_hybrid". Ling-3.0 (bailing_moe_v3) is not supported yet: ...

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's generate_step with an argmax sampler, run on mlxcel's own prompt ids (identical for every run). Prompts:

  • the issue's revenue question (57 prompt tokens, N = 128);
  • "Explain the difference between TCP and UDP." (28 tokens, N = 64);
  • a 392-token word problem (N = 64).

Leading generated tokens that agree:

checkpoint revenue (128) TCP/UDP (64) 392-token prompt (64)
rapid-mlx 4-bit 1 0 64/64
mlx-lm 4-bit conversion 7 31 64/64
bf16 original 128/128 59 64/64

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:

  • rapid revenue at position 1: top-2 logits 20.5 / 20.5;
  • rapid TCP at position 0: 23.25 / 23.25;
  • conversion revenue at position 7: 20.625 / 20.625;
  • conversion TCP at position 31: 25.125 / 25.125;
  • bf16 TCP at position 59: the reference's own full-sequence forward puts mlxcel's token ahead (22.375 vs 22.25).

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 with Answer: $480., the answer starts with The net revenue is $480., and the output's last line is - Net after refund: $517 − $37 = $480. It has no **Answer:** line.
  • Fused MoE default: EOS after 251 tokens. The output ends with **Answer:** $480.
  • mlx-lm on the same prompt ids: ends with **Answer:** $480 before 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 the MLXCEL_FUSED_MOE=0 run. All parity numbers above use MLXCEL_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):

  • /health returns ok.
  • A streamed chat completion of the revenue question (temperature 0, max_tokens 1024) returns 242 chunks, finish_reason: stop, the reasoning and the answer in separate channels, and content ending **Answer:** $480.
  • Two different prompts (36 and 31 prompt tokens, 96 generated tokens each) give identical reasoning and content when run alone and when sent concurrently, so the scheduler decodes them as one batch over each row's own layer state.
  • The server log shows the prompt-cache snapshot taken under family bailing_moe_v3.

Unit tests (cargo test --profile test-fast --features cuda --lib)

bailing_moe_v3: 23 new tests, all pass. The bailing_moe_v3 filter also runs the renamed bailing_hybrid dispatch test, so it reports 24.

  • config parse, mlx-lm's defaults for absent fields (head_dim 128, shared-expert width 512, q_lora_rank 256, and an explicit null q_lora_rank), layer kinds including a trailing partial group, layer_group_size 1, fewer layers than one group, first_k_dense_replace 0/24/25, shared-expert width 0/1/2;
  • each refused flag by name, the all-zero limit list accepted;
  • out-of-range scalars, including NaN/-inf, a positive lower bound, and a top-k beyond the kept groups;
  • sanitize on the rapid-mlx and HF layouts, MTP drop, idempotence, router cast, tied head;
  • quantized kv_b_proj dequantize-and-split checked element by element against the dequantized plane; a scales-only plane refused;
  • validate_weights naming each mis-shaped tensor;
  • validate_weights on the routed-expert stack: a pre-stacked switch_mlp plane 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;
  • a KDA forward (3-token prefill plus one decode step) against a float64 hand computation of the conv, L2 norm, lower-bounded per-dimension gate, delta rule, o_norm and output gate;
  • the MLA output scaled per head by its own sigmoid gate;
  • whole-model decode after prefill matching one full prefill, fallback reset between prompts, two-row layer-state decode matching each row alone, a mismatched state row refused;
  • the hybrid state contract;
  • detection.

Before the fix, on the previous commit's tree with only the new tests added, the bailing_moe_v3 filter gives 22 passed and 2 failed:

  • validate_weights_checks_the_routed_expert_stack: the stack one expert short is accepted (validate_weights returns Ok(())).
  • 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: bailing 140 (bailing_moe_v3 23, bailing_moe 50, bailing_moe_linear 40, bailing_hybrid 24, plus 3 Ming-Image and prompt-cache tests that match the filter), kimi_linear 25, kimi_k3 119 (1 ignored), gated_delta 18 (11 ignored), detection 307 (7 ignored), batched_decode_coverage 14, rope_parameters_lift 5, registry 76, memory_estimate 77, mla_batched 5.

Gate and checks

The final commit's tree is 7f3461f8. It differs from tree 1770eb69 only by a doc comment in src/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-server built from 1770eb69; the doc-comment change does not reach either binary.

  • Every one of the nine greedy runs gives the same token ids as the earlier binaries.
  • The two answer runs again reach $480 after 329 and 251 tokens.
  • The server check gives the same result: 242 chunks, finish_reason: stop, content ending **Answer:** $480, concurrent equal to alone for both prompts.
  • All three checkpoints pass the new routed-expert validation: the HF per-expert bf16 original, the rapid-mlx pre-stacked 4-bit and the mlx-lm conversion.

Checks:

  • cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings: passes on 1770eb69 and on 7f3461f8. The only warning: lines are mlxcel-core's C++ build-script output and the WebUI placeholder note.
  • cargo fmt --all -- --check: the only diff is src/loading/vlm_lfm3_vl.rs. It fails the same way on unmodified main 517ede2d7 and is fixed on current origin/main by 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-cuda with a private 0700 TMPDIR on 1770eb69 (tree hash checked before and after). 207 test binaries: 18,885 passed, 2 failed, 566 ignored. The mlxcel lib alone: 14,290 passed, 0 failed, 298 ignored. Both failures also fail on unmodified main 517ede2d7:

  • tests/mlx_test_guard_coverage.rs::mlx_evaluating_lib_tests_take_mlx_test_guard names only src/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. The mlxcel lib gives 14,290 passed, 0 failed and 298 ignored. The two failures are the same two. The bailing lib 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:

  • the KDA lower bound dropped;
  • the MLA head gate dropped;
  • the trailing partial group not MLA;
  • the raw [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_mla and sanitize_normalizes_the_rapid_mlx_and_hf_layouts. the_model_reports_the_hybrid_state_contract fails 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 of b_proj, because the fixtures are float32. The bf16 real-checkpoint parity above is what exercises them.

Merge: git merge-tree --write-tree origin/main HEAD against ac5716b8f (#3719) is clean. The merged tree was not tested.

Limits

  • Ling-3.1-flash is not loaded. Its configs are refused by name. Still to port:
    • per-layer post-SiLU clipped SwiGLU;
    • the element_wise and null MLA gates;
    • the finite-minimum MLA padding mask;
    • re-quantizing a quantized kv_b_proj;
    • the oQ layout (quantized mlp.gate.gate_proj, mtp.*) and its per-module quantization overrides;
    • the block-FP8 original.
  • Multi-row decode is the per-row fallback, not a fused batched kernel.
  • forward_batched_with_ids without 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.
  • The fused MoE decode default is not the parity path (see the revenue section). Parity was measured with MLXCEL_FUSED_MOE=0.
  • bailing_hybrid (Ling-2.6-flash) has the same gap this PR closes for V3: its validate_weights does not check the routed-expert stack against num_experts. That is existing behaviour and is left for a separate change.
  • The MLA latent cache is stored in the cache's own per-token mode; the quantized-latent view Kimi Linear uses is not enabled for this family.
  • The scheduler and server path was exercised with two concurrent requests only, not under load.
  • The registry advertises fp16 KV only for this family. The int8 and Turbo KV modes, prompt-cache restore of a snapshot, and speculative decoding were not exercised.
  • Ling-2.6-flash (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 that validate_experts now delegates to the extracted validate_routed_experts with the same arguments, and its unit tests (50) pass.

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

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant