From 6a0f4f9759d17c20908a7f2a5a00273bf4eb4cbb Mon Sep 17 00:00:00 2001 From: xocialize Date: Mon, 15 Jun 2026 20:05:01 -0700 Subject: [PATCH 1/4] Add Gemma3 allHiddenStates for frozen-text-encoder use MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Encoder-style multi-layer hidden-state extraction on Gemma3Model / Gemma3TextModel: returns the embedding output plus every transformer layer's output (numHiddenLayers + 1 states), under a single caller- supplied uniform mask (combined causal+padding), intentionally bypassing the per-layer sliding/global mask selection of the generation path. Motivation: multimodal generators increasingly condition on ALL hidden states of a frozen LLM text encoder rather than on generated tokens — e.g. Lightricks LTX-2 conditions its video DiT on all 49 hidden states of Gemma-3-12B. Per-layer materialization keeps command buffers small so long-sequence encodes on large checkpoints stay under the macOS GPU watchdog. Unit tests run on a tiny randomly-initialized model (no downloads): state count/shapes, first-state == scaled embedding, layers transform the state, determinism. Co-Authored-By: Claude Fable 5 --- .../Models/Gemma3Text+AllHiddenStates.swift | 54 ++++++++++++++ .../Gemma3AllHiddenStatesTests.swift | 71 +++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100644 Libraries/MLXLLM/Models/Gemma3Text+AllHiddenStates.swift create mode 100644 Tests/MLXLMTests/Gemma3AllHiddenStatesTests.swift diff --git a/Libraries/MLXLLM/Models/Gemma3Text+AllHiddenStates.swift b/Libraries/MLXLLM/Models/Gemma3Text+AllHiddenStates.swift new file mode 100644 index 0000000000..0c2cae4031 --- /dev/null +++ b/Libraries/MLXLLM/Models/Gemma3Text+AllHiddenStates.swift @@ -0,0 +1,54 @@ +// +// Gemma3Text+AllHiddenStates.swift +// mlx-swift-lm +// +// Encoder-style multi-layer hidden-state extraction for Gemma 3 text models. +// Supports using Gemma 3 as a frozen text ENCODER — a pattern in multimodal +// generation where a downstream model conditions on every layer's hidden state +// rather than on generated tokens (e.g. Lightricks LTX-2 conditions its video +// DiT on all 49 Gemma-3-12B hidden states). +// + +import Foundation +import MLX +import MLXLMCommon + +extension Gemma3Model { + /// Returns the embedding output plus each transformer layer's output — + /// `numHiddenLayers + 1` states, each shaped `(B, T, hiddenSize)`. + /// + /// A SINGLE uniform `mask` is applied to every layer. This is the + /// text-encoder use: the caller supplies a combined causal+padding mask and + /// the per-layer sliding-window/global mask selection used by + /// `callAsFunction(_:mask:cache:)` is intentionally bypassed. + public func allHiddenStates( + _ inputs: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode + ) -> [MLXArray] { + var h = embedTokens(inputs) + let scale = MLXArray(sqrt(Float(config.hiddenSize)), dtype: .bfloat16) + h = h * scale.asType(h.dtype) + + var states: [MLXArray] = [h] + for layer in layers { + h = layer(h, mask: mask, cache: nil) + // Per-layer materialization keeps each Metal command buffer small so + // long-sequence encodes on large checkpoints stay under the macOS GPU + // watchdog — without it, all layers fuse into one dispatch. + eval(h) + states.append(h) + } + return states + } +} + +extension Gemma3TextModel { + /// See ``Gemma3Model/allHiddenStates(_:mask:)``. Convenience forwarding from + /// the top-level text model to its inner `model`. + public func allHiddenStates( + _ inputs: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode + ) -> [MLXArray] { + model.allHiddenStates(inputs, mask: mask) + } +} diff --git a/Tests/MLXLMTests/Gemma3AllHiddenStatesTests.swift b/Tests/MLXLMTests/Gemma3AllHiddenStatesTests.swift new file mode 100644 index 0000000000..f527fc3658 --- /dev/null +++ b/Tests/MLXLMTests/Gemma3AllHiddenStatesTests.swift @@ -0,0 +1,71 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLMCommon +import Testing + +@testable import MLXLLM + +/// Unit tests for `Gemma3TextModel.allHiddenStates` — the encoder-style +/// multi-layer hidden-state extraction (frozen-text-encoder use). Runs on a +/// tiny randomly-initialized model; no weights are downloaded. +struct Gemma3AllHiddenStatesTests { + + private static func makeModel() -> Gemma3TextModel { + let config = Gemma3TextConfiguration( + modelType: "text", + hiddenSize: 64, hiddenLayers: 8, intermediateSize: 64, attentionHeads: 4, + headDim: 64, + rmsNormEps: 0.00001, vocabularySize: 100, kvHeads: 4, + ropeTheta: 1_000_000, ropeLocalBaseFreq: 10_000, + ropeTraditional: false, queryPreAttnScalar: 256, + slidingWindow: 512, slidingWindowPattern: 6, + maxPositionEmbeddings: 32768 + ) + let model = Gemma3TextModel(config) + eval(model) + return model + } + + @Test("Returns numHiddenLayers + 1 states with (B, T, hiddenSize) shapes") + func testStateCountAndShapes() { + let model = Self.makeModel() + let tokens = MLXArray([3, 14, 15, 92, 65, 35], [1, 6]) + let states = model.allHiddenStates(tokens, mask: .causal) + + #expect(states.count == 8 + 1) + for state in states { + #expect(state.shape == [1, 6, 64]) + } + } + + @Test("First state is the scaled embedding; layers change the state") + func testFirstStateIsScaledEmbeddingAndLayersTransform() { + let model = Self.makeModel() + let tokens = MLXArray([3, 14, 15, 92], [1, 4]) + let states = model.allHiddenStates(tokens, mask: .causal) + + let embedded = model.model.embedTokens(tokens) + let scale = MLXArray(sqrt(Float(64)), dtype: .bfloat16) + let expected = embedded * scale.asType(embedded.dtype) + #expect(allClose(states[0], expected).item(Bool.self)) + + // A randomly-initialized layer stack must actually transform the input. + let firstVsLast = allClose(states[0], states[8], atol: 1e-3).item(Bool.self) + #expect(!firstVsLast) + } + + @Test("Deterministic: repeated calls produce identical states") + func testDeterminism() { + let model = Self.makeModel() + let tokens = MLXArray([7, 42, 9, 88, 21], [1, 5]) + let a = model.allHiddenStates(tokens, mask: .causal) + let b = model.allHiddenStates(tokens, mask: .causal) + + #expect(a.count == b.count) + for (x, y) in zip(a, b) { + #expect(allClose(x, y).item(Bool.self)) + } + } +} From 92b0ead3219fa48d1584929a78f961a811b9b668 Mon Sep 17 00:00:00 2001 From: xocialize Date: Mon, 6 Jul 2026 17:14:29 -0600 Subject: [PATCH 2/4] style: swift-format import ordering in MTPSpeculativeTokenIteratorTests Move @_spi(Testing) @testable import below the plain imports to satisfy the swift-format pre-commit hook. Co-Authored-By: Claude Opus 4.8 --- Tests/MLXLMTests/MTPSpeculativeTokenIteratorTests.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Tests/MLXLMTests/MTPSpeculativeTokenIteratorTests.swift b/Tests/MLXLMTests/MTPSpeculativeTokenIteratorTests.swift index 98fc5513cd..518896a7a7 100644 --- a/Tests/MLXLMTests/MTPSpeculativeTokenIteratorTests.swift +++ b/Tests/MLXLMTests/MTPSpeculativeTokenIteratorTests.swift @@ -2,10 +2,11 @@ import Foundation import MLX -@_spi(Testing) @testable import MLXLMCommon import MLXNN import Testing +@_spi(Testing) @testable import MLXLMCommon + // MARK: - Synthetic mocks for iterator plumbing /// Records `draftBlock(...)` invocations and returns a fixed token pattern From c92f85debd7479235bedfaa2df43ca8d1b734ea8 Mon Sep 17 00:00:00 2001 From: Dustin Nielson Date: Thu, 16 Jul 2026 09:05:26 -0700 Subject: [PATCH 3/4] Rework: expose Gemma3 encoder surface instead of shipping allHiddenStates Per review feedback, the encoder-style allHiddenStates extension was too specialized for MLXLLM: its single uniform mask bypasses Gemma3's per-layer sliding-window/global mask selection, which diverges from generic Gemma3 semantics for texts longer than the sliding window. That tap now lives in client code; this repo only exposes the minimal public surface a client module needs to implement it: - Gemma3TextConfiguration.hiddenSize, .hiddenLayers: internal -> public - Gemma3TransformerBlock: internal -> public (init stays internal) - Gemma3TransformerBlock.callAsFunction(_:mask:cache:): internal -> public - Gemma3Model.embedTokens: internal -> public - Gemma3Model.layers: internal -> public - Gemma3Model.config: internal -> public No behavior changes; access levels and doc comments only. `public` (not `open`) since clients only call members from an extension; no subclassing is required. Gemma3EncoderAccessTests replaces the old test file: it implements the same allHiddenStates tap inside the test using `import MLXLLM` without `@testable`, proving the exposed surface is sufficient, and asserts state count (numHiddenLayers + 1), (B, T, hiddenSize) shapes, first state == scaled embedding, and determinism on a tiny randomly-initialized model. Co-Authored-By: Claude Opus 4.8 --- .../Models/Gemma3Text+AllHiddenStates.swift | 54 ---------- Libraries/MLXLLM/Models/Gemma3Text.swift | 21 ++-- .../Gemma3AllHiddenStatesTests.swift | 71 ------------- .../MLXLMTests/Gemma3EncoderAccessTests.swift | 100 ++++++++++++++++++ 4 files changed, 114 insertions(+), 132 deletions(-) delete mode 100644 Libraries/MLXLLM/Models/Gemma3Text+AllHiddenStates.swift delete mode 100644 Tests/MLXLMTests/Gemma3AllHiddenStatesTests.swift create mode 100644 Tests/MLXLMTests/Gemma3EncoderAccessTests.swift diff --git a/Libraries/MLXLLM/Models/Gemma3Text+AllHiddenStates.swift b/Libraries/MLXLLM/Models/Gemma3Text+AllHiddenStates.swift deleted file mode 100644 index 0c2cae4031..0000000000 --- a/Libraries/MLXLLM/Models/Gemma3Text+AllHiddenStates.swift +++ /dev/null @@ -1,54 +0,0 @@ -// -// Gemma3Text+AllHiddenStates.swift -// mlx-swift-lm -// -// Encoder-style multi-layer hidden-state extraction for Gemma 3 text models. -// Supports using Gemma 3 as a frozen text ENCODER — a pattern in multimodal -// generation where a downstream model conditions on every layer's hidden state -// rather than on generated tokens (e.g. Lightricks LTX-2 conditions its video -// DiT on all 49 Gemma-3-12B hidden states). -// - -import Foundation -import MLX -import MLXLMCommon - -extension Gemma3Model { - /// Returns the embedding output plus each transformer layer's output — - /// `numHiddenLayers + 1` states, each shaped `(B, T, hiddenSize)`. - /// - /// A SINGLE uniform `mask` is applied to every layer. This is the - /// text-encoder use: the caller supplies a combined causal+padding mask and - /// the per-layer sliding-window/global mask selection used by - /// `callAsFunction(_:mask:cache:)` is intentionally bypassed. - public func allHiddenStates( - _ inputs: MLXArray, - mask: MLXFast.ScaledDotProductAttentionMaskMode - ) -> [MLXArray] { - var h = embedTokens(inputs) - let scale = MLXArray(sqrt(Float(config.hiddenSize)), dtype: .bfloat16) - h = h * scale.asType(h.dtype) - - var states: [MLXArray] = [h] - for layer in layers { - h = layer(h, mask: mask, cache: nil) - // Per-layer materialization keeps each Metal command buffer small so - // long-sequence encodes on large checkpoints stay under the macOS GPU - // watchdog — without it, all layers fuse into one dispatch. - eval(h) - states.append(h) - } - return states - } -} - -extension Gemma3TextModel { - /// See ``Gemma3Model/allHiddenStates(_:mask:)``. Convenience forwarding from - /// the top-level text model to its inner `model`. - public func allHiddenStates( - _ inputs: MLXArray, - mask: MLXFast.ScaledDotProductAttentionMaskMode - ) -> [MLXArray] { - model.allHiddenStates(inputs, mask: mask) - } -} diff --git a/Libraries/MLXLLM/Models/Gemma3Text.swift b/Libraries/MLXLLM/Models/Gemma3Text.swift index 1cc94b0591..0385232f44 100644 --- a/Libraries/MLXLLM/Models/Gemma3Text.swift +++ b/Libraries/MLXLLM/Models/Gemma3Text.swift @@ -14,8 +14,8 @@ import MLXNN public struct Gemma3TextConfiguration: Codable { let modelType: String - let hiddenSize: Int - let hiddenLayers: Int + public let hiddenSize: Int + public let hiddenLayers: Int let intermediateSize: Int let attentionHeads: Int let headDim: Int @@ -232,7 +232,10 @@ class Gemma3MLP: Module { } } -class Gemma3TransformerBlock: Module { +/// A single Gemma 3 transformer layer. Public so client code can drive the +/// layer stack directly (e.g. encoder-style taps that collect every layer's +/// hidden state); construction remains internal to ``Gemma3Model``. +public class Gemma3TransformerBlock: Module { @ModuleInfo(key: "self_attn") var selfAttention: Gemma3Attention @ModuleInfo var mlp: Gemma3MLP @ModuleInfo(key: "input_layernorm") var inputLayerNorm: Gemma.RMSNorm @@ -265,7 +268,7 @@ class Gemma3TransformerBlock: Module { super.init() } - func callAsFunction( + public func callAsFunction( _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache? = nil @@ -283,11 +286,15 @@ class Gemma3TransformerBlock: Module { } public class Gemma3Model: Module { - @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding - @ModuleInfo var layers: [Gemma3TransformerBlock] + /// Token embedding table. Note callers must scale its output by + /// `sqrt(hiddenSize)` (in bfloat16) to match Gemma 3 semantics — see + /// ``callAsFunction(_:mask:cache:)``. + @ModuleInfo(key: "embed_tokens") public var embedTokens: Embedding + /// The transformer layer stack, exposed for encoder-style client taps. + @ModuleInfo public var layers: [Gemma3TransformerBlock] @ModuleInfo var norm: Gemma.RMSNorm - let config: Gemma3TextConfiguration + public let config: Gemma3TextConfiguration init(_ config: Gemma3TextConfiguration) { self.config = config diff --git a/Tests/MLXLMTests/Gemma3AllHiddenStatesTests.swift b/Tests/MLXLMTests/Gemma3AllHiddenStatesTests.swift deleted file mode 100644 index f527fc3658..0000000000 --- a/Tests/MLXLMTests/Gemma3AllHiddenStatesTests.swift +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright © 2026 Apple Inc. - -import Foundation -import MLX -import MLXLMCommon -import Testing - -@testable import MLXLLM - -/// Unit tests for `Gemma3TextModel.allHiddenStates` — the encoder-style -/// multi-layer hidden-state extraction (frozen-text-encoder use). Runs on a -/// tiny randomly-initialized model; no weights are downloaded. -struct Gemma3AllHiddenStatesTests { - - private static func makeModel() -> Gemma3TextModel { - let config = Gemma3TextConfiguration( - modelType: "text", - hiddenSize: 64, hiddenLayers: 8, intermediateSize: 64, attentionHeads: 4, - headDim: 64, - rmsNormEps: 0.00001, vocabularySize: 100, kvHeads: 4, - ropeTheta: 1_000_000, ropeLocalBaseFreq: 10_000, - ropeTraditional: false, queryPreAttnScalar: 256, - slidingWindow: 512, slidingWindowPattern: 6, - maxPositionEmbeddings: 32768 - ) - let model = Gemma3TextModel(config) - eval(model) - return model - } - - @Test("Returns numHiddenLayers + 1 states with (B, T, hiddenSize) shapes") - func testStateCountAndShapes() { - let model = Self.makeModel() - let tokens = MLXArray([3, 14, 15, 92, 65, 35], [1, 6]) - let states = model.allHiddenStates(tokens, mask: .causal) - - #expect(states.count == 8 + 1) - for state in states { - #expect(state.shape == [1, 6, 64]) - } - } - - @Test("First state is the scaled embedding; layers change the state") - func testFirstStateIsScaledEmbeddingAndLayersTransform() { - let model = Self.makeModel() - let tokens = MLXArray([3, 14, 15, 92], [1, 4]) - let states = model.allHiddenStates(tokens, mask: .causal) - - let embedded = model.model.embedTokens(tokens) - let scale = MLXArray(sqrt(Float(64)), dtype: .bfloat16) - let expected = embedded * scale.asType(embedded.dtype) - #expect(allClose(states[0], expected).item(Bool.self)) - - // A randomly-initialized layer stack must actually transform the input. - let firstVsLast = allClose(states[0], states[8], atol: 1e-3).item(Bool.self) - #expect(!firstVsLast) - } - - @Test("Deterministic: repeated calls produce identical states") - func testDeterminism() { - let model = Self.makeModel() - let tokens = MLXArray([7, 42, 9, 88, 21], [1, 5]) - let a = model.allHiddenStates(tokens, mask: .causal) - let b = model.allHiddenStates(tokens, mask: .causal) - - #expect(a.count == b.count) - for (x, y) in zip(a, b) { - #expect(allClose(x, y).item(Bool.self)) - } - } -} diff --git a/Tests/MLXLMTests/Gemma3EncoderAccessTests.swift b/Tests/MLXLMTests/Gemma3EncoderAccessTests.swift new file mode 100644 index 0000000000..6f87d03cc2 --- /dev/null +++ b/Tests/MLXLMTests/Gemma3EncoderAccessTests.swift @@ -0,0 +1,100 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLLM +import MLXNN +import Testing + +/// Verifies that the public Gemma 3 surface (`Gemma3Model.embedTokens`, +/// `Gemma3Model.layers`, `Gemma3TransformerBlock.callAsFunction`, and the +/// config's `hiddenSize`/`hiddenLayers`) is sufficient for a CLIENT module to +/// implement an encoder-style all-hidden-states tap — e.g. using Gemma 3 as a +/// frozen text encoder whose per-layer states condition a downstream model. +/// +/// Deliberately imports `MLXLLM` without `@testable`: everything below must +/// compile against public API only. Runs on a tiny randomly-initialized model; +/// no weights are downloaded. +struct Gemma3EncoderAccessTests { + + private static func makeModel() -> Gemma3TextModel { + let config = Gemma3TextConfiguration( + modelType: "text", + hiddenSize: 64, hiddenLayers: 8, intermediateSize: 64, attentionHeads: 4, + headDim: 64, + rmsNormEps: 0.00001, vocabularySize: 100, kvHeads: 4, + ropeTheta: 1_000_000, ropeLocalBaseFreq: 10_000, + ropeTraditional: false, queryPreAttnScalar: 256, + slidingWindow: 512, slidingWindowPattern: 6, + maxPositionEmbeddings: 32768 + ) + let model = Gemma3TextModel(config) + eval(model) + return model + } + + /// The client-side tap this access surface exists for: embedding output + /// plus each transformer layer's output — `numHiddenLayers + 1` states, + /// each shaped `(B, T, hiddenSize)` — with a single caller-supplied mask + /// applied uniformly to every layer. + private static func allHiddenStates( + of model: Gemma3TextModel, + inputs: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode + ) -> [MLXArray] { + let inner = model.model + var h = inner.embedTokens(inputs) + let scale = MLXArray(sqrt(Float(inner.config.hiddenSize)), dtype: .bfloat16) + h = h * scale.asType(h.dtype) + + var states: [MLXArray] = [h] + for layer in inner.layers { + h = layer(h, mask: mask, cache: nil) + eval(h) + states.append(h) + } + return states + } + + @Test("Tap returns numHiddenLayers + 1 states with (B, T, hiddenSize) shapes") + func testStateCountAndShapes() { + let model = Self.makeModel() + let tokens = MLXArray([3, 14, 15, 92, 65, 35], [1, 6]) + let states = Self.allHiddenStates(of: model, inputs: tokens, mask: .causal) + + #expect(states.count == model.config.hiddenLayers + 1) + for state in states { + #expect(state.shape == [1, 6, model.config.hiddenSize]) + } + } + + @Test("First state is the scaled embedding; layers change the state") + func testFirstStateIsScaledEmbeddingAndLayersTransform() { + let model = Self.makeModel() + let tokens = MLXArray([3, 14, 15, 92], [1, 4]) + let states = Self.allHiddenStates(of: model, inputs: tokens, mask: .causal) + + let embedded = model.model.embedTokens(tokens) + let scale = MLXArray(sqrt(Float(model.config.hiddenSize)), dtype: .bfloat16) + let expected = embedded * scale.asType(embedded.dtype) + #expect(allClose(states[0], expected).item(Bool.self)) + + // A randomly-initialized layer stack must actually transform the input. + let firstVsLast = allClose(states[0], states[states.count - 1], atol: 1e-3) + .item(Bool.self) + #expect(!firstVsLast) + } + + @Test("Deterministic: repeated calls produce identical states") + func testDeterminism() { + let model = Self.makeModel() + let tokens = MLXArray([7, 42, 9, 88, 21], [1, 5]) + let a = Self.allHiddenStates(of: model, inputs: tokens, mask: .causal) + let b = Self.allHiddenStates(of: model, inputs: tokens, mask: .causal) + + #expect(a.count == b.count) + for (x, y) in zip(a, b) { + #expect(allClose(x, y).item(Bool.self)) + } + } +} From 8ff0ade16223904a6f82bb65913d87202d2a6080 Mon Sep 17 00:00:00 2001 From: xocialize Date: Sat, 18 Jul 2026 15:50:04 -0700 Subject: [PATCH 4/4] Scope the Gemma3 encoder surface to @_spi(GemmaEncoder); fix DocC link Per review feedback, gate the newly exposed Gemma 3 encoder surface behind an SPI group instead of plain `public`, so opted-in clients can implement an encoder-style all-hidden-states tap without these symbols becoming advertised public API of MLXLLM. All seven declarations move from `public` to `@_spi(GemmaEncoder) public`: - Gemma3TextConfiguration.hiddenSize, .hiddenLayers - Gemma3TransformerBlock (class) and its callAsFunction(_:mask:cache:) - Gemma3Model.embedTokens, .layers, .config `Gemma3Model.layers` is typed on the SPI `Gemma3TransformerBlock`, so it must carry the same SPI group; the combination compiles and is usable from a client that writes `@_spi(GemmaEncoder) import MLXLLM`. Group name: the repo's only existing group is `@_spi(Testing)`, which marks test-only escape hatches (MTPSpeculativeTokenIterator's processor accessors, Gemma4Assistant.forwardHidden). This surface is meant for production client code, so reusing `Testing` would mislabel it; `GemmaEncoder` follows the purpose-descriptive, one-group-per-feature style of mlx-swift's `@_spi(MaterializedModule)`. Also fixes the `Verify documentation` CI failure. The doc comment on `Gemma3Model.embedTokens` used a relative link, ``callAsFunction(_:mask:cache:)``, which DocC tried to resolve as a child of the property. It cannot be fixed by qualifying it either: `Gemma3Model.callAsFunction` is internal, so it is not in the public symbol graph and `Gemma3Model/callAsFunction(...)` would not resolve (its signature also differs -- `mask` is optional there). Downgraded to plain code formatting with prose instead. Audited every doc comment this branch touches; this was the only symbol link. No behavior changes: access levels, attributes, and doc comments only. Co-Authored-By: Claude Opus 4.8 --- Libraries/MLXLLM/Models/Gemma3Text.swift | 34 +++++++++++-------- .../MLXLMTests/Gemma3EncoderAccessTests.swift | 22 +++++++----- 2 files changed, 33 insertions(+), 23 deletions(-) diff --git a/Libraries/MLXLLM/Models/Gemma3Text.swift b/Libraries/MLXLLM/Models/Gemma3Text.swift index 0385232f44..2283267c02 100644 --- a/Libraries/MLXLLM/Models/Gemma3Text.swift +++ b/Libraries/MLXLLM/Models/Gemma3Text.swift @@ -14,8 +14,8 @@ import MLXNN public struct Gemma3TextConfiguration: Codable { let modelType: String - public let hiddenSize: Int - public let hiddenLayers: Int + @_spi(GemmaEncoder) public let hiddenSize: Int + @_spi(GemmaEncoder) public let hiddenLayers: Int let intermediateSize: Int let attentionHeads: Int let headDim: Int @@ -232,10 +232,13 @@ class Gemma3MLP: Module { } } -/// A single Gemma 3 transformer layer. Public so client code can drive the -/// layer stack directly (e.g. encoder-style taps that collect every layer's -/// hidden state); construction remains internal to ``Gemma3Model``. -public class Gemma3TransformerBlock: Module { +/// A single Gemma 3 transformer layer. +/// +/// Exposed at `@_spi(GemmaEncoder)` scope so opted-in client code can drive the +/// layer stack directly — e.g. encoder-style taps that collect every layer's +/// hidden state — without this becoming advertised public API. Construction +/// remains internal to ``Gemma3Model``. +@_spi(GemmaEncoder) public class Gemma3TransformerBlock: Module { @ModuleInfo(key: "self_attn") var selfAttention: Gemma3Attention @ModuleInfo var mlp: Gemma3MLP @ModuleInfo(key: "input_layernorm") var inputLayerNorm: Gemma.RMSNorm @@ -268,7 +271,7 @@ public class Gemma3TransformerBlock: Module { super.init() } - public func callAsFunction( + @_spi(GemmaEncoder) public func callAsFunction( _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache? = nil @@ -286,15 +289,18 @@ public class Gemma3TransformerBlock: Module { } public class Gemma3Model: Module { - /// Token embedding table. Note callers must scale its output by - /// `sqrt(hiddenSize)` (in bfloat16) to match Gemma 3 semantics — see - /// ``callAsFunction(_:mask:cache:)``. - @ModuleInfo(key: "embed_tokens") public var embedTokens: Embedding - /// The transformer layer stack, exposed for encoder-style client taps. - @ModuleInfo public var layers: [Gemma3TransformerBlock] + /// Token embedding table. + /// + /// Exposed at `@_spi(GemmaEncoder)` scope. Callers must scale its output by + /// `sqrt(hiddenSize)` (computed in bfloat16) to match Gemma 3 semantics, as + /// this type's own `callAsFunction(_:mask:cache:)` does. + @ModuleInfo(key: "embed_tokens") @_spi(GemmaEncoder) public var embedTokens: Embedding + /// The transformer layer stack, exposed at `@_spi(GemmaEncoder)` scope for + /// encoder-style client taps. + @ModuleInfo @_spi(GemmaEncoder) public var layers: [Gemma3TransformerBlock] @ModuleInfo var norm: Gemma.RMSNorm - public let config: Gemma3TextConfiguration + @_spi(GemmaEncoder) public let config: Gemma3TextConfiguration init(_ config: Gemma3TextConfiguration) { self.config = config diff --git a/Tests/MLXLMTests/Gemma3EncoderAccessTests.swift b/Tests/MLXLMTests/Gemma3EncoderAccessTests.swift index 6f87d03cc2..087d7e78d3 100644 --- a/Tests/MLXLMTests/Gemma3EncoderAccessTests.swift +++ b/Tests/MLXLMTests/Gemma3EncoderAccessTests.swift @@ -2,19 +2,23 @@ import Foundation import MLX -import MLXLLM +@_spi(GemmaEncoder) import MLXLLM import MLXNN import Testing -/// Verifies that the public Gemma 3 surface (`Gemma3Model.embedTokens`, -/// `Gemma3Model.layers`, `Gemma3TransformerBlock.callAsFunction`, and the -/// config's `hiddenSize`/`hiddenLayers`) is sufficient for a CLIENT module to -/// implement an encoder-style all-hidden-states tap — e.g. using Gemma 3 as a -/// frozen text encoder whose per-layer states condition a downstream model. +/// Verifies that the `@_spi(GemmaEncoder)` Gemma 3 surface +/// (`Gemma3Model.embedTokens`, `Gemma3Model.layers`, +/// `Gemma3TransformerBlock.callAsFunction`, and the config's +/// `hiddenSize`/`hiddenLayers`) is sufficient for a CLIENT module to implement +/// an encoder-style all-hidden-states tap — e.g. using Gemma 3 as a frozen text +/// encoder whose per-layer states condition a downstream model. /// -/// Deliberately imports `MLXLLM` without `@testable`: everything below must -/// compile against public API only. Runs on a tiny randomly-initialized model; -/// no weights are downloaded. +/// Deliberately imports `MLXLLM` without `@testable`, opting in via +/// `@_spi(GemmaEncoder)` exactly as a client module would: everything below +/// must compile against declared API only, with no internal access. The SPI +/// opt-in keeps this surface off the advertised public API of MLXLLM while +/// still making it usable outside the module. Runs on a tiny +/// randomly-initialized model; no weights are downloaded. struct Gemma3EncoderAccessTests { private static func makeModel() -> Gemma3TextModel {