Skip to content

feat(models): port GLM (glm, GlmForCausalLM) - #3749

Open
Jaeyeong-CHOI wants to merge 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:feat/glm-text-port
Open

Jaeyeong-CHOI wants to merge 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:feat/glm-text-port

Conversation

@Jaeyeong-CHOI

@Jaeyeong-CHOI Jaeyeong-CHOI commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #3750.

GlmForCausalLM checkpoints ("model_type": "glm": GLM-4-9B -hf, GLM-Edge 1.5B/4B, and MLX exports of them) failed with Unsupported model type: glm. They now load in mlxcel generate, mlxcel-server and mlxcel arch, with native batched decode.

The GLM block is the GLM 4 block without its two extra post-norms, so the new src/models/glm.rs reuses glm4::Attention (Q/K/V with optional bias, interleaved RoPE on the first rope_dims dimensions) and glm4::MLP (fused gate_up_proj SwiGLU), and adds a two-norm pre-norm block and a tied-or-untied head.

The config defaults are transformers' GlmConfig ones. This matters for the 9B: its configs leave out partial_rotary_factor, which transformers reads as 0.5. The original ChatGLM code rotates half of each head as well: modeling_chatglm.py in THUDM/glm-4-9b-chat builds RotaryEmbedding(kv_channels // 2) and rotates the first 64 of the 128 dims. mlx-lm's glm module always rotates the whole head, and on glm-4-9b-chat-hf it already picks a different first token on a 521-id prompt, at a step where transformers' top logit leads by 16.5. So the reference here is transformers, not mlx-lm. On GLM-Edge, which declares 1.0, the two agree (64/64 greedy tokens on both prompts).

