Skip to content

feat: re-enable MLXServer for alpha - #4

Closed
TheTom wants to merge 56 commits into
mainfrom
pr/mlx-server-alpha
Closed

TheTom wants to merge 56 commits into
mainfrom
pr/mlx-server-alpha

Conversation

@TheTom

@TheTom TheTom commented Apr 18, 2026

Copy link
Copy Markdown
Owner

Summary

  • Register MLXServer as executable product/target in Package.swift
  • Update loadContainer to use macro-based HuggingFace integration (from:/using: params)
  • Add @unchecked Sendable to ModelContext for actor boundary crossing
  • Swift 5 language mode for server target (avoids strict concurrency errors in pre-existing server code)
  • Add --kv flag for TurboQuant KV cache scheme selection (e.g. --kv turbo8v4)
  • Disable thinking mode for chat completions (enable_thinking: false)

Usage

swift build -c release --product MLXServer
.build/release/MLXServer --model mlx-community/Qwen3.5-35B-A3B-4bit --kv turbo8v4 --port 8080

Test plan

  • swift build -c release --product MLXServer — clean build
  • Server starts, loads model, serves /health, /v1/models, /v1/chat/completions
  • --kv turbo8v4 flows through to cache creation and generate params
  • Verify no regression on existing library targets

Base: alpha (via origin). PR targets fork/main for visibility.

🤖 Generated with Claude Code

DePasqualeOrg and others added 30 commits April 9, 2026 09:27
Support multiple parallel tool calls and buffering for Llama 3

Llama 3 natively supports tool calling through an ipython environment which
generates arrays for multiple parallel tool invocations. Depending on the
model size and prompt, it generates either a JSON list of function objects
or a python-style array of function calls.

- Sets `startTag` to `<|python_tag|>` to ensure `ToolCallProcessor`
  correctly buffers tool output without leaking it to the streaming UI.
- Upgrades `Llama3ToolCallParser` to parse multiple parallel tool calls
  from JSON array payloads `[{"name": ...}]` during `parseEOS`.
- Upgrades `PythonicToolCallParser` to extract multiple sequential
  pythonic function calls `[func1(), func2()]` via `parseEOS`.
- Refactors `PythonicToolCallParser` to use modern high-performance
  Swift 5.7+ Regex literals instead of legacy NSRegularExpression.
