From 442c624287ce335fcd2a3b6fcced2720fc289b5d Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Thu, 16 Apr 2026 12:07:22 -0600 Subject: [PATCH 1/5] build: add Makefile and setup-dev.sh for alpha 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) --- Makefile | 268 +++++++++++++++++++++++++++++++++++++++++++ scripts/setup-dev.sh | 84 ++++++++++++++ 2 files changed, 352 insertions(+) create mode 100644 Makefile create mode 100755 scripts/setup-dev.sh diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000..e5e6781e1a --- /dev/null +++ b/Makefile @@ -0,0 +1,268 @@ +# Makefile — Smart build orchestrator for mlx-swift-lm +# +# Swift Package Manager doesn't track Metal shaders, native dylibs, or changes +# deep in git submodules (mlx, mlx-c). This Makefile fills the gaps using +# file-timestamp dependencies so only stale targets rebuild. +# +# Quick reference: +# make — full incremental build for tests/benchmarks +# make metal — recompile Metal shaders only +# make bridge — recompile prefill bridge dylib only +# make spm — Swift build only (with Cmlx cache invalidation) +# make status — show what's built and what's stale +# make clean — remove build artifacts (keep checkouts) +# make clean-all — full reset (re-fetches dependencies) +# make clean-cmlx — force SPM to recompile C/C++ on next build + +SHELL := /bin/bash +.DEFAULT_GOAL := build-tests + +# ─── Configuration ──────────────────────────────────────────────────────────── + +PROJECT_ROOT := $(CURDIR) +BUILD_DIR := $(PROJECT_ROOT)/.build +STAMP_DIR := $(BUILD_DIR)/.stamps +RELEASE_DIR := $(BUILD_DIR)/arm64-apple-macosx/release +XCTEST_DIR := $(RELEASE_DIR)/mlx-swift-lmPackageTests.xctest/Contents/MacOS + +CONFIG ?= release +SWIFT_FLAGS ?= -Xswiftc -enable-testing + +# ─── Locate mlx-swift (local override > sibling > SPM checkout) ─────────────── + +MLX_SWIFT_DIR := $(or \ + $(wildcard $(MLX_SWIFT_PATH)), \ + $(wildcard $(PROJECT_ROOT)/../mlx-swift), \ + $(BUILD_DIR)/checkouts/mlx-swift) + +METAL_SRC_DIR := $(MLX_SWIFT_DIR)/Source/Cmlx/mlx-generated/metal +CMLX_SRC_DIR := $(MLX_SWIFT_DIR)/Source/Cmlx + +# ─── Source file discovery (evaluated each invocation) ──────────────────────── +# Make re-expands $(shell ...) every time you run `make`, so new/deleted files +# are picked up automatically. + +METAL_SOURCES := $(shell find "$(METAL_SRC_DIR)" \( -name '*.metal' -o -name '*.h' \) -type f 2>/dev/null) +CMLX_SOURCES := $(shell find "$(CMLX_SRC_DIR)/mlx" "$(CMLX_SRC_DIR)/mlx-c" \ + \( -name '*.cpp' -o -name '*.c' -o -name '*.h' \) -type f 2>/dev/null) +SWIFT_SOURCES := $(shell find "$(PROJECT_ROOT)/Libraries" "$(PROJECT_ROOT)/Sources" \ + -name '*.swift' -type f 2>/dev/null) + +# NativePrefillBridge C++ — SPM compiles these; list them so `make` reruns swift build when they change. +NATIVE_PREFILL_SOURCES := $(shell find "$(PROJECT_ROOT)/Sources/NativePrefillBridge" \ + \( -name '*.cpp' -o -name '*.h' \) -type f 2>/dev/null) + +# Bridge sources — alpha has split gemma + qwen bridges that share generic_prefill. +BRIDGE_SRC_DIR := $(PROJECT_ROOT)/Sources/NativePrefillBridge +BRIDGE_SRCS := $(BRIDGE_SRC_DIR)/prefill_bridge_gemma.cpp \ + $(BRIDGE_SRC_DIR)/prefill_bridge_qwen.cpp \ + $(BRIDGE_SRC_DIR)/generic_prefill.cpp +BRIDGE_HDRS := $(BRIDGE_SRC_DIR)/prefill_bridge_gemma.h \ + $(BRIDGE_SRC_DIR)/prefill_bridge_qwen.h \ + $(BRIDGE_SRC_DIR)/generic_prefill.h +BRIDGE_DYLIBS := $(BRIDGE_SRC_DIR)/libprefill_bridge_gemma.dylib \ + $(BRIDGE_SRC_DIR)/libprefill_bridge_qwen.dylib + +# Output artifacts +METALLIB := $(RELEASE_DIR)/mlx.metallib +BRIDGE_RELEASES := $(RELEASE_DIR)/libprefill_bridge_gemma.dylib \ + $(RELEASE_DIR)/libprefill_bridge_qwen.dylib + +# Stamp files — touch-files that record when each step last succeeded +STAMP_METAL := $(STAMP_DIR)/metallib +STAMP_SPM := $(STAMP_DIR)/spm-build +STAMP_BRIDGE := $(STAMP_DIR)/prefill-bridge +STAMP_CMLX := $(STAMP_DIR)/cmlx-check + +# ─── Directory creation ────────────────────────────────────────────────────── + +$(STAMP_DIR): + @mkdir -p $@ + +# ─── Metal shader compilation ──────────────────────────────────────────────── +# SPM cannot compile .metal files. We compile them into mlx.metallib ourselves. +# Only recompiles when a .metal or kernel .h file changes. + +.PHONY: metal +metal: $(STAMP_METAL) + +$(STAMP_METAL): $(METAL_SOURCES) | $(STAMP_DIR) + @echo "==> Metal sources changed — recompiling shaders..." + @bash "$(PROJECT_ROOT)/scripts/build-metallib.sh" $(CONFIG) + @touch $@ + +# ─── Cmlx cache invalidation ──────────────────────────────────────────────── +# When C/C++ files inside the mlx or mlx-c submodules change, SPM's build.db +# may still consider Cmlx "up to date" (it caches content signatures keyed by +# the dependency revision in workspace-state.json). +# +# Fix: delete just .build/.../Cmlx.build/ — this forces SPM to recompile the +# C target on the next `swift build` while leaving all Swift targets cached. + +$(STAMP_CMLX): $(CMLX_SOURCES) | $(STAMP_DIR) + @if [ -f "$@" ] && [ -d "$(RELEASE_DIR)/Cmlx.build" ]; then \ + echo "==> Cmlx sources changed since last build — invalidating SPM Cmlx cache..."; \ + rm -rf "$(RELEASE_DIR)/Cmlx.build"; \ + elif [ ! -f "$@" ]; then \ + echo "==> Seeding Cmlx stamp (first run — not invalidating existing cache)"; \ + fi + @touch $@ + +# ─── SPM build ─────────────────────────────────────────────────────────────── +# Runs `swift build --build-tests` only if Swift sources changed OR the Cmlx +# cache was invalidated (which updates the STAMP_CMLX sentinel). + +.PHONY: spm +spm: $(STAMP_SPM) + +$(STAMP_SPM): $(SWIFT_SOURCES) $(NATIVE_PREFILL_SOURCES) $(STAMP_CMLX) | $(STAMP_DIR) + @echo "==> Building Swift targets ($(CONFIG))..." + swift build --build-tests -c $(CONFIG) $(SWIFT_FLAGS) + @touch $@ + +# ─── Prefill bridge dylib ─────────────────────────────────────────────────── +# Compiled via clang++ against MLX. Only rebuilds when source or header changes. + +.PHONY: bridge +bridge: $(STAMP_BRIDGE) + +$(STAMP_BRIDGE): $(BRIDGE_SRCS) $(BRIDGE_HDRS) | $(STAMP_DIR) + @echo "==> Prefill bridge source changed — recompiling dylibs..." + @bash "$(PROJECT_ROOT)/scripts/build-prefill-bridge.sh" + @touch $@ + +# ─── Artifact installation ────────────────────────────────────────────────── +# Copies metallib and dylib into .build/release/ and the .xctest bundle. +# Must run AFTER spm because `swift build --build-tests` can regenerate the +# test bundle directory, wiping previously-copied files. + +.PHONY: install-artifacts +install-artifacts: $(STAMP_SPM) $(STAMP_METAL) + @mkdir -p "$(RELEASE_DIR)" + @# --- metallib --- + @if [ -f "$(METALLIB)" ] && [ -d "$(XCTEST_DIR)" ]; then \ + cp "$(METALLIB)" "$(XCTEST_DIR)/mlx.metallib"; \ + echo " copied mlx.metallib -> test bundle"; \ + fi + @# --- bridge dylibs -> release dir + test bundle --- + @for dylib in $(BRIDGE_DYLIBS); do \ + if [ -f "$$dylib" ]; then \ + name=$$(basename "$$dylib"); \ + cp "$$dylib" "$(RELEASE_DIR)/$$name"; \ + echo " copied $$name -> $(RELEASE_DIR)/"; \ + if [ -d "$(XCTEST_DIR)" ]; then \ + cp "$$dylib" "$(XCTEST_DIR)/$$name"; \ + echo " copied $$name -> test bundle"; \ + fi; \ + fi; \ + done + +# ─── Main targets ─────────────────────────────────────────────────────────── + +.PHONY: build +# NativePrefillBridge C++ is built via SPM (`swift build`). Optional standalone gemma/qwen bridge dylibs: `make bridge`. +build: spm metal + +.PHONY: build-tests +build-tests: build install-artifacts + @echo "" + @echo "Build complete — all artifacts in place." + +# ─── Clean targets ─────────────────────────────────────────────────────────── + +.PHONY: clean +clean: + swift package clean + rm -rf "$(STAMP_DIR)" + @echo "Cleaned build artifacts. Dependency checkouts preserved." + +.PHONY: clean-all +clean-all: + swift package reset + rm -rf "$(STAMP_DIR)" + @echo "Full reset. Run 'swift package resolve' or 'make' to re-fetch." + +# Surgical: force SPM to recompile just the C/C++ target on next build +.PHONY: clean-cmlx +clean-cmlx: + rm -rf "$(RELEASE_DIR)/Cmlx.build" + rm -f "$(STAMP_CMLX)" "$(STAMP_SPM)" + @echo "Cmlx cache invalidated. Next 'make' will recompile C/C++ sources." + +.PHONY: clean-metal +clean-metal: + rm -f "$(METALLIB)" + rm -f "$(STAMP_METAL)" + @echo "Metal cache cleared. Next 'make' will recompile shaders." + +.PHONY: clean-bridge +clean-bridge: + rm -f $(BRIDGE_DYLIBS) $(BRIDGE_RELEASES) + rm -f "$(STAMP_BRIDGE)" + @echo "Bridge cache cleared. Next 'make bridge' will recompile dylibs." + +# ─── Status ────────────────────────────────────────────────────────────────── + +.PHONY: status +status: + @echo "mlx-swift-lm build status" + @echo "=========================" + @echo "" + @echo "mlx-swift location: $(MLX_SWIFT_DIR)" + @echo "" + @echo "Stamps (last successful build):" + @if [ -d "$(STAMP_DIR)" ]; then \ + for f in $(STAMP_DIR)/*; do \ + [ -f "$$f" ] && echo " $$(basename $$f): $$(stat -f '%Sm' -t '%Y-%m-%d %H:%M:%S' $$f)"; \ + done; \ + else \ + echo " (none — run 'make' to build)"; \ + fi + @echo "" + @echo "Artifacts:" + @[ -f "$(METALLIB)" ] \ + && echo " mlx.metallib (release): OK" \ + || echo " mlx.metallib (release): MISSING" + @[ -f "$(XCTEST_DIR)/mlx.metallib" ] 2>/dev/null \ + && echo " mlx.metallib (test bundle): OK" \ + || echo " mlx.metallib (test bundle): MISSING" + @for dylib in $(BRIDGE_DYLIBS); do \ + name=$$(basename "$$dylib"); \ + [ -f "$$dylib" ] \ + && echo " $$name (source): OK" \ + || echo " $$name (source): MISSING"; \ + done + @for dylib in $(BRIDGE_RELEASES); do \ + name=$$(basename "$$dylib"); \ + [ -f "$$dylib" ] \ + && echo " $$name (release): OK" \ + || echo " $$name (release): MISSING"; \ + done + @echo "" + @echo "SPM Cmlx cache:" + @[ -d "$(RELEASE_DIR)/Cmlx.build" ] \ + && echo " Cmlx.build: present ($$(du -sh "$(RELEASE_DIR)/Cmlx.build" | cut -f1))" \ + || echo " Cmlx.build: empty (will recompile on next build)" + +# ─── Help ──────────────────────────────────────────────────────────────────── + +.PHONY: help +help: + @echo "mlx-swift-lm build targets:" + @echo "" + @echo " make Full incremental build for tests/benchmarks" + @echo " make spm Swift build (Swift + NativePrefillBridge C++, Cmlx invalidation)" + @echo " make metal Recompile Metal shaders only" + @echo " make bridge Build standalone prefill_bridge_gemma + prefill_bridge_qwen dylibs" + @echo " make status Show build state and artifact locations" + @echo "" + @echo " make clean Remove build artifacts (keep dependency checkouts)" + @echo " make clean-all Full reset (re-fetches everything)" + @echo " make clean-cmlx Force recompile of C/C++ sources (mlx, mlx-c)" + @echo " make clean-metal Force recompile of Metal shaders" + @echo " make clean-bridge Force recompile of prefill bridge" + @echo "" + @echo "Environment:" + @echo " MLX_SWIFT_PATH Override mlx-swift dependency location" + @echo " CONFIG release (default) or debug" + @echo " SWIFT_FLAGS Extra flags for swift build" diff --git a/scripts/setup-dev.sh b/scripts/setup-dev.sh new file mode 100755 index 0000000000..4ed5aca35d --- /dev/null +++ b/scripts/setup-dev.sh @@ -0,0 +1,84 @@ +#!/bin/bash +# setup-dev.sh +# Development environment setup for mlx-swift-lm. +# Compiles MLX Metal shaders and builds test targets for benchmarking. +# +# Run once after cloning or after fetching new mlx-swift changes: +# ./scripts/setup-dev.sh + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" + +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +ok() { echo -e "${GREEN} ✓${NC} $1"; } +warn() { echo -e "${YELLOW} ⚠${NC} $1"; } +fail() { echo -e "${RED} ✗${NC} $1"; exit 1; } + +echo "" +echo "Setting up mlx-swift-lm development environment..." +echo "" + +# ───────────────────────────────────────────── +# Prerequisites +# ───────────────────────────────────────────── +echo "Checking prerequisites..." + +# Xcode Command Line Tools +if ! xcode-select -p &>/dev/null; then + fail "Xcode Command Line Tools not found. Install with: xcode-select --install" +fi +ok "Xcode CLI tools: $(xcode-select -p)" + +# xcrun (Metal compiler) +if ! xcrun --find metal &>/dev/null 2>&1; then + fail "xcrun metal not found. Install Xcode or Xcode Command Line Tools." +fi +ok "xcrun metal: available" + +# Swift +if ! command -v swift &>/dev/null; then + fail "Swift not found. Install Xcode or Swift toolchain." +fi +SWIFT_VERSION=$(swift --version 2>&1 | grep -oE 'Swift version [0-9]+\.[0-9]+' | head -1) +ok "Swift: $SWIFT_VERSION" + +# ───────────────────────────────────────────── +# Resolve packages +# ───────────────────────────────────────────── +echo "" +echo "Resolving Swift package dependencies..." +cd "$PROJECT_ROOT" +swift package resolve +ok "Packages resolved" + +# ───────────────────────────────────────────── +# Build (SPM + Metal shaders + native dylibs) +# ───────────────────────────────────────────── +echo "" +echo "Building (make build-tests)..." +make -C "$PROJECT_ROOT" build-tests +ok "Build complete — all artifacts in place" + +# ───────────────────────────────────────────── +# Done +# ───────────────────────────────────────────── +echo "" +echo -e "${GREEN}✅ Setup complete!${NC}" +echo "" +echo "Run a quick benchmark:" +echo " ./scripts/benchmark.sh --model qwen35-0.8b --context 128" +echo "" +echo "Run a comprehensive benchmark sweep:" +echo " ./scripts/benchmark.sh --model qwen35-2b --quant all --kv all --quick" +echo "" +echo "See benchmarks/README.md for the full CLI reference." +echo "" +echo "Note: For unit tests (non-benchmark), use xcodebuild:" +echo " xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS'" +echo "" From ad507331cbf67b6fa3ae2808025732e4d37a4f29 Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Thu, 16 Apr 2026 12:07:36 -0600 Subject: [PATCH 2/5] docs: add make, testing, and benchmarking sections to README MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- README.md | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/README.md b/README.md index b45683fdcf..60300d648b 100644 --- a/README.md +++ b/README.md @@ -265,6 +265,93 @@ let text = tokenizer.decode(tokens: ids) let text = tokenizer.decode(tokenIds: ids) ``` +## Development Setup + +Run once after cloning (or after fetching new `mlx-swift` changes): + +```bash +./scripts/setup-dev.sh +``` + +### Why `make` instead of `swift build` + +Swift Package Manager (SPM) does not handle several parts of this repo's build pipeline: + +- **Metal shaders** — SPM cannot compile `.metal` files. The MLX Metal kernels must be compiled separately into `mlx.metallib` and copied into the test bundle. +- **Native C++ dylibs** — The prefill bridges (`libprefill_bridge_gemma.dylib`, `libprefill_bridge_qwen.dylib`) are built via `clang++` and must be placed in the build output and test bundle manually. +- **Submodule staleness** — When you modify C/C++ files deep in git submodules (`mlx-swift` → `mlx` → `mlx-c`), SPM's build cache may not detect the change. It tracks content signatures keyed by the dependency's git revision, so edits within a submodule can go stale. +- **Test bundle regeneration** — `swift build --build-tests` can regenerate the `.xctest` bundle, wiping previously-copied Metal shaders and dylibs. + +The project [Makefile](Makefile) wraps SPM and fills these gaps using file-timestamp dependency tracking. It only rebuilds what actually changed: + +| What changed | What rebuilds | What stays cached | +|---|---|---| +| A `.metal` or kernel `.h` file | Metal shaders only | SPM targets, bridge dylibs | +| A `.cpp`/`.c`/`.h` in `mlx` or `mlx-c` | SPM's Cmlx target only | Swift targets, Metal, bridges | +| Swift sources | SPM incremental rebuild | Metal, bridges | +| A bridge `.cpp`/`.h` in `Sources/NativePrefillBridge/` | Bridge dylibs only | SPM, Metal | +| Nothing | Artifact copy only (~instant) | Everything | + +After every build, artifacts (metallib, dylibs) are copied to the release directory and test bundle automatically. + +You do not need to use `make` directly for typical workflows — `setup-dev.sh` and `benchmark.sh` both call it internally. For manual builds or targeted rebuilds, see `make help`. + +#### Manual builds + +For targeted rebuilds when working on specific parts of the stack: + +```bash +make # Full incremental build (only rebuilds what changed) +make metal # Recompile Metal shaders only +make bridge # Recompile prefill bridge dylibs only +make spm # Swift build only (with Cmlx cache invalidation) +make status # Show what's built and what's stale +make clean-cmlx # Force SPM to recompile C/C++ on next build +make help # Full reference +``` + +## Testing + +Tests require Metal and must be run via Xcode's build system so that the MLX Metal shaders (`default.metallib`) are built and available. Running `swift test` directly will fail with "Failed to load the default metallib" because SwiftPM does not build Metal shaders. + +In Xcode: open the package and run tests (Cmd-U), or from the command line: + +```bash +xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS' +``` + +Benchmarks are an exception — they're gated behind a Swift Testing filter (`swift test --filter benchmark`) and invoked via `./scripts/benchmark.sh`, which handles the Metal shader build via `make`. See the next section. + +## Benchmarking + +Inference benchmarks measure prefill throughput, decode tok/s, TTFT, perplexity, KL divergence, and GPU memory across models, quantization levels, and KV cache configurations. Benchmarks run in **release mode** and write markdown reports to `benchmarks/`. + +See [`benchmarks/README.md`](benchmarks/README.md) for the complete CLI reference, methodology details, and environment variable API. + +This resolves Swift packages, compiles Metal shaders, does an initial release build, and copies all artifacts into the test bundle. After setup, all benchmark commands work immediately. + +### Basic benchmark + +Benchmark any registered model family or HuggingFace repo directly: + +```bash +# Known model family (downloads automatically on first run) +./scripts/benchmark.sh --model qwen35-0.8b --context 128 + +# Any HuggingFace model by repo ID +./scripts/benchmark.sh --model mlx-community/Qwen3-4B-4bit --context 128 + +# With perplexity tracking +./scripts/benchmark.sh --model mlx-community/Qwen3-4B-4bit --context 128 --ppl + +# Multi-model sweep — all rows land in one hardware-dated report file +./scripts/benchmark.sh --model qwen35-0.8b,qwen35-2b --kv none,turbo4v2 --quick +``` + +Results are saved as hardware-dated markdown files in `benchmarks/`, one file per sweep per day (e.g. `benchmarks/m1-max-64gb-2026-04-16.md`). All runs for the same model across the sweep are grouped together in that file. + +For more advanced benchmark combinations and options see [`benchmarks/README.md`](benchmarks/README.md). + ## Documentation Developers can use these examples in their own programs -- just import the swift package! From 12103033ad94b4794c0188b7033a3285ff833051 Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Thu, 16 Apr 2026 12:08:04 -0600 Subject: [PATCH 3/5] bench: hardware-dated writer, multi-config sweeps, new README MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- Tests/Benchmarks/Utils/BenchmarkWriter.swift | 554 ++++++++++++------ Tests/Benchmarks/baselines/README.md | 35 -- .../baselines/m5-max-128gb-2026-04-16.md | 297 ---------- benchmarks/README.md | 429 ++++++++++++++ scripts/benchmark.sh | 192 +++--- 5 files changed, 897 insertions(+), 610 deletions(-) delete mode 100644 Tests/Benchmarks/baselines/README.md delete mode 100644 Tests/Benchmarks/baselines/m5-max-128gb-2026-04-16.md create mode 100644 benchmarks/README.md diff --git a/Tests/Benchmarks/Utils/BenchmarkWriter.swift b/Tests/Benchmarks/Utils/BenchmarkWriter.swift index f383fa18da..7364f0e55f 100644 --- a/Tests/Benchmarks/Utils/BenchmarkWriter.swift +++ b/Tests/Benchmarks/Utils/BenchmarkWriter.swift @@ -2,35 +2,36 @@ import Foundation import MLX import MLXLMCommon -/// Writes benchmark results to markdown files in benchmarks/. +/// Writes benchmark results to a single hardware-dated markdown file under `benchmarks/`. /// -/// Each run creates one file per model with context scaling table and special test results. -/// Filename: `YYYY-MM-DD-HHmm-{model-slug}-benchmark.md` +/// File naming: `{chip-slug}-{ram}gb-{YYYY-MM-DD}.md` +/// Example: `m1-max-64gb-2026-04-16.md`, `m5-max-128gb-2026-04-16.md` +/// +/// Multiple runs (across models, quantizations, KV configs, methods) accumulate into the +/// same file, grouped by model. State lives in a `.{filename}.state.json` sidecar so the +/// markdown can be re-rendered deterministically and runs in separate `swift test` +/// invocations (as the CLI does for multi-model sweeps) continue to append into the +/// same file. +/// +/// See `benchmarks/README.md#output` for the on-disk layout. enum BenchmarkWriter { private static let lock = NSLock() - /// Track which files have been initialized (header written) this session - nonisolated(unsafe) private static var initializedFiles: Set = [] + + // MARK: - Public append API (unchanged signature) /// Generation + runner metadata for the benchmark markdown header. struct BenchmarkParameters { - /// Exact ``GenerateParameters`` passed to `ModelContainer.generate` (or equivalent for wikitext2 cache). let generate: GenerateParameters - /// Effective thinking mode (model supports it and MLX_BENCH_THINK=1). let thinkingEnabled: Bool - /// Thinking-budget processor cap when thinking is active; nil otherwise. let thinkingTokenBudget: Int? - /// KL divergence env + whether it applies to this benchmark method/config. let kldSummary: String - /// Effective max ops per buffer: env override or hardware default (see `resolvedMaxOpsPerBufferReport()`). let maxOpsPerBuffer: String let batchSize: Int - /// e.g. none, ngram (size=…), draft (repo-id). let speculativeDecoding: String - /// Short description for `## System prompt` (no full user prompt text). let systemPromptSummary: String } - /// Append a benchmark result row to the model's markdown file. + /// Append a benchmark result row to the session's markdown file. static func append( model: String, repoId: String = "", @@ -54,100 +55,309 @@ enum BenchmarkWriter { outputPreview: String, parameters: BenchmarkParameters? = nil ) { - let slug = model - .replacingOccurrences(of: " ", with: "-") - .lowercased() - .replacingOccurrences(of: "/", with: "-") - let dir = benchmarkDir(modelSlug: slug) - let dateStr = Self.sessionDateString - let method = ProcessInfo.processInfo.environment["MLX_BENCH_METHOD"] ?? "simple" - let filename = "\(slug)-\(quantization)-\(kvConfig)-\(method)-benchmark-\(dateStr).md" - let path = dir.appendingPathComponent(filename) - lock.lock() defer { lock.unlock() } - // Write header on first append for this file - if !initializedFiles.contains(filename) { - initializedFiles.insert(filename) - - let branch = gitBranch() - let commit = gitLastCommitLine() - let hw = hardwareInfo() - - var header = "# Inference Benchmark - \(model)\n\n" - header += "- **Date**: \(Self.humanDateString)\n" - header += "- **Branch**: `\(branch)`\n" - header += "- **Commit**: \(commit)\n" - header += "- **Quantization**: \(quantization)\n" - if !repoId.isEmpty { - header += "- **Model**: `\(repoId)`\n" - } - header += "\n" - header += "## Hardware\n\n" - header += "| Property | Value |\n" - header += "|----------|-------|\n" - header += "| Chip | \(hw.chip) |\n" - header += "| System RAM | \(hw.systemRAM) |\n" - header += "| GPU Memory Limit | \(hw.gpuLimit) |\n" - header += "| macOS | \(hw.osVersion) |\n" - header += "\n" - if let p = parameters { - header += "## Parameters\n\n" - header += "| Parameter | Value |\n" - header += "|-----------|-------|\n" - appendGenerateParametersRows(to: &header, params: p.generate) - if let budget = p.thinkingTokenBudget { - header += "| Thinking token budget (processor) | \(budget) |\n" + let hw = hardwareInfo() + let filename = sessionFilename(hw: hw) + let projectRoot = Self.projectRoot() + let markdownURL = projectRoot + .appendingPathComponent("benchmarks") + .appendingPathComponent(filename + ".md") + let sidecarURL = projectRoot + .appendingPathComponent("benchmarks") + .appendingPathComponent("." + filename + ".state.json") + + try? FileManager.default.createDirectory( + at: markdownURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + + var state = loadState(from: sidecarURL) ?? SessionState( + chip: hw.chip, + gpuArch: GPU.deviceInfo().architecture, + systemRAM: hw.systemRAM, + gpuLimit: hw.gpuLimit, + osVersion: hw.osVersion, + branch: gitBranch(), + commit: gitLastCommitLine(), + naxEnabled: detectNAX(), + createdAt: isoDateTime(Date()), + models: [] + ) + + let row = ResultRow( + contextSize: contextSize, + promptTokens: promptTokens, + prefillTokPerSec: prefillTokPerSec, + decodeTokPerSec: genTokPerSec, + genTokens: genTokens, + ttftMs: ttftMs, + thinkPPL: thinkingPerplexity, + genPPL: generationPerplexity, + thinkKLD: thinkingKLD, + genKLD: generationKLD, + baselineGPU: baselineGPU, + peakGPU: peakGPU, + kvDelta: kvDelta, + kvCacheBytes: kvCacheBytes + ) + + let configKey = "\(quantization) / \(kvConfig) / \(scenario)" + var paramRows: [[String]] = [] + var systemPrompt = "" + if let p = parameters { + paramRows = buildParameterRows(p) + systemPrompt = p.systemPromptSummary + } + + // Locate or create model entry (preserves insertion order). + if let mi = state.models.firstIndex(where: { $0.displayName == model }) { + if let ci = state.models[mi].configs.firstIndex(where: { $0.key == configKey }) { + state.models[mi].configs[ci].rows.append(row) + if state.models[mi].configs[ci].outputSample.isEmpty { + state.models[mi].configs[ci].outputSample = outputPreview } - header += "| Thinking (effective) | \(p.thinkingEnabled ? "Yes" : "No") |\n" - header += "| Perplexity tracking (MLX_BENCH_PPL) | \(p.generate.trackPerplexity ? "Yes" : "No") |\n" - header += "| KL divergence (MLX_BENCH_KLD) | \(mdTableCell(p.kldSummary)) |\n" - header += "| Batch size (MLX_BENCH_BATCH) | \(p.batchSize) |\n" - header += "| Speculative decoding | \(mdTableCell(p.speculativeDecoding)) |\n" - header += "| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | \(mdTableCell(p.maxOpsPerBuffer)) |\n" - header += "\n" - header += "## System prompt\n\n" - header += p.systemPromptSummary - header += "\n\n" + } else { + state.models[mi].configs.append(ConfigEntry( + key: configKey, + quantization: quantization, + kvConfig: kvConfig, + method: scenario, + parameterRows: paramRows, + systemPromptSummary: systemPrompt, + rows: [row], + outputSample: outputPreview + )) } - header += "## Methodology\n\n" - header += "For details see [here](../README.md#methodology).\n" - header += "\n" - header += "## Results\n\n" - header += "| Method | Context Limit | Prompt Tokens | KV Config | Prefill tok/s | Gen tok/s | Gen Tokens | TTFT | Think PPL | Gen PPL | Think KLD | Gen KLD | GPU Baseline | GPU Peak | KV Delta | KV Cache | Output |\n" - header += "|--------|---------------|---------------|-----------|---------------|-----------|------------|------|-----------|---------|-----------|---------|-------------|----------|----------|----------|--------|\n" - - try? header.write(to: path, atomically: true, encoding: .utf8) + } else { + state.models.append(ModelEntry( + displayName: model, + repoId: repoId, + configs: [ConfigEntry( + key: configKey, + quantization: quantization, + kvConfig: kvConfig, + method: scenario, + parameterRows: paramRows, + systemPromptSummary: systemPrompt, + rows: [row], + outputSample: outputPreview + )] + )) } - // Append row + full output in collapsible block - let tablePreview = String(outputPreview.prefix(60)) - .replacingOccurrences(of: "|", with: "\\|") - .replacingOccurrences(of: "\n", with: " ") - let contextStr = contextSize > 0 ? "\(contextSize)" : "—" - let thinkPplStr = thinkingPerplexity.map { String(format: "%.4f", $0) } ?? "—" - let genPplStr = generationPerplexity.map { String(format: "%.4f", $0) } ?? "—" - let thinkKldStr = thinkingKLD.map { String(format: "%.4f", $0) } ?? "—" - let genKldStr = generationKLD.map { String(format: "%.4f", $0) } ?? "—" - let kvCacheStr = kvCacheBytes > 0 ? formatBytes(kvCacheBytes) : "—" - let content = "| \(scenario) | \(contextStr) | \(promptTokens) | \(kvConfig) | \(String(format: "%.1f", prefillTokPerSec)) | \(String(format: "%.1f", genTokPerSec)) | \(genTokens) | \(String(format: "%.0f", ttftMs))ms | \(thinkPplStr) | \(genPplStr) | \(thinkKldStr) | \(genKldStr) | \(formatBytes(baselineGPU)) | \(formatBytes(peakGPU)) | \(formatBytes(kvDelta)) | \(kvCacheStr) | \(tablePreview) |\n" - - if let handle = try? FileHandle(forWritingTo: path) { - handle.seekToEndOfFile() - handle.write(content.data(using: .utf8)!) - handle.closeFile() + saveState(state, to: sidecarURL) + let markdown = renderMarkdown(state: state) + try? markdown.write(to: markdownURL, atomically: true, encoding: .utf8) + } + + // MARK: - State types (JSON sidecar) + + private struct SessionState: Codable { + var chip: String + var gpuArch: String + var systemRAM: String + var gpuLimit: String + var osVersion: String + var branch: String + var commit: String + var naxEnabled: Bool + var createdAt: String + var models: [ModelEntry] + } + + private struct ModelEntry: Codable { + var displayName: String + var repoId: String + var configs: [ConfigEntry] + } + + private struct ConfigEntry: Codable { + var key: String + var quantization: String + var kvConfig: String + var method: String + var parameterRows: [[String]] + var systemPromptSummary: String + var rows: [ResultRow] + var outputSample: String + } + + private struct ResultRow: Codable { + var contextSize: Int + var promptTokens: Int + var prefillTokPerSec: Double + var decodeTokPerSec: Double + var genTokens: Int + var ttftMs: Double + var thinkPPL: Double? + var genPPL: Double? + var thinkKLD: Double? + var genKLD: Double? + var baselineGPU: Int + var peakGPU: Int + var kvDelta: Int + var kvCacheBytes: Int + } + + // MARK: - Sidecar I/O + + private static func loadState(from url: URL) -> SessionState? { + guard let data = try? Data(contentsOf: url) else { return nil } + return try? JSONDecoder().decode(SessionState.self, from: data) + } + + private static func saveState(_ state: SessionState, to url: URL) { + let enc = JSONEncoder() + enc.outputFormatting = [.prettyPrinted, .sortedKeys] + guard let data = try? enc.encode(state) else { return } + try? data.write(to: url, options: .atomic) + } + + // MARK: - Markdown rendering + + private static func renderMarkdown(state: SessionState) -> String { + var md = "" + md += "# Benchmark: \(state.chip) — \(datePortion(state.createdAt))\n\n" + + // Environment block + md += "**Hardware:** \(state.chip), \(state.systemRAM) unified memory" + md += " (GPU limit \(state.gpuLimit))\n" + md += "**OS:** macOS \(state.osVersion)\n" + md += "**Branch:** `\(state.branch)`\n" + md += "**Commit:** \(state.commit)\n" + md += "**NAX:** \(state.naxEnabled ? "ENABLED ✓" : "DISABLED ✗")\n" + md += "**Created:** \(state.createdAt)\n\n" + + if state.models.isEmpty { + md += "_No benchmark rows recorded yet._\n" + } else { + md += "## Models\n\n" + for m in state.models { + md += renderModelSection(m) + } } + + // Methodology link + md += "## Methodology\n\n" + md += "See [benchmarks/README.md](README.md#methodology) for method definitions, " + md += "perplexity / KLD computation, and memory accounting.\n" + + return md } - // MARK: - Helpers + private static func renderModelSection(_ model: ModelEntry) -> String { + var md = "### \(model.displayName)\n\n" + if !model.repoId.isEmpty { + md += "**Model:** `\(model.repoId)`\n\n" + } - /// Escape `|` for markdown table cells. - private static func mdTableCell(_ s: String) -> String { - s.replacingOccurrences(of: "|", with: "\\|") + // Results table (shared across all configs for this model). + md += "#### Results\n\n" + md += "| Config | Ctx | Prompt | Prefill tok/s | Decode tok/s | TTFT | Think PPL | Gen PPL | Think KLD | Gen KLD | GPU Base | GPU Peak |\n" + md += "|--------|----:|-------:|--------------:|-------------:|-----:|----------:|--------:|----------:|--------:|---------:|---------:|\n" + for c in model.configs { + for r in c.rows { + let ctx = r.contextSize > 0 ? "\(r.contextSize)" : "—" + let thinkPPL = r.thinkPPL.map { String(format: "%.4f", $0) } ?? "—" + let genPPL = r.genPPL.map { String(format: "%.4f", $0) } ?? "—" + let thinkKLD = r.thinkKLD.map { String(format: "%.4f", $0) } ?? "—" + let genKLD = r.genKLD.map { String(format: "%.4f", $0) } ?? "—" + md += "| \(mdTableCell(c.key))" + md += " | \(ctx)" + md += " | \(r.promptTokens)" + md += " | \(String(format: "%.1f", r.prefillTokPerSec))" + md += " | \(String(format: "%.1f", r.decodeTokPerSec))" + md += " | \(String(format: "%.0f", r.ttftMs))ms" + md += " | \(thinkPPL) | \(genPPL)" + md += " | \(thinkKLD) | \(genKLD)" + md += " | \(formatBytes(r.baselineGPU))" + md += " | \(formatBytes(r.peakGPU)) |\n" + } + } + md += "\n" + + // Output samples (one per config) + md += "#### Output samples\n\n" + for c in model.configs { + md += "**\(c.key)**\n\n" + let sample = c.outputSample.isEmpty ? "_(no output captured)_" + : String(c.outputSample.prefix(400)) + .replacingOccurrences(of: "\n", with: " ") + md += "```\n\(sample)\n```\n\n" + } + + // Parameters (one block per config — placed BELOW results per user direction) + md += "#### Parameters\n\n" + for c in model.configs { + md += "**\(c.key)**\n\n" + md += "| Parameter | Value |\n" + md += "|-----------|-------|\n" + for row in c.parameterRows where row.count == 2 { + md += "| \(row[0]) | \(row[1]) |\n" + } + md += "\n" + if !c.systemPromptSummary.isEmpty { + md += "_System prompt:_ \(c.systemPromptSummary)\n\n" + } + } + + return md + } + + // MARK: - Parameters serialisation + + private static func buildParameterRows(_ p: BenchmarkParameters) -> [[String]] { + func optFloat(_ x: Float?) -> String { + guard let x else { return "nil" } + return String(format: "%g", x) + } + let gp = p.generate + let strat = mdTableCell(kvCacheStrategyLine(from: gp)) + let maxKV = gp.maxKVSize.map { "\($0) tokens (RotatingKVCache)" } ?? "unbounded (KVCacheSimple)" + + var rows: [[String]] = [ + ["KV cache strategy", strat], + ["Max KV size", mdTableCell(maxKV)], + ["KV bits", gp.kvBits.map(String.init) ?? "nil"], + ["KV scheme", mdTableCell(gp.kvScheme ?? "nil")], + ["KV group size", "\(gp.kvGroupSize)"], + ["Quantized KV start", "\(gp.quantizedKVStart)"], + ["Prefill step size", "\(gp.prefillStepSize)"], + ["Max tokens", gp.maxTokens.map(String.init) ?? "nil"], + ["Temperature", "\(gp.temperature)"], + ["Top P", "\(gp.topP)"], + ["Top K", "\(gp.topK)"], + ["Min P", "\(gp.minP)"], + ["Repetition penalty", optFloat(gp.repetitionPenalty)], + ["Repetition context size", "\(gp.repetitionContextSize)"], + ["Presence penalty", optFloat(gp.presencePenalty)], + ["Presence context size", "\(gp.presenceContextSize)"], + ["Frequency penalty", optFloat(gp.frequencyPenalty)], + ["Frequency context size", "\(gp.frequencyContextSize)"], + ["Reasoning effort", mdTableCell(gp.reasoningEffort ?? "nil")], + ["Think start token id", gp.thinkStartTokenId.map { "\($0)" } ?? "nil"], + ["Think end token id", gp.thinkEndTokenId.map { "\($0)" } ?? "nil"], + ["Thinking phase prefilled", gp.thinkingPhasePrefilled ? "true" : "false"], + ["Collect per-token data", gp.collectPerTokenData ? "true" : "false"], + ["Track perplexity", gp.trackPerplexity ? "true" : "false"], + ["N-gram size", "\(gp.ngramSize)"], + ["Max n-gram draft tokens", "\(gp.maxNgramDraftTokens)"], + ["Additional processors count", "\(gp.additionalProcessors.count)"], + ] + if let budget = p.thinkingTokenBudget { + rows.append(["Thinking token budget (processor)", "\(budget)"]) + } + rows.append(["Thinking (effective)", p.thinkingEnabled ? "Yes" : "No"]) + rows.append(["Perplexity tracking (MLX_BENCH_PPL)", gp.trackPerplexity ? "Yes" : "No"]) + rows.append(["KL divergence (MLX_BENCH_KLD)", mdTableCell(p.kldSummary)]) + rows.append(["Batch size (MLX_BENCH_BATCH)", "\(p.batchSize)"]) + rows.append(["Speculative decoding", mdTableCell(p.speculativeDecoding)]) + rows.append(["Max ops per buffer (MLX_MAX_OPS_PER_BUFFER)", mdTableCell(p.maxOpsPerBuffer)]) + return rows } - /// Human-readable KV path from ``GenerateParameters`` (Turbo vs affine vs FP16). private static func kvCacheStrategyLine(from p: GenerateParameters) -> String { if let s = p.kvScheme, !s.isEmpty { return "TurboQuant (\(s))" @@ -158,67 +368,65 @@ enum BenchmarkWriter { return "None (FP16)" } - private static func appendGenerateParametersRows(to header: inout String, params p: GenerateParameters) { - func optFloat(_ x: Float?) -> String { - guard let x else { return "nil" } - return String(format: "%g", x) - } - let strat = mdTableCell(kvCacheStrategyLine(from: p)) - let maxKV = p.maxKVSize.map { "\($0) tokens (RotatingKVCache)" } ?? "unbounded (KVCacheSimple)" - let rows: [(String, String)] = [ - ("KV cache strategy", strat), - ("Max KV size", mdTableCell(maxKV)), - ("KV bits", p.kvBits.map(String.init) ?? "nil"), - ("KV scheme", mdTableCell(p.kvScheme ?? "nil")), - ("KV group size", "\(p.kvGroupSize)"), - ("Quantized KV start", "\(p.quantizedKVStart)"), - ("Prefill step size", "\(p.prefillStepSize)"), - ("Max tokens", p.maxTokens.map(String.init) ?? "nil"), - ("Temperature", "\(p.temperature)"), - ("Top P", "\(p.topP)"), - ("Top K", "\(p.topK)"), - ("Min P", "\(p.minP)"), - ("Repetition penalty", optFloat(p.repetitionPenalty)), - ("Repetition context size", "\(p.repetitionContextSize)"), - ("Presence penalty", optFloat(p.presencePenalty)), - ("Presence context size", "\(p.presenceContextSize)"), - ("Frequency penalty", optFloat(p.frequencyPenalty)), - ("Frequency context size", "\(p.frequencyContextSize)"), - ("Reasoning effort", mdTableCell(p.reasoningEffort ?? "nil")), - ("Think start token id", p.thinkStartTokenId.map { "\($0)" } ?? "nil"), - ("Think end token id", p.thinkEndTokenId.map { "\($0)" } ?? "nil"), - ("Thinking phase prefilled", p.thinkingPhasePrefilled ? "true" : "false"), - ("Collect per-token data", p.collectPerTokenData ? "true" : "false"), - ("Track perplexity", p.trackPerplexity ? "true" : "false"), - ("N-gram size", "\(p.ngramSize)"), - ("Max n-gram draft tokens", "\(p.maxNgramDraftTokens)"), - ("Additional processors count", "\(p.additionalProcessors.count)"), - ] - for (k, v) in rows { - header += "| \(k) | \(v) |\n" - } + private static func mdTableCell(_ s: String) -> String { + s.replacingOccurrences(of: "|", with: "\\|") } - private static func benchmarkDir(modelSlug: String) -> URL { - // Route to model family subfolder: "qwen3.5-0.8b-4bit" → "qwen3.5-0.8b" - // Strip the quantization suffix (last hyphenated component like -bf16, -4bit, -8bit) - let quantSuffixes = ["-bf16", "-8bit", "-4bit", "-nvfp4", "-mxfp4"] - var familySlug = modelSlug - for suffix in quantSuffixes { - if familySlug.hasSuffix(suffix) { - familySlug = String(familySlug.dropLast(suffix.count)) - break - } + // MARK: - Filename helpers + + /// `{chip-slug}-{ram}gb-{YYYY-MM-DD}` — no extension. + static func sessionFilename(hw: HardwareInfo) -> String { + let chipSlug = chipSlug(from: hw.chip) + let ramSlug = hw.systemRAM.lowercased() // "64GB" → "64gb" + let date = sessionDatePortion + return "\(chipSlug)-\(ramSlug)-\(date)" + } + + /// "Apple M1 Max (applegpu_g13s)" → "m1-max". + private static func chipSlug(from chip: String) -> String { + // Strip trailing "(...)" annotation. + var s = chip + if let paren = s.firstIndex(of: "(") { + s = String(s[.. String { + String(iso.prefix(10)) + } + + private static func isoDateTime(_ d: Date) -> String { + let fmt = ISO8601DateFormatter() + fmt.formatOptions = [.withInternetDateTime] + return fmt.string(from: d) + } + + // MARK: - Project root / git + static func projectRoot() -> URL { - // Walk up from the build directory to find Package.swift var dir = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) for _ in 0..<5 { if FileManager.default.fileExists(atPath: dir.appendingPathComponent("Package.swift").path) { @@ -237,7 +445,6 @@ enum BenchmarkWriter { .replacingOccurrences(of: "ref: refs/heads/", with: "") ?? "unknown" } - /// Short hash and subject for the current HEAD, for benchmark provenance. private static func gitLastCommitLine() -> String { let root = projectRoot() let process = Process() @@ -265,22 +472,7 @@ enum BenchmarkWriter { } } - /// Session-level date string (same for all results in one test run) - nonisolated(unsafe) private static var _sessionDate: String? - private static var sessionDateString: String { - if let cached = _sessionDate { return cached } - let fmt = DateFormatter() - fmt.dateFormat = "yyyy-MM-dd-HHmm" - let s = fmt.string(from: Date()) - _sessionDate = s - return s - } - - private static var humanDateString: String { - let fmt = DateFormatter() - fmt.dateFormat = "yyyy-MM-dd HH:mm" - return fmt.string(from: Date()) - } + // MARK: - Hardware struct HardwareInfo { let chip: String @@ -303,42 +495,32 @@ enum BenchmarkWriter { ) } - /// Returns a human-readable chip name combined with the GPU architecture ID. - /// e.g. "Apple M1 Max (applegpu_g13s)" private static func humanReadableChipName(gpuArch: String) -> String { var size = 0 sysctlbyname("machdep.cpu.brand_string", nil, &size, nil, 0) var brand = [CChar](repeating: 0, count: size) sysctlbyname("machdep.cpu.brand_string", &brand, &size, nil, 0) let brandStr = String(cString: brand) - - // On Apple Silicon, brand_string is empty — use hw.model instead if !brandStr.isEmpty { return "\(brandStr) (\(gpuArch))" } - size = 0 sysctlbyname("hw.model", nil, &size, nil, 0) var model = [CChar](repeating: 0, count: size) sysctlbyname("hw.model", &model, &size, nil, 0) let modelStr = String(cString: model) - - // Map hw.model identifiers to marketing names let marketingName = appleChipName(from: modelStr, gpuArch: gpuArch) return "\(marketingName) (\(gpuArch))" } - /// Derive a marketing-style chip name from hw.model + GPU arch. private static func appleChipName(from model: String, gpuArch: String) -> String { - // GPU arch suffix encodes the die variant: - // g13 = M1 family, g14 = M2 family, g15 = M3 family, g16 = M4 family - // s = standard, d = Pro, x = Max, c = Ultra let archLower = gpuArch.lowercased() let gen: String if archLower.contains("g13") { gen = "M1" } else if archLower.contains("g14") { gen = "M2" } else if archLower.contains("g15") { gen = "M3" } else if archLower.contains("g16") { gen = "M4" } + else if archLower.contains("g17") { gen = "M5" } else { return model.isEmpty ? gpuArch : model } let variant: String @@ -358,6 +540,14 @@ enum BenchmarkWriter { } } + // MARK: - NAX detection (parity with InferenceBenchmark.printBuildEnvironment) + + private static func detectNAX() -> Bool { + let naxObj = FileManager.default.fileExists( + atPath: ".build/arm64-apple-macosx/release/Cmlx.build/mlx-generated/steel_attention_nax.cpp.o") + return naxObj + } + // MARK: - MLX max ops per buffer (Metal backend defaults) /// Hardware default for max ops per command buffer **before** `MLX_MAX_OPS_PER_BUFFER` is applied. @@ -365,15 +555,15 @@ enum BenchmarkWriter { static func hardwareDefaultMaxOpsPerBuffer(gpuArch: String) -> Int { guard let suffix = gpuArch.last else { return 40 } switch suffix { - case "p": return 20 // phone - case "g": return 40 // base, pro - case "s": return 200 // max - case "d": return 200 // ultra + case "p": return 20 + case "g": return 40 + case "s": return 200 + case "d": return 200 default: return 40 } } - /// Value shown in benchmark markdown: parsed env, or numeric hardware default with GPU arch. + /// Value shown in the Parameters table. static func resolvedMaxOpsPerBufferReport() -> String { let raw = ProcessInfo.processInfo.environment["MLX_MAX_OPS_PER_BUFFER"]? .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" diff --git a/Tests/Benchmarks/baselines/README.md b/Tests/Benchmarks/baselines/README.md deleted file mode 100644 index 308a310c62..0000000000 --- a/Tests/Benchmarks/baselines/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Benchmark Baselines - -This directory holds periodic full-matrix benchmark runs for the inference -benchmark suite in `Tests/Benchmarks/InferenceBenchmark.swift`. Each file is -a snapshot of prefill / decode tokens-per-second across the supported model -range on a specific piece of hardware at a specific point in time. - -Use these as a reference when: - -- Diagnosing a perf regression — compare current numbers against the most - recent baseline on matching hardware. -- Landing a kernel or framework change — re-run the affected rows and update - the baseline if the delta is material. -- Picking a model for a target device — the TL;DR table shows prefill/decode - at 1k context and whether 8k coherency holds. - -## File naming - -`{hardware}-{ram}-{YYYY-MM-DD}.md` - -Examples: -- `m5-max-128gb-2026-04-16.md` -- `m3-ultra-192gb-2026-04-30.md` - -## Methodology - -All baselines should record: - -- Hardware, OS version, and the alpha branch / PRs applied -- Whether NAX is enabled -- `MLX_BENCH_METHOD` (summarization is the default for multi-ctx sweeps) -- Both swift and bridge paths (bridge only differs for Gemma 4) -- Prefill and decode tok/s at 128, 512, 1k, 2k, 4k, 8k, 16k, 32k -- An 8k coherency sample per model (short output snippet proving it generates - sensible text, not garbage) diff --git a/Tests/Benchmarks/baselines/m5-max-128gb-2026-04-16.md b/Tests/Benchmarks/baselines/m5-max-128gb-2026-04-16.md deleted file mode 100644 index 948db8199a..0000000000 --- a/Tests/Benchmarks/baselines/m5-max-128gb-2026-04-16.md +++ /dev/null @@ -1,297 +0,0 @@ -# Baseline: M5 Max 128GB — 2026-04-16 - -**Hardware:** M5 Max, 128GB unified memory -**OS:** macOS 26.3 (Darwin 25.3.0) -**Branch:** `alpha` with PR #44 (Gemma 4 coherence + real BPE tokenizer) and PR #45 (Gemma 4 26B MoE + Qwen3.5 GDN fused decode) -**NAX:** enabled -**Method:** `MLX_BENCH_METHOD=summarization`, swift mode (native Swift) and bridge mode (`NATIVE_PREFILL=1`, only meaningful for Gemma 4) -**Coverage:** 14 models × 8 context points (128 → 32k) × swift & bridge paths, plus 8k coherency samples - -## TL;DR - -| Model | Prefill @ 1k | Decode @ 1k | Coherent @ 8k | -|-------|-------------:|------------:|---------------| -| **Gemma 4 E2B (2B)** | **20,206** | 195 | ✅ | -| Qwen2.5 3B | 6,930 | 184 | ✅ | -| Llama 3.2 3B | 6,837 | 202 | ✅ | -| Phi-4 Mini | 6,162 | 163 | ✅ | -| Qwen3 4B | 5,641 | 162 | ✅ (thinking) | -| Qwen3-Coder 30B MoE | 3,469 | 107 | ✅ | -| Mistral 7B | 3,434 | 108 | ✅ | -| Nemotron 30B-A3B | 2,727 | 155 | ✅ | -| GPT-OSS 20B | 2,465 | 111 | ✅ (analysis channel) | -| MiniMax M2 (~46B) | 732 | 57 | ✅ | -| Gemma 4 26B A4B | 642 | 53 | ✅ | -| Qwen3.5 2B (GDN) | 659 | 285 | ✅ | -| Qwen3.5 9B (GDN) | 343 | 93 | ✅ (thinking) | -| Qwen3.5 35B-A3B (GDN MoE) | 271 | 135 | ✅ (thinking) | - -**Key findings:** -- **NAX delivers 2–3.5x prefill speedup** across every model. -- **Bridge vs Swift is within noise for every model except Gemma 4** — only Gemma 4 has a real dlopen-based C++ prefill bridge. For all other models the "bridge" path falls through to Swift. -- **Gemma 4 E2B peaks at 20K tok/s prefill** at 1024 context. -- **Gemma 4 26B A4B** now loads and runs — 600 tok/s prefill, stable 50 tok/s decode through 8k. -- **Qwen3.5 GatedDeltaNet decode** now uses the fused `gatedDeltaStepFused` Metal kernel at T=1; decode is +20–34% on 2B/9B and +128–172% on the 35B MoE (GDN + MoE compounds the dispatch-overhead savings). -- All 14 models produce coherent Gatsby summaries at 8k context. - -## Speed — Prefill / Decode (tokens/sec) - -### Llama-3.2-3B-Instruct-4bit - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 2798.5 | 210.1 | 2934.9 | 210.0 | -| 512 | 5816.8 | 202.1 | 5823.8 | 201.7 | -| 1024 | 6837.0 | 201.8 | 6755.9 | 202.3 | -| 2048 | 8111.3 | 193.6 | 8112.2 | 192.3 | -| 4096 | 7663.5 | 178.4 | 7704.1 | 177.8 | -| 8192 | 6995.8 | 153.9 | 6971.3 | 153.3 | -| 16384 | 5849.0 | 123.0 | 5844.6 | 122.1 | -| 32768 | 4174.7 | 86.5 | 4198.2 | 85.5 | - -### MiniMax-M2.7-ConfigI-MLX - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 195.9 | 60.0 | 196.4 | 60.1 | -| 512 | 563.3 | 58.2 | 558.5 | 58.3 | -| 1024 | 732.5 | 56.8 | 846.1 | 56.9 | -| 2048 | 870.8 | 54.5 | 812.8 | 54.6 | -| 4096 | 861.8 | 51.2 | 928.7 | 51.1 | -| 8192 | 895.5 | 44.6 | 923.0 | 45.0 | -| 16384 | 815.0 | 38.3 | 829.2 | 38.1 | -| 32768 | 522.3 | 29.1 | 672.9 | 29.4 | - -### Mistral-7B-Instruct-v0.3-4bit - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 1991.5 | 111.5 | 1993.2 | 111.3 | -| 512 | 3181.7 | 110.8 | 3175.2 | 110.2 | -| 1024 | 3434.1 | 108.3 | 3437.6 | 106.7 | -| 2048 | 3530.8 | 105.8 | 3513.2 | 105.4 | -| 4096 | 3418.9 | 102.4 | 3426.9 | 101.5 | -| 8192 | 3199.7 | 93.1 | 3196.9 | 92.8 | -| 16384 | 2716.2 | 78.5 | 2739.4 | 78.3 | -| 32768 | 2041.4 | 56.5 | 2044.6 | 59.2 | - -### Nemotron-Cascade-2-30B-A3B-4bit - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 128.4 | 155.1 | 965.7 | 155.5 | -| 512 | 2313.5 | 155.7 | 2349.6 | 154.2 | -| 1024 | 2726.6 | 154.5 | 2711.6 | 152.9 | -| 2048 | 2527.0 | 153.5 | 2514.9 | 152.3 | -| 4096 | 2425.8 | 149.5 | 2430.5 | 152.1 | -| 8192 | 2356.1 | 148.0 | 2368.6 | 148.3 | -| 16384 | 2323.6 | 143.5 | 2323.7 | 143.3 | -| 32768 | 2218.4 | 133.8 | 2223.6 | 134.9 | - -### Phi-4-mini-instruct-4bit - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 2479.3 | 173.6 | 2405.1 | 172.4 | -| 512 | 5310.7 | 169.4 | 5418.5 | 167.9 | -| 1024 | 6161.8 | 162.9 | 6129.1 | 163.4 | -| 2048 | 6810.8 | 157.4 | 6806.0 | 156.1 | -| 4096 | 6594.3 | 145.3 | 6555.0 | 145.2 | -| 8192 | 6006.0 | 126.7 | 5997.1 | 126.3 | -| 16384 | 5020.7 | 101.3 | 5018.8 | 101.3 | -| 32768 | 3630.3 | 72.3 | 3577.5 | 72.3 | - -### Qwen2.5-3B-Instruct-4bit - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 2447.7 | 199.0 | 2527.1 | 198.8 | -| 512 | 6466.1 | 190.9 | 6252.3 | 192.3 | -| 1024 | 6929.6 | 183.5 | 7069.8 | 184.1 | -| 2048 | 7845.6 | 178.2 | 7990.8 | 178.2 | -| 4096 | 7763.9 | 176.2 | 7786.4 | 177.6 | -| 8192 | 7181.2 | 163.8 | 7196.7 | 164.6 | -| 16384 | 6089.4 | 140.7 | 6071.6 | 140.8 | -| 32768 | 4628.9 | 113.7 | 4644.2 | 113.9 | - -### Qwen3-4B-4bit - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 2185.3 | 172.2 | 2135.6 | 171.8 | -| 512 | 5038.4 | 168.2 | 4915.7 | 167.9 | -| 1024 | 5641.3 | 161.6 | 5613.0 | 161.0 | -| 2048 | 5911.1 | 154.1 | 5876.6 | 153.9 | -| 4096 | 5640.3 | 141.2 | 5626.1 | 140.7 | -| 8192 | 5002.1 | 121.9 | 4965.6 | 122.1 | -| 16384 | 4011.4 | 95.5 | 4008.7 | 95.4 | -| 32768 | 2729.4 | 66.8 | 2718.8 | 66.8 | - -### Qwen3-Coder-30B-A3B-Instruct-MLX-6bit - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 752.0 | 111.9 | 748.8 | 112.2 | -| 512 | 2366.6 | 109.0 | 2404.4 | 108.7 | -| 1024 | 3468.5 | 106.9 | 3499.3 | 106.5 | -| 2048 | 4378.6 | 101.9 | 4378.7 | 102.4 | -| 4096 | 3819.9 | 96.3 | 4267.6 | 96.6 | -| 8192 | 3787.3 | 85.7 | 3805.6 | 86.3 | -| 16384 | 3057.8 | 72.5 | 3075.0 | 72.5 | -| 32768 | 2080.5 | 56.4 | 2072.2 | 56.3 | - -### Qwen3.5-2B-4bit - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 735.6 | 289.6 | 735.6 | 289.6 | -| 512 | 738.1 | 287.9 | 738.1 | 287.9 | -| 1024 | 658.7 | 284.6 | 658.7 | 284.6 | -| 2048 | 632.6 | 278.9 | 632.6 | 278.9 | -| 4096 | 617.6 | 267.2 | 617.6 | 267.2 | -| 8192 | 639.8 | 247.8 | 639.8 | 247.8 | -| 16384 | 608.9 | 209.7 | 608.9 | 209.7 | -| 32768 | 625.8 | 164.4 | 625.8 | 164.4 | - -### Qwen3.5-35B-A3B-4bit - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 234.6 | 137.6 | 234.6 | 137.6 | -| 512 | 259.5 | 135.6 | 259.5 | 135.6 | -| 1024 | 270.7 | 134.8 | 270.7 | 134.8 | -| 2048 | 257.9 | 133.0 | 257.9 | 133.0 | -| 4096 | 259.3 | 132.5 | 259.3 | 132.5 | -| 8192 | 258.5 | 126.0 | 258.5 | 126.0 | -| 16384 | 247.6 | 120.9 | 247.6 | 120.9 | -| 32768 | 199.7 | 107.3 | 199.7 | 107.3 | - -### Qwen3.5-9B-4bit - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 354.2 | 94.8 | 354.2 | 94.8 | -| 512 | 307.1 | 93.4 | 307.1 | 93.4 | -| 1024 | 342.9 | 92.7 | 342.9 | 92.7 | -| 2048 | 321.9 | 90.6 | 321.9 | 90.6 | -| 4096 | 315.6 | 88.3 | 315.6 | 88.3 | -| 8192 | 322.0 | 85.2 | 322.0 | 85.2 | -| 16384 | 281.0 | 87.6 | 281.0 | 87.6 | -| 32768 | 279.2 | 80.5 | 279.2 | 80.5 | - -### gemma-4-26b-a4b-4bit - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 444.2 | 51.6 | 447.5 | 50.3 | -| 512 | 631.1 | 53.0 | 582.4 | 52.0 | -| 1024 | 642.3 | 52.7 | 594.4 | 51.2 | -| 2048 | 631.6 | 51.9 | 627.9 | 50.0 | -| 4096 | 621.6 | 51.7 | 620.9 | 49.6 | -| 8192 | 598.1 | 50.1 | 591.6 | 49.0 | -| 16384 | 547.0 | 47.2 | 569.3 | 47.2 | -| 32768 | 522.1 | 42.6 | — | — | - -### gemma-4-e2b-it-4bit - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 5000.3 | 193.7 | 5531.8 | 200.5 | -| 512 | 17845.7 | 194.4 | 17269.5 | 194.1 | -| 1024 | 20206.1 | 194.8 | 20149.1 | 195.4 | -| 2048 | 16744.6 | 193.5 | 16620.0 | 193.1 | -| 4096 | 13611.2 | 189.1 | 13564.3 | 188.9 | -| 8192 | 13321.7 | 179.7 | 13397.6 | 180.9 | -| 16384 | 12682.6 | 168.6 | 12675.1 | 168.1 | -| 32768 | 11292.0 | 145.0 | 11317.4 | 145.1 | - -### gpt-oss-20b-MXFP4-Q8 - -| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | -|----:|--------:|--------:|--------:|--------:| -| 128 | 379.6 | 113.6 | 969.3 | 111.5 | -| 512 | 2199.5 | 112.5 | 2278.2 | 111.6 | -| 1024 | 2465.3 | 110.7 | 2803.9 | 110.9 | -| 2048 | 3248.4 | 108.8 | 3285.8 | 113.3 | -| 4096 | 2534.4 | 106.9 | 3263.7 | 105.7 | -| 8192 | 2939.7 | 101.9 | 3203.2 | 101.2 | -| 16384 | 2943.7 | 92.1 | 3027.8 | 95.0 | -| 32768 | 2598.6 | 79.2 | 2614.8 | 81.8 | - - -## Coherency — 8k Context Output - -## gemma-4-e2b-it-4bit (swift) -``` -This is a fascinating excerpt from **The Great Gatsby** by F. Scott Fitzgerald, likely narrated by the character **Nick Carraway**. -``` - -## gemma-4-26b-a4b-4bit (swift) -``` -The excerpt is the opening of F. Scott Fitzgerald's *The Great Gatsby*, narrated by Nick Carraway. Nick introduces himself, recalls his father's advice about reserving judgment, and describes his move east to West Egg on Long Island the summer he met Gatsby. -``` - -## gpt-oss-20b-MXFP4-Q8 (swift) -``` -<|channel|>analysis<|message|>We need to summarize the content. The content is a long, somewhat chaotic text that appears to be a mash-up of "The Grea -``` - -## Llama-3.2-3B-Instruct-4bit (swift) -``` -The passage is the opening of F. Scott Fitzgerald's novel "The Great Gatsby". The story is narrated by Nick Carraway, a young man from the Midwest who -``` - -## Mistral-7B-Instruct-v0.3-4bit (swift) -``` -This is the first chapter of "The Great Gatsby" by F. Scott Fitzgerald. The novel is set in the summer of 1922 and follows the story of Nick Carraway, -``` - -## Nemotron-Cascade-2-30B-A3B-4bit (swift) -``` -We need to summarize the content above, which presumably is an excerpt or a parody of The Great Gatsby with a modern twist, but we need to summarize t -``` - -## Phi-4-mini-instruct-4bit (swift) -``` -Nick Carraway, a bond man living in East Egg, New York, recounts a summer evening spent visiting Daisy Buchanan, a distant cousin and a resident of a -``` - -## Qwen2.5-3B-Instruct-4bit (swift) -``` -The passage describes the protagonist's journey to East Egg, where he meets Tom Buchanan and his wife, Daisy. The interaction with Tom and Daisy revea -``` - -## Qwen3-4B-4bit (swift) -``` - -``` - -## Qwen3-Coder-30B-A3B-Instruct-MLX-6bit (swift) -``` -Here's a summary of the first chapter of *The Great Gatsby*: -``` - -## Qwen3.5-2B-4bit (swift) -``` -The provided text is the opening chapter of *The Great Gatsby* by F. Scott Fitzgerald. It is divided into three main sections: -``` - -## Qwen3.5-9B-4bit (swift) -``` -Thinking Process: -``` - -## Qwen3.5-35B-A3B-4bit (swift) -``` -Thinking Process: -``` - -## MiniMax-M2.7-ConfigI-MLX (swift) -``` -The user asks: "Summarize the content above." The content is a passage from The Great Gatsby, Chapter 1. Summarize the content. -``` - - -## Raw Log - -Full timestamped run log in `/tmp/overnight_bench/log.txt` diff --git a/benchmarks/README.md b/benchmarks/README.md new file mode 100644 index 0000000000..f85844fea3 --- /dev/null +++ b/benchmarks/README.md @@ -0,0 +1,429 @@ +# Inference Benchmarks + +Automated benchmarks for MLX Swift LM inference across model families, weight quantizations, and KV cache compression strategies running on Apple Silicon. + +The CLI (`benchmark.sh`) is designed to be language-agnostic — all configuration is passed via environment variables, making it straightforward to add backends in other languages (Python, Java) for cross-platform benchmarking. + +Benchmark reports in this directory also serve as **baselines** — periodic full-matrix snapshots of prefill / decode tokens-per-second across the supported model range on a specific piece of hardware at a specific point in time. Use them when: + +- **Diagnosing a perf regression** — compare current numbers against the most recent baseline on matching hardware. +- **Landing a kernel or framework change** — re-run the affected rows and update the baseline if the delta is material. +- **Picking a model for a target device** — the TL;DR table shows prefill/decode at 1k context and whether 8k coherency holds. + +## Setup + +Run once after cloning (or after fetching new `mlx-swift` changes): + +```bash +./scripts/setup-dev.sh +``` + +This resolves Swift packages, compiles Metal shaders, builds the prefill bridge dylib, and does an initial release build. After setup, all benchmark commands work immediately. + +Internally, `setup-dev.sh` and `benchmark.sh` both call `make build-tests`, which handles the full build pipeline incrementally — only rebuilding what actually changed. See the [main README](../README.md#why-make-instead-of-swift-build) for details on why `make` is used. + +If you are iterating on C/C++ code in the `mlx` or `mlx-c` submodules and benchmarks are using stale artifacts, run: + +```bash +make clean-cmlx # Invalidate SPM's C/C++ cache +make status # Verify what's built +``` + +Then re-run your benchmark — it will recompile only the C/C++ target. + +## Quick Start + +```bash +# Simple chat evaluation (default method) +./scripts/benchmark.sh --model qwen35-0.8b + +# Simple eval with perplexity tracking +./scripts/benchmark.sh --model qwen35-0.8b --ppl + +# Context-scaling summarization (3 quick context sizes) +./scripts/benchmark.sh --model qwen35-9b --method summarization --quick + +# WikiText-2 perplexity at a specific context +./scripts/benchmark.sh --model qwen35-0.8b --method wikitext2 --context 1024 + +# Needle-in-a-haystack +./scripts/benchmark.sh --model qwen35-9b --method niah --context 4096 + +# With KLD quality metrics +./scripts/benchmark.sh --model qwen35-0.8b --method summarization --kv affine4 --kld + +# Full matrix: all quants × all KV configs +./scripts/benchmark.sh --model qwen35-0.8b --quant all --kv all --quick + +# Multi-model sweep: two models, two KV configs, quick contexts — one output file +./scripts/benchmark.sh --model qwen35-0.8b,qwen35-2b --kv none,turbo4v2 --quick + +# Two methods against the same model +./scripts/benchmark.sh --model qwen35-0.8b --method simple,summarization +``` + +## CLI Reference + +| Flag | Description | Default | +|------|-------------|---------| +| `--model MODELS` | **(required)** Model family / HF repo ID. Comma-separated for multi-model sweeps. | — | +| `--method METHODS` | Benchmark method(s), comma-separated (see [Methods](#methods)) | `simple` | +| `--quant QUANTS` | Weight quantization(s): `bf16`, `8bit`, `4bit`, or `all`. Comma-separated for multiple. | `4bit` | +| `--kv CONFIGS` | KV cache config(s) (see [KV Cache Configurations](#kv-cache-configurations)). Comma-separated or `all`. | `none` | +| `--context SIZES` | Comma-separated context sizes (e.g., `128,1024,4096`) | All 11 sizes | +| `--quick` | Quick mode: 128 + 1024 + 4096 + 32768 tokens only | Off | +| `--ppl` | Track per-token perplexity during generation | Off | +| `--kld` | Compute KL divergence vs bf16/8bit baseline | Off | +| `--baseline` | Auto-select highest-fidelity variant that fits in GPU memory | Off | +| `--batch N` | Run N concurrent generations | `1` | +| `--think` | Enable thinking mode for thinking-capable models | Off | +| `-h`, `--help` | Show usage | — | + +**Comma-separated lists** on `--model`, `--method`, `--quant`, and `--kv` produce the full Cartesian product of permutations. Every permutation runs in sequence, and every row lands in the **same** hardware-dated output file (see [Output](#output)), grouped by model. A sweep like: + +```bash +./scripts/benchmark.sh --model qwen35-0.8b,qwen35-2b \ + --method simple,summarization --quant 4bit --kv none,turbo4v2 --quick +``` + +runs 2 × 2 × 1 × 2 = 8 permutations and produces one report file covering both models. + +`--quant all` expands to `bf16,8bit,4bit`. `--kv all` expands to `none,affine8,affine4,turbo4,turbo4v2,turbo3`. These can be combined with comma lists on the other dimensions. + +> **Max speed tip:** For pure throughput measurements, omit `--ppl` and `--kld`. Both flags add significant compute overhead — `--ppl` tracks per-token log-probabilities during generation, and `--kld` loads a second baseline model and runs a full forced-decode pass after generation completes. Leave them off when you only care about tok/s and TTFT. + +## Methods + +| Method | Description | Context Scaling | Generation | Pass/Fail | +|--------|-------------|:---:|:---:|:---:| +| `simple` | Basic chat prompt — generation speed + PPL | No | Yes | No | +| `summarization` | Pre-sized prompts across context sizes | Yes | Yes | No | +| `wikitext2` | Standard LM perplexity via forced decode on WikiText-2 | Yes | No | No | +| `niah` | Needle-in-a-haystack retrieval at multiple depths | Yes | Yes | Yes | +| `multi-turn` | Multi-turn conversation with name recall | No | Yes | Yes | +| `tool-calling` | Tool call generation and validation | No | Yes | Yes | + +## Model Families + +All Qwen3.5 models use a hybrid **GatedDeltaNet** architecture: 75% linear attention layers (MambaCache) + 25% standard attention layers (KVCacheSimple), with full attention every 4th layer. + +| Family | Short Name | Quantizations | Architecture | +|--------|------------|---------------|--------------| +| Qwen3.5 0.8B | `qwen35-0.8b` | bf16, 8bit, 4bit | GatedDeltaNet | +| Qwen3.5 2B | `qwen35-2b` | bf16, 8bit, 4bit | GatedDeltaNet | +| Qwen3.5 4B | `qwen35-4b` | bf16, 8bit, 4bit | GatedDeltaNet | +| Qwen3.5 9B | `qwen35-9b` | bf16, 8bit, 4bit | GatedDeltaNet | +| Qwen3.5 27B | `qwen35-27b` | bf16, 8bit, 4bit | GatedDeltaNet | +| Qwen3.5 35B A3B | `qwen35-35b-a3b` | bf16, 8bit, 4bit | GatedDeltaNet MoE | +| GPT-OSS 20B | `gpt-oss-20b` | bf16, 4bit | Transformer | +| Nemotron Cascade 2 30B A3B | `nemotron-30b-a3b` (aliases: `nemotron-cascade-2`, `nemotron-cascade-2-30b-a3b`, …) | 8bit, 4bit, nvfp4, mxfp4 | Nemotron H (hybrid Mamba / attention / MoE) | +| Gemma 4 E2B | `gemma4-e2b` | bf16, 8bit, 4bit, mxfp4 | Dense + PLE | +| Gemma 4 E4B | `gemma4-e4b` | bf16, 8bit, 4bit, mxfp4 | Dense + PLE | +| Gemma 4 26B A4B | `gemma4-26b-a4b` | bf16, 8bit, 4bit, mxfp4 | Transformer MoE | +| Gemma 4 31B | `gemma4-31b` | bf16, 8bit, 4bit, mxfp4 | Dense | + +Any HuggingFace repo ID can also be passed directly as `--model org/repo-id`. + +## Model cache and downloads + +Models are downloaded on first use via [`HubClient`](https://github.com/huggingface/swift-huggingface) (through the `#hubDownloader()` macro in [`Tests/Benchmarks/InferenceBenchmark.swift`](../Tests/Benchmarks/InferenceBenchmark.swift)) and cached in the **Python-compatible Hugging Face cache structure**. That means snapshots downloaded by Python's `huggingface-cli` or `huggingface_hub` are read directly by the benchmark harness without re-downloading, and vice versa. + +### Cache resolution order + +`HubClient` picks the cache directory from the first of these that is set: + +1. **`HF_HUB_CACHE`** — absolute path to the cache directory. Highest priority, use this to point at an external drive, a shared team volume, etc. +2. **`HF_HOME`** — HF home directory; the cache is placed at `$HF_HOME/hub`. +3. **Default**: `~/.cache/huggingface/hub` on non-sandboxed macOS. (Sandboxed Apple apps use `Library/Caches/huggingface/hub`; that path does not apply to the benchmark harness, which runs unsandboxed as a test target.) + +### Examples + +```bash +# Use an external SSD as the cache root (takes precedence over ~/.cache) +export HF_HUB_CACHE="/Volumes/FastSSD/hf-cache" +./scripts/benchmark.sh --model qwen35-0.8b + +# Or organise HF state under one parent directory +export HF_HOME="$HOME/work/hf" # cache ends up at $HF_HOME/hub +./scripts/benchmark.sh --model qwen35-0.8b + +# Fall back to the default (~/.cache/huggingface/hub) +unset HF_HUB_CACHE HF_HOME +./scripts/benchmark.sh --model qwen35-0.8b +``` + +If you set `HF_HUB_CACHE` / `HF_HOME` in your shell rc file, every subsequent `benchmark.sh` invocation and every `swift test` subprocess it spawns will inherit the setting. + +### Cache-first behaviour + +Every `download(...)` call routes through `HubClient.downloadSnapshot`, which checks for a complete cached snapshot (`{cache}/models--{org}--{name}/snapshots/{rev}/…`) before making any HTTP calls. If the exact `(repo, revision, file globs)` is already on disk, the call returns the local directory URL immediately — progress jumps to 100%, no network. A missing file triggers a native Swift download via `URLSession`; no Python `huggingface-cli` or other external tooling is required. + +If you want to guarantee offline behaviour (fail rather than download), that's an upstream feature of `HubClient` via `localFilesOnly: true`. The current harness doesn't expose it as a flag — if you need it, open a tracking issue. + +### Private / gated repositories + +Authentication is handled by the same environment conventions as the Python clients: `HF_TOKEN` in your environment (or `$HF_HOME/token`) gets picked up automatically by `HubClient.default`. You do not need to touch benchmark code. + +### What is cached + +Every snapshot download pulls the file globs the model factory asks for — typically `*.safetensors`, `*.json`, and the tokenizer files (`tokenizer.json`, `tokenizer_config.json`, `*.jinja`). Non-matching files in the repo (training artifacts, README images, etc.) are not downloaded. Compressed caches are **not** supported — each snapshot is stored as symlinked blobs under `blobs/` plus a `snapshots/{rev}/` tree, matching the Python client layout. + +## Context Sizes + +Context-scaling methods (`summarization`, `wikitext2`, `niah`) run across 11 sizes by default: + +**128, 256, 512, 1K, 2K, 4K, 8K, 16K, 32K, 64K, 128K** tokens + +Use `--context` to specify a subset, or `--quick` for 128 + 1024 + 4096. + +For non-scaling methods (`simple`, `multi-turn`, `tool-calling`), the context limit is fixed at 4096 tokens, enforced via `RotatingKVCache` (`maxKVSize`) to simulate a realistic chat deployment. + +## KV Cache Configurations + +| Config | Compression | Description | +|--------|-------------|-------------| +| `none` | — | Unquantized FP16 KV cache (baseline) | +| `affine8` | K 8-bit, V 8-bit | MLX affine 8-bit quantization (quantized start at offset 512) | +| `affine4` | K 4-bit, V 4-bit | MLX affine 4-bit quantization (quantized start at offset 512) | +| `turbo8` | K 8-bit, V 8-bit (symmetric) | TurboQuant MSE 8-bit compression (starts at offset 0) | +| `turbo8v4` | K 8-bit, V 4-bit (asymmetric) | TurboQuant asymmetric: 8-bit keys, 4-bit values | +| `turbo8v2` | K 8-bit, V 2-bit (asymmetric) | TurboQuant asymmetric: 8-bit keys, 2-bit values | +| `turbo4` | K 4-bit, V 4-bit (symmetric) | TurboQuant MSE 4-bit compression (starts at offset 0) | +| `turbo4v3` | K 4-bit, V 3-bit (asymmetric) | TurboQuant asymmetric: 4-bit keys, 3-bit values | +| `turbo4v2` | K 4-bit, V 2-bit (asymmetric) | TurboQuant asymmetric: 4-bit keys, 2-bit values | +| `turbo3` | K 3-bit, V 3-bit (symmetric) | TurboQuant MSE 3-bit compression | +| `turbo3v2` | K 3-bit, V 2-bit (asymmetric) | TurboQuant asymmetric: 3-bit keys, 2-bit values | +| `all` | — | Shortcut: expands to `none,affine8,affine4,turbo4,turbo4v2,turbo3` | + +**Affine** configs use MLX's built-in quantized-cache path (per-group scale + zero point) and defer quantization until offset 512 — the first 512 KV slots stay full precision to avoid stomping on the short-context path that matters most for TTFT. **Turbo** configs use the TurboQuant MSE-optimal codebook starting at offset 0. **Asymmetric** turbo variants (`turbo{K}v{V}`) compress values more aggressively than keys, exploiting the fact that value projections tolerate more quantization noise than keys in attention. + +## Methodology + +### System prompts + +Several methods use the **same** short assistant system message (defined in the benchmark suite as `minimalSystemPrompt`): + +> You are a helpful assistant. Keep responses concise. + +That string applies to **`simple`**, **`multi-turn`**, **`tool-calling`**, and **`niah`**. Individual benchmark markdown files link here instead of repeating long user prompts. + +**`summarization`** (including the warmup pass) uses **no** system role — only user messages built from the bundled prompt files (see Summarization below). **`wikitext2`** has no chat template system role; it evaluates raw WikiText-2 continuation. + +### Simple + +Sends a basic chat prompt ("Hello! What is your name and what can you help me with?") to the model with a 4096-token context limit. Measures generation speed, TTFT, and perplexity. Quick single evaluation without context scaling. No pass/fail validation. + +### Summarization + +Loads pre-generated prompt files (excerpts from The Great Gatsby) sized to each target token count. The context limit (`maxKVSize`) matches the target size, so the KV cache is bounded. The model generates a summary response (up to 200 tokens). Measures prefill throughput, generation throughput, TTFT, perplexity, and GPU memory at each context size. No pass/fail validation. + +### WikiText-2 + +Standard LM perplexity evaluation via **forced decode** on the WikiText-2 test dataset. No generation occurs. + +**How it works:** +1. The WikiText-2 test text is tokenized using the model's tokenizer and sliced to the target context size. +2. Tokens are fed through the model in 2048-token chunks, capturing logits at every position. +3. At each position, the log-probability of the actual next token is computed via `log(softmax(logits, axis: -1))`. +4. KV cache quantization (if configured) is applied after each chunk, measuring its impact on prediction quality. +5. **Word-level PPL** (the standard metric per EleutherAI) is computed: `exp(total_NLL / word_count)`, where word count is from the decoded text. This normalizes across different tokenizers, making results comparable across model families. + +Token-level PPL is also computed and logged but the word-level metric is reported in the results table. Expected ranges: ~15-30 for instruct-tuned 0.8B models on raw Wikipedia text (instruct models score higher than base models since they're fine-tuned for conversations, not raw text continuation). + +### Needle-in-a-Haystack (NIAH) + +Tests long-context retrieval by inserting a known fact into filler text at multiple depth positions and asking the model to retrieve it. + +**How it works:** +1. For each context size, filler text (Great Gatsby excerpts from the pre-sized prompt files) is loaded. +2. The needle — `"The special magic verification code is BLUE TIGER 42."` — is inserted at **5 depth positions**: 10%, 25%, 50%, 75%, and 90% of the document. +3. The retrieval question — `"What is the special magic verification code mentioned in the text above? Reply with only the code, nothing else."` — is appended after the filler. +4. Each depth produces a separate benchmark run (5 rows per context size). +5. The KV cache is **unbounded** (no `maxKVSize`) so the model can see the entire prompt. +6. **Pass/fail**: output is checked for the substring "BLUE TIGER 42" (case-insensitive). Results are prefixed `PASS(@50%)` or `FAIL(@50%)` in the Output column. + +This produces a depth × context matrix showing where the model succeeds or fails at retrieval. Small models (0.8B) typically fail at larger contexts and certain depth positions, while larger models (9B+) should pass consistently. + +### Multi-Turn + +Tests context recall across a multi-turn conversation. Two names ("Bob" and "Alice") are introduced early in the conversation, and the model is asked to recall each one. + +**Conversation structure:** +1. User: "Hello, what is your name?" → Assistant responds +2. User: "My name is Bob and my partner's name is Alice." → Assistant acknowledges (without repeating names) +3. Test 1: "What is my name?" → **PASS** if output contains "Bob" +4. Test 2: "What is my partner's name?" → **PASS** if output contains "Alice" + +Each recall test produces a separate row in the results table. The assistant's acknowledgment is kept neutral ("Nice to meet you! What can I help you with?") to avoid leaking answers. + +### Tool Calling + +Tests whether the model correctly generates a tool call when given a tool-use prompt and a tool specification. + +**Setup:** +- Prompt: "What is the current date and time?" +- Tool: `execute_shell` — a mock shell execution tool with a `command` string parameter +- The model is expected to generate a tool call to `execute_shell` with a command containing "date" + +**Pass/fail** (strict validation): +1. The generation stream must produce a `.toolCall` event → otherwise `FAIL(no tool call)` +2. The tool call function name must be `execute_shell` → otherwise `FAIL(wrong tool: )` +3. The command argument must contain "date" → otherwise `FAIL(wrong command: )` +4. All three pass → `PASS` + +### Perplexity (Think PPL / Gen PPL) + +Perplexity is computed as `exp(mean negative log-probability)` over generated tokens. It is tracked separately for the **thinking phase** and the **generation phase**. Lower values indicate higher model confidence in its predictions. + +Thinking is **disabled by default** for maximum speed. Use `--think` to enable it: + +```bash +# Speed benchmark (no thinking overhead) +./scripts/benchmark.sh --model gemma4-e2b --quant 4bit --method summarization --quick --ppl + +# Quality benchmark with thinking separation +./scripts/benchmark.sh --model gemma4-e2b --quant 4bit --method summarization --quick --ppl --think +``` + +When `--think` is enabled for thinking-capable models: +- **Qwen3.5**: Prefills `\n` in the assistant turn; tracks tokens between `` and `` +- **Gemma 4**: Passes `enable_thinking=true` to the chat template; tracks tokens between `<|channel>` and `` +- A thinking budget processor forces the end-think token after 200 thinking tokens and suppresses EOS during thinking to ensure both phases are measured + +For `wikitext2`, the Gen PPL column reports word-level perplexity from the forced-decode evaluation (no thinking phase applies). + +### KL Divergence (Think KLD / Gen KLD) + +When `--kld` is enabled, KL divergence measures how much a deployment configuration (weight quantization + KV cache compression) degrades the model's output distribution compared to the highest-fidelity baseline available for that model family. + +**How it works:** + +1. The target model generates tokens normally with per-token log-probability tracking enabled. +2. After generation completes, the highest-fidelity baseline model (bf16 preferred, 8-bit fallback if bf16 exceeds GPU memory) is loaded without KV cache compression. +3. The target's generated tokens are **forced-decoded** through the baseline model — each token is fed sequentially, and the baseline's log-probability for that token is recorded. +4. KLD is computed per phase as: `mean(target_logprob - baseline_logprob)` (always >= 0). + +Values near **0** indicate negligible quality loss. Higher values indicate greater divergence from the gold standard. + +**KLD decision matrix:** + +| Target Quant | KV Config | Baseline Selected | KLD Runs? | What It Measures | +|--------------|-----------|-------------------|-----------|------------------| +| bf16 | none | — | No | Target IS the baseline | +| bf16 | affine4/turbo | bf16 | Yes | KV compression cost | +| 8bit | none | bf16 | Yes | Weight quantization cost | +| 8bit | affine4/turbo | bf16 | Yes | Weight quant + KV compression | +| 4bit | none | bf16 | Yes | Weight quantization cost | +| 4bit | affine4/turbo | bf16 | Yes | Weight quant + KV compression | + +When bf16 exceeds GPU memory (e.g., 27B models on 48GB): + +| Target Quant | KV Config | Baseline Selected | KLD Runs? | What It Measures | +|--------------|-----------|-------------------|-----------|------------------| +| 8bit | none | 8bit | No | Same config, skipped | +| 8bit | affine4/turbo | 8bit | Yes | KV compression cost | +| 4bit | none | 8bit | Yes | Weight quantization cost | +| 4bit | affine4/turbo | 8bit | Yes | Weight quant + KV compression | + +### GPU Memory (GPU Baseline / GPU Peak / KV Delta) + +Three memory metrics are reported for each benchmark run: + +- **GPU Baseline**: GPU memory after the model weights are loaded but before generation starts. This is the static cost of holding the model in memory. +- **GPU Peak**: High-water mark of GPU memory during the entire run, including transient allocations. Captured via `MLX.Memory.peakMemory`. +- **KV Delta**: The increase in active GPU memory from the KV cache, measured as `activeGPU - baselineGPU` after generation completes. For KV-quantized runs (affine4, turbo4, turbo3), this reflects the compressed cache size. Comparing KV Delta between `none` and a quantized config at the same context shows how much memory the compression saves. + +**Why GPU Peak is much higher than GPU Baseline + KV Delta:** + +The gap is primarily intermediate computation tensors allocated during the forward pass — attention scores, QKV projections, FFN activations, softmax buffers, Conv1d state (for GatedDeltaNet), and recurrent state updates. These are allocated during each forward step and freed afterward, but they contribute to the peak memory high-water mark. + +Key factors: +- **Prefill dominates peak**: Prefill processes the full prompt at once (e.g., 1024 tokens), creating much larger intermediate tensors than single-token generation. The peak is usually hit during prefill. +- **MLX memory pool**: MLX does not immediately return freed memory to the OS — it caches freed allocations for reuse. `peakMemory` reflects the cumulative high-water mark, not just what is actively held. +- **GatedDeltaNet overhead**: The hybrid GatedDeltaNet architecture (used by all Qwen3.5 models) has higher intermediate memory than standard transformers due to simultaneous QKV projections, conv state concatenation, and gated delta updates per layer. + +## Environment Variables + +All configuration is passed via environment variables, enabling any backend to implement the benchmark interface. + +| Env Var | Values | Default | Description | +|---------|--------|---------|-------------| +| `MLX_BENCH_MODEL` | registry name or HF repo (single value — CLI iterates over multiple) | *required* | Model to benchmark | +| `MLX_BENCH_METHOD` | `simple`, `summarization`, `wikitext2`, `niah`, `multi-turn`, `tool-calling` | `simple` | Test method | +| `MLX_BENCH_QUANT` | `bf16`, `8bit`, `4bit` | `4bit` | Weight quantization | +| `MLX_BENCH_KV` | `none`, `affine8`, `affine4`, `turbo8`, `turbo8v4`, `turbo8v2`, `turbo4`, `turbo4v3`, `turbo4v2`, `turbo3`, `turbo3v2` | `none` | KV cache config | +| `MLX_BENCH_CONTEXT` | comma-separated ints (e.g., `128,1024,4096`) | all 11 sizes | Context sizes to test | +| `MLX_BENCH_PPL` | `1` | unset | Enable perplexity tracking | +| `MLX_BENCH_KLD` | `1` | unset | Enable KLD computation | +| `MLX_BENCH_BASELINE` | `1` | unset | Auto-select highest-fidelity variant that fits in GPU memory | +| `MLX_BENCH_BATCH` | integer | `1` | Number of concurrent generations | +| `MLX_BENCH_THINK` | `1` | unset | Enable thinking mode | +| `MLX_BENCH_PROMPT` | string | built-in | Override the `simple`-method user prompt | +| `MLX_MAX_OPS_PER_BUFFER` | integer | hardware default (200 on Max/Ultra) | MLX Metal command-buffer commit threshold. Captured into every Parameters block so report readers can see what was in effect. | + +The underlying test binary (`InferenceBenchmark.swift`) reads a **single** model / method / quant / KV permutation per process — one row of the sweep. `benchmark.sh` does the enumeration and re-invokes `swift test` once per permutation. All processes in a single sweep write into the same hardware-dated report file via the JSON state sidecar described in [Output](#output), so the grouping is preserved even though each row lives in its own process. + +## Output + +Benchmark reports are saved as Markdown files in this `benchmarks/` directory, **one file per run, scoped to the hardware and date it was produced on** — not one file per model. A full-matrix sweep across 14 models lives in a single file, making cross-model comparisons and regression diffs easy to eyeball. + +### File naming + +``` +{hardware}-{ram}-{YYYY-MM-DD}.md +``` + +Examples: +- `m1-max-64gb-2026-04-16.md` +- `m5-max-128gb-2026-04-16.md` +- `m3-ultra-192gb-2026-04-30.md` + +If multiple runs happen on the same hardware on the same day, append a run index or a short tag: `m5-max-128gb-2026-04-16-pr45.md`, `m1-max-64gb-2026-04-16-run2.md`. + +### File structure + +Each benchmark file follows this layout, top to bottom: + +1. **Title** — `# Benchmark: {chip} — {YYYY-MM-DD}`. +2. **Environment block** — hardware (chip + unified memory + GPU limit), OS, branch, commit, NAX state, creation timestamp. +3. **`## Models`** — wrapper heading. +4. **`### {Model name}`** per model, each containing: + - `#### Results` — a single table with one row per `(quant / kv / method)` config × context size, in column order: + `Config | Ctx | Prompt | Prefill tok/s | Decode tok/s | TTFT | Think PPL | Gen PPL | Think KLD | Gen KLD | GPU Base | GPU Peak` + - `#### Output samples` — fenced code block per config showing the first ~400 characters of the generated output. Proves the run didn't produce garbage. + - `#### Parameters` — one block per config (below the results as per the owner's preference), with the full parameter table: KV strategy, max KV size, KV bits/scheme/group/start, prefill step size, max tokens, temperature, top_p, top_k, min_p, repetition / presence / frequency penalties, reasoning effort, thinking config, per-token data tracking, n-gram speculative settings, PPL / KLD / batch / speculative / `MLX_MAX_OPS_PER_BUFFER`. +5. **`## Methodology`** — single-line pointer back to this README. + +### How rows are written + +Each `(model, quant, kv, method, context)` run appends exactly one row to the results table for its model. Configs within the same model share a single Results table (rows include the Config column so you can eyeball quant/kv/method deltas side-by-side). Configs remain in insertion order — the order `benchmark.sh` visited them during the sweep. + +State of truth lives in a JSON sidecar next to the markdown file: `benchmarks/.{chip}-{ram}-{date}.state.json`. The markdown is re-rendered from the sidecar on every append. This means: + +- Multi-process sweeps (every `swift test` invocation is its own process) accumulate into the same report. +- Editing the markdown by hand is fine for annotation but the sidecar is the authoritative input — next write overrides the markdown from the sidecar. +- If you need a clean slate on a given day, delete both the `.md` and the matching `.state.json`. + +### Content rules + +- **Parameters live beneath their own config's results row (not in a single top-level block).** This keeps parameter deltas visible when a sweep varied quant or KV config across rows of the same model. +- **Output samples stay short.** ~400 characters is enough to verify coherence. Longer outputs bloat diffs and obscure the signal. +- **Don't repeat the methodology in every file.** The Methodology link at the bottom is the single source of truth; individual files should only add notes when they deviate from the defaults documented here. +- **Record hardware-default `MLX_MAX_OPS_PER_BUFFER`** — on M1 Max/Ultra and M5 Max the committed default is 200; the effective value is captured in every Parameters block regardless of whether it was set via env. + +### When to update baselines + +- A material perf delta lands (≥ 5% on prefill or decode, or any peak-memory change > 10%). +- A kernel or framework change affects the row (even if the net delta is small — the new snapshot anchors the "it worked here" state). +- New hardware is added. + +## Directory layout + +``` +benchmarks/ +├── README.md # This file +├── m1-max-64gb-2026-04-16.md # Full-matrix baseline on M1 Max +├── m5-max-128gb-2026-04-16.md # Full-matrix baseline on M5 Max +├── m3-ultra-192gb-2026-04-30.md # Full-matrix baseline on M3 Ultra +``` + diff --git a/scripts/benchmark.sh b/scripts/benchmark.sh index 9e62da3106..aaaf9c3ffd 100755 --- a/scripts/benchmark.sh +++ b/scripts/benchmark.sh @@ -8,8 +8,12 @@ # ./scripts/benchmark.sh --model qwen35-0.8b # Simple eval (default) # ./scripts/benchmark.sh --model qwen35-0.8b --method summarization --quick # ./scripts/benchmark.sh --model qwen35-0.8b --quant all --kv all # Full matrix +# ./scripts/benchmark.sh --model qwen35-0.8b,qwen35-2b --kv none,turbo4v2 # -# Results saved as markdown in benchmarks//. +# --model, --method, --quant, and --kv all accept comma-separated lists. +# All permutations (model × quant × kv × method) run in sequence; every row +# lands in the same hardware-dated file at benchmarks/{chip}-{ram}-{date}.md, +# grouped by model. set -e @@ -54,19 +58,23 @@ Inference benchmarks in RELEASE mode. Measures throughput, perplexity, TTFT, KL divergence, and GPU memory. Options: - --model MODEL (required) Model family or HuggingFace repo ID - --method METHOD Benchmark method (default: simple) + --model MODELS (required) One or more model families / HuggingFace repo IDs + Comma-separated for multiple: qwen35-0.8b,qwen35-2b + --method METHODS Benchmark method(s), comma-separated (default: simple) simple Basic chat prompt — generation speed + PPL summarization Context-scaling with pre-sized prompts wikitext2 Standard LM perplexity via forced decode niah Needle-in-a-haystack retrieval multi-turn Multi-turn conversation tool-calling Tool call generation - --quant QUANT Weight quantization: bf16, 8bit, 4bit, all (default: 4bit) - --kv CONFIG KV cache config: none, affine8, affine4, turbo4, turbo3, all (default: none) - Comma-separated for multiple: none,turbo4,turbo4v2 + --quant QUANTS Weight quantization(s): bf16, 8bit, 4bit, all (default: 4bit) + Comma-separated for multiple: bf16,4bit + --kv CONFIGS KV cache config(s): none, affine8, affine4, turbo4, turbo4v2, + turbo4v3, turbo3, turbo3v2, turbo8, turbo8v2, turbo8v4, all + (default: none). Comma-separated for multiple: none,turbo4v2 --context SIZE Comma-separated context sizes (default: all 11 sizes for scaling methods) - --quick Quick mode: 128 + 1024 + 4096 tokens only + --quick Quick mode: 128 + 1024 + 4096 + 32768 tokens only + --ppl Track per-token perplexity during generation --kld Compute KL divergence vs bf16/8bit baseline --baseline Auto-select highest-fidelity variant (bf16 → 8bit → 4bit) --batch N Run N concurrent generations (default: 1) @@ -90,13 +98,15 @@ Model families: Custom HuggingFace model Examples: - ./scripts/benchmark.sh --model qwen35-0.8b # Simple eval - ./scripts/benchmark.sh --model qwen35-9b --method summarization --quick # Fast summarization + ./scripts/benchmark.sh --model qwen35-0.8b # Simple eval + ./scripts/benchmark.sh --model qwen35-9b --method summarization --quick # Fast summarization ./scripts/benchmark.sh --model qwen35-0.8b --method wikitext2 --context 1024 - ./scripts/benchmark.sh --model qwen35-0.8b --quant bf16 --kv none # bf16 baseline - ./scripts/benchmark.sh --model qwen35-0.8b --quant all --kv all --quick # Full matrix - ./scripts/benchmark.sh --model qwen35-9b --kv affine4 --kld # With KLD - ./scripts/benchmark.sh --model nemotron-cascade-2 --quant 4bit # Nemotron Cascade 2 (alias) + ./scripts/benchmark.sh --model qwen35-0.8b --quant bf16 --kv none # bf16 baseline + ./scripts/benchmark.sh --model qwen35-0.8b --quant all --kv all --quick # Full matrix + ./scripts/benchmark.sh --model qwen35-9b --kv affine4 --kld # With KLD + ./scripts/benchmark.sh --model qwen35-0.8b,qwen35-2b --kv none,turbo4v2 --quick # Multi-model sweep + ./scripts/benchmark.sh --model qwen35-0.8b --method simple,summarization # Two methods + ./scripts/benchmark.sh --model nemotron-cascade-2 --quant 4bit # Nemotron (alias) HELP } @@ -129,11 +139,19 @@ if [ -z "$MODEL" ]; then exit 1 fi -# Validate method -case "$METHOD" in - simple|summarization|wikitext2|niah|multi-turn|tool-calling) ;; - *) log_error "Unknown method: $METHOD"; exit 1 ;; -esac +# Build model list (comma-separated for multi-model sweeps) +MODELS=() +IFS=',' read -ra MODELS <<< "$MODEL" + +# Build method list (comma-separated for multi-method sweeps) +METHODS=() +IFS=',' read -ra METHODS <<< "$METHOD" +for m in "${METHODS[@]}"; do + case "$m" in + simple|summarization|wikitext2|niah|multi-turn|tool-calling) ;; + *) log_error "Unknown method: $m"; exit 1 ;; + esac +done # Build quant list QUANTS=() @@ -142,7 +160,7 @@ if $BASELINE; then elif [ "$QUANT" = "all" ]; then QUANTS=("bf16" "8bit" "4bit") else - QUANTS=("$QUANT") + IFS=',' read -ra QUANTS <<< "$QUANT" fi # Build KV list @@ -167,10 +185,10 @@ log_info "║ Inference Benchmarks ║" log_info "║ RELEASE MODE ║" log_info "╚══════════════════════════════════════════╝" log_info "" -log_info "Model: $MODEL" -log_info "Method: $METHOD" -log_info "Quant: $(IFS=,; echo "${QUANTS[*]}")" -log_info "KV: $(IFS=,; echo "${KVS[*]}")" +log_info "Models: $(IFS=,; echo "${MODELS[*]}")" +log_info "Methods: $(IFS=,; echo "${METHODS[*]}")" +log_info "Quants: $(IFS=,; echo "${QUANTS[*]}")" +log_info "KVs: $(IFS=,; echo "${KVS[*]}")" $KLD && log_info "KLD: yes" $THINK && log_info "Think: yes" [ "$BATCH" -gt 1 ] && log_info "Batch: $BATCH" @@ -194,79 +212,61 @@ fi log_info "Running benchmarks..." echo "" -for q in "${QUANTS[@]}"; do - for kv in "${KVS[@]}"; do - # Set env vars for the backend - export MLX_BENCH_MODEL="$MODEL" - export MLX_BENCH_METHOD="$METHOD" - export MLX_BENCH_KV="$kv" - - if [ "$q" = "baseline" ]; then - export MLX_BENCH_BASELINE=1 - unset MLX_BENCH_QUANT - else - unset MLX_BENCH_BASELINE - export MLX_BENCH_QUANT="$q" - fi - - if [ -n "$CONTEXTS" ]; then - export MLX_BENCH_CONTEXT="$CONTEXTS" - else - unset MLX_BENCH_CONTEXT - fi - - if $KLD; then - export MLX_BENCH_KLD=1 - else - unset MLX_BENCH_KLD - fi - - if ${PPL:-false}; then - export MLX_BENCH_PPL=1 - else - unset MLX_BENCH_PPL - fi - - if [ "$BATCH" -gt 1 ]; then - export MLX_BENCH_BATCH="$BATCH" - else - unset MLX_BENCH_BATCH - fi - - if $THINK; then - export MLX_BENCH_THINK=1 - else - unset MLX_BENCH_THINK - fi - - log_info "Running: quant=$q kv=$kv method=$METHOD" - - # Stream filtered output in real-time. - # - # Swift Testing (the `@Test` framework) captures stdout from tests and - # only emits it after each test completes — so `print()` inside the - # test body never streams when `swift test` is piped (non-TTY). - # Wrapping with `script -q /dev/null` allocates a PTY for swift test, - # which bypasses Swift Testing's capture and lets prints flush live. - # The Swift test also calls setlinebuf(stdout) as a belt-and-suspenders. - # grep --line-buffered ensures matched lines appear without delay. - # Full output captured to $TMPOUT for post-mortem on failure. - TMPOUT=$(mktemp) - script -q /dev/null swift test --skip-build -c release --filter "benchmark" 2>&1 \ - | tee "$TMPOUT" \ - | grep -E --line-buffered "\[ENV\]|\[WARMUP\]|\[BENCH\]|\[MEM\]|\[KLD\]|\[RESULT\]|\[KV-QUANT\]|\[TURBO\]|\[PROGRESS\]|Test.*passed|Test.*failed|[Ee]rror|[Ff]atal|BenchmarkError|threw|[Ee]xception|issue at" - EXIT_CODE=${PIPESTATUS[0]} - - if [ "$EXIT_CODE" -ne 0 ]; then - log_error "Run failed (exit code $EXIT_CODE, quant=$q kv=$kv):" - # Show additional context from the full output - grep -iE "error|fatal|BenchmarkError|threw|exception|exceeds|issue" "$TMPOUT" | tail -20 - fi - - rm -f "$TMPOUT" - echo "" +# Common env vars (stable across all permutations). +if [ -n "$CONTEXTS" ]; then export MLX_BENCH_CONTEXT="$CONTEXTS"; else unset MLX_BENCH_CONTEXT; fi +if $KLD; then export MLX_BENCH_KLD=1; else unset MLX_BENCH_KLD; fi +if ${PPL:-false}; then export MLX_BENCH_PPL=1; else unset MLX_BENCH_PPL; fi +if [ "$BATCH" -gt 1 ]; then export MLX_BENCH_BATCH="$BATCH"; else unset MLX_BENCH_BATCH; fi +if $THINK; then export MLX_BENCH_THINK=1; else unset MLX_BENCH_THINK; fi + +TOTAL_RUNS=$(( ${#MODELS[@]} * ${#METHODS[@]} * ${#QUANTS[@]} * ${#KVS[@]} )) +RUN_INDEX=0 +FAILED_RUNS=() + +for model in "${MODELS[@]}"; do + for method in "${METHODS[@]}"; do + for q in "${QUANTS[@]}"; do + for kv in "${KVS[@]}"; do + RUN_INDEX=$(( RUN_INDEX + 1 )) + + export MLX_BENCH_MODEL="$model" + export MLX_BENCH_METHOD="$method" + export MLX_BENCH_KV="$kv" + + if [ "$q" = "baseline" ]; then + export MLX_BENCH_BASELINE=1 + unset MLX_BENCH_QUANT + else + unset MLX_BENCH_BASELINE + export MLX_BENCH_QUANT="$q" + fi + + log_info "[$RUN_INDEX/$TOTAL_RUNS] model=$model method=$method quant=$q kv=$kv" + + # Stream filtered output in real-time via a PTY (script -q) so Swift Testing + # flushes print() calls mid-test. Full output captured for post-mortem. + TMPOUT=$(mktemp) + script -q /dev/null swift test --skip-build -c release --filter "benchmark" 2>&1 \ + | tee "$TMPOUT" \ + | grep -E --line-buffered "\[ENV\]|\[WARMUP\]|\[BENCH\]|\[MEM\]|\[KLD\]|\[RESULT\]|\[KV-QUANT\]|\[TURBO\]|\[PROGRESS\]|Test.*passed|Test.*failed|[Ee]rror|[Ff]atal|BenchmarkError|threw|[Ee]xception|issue at" + EXIT_CODE=${PIPESTATUS[0]} + + if [ "$EXIT_CODE" -ne 0 ]; then + log_error "Run failed (exit=$EXIT_CODE model=$model method=$method quant=$q kv=$kv):" + grep -iE "error|fatal|BenchmarkError|threw|exception|exceeds|issue" "$TMPOUT" | tail -20 + FAILED_RUNS+=("$model/$method/$q/$kv") + fi + + rm -f "$TMPOUT" + echo "" + done + done done done -log_info "Benchmark complete!" -log_info "Results saved to benchmarks/" +log_info "Benchmark complete! $((TOTAL_RUNS - ${#FAILED_RUNS[@]}))/$TOTAL_RUNS runs succeeded." +if [ ${#FAILED_RUNS[@]} -gt 0 ]; then + log_warn "Failed runs:" + for r in "${FAILED_RUNS[@]}"; do log_warn " - $r"; done +fi +log_info "Results: benchmarks/{chip}-{ram}-$(date +%Y-%m-%d).md" From a16b8dd5649c2c1180a5eee71bea1ceed85a21d4 Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Thu, 16 Apr 2026 12:08:31 -0600 Subject: [PATCH 4/5] bench: migrate InferenceBenchmark to 3.x HubClient loader MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- Tests/Benchmarks/InferenceBenchmark.swift | 242 ++++------------------ 1 file changed, 39 insertions(+), 203 deletions(-) diff --git a/Tests/Benchmarks/InferenceBenchmark.swift b/Tests/Benchmarks/InferenceBenchmark.swift index 3b37365a47..7011b4c8e1 100644 --- a/Tests/Benchmarks/InferenceBenchmark.swift +++ b/Tests/Benchmarks/InferenceBenchmark.swift @@ -2,203 +2,24 @@ import Foundation import Testing import MLX import MLXNN -@testable import MLXLMCommon +import MLXLMCommon import MLXLLM +import HuggingFace import MLXHuggingFace import Tokenizers -// MARK: - HuggingFace Integration (Benchmark) - -/// Minimal HuggingFace downloader for benchmark model loading. -/// Downloads model snapshots using the HF Hub HTTP API + URLSession. -private struct HFDownloader: Downloader { - func download( - id: String, - revision: String?, - matching patterns: [String], - useLatest: Bool, - progressHandler: @Sendable @escaping (Progress) -> Void - ) async throws -> URL { - let rev = revision ?? "main" - // Check local HF cache first - let cacheDir = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent(".cache/huggingface/hub") - .appendingPathComponent("models--\(id.replacingOccurrences(of: "/", with: "--"))") - .appendingPathComponent("snapshots") - - // If cached snapshot exists and we don't need latest, use it - if !useLatest, let snapshots = try? FileManager.default.contentsOfDirectory( - at: cacheDir, includingPropertiesForKeys: nil - ), let first = snapshots.first { - return first - } - - // Download using huggingface_hub CLI (requires `pip install huggingface_hub`) - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/env") - let patternsArg = patterns.map { "--include=\($0)" }.joined(separator: " ") - process.arguments = [ - "bash", "-c", - "huggingface-cli download \(id) --revision \(rev) \(patternsArg) --local-dir-use-symlinks false 2>/dev/null | tail -1" - ] - let pipe = Pipe() - process.standardOutput = pipe - try process.run() - process.waitUntilExit() - - let output = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)? - .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - - if !output.isEmpty, FileManager.default.fileExists(atPath: output) { - return URL(fileURLWithPath: output) - } - - // Fallback: check cache again (download may have populated it) - if let snapshots = try? FileManager.default.contentsOfDirectory( - at: cacheDir, includingPropertiesForKeys: nil - ), let first = snapshots.first { - return first - } - - throw NSError(domain: "HFDownloader", code: 1, userInfo: [ - NSLocalizedDescriptionKey: "Failed to download \(id). Install huggingface-cli: pip install huggingface_hub" - ]) - } -} - -/// Tokenizer loader that uses swift-transformers' AutoTokenizer (real BPE/SentencePiece). -private struct HFTokenizerLoader: TokenizerLoader { - func load(from directory: URL) async throws -> any MLXLMCommon.Tokenizer { - let upstream = try await AutoTokenizer.from(modelFolder: directory) - return TokenizerBridge(upstream) - } -} - -/// Bridges swift-transformers' Tokenizer to MLXLMCommon.Tokenizer. -private struct TokenizerBridge: MLXLMCommon.Tokenizer, @unchecked Sendable { - private let upstream: any Tokenizers.Tokenizer - - init(_ upstream: any Tokenizers.Tokenizer) { self.upstream = upstream } - - func encode(text: String, addSpecialTokens: Bool) -> [Int] { - upstream.encode(text: text, addSpecialTokens: addSpecialTokens) - } - func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { - upstream.decode(tokens: tokenIds, skipSpecialTokens: skipSpecialTokens) - } - func convertTokenToId(_ token: String) -> Int? { upstream.convertTokenToId(token) } - func convertIdToToken(_ id: Int) -> String? { upstream.convertIdToToken(id) } - - var bosToken: String? { upstream.bosToken } - var eosToken: String? { upstream.eosToken } - var unknownToken: String? { upstream.unknownToken } - - func applyChatTemplate( - messages: [[String: any Sendable]], - tools: [[String: any Sendable]]?, - additionalContext: [String: any Sendable]? - ) throws -> [Int] { - return try upstream.applyChatTemplate( - messages: messages, - tools: tools, - additionalContext: additionalContext - ) - } -} +// MARK: - HuggingFace Integration -/// Minimal tokenizer that reads tokenizer.json for vocab and merges. -/// Supports basic encode/decode and applyChatTemplate via tokenizer_config.json. -/// TODO: This is a simplified implementation — for full compatibility, add swift-transformers -/// to Package.swift as a test dependency. -private struct SimpleJSONTokenizer: MLXLMCommon.Tokenizer, @unchecked Sendable { - let vocab: [String: Int] - let reverseVocab: [Int: String] - let _bosToken: String? - let _eosToken: String? - let _unknownToken: String? - let chatTemplate: String? - - init(directory: URL) throws { - let tokenizerURL = directory.appendingPathComponent("tokenizer.json") - let configURL = directory.appendingPathComponent("tokenizer_config.json") - - // Load vocab from tokenizer.json - var loadedVocab: [String: Int] = [:] - if FileManager.default.fileExists(atPath: tokenizerURL.path), - let data = try? Data(contentsOf: tokenizerURL), - let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], - let model = json["model"] as? [String: Any], - let v = model["vocab"] as? [String: Int] { - loadedVocab = v - } - self.vocab = loadedVocab - self.reverseVocab = Dictionary(uniqueKeysWithValues: loadedVocab.map { ($1, $0) }) - - // Load config for special tokens and chat template - var bos: String? = nil - var eos: String? = nil - var unk: String? = nil - var template: String? = nil - if FileManager.default.fileExists(atPath: configURL.path), - let data = try? Data(contentsOf: configURL), - let config = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { - if let t = config["bos_token"] as? String { bos = t } - else if let d = config["bos_token"] as? [String: Any] { bos = d["content"] as? String } - if let t = config["eos_token"] as? String { eos = t } - else if let d = config["eos_token"] as? [String: Any] { eos = d["content"] as? String } - if let t = config["unk_token"] as? String { unk = t } - else if let d = config["unk_token"] as? [String: Any] { unk = d["content"] as? String } - template = config["chat_template"] as? String - } - self._bosToken = bos - self._eosToken = eos - self._unknownToken = unk - self.chatTemplate = template - } - - func encode(text: String, addSpecialTokens: Bool) -> [Int] { - // Simple whitespace tokenization fallback — real BPE requires swift-transformers - text.split(separator: " ").compactMap { vocab[String($0)] } - } - - func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { - tokenIds.compactMap { reverseVocab[$0] }.joined(separator: " ") - } - - func convertTokenToId(_ token: String) -> Int? { vocab[token] } - func convertIdToToken(_ id: Int) -> String? { reverseVocab[id] } - - var bosToken: String? { _bosToken } - var eosToken: String? { _eosToken } - var unknownToken: String? { _unknownToken } - - func applyChatTemplate( - messages: [[String: any Sendable]], - tools: [[String: any Sendable]]?, - additionalContext: [String: any Sendable]? - ) throws -> [Int] { - // Minimal chat template: concatenate message contents - // Full Jinja template support requires swift-transformers - let text = messages.compactMap { $0["content"] as? String }.joined(separator: "\n") - return encode(text: text) - } -} - -/// Convenience extension providing the pre-alpha `loadContainer(configuration:progressHandler:)` API. -/// Uses a minimal HuggingFace downloader and JSON-based tokenizer loader. -extension LLMModelFactory { - func loadContainer( - configuration: ModelConfiguration, - progressHandler: @Sendable @escaping (Progress) -> Void = { _ in } - ) async throws -> ModelContainer { - try await loadContainer( - from: HFDownloader(), - using: HFTokenizerLoader(), - configuration: configuration, - progressHandler: progressHandler - ) - } -} +// Macro-generated bridges from MLXHuggingFace: +// - `#hubDownloader()` wraps `HubClient.default` (cache-first; auto-detects +// `~/.cache/huggingface/hub` unless `HF_HUB_CACHE` / `HF_HOME` override it) +// as an `MLXLMCommon.Downloader`. +// - `#huggingFaceTokenizerLoader()` wraps swift-transformers' `AutoTokenizer` +// as an `MLXLMCommon.TokenizerLoader`. +// +// The pattern mirrors `IntegrationTesting/IntegrationTestingTests/ToolCallIntegrationTests.swift`. +private let benchmarkDownloader: any Downloader = #hubDownloader() +private let benchmarkTokenizerLoader: any TokenizerLoader = #huggingFaceTokenizerLoader() // MARK: - Thinking Budget Processor @@ -1055,12 +876,15 @@ struct InferenceBenchmarks { : ModelConfiguration(id: baselineVariant.repoId, extraEOSTokens: Set(family.extraEOSTokens)) let baselineContainer = try await LLMModelFactory.shared.loadContainer( - configuration: baselineConfig - ) { p in - if p.fractionCompleted < 0.01 || p.fractionCompleted > 0.99 { - print("[KLD] Loading baseline: \(String(format: "%.0f", p.fractionCompleted * 100))%") + from: benchmarkDownloader, + using: benchmarkTokenizerLoader, + configuration: baselineConfig, + progressHandler: { p in + if p.fractionCompleted < 0.01 || p.fractionCompleted > 0.99 { + print("[KLD] Loading baseline: \(String(format: "%.0f", p.fractionCompleted * 100))%") + } } - } + ) // Prepare input with the baseline model's tokenizer let kldInput = try await baselineContainer.prepare( @@ -1231,11 +1055,20 @@ struct InferenceBenchmarks { let batchStart = Date() + // Sendable capture for the task group: UserInput itself isn't Sendable, but + // its constructor inputs (`[Message]` + optional `[String: any Sendable]`) + // are. Rebuild a fresh UserInput inside each task from these primitives. + let taskMessages = allMessages + let taskAdditionalContext = additionalContext + let results: [BatchResult] = try await withThrowingTaskGroup(of: BatchResult.self) { group in for _ in 0.. 0.99 { - print("[BENCH] Loading: \(String(format: "%.0f", p.fractionCompleted * 100))%") + from: benchmarkDownloader, + using: benchmarkTokenizerLoader, + configuration: modelConfig, + progressHandler: { p in + if p.fractionCompleted < 0.01 || p.fractionCompleted > 0.99 { + print("[BENCH] Loading: \(String(format: "%.0f", p.fractionCompleted * 100))%") + } } - } + ) ModelCache.shared.set(repoId, container) return container } From 227df26884a6f9f4b442c428c71bb99ed7ec6056 Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Thu, 16 Apr 2026 12:08:44 -0600 Subject: [PATCH 5/5] bench: add M1 Max and M5 Max baselines, gitignore writer state sidecars MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- .gitignore | 7 +- benchmarks/m1-max-64gb-2026-04-16.md | 518 ++++++++++++++++++++++++++ benchmarks/m5-max-128gb-2026-04-16.md | 297 +++++++++++++++ 3 files changed, 821 insertions(+), 1 deletion(-) create mode 100644 benchmarks/m1-max-64gb-2026-04-16.md create mode 100644 benchmarks/m5-max-128gb-2026-04-16.md diff --git a/.gitignore b/.gitignore index ace725cf1b..4d65f7193e 100644 --- a/.gitignore +++ b/.gitignore @@ -96,4 +96,9 @@ iOSInjectionProject/ .vscode # Claude -.claude/ \ No newline at end of file +.claude/ + +# Benchmark writer state sidecars. The markdown reports in benchmarks/ are +# committed as baselines; the JSON state is local-only so the writer can +# re-render the markdown across processes within a single sweep. +benchmarks/.*.state.json \ No newline at end of file diff --git a/benchmarks/m1-max-64gb-2026-04-16.md b/benchmarks/m1-max-64gb-2026-04-16.md new file mode 100644 index 0000000000..51330e0ca5 --- /dev/null +++ b/benchmarks/m1-max-64gb-2026-04-16.md @@ -0,0 +1,518 @@ +# Benchmark: Apple M1 Max (applegpu_g13s) — 2026-04-16 + +**Hardware:** Apple M1 Max (applegpu_g13s), 64GB unified memory (GPU limit 48GB) +**OS:** macOS 15.7.4 +**Branch:** `alpha` +**Commit:** `8491040 adding .claude to gitignore` +**NAX:** ENABLED ✓ +**Created:** 2026-04-16T17:32:32Z + +## Models + +### Qwen3.5 0.8B + +**Model:** `mlx-community/Qwen3.5-0.8B-bf16` + +#### Results + +| Config | Ctx | Prompt | Prefill tok/s | Decode tok/s | TTFT | Think PPL | Gen PPL | Think KLD | Gen KLD | GPU Base | GPU Peak | +|--------|----:|-------:|--------------:|-------------:|-----:|----------:|--------:|----------:|--------:|---------:|---------:| +| bf16 / no-quant / summarization | 128 | 109 | 210.8 | 102.2 | 518ms | — | — | — | — | 1.40GB | 1.60GB | +| 4bit / no-quant / summarization | 128 | 109 | 231.2 | 134.2 | 472ms | — | — | — | — | 404MB | 580MB | +| 4bit / no-quant / simple | 4096 | 49 | 133.3 | 116.0 | 369ms | — | — | — | — | 404MB | 613MB | +| 4bit / turbo4v2 / simple | 4096 | 49 | 176.8 | 113.4 | 279ms | — | — | — | — | 404MB | 613MB | +| 8bit / no-quant / simple | 4096 | 49 | 172.3 | 96.9 | 286ms | — | — | — | — | 763MB | 976MB | +| 8bit / turbo4v2 / simple | 4096 | 49 | 149.8 | 121.4 | 329ms | — | — | — | — | 763MB | 962MB | + +#### Output samples + +**bf16 / no-quant / summarization** + +``` +Based on the excerpt you provided, here is a summary: The text opens with a nostalgic and dramatic monologue written by Zelda in response to "Once again to Zelda." The song asks her to wear a golden hat if it moves her, to bounce high even for herself if she can't help it, and to cry with the phrase "Lover, gold-hatted." The lyrics suggest that the characters in the story are a couple seeking em +``` + +**4bit / no-quant / summarization** + +``` +Based on the text you provided, which is a famous excerpt from **The Song of the Golden Rose** written by F. Scott Fitzgerald in 1923, here is a summary of its content: **What the text says:** The excerpt contains an original dialogue between Zelda and a golden hat character. It begins with the dialogue in English (written on page 1, though the formatting suggests it is often associated with page +``` + +**4bit / no-quant / simple** + +``` +Thinking Process: 1. **Analyze the Request:** The user is asking "Hello! What is your name and what can you help me with?". I need to answer this politely. 2. **Identify Key Information:** * My name (as an AI, I'm not human). Wait, the user isn't asking *my* name. The question is in English and informal ("Hello!"). * Actually, since I am an AI (in the context of this prompt), I don +``` + +**4bit / turbo4v2 / simple** + +``` +The user is asking me to introduce myself and help them with what. I am Qwen3.5, my name is Qwen3.5, and I can help with a variety of tasks, including problem-solving, coding assistance, data analysis, creative writing, logical reasoning, and more. I am **Qwen3.5**. I can assist with various tasks like problem-solving, coding assistance, creative writing, logical reasoning, and data anal +``` + +**8bit / no-quant / simple** + +``` +Thinking Process: 1. **Analyze the Request:** The user is asking for my name and what I can help with. 2. **Determine My Role:** I am Qwen3.5, a large language model developed by Tongyi Lab. 3. **Identify Help Capabilities:** I can help with: * Text generation (writing creative stories, coding, explanations). * Question answering. * Problem-solving and logic reasoning. * +``` + +**8bit / turbo4v2 / simple** + +``` +Thinking Process: 1. **Analyze the Request:** The user is asking two things about me (the AI assistant persona) at first: * "What is your name and what can you help me with?" 2. **Identify the Persona:** I am Qwen3.5, a large-scale language model developed by Tongyi Lab. My name is "Qwen3.5". I am an AI assistant and language model developed by Alibaba Cloud. 3. **Identify Capabilities +``` + +#### Parameters + +**bf16 / no-quant / summarization** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | None (FP16) | +| Max KV size | 128 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | nil | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | nil | +| Think end token id | nil | +| Thinking phase prefilled | false | +| Collect per-token data | false | +| Track perplexity | false | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 0 | +| Thinking (effective) | No | +| Perplexity tracking (MLX_BENCH_PPL) | No | +| KL divergence (MLX_BENCH_KLD) | No | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ No system role message; user-only messages per methodology (no full user prompt in this report). + +**4bit / no-quant / summarization** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | None (FP16) | +| Max KV size | 128 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | nil | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | nil | +| Think end token id | nil | +| Thinking phase prefilled | false | +| Collect per-token data | false | +| Track perplexity | false | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 0 | +| Thinking (effective) | No | +| Perplexity tracking (MLX_BENCH_PPL) | No | +| KL divergence (MLX_BENCH_KLD) | No | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ No system role message; user-only messages per methodology (no full user prompt in this report). + +**4bit / no-quant / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | None (FP16) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | nil | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +**4bit / turbo4v2 / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | TurboQuant (turbo4v2) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | turbo4v2 | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +**8bit / no-quant / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | None (FP16) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | nil | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +**8bit / turbo4v2 / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | TurboQuant (turbo4v2) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | turbo4v2 | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +### Qwen3.5 2B + +**Model:** `mlx-community/Qwen3.5-2B-4bit` + +#### Results + +| Config | Ctx | Prompt | Prefill tok/s | Decode tok/s | TTFT | Think PPL | Gen PPL | Think KLD | Gen KLD | GPU Base | GPU Peak | +|--------|----:|-------:|--------------:|-------------:|-----:|----------:|--------:|----------:|--------:|---------:|---------:| +| 4bit / no-quant / simple | 4096 | 49 | 131.5 | 116.4 | 374ms | — | — | — | — | 1010MB | 1.20GB | +| 4bit / turbo4v2 / simple | 4096 | 49 | 125.0 | 102.1 | 393ms | — | — | — | — | 1010MB | 1.20GB | +| 8bit / no-quant / simple | 4096 | 49 | 116.2 | 87.5 | 423ms | — | — | — | — | 1.86GB | 2.07GB | +| 8bit / turbo4v2 / simple | 4096 | 49 | 134.9 | 96.5 | 365ms | — | — | — | — | 1.86GB | 2.07GB | + +#### Output samples + +**4bit / no-quant / simple** + +``` +The user is asking my name and what I can do. I need to respond clearly, confirming I'm Qwen3.5 from Tongyi Lab. I'll keep it concise since the user asked for conciseness first. My identity is clear enough to avoid unnecessary detail upfront. **Response Plan:** 1. State the name: Qwen (specifically Qwen3.5, but I'll stick to Qwen for broader scope) 2. Directly answer the second question about w +``` + +**4bit / turbo4v2 / simple** + +``` + I'm Qwen3.5, developed by Alibaba Cloud's Tongyi Lab. I can assist with tasks like writing, code generation, logical reasoning, and creative content creation. How can I help you today? +``` + +**8bit / no-quant / simple** + +``` +Okay, the user is asking for my name and capabilities. Let me check the system instructions first. I need to make sure they are in line with the guidelines. The user mentioned that if the response is too technical, I should use simple terms. However, this request is straightforward. First, I should state my name clearly. My name is Qwen3.5. Then, list the main features without technical jargon. C +``` + +**8bit / turbo4v2 / simple** + +``` +The user is asking for my introduction and capabilities. I am Qwen3.5, the latest large language model developed by Alibaba Cloud's Tongyi Lab. I should briefly state my identity and clarify what I can help with, keeping the response concise as requested. 1. State identity: Qwen3.5 by Alibaba Cloud's Tongyi Lab. 2. Clarify capabilities: General knowledge, complex tasks (code, analysis), and spe +``` + +#### Parameters + +**4bit / no-quant / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | None (FP16) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | nil | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +**4bit / turbo4v2 / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | TurboQuant (turbo4v2) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | turbo4v2 | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +**8bit / no-quant / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | None (FP16) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | nil | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +**8bit / turbo4v2 / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | TurboQuant (turbo4v2) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | turbo4v2 | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +## Methodology + +See [benchmarks/README.md](README.md#methodology) for method definitions, perplexity / KLD computation, and memory accounting. diff --git a/benchmarks/m5-max-128gb-2026-04-16.md b/benchmarks/m5-max-128gb-2026-04-16.md new file mode 100644 index 0000000000..948db8199a --- /dev/null +++ b/benchmarks/m5-max-128gb-2026-04-16.md @@ -0,0 +1,297 @@ +# Baseline: M5 Max 128GB — 2026-04-16 + +**Hardware:** M5 Max, 128GB unified memory +**OS:** macOS 26.3 (Darwin 25.3.0) +**Branch:** `alpha` with PR #44 (Gemma 4 coherence + real BPE tokenizer) and PR #45 (Gemma 4 26B MoE + Qwen3.5 GDN fused decode) +**NAX:** enabled +**Method:** `MLX_BENCH_METHOD=summarization`, swift mode (native Swift) and bridge mode (`NATIVE_PREFILL=1`, only meaningful for Gemma 4) +**Coverage:** 14 models × 8 context points (128 → 32k) × swift & bridge paths, plus 8k coherency samples + +## TL;DR + +| Model | Prefill @ 1k | Decode @ 1k | Coherent @ 8k | +|-------|-------------:|------------:|---------------| +| **Gemma 4 E2B (2B)** | **20,206** | 195 | ✅ | +| Qwen2.5 3B | 6,930 | 184 | ✅ | +| Llama 3.2 3B | 6,837 | 202 | ✅ | +| Phi-4 Mini | 6,162 | 163 | ✅ | +| Qwen3 4B | 5,641 | 162 | ✅ (thinking) | +| Qwen3-Coder 30B MoE | 3,469 | 107 | ✅ | +| Mistral 7B | 3,434 | 108 | ✅ | +| Nemotron 30B-A3B | 2,727 | 155 | ✅ | +| GPT-OSS 20B | 2,465 | 111 | ✅ (analysis channel) | +| MiniMax M2 (~46B) | 732 | 57 | ✅ | +| Gemma 4 26B A4B | 642 | 53 | ✅ | +| Qwen3.5 2B (GDN) | 659 | 285 | ✅ | +| Qwen3.5 9B (GDN) | 343 | 93 | ✅ (thinking) | +| Qwen3.5 35B-A3B (GDN MoE) | 271 | 135 | ✅ (thinking) | + +**Key findings:** +- **NAX delivers 2–3.5x prefill speedup** across every model. +- **Bridge vs Swift is within noise for every model except Gemma 4** — only Gemma 4 has a real dlopen-based C++ prefill bridge. For all other models the "bridge" path falls through to Swift. +- **Gemma 4 E2B peaks at 20K tok/s prefill** at 1024 context. +- **Gemma 4 26B A4B** now loads and runs — 600 tok/s prefill, stable 50 tok/s decode through 8k. +- **Qwen3.5 GatedDeltaNet decode** now uses the fused `gatedDeltaStepFused` Metal kernel at T=1; decode is +20–34% on 2B/9B and +128–172% on the 35B MoE (GDN + MoE compounds the dispatch-overhead savings). +- All 14 models produce coherent Gatsby summaries at 8k context. + +## Speed — Prefill / Decode (tokens/sec) + +### Llama-3.2-3B-Instruct-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 2798.5 | 210.1 | 2934.9 | 210.0 | +| 512 | 5816.8 | 202.1 | 5823.8 | 201.7 | +| 1024 | 6837.0 | 201.8 | 6755.9 | 202.3 | +| 2048 | 8111.3 | 193.6 | 8112.2 | 192.3 | +| 4096 | 7663.5 | 178.4 | 7704.1 | 177.8 | +| 8192 | 6995.8 | 153.9 | 6971.3 | 153.3 | +| 16384 | 5849.0 | 123.0 | 5844.6 | 122.1 | +| 32768 | 4174.7 | 86.5 | 4198.2 | 85.5 | + +### MiniMax-M2.7-ConfigI-MLX + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 195.9 | 60.0 | 196.4 | 60.1 | +| 512 | 563.3 | 58.2 | 558.5 | 58.3 | +| 1024 | 732.5 | 56.8 | 846.1 | 56.9 | +| 2048 | 870.8 | 54.5 | 812.8 | 54.6 | +| 4096 | 861.8 | 51.2 | 928.7 | 51.1 | +| 8192 | 895.5 | 44.6 | 923.0 | 45.0 | +| 16384 | 815.0 | 38.3 | 829.2 | 38.1 | +| 32768 | 522.3 | 29.1 | 672.9 | 29.4 | + +### Mistral-7B-Instruct-v0.3-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 1991.5 | 111.5 | 1993.2 | 111.3 | +| 512 | 3181.7 | 110.8 | 3175.2 | 110.2 | +| 1024 | 3434.1 | 108.3 | 3437.6 | 106.7 | +| 2048 | 3530.8 | 105.8 | 3513.2 | 105.4 | +| 4096 | 3418.9 | 102.4 | 3426.9 | 101.5 | +| 8192 | 3199.7 | 93.1 | 3196.9 | 92.8 | +| 16384 | 2716.2 | 78.5 | 2739.4 | 78.3 | +| 32768 | 2041.4 | 56.5 | 2044.6 | 59.2 | + +### Nemotron-Cascade-2-30B-A3B-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 128.4 | 155.1 | 965.7 | 155.5 | +| 512 | 2313.5 | 155.7 | 2349.6 | 154.2 | +| 1024 | 2726.6 | 154.5 | 2711.6 | 152.9 | +| 2048 | 2527.0 | 153.5 | 2514.9 | 152.3 | +| 4096 | 2425.8 | 149.5 | 2430.5 | 152.1 | +| 8192 | 2356.1 | 148.0 | 2368.6 | 148.3 | +| 16384 | 2323.6 | 143.5 | 2323.7 | 143.3 | +| 32768 | 2218.4 | 133.8 | 2223.6 | 134.9 | + +### Phi-4-mini-instruct-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 2479.3 | 173.6 | 2405.1 | 172.4 | +| 512 | 5310.7 | 169.4 | 5418.5 | 167.9 | +| 1024 | 6161.8 | 162.9 | 6129.1 | 163.4 | +| 2048 | 6810.8 | 157.4 | 6806.0 | 156.1 | +| 4096 | 6594.3 | 145.3 | 6555.0 | 145.2 | +| 8192 | 6006.0 | 126.7 | 5997.1 | 126.3 | +| 16384 | 5020.7 | 101.3 | 5018.8 | 101.3 | +| 32768 | 3630.3 | 72.3 | 3577.5 | 72.3 | + +### Qwen2.5-3B-Instruct-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 2447.7 | 199.0 | 2527.1 | 198.8 | +| 512 | 6466.1 | 190.9 | 6252.3 | 192.3 | +| 1024 | 6929.6 | 183.5 | 7069.8 | 184.1 | +| 2048 | 7845.6 | 178.2 | 7990.8 | 178.2 | +| 4096 | 7763.9 | 176.2 | 7786.4 | 177.6 | +| 8192 | 7181.2 | 163.8 | 7196.7 | 164.6 | +| 16384 | 6089.4 | 140.7 | 6071.6 | 140.8 | +| 32768 | 4628.9 | 113.7 | 4644.2 | 113.9 | + +### Qwen3-4B-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 2185.3 | 172.2 | 2135.6 | 171.8 | +| 512 | 5038.4 | 168.2 | 4915.7 | 167.9 | +| 1024 | 5641.3 | 161.6 | 5613.0 | 161.0 | +| 2048 | 5911.1 | 154.1 | 5876.6 | 153.9 | +| 4096 | 5640.3 | 141.2 | 5626.1 | 140.7 | +| 8192 | 5002.1 | 121.9 | 4965.6 | 122.1 | +| 16384 | 4011.4 | 95.5 | 4008.7 | 95.4 | +| 32768 | 2729.4 | 66.8 | 2718.8 | 66.8 | + +### Qwen3-Coder-30B-A3B-Instruct-MLX-6bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 752.0 | 111.9 | 748.8 | 112.2 | +| 512 | 2366.6 | 109.0 | 2404.4 | 108.7 | +| 1024 | 3468.5 | 106.9 | 3499.3 | 106.5 | +| 2048 | 4378.6 | 101.9 | 4378.7 | 102.4 | +| 4096 | 3819.9 | 96.3 | 4267.6 | 96.6 | +| 8192 | 3787.3 | 85.7 | 3805.6 | 86.3 | +| 16384 | 3057.8 | 72.5 | 3075.0 | 72.5 | +| 32768 | 2080.5 | 56.4 | 2072.2 | 56.3 | + +### Qwen3.5-2B-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 735.6 | 289.6 | 735.6 | 289.6 | +| 512 | 738.1 | 287.9 | 738.1 | 287.9 | +| 1024 | 658.7 | 284.6 | 658.7 | 284.6 | +| 2048 | 632.6 | 278.9 | 632.6 | 278.9 | +| 4096 | 617.6 | 267.2 | 617.6 | 267.2 | +| 8192 | 639.8 | 247.8 | 639.8 | 247.8 | +| 16384 | 608.9 | 209.7 | 608.9 | 209.7 | +| 32768 | 625.8 | 164.4 | 625.8 | 164.4 | + +### Qwen3.5-35B-A3B-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 234.6 | 137.6 | 234.6 | 137.6 | +| 512 | 259.5 | 135.6 | 259.5 | 135.6 | +| 1024 | 270.7 | 134.8 | 270.7 | 134.8 | +| 2048 | 257.9 | 133.0 | 257.9 | 133.0 | +| 4096 | 259.3 | 132.5 | 259.3 | 132.5 | +| 8192 | 258.5 | 126.0 | 258.5 | 126.0 | +| 16384 | 247.6 | 120.9 | 247.6 | 120.9 | +| 32768 | 199.7 | 107.3 | 199.7 | 107.3 | + +### Qwen3.5-9B-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 354.2 | 94.8 | 354.2 | 94.8 | +| 512 | 307.1 | 93.4 | 307.1 | 93.4 | +| 1024 | 342.9 | 92.7 | 342.9 | 92.7 | +| 2048 | 321.9 | 90.6 | 321.9 | 90.6 | +| 4096 | 315.6 | 88.3 | 315.6 | 88.3 | +| 8192 | 322.0 | 85.2 | 322.0 | 85.2 | +| 16384 | 281.0 | 87.6 | 281.0 | 87.6 | +| 32768 | 279.2 | 80.5 | 279.2 | 80.5 | + +### gemma-4-26b-a4b-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 444.2 | 51.6 | 447.5 | 50.3 | +| 512 | 631.1 | 53.0 | 582.4 | 52.0 | +| 1024 | 642.3 | 52.7 | 594.4 | 51.2 | +| 2048 | 631.6 | 51.9 | 627.9 | 50.0 | +| 4096 | 621.6 | 51.7 | 620.9 | 49.6 | +| 8192 | 598.1 | 50.1 | 591.6 | 49.0 | +| 16384 | 547.0 | 47.2 | 569.3 | 47.2 | +| 32768 | 522.1 | 42.6 | — | — | + +### gemma-4-e2b-it-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 5000.3 | 193.7 | 5531.8 | 200.5 | +| 512 | 17845.7 | 194.4 | 17269.5 | 194.1 | +| 1024 | 20206.1 | 194.8 | 20149.1 | 195.4 | +| 2048 | 16744.6 | 193.5 | 16620.0 | 193.1 | +| 4096 | 13611.2 | 189.1 | 13564.3 | 188.9 | +| 8192 | 13321.7 | 179.7 | 13397.6 | 180.9 | +| 16384 | 12682.6 | 168.6 | 12675.1 | 168.1 | +| 32768 | 11292.0 | 145.0 | 11317.4 | 145.1 | + +### gpt-oss-20b-MXFP4-Q8 + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 379.6 | 113.6 | 969.3 | 111.5 | +| 512 | 2199.5 | 112.5 | 2278.2 | 111.6 | +| 1024 | 2465.3 | 110.7 | 2803.9 | 110.9 | +| 2048 | 3248.4 | 108.8 | 3285.8 | 113.3 | +| 4096 | 2534.4 | 106.9 | 3263.7 | 105.7 | +| 8192 | 2939.7 | 101.9 | 3203.2 | 101.2 | +| 16384 | 2943.7 | 92.1 | 3027.8 | 95.0 | +| 32768 | 2598.6 | 79.2 | 2614.8 | 81.8 | + + +## Coherency — 8k Context Output + +## gemma-4-e2b-it-4bit (swift) +``` +This is a fascinating excerpt from **The Great Gatsby** by F. Scott Fitzgerald, likely narrated by the character **Nick Carraway**. +``` + +## gemma-4-26b-a4b-4bit (swift) +``` +The excerpt is the opening of F. Scott Fitzgerald's *The Great Gatsby*, narrated by Nick Carraway. Nick introduces himself, recalls his father's advice about reserving judgment, and describes his move east to West Egg on Long Island the summer he met Gatsby. +``` + +## gpt-oss-20b-MXFP4-Q8 (swift) +``` +<|channel|>analysis<|message|>We need to summarize the content. The content is a long, somewhat chaotic text that appears to be a mash-up of "The Grea +``` + +## Llama-3.2-3B-Instruct-4bit (swift) +``` +The passage is the opening of F. Scott Fitzgerald's novel "The Great Gatsby". The story is narrated by Nick Carraway, a young man from the Midwest who +``` + +## Mistral-7B-Instruct-v0.3-4bit (swift) +``` +This is the first chapter of "The Great Gatsby" by F. Scott Fitzgerald. The novel is set in the summer of 1922 and follows the story of Nick Carraway, +``` + +## Nemotron-Cascade-2-30B-A3B-4bit (swift) +``` +We need to summarize the content above, which presumably is an excerpt or a parody of The Great Gatsby with a modern twist, but we need to summarize t +``` + +## Phi-4-mini-instruct-4bit (swift) +``` +Nick Carraway, a bond man living in East Egg, New York, recounts a summer evening spent visiting Daisy Buchanan, a distant cousin and a resident of a +``` + +## Qwen2.5-3B-Instruct-4bit (swift) +``` +The passage describes the protagonist's journey to East Egg, where he meets Tom Buchanan and his wife, Daisy. The interaction with Tom and Daisy revea +``` + +## Qwen3-4B-4bit (swift) +``` + +``` + +## Qwen3-Coder-30B-A3B-Instruct-MLX-6bit (swift) +``` +Here's a summary of the first chapter of *The Great Gatsby*: +``` + +## Qwen3.5-2B-4bit (swift) +``` +The provided text is the opening chapter of *The Great Gatsby* by F. Scott Fitzgerald. It is divided into three main sections: +``` + +## Qwen3.5-9B-4bit (swift) +``` +Thinking Process: +``` + +## Qwen3.5-35B-A3B-4bit (swift) +``` +Thinking Process: +``` + +## MiniMax-M2.7-ConfigI-MLX (swift) +``` +The user asks: "Summarize the content above." The content is a passage from The Great Gatsby, Chapter 1. Summarize the content. +``` + + +## Raw Log + +Full timestamped run log in `/tmp/overnight_bench/log.txt`