Skip to content

feat(glm4): consolidate fused-SwiGLU MLP into MLXLMCommon (WS-C #6) - #178

Merged
ekryski merged 1 commit into
alphafrom
ek/wsc6-glm4-consolidation
May 8, 2026
Merged

ekryski merged 1 commit into
alphafrom
ek/wsc6-glm4-consolidation

Conversation

@ekryski

@ekryski ekryski commented May 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

WS-C #6: lifts the bit-identical gate_up_proj SwiGLU MLP shared by the LLM GLM4 text decoder and the VLM GlmOcr language stack into a new MLXLMCommon.GLM4 public namespace, following the WS-C #5 (Qwen 3) pattern.

  • What's shared: MLXLMCommon.GLM4.LayerArgs adapter + MLXLMCommon.GLM4.MLP (fused gate_up_proj SwiGLU — single matmul producing 2 * intermediate, split + silu(gate) * up + down).
  • What's NOT shared: Attention / DecoderLayer / ModelInner — the LLM uses standard applyRotaryPosition with partialRotaryFactor and an internally-managed RoPE, while the VLM GlmOcr Attention takes a precomputed (cos, sin) tuple from GlmOcrRotaryEmbedding (M-RoPE, same family as Qwen3VL). Forcing a unified Attention would either degrade the LLM hot path or impose an indirection. File-level note in Libraries/MLXLMCommon/Models/GLM4.swift documents this with future-work alignment to the cross-family M-RoPE helper deferred from PR feat(qwen3): consolidate MLP + add VLM prefill-sync barrier (WS-C #5) #177.

Consumer changes

Bench registry

Added glm4-9b, glm4-32b, glm-ocr family entries to Tests/Benchmarks/Utils/ModelRegistry.swift — ./scripts/benchmark.sh --model glm4-9b --quant 4bit ... works directly.

Verification (M1 Max 64GB)

  • swift build clean across LLM + VLM + Benchmarks targets.
  • LLM smoke mlx-community/GLM-4-9B-0414-4bit, kv=none, simple: 79.8 tok/s prefill, 50.7 tok/s decode, 390ms TTFT, 5.21GB peak. Coherent output: "Hello! I'm an AI assistant. I can help you with a wide range of topics, including answering questions, providing information, helping with calculations, and mo…"
  • VLM smoke mlx-community/GLM-OCR-4bit, kv=none, vision: 570.1 tok/s prefill, 247.0 tok/s decode, 1224ms TTFT, 2.46GB peak. Coherent on the bench dog image: "The image shows a golden retriever standing on a concrete surface. The dog appears to be happy and alert, with its tail curled upwards. It is wearing…" — --vision-expect dog matched.

Test plan

  • swift build clean
  • ./scripts/benchmark.sh --model glm4-9b --quant 4bit --kv none --method simple produces coherent text output
  • ./scripts/benchmark.sh --model glm-ocr --quant 4bit --kv none --method vision produces coherent vision description and matches the expected keyword

Closes one of the 8 WS-C consolidation entries listed under issue #168.

@github-actions github-actions Bot added the feature New feature (auto-applied from feat: prefix) label May 7, 2026
@ekryski ekryski added enhancement New feature or request and removed feature New feature (auto-applied from feat: prefix) labels May 8, 2026
…WS-C #6)

Lift the bit-identical `gate_up_proj` SwiGLU MLP shared by the LLM `GLM4`
text decoder and the VLM `GlmOcr` language stack into a new
`MLXLMCommon.GLM4` public namespace, mirroring the WS-C #5 (Qwen 3) pattern.

What's shared
- `MLXLMCommon.GLM4.LayerArgs` — adapter struct (hiddenSize / intermediateSize / rmsNormEps).
- `MLXLMCommon.GLM4.MLP` — fused gate_up_proj SwiGLU: single matmul producing
  `2 * intermediate` outputs, split + silu(gate) * up + down. Bit-identical
  between the LLM `GLM4MLP` and the VLM `GlmOcrLanguage.MLP`.

What's NOT shared (documented in `MLXLMCommon/Models/GLM4.swift` file header)
- Attention — LLM uses standard `applyRotaryPosition(rope, ...)` with
  `partialRotaryFactor` and an internally-managed RoPE; VLM `GlmOcr`
  Attention takes a precomputed `(cos, sin)` tuple from
  `GlmOcrRotaryEmbedding` (M-RoPE family, same pattern as Qwen 3 VL).
- DecoderLayer / ModelInner — diverge on the Attention surface above.

Future-work alignment with `IMPLEMENTATION-PLAN.md`
- Once GlmOcr and Qwen3VL both consume a shared M-RoPE helper (same
  blocking factor as PR #177's deferred consolidation), the two VLM
  Attention classes shrink enough for a fuller cross-family share. Tracked
  via the WS-C consolidation umbrella issue #168.

Consumer changes
- `Libraries/MLXLLM/Models/GLM4.swift` — `class GLM4MLP` → `typealias
  GLM4MLP = GLM4.MLP` plus a `fileprivate convenience init(_ args:)` so
  the existing `GLM4MLP(args)` call site at `GLM4DecoderLayer` is
  preserved.
- `Libraries/MLXVLM/Models/GlmOcr.swift` — inner `fileprivate class MLP`
  → `fileprivate typealias MLP = MLXLMCommon.GLM4.MLP` inside the existing
  `private enum Language` namespace.
- `Libraries/MLXVLM/Models/GlmOcr.swift` `GlmOcr.prepare` — added the same
  prefill-sync `eval(cacheArrays + [logits])` barrier that landed for
  Gemma 3 / Gemma 4 / Mistral 3 / LFM 2 / Qwen 3 VL (issue #169 pattern).
  Pre-emptive: not currently observed on GLM-OCR, but the call site has
  the same shape as the families that did manifest the bug.

Bench registry
- Added `glm4-9b`, `glm4-32b`, `glmOcr` family entries to
  `Tests/Benchmarks/Utils/ModelRegistry.swift` so `--model glm4-9b
  --quant 4bit` works directly from the bench script.

Verification
- `swift build` clean across LLM + VLM + Benchmarks targets.
- LLM smoke (`mlx-community/GLM-4-9B-0414-4bit`, kv=none, simple): 79.8
  tok/s prefill, 50.7 tok/s decode, 390ms TTFT, 5.21GB peak. Coherent
  output: "Hello! I'm an AI assistant. I can help you with a wide range of
  topics, including answering questions, providing information, helping
  with calculations, and mo…"
- VLM smoke (`mlx-community/GLM-OCR-4bit`, kv=none, vision): 570.1 tok/s
  prefill, 247.0 tok/s decode, 1224ms TTFT, 2.46GB peak. Coherent output
  on the bench dog image: "The image shows a golden retriever standing on
  a concrete surface. The dog appears to be happy and alert, with its
  tail curled upwards. It is wearing…" — vision-expect "dog" matched.

Closes one of the 8 WS-C consolidation entries listed under issue #168.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski
ekryski force-pushed the ek/wsc6-glm4-consolidation branch from 2878027 to 13bdaf2 Compare May 8, 2026 00:29
@github-actions github-actions Bot added the feature New feature (auto-applied from feat: prefix) label May 8, 2026
@ekryski
ekryski merged commit c25d1cf into alpha May 8, 2026
5 checks passed
@ekryski
ekryski deleted the ek/wsc6-glm4-consolidation branch May 8, 2026 00:29
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…ekryski#178)

* Preserve QuickTime audio in memory-backed video assets

* Keep JPEG orientation metadata integer in the regression fixture

* Honor cumulative coverage and deferred retirement in paged test owner

---------

Co-authored-by: jonathan308 <5055076+jonathan308@users.noreply.github.com>
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…ski#192)

Since eeba2af (ekryski#178), 31 XCTest cases in five MiMo suites throw
nativeLaneRequired on the hosted CI runner, so every run of Fork Tests
on main fails. The tests need the exclusive native GPU lane, which the
runner does not have.

This change turns each of those throws into an XCTSkipUnless on the
same environment variables. The tests now skip, with the reason, on a
machine without the lane, and run as before where the variables are
set. The unused nativeLaneRequired enum case is removed from each
suite.

Tests only. No production code change.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
ml-explore#289)

* fix(cache): preserve demanded fork checkpoints and bound short capture

* test: let expected paged work refusals reach the caller (ekryski#209)

PagedWorkFixture.prepare wrapped prepareAttentionWork in XCTUnwrap.
XCTUnwrap records a test failure when its expression throws, also
when the caller expects the throw with XCTAssertThrowsError. Three
tests expect prepare to refuse, so each expected refusal was recorded
as a failure. prepare now throws the refusal to the caller and fails
only when prepareAttentionWork returns nil.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit b7bbdc2)

* fix(paged): write a full destination for broadcast direct KV (ekryski#210)

Materialize broadcast retained KV into a complete contiguous destination while preserving bit values, ownership validation, and reservation bounds. Focused differential paging, lifetime, and bit-exact validation completed during review.

(cherry picked from commit 3799b11)

* test(mimo): skip native-lane tests on machines without the lane (ekryski#192)

Since eeba2af (ekryski#178), 31 XCTest cases in five MiMo suites throw
nativeLaneRequired on the hosted CI runner, so every run of Fork Tests
on main fails. The tests need the exclusive native GPU lane, which the
runner does not have.

This change turns each of those throws into an XCTSkipUnless on the
same environment variables. The tests now skip, with the reason, on a
machine without the lane, and run as before where the variables are
set. The unused nativeLaneRequired enum case is removed from each
suite.

Tests only. No production code change.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit c288f53)

* test(mimo): assert the MiMo contracts that ekryski#171 shipped (ekryski#211)

Three assertions in the MiMo tests disagree with the code that the same
PR (ekryski#171) added:

- The MiMo cache conforms to CBv2MTPRectangularSerializing, and
  MiMoV26RectangularVerifyTests asserts that the bank supports
  rectangular MTP verification. The test asserted the opposite.
- CBv2PrefillRequirement.evaluationOnly returns a [B, 1] handle
  (EngineLoopV2.prefillOutput). The test expected shape [1].
- MiMoV26MTPAssistant conforms to
  CBv2HistoricalMTPPrefixCheckpointCoding (MiMoV26MTPPrefixCheckpoint).
  The test asserted that it is not a prefix checkpoint drafter.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 5e9d268)

* test: run bit-exact reference tests only on reference hardware (ekryski#174)

* style: format DiffusionGemmaVisionOracleTests.swift

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: format DiffusionGemmaFactoryTests.swift

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: run bit-exact reference tests only on reference hardware

Nine DiffusionGemma tests compare float bits with frozen references.
On the hosted macos-26 runner (Apple M1 VM) they differ in the low bits,
with no change in shape, dtype or sign. Add a `.referenceHardware`
Swift Testing trait that runs a test only when MLX_REFERENCE_HARDWARE=1,
and mark the nine tests with it. Elsewhere they report as skipped with
the reason. No assertion, tolerance or reference changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: gate only the bit comparisons of mixed DiffusionGemma tests

Three gated tests also held checks that pass on any hardware. Split them
so only the bit-for-bit comparison is gated:

- prefixIdentityTokensOwnerAndEmptyStateFailClosed() runs its
  fail-closed probes on all hardware. The donor-logits bit comparison
  moves to failClosedProbesLeaveDonorLogitsBitExact().
- nativeFactoryLoadsExactStateAndReleasesItsModel() keeps the load and
  model-release checks on all hardware. The logits bit comparison moves
  to nativeFactoryDenoiseMatchesReferenceBits().
- The two parameterized vision tests run their bf16 case on all
  hardware. The fp32 case moves to a separate gated test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: gate only the reference comparisons of three more DiffusionGemma tests

Split the three tests that were still gated whole, so their checks that
pass on any hardware run everywhere:

- chunkedSessionBoundsPrefillAndCanCancelAfterPrefill() keeps the
  prefill bounds, the complete flag, the counters, cancel, the emitted
  checkpoint and the released cache for widths 1, 3 and 7. The KV and
  logits bit comparisons move to chunkedSessionMatchesIndependentNativeReference().
- sharedWeightsConditioningKeepsCommittedCacheState() keeps the fixture
  checks, both cache positions and the unchanged encoder KV after the
  provisional canvas. The reference comparisons stay in
  sharedWeightsConditioningAndCommittedCacheMatchReference().
- committedPrefixRestoreKeepsPositionsAfterDonorRetirement() keeps the
  token count, retained bytes, donor release and both positions. The
  reference comparisons stay in
  committedPrefixRestoreIsExactAfterDonorAppendAndRetirement().

Each pair shares one helper. The fixture reference, case-count and
parameter-count checks of the block and fp32 vision fixtures also run
everywhere now, in blockOracleFixtureIsPinned() and fp32FixtureIsPinned().
CONTRIBUTING.md says which comparisons the gate covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit a046367)

* docs: describe demanded checkpoints and their shared fixture

* fix(cache): honor request participation in short checkpoint scheduling

* Preserve demanded checkpoint eligibility through preemption and packing

* test: size the slot-cap request from what the ledger accepts

slotCapLeavesRoomForServing() sized its request from bytesReserved.
bytesReserved includes the paged pool's physical-floor overhead, which a
request's target KV replaces when it reserves. The overhead depends on
the buffer sizes the MLX allocator returns: a 36,864-byte segment gets a
49,152-byte buffer, or a 65,536-byte buffer reused from the process-wide
cache. When earlier work left 64 KiB buffers in the cache, the capped
arm left more than 5.5 windows of real slack instead of half a window,
and the uncapped arm's reservation fit.

Find the largest request the ledger accepts beside the capped set with
trial reservations, then take half a window off it. The assertions do
not change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 06224a8)

* Retain demanded native frontiers and preserve observed prefill endpoints

* Document current SDK parameters and generation links

* Disambiguate the task generation documentation link

---------

Co-authored-by: David Tai <dtaipublic@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request feature New feature (auto-applied from feat: prefix)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant