Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/supported-models.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ Implemented model families include:
- MiniMax-M3 (`minimax_m3`, MiniMax: a hybrid dense/MoE decoder that follows MiniMax-M2 (`minimax`) but swaps in Gemma-style RMSNorm (weight+1) everywhere including per-head Q/K norm, clamp-SwiGLU (`swigluoai`) experts and dense MLPs, partial RoPE (`rotary_dim` of `head_dim`), and a sigmoid router with a selection-only routing bias plus one shared expert. The per-layer plan comes from `moe_layer_freq` (leading dense layers, then MoE); routed experts load the Mixtral-style `block_sparse_moe.experts.{i}.w1/w3/w2` checkpoint naming (auto-falling back to `gate_proj/up_proj/down_proj`), and the shared expert is always a separate `block_sparse_moe.shared_experts` MLP added to the routed mixture at a fixed weight of 1.0, never packed into the switch tensors. The sparse layers (`sparse_attention_config.sparse_attention_freq`) add a block-sparse "MSA" indexer with an MQA-style index: per-head `index_q_proj` query heads score against a single shared `index_k_proj` key head, each normed (Gemma norm) and RoPE'd, top-`sparse_topk_blocks` selection over `sparse_block_size` key blocks scored by their max token score, expanded to an additive block mask on top of the causal mask, with the shared index key cached alongside the regular K (requires `sparse_index_dim == head_dim`, else the indexer falls back to dense). When the selected window still covers at least half the live cache, attention stays dense; when `sparse_topk_blocks` covers every block, the block mask is all zeros and attention is bit-identical to dense; a zero `sparse_block_size` or `sparse_topk_blocks` is rejected at load time instead of dividing by zero or mis-indexing the block partition. Only the text decoder is implemented; the VL wrapper and MTP head are out of scope (MTP tensors are skipped on load). The only public checkpoint is the 427B `MiniMaxAI/MiniMax-M3` VL repo, which exceeds the development machine's memory, so validation is synthetic reduced-config unit tests plus a real-`text_config` parse test; real-checkpoint load/generate carries over to a follow-up runtime validation.)
- InternLM 2 / 3 (both families share one dynamic-NTK rotary schedule, `src/models/dynamic_ntk_rope.rs`: positions are never scaled, and the rotary base is recomputed per forward from the live sequence length, departing from `rope_theta` only once the sequence passes `max_position_embeddings`. That is what the checkpoints' own remote code implements, via transformers' `_compute_dynamic_ntk_parameters`; a `linear` block is the mirror image, dividing the position by `factor` and leaving the base alone. Like every other text family here they satisfy the maskless-prefill contract by routing a multi-token prefill with no caller mask through `causal_attention`. Validation checkpoint: `mlx-community/internlm3-8b-instruct-4bit`, token-exact on a 56-token prompt against a **corrected** mlx-lm 0.31.3 greedy reference, and pinned by `tests/causal_prefill_greedy_parity.rs`. The correction matters and the qualifier is not decorative: stock mlx-lm 0.31.3 computes `rope_scale = 1 / factor if rope_type == "linear" else 2.0` for both InternLM families, so on a `dynamic` checkpoint it rotates every token at twice its true position, and mlxcel matched it id for id until #1324 because the same expression had been ported verbatim. The reference this entry now claims parity against is that same mlx-lm with only its per-layer rope module replaced by the schedule above; ids from mlxcel's own output were deliberately not used. That parity holds on identical prompt ids, which is the only comparison that isolates the model: this checkpoint ships a `tokenizer.json` whose byte-fallback splitting disagrees with its own `tokenizer.model`, and mlxcel prefers `tokenizer.json` while the reference harness loads the repo's `InternLM3Tokenizer` under `trust_remote_code`. Both tokenizations round-trip to the same text, so an end-to-end CLI comparison against mlx-lm compares two different prompt id sequences and diverges for reasons that have nothing to do with the decoder. InternLM2's own checkpoint, `mlx-community/internlm2_5-7b-chat-4bit`, is held to a weaker standard, and issue #1320 records exactly which one: a 34021-token prompt enters the dynamic branch and rescales to `base_eff=1077737.0`, which is the closed form above evaluated at that length (f64 gives 1077736.99 there, so the f32 the code computes agrees with the exact value to every digit the log prints; the length is what has to be quoted carefully, since the base moves about 62 per token at that point and 34020 gives 1077674.91). What that does not establish is the rotation itself. The accompanying byte-identity runs, an 89-token prompt and the 34021-token one, compare this tree against the same tree with only the schedule's debug diagnostic removed, so they are a control showing the diagnostic is inert, not a parity result. No corrected long-context reference exists for this family the way it does for InternLM3 above, so the long run's standing claim is that the branch is entered and computes the documented base, and no more.)
- GLM 4, GLM MoE, GLM MoE Lite (`glm4_moe_lite`, GLM-4.7-Flash; its next-token-prediction layer is served as a separate MTP drafter, see the speculative-decoding table), GLM MoE DSA
- GLM (`glm`, `GlmForCausalLM`: the transformers port of GLM-4-9B (`zai-org/glm-4-9b-chat-hf`, `glm-4-9b-hf`) and the GLM-Edge chat models (`zai-org/glm-edge-1.5b-chat`, `glm-edge-4b-chat`). The GLM 4 block without its two post-norms: interleaved RoPE on the first `partial_rotary_factor * head_dim` dimensions of each head, Q/K/V biases when the checkpoint has them, a fused `gate_up_proj` SwiGLU MLP, tied or untied head. Config defaults are transformers' `GlmConfig` ones: the 9B configs omit `partial_rotary_factor`, which means 0.5 (the original ChatGLM rotates half of each head), while mlx-lm's `glm` module rotates the whole head there; GLM-Edge declares 1.0. Validated against transformers 5.20.2 (float32, CPU) on the bf16 releases of `glm-edge-1.5b-chat`, `glm-edge-4b-chat` and `glm-4-9b-chat-hf`: on a 23-id and a 521/557-id chat prompt, the transformers token is mlxcel's argmax at all 64 teacher-forced steps, and `tests/glm_parity.rs` pins the 1.5B and the 9B. A `rope_scaling` other than the default is refused. No tensor parallelism. GLM-Edge-V (`zai-org/glm-edge-v-2b`, `glm-edge-v-5b`: `glm` with a `vision_config`) loads as the text decoder only; its vision tower (`model.vision.*`) is ignored and images are not supported.)
- ERNIE 4.5 and ERNIE 4.5 MoE
- Hunyuan dense and MoE variants (`hunyuan_v1_dense` and `hunyuan_moe`, Tencent: separate implementations sharing only the generic core layers, both with per-head Q/K RMSNorm applied after the rotation and a DynamicNTK-alpha rope base folded in once at load (`rope_theta * alpha^(d/(d-2))`) rather than recomputed per forward; the MoE adds softmax routing over `num_experts` with per-layer `moe_topk`, an optional shared MLP gated by `use_mixed_mlp_moe`, and optional cross-layer attention (`use_cla`) where a layer reuses an earlier layer's K/V but still runs its own SDPA, which is why the mask policy has to live in the attention leaf rather than in the CLA plumbing above it. Both satisfy the maskless-prefill contract by routing a multi-token prefill with no caller mask through `causal_attention`. Validation checkpoint for the dense family: `tencent/Hunyuan-1.8B-Instruct` as a 4-bit MLX conversion, token-exact against the mlx-lm 0.31.3 greedy reference on a 36-token chat-templated prompt and pinned by `tests/causal_prefill_greedy_parity.rs`. That checkpoint degenerates on raw text completion under the reference itself, so a coherent continuation needs the chat template; the parity gate is on prompt ids either way. The MoE family has no runnable reference: the only local checkpoint is `mlx-community/Hunyuan-A13B-Instruct-4bit` at 42 GB and its bf16 sibling does not fit the development machine, so it carries the reference-free causality gate only, opt-in behind `MLXCEL_TEST_HUNYUAN_MOE=1` so a 42 GB load stays off the default test run.)
- IBM Granite dense (`granite`)
Expand Down
3 changes: 3 additions & 0 deletions src/distributed/tensor_parallel/inference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,9 @@ fn fallback_architecture(model_type: ModelType) -> &'static str {
ModelType::InternLM2 => "internlm2",
ModelType::InternLM3 => "internlm3",
ModelType::Baichuan => "baichuan",
// GLM is not TP-enabled (no `glm` plan); this arm keeps the dispatch
// table total.
ModelType::Glm => "glm",
ModelType::Glm4 | ModelType::Glm4v | ModelType::GlmOcr => "glm4",
ModelType::Glm4Moe | ModelType::Glm4vMoe => "glm4_moe",
ModelType::Glm4MoeLite => "glm4_moe_lite",
Expand Down
1 change: 1 addition & 0 deletions src/execution/memory_estimate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1327,6 +1327,7 @@ fn inspect_registry_id(model_type: ModelType) -> &'static str {
ModelType::InternLM2 => "internlm2",
ModelType::InternLM3 => "internlm3",
ModelType::Baichuan => "baichuan",
ModelType::Glm => "glm",
ModelType::Glm4 => "glm4",
ModelType::Glm4Moe => "glm4_moe",
ModelType::Glm4MoeLite => "glm4_moe_lite",
Expand Down
2 changes: 2 additions & 0 deletions src/loaded_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ pub enum LoadedModel {
InternLM2(models::InternLM2Model),
InternLM3(models::InternLM3Model),
Baichuan(models::BaichuanModel),
Glm(models::GlmModel),
Glm4(models::Glm4Model),
Glm4Moe(models::Glm4MoeModel),
Glm4MoeLite(models::Glm4MoeLiteModel),
Expand Down Expand Up @@ -411,6 +412,7 @@ macro_rules! delegate_language_model {
LoadedModel::InternLM2(inner) => LanguageModel::$method(inner, $($arg),*),
LoadedModel::InternLM3(inner) => LanguageModel::$method(inner, $($arg),*),
LoadedModel::Baichuan(inner) => LanguageModel::$method(inner, $($arg),*),
LoadedModel::Glm(inner) => LanguageModel::$method(inner, $($arg),*),
LoadedModel::Glm4(inner) => LanguageModel::$method(inner, $($arg),*),
LoadedModel::Glm4Moe(inner) => LanguageModel::$method(inner, $($arg),*),
LoadedModel::Glm4MoeLite(inner) => LanguageModel::$method(inner, $($arg),*),
Expand Down
3 changes: 2 additions & 1 deletion src/loading/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,8 @@ fn parse_eos_token_ids(config: &serde_json::Value) -> Vec<i32> {
/// [`parse_eos_token_ids`] skips them. The error names the offending value.
///
/// Used by: `models::limite_config::ModelArgs::validate`,
/// `models::xing4_0::Xing40Config` deserialization.
/// `models::xing4_0::Xing40Config` deserialization,
/// `models::glm::ModelArgs::eos_token_ids`.
pub(crate) fn checked_eos_token_ids(value: Option<&serde_json::Value>) -> Result<Vec<i32>, String> {
let items: &[serde_json::Value] = match value {
Some(serde_json::Value::Array(items)) => items,
Expand Down
1 change: 1 addition & 0 deletions src/model_metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ macro_rules! for_each_model_registration {
InternLM2 => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::InternLM2Model::load, args: models::internlm2::ModelArgs, weight_builder: models::InternLM2Model::from_weights, wrap: LoadedModel::InternLM2 } };
InternLM3 => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::InternLM3Model::load, args: models::internlm3::ModelArgs, weight_builder: models::InternLM3Model::from_weights, wrap: LoadedModel::InternLM3 } };
Baichuan => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::BaichuanModel::load, args: models::baichuan::BaichuanConfig, weight_builder: models::BaichuanModel::from_weights, wrap: LoadedModel::Baichuan } };
Glm => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::GlmModel::load, args: models::glm::ModelArgs, weight_builder: models::GlmModel::from_weights, wrap: LoadedModel::Glm } };
Glm4 => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::Glm4Model::load, args: models::glm4::ModelArgs, weight_builder: models::Glm4Model::from_weights, wrap: LoadedModel::Glm4 } };
Glm4Moe => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::Glm4MoeModel::load, args: models::glm4_moe::ModelArgs, weight_builder: models::Glm4MoeModel::from_weights, wrap: LoadedModel::Glm4Moe } };
Glm4MoeLite => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::Glm4MoeLiteModel::load, args: models::glm4_moe_lite::ModelArgs, weight_builder: models::Glm4MoeLiteModel::from_weights, wrap: LoadedModel::Glm4MoeLite } };
Expand Down
1 change: 1 addition & 0 deletions src/models/batched_decode_coverage_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ const EXPECTED_NATIVE: &[&str] = &[
"Glm4vMoeModel@src/vision/glm4v_moe.rs",
"Glm4vMoeTextModel@src/models/glm4v_moe.rs",
"Glm4vTextModel@src/models/glm4v.rs",
"GlmModel@src/models/glm.rs",
"GlmOcrModel@src/vision/glm_ocr.rs",
"Gpt2Model@src/models/gpt2.rs",
"GptBigCodeModel@src/models/gpt_bigcode.rs",
Expand Down
1 change: 1 addition & 0 deletions src/models/detection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1120,6 +1120,7 @@ pub(crate) fn detect_model_type_with_probes<P: ModelDetectionProbes + ?Sized>(
"internlm3" => Ok(ModelType::InternLM3),
"baichuan_m1" => Ok(ModelType::Baichuan),
"bitnet" => Ok(ModelType::BitNet),
"glm" => Ok(ModelType::Glm),
"glm4" => Ok(ModelType::Glm4),
"glm4_moe" => Ok(ModelType::Glm4Moe),
"solar_open" => Ok(ModelType::SolarOpen),
Expand Down
25 changes: 25 additions & 0 deletions src/models/detection_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,31 @@ fn gptj_model_type_is_detected() {
);
}

#[test]
fn glm_model_type_is_detected_apart_from_glm4() {
// `GlmForCausalLM` (GLM-4-9B `-hf`, GLM-Edge) says `glm`; it is not the
// `glm4` block with the two extra post-norms.
assert_eq!(
detect_config(
"glm",
json!({
"model_type": "glm",
"architectures": ["GlmForCausalLM"],
"num_attention_heads": 32,
"num_key_value_heads": 2
}),
),
ModelType::Glm
);
assert_eq!(
detect_config(
"glm4-not-glm",
json!({ "model_type": "glm4", "architectures": ["Glm4ForCausalLM"] })
),
ModelType::Glm4
);
}

#[test]
fn gpt_neox_model_type_is_detected() {
// GPT-NeoX shares the `GPT` prefix in `architectures` with GPT-2 and
Expand Down
Loading