From f845618ae9d198ae8c2650b70c5f4cc20f0ce3ae Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Thu, 16 Apr 2026 17:22:46 -0600 Subject: [PATCH 1/2] bench: add --ngram flag, default n-gram speculative decoding off MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit alpha defaults `GenerateParameters.ngramSize` to 3 so library clients get trigram speculative decoding out of the box. That composite — speculation accept-rate × draft overhead — adds run-to-run variance that masks the primitive we actually want to measure in benchmarks (pure autoregressive decode tok/s). A 4096-ctx Qwen3.5 0.8B summarization row drifted ~10% vs a prior baseline that defaulted ngramSize to 0; investigation showed the whole delta was speculation accept-rate noise, not a real perf change. This PR makes benchmarks default to no speculation and adds a CLI flag to opt in explicitly when we want to measure the speculative path. Changes 1. `scripts/benchmark.sh` gains `--ngram SIZE`, default 0 (disabled). Value validated as a non-negative integer; exported as `MLX_BENCH_NGRAM=N` unconditionally so the harness always sees an explicit value. Logs `[INFO] N-gram: size=N` when non-zero. 2. `BenchEnv.ngramSize: Int` reads `MLX_BENCH_NGRAM`, defaults 0. Deliberately diverges from the library default (3) — library clients get the typical-use default; benchmarks get a clean primitive and opt in for speculative measurements. 3. Two `GenerateParameters` call sites in `InferenceBenchmark.swift` now pass `ngramSize: BenchEnv.ngramSize` and `maxNgramDraftTokens: BenchEnv.ngramSize` — the main `runGenerationBenchmark` and the batched-decode path. `wikitext2` and the KLD forced-decode path don't sample, so ngramSize has no effect there and we leave them alone. 4. `benchmarks/README.md` documents `--ngram SIZE` in the CLI table and `MLX_BENCH_NGRAM` in the environment-variable table, with a note on why the benchmark default diverges from the library default. Co-Authored-By: Claude Opus 4.7 (1M context) --- Tests/Benchmarks/InferenceBenchmark.swift | 20 ++++++++++++++++++++ benchmarks/README.md | 2 ++ scripts/benchmark.sh | 18 ++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/Tests/Benchmarks/InferenceBenchmark.swift b/Tests/Benchmarks/InferenceBenchmark.swift index 136ad25da5..9a4aab17e3 100644 --- a/Tests/Benchmarks/InferenceBenchmark.swift +++ b/Tests/Benchmarks/InferenceBenchmark.swift @@ -577,6 +577,22 @@ private enum BenchEnv { let v = raw.trimmingCharacters(in: .whitespacesAndNewlines) return v.isEmpty ? nil : v } + /// N-gram speculative-decoding size for the benchmark run. Default is 0 + /// (disabled) so benchmarks measure pure autoregressive decode rather + /// than a composite with variable accept-rate overhead. Set via + /// `--ngram N` → `MLX_BENCH_NGRAM=N`. + /// + /// This differs from the library's `GenerateParameters.ngramSize` + /// default (3) — the library picks a typical usable value; benchmarks + /// prefer a clean baseline and let the user opt in to measure the + /// speculative path explicitly. + static var ngramSize: Int { + guard let raw = ProcessInfo.processInfo.environment["MLX_BENCH_NGRAM"], + let v = Int(raw.trimmingCharacters(in: .whitespacesAndNewlines)), + v >= 0 + else { return 0 } + return v + } } // MARK: - Baseline Token Data @@ -1110,6 +1126,8 @@ struct InferenceBenchmarks { kvScheme: kv.kvScheme, additionalProcessors: additionalProcessors, reasoningEffort: BenchEnv.reasoningEffort ?? family.reasoningEffort, + ngramSize: BenchEnv.ngramSize, + maxNgramDraftTokens: BenchEnv.ngramSize, thinkStartTokenId: thinkStartId, thinkEndTokenId: thinkEndId, thinkingPhasePrefilled: thinkStartId != nil && !family.thinkingConfig.assistantPrefill.isEmpty, @@ -1416,6 +1434,8 @@ struct InferenceBenchmarks { presencePenalty: family.presencePenalty, prefillStepSize: 2048, kvScheme: kv.kvScheme, + ngramSize: BenchEnv.ngramSize, + maxNgramDraftTokens: BenchEnv.ngramSize, trackPerplexity: false ) diff --git a/benchmarks/README.md b/benchmarks/README.md index db90adfaca..6ea366591f 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -81,6 +81,7 @@ Then re-run your benchmark — it will recompile only the C/C++ target. | `--batch N` | Run N concurrent generations | `1` | | `--think` | Enable thinking mode for thinking-capable models | Off | | `--reasoning EFFORT` | Reasoning effort for models that support it (e.g. GPT-OSS). Values: `low`, `medium`, `high`. Ignored by models without a reasoning-effort setting. | `medium` | +| `--ngram SIZE` | N-gram speculative decoding size. `0` disables speculation entirely (pure autoregressive decode). `3` matches the library's typical-use default (trigram matching, 3-token drafts). Higher values require longer repeated sequences in generated text to hit. Disabled by default so benchmarks measure deterministic decode without accept-rate variance. | `0` | | `-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: @@ -363,6 +364,7 @@ All configuration is passed via environment variables, enabling any backend to i | `MLX_BENCH_BATCH` | integer | `1` | Number of concurrent generations | | `MLX_BENCH_THINK` | `1` | unset | Enable thinking mode | | `MLX_BENCH_REASONING` | `low`, `medium`, `high`, or passthrough | unset (falls back to the model family's registered default) | Reasoning effort for models that honour it (GPT-OSS). Plumbed into `GenerateParameters.reasoningEffort`; ignored by models whose chat templates don't consume it. | +| `MLX_BENCH_NGRAM` | non-negative integer | `0` | N-gram speculative-decoding size. Plumbed into both `GenerateParameters.ngramSize` and `maxNgramDraftTokens`. `0` disables speculation entirely; any positive value enables trigram-style drafting with N tokens of history matched and N draft tokens proposed per round. Benchmark default is `0` so measurements are deterministic; the library itself defaults to `3`. | | `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. | diff --git a/scripts/benchmark.sh b/scripts/benchmark.sh index d1b1afdfc0..3c1356654a 100755 --- a/scripts/benchmark.sh +++ b/scripts/benchmark.sh @@ -46,6 +46,7 @@ BASELINE=false BATCH=1 THINK=false REASONING="medium" +NGRAM=0 QUICK_CONTEXTS="128,1024,4096,32768" # ───────────────────────────────────────────── @@ -84,6 +85,11 @@ Options: Values: low, medium, high (default: medium). Maps to MLX_BENCH_REASONING; ignored by models without a reasoning_effort setting. + --ngram SIZE N-gram speculative decoding size (default: 0 = disabled). + Typical: 3 (trigram matching). Higher values require longer + repeated sequences in generated text to hit. Disabled by + default so benchmarks measure pure autoregressive decode — + set non-zero to evaluate speculative decoding speedup. -h, --help Show this help Model families: @@ -134,6 +140,7 @@ while [[ $# -gt 0 ]]; do --batch) BATCH="$2"; shift 2 ;; --think) THINK=true; shift ;; --reasoning) REASONING="$2"; shift 2 ;; + --ngram) NGRAM="$2"; shift 2 ;; -h|--help) show_help; exit 0 ;; *) log_error "Unknown argument: $1"; show_help; exit 1 ;; esac @@ -167,6 +174,12 @@ case "$REASONING" in *) log_warn "Unusual reasoning effort '$REASONING' (expected low/medium/high); passing through" ;; esac +# Validate ngram size — must be a non-negative integer. +if ! [[ "$NGRAM" =~ ^[0-9]+$ ]]; then + log_error "--ngram must be a non-negative integer (got: $NGRAM)" + exit 1 +fi + # Build quant list QUANTS=() if $BASELINE; then @@ -206,6 +219,7 @@ log_info "KVs: $(IFS=,; echo "${KVS[*]}")" $KLD && log_info "KLD: yes" $PPL && log_info "PPL: yes" $THINK && log_info "Think: yes (reasoning=$REASONING)" +[ "$NGRAM" -gt 0 ] && log_info "N-gram: size=$NGRAM" [ "$BATCH" -gt 1 ] && log_info "Batch: $BATCH" [ -n "$CONTEXTS" ] && log_info "Context: $CONTEXTS" log_info "" @@ -236,6 +250,10 @@ if $THINK; then export MLX_BENCH_THINK=1; else unset MLX_BENCH_THINK; fi # Reasoning effort — only set when non-default so unset tells the harness to # fall back to the model family's registered value. if [ "$REASONING" != "medium" ]; then export MLX_BENCH_REASONING="$REASONING"; else unset MLX_BENCH_REASONING; fi +# N-gram size — always export so the harness sees an explicit value (0 = off). +# Benchmark default is 0 to measure pure autoregressive decode; set --ngram N +# to evaluate speculative decoding speedup. +export MLX_BENCH_NGRAM="$NGRAM" TOTAL_RUNS=$(( ${#MODELS[@]} * ${#METHODS[@]} * ${#QUANTS[@]} * ${#KVS[@]} )) RUN_INDEX=0 From 64a8be002d731955fcaf5fd25d844cf20b4119df Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Thu, 16 Apr 2026 17:30:03 -0600 Subject: [PATCH 2/2] =?UTF-8?q?bench:=20configKeyExtras=20=E2=80=94=20dist?= =?UTF-8?q?inct=20config=20blocks=20for=20A/B=20on=20--ngram?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The writer grouped rows by a config key built from `quantization / kvConfig / scenario`. Two runs that differ only in a dimension outside that triple — e.g. two runs of `qwen35-0.8b 4bit turbo4v2 summarization`, one with `--ngram 0` and one with `--ngram 3` — collapsed into the same config entry. Both results rows landed in the table, but the Parameters block only reflected whichever run created the entry first. Reader couldn't tell which row was which. Fix: `BenchmarkWriter.append` takes a new optional `configKeyExtras: [(String, String)] = []` that's appended to the config key as ` / key=value` pairs. The InferenceBenchmark harness passes `[("ngram", "N")]` when `BenchEnv.ngramSize > 0`; nothing otherwise. Result with `--ngram 0` then `--ngram 3` on the same cell: 4bit / turbo4v2 / summarization 4bit / turbo4v2 / summarization / ngram=3 Separate Parameters blocks with `N-gram size | 0` and `N-gram size | 3` respectively. Extensible to other benchmark-time dimensions that aren't part of the quant/kv/method triple (e.g. reasoning effort) without further schema changes. Co-Authored-By: Claude Opus 4.7 (1M context) --- Tests/Benchmarks/InferenceBenchmark.swift | 1 + Tests/Benchmarks/Utils/BenchmarkWriter.swift | 12 +++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Tests/Benchmarks/InferenceBenchmark.swift b/Tests/Benchmarks/InferenceBenchmark.swift index 9a4aab17e3..8b031f6393 100644 --- a/Tests/Benchmarks/InferenceBenchmark.swift +++ b/Tests/Benchmarks/InferenceBenchmark.swift @@ -1343,6 +1343,7 @@ struct InferenceBenchmarks { quantization: variant.quantization, kvConfig: kv.description, scenario: scenario, + configKeyExtras: BenchEnv.ngramSize > 0 ? [("ngram", "\(BenchEnv.ngramSize)")] : [], contextSize: contextSize, promptTokens: prefillTokens, prefillTokPerSec: prefillTokPerSec, diff --git a/Tests/Benchmarks/Utils/BenchmarkWriter.swift b/Tests/Benchmarks/Utils/BenchmarkWriter.swift index 9847d2df6d..2de9ee861e 100644 --- a/Tests/Benchmarks/Utils/BenchmarkWriter.swift +++ b/Tests/Benchmarks/Utils/BenchmarkWriter.swift @@ -32,12 +32,19 @@ enum BenchmarkWriter { } /// Append a benchmark result row to the session's markdown file. + /// + /// Rows are grouped by model → config. The config identity is + /// `quantization / kvConfig / scenario` plus any non-empty `configKeyExtras` + /// appended as ` / key=value` pairs (e.g. `ngram=3`) so that two runs which + /// differ only on a dimension outside (quant, kv, method) — like `--ngram` + /// — land in separate config blocks with distinct Parameters tables. static func append( model: String, repoId: String = "", quantization: String, kvConfig: String, scenario: String, + configKeyExtras: [(String, String)] = [], contextSize: Int, promptTokens: Int, prefillTokPerSec: Double, @@ -103,7 +110,10 @@ enum BenchmarkWriter { kvCacheBytes: kvCacheBytes ) - let configKey = "\(quantization) / \(kvConfig) / \(scenario)" + var configKey = "\(quantization) / \(kvConfig) / \(scenario)" + for (k, v) in configKeyExtras { + configKey += " / \(k)=\(v)" + } var paramRows: [[String]] = [] var systemPrompt = "" if let p = parameters {