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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 8 additions & 13 deletions Libraries/MLXLLM/Models/GLM4.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,19 +73,14 @@ class GLM4Attention: Module {
}
}

class GLM4MLP: Module, UnaryLayer {
@ModuleInfo(key: "gate_up_proj") var gateUp: Linear
@ModuleInfo(key: "down_proj") var down: Linear

public init(_ args: GLM4Configuration) {
_gateUp.wrappedValue = Linear(args.hiddenSize, 2 * args.intermediateSize, bias: false)
_down.wrappedValue = Linear(args.intermediateSize, args.hiddenSize, bias: false)
}

public func callAsFunction(_ x: MLXArray) -> MLXArray {
let x = gateUp(x)
let chunks = split(x, parts: 2, axis: -1)
return down(silu(chunks[0]) * chunks[1])
// MLP is shared with the GlmOcr VLM language stack via `MLXLMCommon.GLM4.MLP`
// — a fused gate_up_proj SwiGLU. See file-level note in
// `Libraries/MLXLMCommon/Models/GLM4.swift` for why only the MLP is shared.
typealias GLM4MLP = GLM4.MLP

extension GLM4.MLP {
fileprivate convenience init(_ args: GLM4Configuration) {
self.init(dimensions: args.hiddenSize, hiddenDimensions: args.intermediateSize)
}
}

Expand Down
72 changes: 72 additions & 0 deletions Libraries/MLXLMCommon/Models/GLM4.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright © 2026 Apple Inc.
//
// Shared GLM 4 building blocks. Like Qwen 3 (PR #177), the GLM 4
// family has substantive architectural divergence between LLM and VLM
// that prevents a full layer-stack consolidation in this PR:
//
// - LLM `GLM4Attention` uses standard `applyRotaryPosition(rope, ...)`
// with `partialRotaryFactor` and an internally-managed RoPE.
// - VLM `GlmOcr` Attention takes a precomputed `(cos, sin)` tuple from
// outside via `positionEmbeddings` parameter, with a custom
// `GlmOcrRotaryEmbedding` class generating the (cos, sin) pair using
// multimodal positionIds. Same M-RoPE family of design as Qwen3VL.
//
// Forcing a unified shared Attention would either degrade the LLM's
// inline-RoPE path or impose an indirection on the LLM hot path.
// Instead, this namespace lifts what's bit-identical (the fused
// gate-up-proj SwiGLU MLP) and leaves Attention / DecoderLayer /
// ModelInner per-target.
//
// Future-work alignment with `IMPLEMENTATION-PLAN.md`:
//
// - **M-RoPE shared helper** — same blocking factor as PR #177 (Qwen
// 3). Once GlmOcr and Qwen3VL both consume a shared M-RoPE helper,
// their respective Attention classes shrink enough for fuller
// consolidation. Track via the consolidation umbrella issue.
//
// Consolidation reference: issue #168.

import Foundation
import MLX
import MLXNN

/// Public namespace for the GLM 4 text decoder. The layer-stack
/// classes are intentionally NOT included here; see file-level note.
public enum GLM4 {

// MARK: - LayerArgs (adapter)

public struct LayerArgs: Sendable {
public let hiddenSize: Int
public let intermediateSize: Int
public let rmsNormEps: Float

public init(hiddenSize: Int, intermediateSize: Int, rmsNormEps: Float) {
self.hiddenSize = hiddenSize
self.intermediateSize = intermediateSize
self.rmsNormEps = rmsNormEps
}
}

// MARK: - MLP

/// Fused gate-up SwiGLU MLP — single `gate_up_proj` matmul producing
/// `2 * intermediate` outputs, then split + silu(gate) * up + down.
/// Bit-identical between the LLM `GLM4MLP` and VLM `GlmOcrLanguage.MLP`.
public class MLP: Module, UnaryLayer {
@ModuleInfo(key: "gate_up_proj") var gateUp: Linear
@ModuleInfo(key: "down_proj") var down: Linear

public init(dimensions: Int, hiddenDimensions: Int) {
self._gateUp.wrappedValue = Linear(dimensions, 2 * hiddenDimensions, bias: false)
self._down.wrappedValue = Linear(hiddenDimensions, dimensions, bias: false)
super.init()
}

public func callAsFunction(_ x: MLXArray) -> MLXArray {
let xx = gateUp(x)
let parts = split(xx, parts: 2, axis: -1)
return down(silu(parts[0]) * parts[1])
}
}
}
32 changes: 16 additions & 16 deletions Libraries/MLXVLM/Models/GlmOcr.swift
Original file line number Diff line number Diff line change
Expand Up @@ -198,22 +198,11 @@ private enum Language {

// MARK: MLP

fileprivate class MLP: Module, UnaryLayer {

@ModuleInfo(key: "gate_up_proj") var gateUpProj: Linear
@ModuleInfo(key: "down_proj") var down: Linear

public init(dimensions: Int, hiddenDimensions: Int) {
self._gateUpProj.wrappedValue = Linear(dimensions, hiddenDimensions * 2, bias: false)
self._down.wrappedValue = Linear(hiddenDimensions, dimensions, bias: false)
}

public func callAsFunction(_ x: MLXArray) -> MLXArray {
let x = gateUpProj(x)
let parts = split(x, parts: 2, axis: -1)
return down(silu(parts[0]) * parts[1])
}
}
// Shared with the LLM `GLM4` text decoder via the `MLXLMCommon.GLM4`
// namespace — fused `gate_up_proj` SwiGLU. See file-level note in
// `Libraries/MLXLMCommon/Models/GLM4.swift` for why this is the only
// bit-identical layer between the LLM and VLM stacks.
fileprivate typealias MLP = MLXLMCommon.GLM4.MLP

// MARK: Decoder Layer

Expand Down Expand Up @@ -1034,6 +1023,17 @@ public class GlmOcr: Module, VLMModel, KVCacheDimensionProvider {

let result = languageModel(nil, cache: cache, inputEmbedding: inputEmbeddings)

// Mirror the Gemma 4 / Gemma 3 / Mistral 3 / LFM 2 / Qwen 3 VL
// prefill-sync barrier (see #169): the prefill leaves K/V writes
// pending in the command buffer, so the iterator's first decode
// forward can read the cache before those writes commit, producing
// garbage logits. Hard sync on cache + logits before returning.
var cacheArrays: [MLXArray] = []
for c in cache {
cacheArrays.append(contentsOf: c.innerState())
}
eval(cacheArrays + [result.logits])

return .logits(result)
}

Expand Down
47 changes: 47 additions & 0 deletions Tests/Benchmarks/Utils/ModelRegistry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,51 @@ enum ModelRegistry {
supportsThinking: false, reasoningEffort: nil
)

// MARK: - GLM 4

static let glm4_9B = ModelFamily(
name: "GLM 4 9B 0414", shortName: "glm4-9b",
variants: [
.init(quantization: "bf16", repoId: "mlx-community/GLM-4-9B-0414-bf16"),
.init(quantization: "8bit", repoId: "mlx-community/GLM-4-9B-0414-8bit"),
.init(quantization: "6bit", repoId: "mlx-community/GLM-4-9B-0414-6bit"),
.init(quantization: "4bit", repoId: "mlx-community/GLM-4-9B-0414-4bit"),
],
temperature: 0.6, topP: 0.95, topK: 20, minP: 0.0,
presencePenalty: nil, repetitionPenalty: nil,
extraEOSTokens: [],
supportsThinking: false, reasoningEffort: nil
)

static let glm4_32B = ModelFamily(
name: "GLM 4 32B 0414", shortName: "glm4-32b",
variants: [
.init(quantization: "8bit", repoId: "mlx-community/GLM-4-32B-0414-8bit"),
.init(quantization: "6bit", repoId: "mlx-community/GLM-4-32B-Base-0414-6bit"),
.init(quantization: "4bit", repoId: "mlx-community/GLM-4-32B-0414-4bit"),
],
temperature: 0.6, topP: 0.95, topK: 20, minP: 0.0,
presencePenalty: nil, repetitionPenalty: nil,
extraEOSTokens: [],
supportsThinking: false, reasoningEffort: nil
)

// MARK: - GlmOcr (VLM — vision encoder + GLM 4 text decoder)

static let glmOcr = ModelFamily(
name: "GLM-OCR (VLM)", shortName: "glm-ocr",
variants: [
.init(quantization: "bf16", repoId: "mlx-community/GLM-OCR-bf16"),
.init(quantization: "8bit", repoId: "mlx-community/GLM-OCR-8bit"),
.init(quantization: "6bit", repoId: "mlx-community/GLM-OCR-6bit"),
.init(quantization: "4bit", repoId: "mlx-community/GLM-OCR-4bit"),
],
temperature: 0.6, topP: 0.95, topK: 20, minP: 0.0,
presencePenalty: nil, repetitionPenalty: nil,
extraEOSTokens: [],
supportsThinking: false, reasoningEffort: nil
)

// MARK: - All Families

static let allFamilies: [ModelFamily] = [
Expand All @@ -488,12 +533,14 @@ enum ModelRegistry {
lfm2_1_2B,
ministral3_3B,
gemma3_1B,
glm4_9B, glm4_32B,
// Vision-language (text+vision)
lfm2_VL_1_6B,
mistralSmall3_1_24B_VL,
qwen2VL_2B, qwen25VL_3B,
fastvlm_0_5B,
gemma3_4B,
glmOcr,
]

/// Alternate `--model` names → registry `shortName` (keys lowercased).
Expand Down