- Add integration unit tests for both parsers to verify multi-call arrays.
…models (ekryski#142)

* Add Mistral3, Nemotron, and Qwen3.5 tool call integration test helpers
* Add MLXLMIntegrationTests
* Update documentation

* Use actual asserts in IntegrationTestHelpers.swift

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Avoid converting decoded JSON arguments through Any before constructing ToolCall.Function.\n\nThis fixes Swift 6 Sendable compilation errors in Llama3ToolCallParser during Release iOS builds.\n\nWritten by Codex.
…atch

- Add .contiguous() to SSM conv state outputs across 6 hybrid models
  (prevents non-contiguous Metal buffer reads in subsequent ops)
- Fix prefill loop to process all tokens except last (matches Python)
- Add Memory.clearCache() after prefill to release activation buffers
- Fix fp32 promotion in Gemma3n PLE scalars (bare Float, not MLXArray)
- Fix NemotronH RMSNormGated to use MLXArray.mlxNone (matches Python weight=None)
- Add isPrefill per-layer eval guard in NemotronH backbone
- Fix segsum bf16 dtype match to avoid fp32 promotion

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
fix: base model fixes — contiguous, prefill loop, SSM
- Add peek() protocol method for non-mutating K/V access (Gemma 4 shared KV)
- Add memoryBytes property for cache memory tracking
- Add eval() after resize to break lazy computation chains
- Add DType.bytesPerElement helper

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
feat: KV cache — peek(), memoryBytes, eval barriers
- Add cache: parameter to TokenIterator and ModelContainer.generate()
- Add kvScheme to GenerateParameters for KV cache quantization
- Add additionalProcessors to GenerateParameters with CompositeLogitProcessor
- Add ModelContainer.generateTokens() with cache: parameter
- Add ModelContainer.newCache() for pre-allocated cache creation
- Add WiredMemoryUtils.estimatedTicket() and estimateBudget() for static memory estimation
- Add WiredMemoryUtils.ticket(from:) for measurement-based ticket creation
- Add public init on WiredMemoryMeasurement

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
feat: generation pipeline — cache, kvScheme, thinking, perplexity
Full Gemma 4 text architecture with:
- Sliding + full attention with configurable window pattern
- KV sharing across layers (shared layers reuse donor K/V via peek())
- Per-Layer Embeddings (PLE) with gated projection
- ProportionalRoPE for full-attention layers
- Compiled GEGLU activation
- Attention logit softcapping
- RotatingKVCache.peek() for KV sharing support

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Full Gemma 4 text architecture with:
- Sliding + full attention with configurable window pattern
- KV sharing across layers (shared layers reuse donor K/V via peek())
- Per-Layer Embeddings (PLE) with gated projection
- ProportionalRoPE for full-attention layers
- Compiled GEGLU activation
- Attention logit softcapping
- RotatingKVCache.peek() for KV sharing support

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Gemma 4 vision-language model with:
- SigLIP-based vision encoder
- Multi-modal soft-token projection
- Image input processing via Gemma4Processor

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
MoE architecture with 62 layers, 256 local experts, 8 active per token.
Supports quantized attention with GQA (48 heads, 8 KV heads).

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…he bounds

Pure attention model override: 2048+ token prefill chunks (vs default 512)
reduces TTFT. Full-attention KV cache now respects maxKVSize parameter to
prevent unbounded growth in multi-turn sessions.

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Adds Qwen3.5 model family with GatedDeltaNet layers:
- Gated linear attention with delta rule
- Hybrid SSM + sliding window attention
- Short convolution state management
- MoE support via SwitchLayers

Key improvements from tom-eric branch:
- Fix bf16 dtype promotion in computeGatedDeltaG (no fp32 roundtrip)
- Add eval barriers in gatedDeltaOps to bound prefill memory
- Use ops fallback for gatedDeltaUpdate (Metal kernel has T>1 bug)
- Add .contiguous() on conv cache to prevent 9GB memory leak
- Force dtype per-layer to prevent bf16->fp32 promotion in lazy graph
- Per-layer eval during prefill to cap activation memory
- RotatingKVCache support for attention layers

Deferred: fused Metal kernels, FusedGateUpSwitchGLU, quadratic attention

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
WHT-based KV cache compression with Lloyd-Max quantization:
- TurboQuantKVCache: drop-in replacement for KVCacheSimple
- Metal kernels for compressed attention (turbo SDPA)
- Supports 2-bit and 4-bit KV quantization
- toTurboQuantized() conversion on KVCacheSimple
- AttentionUtils dispatch for turbo KV scheme

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Standalone HTTP server with OpenAI-compatible chat completion API.
Supports model loading, streaming generation, and memory management.

Features:
- OpenAI-compatible /v1/chat/completions and /v1/completions
- Multi-session prompt cache with LCP prefix matching
- Parallel inference slots with prefill serialization
- Thinking model support (reasoning_content in responses)
- Tool call parsing (MiniMax XML, generic XML, <function=> formats)
- macOS memory pressure monitoring with automatic cache eviction
- CORS support, /health, /metrics, /slots endpoints

Note: Package.swift needs MLXServer executable target added separately.

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- InferenceBenchmark with [ENV] build checks (NAX, template)
- Model registry for Gemma 4, Qwen3.5, MiniMax, GPT-OSS, etc.
- BenchmarkWriter for markdown output
- benchmark.sh CLI with --model, --method, --context, --kv flags
- MLX_BENCH_PROMPT and MLX_BENCH_MAX_TOKENS env var support

Note: Package.swift needs Benchmarks test target added separately.

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add MambaCache snapshot/restore for hybrid model speculative decoding,
acceptance rate tracking metrics, and per-step cache quantization
during draft token generation.

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
feat: Gemma 4 text — KV sharing, PLE, sliding window
feat: Gemma 4 VLM — SigLIP vision encoder
feat: TurboQuant KV cache compression
C++ prefill bridge bypasses Swift MLXArray/ARC overhead for 2-3x
faster prefill. Uses dlopen to avoid SPM LTO miscompilation.

- prefill_bridge_gemma.cpp: Gemma 4 forward pass (15 non-shared layers)
- prefill_bridge_qwen.cpp: Qwen MoE forward pass
- generic_prefill.cpp: Multi-architecture bridge
- GemmaPrefillBridge.swift: dlopen/dlsym bridge for Gemma 4
- QwenPrefillBridge.swift: Swift-side Qwen bridge integration
- build-prefill-bridge.sh: compile bridge dylib with clang++ -O3

Opt-in via NATIVE_PREFILL=1. Bridge shares host MLX allocator
via -undefined dynamic_lookup.

Note: Package.swift needs NativePrefillBridge target added separately.

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
feat: native C++ prefill bridge (dlopen)
TheTom and others added 24 commits April 16, 2026 00:26
- GemmaPrefillBridge: @unchecked Sendable + nonisolated(unsafe) on shared
  (fixes Swift 6 strict concurrency error in alpha)
- InferenceBenchmark: load prompts from Resources/llm-test-prompts/
  (files live in subdirectory, not Resources/ directly)

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…fixes

fix: GemmaPrefillBridge Sendable + benchmark resource path
Restores end-to-end Gemma 4 correctness + 2.5x prefill speedup on alpha.

Root causes (three separate bugs):
1. Gemma4Text.swift was a stripped-down port missing ~400 lines of prefill
   logic (chunked prefill, asyncEval CPU-GPU overlap, prefillMode that skips
   shared layers during prefill, KV sharing via lastReturnedKeys/Values).
2. Evaluate.swift used asyncEval for first decode token, triggering Gemma 4
   pad-token bug (second forward pass starts before prefill KV writes commit).
3. InferenceBenchmark.swift used a naive SimpleJSONTokenizer (whitespace split)
   instead of real BPE — all token IDs were garbage, decode output was random.

Changes:
- Libraries/MLXLLM/Models/Gemma4.swift: replace Gemma4Text.swift with full
  working port (uses SwitchGLU instead of FusedGateUpSwitchGLU which alpha
  doesn't have). Inlines GemmaPrefillBridge with @unchecked Sendable.
- Libraries/MLXLMCommon/KVCache.swift: add lastReturnedKeys/Values to
  KVCacheSimple and RotatingKVCache (set in update()) — needed for Gemma 4
  KV sharing to avoid redundant peek() slice ops.
- Libraries/MLXLMCommon/Evaluate.swift: sync-eval first decode token
  (eval(y.tokens) instead of asyncEval) — fixes Gemma 4 pad-token bug.
- Package.swift: add swift-transformers 1.3.0 dep for real BPE tokenization.
- Tests/Benchmarks/InferenceBenchmark.swift: replace SimpleJSONTokenizer
  with TokenizerBridge wrapping swift-transformers' AutoTokenizer. Qualify
  ToolSpec/Message to MLXLMCommon to resolve namespace collision.

Gemma 4 E2B performance (M5 Max, NAX enabled):
  128 ctx:  5,583 prefill / 199.6 decode
  256 ctx: 11,715 / 198.1
  512 ctx: 17,376 / 194.5
 1024 ctx: 20,004 / 195.7   <- peak prefill (2.5x baseline)
 2048 ctx: 17,193 / 193.9
 4096 ctx: 13,773 / 186.5
 8192 ctx: 13,353 / 179.1

Coherent output verified at 128, 1024, and 8192 contexts.

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Followup to PR ekryski#44. Two independent fixes for models that were still
broken after the coherence work landed.

## Gemma 4 26B A4B MoE

Root cause: mixed-precision quantization (shared MLP + router are 8-bit,
rest is 4-bit) encoded as per-layer overrides keyed under the VLM-style
path `language_model.model.layers.N.mlp.gate_proj`. The text-only
`Gemma4TextModel` strips `language_model.` from weights but not from the
per-layer quantization dict, so `quantize()` missed the overrides and
built the shared MLP Linears with the default 4-bit group size, producing
shape mismatches like:

    mismatchedSize(down_proj.weight
        expected [2816, 264]
        actual   [2816, 528])

Fix:
- Add `FusedGateUpSwitchGLU` to MLXLMCommon/SwitchLayers.swift — 26B MoE
  ships a single fused `gate_up_proj` weight `[E, 2*H, D]` instead of
  separate `gate_proj`/`up_proj`, matching how the sanitize step already
  concatenates the two into `gate_up_proj`.
- Swap `Gemma4TransformerBlock.experts` from `SwitchGLU` to
  `FusedGateUpSwitchGLU` so the model's Module tree matches the fused
  weight layout.
- Introduce a `sanitize(perLayerQuantization:)` hook on `LanguageModel`
  (default: identity) and wire it through `Load.swift`. Override it in
  `Gemma4TextModel` to strip the `language_model.` prefix from per-layer
  keys, restoring the mixed-precision overrides for the shared MLP and
  router when the text model is loaded stand-alone.

Verified: `mlx-community/gemma-4-26b-a4b-4bit` now loads and generates
coherent output (2+2=4, capital-of-France=Paris), 220 tok/s prefill,
56 tok/s decode at 128 ctx on M5 Max.

## Qwen3.5 GDN decode

Port the fused GatedDeltaNet recurrence back from the moe branch: the
alpha cleanup dropped the `MLXFast.gatedDeltaStepFused` dispatch and
went back to pure ops, which spends ~4–6 separate dispatches per GDN
layer at decode. The fused kernel absorbs rmsNorm(q), rmsNorm(k),
sigmoid(b)→beta, and g = exp(-exp(aLog)*softplus(a+dtBias)) into a
single Metal dispatch and is correct at T=1.

- Add `fusedGatedDeltaUpdate(qRaw, kRaw, v, a, b, aLog, dtBias, …)` in
  GatedDelta.swift that calls `MLXFast.gatedDeltaStepFused`.
- In `Qwen35.swift`, use the fused path at T=1 decode and keep the
  ops-based prefill (pre-computed norms) for T>1, matching the moe
  branch's split. Fused at prefill regresses speed because of register
  pressure; the framework non-fused kernel has a correctness bug at
  T>1, so ops remain the safe prefill path.

Verified: `Qwen3.5-2B-4bit` and `Qwen3.5-9B-4bit` both generate
coherent text; 2B decode 283 tok/s, 9B decode 96 tok/s.

## Regression check

Gemma 4 E2B (uniform 4-bit, no per-layer overrides, not GDN) still
loads and generates cleanly — 1077 tok/s prefill, 202 tok/s decode —
confirming the prefix-strip is a no-op for models without nested
quantization dicts and the fused kernel path is gated by T=1.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: tturney@psyguard.ai
First reference baseline for the inference benchmark suite in
Tests/Benchmarks/InferenceBenchmark.swift. Covers 14 models × 8 context
points (128 → 32k) × swift + bridge paths, plus 8k coherency samples.

Captured on alpha with PR ekryski#44 (Gemma 4 coherence) and PR ekryski#45 (Gemma 4 26B
MoE + Qwen3.5 GDN fused decode) applied, NAX enabled. Method is
`MLX_BENCH_METHOD=summarization`.

Also adds a baselines/README.md describing file naming and methodology
so future baseline runs (M3 Ultra, M5 Pro, etc.) drop in consistently.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: tturney@psyguard.ai
fix: Gemma 4 coherence — full model, KV sharing, real tokenizer
fix: Gemma 4 26B MoE mixed-precision + Qwen3.5 GDN fused decode
…2026-04-16

docs: add M5 Max 128GB benchmark baseline (2026-04-16)
SPM doesn't compile Metal shaders, build the native C++ prefill-bridge
dylibs, or detect changes deep in git submodules. The Makefile fills
those gaps with file-timestamp dependency tracking so only stale
targets rebuild. setup-dev.sh is a one-shot bootstrap for fresh
clones: prerequisite check, swift package resolve, make build-tests.

Bridge targets point at alpha's split layout
(prefill_bridge_gemma.cpp/.h/.dylib + prefill_bridge_qwen.cpp/.h/.dylib)
rather than the legacy prefill_bridge_v2 naming.

Verified end-to-end: rm -rf .build && ./scripts/setup-dev.sh from a
clean checkout completes successfully, producing mlx.metallib and
staging it into the xctest bundle.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Merges three fork-specific sections from ek/tom-eric-moe-tuning into
alpha's README, inserted before the Documentation section:

- Why make instead of swift build — enumerates the four SPM gaps
  (Metal shaders, native dylibs, submodule staleness, test-bundle
  regeneration) and the incremental-rebuild table.
- Testing — xcodebuild invocation for the non-benchmark suite, with
  a callout that benchmarks go through scripts/benchmark.sh.
- Benchmarking — Setup / Basic benchmark / Manual builds
  subsections pointing at benchmarks/README.md.

Adjusted from the source material to match alpha's actual state:
references the split prefill_bridge_gemma + prefill_bridge_qwen
dylibs instead of the legacy prefill_bridge_v2, and points at the
new flat hardware-dated output layout (benchmarks/{chip}-{ram}-{date}.md)
instead of per-model-family subdirectories.

Alpha's 3.x migration content, tokenizer/downloader integration
tables, and Quick Start examples are kept intact.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Problem: the previous writer produced one markdown file per
(model, quant, kv, method) with the run timestamp in the filename.
Cross-run comparisons and multi-model sweeps needed a different
layout, and the CLI could only iterate over {quant} x {kv} with one
model/method per invocation.

Changes

scripts/benchmark.sh:
- --model, --method, --quant, --kv now accept comma-separated lists.
- All runs in a sweep iterate the full Cartesian product in one
  script invocation with a [N/TOTAL] progress prefix.
- Per-run failures are tracked and summarised at the end rather than
  aborting the sweep.
- Help text updated with multi-value usage examples.

Tests/Benchmarks/Utils/BenchmarkWriter.swift:
- Full rewrite. Output goes to benchmarks/{chip-slug}-{ram}gb-{date}.md
  (flat layout, no per-model subdirectory).
- State of truth lives in a JSON sidecar
  (benchmarks/.{filename}.state.json). The markdown is re-rendered
  from the sidecar on every append, so multi-process sweeps
  (each swift test invocation is a separate process) merge cleanly
  into one report.
- Per-model grouping: ## Models -> ### {ModelName} with one
  #### Results table (Config | Ctx | Prompt | Prefill | Decode |
  TTFT | Think PPL | Gen PPL | Think KLD | Gen KLD | GPU Base |
  GPU Peak), #### Output samples, and #### Parameters below each
  model's results (one Parameters block per config).
