Skip to content

Merge main into alpha (v3 API + Gemma 4 fixes) — pre-tag for v3.32.0-alpha - #167

Merged
ekryski merged 19 commits into
alphafrom
ek/merge-main-into-alpha
May 6, 2026
Merged

ekryski merged 19 commits into
alphafrom
ek/merge-main-into-alpha

Conversation

@ekryski

@ekryski ekryski commented May 5, 2026 •

Copy link
Copy Markdown
Owner

Merges upstream main (currently at 3.31.3) into alpha so the fork can tag v3.32.0-alpha cleanly above mainline.

What lands from main

10 commits of v3 API + Gemma 4 + bug fixes that were missing from alpha:

Conflict resolution highlights

  • Package.swift: kept ekryski/mlx-swift@alpha pin (will swap to a versioned dep once v0.32.0-alpha is tagged on the sibling repo); kept swift-transformers (correctly transitive through #huggingFaceTokenizerLoader() macro expansion — bench target IS on the v3 API); adopted main's tighter swift-syntax 600..604 range.
  • README.md: kept main's leaner intro + Quick Start, appended alpha's fork-specific sections (Migrating to v3, Publishing a Release, Development Setup, Testing, Benchmarking, Configuration env vars).
  • LanguageModel.swift: adopted main's BaseLanguageModel split; moved alpha's sanitize(perLayerQuantization:) requirement up to BaseLanguageModel; kept supportsTurboQuantization on LanguageModel.
  • Gemma 4 LLM: kept alpha's standalone Gemma4TextModel pattern (factory registers `gemma4` and `gemma4_text` to the same standalone model). The wrapper-based pattern from main's Gemma4Model shim was tried and reverted — alpha's Gemma4TextModel.sanitize strips the language_model. prefix (designed for top-level use), which conflicts with the wrapper's prepend logic and produced `keyNotFound` on E2B load. Alpha's full Gemma 4 perf work is preserved (fused gate_up_proj, compile()-cached SharedMLP, symbolic .slidingWindow SDPA, MoE 26B-A4B).
  • Gemma 4 VLM: adopted main's 1929-line version (has the system-message + modality-order fixes from feat(gemma4): spec 041 phase 5 — affine donor compression via shared-reader quantised path #211 and v3 API embedder fixes). Alpha's GPU-sync sliding-mask perf work (perf(gemma3n): remove per-forward GPU→CPU sync in sliding-mask offset #53) is not carried over and should be re-applied as a follow-up PR.
  • Documentation.docc/upgrade.md → v2-to-v3-migration.md: renamed per fork convention; cross-references updated in Documentation.md, using.md, README.md.

New tests added

Tests/MLXLMTests/Gemma4ConfigurationTests.swift — locks down Gemma4TextConfiguration's dual decoding path (flat / nested-text_config) and rope_parameters decoding. Three cases, all pass in debug + release.

Verification

  • `swift build` clean, `make` clean, `swift build --build-tests` clean.
  • `swift test --skip-build -c release --skip Benchmarks` passes 152 swift-testing tests in 14 suites + the new XCTest cases.
  • Smoke matrix (real model loads via ./scripts/benchmark.sh --quick):
    • Qwen3.5 0.8B 4bit × {none, affine4, turbo4v2} × {1k, 4k, 32k} → 3/3 ✓ coherent output
    • Gemma 4 E2B 4bit × {none, affine4, turbo4v2} × {128, 1k, 4k, 32k} → 3/3 ✓ coherent output (this caught and fixed the wrapper-pattern regression)
    • Nemotron Cascade 2 30B-A3B (hybrid) × {none, affine4} × {1k, 32k} → 2/2 ✓ coherent output

Follow-up work tracked

Test plan

  • All existing tests still pass (152 + 3 new = 155).
  • Smoke matrix coherent on Qwen3.5, Gemma 4, Nemotron — all KV modes.
  • Reviewer eyes-on for the Gemma 4 architectural decision (kept alpha's standalone pattern vs. main's wrapper).
  • swift-transformers dep clarified: transitive through #huggingFaceTokenizerLoader() macro expansion (the bench target IS on v3 — uses #hubDownloader() + #huggingFaceTokenizerLoader(); the dep is needed because the macro expands to code that constructs a swift-transformers AutoTokenizer). Not legacy / not removable.

adrgrondin and others added 17 commits April 13, 2026 08:55
* Add gemma 4 model (text, vision, MoE)
=
* Add Gemma 4 text model support (E2B and E4B)

Port of gemma4.py and gemma4_text.py from mlx-lm. Adds support for
Gemma 4's text-only architecture including:
- Per-Layer Embeddings (PLE) with gated residual
- Shared KV cache across later layers
- Dual RoPE (proportional for full attention, default for sliding)
- ProportionalRoPE with partial_rotary_factor support
- Global head dimensions (512) for full-attention layers
- Double-wide MLP for KV-shared layers
- Logit softcapping
- LoRA support

Registers gemma4 and gemma4_text model types plus E2B/E4B 4-bit
model configurations.

* Fix Gemma 4 model IDs and EOS tokens

- Model IDs: use correct HuggingFace repo names (lowercase, no "-lm-")
  - gemma-4-E2B-it-lm-4bit → gemma-4-e2b-it-4bit
  - gemma-4-E4B-it-lm-4bit → gemma-4-e4b-it-4bit
- EOS token: <end_of_turn> (Gemma 3) → <turn|> (Gemma 4, token ID 106)

MLXArray.ones([1]) defaults to float32, which can cause dtype
promotion when multiplied with bfloat16/float16 model tensors.
Specify .float16 explicitly to avoid hidden AsType nodes.

* Fix weight key mapping for language_model property

Add @ModuleInfo(key: "language_model") so the property matches the
snake_case key in checkpoint weight files. Without this, weight loading
fails with keyNotFound for the language_model subtree.

Reported-by: john-rocky (PR #185 comment)

* Address review feedback: remove force unwraps, use shared ProportionalRoPE

- Make layerTypes non-optional in config (decode or derive from pattern)
- Replace vProj! force unwrap with if let binding
- Switch from local ProportionalRoPE to shared initializeRope() factory
- Remove 60-line local ProportionalRoPE class (now in RoPEUtils.swift)

---------

Co-authored-by: Stefan Geens <stefan.geens@gmail.com>
- see #189
- download jinja files in all paths
- macros use fully qualified type names
* v3 api embedder fixes

- replaces embedder loading, context and container with LLM variant
- this reuses all the code from LLM/VLM model type and model registries, along with the factory, download and load code

* fix warnings, clean up shape/dim
…and `CacheList` (#155)

* Prompt-cache restore for ArraysCache and CacheList
* Replace NOP with assertionFailure
* Add Gemma4PositionOffset

* add BatchPositionedKVCache stub
* Align Gemma4 messages with chat template

* Respect Gemma 4 modality order
The Qwen3-Next family uses the same XML tool call format as Qwen3.5
but wasn't recognized by ToolCallFormat.infer(), so tool calls were
silently lost.

Fixes #161.
* add upgrade docs, how to use, how to develop.
* add macro docs, reference for shortcut
* move some documentation from README to upgrade.  Prep README for 3.x release
BERT models crash when input exceeds maxPositionEmbeddings because
the position embedding table is fixed-size. Truncate with a warning
rather than crashing.

Expose maxPositionEmbeddings on the EmbeddingModel protocol (default
nil, non-breaking) so callers can check the limit and pre-truncate
or chunk as needed.

Fixes #62.
* Bump swift-syntax dependency
* Update and fix usage examples
Brings the upstream v3 work and ~10 commits of fixes onto alpha so the
fork can tag v3.32.0-alpha cleanly above main's v3.31.3.

Notable conflicts resolved:

- README.md: kept main's leaner intro + Quick Start, appended alpha's
  fork-specific sections (Migrating to v3 link, Publishing a Release,
  Development Setup, Testing, Benchmarking, Configuration env vars).
  Dropped alpha's "Breaking Changes" section since it duplicates the
  upgrade.md content.
- Documentation.docc/Documentation.md: merged article lists; pointed
  README at main's canonical upgrade.md and removed the temporary
  v2-to-v3-migration.md (which was a less complete alpha extraction).
  Kept alpha's publishing-a-release.md.
- Package.swift: kept ekryski/mlx-swift@alpha pin (will be bumped to a
  versioned dependency once mlx-swift v0.32.0-alpha is tagged), kept
  swift-transformers (still used by alpha's Benchmarks test target),
  adopted main's tighter swift-syntax range.
- LanguageModel.swift: adopted main's BaseLanguageModel split; moved
  alpha's sanitize(perLayerQuantization:) requirement up to
  BaseLanguageModel; kept supportsTurboQuantization on LanguageModel.
- LLMModelFactory: adopted main's split — gemma4 → Gemma4Model (HF
  text_config-aware shim), gemma4_text → Gemma4TextModel.
- Libraries/MLXLLM/Models/Gemma4.swift: adopted main's 107-line shim
  that wraps Gemma4TextModel for the nested HF config layout.
- Libraries/MLXLLM/Models/Gemma4Text.swift: NEW. Took alpha's full
  Gemma4 text impl (was previously in Gemma4.swift, with all alpha's
  perf work — fused gate_up_proj, compile()-cached SharedMLP,
  symbolic .slidingWindow SDPA mask, 26B-A4B MoE). Made
  vocabularySize a `var` so the Gemma4Configuration shim can
  propagate vocab_size into the text config.
- Libraries/MLXVLM/Models/Gemma4.swift: adopted main's version (1929
  lines, has the system message + modality order fixes from #211 and
  v3 API embedder fixes from #202). Alpha's GPU-sync perf work
  (#53 — sliding-mask offset) is NOT carried over and should be
  re-applied as a follow-up.
- Libraries/MLXVLM/Models/Gemma3.swift: kept alpha's argWhere-based
  GPU-side maskedScatter (perf path, avoids CPU readback).
- Libraries/MLXLLM/Models/Gemma3nText.swift: kept alpha's
  GPU-resident sliding-mask offset path.
- Added .slidingWindow case to gemma4AdjustAttentionMask switch in
  VLM/Gemma4.swift (alpha's mlx-swift exposes this case).

Build: `swift build` clean, `make` clean, `swift test --skip Benchmarks`
passes 152 tests in 14 suites.

Follow-up work (separate PRs after this merges):
- Re-apply alpha's #53 perf optimization (GPU-resident sliding-mask
  offset) to the new VLM/Gemma4.swift.
- Bring main's Gemma4PositionOffset / BatchPositionedKVCache stub
  (#212) into the new Gemma4Text.swift.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…to-v3-migration.md

Gemma4 fix:
- The Gemma 4 E2B/E4B smoke test caught a load-time keyNotFound error on
  every kv mode (`language_model.model.norm.weight` missing). Root cause:
  main's Gemma4Model wraps Gemma4TextModel via @ModuleInfo(key:
  "language_model"), expecting a wrapper-style sanitize that prepends
  `language_model.model.` — but alpha's Gemma4TextModel was designed as a
  top-level model whose sanitize *strips* the language_model. prefix.
  Combining the two paths made keys mismatch in both directions.
- Reverted to alpha's standalone pattern: register both "gemma4" and
  "gemma4_text" → Gemma4TextConfiguration / Gemma4TextModel.
- Removed Libraries/MLXLLM/Models/Gemma4Text.swift (was a copy of alpha's
  Gemma4.swift content with `vocabularySize` made mutable for the shim).
- Restored Libraries/MLXLLM/Models/Gemma4.swift to alpha's full 1207-line
  text impl (with all alpha's perf work intact: fused gate_up_proj,
  compile()-cached SharedMLP, symbolic .slidingWindow SDPA mask, MoE
  support for 26B-A4B).
- Confirmed: Gemma 4 E2B 4bit summarization passes 3/3 KV modes (none,
  affine4, turbo4v2) at ctx 128/1024/4096/32768 with coherent output.

Doc rename per user direction (keep our naming convention):
- `upgrade.md` → `v2-to-v3-migration.md`. Cross-references updated in
  Documentation.md and using.md. README link + URL anchors swapped.

README structure (user edits preserved):
- New `## Upgrading` parent section with `### Migrating to Version 3` as a
  subsection — gives a clean place to add `### Migrating to Version 4`
  later without churn.
- "Multiple KV compression algorithms" bullet added to the key features.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The standalone Gemma4TextModel pattern relies on Gemma4TextConfiguration
correctly decoding both HF config layouts:
  1. Flat — text fields at top level (E2B / E4B / 31B text-only).
  2. Nested — text fields wrapped in `text_config` (VLM-style).

The custom `init(from:)` handles both via a `text_config` probe before
falling back to top-level decoding. Recent merge work briefly broke this
(by introducing main's wrapper-style Gemma4Model shim that conflicts with
alpha's standalone pattern); these tests guard against future regressions
of the same shape and document the contract.

Three test cases:
- `testFlatConfigDecoding` — E2B/E4B JSON shape
- `testNestedTextConfigDecoding` — VLM JSON shape with vision_config
  sibling and explicit `num_global_key_value_heads`
- `testRopeParametersNested` — `rope_parameters.{sliding,full}_attention`
  decoding (the actual config format in real Gemma 4 weights)

All three pass in both debug and release builds.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…ward-port main fixes

Reverses the Gemma4 VLM merge direction: restore alpha's pre-merge
1538-line implementation (with all its perf work intact) as the base,
then forward-port the two small targeted fixes from main on top.

Why: main's 1929-line VLM Gemma4 (which the merge initially adopted) was
written independently from alpha's, with structurally different norm
classes (`Gemma4RMSNormZeroShift` + `Gemma4RMSNormNoScale` vs alpha's
fused-RMSNorm-RoPE path), no compiled QKV, and no GPU-resident
masked-scatter. Taking main's text-decoder wholesale would have lost:

- argWhere-based gemma4MaskedScatter (avoids `asArray(Bool.self)`
  full-mask CPU readback during VLM image-token splice — alpha's #53
  perf optimization)
- Compiled QKV for attention
- Fused gate_up_proj + compile()-cached SharedMLP forward
- FusedGateUpSwitchGLU MoE routing for 26B-A4B
- Symbolic .slidingWindow SDPA mask routing

Forward-ported from main on top of alpha's base:

- #211 (system message + modality order): added `Gemma4MessageGenerator`
  struct (system messages stay text-only; user/assistant messages emit
  images first, then videos, then text — matching the Gemma 4 chat
  template). `Gemma4Processor.prepare` now uses it instead of
  `Qwen2VLMessageGenerator()`.
- #202 (modern dim API): `flattenedSource.shape[0]` → `dim(0)` in
  `gemma4MaskedScatter`. Other #202 hunks (`maskArray.shape.last`
  cleanup, unused token-count diagnostics) didn't apply — alpha's
  attention-mask handling is structured differently and the processor
  never had those diagnostics.

Verification:
- `swift build` clean, `swift build --build-tests` clean.
- `swift test --skip Benchmarks` passes 152 tests in 14 suites.
- LLM-side Gemma 4 E2B smoke (3 KV modes × 4 contexts) coherent —
  exercises the same Gemma4TextConfiguration decode path.

Note: full image-input smoke for the VLM path (loading via
VLMModelFactory and running an image+prompt through Gemma4Processor)
would benefit from a new `--method vision` mode in InferenceBenchmark
that takes an image path. Scoped as a follow-up — see comment on the
PR for the proposed shape.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The earlier backport (commit 921e16b) restored alpha's pre-merge VLM
Gemma4 to preserve text-decoder perf work. End-to-end smoke against
the actual `mlx-community/gemma-4-e2b-it-4bit` weights revealed alpha's
VLM Gemma4 was broken vs the current HF config schema:

1. `Gemma4VisionConfiguration` required an `image_size` field that
   doesn't exist in the current Gemma 4 vision_config (HF uses
   `position_embedding_size` + `patch_size` instead).
2. Alpha's vision encoder was missing layer types that main implements
   (`Gemma4VisionRMSNorm`, `Gemma4ClippableLinear`, `Gemma4VisionPooler`,
   `Gemma4MultimodalEmbedder`) — alpha's perf work was on the LLM/text-
   decoder side; the VLM path was apparently never tested end-to-end
   against the official Gemma 4 weights.

Conclusion: alpha's VLM Gemma4 is not meaningfully "ahead" of main —
it's just unmaintained. Take main's full 1929-line VLM Gemma4 (with
the post-#180 fixes from #211 system-message + modality order and
#202 modern dim API). The text-decoder perf gap with the LLM-side
Gemma4.swift (fused gate_up_proj, compile()-cached SharedMLP,
FusedGateUpSwitchGLU, etc.) becomes a known follow-up — to be
addressed as part of the LLM/VLM common-code consolidation pass that
lifts shared text-decoder pieces into MLXLMCommon.

Single tweak vs main: added `.slidingWindow` to the
`gemma4AdjustAttentionMask` switch (alpha's mlx-swift exposes the
case; main was authored before it landed).

Vision bench harness — new method to validate VLM end-to-end on real
weights:

- `runGenerationBenchmark` gains `images: [URL] = []`, `chatMessages:
  [Chat.Message]? = nil`, and `useVLM: Bool = false`. When
  `chatMessages` is set, the function builds `UserInput(chat:)` so the
  model's `MessageGenerator` runs and expands images into the chat
  template's image-placeholder tokens (Gemma 4: 280 vision soft tokens
  per image). Pre-existing call sites (text-only) continue to use the
  `messages: [Message]` raw-dict path with no behavioural change.
- `loadOrCacheModel` gains `useVLM: Bool = false`. When true, dispatches
  through `VLMModelFactory.shared.loadContainer`. The cache key is
  salted with `:vlm` so the same model id can be cached separately for
  each modality (Gemma 4 E2B is loadable both ways).
- New `runVisionBenchmark` wires the bench-level method case to a
  default golden-retriever fixture at
  `Tests/Benchmarks/Resources/vlm-test-prompts/test-image1.jpeg`.
  Pass/fail is a substring check against the output (default keyword:
  "dog"; override via env vars).
- New `case "vision":` in the dispatch switch.

CLI surface (benchmark.sh):
- `--method vision` accepted.
- `--image <path>` overrides the default image (relative paths
  resolved against the repo root, where the bench runs).
- `--vision-prompt "..."` overrides the default prompt.
- `--vision-expect <keyword>` overrides the pass/fail keyword.

Verification:
- `swift build` clean, `make` clean.
- Vision smoke on Gemma 4 E2B 4bit + the checked-in golden-retriever
  image: 1/1 PASSED.
  - Prompt: "What animal is in this image? Answer in one word."
  - Output: "Dog"
  - Prepared 304 tokens (22 text + 280 image + 2 wrappers).
  - TTFT: 1445ms · Prefill: 211 tok/s · GPU peak: 3.94GB · KV cache: 7MB.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski

ekryski commented May 5, 2026 •

Copy link
Copy Markdown
Owner Author

Update — Gemma 4 VLM verified end-to-end via new vision bench

TL;DR: reverted today's earlier backport (alpha's perf-optimized VLM Gemma 4 turned out to be broken against the current HF config schema), took main's VLM Gemma 4 instead, added a vision-mode bench harness, smoke-tested with the checked-in golden-retriever fixture — model correctly answered "Dog".

What happened

The 1538-line "alpha VLM Gemma 4 + main fixes forward-ported" version that landed in commit 921e16b failed when actually loading mlx-community/gemma-4-e2b-it-4bit:

  1. Gemma4VisionConfiguration required an image_size field that doesn't exist in the current Gemma 4 vision_config. HF uses position_embedding_size + patch_size + pooling_kernel_size.
  2. The vision encoder layer types (Gemma4VisionRMSNorm, Gemma4ClippableLinear, Gemma4VisionPooler, Gemma4MultimodalEmbedder) didn't exist on alpha's side at all — alpha's perf work was on the LLM/text-decoder side, the VLM was apparently never tested end-to-end against the actual Gemma 4 weights.

So alpha's VLM wasn't really "ahead of main with perf optimizations" — it was unmaintained against the model it was supposed to support. The honest move is to take main's working version and treat the text-decoder perf reconciliation as a separate, durable task.

What landed in 582582a

New: vision bench harness (--method vision)

Added so we can actually verify Gemma 4 VLM (and any future VLM) end-to-end on real weights without leaving the bench harness:

  • runGenerationBenchmark gained images: [URL] = [], chatMessages: [Chat.Message]? = nil, useVLM: Bool = false. When chatMessages is set, the function builds UserInput(chat:) so the model's MessageGenerator runs and expands images into the chat-template's image-placeholder tokens (Gemma 4: 280 vision soft tokens per image).
  • Pre-existing call sites are untouched — the new params all default to "no change".
  • loadOrCacheModel gained useVLM: Bool. When true, dispatches through VLMModelFactory.shared.loadContainer. Cache key salted with :vlm so the same model id can cache separately for each modality.
  • benchmark.sh accepts --method vision plus optional --image <path>, --vision-prompt "...", --vision-expect <keyword> overrides.
  • Default fixture: Tests/Benchmarks/Resources/vlm-test-prompts/test-image1.jpeg (the golden retriever you pointed me at). Default prompt: "What animal is in this image? Answer in one word." Default pass-keyword: dog.

Verification

./scripts/benchmark.sh --model gemma4-e2b --method vision --quick --kv none →

Metric Value
Output "Dog"
Validation ✓ (output contains "dog")
Prompt tokens 304 (= 22 text + 280 image + 2 wrappers)
TTFT 1445 ms
Prefill 211 tok/s
GPU peak 3.94 GB
KV cache 7 MB

Follow-up

The text-decoder perf gap (alpha-side LLM Gemma 4 has fused gate_up_proj, compile()-cached SharedMLP, FusedGateUpSwitchGLU MoE routing, symbolic .slidingWindow SDPA mask, fused RMSNorm+RoPE; VLM-side does not) is now tracked as #168 — to be closed via the LLM/VLM common-code consolidation pass that lifts shared text-decoder pieces into MLXLMCommon.

Branch is now ready for the v3.32.0-alpha tag once you've reviewed.

…e metrics

Two issues with the initial vision-bench harness:

1. `maxTokens: 64` produced gen tok/s = 0 because Gemma 4 emits "Dog"
   then EOS for the original "Answer in one word" prompt — only one
   token of decode, not enough for a meaningful steady-state
   measurement.

2. Bumping to `maxTokens: 200` and asking the model to "describe in
   detail" exposed a sampling pathology: at the default temperature
   (0.6), Gemma 4 VLM collapses to a stream of `<pad>` tokens after
   the first generated token on open-ended vision prompts. The decode
   numbers come out clean (94.8 tok/s) but the output is garbage.
   Greedy decode on the same prompt + image produces a coherent
   description ("This is a photograph of a beautiful, medium-to-
   large-sized dog, likely a Golden Retriever, standing outdoors in
   front of a white house.") with effectively the same decode
   throughput.

Vision-as-smoke-test wants deterministic, reproducible, semantically
correct output. Force `MLX_BENCH_TEMPERATURE=0` for the duration of
`runVisionBenchmark` (with prior-value restore via `defer`), respecting
any explicit caller override. Also bump `maxTokens: 64 → 200` and
switch the default prompt to "Describe the image in English." (matches
`VLMRegistry.gemma4_E2B_it_4bit.defaultPrompt`, which Gemma 4 was
instruction-tuned on).

Final smoke run on Gemma 4 E2B 4bit, golden-retriever fixture, defaults:
- Output: "ThisThis is a photograph of a dog, likely a Golden Retriever,
  standing outdoors in front of a house."
- Validation: passes (output contains "dog")
- Prepared 298 tokens (16 text + 280 image + 2 wrappers)
- TTFT: 653 ms
- Prefill: 457.7 tok/s
- Generation: 101.6 tok/s (over 200 tokens — meaningful steady-state)
- GPU peak: 3.94 GB
- KV cache: 9 MB

Row lands in the standard markdown table with the
`<quant> / <kv> / vision` taxonomy via the existing BenchmarkWriter
path — no separate writer needed; `runVisionBenchmark` reuses
`runGenerationBenchmark`'s reporting.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski

ekryski commented May 6, 2026

Copy link
Copy Markdown
Owner Author

Just now need to rebase alpha and resolve conflicts with it after monkey patching things during the merge so we didn't bring in completely broken upstream changes. 🫠

ekryski added a commit that referenced this pull request May 6, 2026
…conflict

Pre-rebase the spec 006 PR 1 branch onto the merge branch so that once
PR #167 lands and alpha advances, this branch (and the rest of the spec
006 stack) merges cleanly without surprise conflicts at GitHub merge
time.

Conflict resolved in `Libraries/MLXLMCommon/KVCache.swift` —
`savePromptCache` cache-class-name discrimination:

- Main (#155, "Fix prompt-cache round-trip support for ArraysCache,
  MambaCache, and CacheList") introduced a private
  `cacheClassName(_:)` helper for this discrimination.
- This branch (PR 1) inlined the same logic in `savePromptCache` with a
  `StandardKVCache` + `eviction` switch, because spec 006's
  consolidation collapsed `KVCacheSimple` and `RotatingKVCache` into
  typealiases of `StandardKVCache` — main's `is RotatingKVCache` /
  `is KVCacheSimple` checks become ambiguous on the post-consolidation
  surface (both match every `StandardKVCache` instance).

Resolution: keep main's helper-function shape (cleaner; reusable),
but rewrite the body to use this branch's `StandardKVCache` +
`eviction` discrimination. Persistence still emits "RotatingKVCache"
for windowed eviction and "KVCache" for unbounded eviction, matching
the on-disk format the loader expects.

Auto-merged cleanly:
- `README.md` — main's leaner intro + this branch's KV-compression
  bullet kept; v2-to-v3 link picked up.
- `Tests/MLXLMTests/KVCacheTests.swift` — kept this branch's
  `@testable import MLXLMCommon` (needed for spec 006 internal-types
  tests) + main's new `tempURL()` helper.

Verification:
- `swift build` clean.
- `swift test --filter KVCacheTests` passes 47 tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request May 6, 2026
… 2 class names

Pre-rebase the PR 2 cleanup branch onto the now-merged PR 1 branch so
the spec 006 stack stays mergeable after PR #167 lands on alpha.

Conflicts resolved:

- `Libraries/MLXLMCommon/KVCache.swift` (savePromptCache + loadPromptCache):
  PR 2 inlined save/load class-name discrimination using the post-rename
  classes (`StandardKVCache` + eviction, `AffineQuantizedKVCache`,
  `SSMStateCache`); the merge brings in main's `cacheClassName(_:)` /
  `restoreCacheFromMetaState(...)` helper-function pattern. Resolution:
  keep main's helper-function pattern at the call sites, but rewrite
  the helper bodies to use PR 2's renamed types. On-disk strings stay
  as the legacy Python-compatible names ("KVCache", "RotatingKVCache",
  "QuantizedKVCache", "MambaCache") for cross-platform mlx-lm interop.
  `ChunkedKVCache` was deleted in PR 2; its `restoreCacheFromMetaState`
  case now throws a loud `KVCacheError` rather than silently returning
  the wrong cache shape.

- `Libraries/MLXVLM/Models/Gemma4.swift` (newCache for `gemma4_text` layer
  pattern): PR 2 had alpha's append-style fragment that conflicted with
  main's `.map`-based newCache. Took main's `.map` structure (matches
  the rest of main's Gemma4 VLM impl) but renamed
  `RotatingKVCache(maxSize:)` → `StandardKVCache(maxSize:)` to match
  PR 2's typealias removal. Also fixed `as? QuantizedKVCacheProtocol`
  → `as? AffineQuantizedKVCache` (the protocol was dropped in PR 2).

- `benchmarks/m1-max-64gb-2026-05-05.md`: append-only bench log; took
  the incoming side (PR 167's runs are the most recent and include the
  vision-bench rows we added in this branch chain).

- `Tests/MLXLMTests/KVCacheTests.swift`: main's #155 added round-trip
  tests using the legacy class names (`MambaCache()`, `KVCacheSimple()`,
  `RotatingKVCache(maxSize:)`, `as? MambaCache`, `as? KVCacheSimple`,
  `as? RotatingKVCache`). Renamed to PR 2's surface
  (`SSMStateCache()`, `StandardKVCache()`, `StandardKVCache(maxSize:)`,
  `as? SSMStateCache`, `as? StandardKVCache`). Test function names
  (`testRotatingKVCache...`) and `// MARK:` comments left as-is —
  they're descriptive labels, not type references.

Verification:
- `swift build` clean.
- `swift test --filter KVCacheTests` passes 47 tests.
- `swift test --skip Benchmarks` passes 164 tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request May 6, 2026
Pre-rebase the PR 3 self-transition branch onto the now-merged PR 2 so
the spec 006 stack stays mergeable after PR #167 lands on alpha.

No code-level conflicts — git auto-merged `KVCache.swift` and
`InferenceBenchmark.swift`. The forward-merge picks up:

- PR 2's KVCache helpers (`cacheClassName(_:)` /
  `restoreCacheFromMetaState(...)`) updated for the post-rename class
  names.
- The `Libraries/MLXVLM/Models/Gemma4.swift` revert to main's working
  version + the `as? AffineQuantizedKVCache` fix in the inlined
  attention path.
- The new `--method vision` bench harness (greedy default, 200 maxTokens,
  golden-retriever fixture, BenchmarkWriter row).

Verification:
- `swift build` clean.
- `swift test --filter KVCacheTests` passes 47 tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request May 6, 2026
Final pre-rebase in the spec 006 stack so the chain stays mergeable
after PR #167 lands on alpha.

Conflict resolved:

- `Libraries/MLXVLM/Models/Gemma4.swift` (Gemma4Text newCache):
  PR 4 introduced the `makeAttentionCache(parameters:maxSize:)` factory
  to handle the `.affine` compressionAlgorithm path (returns an
  `AffineQuantizedKVCache` instead of a plain `StandardKVCache` when
  set). The forward-merge brings PR 3's main-version newCache that
  uses direct `StandardKVCache(...)` construction with a
  `prefix(hiddenLayers - numKVSharedLayers)` filter (KV-shared layers
  reuse an earlier layer's cache and don't allocate their own).
  Resolution: keep PR 3's filter (correctness — KV-shared layers
  shouldn't double-allocate) AND PR 4's factory (correctness — affine
  quantization needs the right cache class up front). Compose them.

Auto-merged cleanly:
- `Libraries/MLXLLM/Models/MiMoV2Flash.swift`
- `Libraries/MLXLMCommon/KVCache.swift`
- `Libraries/MLXLMCommon/LanguageModel.swift`
- `Libraries/MLXVLM/Models/LFM2VL.swift`
- `Tests/Benchmarks/InferenceBenchmark.swift`

Bench log (`benchmarks/m1-max-64gb-2026-05-05.md`): took the incoming
side (PR 3's runs are the most recent in the chain).

Verification on the final branch:
- `swift build` clean.
- `make` clean (metallib copied to test bundle).
- `swift test --skip Benchmarks` passes 164 tests in 14 suites.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

@ekryski ekryski left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Reviewed manually and looks good.

Three small fixes from your PR 167 review pass:

1. **Drop `benchmarks/m1-max-64gb-2026-05-05.md` from the PR.** This
   file accumulated bench rows during the merge / Gemma 4 / vision-
   harness smoke runs. It's a useful local artifact but isn't merge-
   relevant code. `git rm --cached` removes it from the index;
   `.gitignore` keeps it from re-tracking on subsequent local bench
   runs while leaving the file on disk. Other dated bench logs in
   `benchmarks/` stay tracked — only this PR's smoke artifact is
   excluded.

2. **Modality-order coverage for `Gemma4MessageGenerator`.** Main's
   #211 added `Gemma4MessageGenerator` and two tests
   (`testGemma4ConversionText`, `testGemma4ConversionImage`) that cover
   text-only and single-image cases. The #211 fix was specifically
   about modality *ordering* (images first, then videos, then text)
   and *system-role text-only* enforcement, but neither of those
   contracts had a regression test. Added two:

   - `testGemma4ConversionImagesAndVideosOrdering` — multi-image
     + video + text user message must serialize as
     image → image → video → text (matching the Gemma 4 chat
     template's expected slot order).
   - `testGemma4ConversionSystemRoleStaysTextEvenWithImages` — even
     if a caller attaches images to a system message, the generator
     must drop them. Image placeholders in the system slot break the
     chat template silently; this locks the contract loud.

   `swift test --filter UserInputTests` passes 10 tests
   (8 existing + 2 new).

Note: the third PR-review item ("swift-transformers retention" callout
in the PR test plan) is being clarified separately in the PR
description — the dep is correct (transitive through the
`#huggingFaceTokenizerLoader()` macro expansion), not legacy code.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski
ekryski merged commit 45c5df2 into alpha May 6, 2026
4 checks passed
@ekryski
ekryski deleted the ek/merge-main-into-alpha branch May 6, 2026 01:51
TheTom pushed a commit to TheTom/mlx-swift-lm that referenced this pull request Jun 11, 2026
…i#167)

The tools schema was passed to the chat template (so the model knew
about the tools) but never forwarded to the ToolCallProcessor that
parses the response. Without it, array and other non-string parameter
types in XML tool call formats (Qwen 3.5) were returned as raw strings
instead of being decoded to their proper types.

Fixes ekryski#159.
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
* ci: build the fork and run its Metal test suites

Add the Fork Tests workflow. It builds the package on a macos-26
runner, builds the full MLX Metal library with cmake, copies it next
to the test binaries, and runs six CBv2 paged suites one step each.
A suite step fails when the suite executes zero tests or skips a test.

Port the scripts from d-inference and add them to fork.yaml.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* ci: remove the empty GPU listing from Fork Tests

system_profiler SPDisplaysDataType prints nothing on the hosted
macos-26 VM. The CPU, memory and disk lines stay.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* ci: select the newest release of Xcode 26 in Fork Tests

Pick the newest Xcode_26.x app whose name is only a version number.
Beta and release candidate apps are left out, so a new beta on the
runner image cannot change CI without a pull request. The step still
fails when the selected Swift is older than 6.3.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* ci: correct the Metal library notes in build-metallib.sh

swift build makes no Metal library. The pinned mlx-swift excludes the
MLX kernel sources and nojit_kernels.cpp from Cmlx, so SwiftPM builds
MLX in JIT mode, and every MLX operation traps without a staged
mlx.metallib. The partial 459-symbol library comes from xcodebuild,
which this workflow does not use.

State that the 10,000-symbol floor rejects a JIT-mode or incomplete
cmake build.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* ci: key the SwiftPM cache on the commit and clean it before saving

End the cache key with the commit SHA, as d-inference does, so each
push to main saves a new entry. The prefix restore key still restores
the newest entry for the same Xcode.

Before the save, delete the staged mlx.metallib copies and the
coverage data, so the cache keeps only SwiftPM output.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* ci: fix wording in the Fork Tests files

- run-nested-suite.sh: the suites need no model weights, but one test
  needs DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST=1, which the caller sets.
- fork-tests.yml: runs on main are not cancelled once they start.
- Say "self-contained" instead of "hermetic" in the workflow and in
  fork.yaml.
- fork.yaml: write the Fork Tests paragraph as one sentence per line,
  so later pull requests can add a sentence without touching the same
  lines.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test: hold the hog in the waiting-queue backstop test

testWaitingQueueBackstopEmitsCanonicalQueueFullMarker polled every
5 ms for the hog request to show as running, but the hog finished its
60 scripted tokens in milliseconds. A late poll missed the window and
the test failed after 10 s (Fork Tests run 36182132297, attempt 1).

Set eventBufferCapacity to 4, as testDuplicateSubmitThrowsAndFirst-
StreamStillDelivers does. The unread hog stream hits backpressure, so
the hog pauses with its slot retained until the test drains it. The
wait now also requires the hog to be paused. Only this test changes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* style: format CBv2SchedulerLoopTests.swift

Run swift format format with .swift-format on the whole file, so the
format check of ekryski#160 passes. It changes four places outside the
backstop test: two nested CBv2Request calls and three comment
alignments in CBv2EngineLoopConfig arguments. No code changes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* ci: run the scheduler loop suite through the no-skip runner

Add a Fork Tests step that runs CBv2SchedulerLoopTests with
scripts/run-nested-suite.sh, after the six Metal suites. The step
fails when the class executes zero tests or skips a test, so CI runs
the backstop fix instead of only compiling it.

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

* test: make the capacity-loser scheduler test deterministic

testCapacityLoserIsRequeuedNotErrored minted its two requests inside
two async let children. Both children increment the unsynchronized
CBv2SchedFixtures.nextID at the same time, so both requests can get
the same id. The second submit then throws duplicateRequestID. XCTest
reports the last error thrown during the test, which is the
CancellationError from the cbv2SchedCollect watchdog sleep, so the
failure showed as "CancellationError" at CBv2SchedulerTestSupport.swift:533.

The test now mints and submits both requests on its own task. It also
holds the step loop until both requests wait, so both requests compete
for the single KV slot in the same step and the requeue always happens.

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

* test: release the step gate if a submit throws

A defer releases suspendStepExecutionAtCountForTesting on the engine
queue, so a throwing submit in testCapacityLoserIsRequeuedNotErrored
cannot leave the step loop held.

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

* test: mint fixture request ids under a lock

CBv2SchedFixtures.request incremented a static counter and read it
again. Concurrent callers could get the same id. An NSLock now does the
increment and the read in one step. The comment no longer says that ids
come from the main thread.

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

* test: drop the stale id race from the capacity-loser comment

The fixture now mints ids under a lock, so minting in two async let
children no longer races. The comment keeps the reason that stays true:
the test holds the step loop so both requests wait. nextID is now
private, so no caller can bypass the lock.

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

* test: change MTP driver state on the engine queue in forcedPolicy

The test "policy is forced to serial B1 depth one" called
restoreAssistantState, materializedAssistantBytes and invalidateCarry
on the driver from the test task. That state is engine-thread confined.
The engine loop starts with an engineStep on its queue, and
publishGauges reads the same dictionary. When the two overlap, the
engine queue crashes with EXC_BAD_ACCESS in materializedAssistantBytes.
Parallel Swift Testing runs make the overlap more likely.

The test now makes these calls in onEngineQueueSync. The assertions
do not change.

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

* test: evaluate Lightning MTP weights before the first draft

Three Qwen4ExpLightningMTPTests tests drafted with unevaluated random
weights. The compiled decode trace in Qwen4ExpGatedResidual holds the
weights as constants, and MLX compile walks the lazy graph of each
constant recursively. Lazy random weights hang off the process-wide
MLXRandom key chain. When many tests draw keys and none evaluates them,
the chain gets deep, and the walk overflowed the 512 KiB stack of the
test's cooperative thread (SIGBUS at the stack guard, compile_dfs about
815 levels deep).

The tests now evaluate the target and the assistant after they build
them, as the production path does after it loads weights. The
assertions do not change.

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

* ci: run the SDK and MTP suites on pull requests (ekryski#161)

* ci: run the SDK and MTP suites in Fork Tests

Add one step for each of the 15 SDK suites that the d-inference
Provider Tests job runs. Each step uses scripts/run-nested-suite.sh,
so a suite fails when it executes zero tests or skips a test.

Add a last step that runs swift test --skip-build over the whole
package once, without the zero-test and skip checks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* ci: give NemotronH35BackendParityTests 20 minutes

The suite took 5 min 20 s on the hosted macos-26 runner, half of
its 10-minute limit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* ci: report line coverage from the whole-package test run

Build with --enable-code-coverage and run the last test step with
--enable-code-coverage. Then run llvm-cov report on the test bundle
without the test sources and .build, write the TOTAL line coverage to
the step summary, and upload the full report as an artifact.
There is no minimum.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* ci: check the whole-package test run and show its failures

- The whole-package step now fails when XCTest or Swift Testing ran
  zero tests.
- After a failure, it prints each XCTest "error:" line and each Swift
  Testing "recorded an issue" line as an error annotation, so the
  failing tests show in the job summary.
- Pin actions/upload-artifact to v7.0.1 (Node 24).
- Say that every suite step runs the instrumented binaries and that
  only the last step collects and reports coverage.
- fork.yaml: add one sentence about the whole-package run and the
  coverage report.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* ci: run the whole-package pass serially and annotate crashes

Run the whole-package swift test pass with --no-parallel, as
d-inference scripts/run-provider-tests.sh does: Swift Testing
otherwise overlaps suites that share process-wide MLX state and
cooperative-executor capacity, and a serial pass makes a crash
attributable to one test. Raise the step limit to 120 minutes.

After a failure, annotate "error:", "recorded an issue", "signal 11",
"Segmentation fault" and "Fatal error" also when they start in the
middle of a line. Run 36284732312 crashed with signal 11 mid-line and
got no annotation.

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

* ci: upload crash reports when the whole-package pass fails

A crash of the Swift Testing helper printed only the signal in run
36284732312. This step uploads ~/Library/Logs/DiagnosticReports when the
step fails, so the backtrace of each thread is available.

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.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.

7 participants