From 8862f7a694940ad8f78145d23bad9254c20eb9e3 Mon Sep 17 00:00:00 2001 From: Jaeyeong Choi <144660874+Jaeyeong-CHOI@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:53:56 +0900 Subject: [PATCH] feat(models): port GLM (glm, GlmForCausalLM) The transformers port of GLM-4-9B (glm-4-9b-chat-hf) and the GLM-Edge chat models declare model_type "glm" and were refused as an unsupported model type. The block is the GLM 4 block without its two extra post-norms, so the new module reuses glm4::Attention and glm4::MLP and adds a two-norm block and a tied or untied head. The config defaults follow transformers' GlmConfig, not mlx-lm. The 9B configs omit partial_rotary_factor, which GlmConfig reads as 0.5; mlx-lm's glm module rotates the whole head and diverges from transformers there. Pinned against transformers on the bf16 releases of glm-edge-1.5b-chat and glm-4-9b-chat-hf. --- docs/supported-models.md | 1 + src/distributed/tensor_parallel/inference.rs | 3 + src/execution/memory_estimate.rs | 1 + src/loaded_model.rs | 2 + src/loading/mod.rs | 3 +- src/model_metadata.rs | 1 + src/models/batched_decode_coverage_tests.rs | 1 + src/models/detection.rs | 1 + src/models/detection_tests.rs | 25 + src/models/glm.rs | 553 ++++++++++++++ src/models/glm4.rs | 3 + src/models/glm_tests.rs | 678 ++++++++++++++++++ src/models/last_row_logits_tests.rs | 1 + src/models/mod.rs | 8 + .../popular_dense_batched_decode_tests.rs | 36 + src/models/registry.rs | 2 + tests/glm_parity.rs | 304 ++++++++ 17 files changed, 1622 insertions(+), 1 deletion(-) create mode 100644 src/models/glm.rs create mode 100644 src/models/glm_tests.rs create mode 100644 tests/glm_parity.rs diff --git a/docs/supported-models.md b/docs/supported-models.md index 80cfc9ab08..cf38049926 100644 --- a/docs/supported-models.md +++ b/docs/supported-models.md @@ -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`) diff --git a/src/distributed/tensor_parallel/inference.rs b/src/distributed/tensor_parallel/inference.rs index 87865340dd..909724dd62 100644 --- a/src/distributed/tensor_parallel/inference.rs +++ b/src/distributed/tensor_parallel/inference.rs @@ -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", diff --git a/src/execution/memory_estimate.rs b/src/execution/memory_estimate.rs index 40cfa3f7f2..f6d45e6304 100644 --- a/src/execution/memory_estimate.rs +++ b/src/execution/memory_estimate.rs @@ -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", diff --git a/src/loaded_model.rs b/src/loaded_model.rs index a87f38b898..7e31222a37 100644 --- a/src/loaded_model.rs +++ b/src/loaded_model.rs @@ -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), @@ -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),*), diff --git a/src/loading/mod.rs b/src/loading/mod.rs index e896531372..ac788a9aee 100644 --- a/src/loading/mod.rs +++ b/src/loading/mod.rs @@ -153,7 +153,8 @@ fn parse_eos_token_ids(config: &serde_json::Value) -> Vec { /// [`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, String> { let items: &[serde_json::Value] = match value { Some(serde_json::Value::Array(items)) => items, diff --git a/src/model_metadata.rs b/src/model_metadata.rs index 6806da86f1..54c4ed030d 100644 --- a/src/model_metadata.rs +++ b/src/model_metadata.rs @@ -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 } }; diff --git a/src/models/batched_decode_coverage_tests.rs b/src/models/batched_decode_coverage_tests.rs index 03ca256084..ce9c7e829d 100644 --- a/src/models/batched_decode_coverage_tests.rs +++ b/src/models/batched_decode_coverage_tests.rs @@ -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", diff --git a/src/models/detection.rs b/src/models/detection.rs index 08c15bd123..88c26a78ab 100644 --- a/src/models/detection.rs +++ b/src/models/detection.rs @@ -1120,6 +1120,7 @@ pub(crate) fn detect_model_type_with_probes( "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), diff --git a/src/models/detection_tests.rs b/src/models/detection_tests.rs index 1e0dbd96e4..c2d199121c 100644 --- a/src/models/detection_tests.rs +++ b/src/models/detection_tests.rs @@ -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 diff --git a/src/models/glm.rs b/src/models/glm.rs new file mode 100644 index 0000000000..919099952e --- /dev/null +++ b/src/models/glm.rs @@ -0,0 +1,553 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! GLM (`glm`, `GlmForCausalLM`) model implementation using mlxcel-core +//! +//! The transformers port of ChatGLM-4 (`zai-org/glm-4-9b-chat-hf`, +//! `glm-4-9b-hf`) and the GLM-Edge chat models (`glm-edge-1.5b-chat`, +//! `glm-edge-4b-chat`). It is the GLM-4 (`glm4`) block without the two extra +//! post-norms, so the attention and the fused `gate_up_proj` MLP are the +//! `glm4` ones: +//! - Interleaved (traditional) RoPE over the first +//! `partial_rotary_factor * head_dim` dimensions of each head +//! - Two RMSNorms per block (input, post_attention), pre-norm residuals +//! - Optional Q/K/V biases, loaded when the checkpoint carries them +//! +//! The config defaults are transformers' `GlmConfig` ones, not mlx-lm's. The +//! 9B configs omit `partial_rotary_factor`, and `GlmConfig` reads that as 0.5 +//! (the original ChatGLM rotates half of each head); mlx-lm's `glm` module +//! rotates the full head instead. The GLM-Edge configs declare 1.0, where the +//! two agree. +//! +//! GLM-Edge-V (`zai-org/glm-edge-v-2b`, `glm-edge-v-5b`) also says `glm`, +//! with a `vision_config` and a SigLIP tower under `model.vision.*`. Only its +//! text decoder runs here: the tower is left unread on purpose (see +//! `ignored_vision_tower_tensors`) and images are not supported. + +use crate::models::glm4::{Attention, MLP}; +use mlxcel_core::generate::{BatchedDecodeKind, LanguageModel, route_batched_decode}; +use mlxcel_core::layers::{KVCache, RMSNorm, UnifiedEmbedding, UnifiedLinear}; +use mlxcel_core::weights::WeightMap; +use mlxcel_core::{MlxArray, UniquePtr}; +use serde::Deserialize; +use std::path::Path; + +// Configuration. +#[derive(Debug, Clone, Deserialize)] +#[serde(remote = "Self")] +pub struct ModelArgs { + pub model_type: String, + pub hidden_size: usize, + pub num_hidden_layers: usize, + pub intermediate_size: usize, + pub num_attention_heads: usize, + pub vocab_size: usize, + pub num_key_value_heads: usize, + + #[serde(default = "default_head_dim")] + pub head_dim: usize, + + #[serde(default = "default_rms_norm_eps")] + pub rms_norm_eps: f32, + + #[serde(default = "default_rope_theta")] + pub rope_theta: f32, + + /// Fraction of each head that RoPE rotates. Absent means 0.5, as in + /// transformers' `GlmConfig`. + #[serde(default = "default_partial_rotary_factor")] + pub partial_rotary_factor: f32, + + /// Informational: the Q/K/V biases are loaded when the checkpoint has + /// them, whatever this says. + #[serde(default = "default_attention_bias")] + pub attention_bias: bool, + + #[serde(default)] + pub tie_word_embeddings: bool, + + #[serde(default = "default_max_position_embeddings")] + pub max_position_embeddings: usize, + + #[serde(default)] + pub eos_token_id: Option, + + /// Only the plain RoPE is implemented; [`ModelArgs::validate`] refuses any + /// other `rope_scaling` type rather than run it unscaled. + #[serde(default)] + pub rope_scaling: Option, + + #[serde(default)] + pub quantization: Option, + + /// GLM-Edge-V's vision tower. Read only to say that the tower is ignored; + /// see [`ModelArgs::has_vision_tower`]. + #[serde(default)] + pub vision_config: Option, +} + +mlxcel_core::impl_rope_lifting_deserialize!(ModelArgs); + +/// Weight-name prefix of GLM-Edge-V's vision tower (SigLIP plus adapter). +pub(crate) const VISION_TOWER_PREFIX: &str = "model.vision."; + +/// Number of GLM-Edge-V vision tower tensors in `weights`, none of which the +/// text decoder reads. +/// +/// The decoder looks every weight up by name, so these tensors stay in the +/// map unread. The loaded arrays are lazy, so their data is never read from +/// disk, and they are dropped with the map once the model is built. +pub(crate) fn ignored_vision_tower_tensors(weights: &WeightMap) -> usize { + weights + .keys() + .filter(|name| name.starts_with(VISION_TOWER_PREFIX)) + .count() +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Quantization { + pub group_size: i32, + pub bits: i32, +} + +fn default_head_dim() -> usize { + 128 +} + +fn default_rms_norm_eps() -> f32 { + 1.5625e-07 +} + +fn default_rope_theta() -> f32 { + 10000.0 +} + +fn default_partial_rotary_factor() -> f32 { + 0.5 +} + +fn default_attention_bias() -> bool { + true +} + +fn default_max_position_embeddings() -> usize { + 131072 +} + +/// transformers' `GlmConfig` default: `<|endoftext|>`, `<|user|>`, +/// `<|observation|>` of the GLM-4 tokenizer. +const DEFAULT_EOS_TOKEN_IDS: [i32; 3] = [151329, 151336, 151338]; + +impl ModelArgs { + /// Whether the config declares a vision tower (GLM-Edge-V). `null` and an + /// empty object do not count, as in `detection::has_vision_config`. + pub fn has_vision_tower(&self) -> bool { + match &self.vision_config { + None | Some(serde_json::Value::Null) => false, + Some(serde_json::Value::Object(map)) => !map.is_empty(), + Some(_) => true, + } + } + + /// Number of leading dimensions of each head that RoPE rotates. + pub fn rope_dims(&self) -> usize { + (self.partial_rotary_factor * self.head_dim as f32) as usize + } + + pub fn group_size(&self) -> i32 { + self.quantization + .as_ref() + .map(|q| q.group_size) + .unwrap_or(64) + } + + pub fn bits(&self) -> i32 { + self.quantization.as_ref().map(|q| q.bits).unwrap_or(4) + } + + /// The configured end-of-sequence ids, or the `GlmConfig` default when + /// the config has none. + pub fn eos_token_ids(&self) -> Result, String> { + let ids = crate::loading::checked_eos_token_ids(self.eos_token_id.as_ref())?; + Ok(if ids.is_empty() { + DEFAULT_EOS_TOKEN_IDS.to_vec() + } else { + ids + }) + } + + /// Refuse configs this port would run wrongly instead of failing later + /// with a shape error or silently producing other logits. + pub fn validate(&self) -> Result<(), String> { + if self.num_attention_heads == 0 || self.num_key_value_heads == 0 { + return Err(format!( + "GLM: num_attention_heads ({}) and num_key_value_heads ({}) must be positive", + self.num_attention_heads, self.num_key_value_heads + )); + } + if !self + .num_attention_heads + .is_multiple_of(self.num_key_value_heads) + { + return Err(format!( + "GLM: num_attention_heads ({}) is not a multiple of num_key_value_heads ({})", + self.num_attention_heads, self.num_key_value_heads + )); + } + if !(self.partial_rotary_factor.is_finite() + && self.partial_rotary_factor > 0.0 + && self.partial_rotary_factor <= 1.0) + { + return Err(format!( + "GLM: partial_rotary_factor must be in (0, 1], got {}", + self.partial_rotary_factor + )); + } + let rope_dims = self.rope_dims(); + if rope_dims == 0 || !rope_dims.is_multiple_of(2) { + return Err(format!( + "GLM: partial_rotary_factor {} gives {} rotary dimensions of head_dim {}; \ + the interleaved RoPE needs a positive even count", + self.partial_rotary_factor, rope_dims, self.head_dim + )); + } + if let Some(scaling) = self.rope_scaling.as_ref().filter(|v| !v.is_null()) { + let kind = scaling + .get("rope_type") + .or_else(|| scaling.get("type")) + .and_then(serde_json::Value::as_str) + .unwrap_or(""); + if kind != "default" { + return Err(format!( + "GLM: rope_scaling type `{kind}` is not supported; only the default RoPE is" + )); + } + } + self.eos_token_ids()?; + Ok(()) + } + + /// The same settings in the shape of the GLM-4 decoder's config, whose + /// attention and MLP this model shares. + fn glm4_args(&self) -> crate::models::glm4::ModelArgs { + crate::models::glm4::ModelArgs { + model_type: self.model_type.clone(), + hidden_size: self.hidden_size, + num_hidden_layers: self.num_hidden_layers, + intermediate_size: self.intermediate_size, + num_attention_heads: self.num_attention_heads, + vocab_size: self.vocab_size, + num_key_value_heads: self.num_key_value_heads, + head_dim: self.head_dim, + rms_norm_eps: self.rms_norm_eps, + rope_theta: self.rope_theta, + partial_rotary_factor: self.partial_rotary_factor, + attention_bias: self.attention_bias, + rope_traditional: true, + max_position_embeddings: self.max_position_embeddings, + quantization: self + .quantization + .as_ref() + .map(|q| crate::models::glm4::Quantization { + group_size: q.group_size, + bits: q.bits, + }), + } + } +} + +// Transformer Block with 2 RMSNorm layers. +pub struct TransformerBlock { + pub self_attn: Attention, + pub mlp: MLP, + pub input_layernorm: RMSNorm, + pub post_attention_layernorm: RMSNorm, +} + +impl TransformerBlock { + pub fn forward( + &self, + x: &MlxArray, + cache: &mut KVCache, + mask: Option<&MlxArray>, + ) -> UniquePtr { + let normed = self.input_layernorm.forward(x); + let attn_out = self.self_attn.forward(&normed, cache, mask); + let h = mlxcel_core::add(x, &attn_out); + + let normed = self.post_attention_layernorm.forward(&h); + let mlp_out = self.mlp.forward(&normed); + mlxcel_core::add(&h, &mlp_out) + } + + pub fn forward_batched( + &self, + x: &MlxArray, + caches: &mut [&mut KVCache], + layer_idx: usize, + mask: Option<&MlxArray>, + ) -> UniquePtr { + let normed = self.input_layernorm.forward(x); + let q = self.self_attn.q_proj.forward(&normed); + let k = self.self_attn.k_proj.forward(&normed); + let v = self.self_attn.v_proj.forward(&normed); + let seq_len = mlxcel_core::array_shape(&q)[1]; + let metadata = crate::models::batched_decode_cache::uniform_layer_metadata( + caches, seq_len, 0, "GLM", layer_idx, + ); + let attn = mlxcel_core::batched_decode::forward_split_attention( + &self.self_attn, + &q, + &k, + &v, + caches, + &metadata, + mask, + ); + let attn = self.self_attn.o_proj.forward(&attn); + let h = mlxcel_core::add(x, &attn); + let normed = self.post_attention_layernorm.forward(&h); + let mlp = self.mlp.forward(&normed); + mlxcel_core::add(&h, &mlp) + } + + fn from_weights( + weights: &WeightMap, + args: &ModelArgs, + glm4_args: &crate::models::glm4::ModelArgs, + layer_idx: usize, + ) -> Result { + let prefix = format!("model.layers.{}", layer_idx); + + let self_attn = + Attention::from_weights(weights, glm4_args, &format!("{}.self_attn", prefix))?; + let mlp = MLP::from_weights(weights, glm4_args, &format!("{}.mlp", prefix))?; + + let input_norm_weight = + get_weight_copy(weights, &format!("{}.input_layernorm.weight", prefix))?; + let post_attention_norm_weight = get_weight_copy( + weights, + &format!("{}.post_attention_layernorm.weight", prefix), + )?; + + Ok(Self { + self_attn, + mlp, + input_layernorm: RMSNorm::new(input_norm_weight, args.rms_norm_eps), + post_attention_layernorm: RMSNorm::new(post_attention_norm_weight, args.rms_norm_eps), + }) + } +} + +// GLM Model. +pub struct GlmModel { + pub embed_tokens: UnifiedEmbedding, + pub layers: Vec, + pub norm: RMSNorm, + /// `None` when `tie_word_embeddings` is set: the embedding is the head. + pub lm_head: Option, + pub eos_token_ids: Vec, +} + +impl GlmModel { + /// Forward pass through the entire model + pub fn forward( + &self, + input_ids: &MlxArray, + caches: &mut [KVCache], + mask: Option<&MlxArray>, + ) -> UniquePtr { + self.forward_rows(input_ids, caches, mask, None) + } + + /// [`Self::forward`] projecting every position (`row == None`) or only + /// position `row` (`[B, 1, vocab]`, the prefill's sampled row, #3070). + fn forward_rows( + &self, + input_ids: &MlxArray, + caches: &mut [KVCache], + mask: Option<&MlxArray>, + row: Option, + ) -> UniquePtr { + let mut h = self.embed_tokens.forward(input_ids); + for (i, layer) in self.layers.iter().enumerate() { + h = layer.forward(&h, &mut caches[i], mask); + } + let h = mlxcel_core::generate::select_row(h, row); + let h = self.norm.forward(&h); + self.logits_from_hidden(&h) + } + + /// LM head (or the tied embedding) over normalized hidden states. + fn logits_from_hidden(&self, h: &MlxArray) -> UniquePtr { + match &self.lm_head { + Some(lm_head) => lm_head.forward(h), + None => self.embed_tokens.as_linear(h), + } + } + + pub fn forward_batched_impl( + &self, + input_ids: &MlxArray, + batch_caches: &mut [&mut [KVCache]], + mask: Option<&MlxArray>, + ) -> UniquePtr { + let mut h = self.embed_tokens.forward(input_ids); + for layer_idx in 0..self.layers.len() { + let mut layer_caches = crate::models::batched_decode_cache::collect_layer_caches( + batch_caches, + "GLM", + layer_idx, + ); + h = self.layers[layer_idx].forward_batched(&h, &mut layer_caches, layer_idx, mask); + } + let h = self.norm.forward(&h); + self.logits_from_hidden(&h) + } + + /// Create KV caches for all layers + pub fn make_caches(&self) -> Vec { + (0..self.layers.len()).map(|_| KVCache::new()).collect() + } + + /// Load model from directory + pub fn load>(model_dir: P) -> Result<(Self, ModelArgs), String> { + let model_dir = model_dir.as_ref(); + + let config_path = model_dir.join("config.json"); + let config_str = std::fs::read_to_string(&config_path) + .map_err(|e| format!("Failed to read config.json: {}", e))?; + let args: ModelArgs = serde_json::from_str(&config_str) + .map_err(|e| format!("Failed to parse config.json: {}", e))?; + + let weights = crate::models::load_text_weights(model_dir, None)?; + let model = Self::from_weights(&weights, &args)?; + + Ok((model, args)) + } + + /// Create model from loaded weights + pub fn from_weights(weights: &WeightMap, args: &ModelArgs) -> Result { + args.validate()?; + let vision_tensors = ignored_vision_tower_tensors(weights); + if args.has_vision_tower() || vision_tensors > 0 { + static NOTICE: std::sync::Once = std::sync::Once::new(); + NOTICE.call_once(|| { + eprintln!( + "mlxcel: GLM-Edge-V vision tower is not supported; loading the text decoder only \ + and ignoring vision_config and {vision_tensors} `{VISION_TOWER_PREFIX}*` tensors" + ); + }); + } + let group_size = args.group_size(); + let bits = args.bits(); + let glm4_args = args.glm4_args(); + + let embed_tokens = + UnifiedEmbedding::from_weights(weights, "model.embed_tokens", group_size, bits)?; + + let mut layers = Vec::with_capacity(args.num_hidden_layers); + for i in 0..args.num_hidden_layers { + layers.push(TransformerBlock::from_weights( + weights, args, &glm4_args, i, + )?); + } + + let norm_weight = get_weight_copy(weights, "model.norm.weight")?; + let norm = RMSNorm::new(norm_weight, args.rms_norm_eps); + + let lm_head = if args.tie_word_embeddings { + None + } else { + Some(UnifiedLinear::from_weights( + weights, "lm_head", group_size, bits, + )?) + }; + + Ok(Self { + embed_tokens, + layers, + norm, + lm_head, + eos_token_ids: args.eos_token_ids()?, + }) + } +} + +// Helper Functions. +fn get_weight_copy(weights: &WeightMap, name: &str) -> Result, String> { + weights + .get(name) + .map(|w| mlxcel_core::copy(w)) + .ok_or_else(|| format!("Weight not found: {}", name)) +} + +// LanguageModel trait implementation. +impl LanguageModel for GlmModel { + fn batched_decode_kind(&self) -> BatchedDecodeKind { + BatchedDecodeKind::Native + } + + fn forward( + &self, + input_ids: &MlxArray, + caches: &mut [KVCache], + mask: Option<&MlxArray>, + ) -> UniquePtr { + GlmModel::forward(self, input_ids, caches, mask) + } + + fn last_row_logits( + &self, + input_ids: &MlxArray, + input_embeddings: Option<&MlxArray>, + _seq_id: Option, + caches: &mut [KVCache], + mask: Option<&MlxArray>, + last_pos: usize, + ) -> Option> { + // No embeddings path: decline so the default keeps its behavior. + if input_embeddings.is_some() { + return None; + } + Some(self.forward_rows(input_ids, caches, mask, Some(last_pos))) + } + + fn make_caches(&self) -> Vec { + GlmModel::make_caches(self) + } + + fn num_layers(&self) -> usize { + self.layers.len() + } + + fn eos_token_ids(&self) -> Vec { + self.eos_token_ids.clone() + } + + fn forward_batched( + &self, + input_ids: &MlxArray, + batch_caches: &mut [&mut [KVCache]], + mask: Option<&MlxArray>, + ) -> UniquePtr { + route_batched_decode(self, input_ids, batch_caches, |caches| { + self.forward_batched_impl(input_ids, caches, mask) + }) + } +} + +#[cfg(test)] +#[path = "glm_tests.rs"] +mod tests; diff --git a/src/models/glm4.rs b/src/models/glm4.rs index e01773727a..de0e6fcb41 100644 --- a/src/models/glm4.rs +++ b/src/models/glm4.rs @@ -19,6 +19,9 @@ //! - Fused gate_up_proj: single projection split into gate and up //! - 4 RMSNorm layers per block (input, post_self_attn, post_attention, post_mlp) //! - RoPE with traditional=true +//! +//! [`Attention`] and [`MLP`] are also the GLM (`glm`, `GlmForCausalLM`) +//! block's, in `glm.rs`, which drops the two post-norms. use mlxcel_core::generate::{BatchedDecodeKind, LanguageModel, route_batched_decode}; use mlxcel_core::layers::{KVCache, RMSNorm, UnifiedEmbedding, UnifiedLinear}; diff --git a/src/models/glm_tests.rs b/src/models/glm_tests.rs new file mode 100644 index 0000000000..4d61fb16a3 --- /dev/null +++ b/src/models/glm_tests.rs @@ -0,0 +1,678 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Unit tests for GLM (`glm`, `GlmForCausalLM`). +//! +//! The config tests pin the transformers `GlmConfig` defaults, above all the +//! 0.5 `partial_rotary_factor` that the GLM-4-9B configs leave out. The +//! forward test runs a two-layer model against an independent f64 reference +//! written from transformers' `modeling_glm.py` (interleaved rotation of the +//! leading `partial_rotary_factor * head_dim` dimensions, two norms per +//! block, Q/K/V biases, tied head), and checks that the reference would have +//! caught a full-head rotation. Real checkpoints are compared with +//! transformers in `tests/glm_parity.rs`. + +use super::{GlmModel, ModelArgs}; +use mlxcel_core::weights::WeightMap; +use serde_json::{Value, json}; + +/// `zai-org/glm-4-9b-chat-hf`'s `config.json` (no `partial_rotary_factor`). +const GLM4_9B_CHAT_CONFIG: &str = r#"{ + "architectures": ["GlmForCausalLM"], + "attention_bias": true, + "attention_dropout": 0.0, + "eos_token_id": [151329, 151336, 151338], + "head_dim": 128, + "hidden_act": "silu", + "hidden_size": 4096, + "initializer_range": 0.02, + "intermediate_size": 13696, + "max_position_embeddings": 131072, + "model_type": "glm", + "num_attention_heads": 32, + "num_hidden_layers": 40, + "num_key_value_heads": 2, + "pad_token_id": 151329, + "rms_norm_eps": 1.5625e-07, + "rope_theta": 10000.0, + "tie_word_embeddings": false, + "torch_dtype": "bfloat16", + "transformers_version": "4.46.0.dev0", + "use_cache": true, + "vocab_size": 151552 +}"#; + +/// `zai-org/glm-edge-1.5b-chat`'s `config.json`. +const GLM_EDGE_1_5B_CONFIG: &str = r#"{ + "architectures": ["GlmForCausalLM"], + "partial_rotary_factor": 1.0, + "attention_bias": false, + "attention_dropout": 0.0, + "eos_token_id": [59246, 59253, 59255], + "head_dim": 128, + "hidden_act": "silu", + "hidden_size": 2048, + "initializer_range": 0.02, + "intermediate_size": 6144, + "max_position_embeddings": 8192, + "model_type": "glm", + "num_attention_heads": 16, + "num_hidden_layers": 28, + "num_key_value_heads": 4, + "pad_token_id": 59246, + "rms_norm_eps": 1e-05, + "rope_theta": 10000.0, + "tie_word_embeddings": true, + "torch_dtype": "bfloat16", + "transformers_version": "4.47.0.dev0", + "use_cache": true, + "vocab_size": 59264 +}"#; + +/// `zai-org/glm-edge-v-2b`'s `config.json` (revision +/// 2053707733f99ab52e943904f43c2359a94301ef): GLM-Edge-V says `glm` too, and +/// adds a SigLIP `vision_config` whose tower ships under `model.vision.*`. +const GLM_EDGE_V_2B_CONFIG: &str = r#"{ + "architectures": ["GlmForCausalLM"], + "attention_bias": false, + "attention_dropout": 0.0, + "boi_token_id": 59256, + "eoi_token_id": 59257, + "eos_token_id": [59246, 59253, 59255], + "head_dim": 128, + "hidden_act": "silu", + "hidden_size": 2048, + "initializer_range": 0.02, + "intermediate_size": 6144, + "max_position_embeddings": 4096, + "model_type": "glm", + "num_attention_heads": 16, + "num_hidden_layers": 28, + "num_key_value_heads": 4, + "pad_token_id": 59246, + "partial_rotary_factor": 1.0, + "rms_norm_eps": 1e-05, + "rope_theta": 10000.0, + "tie_word_embeddings": true, + "torch_dtype": "bfloat16", + "transformers_version": "4.47.0.dev0", + "use_cache": true, + "vision_config": { + "hidden_size": 1152, + "image_size": 672, + "intermediate_size": 4304, + "model_type": "siglip_vision_model", + "num_attention_heads": 16, + "num_hidden_layers": 27, + "patch_size": 14, + "torch_dtype": "bfloat16" + }, + "vocab_size": 59264 +}"#; + +fn parse(value: Value) -> Result { + serde_json::from_value(value).map_err(|e| e.to_string()) +} + +fn minimal(extra: Value) -> Value { + let mut config = json!({ + "model_type": "glm", + "hidden_size": 8, + "num_hidden_layers": 1, + "intermediate_size": 16, + "num_attention_heads": 2, + "num_key_value_heads": 1, + "head_dim": 4, + "vocab_size": 32 + }); + for (k, v) in extra.as_object().unwrap() { + config[k] = v.clone(); + } + config +} + +#[test] +fn glm4_9b_config_rotates_half_of_each_head() { + let args: ModelArgs = serde_json::from_str(GLM4_9B_CHAT_CONFIG).expect("9B config parses"); + // transformers' GlmConfig reads the missing key as 0.5; mlx-lm's `glm` + // module rotates the whole head here instead. + assert_eq!(args.partial_rotary_factor, 0.5); + assert_eq!(args.rope_dims(), 64); + assert!(args.attention_bias); + assert!(!args.tie_word_embeddings); + assert_eq!(args.rms_norm_eps, 1.5625e-07); + assert_eq!(args.eos_token_ids().unwrap(), vec![151329, 151336, 151338]); + args.validate().expect("9B config is supported"); +} + +#[test] +fn glm_edge_config_rotates_the_whole_head_and_ties_the_head() { + let args: ModelArgs = serde_json::from_str(GLM_EDGE_1_5B_CONFIG).expect("edge config parses"); + assert_eq!(args.partial_rotary_factor, 1.0); + assert_eq!(args.rope_dims(), 128); + assert!(args.tie_word_embeddings); + assert_eq!(args.rms_norm_eps, 1e-5); + assert_eq!(args.eos_token_ids().unwrap(), vec![59246, 59253, 59255]); + args.validate().expect("edge config is supported"); +} + +#[test] +fn missing_keys_take_the_transformers_glm_config_defaults() { + let args = parse(json!({ + "model_type": "glm", + "hidden_size": 4096, + "num_hidden_layers": 40, + "intermediate_size": 13696, + "num_attention_heads": 32, + "num_key_value_heads": 2, + "vocab_size": 151552 + })) + .unwrap(); + assert_eq!(args.head_dim, 128); + assert_eq!(args.partial_rotary_factor, 0.5); + assert_eq!(args.rope_theta, 10000.0); + assert_eq!(args.rms_norm_eps, 1.5625e-07); + assert!(args.attention_bias); + assert!(!args.tie_word_embeddings); + assert_eq!(args.eos_token_ids().unwrap(), vec![151329, 151336, 151338]); +} + +#[test] +fn transformers_5_rope_parameters_are_lifted() { + let args = parse(minimal(json!({ + "rope_parameters": { + "rope_type": "default", + "rope_theta": 50000.0, + "partial_rotary_factor": 1.0 + } + }))) + .unwrap(); + assert_eq!(args.rope_theta, 50000.0); + assert_eq!(args.partial_rotary_factor, 1.0); + assert_eq!(args.rope_dims(), 4); + args.validate().unwrap(); + + // `rope_parameters` without the factor keeps the 0.5 default. + let args = parse(minimal(json!({ + "rope_parameters": {"rope_type": "default", "rope_theta": 10000.0} + }))) + .unwrap(); + assert_eq!(args.rope_dims(), 2); +} + +#[test] +fn single_integer_eos_is_read() { + let args = parse(minimal(json!({"eos_token_id": 7}))).unwrap(); + assert_eq!(args.eos_token_ids().unwrap(), vec![7]); + // An empty list falls back to the GlmConfig default instead of leaving + // generation with no stop token. This is mlxcel's choice: transformers' + // GlmConfig fills in the default only when `eos_token_id` is absent or + // null, and keeps an explicit `[]`. + let args = parse(minimal(json!({"eos_token_id": []}))).unwrap(); + assert_eq!(args.eos_token_ids().unwrap(), vec![151329, 151336, 151338]); +} + +#[test] +fn unsupported_configs_are_refused() { + let refused = |extra: Value, needle: &str| { + let err = parse(minimal(extra.clone())) + .unwrap() + .validate() + .expect_err(&format!("{extra} must be refused")); + assert!(err.contains(needle), "{extra}: {err}"); + }; + // Rotary factor boundaries: 0, above 1, and one that leaves an odd + // number of rotary dimensions (0.75 * 4 = 3) or none (0.1 * 4 = 0). + refused(json!({"partial_rotary_factor": 0.0}), "(0, 1]"); + refused(json!({"partial_rotary_factor": 1.5}), "(0, 1]"); + refused(json!({"partial_rotary_factor": -0.5}), "(0, 1]"); + refused(json!({"partial_rotary_factor": 0.75}), "positive even"); + refused(json!({"partial_rotary_factor": 0.1}), "positive even"); + // Head counts. + refused(json!({"num_key_value_heads": 0}), "must be positive"); + refused(json!({"num_attention_heads": 0}), "must be positive"); + refused( + json!({"num_attention_heads": 3, "num_key_value_heads": 2}), + "not a multiple", + ); + // Scaled RoPE is not implemented, so it is not run unscaled. + refused( + json!({"rope_scaling": {"rope_type": "linear", "factor": 2.0}}), + "`linear`", + ); + refused( + json!({"rope_scaling": {"type": "yarn", "factor": 4.0}}), + "`yarn`", + ); + // A negative or out-of-range eos id can never be matched. + refused(json!({"eos_token_id": [-1]}), "eos_token_id"); + refused(json!({"eos_token_id": 4294967296u64}), "eos_token_id"); + + // The accepted edges. + for extra in [ + json!({"partial_rotary_factor": 1.0}), + json!({"partial_rotary_factor": 0.5}), + json!({"rope_scaling": null}), + json!({"rope_scaling": {"rope_type": "default"}}), + json!({"num_attention_heads": 2, "num_key_value_heads": 2}), + ] { + parse(minimal(extra.clone())) + .unwrap() + .validate() + .unwrap_or_else(|e| panic!("{extra} must be accepted: {e}")); + } +} + +// --------------------------------------------------------------------------- +// Forward against an f64 reference of transformers' GlmForCausalLM. + +const H: usize = 8; +const NH: usize = 2; +const NKV: usize = 1; +const HD: usize = 4; +const I: usize = 16; +const V: usize = 32; +const LAYERS: usize = 2; +const EPS: f64 = 1e-5; +const THETA: f64 = 10000.0; + +/// Weights as row-major f64 tables, kept beside the MLX copies. +struct Tables { + map: std::collections::HashMap, Vec)>, + phase: usize, +} + +impl Tables { + fn add(&mut self, name: String, shape: &[usize], base: f64, amplitude: f64) { + self.phase += 7; + let len: usize = shape.iter().product(); + let data = (0..len) + .map(|i| base + ((i + self.phase) as f64 * 0.731).sin() * amplitude) + .map(|v| v as f32 as f64) + .collect(); + let shape = shape.iter().map(|&d| d as i32).collect(); + self.map.insert(name, (data, shape)); + } + + fn get(&self, name: &str) -> &[f64] { + &self.map[name].0 + } + + fn weight_map(&self) -> WeightMap { + let mut weights = WeightMap::new(); + for (name, (data, shape)) in &self.map { + let data: Vec = data.iter().map(|&v| v as f32).collect(); + weights.insert(name.clone(), mlxcel_core::from_slice_f32(&data, shape)); + } + weights + } +} + +fn tables() -> Tables { + let mut t = Tables { + map: Default::default(), + phase: 1, + }; + t.add("model.embed_tokens.weight".into(), &[V, H], 0.0, 0.5); + t.add("model.norm.weight".into(), &[H], 0.9, 0.2); + for l in 0..LAYERS { + let p = format!("model.layers.{l}"); + t.add(format!("{p}.input_layernorm.weight"), &[H], 0.9, 0.2); + t.add( + format!("{p}.post_attention_layernorm.weight"), + &[H], + 0.9, + 0.2, + ); + let a = format!("{p}.self_attn"); + t.add(format!("{a}.q_proj.weight"), &[NH * HD, H], 0.0, 0.4); + t.add(format!("{a}.q_proj.bias"), &[NH * HD], 0.0, 0.3); + t.add(format!("{a}.k_proj.weight"), &[NKV * HD, H], 0.0, 0.4); + t.add(format!("{a}.k_proj.bias"), &[NKV * HD], 0.0, 0.3); + t.add(format!("{a}.v_proj.weight"), &[NKV * HD, H], 0.0, 0.4); + t.add(format!("{a}.v_proj.bias"), &[NKV * HD], 0.0, 0.3); + t.add(format!("{a}.o_proj.weight"), &[H, NH * HD], 0.0, 0.4); + t.add( + format!("{p}.mlp.gate_up_proj.weight"), + &[2 * I, H], + 0.0, + 0.3, + ); + t.add(format!("{p}.mlp.down_proj.weight"), &[H, I], 0.0, 0.3); + } + t +} + +fn rms_norm(x: &[f64], w: &[f64]) -> Vec { + let ms = x.iter().map(|v| v * v).sum::() / x.len() as f64; + let r = 1.0 / (ms + EPS).sqrt(); + x.iter().zip(w).map(|(v, g)| v * r * g).collect() +} + +fn linear(w: &[f64], b: Option<&[f64]>, x: &[f64]) -> Vec { + let out = w.len() / x.len(); + (0..out) + .map(|o| { + let dot: f64 = (0..x.len()).map(|i| w[o * x.len() + i] * x[i]).sum(); + dot + b.map_or(0.0, |b| b[o]) + }) + .collect() +} + +/// transformers' `apply_rotary_pos_emb` for GLM: the leading `rot` dims of a +/// head rotate as interleaved pairs, the rest pass through. +fn rope(head: &mut [f64], pos: usize, rot: usize) { + for i in 0..rot / 2 { + let freq = THETA.powf(-((2 * i) as f64) / rot as f64); + let (s, c) = (pos as f64 * freq).sin_cos(); + let (x0, x1) = (head[2 * i], head[2 * i + 1]); + head[2 * i] = x0 * c - x1 * s; + head[2 * i + 1] = x1 * c + x0 * s; + } +} + +fn reference_logits(t: &Tables, tokens: &[i32], rot: usize) -> Vec> { + let emb = t.get("model.embed_tokens.weight"); + let mut hs: Vec> = tokens + .iter() + .map(|&tok| emb[tok as usize * H..(tok as usize + 1) * H].to_vec()) + .collect(); + for l in 0..LAYERS { + let p = format!("model.layers.{l}"); + let a = format!("{p}.self_attn"); + let w = |n: &str| t.get(&format!("{a}.{n}")); + let mut qs = Vec::new(); + let mut ks = Vec::new(); + let mut vs = Vec::new(); + for (pos, h) in hs.iter().enumerate() { + let x = rms_norm(h, t.get(&format!("{p}.input_layernorm.weight"))); + let mut q = linear(w("q_proj.weight"), Some(w("q_proj.bias")), &x); + let mut k = linear(w("k_proj.weight"), Some(w("k_proj.bias")), &x); + for head in q.chunks_mut(HD) { + rope(head, pos, rot); + } + for head in k.chunks_mut(HD) { + rope(head, pos, rot); + } + qs.push(q); + ks.push(k); + vs.push(linear(w("v_proj.weight"), Some(w("v_proj.bias")), &x)); + } + for (pos, h) in hs.iter_mut().enumerate() { + let mut attn = vec![0.0; NH * HD]; + for head in 0..NH { + let kvh = head / (NH / NKV); + let q = &qs[pos][head * HD..(head + 1) * HD]; + let scores: Vec = (0..=pos) + .map(|j| { + let k = &ks[j][kvh * HD..(kvh + 1) * HD]; + q.iter().zip(k).map(|(a, b)| a * b).sum::() / (HD as f64).sqrt() + }) + .collect(); + let m = scores.iter().cloned().fold(f64::MIN, f64::max); + let e: Vec = scores.iter().map(|s| (s - m).exp()).collect(); + let z: f64 = e.iter().sum(); + for (j, ej) in e.iter().enumerate() { + for d in 0..HD { + attn[head * HD + d] += ej / z * vs[j][kvh * HD + d]; + } + } + } + let o = linear(w("o_proj.weight"), None, &attn); + for (hv, ov) in h.iter_mut().zip(&o) { + *hv += ov; + } + let x = rms_norm(h, t.get(&format!("{p}.post_attention_layernorm.weight"))); + let gu = linear(t.get(&format!("{p}.mlp.gate_up_proj.weight")), None, &x); + let act: Vec = (0..I) + .map(|i| { + let g = gu[i]; + g / (1.0 + (-g).exp()) * gu[I + i] + }) + .collect(); + let d = linear(t.get(&format!("{p}.mlp.down_proj.weight")), None, &act); + for (hv, dv) in h.iter_mut().zip(&d) { + *hv += dv; + } + } + } + // Untied when the tables carry an `lm_head`, tied to the embedding + // otherwise. + let head = t + .map + .get("lm_head.weight") + .map_or(emb, |(data, _)| data.as_slice()); + hs.iter() + .map(|h| linear(head, None, &rms_norm(h, t.get("model.norm.weight")))) + .collect() +} + +fn tiny_args(extra: Value) -> ModelArgs { + let mut config = minimal(json!({ + "num_hidden_layers": LAYERS, + "rms_norm_eps": EPS, + "tie_word_embeddings": true, + "attention_bias": true + })); + for (k, v) in extra.as_object().unwrap() { + config[k] = v.clone(); + } + parse(config).unwrap() +} + +fn mlxcel_logits(model: &GlmModel, tokens: &[i32]) -> Vec> { + let input = mlxcel_core::from_slice_i32(tokens, &[1, tokens.len() as i32]); + let mut caches = model.make_caches(); + let logits = model.forward(&input, &mut caches, None); + let flat = mlxcel_core::utils::array_to_vec_f32(&mlxcel_core::astype( + &logits, + mlxcel_core::dtype::FLOAT32, + )); + assert_eq!(flat.len(), tokens.len() * V); + flat.chunks(V) + .map(|row| row.iter().map(|&v| v as f64).collect()) + .collect() +} + +fn max_abs_diff(a: &[Vec], b: &[Vec]) -> f64 { + a.iter() + .flatten() + .zip(b.iter().flatten()) + .map(|(x, y)| (x - y).abs()) + .fold(0.0, f64::max) +} + +#[test] +fn forward_matches_the_transformers_reference_with_the_default_half_rotation() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let t = tables(); + // No `partial_rotary_factor` in the config: 0.5, so 2 of 4 dims rotate. + let args = tiny_args(json!({})); + assert_eq!(args.rope_dims(), 2); + let model = GlmModel::from_weights(&t.weight_map(), &args).expect("tiny GLM builds"); + assert!( + model.lm_head.is_none(), + "tied config keeps no separate head" + ); + + let tokens = [3, 17, 5, 29, 11, 0]; + let got = mlxcel_logits(&model, &tokens); + let half = reference_logits(&t, &tokens, 2); + let full = reference_logits(&t, &tokens, HD); + let err = max_abs_diff(&got, &half); + assert!(err < 1e-4, "max |mlxcel - reference| = {err}"); + // The reference separates the two readings: a full-head rotation (what + // mlx-lm does for the 9B) would be far outside the tolerance. + let gap = max_abs_diff(&half, &full); + assert!(gap > 1e-2, "half vs full rotation differ by only {gap}"); + + // Incremental decode after a prefill gives the same last-row logits. + let mut caches = model.make_caches(); + let prefix = mlxcel_core::from_slice_i32(&tokens[..5], &[1, 5]); + let _ = model.forward(&prefix, &mut caches, None); + let step = mlxcel_core::from_slice_i32(&tokens[5..], &[1, 1]); + let last = mlxcel_core::utils::array_to_vec_f32(&mlxcel_core::astype( + &model.forward(&step, &mut caches, None), + mlxcel_core::dtype::FLOAT32, + )); + let last: Vec = last.iter().map(|&v| v as f64).collect(); + let err = max_abs_diff(&[last], &half[5..]); + assert!(err < 1e-4, "decode step vs reference: {err}"); +} + +#[test] +fn forward_matches_the_reference_with_a_full_rotation_and_untied_head() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let mut t = tables(); + // An untied head with its own values, so a model that projected through + // the embedding instead would miss the reference. + t.add("lm_head.weight".into(), &[V, H], 0.0, 0.5); + let args = tiny_args(json!({"partial_rotary_factor": 1.0, "tie_word_embeddings": false})); + assert_eq!(args.rope_dims(), HD); + let model = GlmModel::from_weights(&t.weight_map(), &args).expect("tiny GLM builds"); + assert!(model.lm_head.is_some()); + + let tokens = [3, 17, 5, 29, 11, 0]; + let untied = reference_logits(&t, &tokens, HD); + let head = t.map.remove("lm_head.weight").unwrap(); + let through_embedding = reference_logits(&t, &tokens, HD); + t.map.insert("lm_head.weight".into(), head); + let gap = max_abs_diff(&untied, &through_embedding); + assert!(gap > 1e-2, "lm_head vs embedding head differ by only {gap}"); + + // A single token: position 0, no rotation at all (the 1-row boundary). + for tokens in [&[9][..], &[3, 17, 5, 29, 11, 0][..]] { + let got = mlxcel_logits(&model, tokens); + let err = max_abs_diff(&got, &reference_logits(&t, tokens, HD)); + assert!(err < 1e-4, "{tokens:?}: max |mlxcel - reference| = {err}"); + } +} + +#[test] +fn missing_post_attention_norm_or_lm_head_is_reported_by_name() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let t = tables(); + let mut weights = t.weight_map(); + weights.remove("model.layers.1.post_attention_layernorm.weight"); + let err = GlmModel::from_weights(&weights, &tiny_args(json!({}))) + .err() + .expect("missing norm is an error"); + assert!( + err.contains("model.layers.1.post_attention_layernorm.weight"), + "{err}" + ); + + let err = GlmModel::from_weights( + &t.weight_map(), + &tiny_args(json!({"tie_word_embeddings": false})), + ) + .err() + .expect("untied config without lm_head is an error"); + assert!(err.contains("lm_head"), "{err}"); +} + +#[test] +fn glm_edge_v_config_parses_as_the_text_decoder() { + let args: ModelArgs = serde_json::from_str(GLM_EDGE_V_2B_CONFIG).expect("edge-v config parses"); + assert!(args.has_vision_tower()); + // The text decoder is GLM-Edge's: whole-head rotation, tied head. + assert_eq!(args.rope_dims(), 128); + assert!(args.tie_word_embeddings); + assert_eq!(args.eos_token_ids().unwrap(), vec![59246, 59253, 59255]); + args.validate() + .expect("a vision_config does not refuse the text decoder"); + + // `null` and `{}` declare no tower, as in `detection::has_vision_config`. + for vision_config in [Value::Null, json!({})] { + let args = parse(minimal(json!({ "vision_config": vision_config }))).unwrap(); + assert!(!args.has_vision_tower(), "{:?}", args.vision_config); + } + assert!(!parse(minimal(json!({}))).unwrap().has_vision_tower()); +} + +/// A GLM-Edge-V-shaped checkpoint directory (the tiny decoder plus tensors +/// under the real tower's names) is detected as `glm` and loads through +/// `GlmModel::load` as the text decoder: the tower tensors reach the weight +/// map, are counted as ignored, and leave the logits exactly as they are +/// without them. +#[test] +fn glm_edge_v_vision_tower_weights_are_ignored_on_load() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let t = tables(); + let mut tensors: Vec<(String, Vec, Vec)> = t + .map + .iter() + .map(|(name, (data, shape))| { + let data = data.iter().map(|&v| v as f32).collect(); + (name.clone(), shape.clone(), data) + }) + .collect(); + let tower = [ + ( + "model.vision.vit.model.vision_model.embeddings.patch_embedding.weight", + vec![6, 3, 2, 2], + ), + ( + "model.vision.adapter.linear_proj.linear_proj.weight", + vec![H as i32, 6], + ), + ("model.vision.adapter.boi", vec![1, 1, H as i32]), + ]; + for (name, shape) in &tower { + let len = shape.iter().product::() as usize; + tensors.push((name.to_string(), shape.clone(), vec![0.25; len])); + } + + let mut config = minimal(json!({ + "num_hidden_layers": LAYERS, + "rms_norm_eps": EPS, + "tie_word_embeddings": true, + "attention_bias": true, + "architectures": ["GlmForCausalLM"], + "boi_token_id": 30, + "eoi_token_id": 31 + })); + let edge_v: Value = serde_json::from_str(GLM_EDGE_V_2B_CONFIG).unwrap(); + config["vision_config"] = edge_v["vision_config"].clone(); + + let dir = crate::models::embedding_test_support::temp_dir("glm_edge_v"); + std::fs::write(dir.join("config.json"), config.to_string()).unwrap(); + crate::models::embedding_test_support::write_f32_safetensors( + &dir.join("model.safetensors"), + &tensors, + ); + + assert_eq!( + crate::models::detection::get_model_type(&dir).unwrap(), + crate::models::ModelType::Glm + ); + let weights = crate::models::load_text_weights(&dir, None).unwrap(); + assert_eq!( + super::ignored_vision_tower_tensors(&weights), + tower.len(), + "the tower tensors are in the loaded map, unread by the decoder" + ); + drop(weights); + + let (model, args) = GlmModel::load(&dir).expect("edge-v checkpoint loads text-only"); + assert!(args.has_vision_tower()); + let tokens = [3, 17, 5, 29, 11, 0]; + let err = max_abs_diff( + &mlxcel_logits(&model, &tokens), + &reference_logits(&t, &tokens, 2), + ); + assert!(err < 1e-4, "max |mlxcel - reference| = {err}"); + + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/src/models/last_row_logits_tests.rs b/src/models/last_row_logits_tests.rs index a46621beef..41c5324f5a 100644 --- a/src/models/last_row_logits_tests.rs +++ b/src/models/last_row_logits_tests.rs @@ -25,6 +25,7 @@ last_row_case!(cohere_last_row_logits, dense::tiny_cohere_model); last_row_case!(ernie45_last_row_logits, dense::tiny_ernie45_model); last_row_case!(exaone_last_row_logits, dense::tiny_exaone_model); last_row_case!(gemma_last_row_logits, dense::tiny_gemma_model, embeddings); +last_row_case!(glm_last_row_logits, dense::tiny_glm_model); last_row_case!(glm4_last_row_logits, dense::tiny_glm4_model); last_row_case!( granite_last_row_logits, diff --git a/src/models/mod.rs b/src/models/mod.rs index aa095d76f0..1d7305fd6b 100644 --- a/src/models/mod.rs +++ b/src/models/mod.rs @@ -219,6 +219,7 @@ pub mod gemma3_embedding; pub mod gemma3n; pub mod gemma4; pub mod gemma4_mtp_target; +pub mod glm; pub mod glm4; pub mod glm4_moe; pub mod glm4_moe_lite; @@ -452,6 +453,7 @@ pub use gemma2::Gemma2Model; pub use gemma3::{Gemma3Model, Gemma3Wrapper}; pub use gemma3n::Gemma3nModel; pub use gemma4::{Gemma4Model, Gemma4SpeculativeSinks, Gemma4Wrapper}; +pub use glm::GlmModel; pub use glm_moe_dsa::GlmMoeDsaModel; pub use glm4::Glm4Model; pub use glm4_moe::Glm4MoeModel; @@ -750,6 +752,9 @@ pub enum ModelType { InternLM2, InternLM3, Baichuan, + /// GLM (`glm`, `GlmForCausalLM`): GLM-4-9B (`-hf`) and GLM-Edge, the + /// GLM-4 block without its two post-norms. + Glm, Glm4, Glm4Moe, Glm4MoeLite, @@ -1098,6 +1103,7 @@ pub const ALL_MODEL_TYPES: &[ModelType] = &[ ModelType::InternLM2, ModelType::InternLM3, ModelType::Baichuan, + ModelType::Glm, ModelType::Glm4, ModelType::Glm4Moe, ModelType::Glm4MoeLite, @@ -1376,6 +1382,7 @@ impl ModelType { ModelType::InternLM3 => ("InternLM 3", "InternLM"), // ----- GLM ----- + ModelType::Glm => ("GLM (GLM-4-9B, GLM-Edge)", "GLM"), ModelType::Glm4 => ("GLM 4", "GLM"), ModelType::Glm4Moe => ("GLM 4 MoE", "GLM"), ModelType::Glm4MoeLite => ("GLM 4 MoE Lite", "GLM"), @@ -1901,6 +1908,7 @@ mod metadata_tests { InternLM2, InternLM3, Baichuan, + Glm, Glm4, Glm4Moe, Glm4MoeLite, diff --git a/src/models/popular_dense_batched_decode_tests.rs b/src/models/popular_dense_batched_decode_tests.rs index af66f82b41..b349db3322 100644 --- a/src/models/popular_dense_batched_decode_tests.rs +++ b/src/models/popular_dense_batched_decode_tests.rs @@ -252,6 +252,41 @@ pub(crate) fn tiny_gemma_model() -> crate::models::gemma::GemmaModel { crate::models::gemma::GemmaModel::from_weights(&w.weights, &args).expect("tiny Gemma builds") } +pub(crate) fn tiny_glm_model() -> crate::models::glm::GlmModel { + // No `partial_rotary_factor`: GLM reads that as 0.5, so half of each head + // rotates. Q/K/V biases and a tied head, as in GLM-Edge-1.5B. + let args = config(json!({ + "model_type": "glm", + "hidden_size": HIDDEN, + "num_hidden_layers": 1, + "intermediate_size": INTERMEDIATE, + "num_attention_heads": 2, + "num_key_value_heads": 1, + "head_dim": HEAD_DIM, + "rms_norm_eps": 1e-5, + "vocab_size": VOCAB, + "rope_theta": 10000.0, + "tie_word_embeddings": true + })); + let mut w = SyntheticWeights::new(); + w.embedding("model.embed_tokens.weight"); + w.norm("model.norm.weight", HIDDEN); + let p = "model.layers.0"; + w.separate_attention(&format!("{p}.self_attn")); + w.bias(format!("{p}.self_attn.q_proj.bias"), Q_OUT); + w.bias(format!("{p}.self_attn.k_proj.bias"), KV_OUT); + w.bias(format!("{p}.self_attn.v_proj.bias"), KV_OUT); + w.linear( + format!("{p}.mlp.gate_up_proj.weight"), + 2 * INTERMEDIATE, + HIDDEN, + ); + w.linear(format!("{p}.mlp.down_proj.weight"), HIDDEN, INTERMEDIATE); + w.norm(format!("{p}.input_layernorm.weight"), HIDDEN); + w.norm(format!("{p}.post_attention_layernorm.weight"), HIDDEN); + crate::models::glm::GlmModel::from_weights(&w.weights, &args).expect("tiny GLM builds") +} + pub(crate) fn tiny_glm4_model() -> crate::models::glm4::Glm4Model { let args = config(json!({ "model_type": "glm4", @@ -543,6 +578,7 @@ dense_contract!(cohere_native_batched_decode_contract, tiny_cohere_model); dense_contract!(ernie45_native_batched_decode_contract, tiny_ernie45_model); dense_contract!(exaone_native_batched_decode_contract, tiny_exaone_model); dense_contract!(gemma_native_batched_decode_contract, tiny_gemma_model); +dense_contract!(glm_native_batched_decode_contract, tiny_glm_model); dense_contract!(glm4_native_batched_decode_contract, tiny_glm4_model); dense_contract!(granite_native_batched_decode_contract, tiny_granite_model); dense_contract!( diff --git a/src/models/registry.rs b/src/models/registry.rs index c2fa139a92..25178ce87b 100644 --- a/src/models/registry.rs +++ b/src/models/registry.rs @@ -815,6 +815,7 @@ impl ModelType { ModelType::InternLM2 => "internlm2", ModelType::InternLM3 => "internlm3", ModelType::Baichuan => "baichuan", + ModelType::Glm => "glm", ModelType::Glm4 => "glm4", ModelType::Glm4Moe => "glm4_moe", ModelType::Glm4MoeLite => "glm4_moe_lite", @@ -1258,6 +1259,7 @@ pub(crate) fn model_type_keys(model_type: ModelType) -> &'static [&'static str] ModelType::InternLM3 => &["internlm3"], ModelType::Baichuan => &["baichuan_m1"], ModelType::BitNet => &["bitnet"], + ModelType::Glm => &["glm"], ModelType::Glm4 => &["glm4"], ModelType::Glm4Moe => &["glm4_moe"], ModelType::Glm4MoeLite => &["glm4_moe_lite"], diff --git a/tests/glm_parity.rs b/tests/glm_parity.rs new file mode 100644 index 0000000000..ed3405bb70 --- /dev/null +++ b/tests/glm_parity.rs @@ -0,0 +1,304 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! GLM (`glm`, `GlmForCausalLM`) against transformers on the original bf16 +//! releases: +//! +//! ```text +//! zai-org/glm-edge-1.5b-chat revision 7b201d3c partial_rotary_factor 1.0, tied head +//! zai-org/glm-4-9b-chat-hf revision 8599336f no partial_rotary_factor (0.5), +//! Q/K/V biases, untied head +//! ``` +//! +//! The reference ids are transformers 5.20.2 greedy decode (torch 2.11.0, CPU, +//! float32) from the same prompt ids: one prefill of the whole prompt, then an +//! argmax loop of single-token steps with no EOS stop. Feeding raw ids keeps +//! tokenizer differences out of the comparison. +//! +//! mlx-lm's `glm` module is not the reference: it rotates the whole head of +//! the 9B, whose config leaves `partial_rotary_factor` out and so means 0.5 in +//! transformers. On the long prompt below mlx-lm 0.32.2 already picks another +//! first token, where transformers' top logit leads the next by 16.5. +//! +//! The gates teacher-force the reference continuation instead of comparing a +//! free-running decode: a near-tie (top two logits within bf16 rounding) flips +//! one step and every later one with it, which says nothing about the model. +//! Feeding the reference token keeps both runs on the same context, so all 64 +//! steps are compared, and a wrong rotary width, a missing bias or an extra +//! norm still shows up as the reference token falling well below mlxcel's +//! maximum logit. +//! +//! Every gate skips when its checkpoint is absent and fails under +//! `MLXCEL_REQUIRE_MODELS=1`. `MLXCEL_TEST_GLM_EDGE_1_5B_DIR` and +//! `MLXCEL_TEST_GLM4_9B_DIR` name the directories explicitly; an override that +//! does not exist always fails. + +mod common; + +use mlxcel::models::GlmModel; +use mlxcel_core::generate::LanguageModel; +use std::path::PathBuf; + +/// Largest allowed gap between mlxcel's maximum logit and the logit it gives +/// the transformers token at one step. Measured on GB10 (CUDA): 0 at all 256 +/// steps of the four cases below. The same 9B weights with +/// `partial_rotary_factor` forced to 1.0 (mlx-lm's reading) reach 6.56 on the +/// short prompt and 13.75 on the long one, where the reference token is the +/// argmax at only 2 of 64 steps. +const MAX_REFERENCE_DEFICIT: f32 = 1.0; + +/// 23 ids: the glm-edge chat template around one user turn, "Explain in three +/// sentences why the sky is blue during the day and red at sunset.". +const EDGE_SHORT_PROMPT: &[i32] = &[ + 59253, 10, 1891, 28195, 309, 3580, 38439, 5158, 283, 22344, 398, 12763, 3468, 283, 3105, 332, + 5706, 636, 10013, 1974, 46, 59254, 10, +]; + +/// transformers greedy continuation of [`EDGE_SHORT_PROMPT`] on glm-edge-1.5b-chat, 64 ids. +const EDGE_SHORT_REF_OUT: &[i32] = &[ + 21896, 283, 3105, 44, 283, 22344, 14223, 12763, 2510, 283, 33867, 302, 325, 51664, 714, 283, + 15796, 1106, 26369, 398, 1945, 12037, 636, 12763, 56580, 115, 44, 1160, 599, 33867, 304, 1066, + 325, 3019, 51664, 332, 1636, 1346, 11431, 46, 4860, 10013, 1974, 44, 283, 22344, 21107, 5706, + 5145, 320, 283, 33867, 302, 325, 35097, 12763, 56580, 115, 714, 283, 6263, 21524, 325, 26577, +]; + +/// 557 ids: the glm-edge chat template around one user turn asking for a five-bullet +/// summary of the first 2,200 bytes of `docs/architecture.md`. +const EDGE_LONG_PROMPT: &[i32] = &[ + 59253, 10, 83, 3704, 285, 1061, 283, 4059, 4576, 309, 6659, 39582, 6572, 1787, 35, 48559, + 29193, 378, 96, 1786, 120, 6712, 96, 398, 261, 518, 679, 309, 3572, 24301, 476, 11956, 40336, + 88, 2050, 261, 387, 3366, 23859, 46, 678, 10, 4107, 9426, 6572, 599, 26060, 1768, 21970, 58, + 46295, 51118, 14197, 636, 283, 13239, 44, 332, 10, 11002, 19702, 44, 3963, 22684, 44, 50258, + 44, 332, 40336, 88, 10657, 6228, 309, 10, 21980, 304, 22713, 1787, 664, 11583, 16038, 16882, + 378, 2721, 1355, 10, 8981, 1779, 7478, 47092, 2783, 45697, 6711, 1159, 1841, 1786, 120, 6712, + 96, 46295, 19687, 332, 1778, 12166, 49773, 10, 7478, 47092, 10524, 43941, 120, 27513, 45697, + 578, 1159, 3490, 44446, 1841, 1786, 120, 6712, 24321, 96, 15398, 10, 7478, 47092, 21193, 47, + 1389, 1159, 46295, 1778, 12166, 2422, 18100, 10, 7478, 47092, 21853, 47, 10287, 1159, 24301, + 47, 9927, 332, 34148, 2069, 419, 10, 7478, 47092, 3745, 49404, 45697, 578, 1159, 3745, 57309, + 332, 19702, 2997, 22180, 50685, 1103, 10, 7478, 47092, 36199, 47, 11126, 1159, 55701, 43894, + 35342, 58, 1160, 6938, 5544, 5494, 7928, 2262, 7478, 47092, 19702, 47, 11126, 1159, 3745, + 19702, 9934, 419, 332, 4590, 9636, 3855, 10, 7478, 47092, 21790, 18170, 45697, 2204, 1159, + 21229, 304, 5742, 19597, 332, 21610, 5742, 20997, 10, 7478, 47092, 21790, 18170, 45687, 10476, + 45697, 1159, 3748, 348, 403, 284, 28922, 49773, 10, 7478, 47092, 8292, 47, 6711, 1159, 2815, + 3745, 5753, 998, 332, 22375, 10, 7478, 47092, 3748, 348, 403, 284, 47, 4201, 1159, 11181, 3748, + 348, 403, 284, 17222, 14569, 11132, 2069, 419, 10, 7478, 47092, 12933, 47, 6711, 1159, 12933, + 3565, 403, 419, 44, 55390, 44, 5515, 1103, 10, 7478, 47092, 14812, 47, 15084, 1159, 14812, + 3565, 9355, 2623, 10, 7478, 47092, 6631, 47, 6711, 1159, 20067, 6631, 44, 3963, 24232, 44, + 23821, 15661, 10, 7478, 47092, 9224, 47, 383, 1159, 38018, 47, 9970, 47, 15175, 4160, 44, 1700, + 6611, 44, 9636, 3855, 10, 7478, 47092, 10112, 7271, 47, 10287, 1159, 10112, 7271, 19702, 2069, + 419, 10, 7478, 47092, 322, 4682, 47, 2146, 1159, 11942, 7102, 35838, 19702, 10, 7478, 47092, + 3853, 43941, 120, 6712, 33226, 47, 5682, 1159, 40336, 88, 387, 3366, 523, 32711, 16639, 332, + 4940, 16038, 13152, 3873, 44739, 10, 7478, 148, 11820, 3853, 43941, 120, 6712, 7728, 47, 5682, + 1159, 19941, 120, 6712, 7728, 58, 40336, 88, 2844, 44, 914, 19526, 486, 29969, 1382, 44, 292, + 5745, 482, 1682, 2043, 10, 5795, 664, 1841, 1786, 120, 6712, 33226, 14069, 96, 8981, 9601, + 43941, 120, 6712, 33226, 47, 96, 48507, 283, 3019, 40336, 88, 23859, 332, 4940, 16038, 24301, + 15299, 6126, 45, 1841, 8981, 9601, 43941, 120, 6712, 33226, 14043, 9601, 45697, 96, 2321, 1841, + 99, 7315, 837, 18753, 96, 30219, 332, 16639, 31492, 334, 45, 1841, 8981, 9601, 43941, 120, + 6712, 33226, 14043, 4320, 2100, 45697, 96, 332, 1841, 8981, 9601, 43941, 120, 6712, 33226, + 14043, 4320, 2100, 47, 96, 2321, 523, 80, 49, 54, 47, 6031, 56, 18066, 350, 2880, 35146, 831, + 86, 13907, 47226, 493, 32, 276, 6154, 13907, 16882, 44, 1839, 854, 47, 352, 2699, 2069, 419, + 44, 332, 13907, 9411, 46, 1841, 20431, 47, 2078, 486, 45697, 5170, 32, 17558, 1841, 57526, + 11906, 837, 2078, 486, 96, 332, 1841, 20431, 837, 2078, 486, 2519, 50752, 11453, 283, 1229, + 8934, 9426, 10, 32, 476, 8206, 115, 283, 41100, 557, 59254, 10, +]; + +/// transformers greedy continuation of [`EDGE_LONG_PROMPT`] on glm-edge-1.5b-chat, 64 ids. +const EDGE_LONG_REF_OUT: &[i32] = &[ + 45, 1841, 1786, 120, 6712, 96, 398, 261, 518, 679, 309, 3572, 24301, 476, 8518, 261, 387, 3366, + 23859, 412, 40336, 88, 10657, 334, 45, 678, 1581, 9426, 6572, 325, 1841, 1786, 120, 6712, 96, + 599, 7882, 320, 424, 21970, 44, 517, 46295, 51118, 32480, 636, 283, 13239, 332, 3745, 19702, + 44, 3963, 22684, 44, 50258, 44, 332, 40336, 88, 10657, 16244, 309, 13950, +]; + +/// 23 ids: the GLM-4 chat template around one user turn, "Explain in three +/// sentences why the sky is blue during the day and red at sunset.". +const GLM4_9B_SHORT_PROMPT: &[i32] = &[ + 151331, 151333, 151336, 198, 840, 20726, 304, 2326, 22809, 3170, 279, 12877, 374, 6303, 2337, + 279, 1899, 323, 2518, 518, 42739, 13, 151337, +]; + +/// transformers greedy continuation of [`GLM4_9B_SHORT_PROMPT`] on glm-4-9b-chat-hf, 64 ids. +const GLM4_9B_SHORT_REF_OUT: &[i32] = &[ + 198, 785, 12877, 7951, 6303, 2337, 279, 1899, 4152, 311, 279, 71268, 315, 38810, 553, 279, + 16550, 13, 2411, 42739, 11, 279, 12877, 10572, 2518, 1576, 279, 23263, 6303, 92080, 525, 36775, + 803, 11, 9376, 279, 5021, 2518, 92080, 311, 40511, 279, 12877, 594, 1894, 13, 151336, 198, 785, + 12877, 374, 6303, 2337, 279, 1899, 1576, 315, 13247, 62524, 71268, 11, 892, 1136, 10170, +]; + +/// 521 ids: the GLM-4 chat template around one user turn asking for a five-bullet +/// summary of the first 2,200 bytes of `docs/architecture.md`. +const GLM4_9B_LONG_PROMPT: &[i32] = &[ + 151331, 151333, 151336, 198, 9187, 5612, 551, 279, 2701, 2197, 304, 4236, 17409, 3501, 382, 2, + 37647, 23188, 271, 63, 66415, 3672, 63, 374, 264, 33627, 44120, 15580, 429, 6738, 19577, 55, + 1526, 264, 356, 1027, 14155, 13, 576, 198, 888, 4343, 3501, 525, 36021, 15418, 25, 39065, + 22257, 8572, 518, 279, 6821, 11, 323, 198, 2528, 8276, 11, 1681, 17948, 11, 37656, 11, 323, + 19577, 55, 7525, 3887, 304, 198, 61721, 13445, 382, 565, 6909, 11586, 6789, 271, 73022, 1318, + 198, 3548, 5894, 11616, 250, 16972, 1887, 25559, 2549, 671, 1565, 66415, 3672, 63, 39065, + 10797, 323, 1186, 5631, 28952, 198, 11616, 250, 16972, 9540, 59134, 87, 12009, 25559, 310, 671, + 43139, 1565, 66415, 3672, 26217, 63, 7868, 198, 11616, 250, 16972, 11288, 14, 503, 671, 39065, + 1186, 5631, 24015, 198, 11616, 250, 16972, 11315, 14, 4293, 671, 15580, 67868, 323, 24816, + 30070, 198, 11616, 250, 16972, 1614, 22165, 25559, 310, 671, 1614, 59292, 323, 8276, 65936, + 47225, 198, 11616, 250, 16972, 19127, 14, 3824, 671, 22544, 29586, 26311, 25, 892, 4712, 51097, + 4637, 741, 11616, 250, 16972, 8276, 14, 3824, 671, 1614, 8276, 58765, 323, 2997, 31116, 4019, + 198, 11616, 250, 16972, 6661, 5047, 25559, 1060, 671, 62198, 1712, 7618, 323, 11429, 1712, + 6845, 198, 11616, 250, 16972, 6661, 5047, 91319, 25559, 671, 78414, 57204, 22245, 28952, 198, + 11616, 250, 16972, 4119, 14, 2549, 671, 1467, 1614, 38131, 323, 17957, 198, 11616, 250, 16972, + 78414, 57204, 14, 1698, 671, 6094, 78414, 57204, 9929, 39086, 30070, 198, 11616, 250, 16972, + 11124, 14, 2549, 671, 11124, 3209, 52154, 11, 36400, 11, 56686, 198, 11616, 250, 16972, 7699, + 14, 5180, 671, 7699, 23602, 1824, 198, 11616, 250, 16972, 3538, 14, 2549, 671, 10125, 3538, 11, + 1681, 14458, 11, 28706, 198, 11616, 250, 16972, 4237, 14, 338, 671, 28964, 14, 4406, 14941, 40, + 2193, 11, 67574, 11, 31116, 4019, 198, 11616, 250, 16972, 45681, 14, 4293, 671, 45681, 8276, + 30070, 198, 11616, 250, 16972, 326, 6215, 14, 664, 671, 6485, 5609, 12949, 8276, 198, 11616, + 250, 16972, 3051, 59134, 87, 3672, 23395, 14, 1797, 671, 19577, 55, 356, 1027, 434, 19389, + 17691, 323, 3347, 11586, 9467, 70654, 198, 11616, 242, 16972, 3051, 59134, 87, 3672, 4450, 14, + 1797, 671, 74813, 3672, 4450, 25, 19577, 55, 1936, 11, 817, 89243, 96061, 11, 74069, 63062, + 198, 13865, 19288, 565, 1565, 66415, 3672, 23395, 19288, 63, 3548, 8193, 59134, 87, 3672, + 23395, 14, 63, 24187, 279, 2118, 19577, 55, 14155, 323, 3347, 11586, 15580, 9662, 1447, 12, + 1565, 3548, 8193, 59134, 87, 3672, 23395, 13428, 8193, 25559, 63, 1959, 1565, 88334, 486, + 13700, 63, 17449, 323, 17691, 12788, 624, 12, 1565, 3548, 8193, 59134, 87, 3672, 23395, 13428, + 61659, 25559, 63, 323, 1565, 3548, 8193, 59134, 87, 3672, 23395, 13428, 61659, 14, 63, 1959, + 33389, 99317, 14, 3221, 23, 16714, 324, 749, 43964, 83952, 6500, 25931, 345, 220, 281, 3279, + 6500, 6789, 11, 46493, 14, 97409, 30070, 11, 323, 6500, 7032, 13, 1565, 9357, 14, 56078, 25559, + 3989, 220, 9977, 1565, 82023, 8232, 486, 56078, 63, 323, 1565, 9357, 486, 56078, 14524, 291, + 7808, 279, 825, 6529, 4343, 198, 220, 429, 21841, 279, 27855, 476, 151337, +]; + +/// transformers greedy continuation of [`GLM4_9B_LONG_PROMPT`] on glm-4-9b-chat-hf, 64 ids. +const GLM4_9B_LONG_REF_OUT: &[i32] = &[ + 198, 12, 1565, 66415, 3672, 63, 374, 264, 33627, 44120, 15580, 429, 24031, 448, 19577, 55, + 1526, 264, 356, 1027, 14155, 624, 12, 576, 584, 4343, 3501, 315, 1565, 66415, 3672, 63, 525, + 17355, 11, 448, 39065, 22257, 30741, 518, 279, 6821, 323, 1614, 13895, 7525, 5382, 304, 12229, + 13445, 624, 12, 576, 1909, 11586, 6789, 315, 1565, 66415, 3672, 63, 5646, 264, 8044, +]; + +fn resolve_model_dir(env: &str, checkpoint: &str) -> Option { + if let Some(dir) = std::env::var_os(env).filter(|v| !v.is_empty()) { + let dir = PathBuf::from(dir); + assert!( + dir.exists(), + "{env}={} does not exist; unset it to use the default checkpoint lookup", + dir.display() + ); + return Some(dir); + } + // Panics under MLXCEL_REQUIRE_MODELS when the checkpoint resolves nowhere. + let dir = common::repo_model_dir(checkpoint); + if dir.exists() { + Some(dir) + } else { + eprintln!("skipping GLM parity: {checkpoint} is not present"); + None + } +} + +fn load(env: &str, checkpoint: &str, rope_dims: usize) -> Option { + let dir = resolve_model_dir(env, checkpoint)?; + let (model, args) = GlmModel::load(&dir).unwrap_or_else(|e| panic!("load {checkpoint}: {e}")); + // A different export under this name would pass for the wrong reason. + assert_eq!( + (args.rope_dims(), args.head_dim), + (rope_dims, 128), + "{checkpoint} has an unexpected rotary width" + ); + Some(model) +} + +/// The `[vocab]` logit row of the last position, as host floats. +fn last_row(logits: &mlxcel_core::MlxArray) -> Vec { + let shape = mlxcel_core::array_shape(logits); + let last = mlxcel_core::slice(logits, &[0, shape[1] - 1, 0], &[1, shape[1], shape[2]]); + let last = mlxcel_core::astype(&last, mlxcel_core::dtype::FLOAT32); + mlxcel_core::eval(&last); + mlxcel_core::array_to_raw_bytes(&last) + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect() +} + +/// Prefill `input_ids` in one forward, then step through `ref_out` one token +/// at a time, feeding the reference token (teacher forcing). Each step's +/// deficit is how far the reference token's logit sits below mlxcel's maximum: +/// zero where mlxcel's argmax is the reference token or ties with it. +fn teacher_forced_deficits(model: &GlmModel, input_ids: &[i32], ref_out: &[i32]) -> Vec { + let mut caches = LanguageModel::make_caches(model); + let prompt = mlxcel_core::from_slice_i32(input_ids, &[1, input_ids.len() as i32]); + let mut logits = LanguageModel::forward(model, &prompt, &mut caches, None); + let mut deficits = Vec::with_capacity(ref_out.len()); + for &tok in ref_out { + let row = last_row(&logits); + let max = row.iter().copied().fold(f32::NEG_INFINITY, f32::max); + deficits.push(max - row[tok as usize]); + let next = mlxcel_core::from_slice_i32(&[tok], &[1, 1]); + logits = LanguageModel::forward(model, &next, &mut caches, None); + } + deficits +} + +fn assert_tracks_reference(name: &str, model: &GlmModel, input_ids: &[i32], ref_out: &[i32]) { + let deficits = teacher_forced_deficits(model, input_ids, ref_out); + let exact = deficits.iter().filter(|&&d| d == 0.0).count(); + let worst = deficits + .iter() + .copied() + .enumerate() + .max_by(|a, b| a.1.total_cmp(&b.1)) + .expect("non-empty reference"); + eprintln!( + "{name}, {}-id prompt: reference token is the argmax at {exact}/{} steps; largest \ + deficit {:.4} at step {}", + input_ids.len(), + ref_out.len(), + worst.1, + worst.0 + ); + assert!( + worst.1 <= MAX_REFERENCE_DEFICIT, + "{name} step {} ranks the transformers token {:.4} below its maximum logit (allowed \ + {MAX_REFERENCE_DEFICIT}); every step: {deficits:?}", + worst.0, + worst.1 + ); + assert!( + exact * 10 >= ref_out.len() * 9, + "{name} agrees with transformers' argmax at only {exact}/{} steps", + ref_out.len() + ); +} + +const EDGE: &str = "glm-edge-1.5b-chat"; +const EDGE_ENV: &str = "MLXCEL_TEST_GLM_EDGE_1_5B_DIR"; +const GLM4_9B: &str = "glm-4-9b-chat-hf"; +const GLM4_9B_ENV: &str = "MLXCEL_TEST_GLM4_9B_DIR"; + +#[test] +fn glm_edge_1_5b_tracks_transformers_greedy() { + // partial_rotary_factor 1.0: the whole 128-wide head rotates. + let Some(model) = load(EDGE_ENV, EDGE, 128) else { + return; + }; + assert_tracks_reference(EDGE, &model, EDGE_SHORT_PROMPT, EDGE_SHORT_REF_OUT); + assert!(EDGE_LONG_PROMPT.len() > 300); + assert_tracks_reference(EDGE, &model, EDGE_LONG_PROMPT, EDGE_LONG_REF_OUT); +} + +#[test] +fn glm4_9b_tracks_transformers_greedy() { + // No partial_rotary_factor in the config: 64 of the 128 dims rotate. + let Some(model) = load(GLM4_9B_ENV, GLM4_9B, 64) else { + return; + }; + assert_tracks_reference(GLM4_9B, &model, GLM4_9B_SHORT_PROMPT, GLM4_9B_SHORT_REF_OUT); + assert!(GLM4_9B_LONG_PROMPT.len() > 300); + assert_tracks_reference(GLM4_9B, &model, GLM4_9B_LONG_PROMPT, GLM4_9B_LONG_REF_OUT); +}