- Public append(...) signature unchanged; no call-site changes needed.
- Added M5 (gpu_g17x) to the chip detection table alongside M1-M4.

benchmarks/README.md (new):
- Full CLI reference with the new multi-value / Cartesian-product
  semantics.
- KV Cache Configurations table covering all 11 supported configs
  (affine{4,8}, turbo{3,4,8}, turbo{4v2,4v3,3v2,8v2,8v4}).
- Environment Variables table with accurate value lists and
  MLX_MAX_OPS_PER_BUFFER documented.
- Output section describing the hardware-dated file layout,
  per-model grouping, and how the JSON state sidecar keeps
  multi-process sweeps consistent.
- Model cache and downloads section covering HF_HUB_CACHE / HF_HOME /
  ~/.cache/huggingface/hub resolution order, Python-client
  compatibility, and cache-first behaviour.

Tests/Benchmarks/baselines/ removed — everything now lives at the
flat benchmarks/ root, matching the new writer output.

Verified end-to-end with a 2 x 2 x 2 x 1 sweep (2 models, 2 quants,
2 KVs, simple method) with --think --kld --ppl: all 8 runs grouped
correctly under two ### subsections in one m1-max-64gb-*.md file.

Known gap: the Think PPL / Gen PPL / Think KLD / Gen KLD columns
currently render '—' on alpha because the underlying library fields
(GenerateCompletionInfo.{thinkingPerplexity, generationPerplexity,
perTokenLogProbs, ...}) are declared but never populated by the
generation loop on alpha. The harness wiring is correct and will
surface these once the library-side instrumentation lands.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Before the 3.x cutover, the benchmark harness carried ~190 lines of
compatibility shims to bridge pre-alpha model/tokenizer loading:

- HFDownloader struct that shelled out to huggingface-cli via
  /usr/bin/env bash (fragile — the subprocess inherits swift test's
  minimal PATH and doesn't find /opt/homebrew/bin/huggingface-cli).
- HFTokenizerLoader + TokenizerBridge hand-rolling the
  AutoTokenizer -> MLXLMCommon.Tokenizer adapter.
- SimpleJSONTokenizer fallback (never wired).
- extension LLMModelFactory { loadContainer(configuration:...) }
  to re-expose the 2.x signature.

The MLXHuggingFace target and swift-transformers are already
dependencies of the Benchmarks test target on alpha, so the shims
are pure debt.

Changes:
- Removes all four shims (~190 lines).
- Adds imports: HuggingFace, MLXHuggingFace, Tokenizers (already
  partial).
- Declares module-level `benchmarkDownloader` via `#hubDownloader()`
  and `benchmarkTokenizerLoader` via `#huggingFaceTokenizerLoader()`,
  matching the pattern in
  IntegrationTesting/IntegrationTestingTests/ToolCallIntegrationTests.swift.
- Updates the two call sites (loadOrCacheModel and the KLD baseline
  loader) to pass `from:using:` explicitly through the 3.x
  `LLMModelFactory.loadContainer(from:using:configuration:progressHandler:)`
  public signature.
- Drops @testable import MLXLMCommon (the shim extension needed it;
  the macro path does not).
- Fixes a latent Swift 6 Sendable error in the batched
  TaskGroup (alpha is on swift-tools-version 6.1; the batched path
  used `copy userInput` which doesn't make the value Sendable).
  Reconstructs UserInput inside each task from already-Sendable
  [Message] + additionalContext captures.

HubClient reads the same Python-compatible cache at
~/.cache/huggingface/hub that huggingface-cli populates, so
previously-downloaded snapshots are re-used with zero network
traffic. Cache location honours HF_HUB_CACHE / HF_HOME overrides.

Short-name resolution (ModelRegistry.family(named:)) and HF repo-ID
resolution (ModelRegistry.customFamily(repoId:)) are unchanged —
both paths still feed a normalized repoId into the downloader.

Verified:
- Cached load (Qwen3.5-0.8B-bf16) — no network, full generation.
- Fresh download (Qwen3.5-0.8B-4bit — previously absent from cache):
  downloaded via HubClient + URLSession, populated cache, generated
  successfully.
- Multi-config sweep across 2 models x 2 quants x 2 KVs: 8/8 runs
  succeeded; Qwen3.5-2B 4bit/8bit were downloaded on demand.

The earlier Qwen3.5 keyNotFound(["language_model", "model", "norm",
"weight"]) error we hit through the shim path does not reproduce on
the 3.x loader path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Commits the first two hardware-dated baselines produced under the
new writer layout:

- benchmarks/m1-max-64gb-2026-04-16.md — this session's sweep on
  Apple M1 Max 64GB (Qwen3.5 0.8B and 2B across {4bit, 8bit} x
  {none, turbo4v2} with --think --kld --ppl, plus the initial
  bf16 / 4bit smoke at 128 ctx summarization). Demonstrates the
  multi-model / multi-config grouping in the new writer format.
- benchmarks/m5-max-128gb-2026-04-16.md — the existing M5 Max
  full-matrix baseline from PR ekryski#46 (hand-curated, 14 models x
  8 context points x swift & bridge paths). Preserved as-is in
  its original format; baselines are frozen snapshots and don't
  need to match the writer's current template.

.gitignore adds `benchmarks/.*.state.json` so writer state sidecars
stay local. The markdown is the source of record for readers; the
sidecar is a rehydration aid for multi-process sweeps.

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

Benchmark build tooling + 3.x loader migration + hardware-dated baselines
…head) (ekryski#48)

* evaluate: populate per-token data for PPL and KLD (opt-in, ~zero overhead)

GenerateCompletionInfo declared thinkingPerplexity / generationPerplexity /
perTokenLogProbs / perTokenIds / perTokenPhases, and GenerateParameters
exposed trackPerplexity / collectPerTokenData, but nothing in the
generation loop populated any of them. Downstream consumers
(benchmark harness PPL columns, KLD forced-decode at
InferenceBenchmark.swift:854, anywhere that branches on completionInfo.
perTokenIds != nil) silently read nil and did nothing.

This change wires the capture without touching the inference path when
the flags are off.

New types (Libraries/MLXLMCommon/Evaluate.swift, near TokenIteratorProtocol):

- PerTokenData — the flushed, phase-labeled, per-token result with
  precomputed thinkingPerplexity / generationPerplexity.
- PerTokenDataCapture — reference-type box holding lazy MLXArray handles
  during the loop. Class (not struct) is required because TokenIterator
  is a struct and `for token in iterator` copies it; the class lets
  appends from the for-in's copy be visible to the outer iterator.
- GenerateParameters.needsPerTokenCapture — single source of truth for
  whether capture is on (trackPerplexity || collectPerTokenData).

TokenIteratorProtocol gets finalizePerTokenData() with a default nil
implementation so SpeculativeTokenIterator opts out automatically.
PPL/KLD with speculative decoding is a separate workstream.

TokenIterator changes:

- Three new stored fields: thinkStartTokenId / thinkEndTokenId /
  thinkingPhasePrefilled (carried from GenerateParameters so the
  finalizer can label phases without an API change to the outer
  generateLoopTask), plus the optional perTokenCapture box.
- All three init overloads wired: the two `parameters:` inits enable
  capture when either flag is set; the manual processor/sampler init
  always disables (that entry point doesn't carry thinking config).
- convertToToken(logits:) gets a single `if let capture = perTokenCapture`
  block emitting the lean kernel chain:

      let lse = logSumExp(logits, axes: [-1])                      // 1 reduction
      let yLogit = takeAlong(logits, y.expandedDimensions(axis:-1),
                             axis: -1)                             // scalar gather
      let selected = yLogit - lse
      asyncEval(selected)

  Scalar output. Does NOT materialise a full-vocab logSoftmax buffer
  (V can be 250k+ tokens → 1MB per step on decode). asyncEval detaches
  the subgraph so it runs concurrently with the next forward pass rather
  than blocking it.
- New non-mutating finalizePerTokenData(): concatenates all captured
  1-element tensors into one [N] tensor, does a SINGLE GPU→CPU transfer
  for the whole generation, labels phases in pure Swift based on stored
  think-start/end ids + thinkingPhasePrefilled, computes exp(-mean(lp))
  per phase.

Generation-loop wiring (two call sites):

- Async path (generateLoopTask): moved Stream().synchronize() ahead of
  the info-event emit (it was already at the end of the function — we
  just need it before the finalize), called iterator.finalizePerTokenData(),
  and plumbed the 5 fields into GenerateCompletionInfo.
- Sync path (deprecated generate(input:context:iterator:didGenerate:)
  returning GenerateCompletionInfo): same finalize call after
  runSynchronousGenerationLoop (which already synchronizes).

Performance validation (M1 Max, Qwen3.5-0.8B 4bit, 1024 ctx, 5 runs each):

          Flags OFF      Flags ON       Delta
Prefill   236.4 ± 2.2    239.6 ± 2.2    +1.4% (within noise)
Decode    159.5 ± 7.9    161.1 ± 4.4    +1.0% (within noise)

The first-pass implementation used logSoftmax(logits) materialising a
[1, V] buffer and showed ~8% decode regression. Switching to the
scalar-output logSumExp + takeAlong chain got overhead into the noise
floor on this workload.

Correctness validation (same config, --ppl --kld --think):

  4bit / no-quant:  Think PPL 2.31, Gen PPL 1.07, Think KLD 0.27, Gen KLD 0.31
  4bit / turbo4v2:  Think PPL 3.39, Gen PPL 1.98, Think KLD 0.32, Gen KLD 0.41

KLD is directionally correct: turbo4v2 (more aggressive KV compression)
diverges more from the bf16 baseline. The benchmark harness's KLD
forced-decode path at InferenceBenchmark.swift:854 — previously dead
because perTokenIds was always nil — now fires.

xcodebuild test -scheme mlx-swift-lm-Package -only-testing MLXLMTests:
54 tests in 4 suites passed.

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

* bench: harmony-channel phase detection + --reasoning flag

Extends PPL/KLD support to harmony-format models (GPT-OSS 20B) whose
reasoning is delimited by channel transitions rather than a bracketed
start/end token pair. Previously `supportsThinking: false` in the
registry — accurate for what the harness could DO, misleading for what
the model actually emits — so harmony reasoning tokens were silently
lumped into the "gen" phase.

What's in this commit

GenerateParameters (Libraries/MLXLMCommon/Evaluate.swift):

- New optional fields, additive — no existing call sites need changes:
    harmonyChannelMarkerTokenId: Int32?          // e.g. 200005 = <|channel|>
    harmonyThinkingChannelTokenIds: [Int32]      // e.g. [35644] = analysis
    harmonyGenerationChannelTokenIds: [Int32]    // e.g. [17196] = final

TokenIterator:

- Stores the three harmony fields alongside existing thinkStart/End.
- labelPhases(_:) dispatches: harmony state machine if markerId set,
  bracket-pair state machine if thinkStart/End set, otherwise every
  token labelled "gen". The harmony SM is ~20 lines: on each token,
  check if it is the marker; if so, flag awaitingChannelName and keep
  the current phase for this token; on the next token, consult the
  thinking/generation sets to flip phase. Unknown channel names leave
  phase unchanged.
- No inference-path changes — phase labeling runs once in the
  finalizer after Stream().synchronize().

Phase string alignment:

- Changed finalizer output from "thinking"/"generation" to "think"/"gen"
  to match the long-standing BaselineTokenData.phases convention at
  InferenceBenchmark.swift:288 and the checks at :1592. The earlier
  PPL/KLD commit left these mismatched; KLD worked only because of a
  bracket-based fallback detector at :1584 that is harmony-blind.
  With the strings aligned, the primary phase-string check fires for
  both bracket and harmony models.

ModelRegistry (Tests/Benchmarks/Utils/ModelRegistry.swift):

- ThinkingConfig.style is now an enum:
    .bracket(start: String, end: String)
    .harmonyChannel(marker: String,
                    thinkingChannels: [String],
                    generationChannels: [String])
- `.qwen` and `.gemma4` statics migrate to .bracket; new `.harmony`
  static describes GPT-OSS's channels (analysis → thinking;
  final, commentary → generation).
- gpt-oss-20b entry flipped to supportsThinking: true,
  thinkingConfig: .harmony.

InferenceBenchmark token resolution:

- The token-ID resolution block at line 634 rewrote to dispatch on
  ThinkingConfig.Style. Bracket models resolve startId + endId as
  before; harmony models resolve markerId + channel-name IDs and
  populate the new GenerateParameters harmony fields. Startup log
  gains a "[BENCH] Harmony channel marker=… thinking=… generation=…"
  line when the harmony path is taken.

--reasoning flag (scripts/benchmark.sh + BenchEnv):

- New CLI flag with default "medium". Accepts low/medium/high (warns
  rather than errors on other values — future model vocabularies pass
  through). Plumbed through MLX_BENCH_REASONING env var to
  BenchEnv.reasoningEffort, which overrides family.reasoningEffort at
  the GenerateParameters construction site. Harness prints
  "Think: yes (reasoning=…)" when --think is active. A new
  "[INFO] PPL: yes" line is also emitted for parity with --kld /
  --think logging.

Docs (benchmarks/README.md):

- --reasoning added to the CLI flags table.
- MLX_BENCH_REASONING added to the environment variables table.
- Quick Start gains a GPT-OSS + --reasoning + --think + --ppl example.

Validation (M1 Max, GPT-OSS 20B 4bit / turbo4v2, --think --kld --ppl)

Harness log confirms harmony resolution:
    Harmony channel marker=200005, thinking=[35644], generation=[17196]

Forced decode output for three configurations:
            ctx / reasoning        Think/Gen tokens   Think PPL  Think KLD
    ctx=1024 / reasoning=medium    199 / 1            2.47       0.39
    ctx=1024 / reasoning=low       199 / 1            3.03       0.64
    ctx=128  / reasoning=low       199 / 1            2.34       0.62

All 199 reasoning tokens attributed to "think" phase. The single
"gen" token is the initial <|channel|> marker itself (labeled with
the pre-transition phase by design — Gen PPL ~ 1.00 confirms the
model was virtually certain <|channel|> was the first token).
Previous GPT-OSS runs showed think=0 / gen=400 because the harness
lacked any way to detect the channel transition; now think-phase
tokens are attributed correctly and Think KLD reflects reasoning-
phase divergence from the bf16 baseline.

Qwen3.5 and Gemma4 bracket models are unaffected — same token
resolution path, same labeling semantics, just on the renamed
"think"/"gen" strings.

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

* bench: harmony thinking-budget processor + fix forced-decode cap

Two issues surfaced once harmony phase detection shipped: GPT-OSS
continued to spend all of its --think token budget reasoning and
never emitted a final-channel answer, and the KLD forced-decode loop
re-applied the bracket-only effectiveMaxTokens cap so it stopped
processing at 200 tokens regardless of how many the target generated.
Both are fixed here; together they let --ppl --kld --think produce
meaningful numbers for both reasoning and visible answer on GPT-OSS.

Budget parity (effectiveMaxTokens)

Previously `effectiveMaxTokens = thinkStartId != nil ? budget + max : max`,
which gated the `+ budget` addition on bracket-only thinking. Harmony
models (harmonyMarkerId set, thinkStartId nil) fell through to the
short branch and got HALF the token budget. Switched to a
`hasThinkingBudget = thinkStartId != nil || harmonyMarkerId != nil`
check — both paths now reserve the same `thinkingBudget` reasoning
tokens on top of the `maxTokens` answer budget.

Same-shaped bug in forcedDecodeKLD capped the forced-decode loop at
`min(tokenIds.count, effectiveMaxTokens)` — bracket-only. Replaced
with `tokenIds.count`; the captured target sequence is already bounded
by the generation loop's own budget, so recapping here only dropped
data (200 captured tokens instead of all 400 target tokens were being
fed through the baseline model).

HarmonyThinkingBudgetProcessor

Analogue of ThinkingBudgetProcessor for channel-transition models.
State machine:

1. Watch for <|channel|> marker, then the following channel-name
   token. On `analysis` set inThinking=true and reset
   thinkingTokenCount. On `final`/`commentary` set inThinking=false.
2. While inThinking, count tokens and suppress EOS so the model
   cannot quit mid-reasoning.
3. When thinkingTokenCount reaches maxThinkingTokens, arm forceIndex=0.
4. Next N process() calls pin the sampler to `forcedTransitionSequence[forceIndex]`
   — for GPT-OSS this is <|end|> <|start|> assistant <|channel|> final
   <|message|> (6 tokens). Token pinning uses the same large-finite
   logit trick (100.0) as ThinkingBudgetProcessor — softmax(+inf)
   would produce NaN which the sampler misroutes.
5. After the transition completes, suppress entry back into the
   analysis channel so the model can't oscillate into reasoning
   during the final answer.

Extended ThinkingConfig.harmonyChannel with a `transitionSequence`
associated value that lists the token strings to force; the harness
resolves them to IDs at startup and hands the Int32 array to the
processor at construction. GPT-OSS's `.harmony` config gets the full
6-token sequence. A nil/missing entry in the resolution table
silently disables the processor (no force) rather than panic — the
generation still runs, it just isn't budget-enforced.

The bracketBudgetProcessor and harmonyBudgetProcessor are mutually
exclusive — exactly one keys off the active thinking style. Both are
appended to additionalProcessors when present so CompositeLogitProcessor
sees them; only one ever fires for a given run.

Caveat: the 6 forced tokens land in GenerateCompletionInfo.perTokenLogProbs
with logprob ~= 0 (we pinned the sampler). They very slightly bias
per-phase PPL toward 1.0 — bounded contribution (6 tokens out of
hundreds) and not material to the signal we care about (reasoning-
phase PPL / KLD comparisons across KV configs). Left as-is; documented
in the processor's doc comment.

scripts/benchmark.sh adds `[HARMONY]` to the log-filter pattern so
future harmony-side diagnostics flow through to the terminal when
added (none ship in this commit).

Validation (M1 Max, GPT-OSS 20B 4bit/turbo4v2, --ppl --kld --think
 --reasoning medium)

Before: Generation 400 tokens, Think/Gen = 199/1, Gen PPL = 1.00
(degenerate), Gen KLD = 0.00 (degenerate). Model ran out of tokens
mid-reasoning.

After:  Generation 300 tokens, Think/Gen = 205/97, Gen PPL = 1.82,
Gen KLD = 0.47. Model emits a real final-channel answer; Gen KLD
reflects the 4-bit turbo4v2 model's answer-distribution divergence
from the bf16 baseline.

The 205 think count is 200 reasoning content + 5 transition tokens
that labelPhases attributes to "think" (everything up to and
including <|channel|> in the transition sequence). The 97 gen count
is the `final` name token, `<|message|>`, and ~95 actual answer
tokens.

Qwen3.5 and Gemma 4 bracket paths are unchanged: Qwen3.5 0.8B 4bit
turbo4v2 ctx 128 still produces Think/Gen = 201/200 with Think PPL
2.34 / Gen PPL 1.13 / Think KLD 0.58 / Gen KLD 0.24.

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

* bench: parse max_ops_per_buffer from device.cpp + group speculative params

Two related Parameters-table cleanups.

Parse max_ops_per_buffer from device.cpp

The hardware-default switch in BenchmarkWriter mirrored the one in
mlx/backend/metal/device.cpp by hand. Committed truth drifted:
device.cpp had 100 for Max/Ultra while the Swift table returned 200,
so the Parameters block reported the wrong default in every run
that didn't set MLX_MAX_OPS_PER_BUFFER.

Fix: resolve the value at runtime by parsing device.cpp directly
from the mlx-swift dependency's on-disk source (same source the
linked mlx library was built from, so the two can't diverge).

Resolution order:
  1. $MLX_SWIFT_PATH/Source/Cmlx/mlx/mlx/backend/metal/device.cpp
  2. {projectRoot}/../mlx-swift/... (sibling checkout)
  3. {projectRoot}/.build/checkouts/mlx-swift/... (SPM cache)

Parser finds the `case 'X':` in Device::Device() matching the current
GPU arch suffix, then grabs the first `max_ops_per_buffer_ = N;` in
that case block. If any step fails (file missing, format drifted,
no matching case) the function falls back to a conservative
hardcoded table whose values track the committed defaults.

The Parameters row now carries a three-state provenance label:
  "N (env)"                       — MLX_MAX_OPS_PER_BUFFER was set
  "N (from device.cpp, <arch>)"   — parsed live from source
  "N (fallback, <arch>)"          — device.cpp not located/parseable

Verified locally: the label now reads
`100 (from device.cpp, applegpu_g13s)`
on a fresh M1 Max run (matching the committed device.cpp value).
Previously it read `200 (hardware default, applegpu_g13s)` — stale.

Group speculative + n-gram fields

The Parameters table listed "N-gram size" and "Max n-gram draft
tokens" next to "Collect per-token data", while "Speculative
decoding" (the enclosing strategy name) sat many rows below near
batch size. Reordered the whole table into seven semantic groups
so related knobs read together:

  KV cache → Generation budget → Sampling → Penalties →
  Thinking / reasoning → Speculative decoding → Telemetry / runtime

Under Speculative decoding, the strategy name now sits immediately
above the n-gram parameters so readers see "Speculative decoding:
ngram (size=3, maxDraft=3)" then the two underlying size / draft
rows as a unit.

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

* bench: remove per-step sync in budget processors (~50% decode win on GPT-OSS)

After the previous PPL / KLD / harmony commits landed, GPT-OSS 20B with
--think --kld --ppl showed a ~33% decode regression at 1024 ctx vs the
no-flags baseline. Qwen3.5 0.8B with the same flags showed only ~1-2%.
The gap meant something was touching the hot path that hurt much more
on a 20B MoE than on a 0.8B dense.

Root cause: `token.item(Int32.self)` in the budget processors' didSample

Both `ThinkingBudgetProcessor` and `HarmonyThinkingBudgetProcessor`
extracted the sampled token's integer ID inside `didSample(token:)` via
`.item(Int32.self)`. `MLXArray.item()` calls `eval()` internally — a
blocking GPU→CPU synchronisation. One sync per token, called from
inside `convertToToken` BEFORE the next forward pass could dispatch.

When no processors are active (e.g. GPT-OSS flags-off, where no
repetition/presence penalties are registered for the family), the per-
step sync path is empty and the pipeline stays full. When a budget
processor joins the chain, every step now serialises on that sync
point, blocking issue of step N+1's forward pass until step N has
fully materialised on CPU. On a 20B MoE each forward is ~15-25 ms so
the stall dominates; on a 0.8B dense (~10 ms) it's barely visible —
explaining the divergence in observed regression.

Isolation test confirmed this is not a logprob-capture cost: running
`--ppl` only (no --think) on GPT-OSS at 1024 ctx turbo4v2 matched the
no-flags decode within 1%. The hit is specifically from --think
engaging the budget processor.

Three related fixes

1. Batched state-machine updates (primary)

   `didSample` no longer calls `.item()` per token. Instead it appends
   the lazy MLXArray to a `pendingTokens` queue and returns immediately,
   letting the next forward pass dispatch without delay. The queue is
   flushed every N tokens (default batch size 10) via a single
   `eval(pendingTokens)` + id extraction pass, then the state machine
   is run over the drained IDs in order.

   Dynamic flush threshold: shrinks as we approach the thinking budget
   so forcing triggers within a few tokens of the configured limit:
     headroom=100 → flush every 10
     headroom=5   → flush every 2
     headroom=0   → flush every 1
   Maximum overshoot ≤ flushBatchSize = 10 tokens, ≤5% of a typical
   200-token budget.

2. Pre-computed EOS suppression mask

   The scatter-per-EOS-token loop inside `process(logits:)`:
       for eosId in eosTokenIds { modified[eosId] = -inf }
   dispatched N scatter kernels per generation step during the
   thinking phase. Replaced with a lazily-built `[V]` additive mask
   constructed host-side and added once per call (one elementwise-add
   kernel). Same for the post-exhaustion `<think>` / analysis-channel
   suppression. 2-5 kernel dispatches → 1 per step.

   Because `LogitProcessor.process(logits:)` is non-mutating on the
   protocol, the cache lives in a `SuppressMaskCache` reference-type
   box held by both processor structs. Stays const from the struct's
   perspective; populates on first call.

3. Skip sync during forced transition (harmony)

   During the 6-token force-emit in `HarmonyThinkingBudgetProcessor`,
   each sampled token is deterministically the one we pinned in
   `process()`. `didSample` now advances `forceIndex` without
   appending to `pendingTokens` (no sync, no state-machine pass) —
   saves 6 item() calls per thinking episode.

Validation (M1 Max, GPT-OSS 20B 4bit, ctx=1024, --ppl --kld --think)

                     Before fix       After fix       Baseline (no flags)
  no-quant prefill   433.6 tok/s      667.8 tok/s     615.8 tok/s
  no-quant decode    43.0 tok/s       68.1 tok/s      63.9 tok/s
  turbo4v2 prefill   401.0 tok/s      674.0 tok/s     590.6 tok/s
  turbo4v2 decode    42.3 tok/s       52.0 tok/s      53.3 tok/s

Flag-on decode now matches the flag-off baseline within noise
(+6.6% on no-quant, -2.4% on turbo4v2). Prefill regression
eliminated — flag-on prefill is slightly *faster* than flag-off
(masks upload once at first call; warmed caches).

Qwen3.5 0.8B bracket-path sanity check (ctx=1024 turbo4v2
--ppl --kld --think): prefill 246 / decode 159.7, think=201 gen=200
forced-decode split exactly respects the 200-token budget. Dynamic
flush threshold near the budget ceiling prevents overshoot on
bracket paths where exact accounting matters.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…yski#49)

* perf(gated-delta): bump prefill eval interval 64 → 128 for +20%

Qwen3.6-35B-A3B prefill on M5 Max @ ctx=1024:
  64 tok barrier: 247 tok/s
  128 tok barrier: 297 tok/s (+20%)
  256 tok barrier: 286 tok/s (+16%)
  512 tok barrier: 293 tok/s (+19%)
  1024 tok barrier: 281 tok/s (+14%)

GPU peak unchanged at 18.54 GB across all eval intervals — the 64-token
cadence was syncing the GPU pipeline too aggressively (30 GDN layers
× 8 syncs per 512-token chunk = 240 syncs per prefill chunk) without
memory benefit. 128 cuts that in half with no memory cost.

Still overridable via GDN_EVAL_INTERVAL env var for further tuning.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: tturney@psyguard.ai

* fix(gated-delta): use Metal kernel at T>1 with fp32 state

Root cause of the previously-flagged "kernel correctness bug at T>1 (max
diff 0.25 vs ops)" was precision, not a kernel bug: the Swift state was
typed q.dtype (bf16), so accumulation across T recurrence steps compounded
rounding error. Python mlx-lm has always used fp32 state, which is why
the same kernel is correct there.

Three coupled fixes:
- Kernel source: write o_state as StT (not InT), matching Python's kernel
- Swift dispatch: pass StT template + use state.dtype for output
- gatedDeltaUpdate: create state in fp32 (and upcast if caller passes bf16)

Prefill path now routes through the single-dispatch Metal kernel instead
of the Swift-side T-loop ops fallback. One Metal dispatch for all T
timesteps per GDN layer, matching Python. Qwen3.6-35B-A3B prefill on
M5 Max is correct and now equivalent to, rather than bypassing, the
kernel — residual Swift-vs-Python perf gap is framework-level dispatch
overhead, not kernel choice (see BuildLog investigation).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: tturney@psyguard.ai

* perf(prefill): asyncEval between chunks — 10x prefill on GDN arches

Previously `LLMModel.prepare` called `eval(cache)` + `MLX.Memory.clearCache()`
after every prefill chunk. `eval` is a blocking sync: the CPU would idle
while the GPU finished chunk N, then build chunk N+1's graph serially,
then sync again. This drained the pipeline after each chunk.

Python mlx-lm gets pipelined prefill for free because its bindings defer
eval until a value is read, so the next chunk's graph builds while the
GPU works on the previous chunk.

Swap to `asyncEval` on the cache's inner state per chunk — non-blocking,
so the CPU can immediately start graph-building the next chunk. One
terminal `eval(cache)` + `clearCache()` after the full prefill loop.

Qwen3.6-35B-A3B-4bit prefill on M5 Max 128GB (ctx, tok/s):

        before →  after     (×)
  128    260     696       2.7x
  512    235    2201       9.4x
  1k     244    3130      12.8x
  2k     270    3937      14.6x
  4k     265    3769      14.2x
  8k     268    3416      12.7x
  32k    522    2040       3.9x

At ctx=2k the gap vs Python mlx-lm (≈4000 tok/s) closes to within 2%.

No regression on non-GDN models:
- Gemma 4 E2B 4-bit: 19725 tok/s @ 1k  (baseline 20206, ~within noise)
- Llama 3.2 3B 4-bit: 6710 tok/s @ 1k  (baseline 6837, ~within noise)

Decode speed unchanged (different code path).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: tturney@psyguard.ai

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…ekryski#50)

Both Qwen35 (GDN hybrid) and NemotronH (Mamba+attention hybrid) called
`eval(hidden, cache)` after every layer during prefill. That was a CPU↔GPU
sync per layer — the CPU would idle waiting for the GPU to finish layer i
before it could start building layer i+1's graph, 40-48 syncs per chunk.

Swap to `asyncEval` so the CPU can build ahead while the GPU pipelines
through the layer stack. Keeps the original memory intent (still schedules
per-layer evaluation to free intermediate activations) but no longer
blocks the CPU.

Measured on M5 Max 128GB, summarization bench, 4-bit prompt-processing:

Nemotron-Cascade-2-30B-A3B-4bit:
  ctx=128:  863 → 960 tok/s (+11%, 3-run avg, stable)
  ctx=1024: 2711 → 2764 tok/s (+2%)
  ctx=4096: 2481 → 2481 tok/s (0%)

Qwen3.5-2B-4bit:
  ctx=128:  2837 → 3018 tok/s (+6%)
  ctx=1024: 10028 → 10348 tok/s (+3%)

Qwen3.5-9B-4bit:
  ctx=128:  1255 → 1320 tok/s (+5%)

Qwen3.6-35B-A3B-4bit:
  ctx=128:  718 → 712 tok/s (noise)
  ctx=1024: 3188 → 3197 tok/s (noise)