Changes

  • src/models/glm.rs (new): ModelArgs with the GlmConfig defaults (partial_rotary_factor 0.5, attention_bias true, rms_norm_eps 1.5625e-07, tie_word_embeddings false, head_dim 128, eos_token_id [151329, 151336, 151338]; transformers 5 rope_parameters lifted by the shared macro). validate() refuses what would otherwise run wrong or fail late: partial_rotary_factor outside (0, 1], a rotary width that is zero or odd, zero heads, heads not a multiple of KV heads, a rope_scaling other than the default, and invalid EOS ids (via checked_eos_token_ids). An empty eos_token_id list also falls back to the default; that is mlxcel's choice, since transformers keeps an explicit []. GlmModel with forward, last_row_logits, native forward_batched, and EOS ids from the config.
  • Registration: ModelType::Glm, detection of "glm", registry keys, model metadata, LoadedModel::Glm, memory-estimate id, TP fallback arm (not TP-enabled), mlxcel arch entry "GLM (GLM-4-9B, GLM-Edge)".
  • src/models/glm4.rs: module doc notes that Attention and MLP are shared with glm.rs (no code change).
  • GLM-Edge-V (zai-org/glm-edge-v-2b, glm-edge-v-5b) also declares "model_type": "glm" / GlmForCausalLM, adds a SigLIP vision_config, and ships the tower as model.vision.* (458 tensors in the 5B). Its text decoder is the same GLM block, so it loads as ModelType::Glm, text only. This is explicit rather than incidental: ModelArgs reads vision_config (has_vision_tower(), with null and {} meaning no tower, as in detection::has_vision_config), and from_weights counts the model.vision.* tensors it leaves unread and prints a one-time notice that the vision tower is not supported and is ignored. The decoder looks every weight up by name, and the loaded arrays are lazy, so the tower's data is never read and is dropped with the weight map.
  • src/loading/mod.rs: checked_eos_token_ids Used by: gains the new caller.
  • Tests: src/models/glm_tests.rs (config defaults for the real 9B and Edge configs, transformers 5 rope_parameters, every refusal and accepted edge; a two-layer forward against an f64 reference written from transformers' modeling_glm.py, with the default half rotation and with full rotation plus an untied head whose lm_head differs from the embedding (the test also checks that projecting through the embedding would miss the reference), single-token and incremental-decode cases; missing-weight errors; GLM-Edge-V: the real glm-edge-v-2b config parses as the text decoder and validates, and a synthetic checkpoint directory with tensors under the real tower names is detected as glm, loads through GlmModel::load with those tensors present in the weight map, and matches the f64 reference); tiny-model batched-decode and last-row contracts; detection test; tests/glm_parity.rs (real checkpoints, teacher-forced against transformers).
  • docs/supported-models.md. No CHANGELOG.md entry; it is written at release time.

Verification

NVIDIA GB10 (sm_121), CUDA 13, base main 9402cf8. Commit tree 18d2868dbbd7abe23b2c257864388e6de454051a. The formatting, lint, CI-script, unit, real-checkpoint, CLI and full-gate results below are from that tree. The reference comparisons, the trace and 4-bit tables, the negative control and the server run were measured on an earlier tree whose model code differed only in lacking the GLM-Edge-V vision_config notice (no change to the forward pass), and the CLI output on all five checkpoints is byte-identical between the two builds.

Before (main 9402cf8). mlxcel generate -m <dir> -p "Hello" -n 8 --temp 0 exits 1 with Error: Unsupported model type: glm for glm-edge-1.5b-chat, glm-4-9b-chat-hf and glm-4-9b-chat-1m-4bit. mlxcel arch lists 238 architectures, with no GLM entry besides GLM 4 / GLM 4 MoE / GLM 4 MoE Lite / GLM MoE DSA.

References. transformers 5.20.2 (torch 2.11.0, CPU, float32) and mlx-lm 0.32.2 (mlx 0.32.4, CUDA). Each checkpoint gets two prompts built with its own chat template: a 23-id question and a five-bullet summary request over the first 2,200 bytes of docs/architecture.md (557 ids with the Edge tokenizer, 521 with the 9B one). Greedy decode is one prefill followed by 64 single-token argmax steps, with no EOS stop.

checkpoint mlx-lm vs transformers, first greedy divergence (short / long)
glm-edge-1.5b-chat none / none (64/64 both)
glm-edge-4b-chat none / none
glm-4-9b-chat-hf step 10 / step 0 (transformers' top-1 leads by 16.5 there)

mlxcel vs transformers. Teacher-forced: the transformers token is fed back at every step, and at each step the deficit is mlxcel's max logit minus its logit for the transformers token.

checkpoint prompt argmax = transformers worst deficit max |mlxcel - transformers| over transformers' top-5 logits free greedy, first divergence
glm-edge-1.5b-chat (bf16) short / long 64/64 / 64/64 0 / 0 0.15 / 0.32 none / none
glm-edge-4b-chat (bf16) short / long 64/64 / 64/64 0 / 0 0.26 / 0.26 none / none
glm-4-9b-chat-hf (bf16) short / long 64/64 / 64/64 0 / 0 0.20 / 0.63 step 17 / none
glm-4-9b-chat-hf, 4-bit mlx_lm.convert -q (group 64) short / long 58/64 / 62/64 0.75 / 0.81 2.72 / 5.88 step 8 / step 21

At the 9B short step 17, transformers' own top two logits are 0.0032 apart (17.3782 vs 17.3750) and mlxcel's bf16 logits tie, so the free-running decode takes the other token. Each non-zero 4-bit deficit falls on a step where transformers' top-two gap is at most 0.50, which is quantization noise. This row is not pinned by a test.

Negative control. The same 9B weights with partial_rotary_factor forced to 1.0 in a copied config (mlx-lm's reading) agree with transformers at only 50/64 and 2/64 steps. The worst deficits are 6.56 and 13.75, and free greedy diverges at step 10 and step 0, exactly where mlx-lm does. tests/glm_parity.rs bounds the deficit at 1.0 and requires agreement at 90% of steps, so it fails on that reading.

Real-checkpoint tests on the commit tree.

MLXCEL_REQUIRE_MODELS=1 MLXCEL_TEST_GLM_EDGE_1_5B_DIR=<glm-edge-1.5b-chat> MLXCEL_TEST_GLM4_9B_DIR=<glm-4-9b-chat-hf> \
  cargo test --locked --profile test-fast --features cuda --test glm_parity -- --test-threads=1 --nocapture

2 passed. All four cases: the reference token is the argmax at 64/64 steps, largest deficit 0.

CLI. mlxcel generate -m <dir> -p "Explain in three sentences why the sky is blue during the day and red at sunset." -n 80 --temp 0 exits 0 with coherent English on glm-edge-1.5b-chat, glm-edge-4b-chat, glm-4-9b-chat-hf, its 4-bit export and glm-4-9b-chat-1m-4bit, and none of them prints the GLM-Edge-V notice. The 9B runs stop on EOS. mlxcel arch now lists 239 architectures, including "GLM (GLM-4-9B, GLM-Edge)".

Server. For glm-edge-1.5b-chat and glm-4-9b-chat-hf, mlxcel-server --model <dir> got four temperature-0 chat requests (max_tokens 48), first one at a time and then all four concurrently, which goes through native batched decode. On the 1.5B all four concurrent responses equal the one-at-a-time ones. On the 9B three of four are equal. The fourth matches for the first 238 characters, then continues "which sc…" instead of "causing more" a few tokens before the length limit. That is the same sky prompt whose single-request greedy already flips at a 0.0032 tie against transformers at step 17. Teacher-forcing mlxcel's own single-request greedy tokens for that prompt puts the split at decode step 46, where the bf16 logits are 16.625 for causing (14371) and 16.5 for which (892): the top two, one bf16 step (0.125) apart. A batched decode step, which accumulates in a different order from a single-row one, can take either.

Gate.

  • cargo fmt --all -- --check: clean.
  • cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings: clean.
  • scripts/ci: every check_*.py and *_test.sh, python3 scripts/ci/check_used_by.py, bash scripts/ci/check_used_by_test.sh and scripts/insert_apache_header.py --check pass, except check_helm_chart.py and helm_chart_package_test.sh, which need a helm binary that is not installed on this machine.
  • Targeted lib tests (cargo test --profile test-fast --features cuda --lib -- --test-threads=1 glm detection_tests batched_decode_coverage last_row_logits popular_dense): 441 passed, 0 failed. This covers the new models::glm::tests (11, including the two GLM-Edge-V tests and the untied-head test), glm_native_batched_decode_contract, glm_last_row_logits, glm_model_type_is_detected_apart_from_glm4 and the pinned batched-decode classification.
  • make verify-test-cuda (cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1): 18,907 passed, 2 failed, 578 ignored. Both failures reproduce on unmodified main 9402cf8 with the same message:
    • tests/mlx_test_guard_coverage.rs mlx_evaluating_lib_tests_take_mlx_test_guard: flags src/vision/encoders/nemotron_h_nano_omni_tests.rs:276 pos_embed_resample_runs_in_f32.
    • tests/step3p7_parity.rs text_decode_delegates_sequence_local_native_batching: assertion failed: !wrapper.supports_padded_prefill() at line 519.
  • git merge-tree --write-tree origin/main HEAD: no conflicts against 9402cf8 (current main); the merged tree equals the commit tree.

Maintainer checklist

  1. Boundaries: partial_rotary_factor 0, negative, above 1, 0.75 and 0.1 of a 4-wide head (odd and zero rotary widths) are refused, and 0.5 and 1.0 are accepted. Also covered: zero attention or KV heads, a head count that is not a multiple of the KV heads, KV heads equal to heads, rope_scaling null / default / linear / yarn, EOS as an int, a list, an empty list, -1 and 2^32. The forward runs on 1 token (position 0, no rotation) and 6 tokens, prefill plus a decode step. Batched decode is checked on ragged, single-row and empty batches.
  2. Complexity: the same per-layer work as GLM 4 minus two norms, and no new host-side loops over sequence length. validate() is O(1).
  3. Other callers: glm4::Attention and glm4::MLP are used unchanged (no signature or behaviour change), and GLM 4's own tests pass in the targeted run. checked_eos_token_ids gains one caller, recorded in its Used by:.
  4. CHANGELOG: not edited. main has no ## [Unreleased] section and no CHANGELOG edits since v0.9.0, so the entry is left to release prep.
  5. No explanatory comment was removed. The only error message that names families is the new GLM: … validation, which lists none.
  6. cargo fmt --all -- --check passes on the commit.

Checkpoints

  • zai-org/glm-edge-1.5b-chat revision 7b201d3c160c25beda4cf0d107617ad975cd1ca8 (bf16, tied, partial_rotary_factor 1.0)
  • zai-org/glm-edge-4b-chat revision a1817f2ab339ecdd8497c4d752ea71a65299f29a (bf16, untied, 1.0)
  • zai-org/glm-4-9b-chat-hf revision 8599336fc6c125203efb2360bfaf4c80eef1d1bf (bf16, Q/K/V bias, no partial_rotary_factor)
  • mlx-community/glm-4-9b-chat-1m-4bit revision 3e129325148017f137a1cf4e148f8b3d37df234f (4-bit affine, group 64)

Limits

  • GLM-Edge-V (glm with a vision_config) loads as the text decoder only; its vision tower is ignored and images are not supported. Its text output was not run against a reference here (no GLM-Edge-V checkpoint was downloaded); the decoder is the same GLM block as GLM-Edge's.
  • Not run on Metal or ROCm; CUDA (GB10) only.
  • No tensor parallelism (the TP dispatch arm only keeps the table total). Not added to the pipeline-parallel list.
  • The registry advertises fp16 KV only. GLM uses the same KVCache path as GLM 4, but quantized or Turbo KV modes were not run on it, so they are not advertised.
  • rope_scaling other than the default is refused rather than implemented. None of the checkpoints above declares one.
  • The 4-bit row comes from a local mlx_lm.convert export of glm-4-9b-chat-hf. mlx-community/glm-4-9b-chat-1m-4bit is a different model (the 1M-context chat). It only gets a CLI smoke run here, because I had no transformers reference for it.
  • The real-checkpoint tests skip when the checkpoints are absent (as in CI). Run them with MLXCEL_TEST_GLM_EDGE_1_5B_DIR / MLXCEL_TEST_GLM4_9B_DIR, or put the checkpoints under models/.

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.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(models): support GLM (glm, GlmForCausalLM): GLM-4-9B -hf and GLM-Edge

1 participant