Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Tests/Benchmarks/InferenceBenchmark.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -1416,6 +1435,8 @@ struct InferenceBenchmarks {
presencePenalty: family.presencePenalty,
prefillStepSize: 2048,
kvScheme: kv.kvScheme,
ngramSize: BenchEnv.ngramSize,
maxNgramDraftTokens: BenchEnv.ngramSize,
trackPerplexity: false
)

Expand Down
12 changes: 11 additions & 1 deletion Tests/Benchmarks/Utils/BenchmarkWriter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 2 additions & 0 deletions benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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. |

Expand Down
18 changes: 18 additions & 0 deletions scripts/benchmark.sh
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ BASELINE=false
BATCH=1
THINK=false
REASONING="medium"
NGRAM=0
QUICK_CONTEXTS="128,1024,4096,32768"

# ─────────────────────────────────────────────
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 ""
Expand Down Expand Up @@ -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
Expand Down