Repository navigation
feat(models): port GLM (glm, GlmForCausalLM) - #3749
Open
Jaeyeong-CHOI wants to merge 1 commit into
Open
Jaeyeong-CHOI wants to merge 1 commit into
Jaeyeong-CHOI wants to merge 1 commit into
Conversation
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #3750.
GlmForCausalLMcheckpoints ("model_type": "glm": GLM-4-9B-hf, GLM-Edge 1.5B/4B, and MLX exports of them) failed withUnsupported model type: glm. They now load inmlxcel generate,mlxcel-serverandmlxcel 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.rsreusesglm4::Attention(Q/K/V with optional bias, interleaved RoPE on the firstrope_dimsdimensions) andglm4::MLP(fusedgate_up_projSwiGLU), and adds a two-norm pre-norm block and a tied-or-untied head.The config defaults are transformers'
GlmConfigones. This matters for the 9B: its configs leave outpartial_rotary_factor, which transformers reads as 0.5. The original ChatGLM code rotates half of each head as well:modeling_chatglm.pyinTHUDM/glm-4-9b-chatbuildsRotaryEmbedding(kv_channels // 2)and rotates the first 64 of the 128 dims. mlx-lm'sglmmodule always rotates the whole head, and onglm-4-9b-chat-hfit 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):ModelArgswith theGlmConfigdefaults (partial_rotary_factor0.5,attention_biastrue,rms_norm_eps1.5625e-07,tie_word_embeddingsfalse,head_dim128,eos_token_id[151329, 151336, 151338]; transformers 5rope_parameterslifted by the shared macro).validate()refuses what would otherwise run wrong or fail late:partial_rotary_factoroutside (0, 1], a rotary width that is zero or odd, zero heads, heads not a multiple of KV heads, arope_scalingother than the default, and invalid EOS ids (viachecked_eos_token_ids). An emptyeos_token_idlist also falls back to the default; that is mlxcel's choice, since transformers keeps an explicit[].GlmModelwithforward,last_row_logits, nativeforward_batched, and EOS ids from the config.ModelType::Glm, detection of"glm", registry keys, model metadata,LoadedModel::Glm, memory-estimate id, TP fallback arm (not TP-enabled),mlxcel archentry "GLM (GLM-4-9B, GLM-Edge)".src/models/glm4.rs: module doc notes thatAttentionandMLPare shared withglm.rs(no code change).zai-org/glm-edge-v-2b,glm-edge-v-5b) also declares"model_type": "glm"/GlmForCausalLM, adds a SigLIPvision_config, and ships the tower asmodel.vision.*(458 tensors in the 5B). Its text decoder is the same GLM block, so it loads asModelType::Glm, text only. This is explicit rather than incidental:ModelArgsreadsvision_config(has_vision_tower(), withnulland{}meaning no tower, as indetection::has_vision_config), andfrom_weightscounts themodel.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_idsUsed by:gains the new caller.src/models/glm_tests.rs(config defaults for the real 9B and Edge configs, transformers 5rope_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 whoselm_headdiffers 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 realglm-edge-v-2bconfig parses as the text decoder and validates, and a synthetic checkpoint directory with tensors under the real tower names is detected asglm, loads throughGlmModel::loadwith 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. NoCHANGELOG.mdentry; it is written at release time.Verification
NVIDIA GB10 (sm_121), CUDA 13, base
main9402cf8. Commit tree18d2868dbbd7abe23b2c257864388e6de454051a. 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-Vvision_confignotice (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 0exits 1 withError: Unsupported model type: glmforglm-edge-1.5b-chat,glm-4-9b-chat-hfandglm-4-9b-chat-1m-4bit.mlxcel archlists 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.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.
mlx_lm.convert -q(group 64)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_factorforced 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.rsbounds 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.
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 0exits 0 with coherent English onglm-edge-1.5b-chat,glm-edge-4b-chat,glm-4-9b-chat-hf, its 4-bit export andglm-4-9b-chat-1m-4bit, and none of them prints the GLM-Edge-V notice. The 9B runs stop on EOS.mlxcel archnow lists 239 architectures, including "GLM (GLM-4-9B, GLM-Edge)".Server. For
glm-edge-1.5b-chatandglm-4-9b-chat-hf,mlxcel-server --model <dir>got four temperature-0 chat requests (max_tokens48), 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 forcausing(14371) and 16.5 forwhich(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: everycheck_*.pyand*_test.sh,python3 scripts/ci/check_used_by.py,bash scripts/ci/check_used_by_test.shandscripts/insert_apache_header.py --checkpass, exceptcheck_helm_chart.pyandhelm_chart_package_test.sh, which need ahelmbinary that is not installed on this machine.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 newmodels::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_glm4and 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 unmodifiedmain9402cf8 with the same message:tests/mlx_test_guard_coverage.rsmlx_evaluating_lib_tests_take_mlx_test_guard: flagssrc/vision/encoders/nemotron_h_nano_omni_tests.rs:276 pos_embed_resample_runs_in_f32.tests/step3p7_parity.rstext_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 (currentmain); the merged tree equals the commit tree.Maintainer checklist
partial_rotary_factor0, 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_scalingnull / 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.validate()is O(1).glm4::Attentionandglm4::MLPare used unchanged (no signature or behaviour change), and GLM 4's own tests pass in the targeted run.checked_eos_token_idsgains one caller, recorded in itsUsed by:.mainhas no## [Unreleased]section and no CHANGELOG edits since v0.9.0, so the entry is left to release prep.GLM: …validation, which lists none.cargo fmt --all -- --checkpasses on the commit.Checkpoints
zai-org/glm-edge-1.5b-chatrevision7b201d3c160c25beda4cf0d107617ad975cd1ca8(bf16, tied,partial_rotary_factor1.0)zai-org/glm-edge-4b-chatrevisiona1817f2ab339ecdd8497c4d752ea71a65299f29a(bf16, untied, 1.0)zai-org/glm-4-9b-chat-hfrevision8599336fc6c125203efb2360bfaf4c80eef1d1bf(bf16, Q/K/V bias, nopartial_rotary_factor)mlx-community/glm-4-9b-chat-1m-4bitrevision3e129325148017f137a1cf4e148f8b3d37df234f(4-bit affine, group 64)Limits
glmwith avision_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.KVCachepath as GLM 4, but quantized or Turbo KV modes were not run on it, so they are not advertised.rope_scalingother than the default is refused rather than implemented. None of the checkpoints above declares one.mlx_lm.convertexport ofglm-4-9b-chat-hf.mlx-community/glm-4-9b-chat-1m-4bitis a different model (the 1M-context chat). It only gets a CLI smoke run here, because I had no transformers reference for it.MLXCEL_TEST_GLM_EDGE_1_5B_DIR/MLXCEL_TEST_GLM4_9B_DIR, or put the checkpoints undermodels/.