diff --git a/Tests/Benchmarks/InferenceBenchmark.swift b/Tests/Benchmarks/InferenceBenchmark.swift index 136ad25da5..8b031f6393 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, @@ -1325,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, @@ -1416,6 +1435,8 @@ struct InferenceBenchmarks { presencePenalty: family.presencePenalty, prefillStepSize: 2048, kvScheme: kv.kvScheme, + ngramSize: BenchEnv.ngramSize, + maxNgramDraftTokens: BenchEnv.ngramSize, trackPerplexity: false ) 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 { 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