Skip to content

Benchmark build tooling + 3.x loader migration + hardware-dated baselines - #47

Merged
ekryski merged 5 commits into
alphafrom
ek/update-benchmark-build-tooling
Apr 16, 2026
Merged

ekryski merged 5 commits into
alphafrom
ek/update-benchmark-build-tooling

Conversation

@ekryski

@ekryski ekryski commented Apr 16, 2026 •

Copy link
Copy Markdown
Owner

Summary

Brings benchmark build + harness tooling onto the alpha branch, migrates the benchmark test target to the 3.x LLMModelFactory.loadContainer(from:using:...) API, and introduces a hardware-dated multi-model report layout.

Five logical commits; each compiles independently.

  • 442c624 build: add Makefile + scripts/setup-dev.sh adapted for alpha's split prefill_bridge_gemma + prefill_bridge_qwen dylibs.
  • ad50733 docs: merge Why make + Testing + Benchmarking sections into README.md (keeps alpha's existing 3.x migration content intact).
  • 1210303 bench: rewrite BenchmarkWriter to produce benchmarks/{chip}-{ram}-{date}.md (flat layout, JSON state sidecar, per-model grouping), teach scripts/benchmark.sh to sweep the Cartesian product of --model × --method × --quant × --kv, and replace the empty benchmarks/README.md with a full CLI / env-var / KV config / output / cache docs reference.
  • a16b8dd bench: delete ~190 lines of pre-3.x loader shims (HFDownloader shell-out to huggingface-cli, hand-rolled TokenizerBridge, the LLMModelFactory.loadContainer(configuration:) compat extension, dead SimpleJSONTokenizer) and replace with #hubDownloader() + #huggingFaceTokenizerLoader() from MLXHuggingFace. Matches the pattern in IntegrationTesting/IntegrationTestingTests/ToolCallIntegrationTests.swift. Also fixes a latent Swift 6 Sendable error in the batched task group.
  • 227df26 bench: commit the first two baselines (m1-max-64gb-2026-04-16.md from this PR's session sweep, m5-max-128gb-2026-04-16.md carried over from docs: add M5 Max 128GB benchmark baseline (2026-04-16) #46 in its original hand-curated format) and add benchmarks/.*.state.json to .gitignore.

Why

  1. Alpha is on swift-tools-version: 6.1 (strict Swift 6 concurrency). The existing @testable import MLXLMCommon + Tests/Benchmarks/InferenceBenchmark.swift shim path hit Sendable hard errors on the batched task group and used a huggingface-cli subprocess that failed under swift test's minimal PATH.
  2. The existing writer produced one .md per (model, quant, kv, method) run. Sweeps across models or KV configs produced a pile of files instead of a single comparable report. The new writer groups rows by model in one hardware-dated file — exactly what the multi-model baselines format needs.
  3. benchmarks/README.md was ~empty; full docs were scattered across commit messages. Now consolidated: CLI flags, env vars, all 11 KV configs, output file layout, and HF cache resolution (HF_HUB_CACHE / HF_HOME / default, Python-compat, cache-first behaviour).
  4. The benchmark harness was carrying pre-alpha loader shims even though alpha already ships MLXHuggingFace macros + HubClient from swift-huggingface. The shims are net debt.

Verified on this branch

  • Fresh clone simulation: rm -rf .build/ && ./scripts/setup-dev.sh → SPM resolve + Cmlx + Metal shader compile all succeed; test bundle staged with mlx.metallib.
  • Non-benchmark suite: xcodebuild test -scheme mlx-swift-lm-Package -only-testing MLXLMTests → TEST SUCCEEDED (54 tests in 4 suites passed in 41s, including SpeculativeDecodingTests).
  • Cached load path: Qwen3.5-0.8B-bf16 from ~/.cache/huggingface/hub — 0 network, 210/102 tok/s prefill/decode, coherent output.
  • Fresh download path: Qwen3.5-0.8B-4bit (not previously in cache) — downloaded via HubClient + URLSession, cache populated, 231/134 tok/s.
  • Multi-model + multi-quant + multi-KV sweep: ./scripts/benchmark.sh --model qwen35-0.8b,qwen35-2b --quant 4bit,8bit --kv none,turbo4v2 --think --kld --ppl --context 128 → 8/8 runs succeeded, all downloads native, output grouped into one m1-max-64gb-2026-04-16.md file with two ### {Model} subsections and one combined #### Results table per model.

Known gap flagged in commit 3

Think PPL / Gen PPL / Think KLD / Gen KLD columns currently render —. This is not a harness wiring bug — the CLI flags, env vars, and GenerateParameters.trackPerplexity / collectPerTokenData are plumbed through correctly. The GenerateCompletionInfo.thinkingPerplexity / .generationPerplexity / .perTokenLogProbs / .perTokenIds / .perTokenPhases struct fields exist on alpha but are declared-only — no generation-loop code populates them. Flagged as a follow-up; the harness will surface real values once the library-side instrumentation lands.

Test plan

  • ./scripts/setup-dev.sh from a fresh clone (rebuilds cleanly).
  • xcodebuild test -scheme mlx-swift-lm-Package -only-testing MLXLMTests still green on the merge commit.
  • ./scripts/benchmark.sh --model qwen35-0.8b --quant 4bit --kv turbo4v2 --context 128 produces a single-row entry in benchmarks/{chip}-{ram}-{date}.md with the new layout.
  • ./scripts/benchmark.sh --model qwen35-0.8b,qwen35-2b --kv none,turbo4v2 --quick produces two ### {Model} subsections in one file, Cartesian-product rows grouped correctly.
  • benchmarks/.m1-max-64gb-2026-04-16.state.json stays out of git on subsequent runs.

ekryski and others added 5 commits April 16, 2026 12:07
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 #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>
@TheTom

TheTom commented Apr 16, 2026

Copy link
Copy Markdown

great cleanup, the hardware-dated layout is much better than the one-file-per-config sprawl.

one thing that jumped out in m1-max-64gb: the prefill/decode trade-off with turbo4v2 flips between 4bit and 8bit at 4k ctx. 4bit goes 133→177 prefill, -2% decode. 8bit goes 172→150 prefill, +25% decode. same model, same config, opposite outcome. was this a single-shot sweep or did you see it across multiple runs?

also happy to help wire the generation-loop side of Think/Gen PPL + KLD if that would unblock filling those columns. without them the table is really just a speed readout.

@ekryski

ekryski commented Apr 16, 2026

Copy link
Copy Markdown
Owner Author

great cleanup, the hardware-dated layout is much better than the one-file-per-config sprawl.

one thing that jumped out in m1-max-64gb: the prefill/decode trade-off with turbo4v2 flips between 4bit and 8bit at 4k ctx. 4bit goes 133→177 prefill, -2% decode. 8bit goes 172→150 prefill, +25% decode. same model, same config, opposite outcome. was this a single-shot sweep or did you see it across multiple runs?

also happy to help wire the generation-loop side of Think/Gen PPL + KLD if that would unblock filling those columns. without them the table is really just a speed readout.

Single shot. Probably just noise or some contention/thermals. I have a lot more running right now that other times I've done benches. Was more focused on correct output than correct numbers. Will run proper benches this evening and while debugging Qwen prefill issues.

@ekryski
ekryski merged commit d6ed784 into alpha Apr 16, 2026
@ekryski
ekryski deleted the ek/update-benchmark-build-tooling branch April 16, 2026 19:32
@ekryski

ekryski commented Apr 16, 2026

Copy link
Copy Markdown
Owner Author

I have a separate PR for KLD and PPL here: #48

Also worth noting that my numbers were with the default max_ops_per_buffer which we know is slow. Will change that as part of the Qwen3.5 prefill fixes (because that is part of it).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants