Skip to content

Expose minimal Gemma3 surface for frozen-text-encoder use - #387

Merged
davidkoski merged 6 commits into
ml-explore:mainfrom
xocialize:gemma3-all-hidden-states
Jul 21, 2026
Merged

davidkoski merged 6 commits into
ml-explore:mainfrom
xocialize:gemma3-all-hidden-states

Conversation

@xocialize

@xocialize xocialize commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Multimodal generators increasingly use a frozen LLM as a text encoder, conditioning on the hidden states of every layer rather than on generated tokens. A concrete example: Lightricks LTX-2 conditions its video DiT on all 49 hidden states of Gemma-3-12B-it. We've been carrying this as a small fork while building a Swift port of LTX-2 — upstreaming so the next consumer of Gemma-3-as-encoder doesn't have to.

Shape (reworked per review)

Originally this PR shipped an allHiddenStates(_:mask:) extension in MLXLLM. Per review, that tap is pipeline-specific (its uniform mask matches the LTX-2 reference encoder, not generic Gemma3 per-layer sliding/global semantics) — so it now lives in client code, and this PR only widens visibility, scoped to @_spi(GemmaEncoder) so it isn't advertised public API:

  • Gemma3TextConfiguration.hiddenSize, .hiddenLayers
  • Gemma3TransformerBlock + its callAsFunction(_:mask:cache:)
  • Gemma3Model.embedTokens, .layers, .config

Clients opt in with @_spi(GemmaEncoder) import MLXLLM. Zero behavior change — attributes and doc comments only.

Testing

Gemma3EncoderAccessTests locks the contract: it implements the client-side all-hidden-states tap using @_spi(GemmaEncoder) import MLXLLM — no @testable — on a tiny randomly-initialized model (no downloads), asserting state count (hiddenLayers + 1), shapes, first-state == scaled embedding, layer transformation, and determinism. 3/3 pass via xcodebuild test. If the exposed surface regresses, this test stops compiling.

Branch is merged up to current main; scripts/verify-docs.sh builds MLXLLM docs clean under --warnings-as-errors.

🤖 Generated with Claude Code

