Skip to content

feat(qwen35): lift VLM SwiGLU MLP into MLXLMCommon + fix VLM prefill-sync (WS-C #8) - #180

Merged
ekryski merged 2 commits into
alphafrom
ek/wsc8-qwen35-consolidation
May 8, 2026
Merged

ekryski merged 2 commits into
alphafrom
ek/wsc8-qwen35-consolidation

Conversation

@ekryski

@ekryski ekryski commented May 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

Final WS-C consolidation: lift the VLM's standard separate-projection SwiGLU MLP (gate_proj / up_proj / down_proj) into a new public MLXLMCommon.Qwen35 namespace. Conservative scope on purpose — Qwen 3.5 is the trickiest of the eight families because of its hybrid GatedDeltaNet (GDN) + Attention stack and the LLM's substantial alpha-branch perf work.

Also fixes #181: the VLM's prepare was returning .logits(...) without flushing the pending prefill K/V + SSM-state writes, producing a token-loop on vision input. The bug surfaced during VLM smoke verification of this PR, but is pre-existing on alpha; folding the fix in here because the smoke run is what found it and the patch lives in the same file the typealias already touches.

Why the LLM doesn't share the lifted MLP

The LLM uses Qwen3NextMLP (defined in Libraries/MLXLLM/Models/Qwen3Next.swift), which is a fused gate_up_proj matmul producing 2 * intermediate outputs in a single linear. The LLM's Qwen35Model.sanitize merges incoming gate_proj + up_proj weights into the fused layout (see fuseGateUpWeights). Forcing the VLM onto this shape would change its weight-loading path; forcing the LLM onto the separate-projection class would silently regress decode. Both classes are now annotated to point at the file-level note that documents the deliberate split.

Other LLM-only alpha-branch perf work explicitly preserved

  • Fused GDN decode dispatch (Qwen35GatedDeltaNet decode S==1 path): fusedGatedDeltaUpdate saves 4–6 dispatches per layer per token, and .contiguous() safety on the conv-state slice prevents the 9 GB lazy-chain blow-up at long contexts. The VLM's GDN runs the slower ops path everywhere.
  • fullyBatchedForward on both Qwen35Attention and Qwen35GatedDeltaNet — LLM-only batched speculative-decoding paths.
  • Turbo KV boundary-layer skip in Qwen35TextModel.newCache(parameters:) — preserves first-N / last-N attention layers uncompressed.

What's shared

VLM prefill-sync fix (#181)

Same race we hit and fixed for Gemma 3 / Gemma 4 / Mistral 3 / LFM 2 / Qwen 3 VL (canonical fix #169), with one wrinkle: Qwen 3.5 is hybrid GDN+Attention, so its linear-attention layers store SSM conv + recurrent state via SSMStateCache, not the standard keys / values. The barrier works unmodified because SSMStateCache: ArraysCache already overrides innerState() to return its cache array (see Libraries/MLXLMCommon/KVCache.swift:1206) — so the same eval call covers both attention K/V and SSM state on the hybrid stack.

Future-work alignment with IMPLEMENTATION-PLAN.md

Verification (M1 Max 64GB)

  • swift build clean across LLM + VLM + Common targets.

  • swift test --filter ToolTests — 39/39 tests pass.

  • LLM smoke `mlx-community/Qwen3.5-0.8B-4bit`, kv=none, simple: 131.4 tok/s prefill, 162.8 tok/s decode, 314ms TTFT, 611MB peak. Coherent: "I am Qwen3.5. I can help with various tasks including:"

  • VLM smoke `mlx-community/Qwen3.5-27B-4bit`, kv=none, vision, dog image, prompt "Describe what you see in this image.":

    Run Prefill Decode TTFT Peak Output
    alpha (commit 7cc47e2) 48.3 tok/s 16.5 tok/s 12033ms 17.23GB "The!!!!!!!!!!!!!!!!!!!!!!!!!!!!…" (200-token "!" loop, fails dog)
    This branch, pre-Qwen3.5-27B-4bit VLM produces token-loop output on vision input (pre-existing on alpha) #181 fix 43.7 tok/s 16.6 tok/s 13254ms 17.24GB "The! </think> This is a full-body, eye-level photograph of a golden retriever…" (leading-token glitch)
    This branch + Qwen3.5-27B-4bit VLM produces token-loop output on vision input (pre-existing on alpha) #181 fix (HEAD) 44.6 tok/s 16.3 tok/s 12998ms 17.24GB "The user wants a description of the image. 1. Identify the main subject: It's a Golden Retriever dog. 2. Describe the dog's appearance…" — clean, dog ID matched

    The eval barrier is a one-time sync at end of prefill; perf delta vs pre-fix is within noise.

Test plan

  • `swift build` clean
  • `swift test --filter ToolTests` passes
  • `./scripts/benchmark.sh --model qwen35-0.8b --quant 4bit --kv none --method simple` produces coherent text output
  • `./scripts/benchmark.sh --model mlx-community/Qwen3.5-27B-4bit --kv none --method vision --vision-prompt "Describe what you see in this image." --vision-expect dog` produces coherent dog description (no token loop)

Closes the eighth and final WS-C consolidation entry under issue #168, plus #181.

Final WS-C consolidation: lift the VLM's standard separate-projection
SwiGLU MLP (`gate_proj` / `up_proj` / `down_proj`) into a new public
`MLXLMCommon.Qwen35` namespace. Conservative scope on purpose — Qwen
3.5 is the trickiest of the eight families because of its hybrid
GatedDeltaNet (GDN) + Attention stack and the LLM's substantial
alpha-branch perf work.

Why the LLM doesn't share the lifted MLP

The LLM uses `Qwen3NextMLP` (defined in
`Libraries/MLXLLM/Models/Qwen3Next.swift`), which is a fused
`gate_up_proj` matmul producing `2 * intermediate` outputs in a
single linear. The LLM's `Qwen35Model.sanitize` merges incoming
`gate_proj` + `up_proj` weights into the fused layout (see
`fuseGateUpWeights`). Forcing the VLM onto this shape would change
its weight-loading path; forcing the LLM onto the separate-projection
class would silently regress decode. Both classes are now annotated
to point at the file-level note that documents the deliberate split.

Other LLM-only alpha-branch perf work explicitly preserved
- Fused GDN decode dispatch (`Qwen35GatedDeltaNet` decode S==1 path):
  `fusedGatedDeltaUpdate` saves 4–6 dispatches per layer per token
  and `.contiguous()` safety on the conv-state slice prevents the
  9 GB lazy-chain blow-up at long contexts. The VLM's GDN runs the
  slower ops path everywhere.
- `fullyBatchedForward` on both `Qwen35Attention` and
  `Qwen35GatedDeltaNet` — LLM-only batched speculative-decoding paths.
- Turbo KV boundary-layer skip in `Qwen35TextModel.newCache(parameters:)`
  — preserves first-N / last-N attention layers uncompressed.

What's shared
- `MLXLMCommon.Qwen35.MLP` — standard SwiGLU MLP, used by the VLM's
  dense `DecoderLayer.mlp` and by its `SparseMoeBlock.sharedExpert`.
  Bit-identical to other Qwen-family MLPs (Qwen 2 / Qwen 3, lifted in
  PR #175 / #177); shipped under the `Qwen35.` prefix to keep the
  consolidation-namespace boundary per-family rather than relying on
  cross-family typealias chains.

Future-work alignment with `IMPLEMENTATION-PLAN.md`
- **Spec 020 phase 2 — `SSMStateCache: TapeReplayCache` + Metal
  kernel** (Tier 1). Both LLM (`Qwen35TextModel.newCache(parameters:)`)
  and VLM (`Qwen35Language.LanguageModel.makeCache`) instantiate
  `SSMStateCache()` inline for hybrid linear-attention layers. Phase 2
  will need to update both factories. The right time to lift them
  into a single `Qwen35.makeHybridCache(...)` helper here is when
  phase 2 lands — the helper signature is shaped by the new
  `TapeReplayCache` protocol, which doesn't exist yet.
- **Spec 028 — chunkwise WY GatedDeltaNet prefill** (Tier 4). The
  LLM's fused decode path is the natural target for the chunkwise
  variant; once spec 028 lands, the GDN class becomes a candidate
  for cross-target lift.
- **Issue #115 (QKV batched fusion)** + **issue #117 (RMSNorm + GEMV
  fusion)**. Same pattern as Qwen 3 (PR #177): once the LLM's
  `fullyBatchedForward` paths simplify to a single fused matmul, an
  `Attention` consolidation becomes safe.
- **Cross-family M-RoPE helper** (deferred from PR #177 / #178). The
  VLM's `Qwen35Language.RotaryEmbedding` is the same M-RoPE shape as
  Qwen3VL / GlmOcr; the helper landing for those unblocks the same
  kind of second-pass consolidation here.

Verification (M1 Max 64GB)
- `swift build` clean across LLM + VLM + Common targets.
- `swift test --filter ToolTests` — 39/39 tests pass (Qwen3.5 tool-call
  format + parser + processor coverage).
- LLM smoke (`mlx-community/Qwen3.5-0.8B-4bit`, kv=none, simple):
  131.4 tok/s prefill, 162.8 tok/s decode, 314ms TTFT, 611MB peak.
  Coherent output: "I am **Qwen3.5**. I can help with various tasks
  including:" — model self-identifies correctly, no token-loop.
- VLM weight-loading is shape-preserving: the typealias resolves to a
  class with identical `gate_proj` / `up_proj` / `down_proj`
  `@ModuleInfo` keys, so existing checkpoints load unchanged.

Closes the eighth and final WS-C consolidation entry under issue #168.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@github-actions github-actions Bot added the feature New feature (auto-applied from feat: prefix) label May 7, 2026
@ekryski ekryski added enhancement New feature or request and removed feature New feature (auto-applied from feat: prefix) labels May 8, 2026
@ekryski

ekryski commented May 8, 2026

Copy link
Copy Markdown
Owner Author

Follow-up: VLM smoke ran (revealed pre-existing alpha bug, not a regression)

The PR description originally listed the VLM smoke as deferred / "shape-preserving" only. Eric pushed back and asked for an actual VLM run — I owed it. Result:

`mlx-community/Qwen3.5-27B-4bit`, kv=none, vision, dog image, prompt "Describe what you see in this image.":

Branch Prefill Decode TTFT Peak Output
`ek/wsc8-qwen35-consolidation` (this PR) 43.7 tok/s 16.6 tok/s 13254ms 17.24GB "The!"
`alpha` (pre-PR, commit 7cc47e2) 48.3 tok/s 16.5 tok/s 12033ms 17.23GB "The!!!!!!!!!!!!!!…" (200-token "!" loop)

Conclusion: token-loop output is a pre-existing bug on alpha, not a regression from this PR. Performance numbers are within noise (small bench-to-bench variance, no consolidation overhead). The typealias is genuinely shape-preserving — the gate_proj / up_proj / down_proj @ModuleInfo keys resolve identically.

Filed #181 for the underlying Qwen3.5 VLM bug — suspected to be the same prefill-sync barrier issue we hit on Gemma 3 / Gemma 4 / Mistral 3 / LFM 2 / Qwen 3 VL (#169 pattern), with the wrinkle that Qwen3.5 is a hybrid GDN+Attention model so SSMStateCache.innerState() may need to expose the SSM tensors for the eval barrier to work.

I'm leaving this PR scoped to the consolidation. Fixing #181 is its own track.

…181

Qwen 3.5 VLM produced a token-loop ("The!!!!!!!!!" or a leading-token
glitch like "The! </think>") on vision input because `Qwen35.prepare`
returned `.logits(output)` without first synchronising the prefill
K/V and SSM-state writes pending in the GPU command buffer. The
iterator's first decode forward then read stale cache and produced
garbage logits.

This is the same race we hit and fixed for Gemma 3 / Gemma 4 /
Mistral 3 / LFM 2 / Qwen 3 VL — closed canonically as #169 — with
one wrinkle: Qwen 3.5 is a hybrid GDN+Attention model and its linear-
attention layers store SSM conv + recurrent state via `SSMStateCache`,
not the standard `keys` / `values`. The barrier still works
unmodified because `SSMStateCache: ArraysCache` already overrides
`innerState()` to return its `cache` array (see
`Libraries/MLXLMCommon/KVCache.swift:1206`), so the same eval call
covers both attention K/V and SSM state on the hybrid stack.

Verification (M1 Max 64GB)
- `mlx-community/Qwen3.5-27B-4bit`, kv=none, vision, dog image,
  prompt "Describe what you see in this image.":
  - **Pre-fix on this branch**: leading-token glitch
    `"The! </think>  This is a full-body, eye-level photograph of a
    golden retriever standing proudly on a smooth, gray, curved
    surface — likely a large stone or conc…"`
  - **alpha (commit 7cc47e2)**: full token-loop
    `"The!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"`
    (200-token "!", `--vision-expect dog` fails)
  - **This commit**: clean reasoning preamble + correct dog ID:
    `"The user wants a description of the image.  1.  Identify the
    main subject: It's a Golden Retriever dog. …"` — `--vision-expect
    dog` matches.
- Prefill / decode / TTFT / GPU peak all within ±5% of pre-fix
  numbers (44.6 / 16.3 tok/s / 12998ms / 17.24GB) — the eval barrier
  is a one-time sync at end of prefill, not a per-token cost.

Folding this into the WS-C #8 consolidation PR rather than splitting
it out: the smoke run that surfaced the bug was the verification step
for the consolidation, and the fix is a 15-line addition to the same
file the typealias already touches.

Closes #181.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@github-actions github-actions Bot added the feature New feature (auto-applied from feat: prefix) label May 8, 2026
@ekryski ekryski changed the title feat(qwen35): lift VLM SwiGLU MLP into MLXLMCommon namespace (WS-C #8) feat(qwen35): lift VLM SwiGLU MLP into MLXLMCommon + fix VLM prefill-sync (WS-C #8) May 8, 2026
@ekryski

ekryski commented May 8, 2026

Copy link
Copy Markdown
Owner Author

#181 fix folded in

The VLM token-loop bug surfaced during smoke verification of this PR is now fixed in the branch (commit 89bb1a0).

Root cause: Qwen35.prepare returned .logits(output) without flushing the prefill K/V + SSM-state writes. The iterator's first decode forward read stale cache → garbage logits. Same race as #169 (Gemma 3 / Gemma 4 / Mistral 3 / LFM 2 / Qwen 3 VL).

Fix: standard eval(cacheArrays + [output.logits]) barrier before returning. SSMStateCache: ArraysCache already exposes its conv + recurrent tensors via innerState() — no infrastructure changes needed for the hybrid stack.

Smoke result on dog image, Qwen3.5-27B-4bit, kv=none, vision:

  • Before fix: "The! </think> This is a full-body, eye-level photograph of a golden retriever…" (leading-token glitch)
  • After fix: "The user wants a description of the image. 1. Identify the main subject: It's a Golden Retriever dog. 2. Describe the dog's appearance…" ✅

Decode 16.3 tok/s, prefill 44.6 tok/s, TTFT 12998ms, peak 17.24GB — all within ±5% of pre-fix (the barrier is a one-time end-of-prefill sync, not per-token).

PR description updated with the new title and verification table; closing #181 once this merges.

@ekryski
ekryski merged commit e3561ce into alpha May 8, 2026
10 checks passed
@ekryski
ekryski deleted the ek/wsc8-qwen35-consolidation branch May 8, 2026 00:34
ekryski added a commit that referenced this pull request May 8, 2026
Continuation of WS-D — fixes the skill manifest that ships in tree at
\`skills/mlx-swift-lm/\` so coding agents that load it as context aren't
working off pre-spec-006 / pre-WS-C class names.

\`references/kv-cache.md\` (full rewrite, +267 / -98)
- Drops the obsolete \`KVCacheSimple\` / \`RotatingKVCache\` /
  \`QuantizedKVCache\` / \`MambaCache\` / \`ChunkedKVCache\` quick-reference
  table. Replaces it with the current concrete classes:
  \`StandardKVCache\` (with \`KVEviction.unbounded\` / \`.window(size:keep:)\`
  modes), \`AffineQuantizedKVCache\`, \`TurboQuantizedKVCache\`,
  \`ArraysCache\`, \`SSMStateCache\`, \`BatchedKVCache\` /
  \`BatchedMambaCache\` / \`BatchedHybridCache\`, \`PagedKVCache\`,
  \`CacheList\`.
- Adds the typed-surface section: \`KVStorage\`, \`KVEviction\`,
  \`KVStorageKind\`, \`KVCacheCompressionAlgorithm\` (and its scoped alias
  \`KVCache.CompressionAlgorithm\`) — including the full string-format
  parser examples (\`"turbo4v2"\`, \`"affine4g32"\`, etc.).
- Documents the \`makeAttentionCache(parameters:maxSize:keep:)\` and
  \`makeKVCache(scheme:eviction:)\` factories and the
  \`turboBoundarySkipSet(...)\` helper for hybrid-model first-N/last-N
  layer skipping.
- Drops \`maybeQuantizeKVCache(...)\`, \`cache.toQuantized(...)\`, and
  \`QuantizedKVCacheProtocol\` — all removed in spec 006 PRs 1–4. Adds
  a "Removed in spec 006" mapping table at the end.
- Notes the \`.turbo + .window\` precondition trap, the
  \`AffineQuantizedKVCache\` window-eviction-ignore, the
  \`isDonor\`-must-stay-raw rule, and the
  \`SSMStateCache.innerState()\`-via-\`ArraysCache\` plumbing that lets the
  VLM prefill-sync barrier cover hybrid models without infrastructure
  changes.

\`references/supported-models.md\` (full rewrite, +205 / -95)
- LLM type table: adds the 25+ \`model_type\`s missing from the previous
  version — \`gemma3_text\`, \`gemma3n\`, \`gemma4\`, \`gemma4_text\`,
  \`qwen3_next\`, \`qwen3_5\`, \`qwen3_5_moe\`, \`qwen3_5_text\`,
  \`deepseek_v4\`, \`glm4_moe\`, \`glm4_moe_lite\`, \`mistral3\`,
  \`lfm2_moe\`, \`gpt_oss\`, \`nemotron_h\`, \`smollm3\`, \`ernie4_5\`,
  \`exaone4\`, \`olmo2\`, \`olmo3\`, \`olmoe\`, \`bailing_moe\`, \`nanochat\`,
  \`falcon_h1\`, \`afmoe\`, \`jamba_3b\`, \`apertus\`, \`baichuan_m1\`,
  \`acereason\`, \`bitnet\`, \`minimax_m2\`, \`mimo_v2_flash\`. Cross-refs
  the consolidated \`MLXLMCommon.<Family>\` namespaces from PRs #172-#180.
- VLM type table: adds \`qwen3_5\`, \`qwen3_5_moe\`, \`gemma4\`,
  \`lfm2_vl\`, \`glm_ocr\`, \`pixtral\`, \`mistral3\`, \`fastvlm\`,
  \`llava_qwen2\`, \`smolvlm\`, \`idefics3\` — fixes typo on previous
  \`lfm2-vl\` (correct: \`lfm2_vl\`).
- \`LLMRegistry\` / \`VLMRegistry\` curated-config sections now sync with
  the actual in-tree entries (51 LLM / 21 VLM at HEAD).
- Adds the full \`ToolCallFormat\` enum (9 cases) — previous version
  was missing \`.mistral\` and \`.llama3\`.
- Notes #170 / #171 / #181 / #183 known gaps inline.

\`references/tool-calling.md\` (line edits, +35 / -8)
- Format table updated to 9 cases with example outputs for \`.mistral\`
  and \`.llama3\`.
- Adds an "Auto-detection" section explaining when explicit
  \`toolCallFormat\` overrides are needed (most chat templates auto-detect
  at load time from \`model_type\`+template combo).
- Adds a "Streaming behaviour" callout — \`ToolCallProcessor\` buffers
  partial output between wrapper / EOM-token boundaries and validates
  argument JSON before emitting the call.

\`references/model-porting.md\` (section additions, +59 / -12)
- "References to open" now points at \`documentation/developing/porting.md\`
  + \`documentation/llm/adding-a-model.md\` + \`documentation/vlm/adding-a-model.md\`
  (the new top-level docs from PR #182), not the deleted
  \`Documentation.docc\` paths.
- New "Use the shared \`MLXLMCommon.<Family>\` namespaces" section listing
  what's exposed per family (Gemma / Gemma3 / Gemma4 / LFM2 / Mistral3 /
  Qwen2 / Qwen3 / GLM4 / Qwen35) and the \`typealias MLP =
  MLXLMCommon.Family.MLP\` consumer pattern.
- New "VLMs: mandatory prefill-sync barrier" section. Documents the
  \`eval(cacheArrays + [output.logits])\` pattern (issue #169 / #181) as
  a required step in every VLM \`prepare(...)\`. Notes that
  \`SSMStateCache.innerState()\` covers hybrid GDN+Attention models.

\`references/embeddings.md\` (section rewrite, +20 / -25)
- Switches the basic + batch examples from the deprecated
  \`perform { model, tokenizer, pooling in }\` 3-arg form to the current
  \`perform { context in }\` form, which is the documented API on
  \`EmbedderModelContainer\` (the older form is
  \`@available(*, deprecated)\`).
- Adds a header callout naming the rename so readers searching for the
  old form land on the right pattern.

\`references/generation.md\` + \`references/wired-memory.md\` (line fixes)
- \`LLMModelFactory.shared.load(configuration:)\` was missing \`from:\` and
  \`using:\` parameters and would not compile. Fixed to pass a
  \`Downloader\` + \`TokenizerLoader\` per the actual factory signature
  (returns \`sending ModelContext\`).

\`SKILL.md\` (deprecated-patterns table additions)
- Expands the "If you see... use instead..." table with all spec-006
  KV-cache renames so an agent reading just the manifest catches the
  full set of v3 → v4 renames in one place. Adds the embedder
  \`perform { model, tokenizer, pooling in }\` deprecation alongside the
  LLM-side counterpart already noted.

\`README.md\` (light polish — separate commit-by-linter, kept in this
commit as part of the same docs theme)
- Trim the "Documentation" lead-in so \`Start here:\` reads as its own
  sentence.
- "Using an LLM" / "Adding an LLM" instead of "Using a model" / "Adding
  a model" so the column is parallel with the VLM column.

Verification
- \`grep -rn "<doc:" documentation/ skills/\` returns nothing.
- \`grep -rn "swiftpackageindex.com/ml-explore/mlx-swift-lm" Libraries/ skills/ README.md\` returns nothing.
- \`grep -rnE "kvBits|kvScheme|maybeQuantize|KVCacheSimple|RotatingKVCache|QuantizedKVCache\b|MambaCache" skills/\` only hits intentional migration callouts.
- \`grep -rn "Documentation.docc" skills/\` returns nothing.
- \`swift build -c release\` clean (no source touched).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
* style: format DiffusionGemmaVisionOracleTests.swift

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

* style: format DiffusionGemmaFactoryTests.swift

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

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

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

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

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

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

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

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

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

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

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

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

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

* style: format HistoricalWindowCheckpointTests.swift

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

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

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

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

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

* test: add test types and a unit test step without the Metal library

Add the Swift Testing tags unit, kernel, integration and reference in
Tests/MLXLMTests/TestTypeTags.swift, and the UnitTests parent suite
that gives the unit tag to the suites under Tests/MLXLMTests/Unit.

Fork Tests runs the unit tests before it builds the Metal library.
swift test cannot select tests by tag, so the step selects the
UnitTests suite by name. CONTRIBUTING.md describes the four types.

Add two example unit suites for JSONValue and ToolCall.execute.

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

* test: select the UnitTests suite of every test target

Other test targets, such as MLXLMServerTests, can then add unit tests
with their own TestTypeTags.swift and no change to the workflow.

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

* test: add unit tests for tool schemas, parser utilities, model factory and adapters

Cover the pure Swift parts of MLXLMCommon/Tool, ModelFactory.swift and
Adapters: JSON schema building, the parser type conversions, error
descriptions, configuration resolution with a recording downloader,
the free load functions on a folder without config.json, the adapter
type registry, the adapter factory, and LoRAConfiguration decoding.

No test uses MLX arrays, the network or model weights.

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

* test: apply review fixes to the test type convention

- Delete every cached *.metallib, not only mlx.metallib, before the
  build and before the cache is saved, so the unit step guard sees the
  same set of files.
- The guard prints the found libraries, then one ::error:: line.
- Add scripts/check-unit-test-files.sh: it fails when a Swift file
  under Tests/<Target>/Unit/ has no extension UnitTests. The unit step
  runs it, and scripts/test-run-nested-suite.sh proves it red on a bad
  file.
- CONTRIBUTING.md: folders for each test target, the sentence on files
  without a type tag, and the section Xcode integration tests.
- fork.yaml: unit tests are under Tests/<Target>/Unit/ for each test
  target; describe the new script.

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

* test: apply review fixes to the model factory and adapter tests

- Match the exact error configurationFileError("config.json",
  "org/absent", _) for the downloader load functions, and pin the
  download requests: 4 requests with the model patterns.
- Check that the registry gives an LLMModelFactory and a
  VLMModelFactory, in place of a count.
- A load without adapter_config.json only has to throw.

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

---------

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

Labels

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

Projects

None yet

1 participant