Short-context-only wins — at ctx≥1k the GPU is already saturated on
per-layer compute and the pipeline stall was shorter than the matmul.
Coherency unchanged at ctx=1024 for both models.


Co-Authored-By: tturney@psyguard.ai

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…yski#51)

* bench: add --ngram flag, default n-gram speculative decoding off

alpha defaults `GenerateParameters.ngramSize` to 3 so library clients
get trigram speculative decoding out of the box. That composite —
speculation accept-rate × draft overhead — adds run-to-run variance
that masks the primitive we actually want to measure in benchmarks
(pure autoregressive decode tok/s). A 4096-ctx Qwen3.5 0.8B
summarization row drifted ~10% vs a prior baseline that defaulted
ngramSize to 0; investigation showed the whole delta was speculation
accept-rate noise, not a real perf change.

This PR makes benchmarks default to no speculation and adds a CLI
flag to opt in explicitly when we want to measure the speculative
path.

Changes

1. `scripts/benchmark.sh` gains `--ngram SIZE`, default 0 (disabled).
   Value validated as a non-negative integer; exported as
   `MLX_BENCH_NGRAM=N` unconditionally so the harness always sees an
   explicit value. Logs `[INFO] N-gram: size=N` when non-zero.

2. `BenchEnv.ngramSize: Int` reads `MLX_BENCH_NGRAM`, defaults 0.
   Deliberately diverges from the library default (3) — library
   clients get the typical-use default; benchmarks get a clean
   primitive and opt in for speculative measurements.

3. Two `GenerateParameters` call sites in `InferenceBenchmark.swift`
   now pass `ngramSize: BenchEnv.ngramSize` and
   `maxNgramDraftTokens: BenchEnv.ngramSize` — the main
   `runGenerationBenchmark` and the batched-decode path.
   `wikitext2` and the KLD forced-decode path don't sample, so
   ngramSize has no effect there and we leave them alone.

4. `benchmarks/README.md` documents `--ngram SIZE` in the CLI table
   and `MLX_BENCH_NGRAM` in the environment-variable table, with a
   note on why the benchmark default diverges from the library default.

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

* bench: configKeyExtras — distinct config blocks for A/B on --ngram

The writer grouped rows by a config key built from
`quantization / kvConfig / scenario`. Two runs that differ only in a
dimension outside that triple — e.g. two runs of
`qwen35-0.8b 4bit turbo4v2 summarization`, one with `--ngram 0` and
one with `--ngram 3` — collapsed into the same config entry. Both
results rows landed in the table, but the Parameters block only
reflected whichever run created the entry first. Reader couldn't
tell which row was which.

Fix: `BenchmarkWriter.append` takes a new optional
`configKeyExtras: [(String, String)] = []` that's appended to the
config key as ` / key=value` pairs. The InferenceBenchmark harness
passes `[("ngram", "N")]` when `BenchEnv.ngramSize > 0`; nothing
otherwise.

Result with `--ngram 0` then `--ngram 3` on the same cell:
  4bit / turbo4v2 / summarization
  4bit / turbo4v2 / summarization / ngram=3
Separate Parameters blocks with `N-gram size | 0` and `N-gram size | 3`
respectively.

Extensible to other benchmark-time dimensions that aren't part of the
quant/kv/method triple (e.g. reasoning effort) without further schema
changes.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`GenerateParameters` shipped `ngramSize = 3` and
`maxNgramDraftTokens = 3` as defaults, so every library consumer who
constructs `GenerateParameters()` implicitly gets trigram prompt-lookup
speculative decoding. Speculation is a net-win only when the generated
text has enough repetition that the trigram table hits with a
reasonable acceptance rate. For novel prose, summarisation, general
chat, etc. accept rate is often too low for the draft work to pay
off — it becomes pure overhead. Yesterday's bench surfaced this as a
~10% decode regression on Qwen3.5-0.8B summarisation at 4096 ctx vs
an older baseline that defaulted to `ngramSize = 0`.

Until we can validate the speculative path with good per-workload
benchmarks and accept-rate instrumentation (being added separately),
the safer library default is off. Clients who want speculation opt
in explicitly:

    GenerateParameters(ngramSize: 3, maxNgramDraftTokens: 3)

The parameters and speculation code path are unchanged — this is a
defaults-only change. Existing callers that pass `ngramSize` /
`maxNgramDraftTokens` explicitly keep their behaviour.

Verified: `xcodebuild test -scheme mlx-swift-lm-Package
-only-testing MLXLMTests` passes.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
input.text.tokens is 2D [1, seqLen] after container.prepare(). prompt.dim(0)
was returning the batch dim (1) instead of seqLen, which sent long prompts
down the padding branch and produced a [seqLen+pad] buffer. ring.append
then crashed trying to broadcast a [seqLen+pad] buffer against a
[capacity] mask.

Flatten first, then compute n, so loadPrompt works on either 1D or 2D input.
12 Python experiment scripts covering the full investigation:
- Layer-skip self-draft (dead: LM head can't read intermediate states)
- Linear aligner (7x calibration improvement, 0% decode generalization)
- Decode-path MLP training (36% acceptance at 100K/100ep scale)
- E2E spec decode v1-v4 (Mamba corruption on batch verify kills GDN)
- Parallel multi-position heads (2-5%, independent prediction fails)
- Separate GDN draft model (target Mamba still corrupted on verify)
- Transformer vs MLP draft head comparison

Key findings documented in Obsidian. These are research artifacts, not
shipping code — they inform the v2 block diffusion drafter architecture.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: tturney@psyguard.ai
Register MLXServer as an executable product/target in Package.swift,
update loadContainer calls to use the new macro-based HuggingFace
integration (from/using params), add @unchecked Sendable to
ModelContext for actor boundary crossing, and set Swift 5 language
mode for the server target to avoid strict concurrency errors.

Also adds --kv flag for TurboQuant KV cache scheme selection and
disables thinking mode for chat completions.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@TheTom TheTom closed this Apr 18, 2026
TheTom added a commit that referenced this pull request May 7, 2026
External audit flagged 4 gaps. Addressing 3 here:

1. **Coordinate-system bug for repeat eviction rounds (#4 in audit).**
   First eviction was correct because storage_idx == original_pos
   pre-compaction. After compaction those diverge: engine.evictPos
   emits storage indices, but rescue text-decode reads
   _PROMPT_TOKEN_IDS[ws:we] expecting original token positions. Round
   2+ would have decoded the wrong text.

   Fix: maybeFinalizeAndCompact translates evictedStorageIdx →
   evictedOriginal via firstCache.translateStorageIndicesToOriginal,
   which reads positionIds (already tracking the storage→original
   map). Eviction callback fires with ORIGINAL positions; rescue
   decoding works for round N.

   New API: TriAttentionKVCache.translateStorageIndicesToOriginal.
   Engine.finalizeEvictRound's callback fire is overridden by
   maybeFinalizeAndCompact's corrected callback fire (the cache-side
   has the positionIds, so this is the right gate).

2. **expectedLayers env-var parity (ekryski#5 in audit).** AMD's
   TriAttentionV3Config.from_env reads VLLM_TRIATT_EXPECTED_LAYERS
   and VLLM_TRIATT_BOUNDARY_SKIP. Swift fromEnv now mirrors both,
   so claim "same env surface as AMD" actually holds.

3. **Tokenizer adapter doc.** MLXLMCommon can't transitively import
   swift-transformers (yyjson dep). Docstring shows callers a
   5-line adapter pattern. Caller wraps modelContext.tokenizer
   into TriAttentionTokenizerLike and calls
   `TriAttentionRescue.shared.setTokenizer(...)` once at app init.

Still TODO from audit:
  - #1 production tokenizer binding: gated on caller doing the
    setTokenizer call. ChatSession or a higher-level driver should
    do it automatically when V3 is enabled. Holding for now —
    requires touching user-facing API.
  - #2 automatic Tier 3 prepend: rehydratePrompt is the API; calling
    site is on caller / driver. Same shape as #1.

13/13 tests still pass on M5 against live longctx-svc :9091.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: tturney <tturney@psyguard.ai>
TheTom added a commit that referenced this pull request May 7, 2026
Closes audit gaps #1 and #2 from the external review:
  #1 production tokenizer binding: was only called from tests.
  #2 automatic Tier 3 prepend: rehydratePrompt API existed but
     nothing called it from a production driver.

Both wire into ChatSession's per-turn flow, gated on the cache
actually being a TriAttentionKVCache (so non-V3 sessions are
bit-identical to upstream):

  let usesV3 = kvCache.contains { $0 is TriAttentionKVCache }
  if usesV3 {
      rescue.setTokenizer(V3ChatTokenizerAdapter(inner: tokenizer))
      if let recovered = rescue.rehydratePrompt(query: userMessage.content) {
          messages.insert(.system(recovered), at: messages.count - 1)
      }
  }

Tokenizer adapter is file-scope (Swift doesn't allow types nested
in closures in generic contexts). Forwards decode(tokens:) to
swift-transformers' Tokenizer.decode(tokenIds:skipSpecialTokens:).

Tier 3 system message is EPHEMERAL — inserted before the user
message in the prompt rendered to the model, but the underlying
session history is untouched. Each turn re-fetches from longctx-svc
based on that turn's user query. Mirrors AMD's
prefill_rehydrate.maybe_rehydrate_messages semantics.

Net for the M5 stack: enable VLLM_TRIATT_ENABLED=1 + set
LONGCTX_ENDPOINT, run a ChatSession against any Qwen3 model, and the
full 3-tier rescue stack runs end-to-end with no per-driver wiring.

Doesn't address audit point #4 (post-compaction position translation
across multi-eviction-round prefills) — that landed at 5ede7a1.

13/13 TriAttention tests still green on M5 :9091. Production rescue
path is now a one-flag flip for any ChatSession user.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: tturney <tturney@psyguard.ai>
TheTom added a commit that referenced this pull request May 14, 2026
External audit flagged 4 gaps. Addressing 3 here:

1. **Coordinate-system bug for repeat eviction rounds (#4 in audit).**
   First eviction was correct because storage_idx == original_pos
   pre-compaction. After compaction those diverge: engine.evictPos
   emits storage indices, but rescue text-decode reads
   _PROMPT_TOKEN_IDS[ws:we] expecting original token positions. Round
   2+ would have decoded the wrong text.

   Fix: maybeFinalizeAndCompact translates evictedStorageIdx →
   evictedOriginal via firstCache.translateStorageIndicesToOriginal,
   which reads positionIds (already tracking the storage→original
   map). Eviction callback fires with ORIGINAL positions; rescue
   decoding works for round N.

   New API: TriAttentionKVCache.translateStorageIndicesToOriginal.
   Engine.finalizeEvictRound's callback fire is overridden by
   maybeFinalizeAndCompact's corrected callback fire (the cache-side
   has the positionIds, so this is the right gate).

2. **expectedLayers env-var parity (ekryski#5 in audit).** AMD's
   TriAttentionV3Config.from_env reads VLLM_TRIATT_EXPECTED_LAYERS
   and VLLM_TRIATT_BOUNDARY_SKIP. Swift fromEnv now mirrors both,
   so claim "same env surface as AMD" actually holds.

3. **Tokenizer adapter doc.** MLXLMCommon can't transitively import
   swift-transformers (yyjson dep). Docstring shows callers a
   5-line adapter pattern. Caller wraps modelContext.tokenizer
   into TriAttentionTokenizerLike and calls
   `TriAttentionRescue.shared.setTokenizer(...)` once at app init.

Still TODO from audit:
  - #1 production tokenizer binding: gated on caller doing the
    setTokenizer call. ChatSession or a higher-level driver should
    do it automatically when V3 is enabled. Holding for now —
    requires touching user-facing API.
  - #2 automatic Tier 3 prepend: rehydratePrompt is the API; calling
    site is on caller / driver. Same shape as #1.

13/13 tests still pass on M5 against live longctx-svc :9091.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: tturney <tturney@psyguard.ai>
TheTom added a commit that referenced this pull request May 14, 2026
Closes audit gaps #1 and #2 from the external review:
  #1 production tokenizer binding: was only called from tests.
  #2 automatic Tier 3 prepend: rehydratePrompt API existed but
     nothing called it from a production driver.

Both wire into ChatSession's per-turn flow, gated on the cache
actually being a TriAttentionKVCache (so non-V3 sessions are
bit-identical to upstream):

  let usesV3 = kvCache.contains { $0 is TriAttentionKVCache }
  if usesV3 {
      rescue.setTokenizer(V3ChatTokenizerAdapter(inner: tokenizer))
      if let recovered = rescue.rehydratePrompt(query: userMessage.content) {
          messages.insert(.system(recovered), at: messages.count - 1)
      }
  }

Tokenizer adapter is file-scope (Swift doesn't allow types nested
in closures in generic contexts). Forwards decode(tokens:) to
swift-transformers' Tokenizer.decode(tokenIds:skipSpecialTokens:).

Tier 3 system message is EPHEMERAL — inserted before the user
message in the prompt rendered to the model, but the underlying
session history is untouched. Each turn re-fetches from longctx-svc
based on that turn's user query. Mirrors AMD's
prefill_rehydrate.maybe_rehydrate_messages semantics.

Net for the M5 stack: enable VLLM_TRIATT_ENABLED=1 + set
LONGCTX_ENDPOINT, run a ChatSession against any Qwen3 model, and the
full 3-tier rescue stack runs end-to-end with no per-driver wiring.

Doesn't address audit point #4 (post-compaction position translation
across multi-eviction-round prefills) — that landed at 5ede7a1.

13/13 TriAttention tests still green on M5 :9091. Production rescue
path is now a one-flag flip for any ChatSession user.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: tturney <tturney@psyguard.ai>
TheTom added a commit that referenced this pull request May 16, 2026
8-iteration sprint at 16K Qwen2.5-14B-1M-4bit on M5 Max:

Baseline (V20, post compiled-swiglu): 32.7 ms/step decode.
After sprint: 24.8 ms/step pipelined.
Python mlx-lm pipelined: 22.7 ms.

Two real wins, six dead ends:

LANDED:
- Sprint iter #1 — `sysmemSnapshot()` forks `vm_stat` from inside the
  t0..t1 timing window. Moved t1 capture to immediately after eval().
  Save: 2 ms (32.7 → 30.4).
- Sprint iter ekryski#6/ekryski#7 — pipelined decode loop. `model + argMax + asyncEval(tok)`
  then `eval(queuedTok)` of the previous step. Pre-queue one step before
  the timing loop so the GPU is already in flight on the first sample.
  Save: 5.6 ms (30.4 → 24.8). Matches mlx-lm Python's generation_stream
  pipeline pattern.

NO-OP:
- Sprint iter #2 — MLX_METAL_AB=1 / MLX_PERSISTENT_AB=1 env. Qwen2's
  K=5120/13824 doesn't trip qmv_quad fast path (qmv_quad is K=64/128).
- Sprint iter #3 — F83_DECODE_STREAM=1 (decode loop on dedicated GPU
  stream). MLX-swift apparently already isolates kernel dispatch from
  default stream housekeeping at decode shape.
- Sprint iter #4 — MLX_INLINE_ACTIVATION=1 (Gemma FusedGateUpSwitchGLU
  env). Qwen2 doesn't use the FusedGateUpSwitchGLU path.
- Sprint iter ekryski#5 — fused gate+up via sanitize-time weight concat.
  Concat works correctly, but MLX.split apparently dispatches, offsetting
  the matmul saving. Kept in tree as `Qwen2.MLP` now uses `gate_up_proj`
  weight + split; harmless.
- Sprint iter ekryski#8 — removed logLine from inside timing loop. Within noise.

Remaining 2.1 ms / 9% gap to Python pipelined is most likely Swift-side
per-call overhead (Module/@ModuleInfo dispatch, MLXArray ARC) on the
identical MLX C++ kernel path. Closing it requires either a custom
fused MLP Metal kernel binding (the C++ `fused_gate_activation` is in
mlx-swift but has no Swift wrapper) or further reducing the
per-decode-step dispatch count.

Env knobs added (opt-in, default off):
- F83_PIPELINE=1 — pipelined decode loop (new default for this bench
  going forward as it matches mlx-lm Python's measurement style).

Co-Authored-By: Claude Opus 4.7 (1M context) <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.

6 participants