xocialize and others added 2 commits July 2, 2026 07:50
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 <noreply@anthropic.com>
Move @_spi(Testing) @testable import below the plain imports to satisfy
the swift-format pre-commit hook.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Comment on lines +24 to +27
public func allHiddenStates(
_ inputs: MLXArray,
mask: MLXFast.ScaledDotProductAttentionMaskMode
) -> [MLXArray] {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like a really cool idea, but I have some questions & concerns about it.

  • should this live in MLXEmbedders? that is where models that do this type of encoding live. I realize this is a bit different than what they do, but would it make more sense to do this on an embedding model (less weights to load, etc)?
  • the embedding model may not be the same as the full gemma3 model so it might not produce the same results, but I wonder if an ability to load the full weights into the encoding model would do the trick? it should be the same structure and the sanitize should discard the unused pieces
  • is this something that would be widely used? It seems like it might be a bit specialized and maybe is better suited as an extension (like this) in the client code. perhaps we just need to make Gemma3Model open (plus expose the bits needed)?

and separately I think there is a correctness issue:

  • the gemma3 mask is a bit complicated with global and local masks for different layers, e.g.
            fullMask = createAttentionMask(h: h, cache: cacheArray[firstFullIdx])

            let slidingWindow = config.slidingWindow > 0 ? config.slidingWindow : 4096
            slidingWindowMask = createAttentionMask(
                h: h, cache: cacheArray[firstSlidingIdx], windowSize: slidingWindow)

It could be that coincidentally, if your text is <= than the prefill window size (512) then it would produce the same result, but it is complicated and I think not quite correct. The mean cosine you report for 1024 might be caused by this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the careful look @davidkoski — I think you've landed on the right answer, and your mask concern is actually the strongest argument for it.

On the mask: you're right about the semantics. The single uniform mask is deliberate — it matches the reference LTX-2 encoder implementation (which is what the video DiT was trained against), not generic Gemma3 generation semantics. The parity goldens in the PR description come from that same reference, so the 0.999866 at T=1024 is 4-bit quant/accumulation noise rather than mask divergence — but your underlying point stands: as a generic Gemma3Model feature, a mask that silently diverges from the model's own per-layer sliding/global selection for T > window is surprising API. That's pipeline-specific behavior, and it shouldn't live in MLXLLM.

Which is your option 3. I've reworked the PR accordingly: the allHiddenStates extension and its LTX-specific masking are gone; the PR is now just the minimal visibility changes needed so a client module can implement the tap itself, plus a test that proves sufficiency — it implements the same tap using only import MLXLLM (no @testable) against a tiny randomly-initialized model, so the exposed surface can't silently regress. We'll carry the actual encoder tap (uniform mask + the per-layer eval that keeps 12B-class encodes under the GPU watchdog) in our LTX package where it belongs.

On MLXEmbedders (your first two questions): we considered it, but the encoder must reproduce exactly the hidden states the pipeline was trained against — full Gemma-3-12B-it weights, all 49 states, the reference's masking. An embedders-side model would still need the same specialized tap and masking to be exact, so it moves the specialization rather than removing it. If a general "LLM-as-encoder" story lands in MLXEmbedders someday we'd happily migrate; for now the open/expose route keeps upstream clean.

The branch is also merged up to current main (which brings in the #404 CI fix, so mac_build_and_test should actually run now). Let me know if the exposure set looks right or if you'd prefer any of it shaped differently.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See what you think about my questions / concern. Thanks!

xocialize and others added 2 commits July 16, 2026 08:56
…ates

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 <noreply@anthropic.com>
@xocialize xocialize changed the title Add Gemma3 allHiddenStates for frozen-text-encoder use Expose minimal Gemma3 surface for frozen-text-encoder use Jul 16, 2026
@davidkoski

Copy link
Copy Markdown
Member

Awesome, i will take a look! What you said about exact repro makes sense.

For exposing the innards, I wonder if using @_spi would make sense:

    /// Usable by extensions to implement `callAsFunction()`
    @_spi(MaterializedModule)
    public let _base: LayerType  

Then in other packages you can explicitly expose access to the symbol like this:

@_spi(MaterializedModule) import MLXNN

extension MaterializedModule: EmbeddingModel where LayerType: EmbeddingModel {

    public func callAsFunction() {
...
        return _base(

Many models already have bits and pieces exposed as public so the change you made may be correct. This @_spi piece is something I learned about recently and it looks like it might be useful in cases like this -- you want to expose something but not fully advertise it.

xocialize and others added 2 commits July 18, 2026 15:44
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 <noreply@anthropic.com>
@xocialize

Copy link
Copy Markdown
Contributor Author

@_spi is a much better fit than plain public here — thanks for the pointer, I hadn't used it. Pushed: the whole surface is now @_spi(GemmaEncoder) public, and clients opt in with @_spi(GemmaEncoder) import MLXLLM. It keeps these internals out of the advertised API while still making the tap implementable, which seems like exactly the "expose but don't advertise" case you described.

Notes on the choices, in case you'd shape any of them differently:

  • Group name. The repo currently has one group, @_spi(Testing), used for test-only escape hatches — reusing it would mislabel a surface meant for production client code, so I went with a purpose-descriptive GemmaEncoder following the MaterializedModule style. Happy to rename or fold it into a single shared repo-wide group if you'd rather have one.
  • layers must carry the group since its element type is SPI — compiler requirement rather than a choice.
  • config is exposed whole, which hands clients the entire Gemma3TextConfiguration even though only hiddenSize/hiddenLayers are SPI-public. I kept it because the tap wants config.hiddenLayers to size the result and threading the two values separately is clumsier — but if you'd prefer to drop config and expose only those two, that's an easy trim.
  • DocC fix. Verify documentation was failing on a relative callAsFunction(_:mask:cache:) link I'd written on a property (DocC resolved it as a child of embedTokens). Qualifying it wasn't possible — Gemma3Model.callAsFunction is internal, so it isn't in the public symbol graph — so it's plain code formatting now. Verified with scripts/verify-docs.sh: MLXLLM builds clean under --warnings-as-errors. (Worth noting the @_spi change alone would have turned CI green, since SPI symbols drop out of the symbol graph — I fixed the comment anyway so it's correct on its own.)

One limitation worth stating plainly, since it's the flip side of your original mask concern: Gemma3TransformerBlock.callAsFunction takes a non-optional mask, so this surface only enables a uniform-mask tap — a client can't reproduce the per-layer sliding/global selection that Gemma3Model.callAsFunction does. That's exactly what our encoder wants (it must match the LTX-2 reference), but it does mean the surface isn't a general-purpose "run the layer stack correctly" API. If you'd rather it were, exposing the mask construction would be the additional piece — though that's more surface than this PR needs, so I've left it out.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes look good, thank you!

@davidkoski
davidkoski merged commit 6608a35 into ml-explore:main Jul 21, 2026
2 checks passed
xocialize added a commit to xocialize/ltx-2-mlx-swift that referenced this pull request Jul 22, 2026
Upstream ml-explore/mlx-swift-lm#387 (merged 2026-07-21, 6608a35) exposes a
minimal Gemma3 surface behind @_spi(GemmaEncoder), but deliberately did not take
our allHiddenStates implementation — a single uniform mask across every layer
matches the LTX-2 reference encoder yet diverges from generic Gemma3 sliding/
global semantics, so it is pipeline-specific and belongs here.

So it moves here. ../mlx-swift-lm is now checked out at plain upstream main and
carries zero local patches, degrading from a fork to a plain revision pin. The
two former fork commits stay on the ltx/gemma-all-hidden-states branch.

New Sources/LTX2/Gemma3+AllHiddenStates.swift ports all three load-bearing
behaviors verbatim: a single uniform caller-supplied causal+padding mask applied
to every layer; per-layer eval, which keeps each Metal command buffer under the
macOS GPU watchdog at T=1024 on the 12B checkpoint; and per-layer
Task.checkCancellation() behind a throws signature, so a cancel lands within
~one layer instead of riding the whole 48-layer forward. The bf16
embed_tokens(ids) * sqrt(hiddenSize) scale is preserved. GemmaEncoder's call
site is unchanged.

Parity reproduces the baseline exactly: --gemma-gate mean cosine 0.999866 across
all 49 hidden states at T=1024 on Gemma-3-12B-it-4bit. --connector-gate and
--text-encode-gate green, full swift test suite passing. The @_spi surface is
sufficient; no upstream follow-up needed.

Two pre-existing problems had to be fixed to run the gates at all. Upstream's
loader now prefers model.safetensors.index.json over globbing *.safetensors, and
the local Gemma checkpoint had been repacked 5 shards to 2 without regenerating
its index, so it pointed at files that no longer exist; the index was rebuilt in
place from the actual shards. And dump_text_encode_goldens.py only emitted .npy
while the Swift gates and the downstream dit_full/e2e_t2v dumpers read a packed
goldens.safetensors — that packing step was ad-hoc, and is now part of the
dumper. RunLTX2's defaultGoldens is derived from #filePath instead of a
pre-relocation absolute path.

The pin is transitional: no release tag contains #387 yet, so this stays a path
dep on a main checkout and must not be shipped from. Adopting a future tag is a
one-line Package.swift edit, marked inline.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
…#387)

Expose Gemma3 encoder surface behind @_spi(GemmaEncoder) for frozen-text-encoder use

Multimodal generators (e.g. Lightricks LTX-2) increasingly condition on ALL hidden states of a frozen LLM text encoder rather than generated tokens. Since an encoder-style all-hidden-states tap uses a single uniform mask that bypasses Gemma3's per-layer sliding-window/global mask selection, it diverges from generic Gemma3 semantics for long texts — so it doesn't belong in MLXLLM itself. Instead, this exposes the minimal surface needed for client code to implement that tap:

Gemma3TextConfiguration.hiddenSize, .hiddenLayers
Gemma3TransformerBlock (class) and .callAsFunction(_:mask:cache:)
Gemma3Model.embedTokens, .layers, .config
All seven are gated @_spi(GemmaEncoder) public (not plain public) so they're usable via @_spi(GemmaEncoder) import MLXLLM without becoming advertised public API. GemmaEncoder is a new SPI group, distinct from the existing test-only @_spi(Testing).

No behavior changes — access levels, attributes, and doc comments only.

Gemma3EncoderAccessTests proves sufficiency by implementing the allHiddenStates tap in test code using only the exposed surface (no @testable), checking state count (numHiddenLayers + 1), (B, T, hiddenSize) shapes, first state == scaled embedding, and determinism on a tiny randomly-initialized model.
davidkoski pushed a commit that referenced this pull request Aug 13, 2026
Expose Gemma 4 encoder surface at @_spi(GemmaEncoder)

Mirrors #387's Gemma 3 exposure for Gemma 4, letting client code drive the
decoder stack directly (e.g., an encoder-style tap collecting all hidden
states) with Gemma 4 as a frozen text encoder.

Exposed under @_spi(GemmaEncoder), off MLXLLM's public API but usable
externally:
  * Gemma4TextConfiguration.hiddenSize / .numHiddenLayers
  * Gemma4DecoderLayer + callAsFunction
  * Gemma4TextModelInner (embedTokens/layers/norm/embedScale/config)
  * Gemma4TextModel.model
  * Gemma4Model.languageModel

Differences from the Gemma 3 change:
1. Gemma4SharedKVState: `package` → `public` (MLXLMCommon), required since it
   appears in callAsFunction's signature. Non-KV-sharing clients pass nil.
2. Gemma4DecoderLayer's private-typed stored properties (selfAttn, mlp,
   router, experts) are now fileprivate — the narrowest fix for the class
   becoming public.

Gemma4EncoderAccessTests validates the surface (like Gemma3EncoderAccessTests)
using only exposed APIs, no @testable: state count, shapes, first-state ==
scaled embedding, determinism, and actual layer transformation — on a tiny
random model with no downloaded weights. Test config zeroes out
per-layer/MoE/shared-KV settings, matching what a self-contained encoder tap
sees.

Critically, the test walks the real load path: it decodes a wrapped
`gemma4_unified` config and reaches the text model via `Gemma4Model.languageModel`
(previously `fileprivate`), rather than constructing `Gemma4TextModel` directly.
Exposing only the inner types wasn't sufficient for an actual checkpoint load —
a sufficiency test that skips the entry point proves the wrong thing.
xocialize added a commit to xocialize/mlx-swift-lm that referenced this pull request Aug 30, 2026
Mirrors the Gemma 3/4 encoder exposures (ml-explore#387, and the Gemma 4 follow-up) for
Falcon-H1, so client code can run the decoder stack over an embedding it built
itself rather than over a single token id.

The motivating case is a DualAR TTS model (Audio8 TTS Preview 0.1b, model_type
`arktts`, `slow_backbone: falcon_h1`) whose slow-stack input is a text embedding
summed with ten codec-codebook embeddings. Such a client never has one token id
to look up, so `FalconH1ModelInner.callAsFunction(_:mask:cache:)` is unreachable
for it, and today the only options are to fork the file or re-implement the mask
setup and layer loop against internal details.

Exposed at @_spi(FalconH1Encoder) scope, keeping this off the advertised public
API of MLXLLM while making it usable outside the module:
  * FalconH1Configuration.hiddenSize / .numHiddenLayers / .rmsNormEps /
    .embeddingMultiplier
  * FalconH1DecoderLayer and its callAsFunction
  * FalconH1ModelInner.init, .embedTokens, .layers, .finalLayerNorm
  * FalconH1ModelInner.callAsFunction(inputsEmbeds:cache:) — new
  * FalconH1ModelInner.callAsFunction(_:mask:cache:) — was internal

`callAsFunction(inputsEmbeds:cache:)` is the seam; the token-id overload now
delegates to it, so the two paths cannot drift. No behaviour changes for
existing callers: FalconH1Model still embeds, runs the stack and applies the
head exactly as before.

`FalconH1ModelInner.init` is exposed because constructing `FalconH1Model` is not
an equivalent way in: the wrapper adds an `lm_head` whenever
`tie_word_embeddings` is false, which is the decoded default. A client bringing
its own head does not want that module and would otherwise have to account for
it when matching module keys against a checkpoint.

`FalconH1Model.model` and the mask helpers (`createSSMMask`,
`createAttentionMask`) were already public, and none of the layer's stored
property types are `private`, so unlike the Gemma 4 change nothing else had to
widen.

FalconH1EncoderAccessTests proves sufficiency the way the Gemma access tests do:
it drives the stack using ONLY the exposed surface, importing MLXLLM without
@testable and opting in via @_spi(FalconH1Encoder). It checks shape,
determinism, that the seam agrees with the token path, that the layer stack can
be driven a layer at a time to tap every hidden state, and that the stack
actually transforms its input — the last so the suite cannot pass on a seam that
returns its argument or runs zero layers.

One test earns its place beyond access checking. `sanitize()` folds
`embedding_multiplier` into `embed_tokens.weight`, which is right when the token
lookup is the only thing entering the stack but is a live trap for a composite-
embedding client: fold it and add unscaled contributions, and the lookup half is
scaled while the rest is not. Measured against the PyTorch reference for the
model above, that is 77% relative error on the embedding and 38% on the final
hidden state — while still producing plausible audio of the right length, so
listening does not catch it. testCompositeEmbeddingMultiplierEquivalence pins
`(raw + other) * m == folded + other * m` and asserts the unscaled-remainder
variant is observably different, both at the embedding and after the stack, so
the wrong form cannot quietly become the expected one.

Runs on a tiny randomly-initialized model; no weights are downloaded.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
davidkoski pushed a commit that referenced this pull request Aug 31, 2026
Mirrors the Gemma 3/4 encoder exposures (#387, and the Gemma 4 follow-up) for
Falcon-H1, so client code can run the decoder stack over an embedding it built
itself rather than over a single token id.

The motivating case is a DualAR TTS model (Audio8 TTS Preview 0.1b, model_type
`arktts`, `slow_backbone: falcon_h1`) whose slow-stack input is a text embedding
summed with ten codec-codebook embeddings. Such a client never has one token id
to look up, so `FalconH1ModelInner.callAsFunction(_:mask:cache:)` is unreachable
for it, and today the only options are to fork the file or re-implement the mask
setup and layer loop against internal details.

Exposed at @_spi(FalconH1Encoder) scope, keeping this off the advertised public
API of MLXLLM while making it usable outside the module:
  * FalconH1Configuration.hiddenSize / .numHiddenLayers / .rmsNormEps /
    .embeddingMultiplier
  * FalconH1DecoderLayer and its callAsFunction
  * FalconH1ModelInner.init, .embedTokens, .layers, .finalLayerNorm
  * FalconH1ModelInner.callAsFunction(inputsEmbeds:cache:) — new
  * FalconH1ModelInner.callAsFunction(_:mask:cache:) — was internal

`callAsFunction(inputsEmbeds:cache:)` is the seam; the token-id overload now
delegates to it, so the two paths cannot drift. No behaviour changes for
existing callers: FalconH1Model still embeds, runs the stack and applies the
head exactly as before.

`FalconH1ModelInner.init` is exposed because constructing `FalconH1Model` is not
an equivalent way in: the wrapper adds an `lm_head` whenever
`tie_word_embeddings` is false, which is the decoded default. A client bringing
its own head does not want that module and would otherwise have to account for
it when matching module keys against a checkpoint.

`FalconH1Model.model` and the mask helpers (`createSSMMask`,
`createAttentionMask`) were already public, and none of the layer's stored
property types are `private`, so unlike the Gemma 4 change nothing else had to
widen.

FalconH1EncoderAccessTests proves sufficiency the way the Gemma access tests do:
it drives the stack using ONLY the exposed surface, importing MLXLLM without
@testable and opting in via @_spi(FalconH1Encoder). It checks shape,
determinism, that the seam agrees with the token path, that the layer stack can
be driven a layer at a time to tap every hidden state, and that the stack
actually transforms its input — the last so the suite cannot pass on a seam that
returns its argument or runs zero layers.

One test earns its place beyond access checking. `sanitize()` folds
`embedding_multiplier` into `embed_tokens.weight`, which is right when the token
lookup is the only thing entering the stack but is a live trap for a composite-
embedding client: fold it and add unscaled contributions, and the lookup half is
scaled while the rest is not. Measured against the PyTorch reference for the
model above, that is 77% relative error on the embedding and 38% on the final
hidden state — while still producing plausible audio of the right length, so
listening does not catch it. testCompositeEmbeddingMultiplierEquivalence pins
`(raw + other) * m == folded + other * m` and asserts the unscaled-remainder
variant is observably different, both at the embedding and after the stack, so
the wrong form cannot quietly become the expected one.

Runs on a tiny randomly-initialized model; no weights are downloaded.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
djandrewgibbons pushed a commit to djandrewgibbons/mlx-swift-lm that referenced this pull request Sep 1, 2026
…e#596)

Mirrors the Gemma 3/4 encoder exposures (ml-explore#387, and the Gemma 4 follow-up) for
Falcon-H1, so client code can run the decoder stack over an embedding it built
itself rather than over a single token id.

The motivating case is a DualAR TTS model (Audio8 TTS Preview 0.1b, model_type
`arktts`, `slow_backbone: falcon_h1`) whose slow-stack input is a text embedding
summed with ten codec-codebook embeddings. Such a client never has one token id
to look up, so `FalconH1ModelInner.callAsFunction(_:mask:cache:)` is unreachable
for it, and today the only options are to fork the file or re-implement the mask
setup and layer loop against internal details.

Exposed at @_spi(FalconH1Encoder) scope, keeping this off the advertised public
API of MLXLLM while making it usable outside the module:
  * FalconH1Configuration.hiddenSize / .numHiddenLayers / .rmsNormEps /
    .embeddingMultiplier
  * FalconH1DecoderLayer and its callAsFunction
  * FalconH1ModelInner.init, .embedTokens, .layers, .finalLayerNorm
  * FalconH1ModelInner.callAsFunction(inputsEmbeds:cache:) — new
  * FalconH1ModelInner.callAsFunction(_:mask:cache:) — was internal

`callAsFunction(inputsEmbeds:cache:)` is the seam; the token-id overload now
delegates to it, so the two paths cannot drift. No behaviour changes for
existing callers: FalconH1Model still embeds, runs the stack and applies the
head exactly as before.

`FalconH1ModelInner.init` is exposed because constructing `FalconH1Model` is not
an equivalent way in: the wrapper adds an `lm_head` whenever
`tie_word_embeddings` is false, which is the decoded default. A client bringing
its own head does not want that module and would otherwise have to account for
it when matching module keys against a checkpoint.

`FalconH1Model.model` and the mask helpers (`createSSMMask`,
`createAttentionMask`) were already public, and none of the layer's stored
property types are `private`, so unlike the Gemma 4 change nothing else had to
widen.

FalconH1EncoderAccessTests proves sufficiency the way the Gemma access tests do:
it drives the stack using ONLY the exposed surface, importing MLXLLM without
@testable and opting in via @_spi(FalconH1Encoder). It checks shape,
determinism, that the seam agrees with the token path, that the layer stack can
be driven a layer at a time to tap every hidden state, and that the stack
actually transforms its input — the last so the suite cannot pass on a seam that
returns its argument or runs zero layers.

One test earns its place beyond access checking. `sanitize()` folds
`embedding_multiplier` into `embed_tokens.weight`, which is right when the token
lookup is the only thing entering the stack but is a live trap for a composite-
embedding client: fold it and add unscaled contributions, and the lookup half is
scaled while the rest is not. Measured against the PyTorch reference for the
model above, that is 77% relative error on the embedding and 38% on the final
hidden state — while still producing plausible audio of the right length, so
listening does not catch it. testCompositeEmbeddingMultiplierEquivalence pins
`(raw + other) * m == folded + other * m` and asserts the unscaled-remainder
variant is observably different, both at the embedding and after the stack, so
the wrong form cannot quietly become the expected one.

Runs on a tiny randomly-initialized model; no weights are downloaded.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…ranches, one rows path

- TensorParallelSwitchLinear.forwards (public, read on every expert down
  forward) is removed: d-inference's test observes the gate projection
  instead and also checks every gather's sorted hint (false).
- tensorParallelCall's remaining loop serves only scoped batch decode rows:
  the byToken branches after the prompt chunk's early return are gone (count
  = B, row slices, axis 0); same ops for those rows.
- callAndWeightedReduceRows is weightedExpertSum(expertRowsByRow(...)): the
  identical graph, one rows path for the unsharded and the TP prompt chunk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…ll-shared-experts

Gemma 4 TP: one shared expert dispatch per registered prompt chunk (prefill 1.87×, same bytes)
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
The changelog keeps both entries (the parts entry now states the measured
best: 4 parts, +13 %). Two new lines over 100 columns are wrapped (a local
Part typealias).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
… hidden rows

The changelog keeps main's entries, then this branch's; fork.yaml merged
without conflict.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants