diff --git a/README.md b/README.md index 02465a2e..4a61eeab 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,8 @@ With flags: ```sh M=path/to/model.gguf -rustingstrata calibrate --model $M # once per model and machine: best chunk size, MTP drafts +rustingstrata calibrate --model $M --dry-run # preview the workload matrix and knob space +rustingstrata calibrate --model $M # once per model and machine: best chunk, context, MTP drafts rustingstrata chat --model $M --gpu # --think for thinking mode, --temp 0.7 to sample rustingstrata generate --model $M --gpu --prompt "Write a haiku about rivers." -n 128 rustingstrata serve --model $M --gpu --addr 127.0.0.1:8080 @@ -77,6 +78,8 @@ Inkling 2 open the GPU by themselves. - [USAGE.md](docs/USAGE.md): flags, the chat page and MCP tools, the OpenAI and Anthropic APIs, prompt caching, several GPUs. +- [CALIBRATION.md](docs/CALIBRATION.md): the budgeted search, objective profiles, task corpora, the `spec` sweep and + the JSON file. - [MODELS.md](docs/MODELS.md): supported architectures and GGUF types, notes and caveats for each model. - [BENCHMARKS.md](docs/BENCHMARKS.md): every model against llama.cpp; older runs are in the [benchmark history](docs/README.md#benchmark-history). diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.md index 194604e2..26853099 100644 --- a/docs/BENCHMARKS.md +++ b/docs/BENCHMARKS.md @@ -275,6 +275,49 @@ used part of the GPU during that run. Alternating runs of the old and new build CUDA 25.4 to 33.5 tok/s, Vulkan 16.6 to 25.4 tok/s, prefill unchanged (within 1-4%). Most of the Vulkan gain is the IQ4_NL expert matvec (105 to 270 GB/s on 8 experts of 2304x2304). +## Calibration v2 validation (RTX 3050 Laptop 4 GB) + +The v2 `calibrate` command measures through `bench`, so its baseline and best trials are the benchmark. Two target +models, page cache warmed by the baseline, one child process per sample with `--reps 1`, greedy, built-in prose, +`--tg 16`, seed 1. Numbers are the mean of one sample (not a range); this is a search-validation run, not a +top-speed record. Full traces are in the JSON files under the cache directory and in the report written by `--out`. + +### Tiel-Coder-35B-A3B-MTP-UD-IQ3_XXS (`qwen35moe`, 13.6 GB) + +Command: `rustingstrata calibrate --model … --samples 10 --pp 128,512 --tg 16 --chunk-values 1024,2048,4096 +--ctx-values 2048,4096 --seed 1`. Baseline knobs: chunk 1024, ctx 2048, mtp 0, short 16, threads 3. Best knobs: +**chunk 4096, ctx 2048, mtp 1, short 16, threads 3**, score 1.299 vs baseline (10 samples, 114.5 s, 0 failures). + +| workload | prefill: baseline → best | decode: baseline → best | TTFT: baseline → best | +|---|---|---|---| +| 128-token prompt | 109.8 → **126.8** tok/s | 17.3 → **28.6** tok/s | 1165.8 → **1009.5** ms | +| 512-token prompt | 230.3 → **306.3** tok/s | 20.1 → **24.4** tok/s | 2223.2 → **1671.6** ms | + +The gain is mostly the MTP draft head (accepted at 128 tokens) plus a larger chunk; the search found it jointly +rather than by optimizing drafts and prefill in separate sweeps. The old v1 calibration file for this model recorded +chunk 4096 and mtp 0. + +### Inkling-2-Mini-UD-Q3_K_XL (`inkling2_loop`, 13.6 GB) + +Command: `rustingstrata calibrate --model … --samples 8 --pp 128,512 --tg 16 --chunk-values 256,512,1024,2048 +--ctx-values 2048,4096 --seed 1`. Baseline knobs: chunk 256, ctx 2048, threads 6. Best knobs: **chunk 256, +ctx 4096, threads 6**, score 1.166 vs baseline (8 samples, 314.2 s, 0 failures). This model used to be skipped by +`calibrate` entirely; it is now measured through its own `bench` path and its chunk/context are applied at load time. + +| workload | prefill: baseline → best | decode: baseline → best | TTFT: baseline → best | +|---|---|---|---| +| 128-token prompt | 23.1 → **29.3** tok/s | 7.2 → **8.3** tok/s | 5541 → **4369** ms | +| 512-token prompt | 45.2 → **50.4** tok/s | 7.4 → 8.1 tok/s | 11327 → **10159** ms | + +### `calibrate spec` on Inkling 2 + +Command: `rustingstrata calibrate spec --model … --tasks prose,coding --spec-types none,ngram-simple,ngram-mod, +ngram-cache --draft-max 4,8 --ngram-n 3,6 --mtp 0 --pp 128 --tg 16 --samples 8 --seed 1` (8 samples, score 1.077 +vs baseline). Winner for both tasks: `ngram-cache`, 4 drafts, n-gram size 6. Decode: prose 8.5 tok/s, coding +6.5 tok/s. The sweep only added its `spec` section: the engine calibration above (chunk 256, ctx 4096) is still +in the file. Acceptance is reported as 0% because the short verbose prompt produced no drafts to accept in these +samples; the timing gain comes from the lookup path, not from accepted drafts. + ## Not yet measured - Qwen3-Next against llama.cpp in one table. diff --git a/docs/CALIBRATION.md b/docs/CALIBRATION.md new file mode 100644 index 00000000..f72efaa0 --- /dev/null +++ b/docs/CALIBRATION.md @@ -0,0 +1,199 @@ +# Calibration + +`rustingstrata calibrate` measures the settings that make a model fastest on **this** machine and writes them to +`~/.cache/rusting_strata/strata-[-backend][-dev…].json`. Later runs read that file unless a flag overrides the +value. One calibration per model, backend and device combination is enough; re-run after changing GPU, driver, quant, +KV format, or a draft file. + +The v2 workflow is universal: every architecture the binary supports is calibrated, including Inkling 2, Hy4, GLM, +DeepSeek and Gemma 4, which used to be skipped because they run on their own code path. It does this by measuring +through the existing `bench` command, so there is only one timing implementation to trust. + +## Quick start + +```sh +M=path/to/model.gguf + +# See what would be measured, without loading any weights: +rustingstrata calibrate --model $M --dry-run + +# A normal calibration (24 samples, balanced objective): +rustingstrata calibrate --model $M + +# An interactive model: favour time to first token, search a small space: +rustingstrata calibrate --model $M --profile interactive \ + --chunk-values 512,1024,2048,4096 --ctx-values 4096,8192 \ + --pp 128,512,2048 --tg 128 --samples 32 + +# Every model under a folder, one after another: +rustingstrata calibrate --model ~/models +``` + +The command prints the derived workload matrix and knob space first, then the baseline and the winning +configuration, and finally the path of the JSON file it wrote. `--out DIR` writes one line per sample to a report. + +## What is optimized + +Three signals are measured for every workload: + +| signal | meaning | direction | +| --- | --- | --- | +| prefill throughput | prompt tokens / prompt prefill time | higher is better | +| decode throughput | generated tokens / greedy decode time | higher is better | +| TTFT | start of prefill → first generated token | lower is better | + +Each is divided by the baseline (the first knob point, measured at the start), and combined with a **weighted +geometric mean**: + +``` +score = (prefill/baseline)^wp · (decode/baseline)^wd · (baseline_ttft/ttft)^wt +``` + +A weighted arithmetic mean would let a huge gain in one signal hide a regression in another; the geometric mean +does not. All three signal ratios are clamped to `[1e-3, 1e3]` so a failed measurement cannot produce infinities. + +Presets set the weights: + +| `--profile` | prefill | decode | TTFT | typical use | +| --- | --- | --- | --- | --- | +| `interactive` | 0.20 | 0.30 | 0.50 | chat, short prompts | +| `balanced` (default) | 0.25 | 0.35 | 0.40 | general use | +| `batch` | 0.50 | 0.40 | 0.10 | long prompts, throughput jobs | + +Use `--objective prefill|decode|ttft` to optimize a single signal, or `--weights 0.3,0.3,0.4` for exact control +(the three numbers are normalized to sum to one). + +## Workloads and tasks + +`--pp` is the list of prompt depths (default `128,512,2048`); `--tg` is the number of decoded tokens (default 128). +Every depth of a task is benchmarked in one child process. + +`--task` selects the corpus, repeatable: + +- `prose` (default): the built-in repeated paragraph. It routes few experts and is a stable machine-level baseline. +- `coding`: a built-in code snippet — punctuation and identifiers change both prefill cost and n-gram acceptance. +- `user:PATH`: your own prompt file. Use it when real traffic matters (RAG documents, long system prompts, etc.). + +For example: + +```sh +rustingstrata calibrate --model $M --task prose --task coding --task user:$(pwd)/prompts.txt \ + --pp 256,2048 --tg 64 +``` + +TTFT is the prefill time of each prompt: the prefill produces the logits of the first generated token, so loading the +model and compiling kernels are not counted (they are not part of a request's latency). + +## Search strategy + +The search is deterministic for a given `--seed` and bounded by `--samples`: + +1. **Baseline** — the first value of every knob is measured on the full workload matrix (not counted in the budget). +2. **Coarse sweep** — up to `min(samples/3, 8)` points from a low-discrepancy (radical-inverse) sequence over the joint + knob space. Unlike a fixed grid, this covers combinations, so a setting that only wins together with another one + is represented. +3. **Multi-start coordinate descent** — the three best coarse points are refined: each knob is tried at every other + value, the best move is kept, and the walk stops after `--patience`-equivalent stagnation (`2` full rounds by + default). Multiple starts avoid the local minima of a single greedy walk. +4. **Final polish** — one more pass from the overall winner over the cheap knobs. + +A candidate that fails (for example, OOM at a large chunk) is recorded with its error and never wins; it still counts +against the sample budget. `--timeout SECS` caps each sample so a bad point cannot hang the run. + +### Knobs + +| knob | values | applies to | +| --- | --- | --- | +| `ctx` | `--ctx-values` (default: `--ctx` and its double) | all | +| `kv` | `--kv-values` (default: `f16`) | all | +| `chunk` | `--chunk-values` (default `256,512,1024,2048,4096`) | all; the arch-specific engines read it from the environment | +| `mtp` | `0,1,2,4` | main engine only | +| `short` | `16,32,64,128` | main engine only | +| `threads` | half and all physical cores | main engine only | + +Multi-GPU runs are supported (pass `--device 0,1`): measurements use the engine's free-VRAM layer split. The v1 +layer-split sweep is not part of v2, and `--split` is ignored with a note. Every architecture is measured, including +Gemma 4 (its `bench` path is part of this change); for the models on their own code path, the measured chunk and +context are applied at load time through `STRATA_DS_CHUNK` / `STRATA_GLM_CHUNK` and the context limit. + +Smaller spaces give more reliable answers for the same budget. If a large chunk OOMs on your card, pass +`--chunk-values 1024,2048,4096` rather than spending samples on failures. If you always run `q8`, pass +`--kv-values q8` so the measurement matches your workload. + +## Flags + +| flag | default | meaning | +| --- | --- | --- | +| `--samples N` | 24 | hard cap on benchmark samples | +| `--reps N` | 3 | repetitions per point (their mean is used) | +| `--warmup N` | 1 | extra discarded run before each sample | +| `--pp A,B,C` | `128,512,2048` | prompt depths | +| `--tg N` | 128 | decoded tokens | +| `--profile NAME` | `balanced` | `interactive`, `balanced`, `batch` | +| `--objective NAME` | — | optimize a single signal | +| `--weights P,D,T` | — | explicit objective weights | +| `--ctx-values A,B` | `--ctx`, double | context lengths to search | +| `--kv-values f16,q8` | `f16` | KV formats to search | +| `--chunk-values A,B` | `256,…,4096` | prefill chunks to search | +| `--task LABEL` | `prose` | corpus (repeatable) | +| `--seed N` | 1 | deterministic search seed | +| `--timeout SECS` | 0 (none) | per-sample time limit | +| `--dry-run` | off | print the plan, take no measurements | +| `--out DIR` | — | also write the full sample trace | +| `--mtp-model` / `--draft-model` | — | measure with that draft file loaded | + +`--model` also accepts a folder: every `.gguf` in it (and its subfolders) is calibrated in turn with the same flags; +a model that fails is reported and the rest go on. `--mtp-model` and `--draft-model` need a single model file. + +## The `spec` subcommand + +`calibrate spec` sweeps speculative-decoding settings **per task**. It answers "which n-gram type and how many drafts +are best for coding vs. prose on this model", rather than tuning prefill knobs. + +```sh +# Inkling 2, with its DSpark draft file, across two corpora: +rustingstrata calibrate spec \ + --model ~/Models/Inkling2/Inkling-2-Mini-UD-Q3_K_XL.gguf \ + --draft-model ~/Models/Inkling2/dspark-Inkling-2-Mini-Q8_0.gguf \ + --tasks prose,coding --spec-types ngram-simple,ngram-mod,ngram-cache \ + --draft-max 4,8,16 --ngram-n 3,6,12 --samples 16 + +# Look first, benchmark second: +rustingstrata calibrate spec --model $M --dry-run +``` + +The knobs are `spec_type` (`none`, `suffix`, `ngram-simple`, `ngram-map-k`, `ngram-map-k4v`, `ngram-mod`, +`ngram-cache`), `draft_max` (drafts verified per step), `ngram_n` (lookup key length) and `mtp` (MTP draft count, main +engine only). The result is written under `spec` in the same calibration file, keyed by task, with the decode rate, +TTFT and draft acceptance percentage of the winner. A spec sweep **only adds that section**: the engine knobs +measured by a previous `calibrate` run are left untouched. Acceptance is task-dependent, which is why the sweep is per task: +a lookup drafter can accept nearly every draft on repetitive text and far fewer on prose. + +## The calibration file + +The file keeps every v1 key (`chunk`, `mtp`, `short`, `ctx`, `gpu`, `bytes`, `measured`, `aux`, `split`), so older +binaries still read it. v2 adds: + +```json +{ + "schema": 2, + "arch": "qwen35moe", + "chunk": 2048, "mtp": 2, "short": 32, "threads": 6, + "ctx": 8192, "ctx_recommended": 8192, "kv": "f16", + "measured": {"prefill_tok_s": 1057.0, "decode_tok_s": 26.7, "ttft_ms": 0.9}, + "best": {"chunk": 2048, "ctx": 8192, "kv": 0, "mtp": 2, "short": 32, "threads": 6}, + "search": {"samples_used": 24, "score": 1.234, "stop_reason": "budget", + "elapsed_ms": 123456, "seed": 1, "objective": "balanced", "profile": "balanced"}, + "workloads": [{"pp": 128, "tg": 128, "task": "prose"}], + "spec": {"prose": {"spec_type": "ngram-mod", "draft_max": 8, "ngram_n": 6, + "acceptance_pct": 72.5}} +} +``` + +`ctx_recommended` is advisory: it is applied only when `--ctx` is left at its default (4096); an explicit `--ctx` +always wins. `--out DIR` writes a separate `strata--calib-report.json` containing all trials, their knob +points, measurements, errors and timings — useful for auditing a surprising result or comparing two seeds. + +The filename encodes backend and device order (`-vulkan`, `-dev0-1`), so calibrations for different setups do not +overwrite each other. As before, `XDG_CACHE_HOME` moves the folder, and a file measured on another GPU or another +file of the same name (different size) is ignored with a warning. diff --git a/docs/USAGE.md b/docs/USAGE.md index 10a5f20a..31f5f432 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -111,8 +111,9 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def differently from one-token decoding, so greedy output can differ at a near tie. - `--chunk`, `--threads` prefill chunk size and CPU expert threads. On a GPU `--threads` defaults to the physical core count (SMT siblings only add contention; on the 6-core/12-thread reference machine 6 beats 12 by ~20%). - `rustingstrata calibrate` measures the best chunk and later runs read it from - `~/.cache/rusting_strata/strata-.json` unless flags override. + `rustingstrata calibrate` measures the best chunk, context size and draft count and later runs read them from + `~/.cache/rusting_strata/strata-.json` unless flags override. See [CALIBRATION.md](CALIBRATION.md) for the + budgeted search, the objective profiles and the `calibrate spec` sweep. `XDG_CACHE_HOME` moves that folder to `$XDG_CACHE_HOME/rusting_strata` (on Windows it is `%LOCALAPPDATA%\rusting_strata`). In a container, set it to a mounted path: `docker run --rm` otherwise discards the file on exit, and the next container runs uncalibrated. The file names the GPU it was measured on, and a file @@ -135,9 +136,9 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def expert placement see the VRAM it takes, and picks the draft count. Runs with the same `--mtp-model` or `--draft-model` file use that count unless `--mtp` is given; runs with another draft file or none do not. - `calibrate --model ~/models` calibrates every model in a folder (and its subfolders, as the chat page lists them), - one after another, with the other flags applied to each. A model that fails is reported and the rest go on; Inkling - 2, Hy4, GLM, DeepSeek and Gemma 4 models are skipped: `calibrate` measures the main engine only, and these models - run on their own code path, which reads no calibration file. `--mtp-model` and `--draft-model` need a single file. + one after another, with the other flags applied to each. A model that fails is reported and the rest go on. All + architectures are included: Inkling 2, Hy4, GLM, DeepSeek and Gemma 4 are measured through their own `bench` path. + `--mtp-model` and `--draft-model` need a single model file. - `--thinking-budget N` (`chat` and `serve`) ends the thinking block after `N` tokens by inserting ``, so the model goes on to the answer (0, the default, is no limit). A request overrides it with `thinking_budget` or `chat_template_kwargs.thinking_budget` (Anthropic: `thinking.budget_tokens`). diff --git a/src/calibrate.rs b/src/calibrate.rs new file mode 100644 index 00000000..474f5a29 --- /dev/null +++ b/src/calibrate.rs @@ -0,0 +1,431 @@ +//! Universal calibration search. +//! +//! This module is the model- and backend-agnostic half of `rustingstrata calibrate`. It knows nothing about GGUFs, +//! GPUs or tokenizers: the caller supplies a `measure` closure that, given a set of knobs and a workload matrix, +//! returns throughput and time-to-first-token numbers. That makes the same search usable with every engine the +//! binary supports, including the ones that run on their own code path. +//! +//! The search is deliberately small-budget and noise-aware: +//! * a deterministic low-discrepancy coarse sweep over the joint knob space, +//! * multi-start coordinate descent from the best coarse points (escapes the local minima of a single greedy walk), +//! * a final joint polish, +//! * a hard sample budget with early stopping, +//! * a weighted geometric-mean objective over prefill throughput, decode throughput and TTFT. + +use anyhow::Result; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::time::Instant; + +/// A point in the knob space. Values are numeric: integer knobs are rounded by the caller when they are applied. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Knobs(pub BTreeMap); + +impl Knobs { + pub fn get(&self, name: &str) -> Option { self.0.get(name).copied() } + pub fn i(&self, name: &str) -> Option { self.get(name).map(|v| v.round().max(0.0) as usize) } + pub fn set(&mut self, name: &str, value: f64) { self.0.insert(name.to_string(), value); } + /// A short, stable label used in progress lines and in the JSON report. + pub fn label(&self) -> String { + self.0.iter().map(|(k, v)| format!("{k}={}", if v.fract() == 0.0 { format!("{v:.0}") } else { format!("{v:.2}") })) + .collect::>().join(" ") + } +} + +/// One discrete knob. `reload` marks knobs whose change needs a fresh model load; the measurement closure can use it +/// to keep a runner alive when only cheap knobs change. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct KnobSpec { + pub name: String, + pub values: Vec, + #[serde(default)] + pub reload: bool, +} + +impl KnobSpec { + pub fn new(name: &str, values: impl IntoIterator, reload: bool) -> Self { + Self { name: name.into(), values: values.into_iter().collect(), reload } + } +} + +/// A prompt/decode pair to benchmark. `task` is a label the measurement closure interprets ("prose", "coding", +/// "user:PATH"); it is passed through so the report records which corpus produced the numbers. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Workload { + pub pp: usize, + pub tg: usize, + pub task: String, +} + +impl Workload { + pub fn new(pp: usize, tg: usize, task: &str) -> Self { Self { pp, tg, task: task.into() } } + pub fn label(&self) -> String { format!("{}pp/{}tg/{}", self.pp, self.tg, self.task) } +} + +/// Throughput and latency of one workload measurement. Higher is better for the rates, lower for `ttft_ms`. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Measurement { + pub prefill_tok_s: f64, + pub decode_tok_s: f64, + pub ttft_ms: f64, + #[serde(default)] + pub drafts_offered: usize, + #[serde(default)] + pub drafts_accepted: usize, +} + +impl Measurement { + fn valid(&self) -> bool { + [self.prefill_tok_s, self.decode_tok_s, self.ttft_ms].iter().all(|v| v.is_finite() && *v > 0.0) + } +} + +/// Relative importance of the three signals. Weights are normalized to sum to one; the preset profiles are the +/// supported way to set them, `--weights` is the explicit one. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Objective { + pub prefill: f64, + pub decode: f64, + pub ttft: f64, +} + +impl Objective { + pub fn balanced() -> Self { Self { prefill: 0.25, decode: 0.35, ttft: 0.40 } } + pub fn interactive() -> Self { Self { prefill: 0.20, decode: 0.30, ttft: 0.50 } } + pub fn batch() -> Self { Self { prefill: 0.50, decode: 0.40, ttft: 0.10 } } + pub fn only(which: &str) -> Result { + Ok(match which { + "prefill" => Self { prefill: 1.0, decode: 0.0, ttft: 0.0 }, + "decode" => Self { prefill: 0.0, decode: 1.0, ttft: 0.0 }, + "ttft" => Self { prefill: 0.0, decode: 0.0, ttft: 1.0 }, + other => anyhow::bail!("unknown objective {other:?} (expected prefill, decode or ttft)"), + }) + } + fn normalized(&self) -> Self { + let sum = self.prefill + self.decode + self.ttft; + if sum <= 0.0 || !sum.is_finite() { return Self::balanced(); } + Self { prefill: self.prefill / sum, decode: self.decode / sum, ttft: self.ttft / sum } + } + /// Score of one measurement relative to the baseline. A weighted geometric mean: a balanced gain is worth more + /// than a large gain in one dimension paired with a regression in another, and the units cancel out. + pub fn score(&self, m: &Measurement, base: &Measurement) -> f64 { + let clamp = |v: f64| v.clamp(1e-3, 1e3); + let pf = clamp(m.prefill_tok_s / base.prefill_tok_s); + let dec = clamp(m.decode_tok_s / base.decode_tok_s); + let ttft = clamp(base.ttft_ms / m.ttft_ms); + let o = self.normalized(); + pf.powf(o.prefill) * dec.powf(o.decode) * ttft.powf(o.ttft) + } +} + +/// Score of a full workload matrix: geometric mean over workloads, so each prompt depth counts equally. Each depth +/// is compared with its own baseline, so the ratio means what it says at every prompt length. +pub fn aggregate_score(ms: &[Measurement], bases: &[Measurement], obj: &Objective) -> f64 { + let fallback = bases.first().cloned().unwrap_or_default(); + let mut acc = 0.0; + let mut n = 0; + for (i, m) in ms.iter().enumerate() { + if !m.valid() { continue; } + let base = bases.get(i).unwrap_or(&fallback); + acc += obj.score(m, base).ln(); + n += 1; + } + if n == 0 { 0.0 } else { (acc / n as f64).exp() } +} + +/// One evaluated candidate. `error` is set (and `score` is zero) when a measurement failed, e.g. an OOM at a large +/// chunk: failed points stay in the trace so the report explains why a region of the space was skipped. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Trial { + pub knobs: Knobs, + pub measurements: Vec, + pub score: f64, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + pub elapsed_ms: u128, + /// How many workloads were measured. Coarse trials use the first workload only; they must not be compared with + /// full-matrix scores, nor can they win the search. + pub workloads: usize, +} + +/// Budget and stopping settings. +#[derive(Clone, Debug)] +pub struct SearchConfig { + /// Hard cap on measurement closure calls. Reaching it always stops the search. + pub samples: usize, + /// Number of coarse low-discrepancy points (capped at a third of the budget). + pub coarse: usize, + /// Multi-start count for coordinate descent. + pub starts: usize, + /// Stop after this many full refinement rounds without an improvement. + pub patience: usize, + /// Deterministic seed (also used for the low-discrepancy sequence). + pub seed: u64, +} + +impl Default for SearchConfig { + fn default() -> Self { Self { samples: 24, coarse: 8, starts: 3, patience: 2, seed: 1 } } +} + +/// Result of a search, including the full trace for the JSON report. +#[derive(Debug, Serialize, Deserialize)] +pub struct SearchResult { + pub best: Trial, + pub baseline: Vec, + pub trials: Vec, + pub samples_used: usize, + pub stop_reason: String, + pub elapsed_ms: u128, + pub seed: u64, +} + +/// Radical inverse in a prime base: a deterministic, well-spread point set in `[0,1)^dims`. No dependencies, same +/// points on every run for a given seed, so a calibration can be reproduced from its recorded seed. +pub fn low_discrepancy(index: usize, dims: usize, seed: u64) -> Vec { + const PRIMES: [u64; 12] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]; + (0..dims).map(|d| { + let base = PRIMES.get(d).copied().unwrap_or(37); + let mut n = index as u64 + seed.wrapping_mul(base); + let mut f = 1.0 / base as f64; + let mut out = 0.0; + while n > 0 { + out += f * (n % base) as f64; + n /= base; + f /= base as f64; + } + out + }).collect() +} + +/// Map a unit point to knob values by nearest candidate (a small jitter-free quantization of the unit cube). +fn quantize(space: &[KnobSpec], unit: &[f64]) -> Knobs { + let mut k = Knobs::default(); + for (spec, u) in space.iter().zip(unit) { + let i = (u.clamp(0.0, 0.999999) * spec.values.len() as f64) as usize; + k.set(&spec.name, spec.values[i.min(spec.values.len() - 1)]); + } + k +} + +fn default_knobs(space: &[KnobSpec]) -> Knobs { + let mut k = Knobs::default(); + for s in space { if let Some(v) = s.values.first() { k.set(&s.name, *v); } } + k +} + +/// Run the search. `measure` is called once per sample with the whole workload matrix; it should apply the knobs, +/// warm up, take its own repetitions and return one measurement per workload. +pub fn search(space: &[KnobSpec], workloads: &[Workload], cfg: &SearchConfig, obj: &Objective, + baseline: Vec, mut measure: F) -> Result +where F: FnMut(&Knobs, &[Workload]) -> Result> +{ + anyhow::ensure!(!space.is_empty() && !workloads.is_empty(), "calibration needs a knob space and at least one workload"); + let fallback = baseline.iter().find(|m| m.valid()).cloned().unwrap_or_else(|| Measurement { prefill_tok_s: 1.0, decode_tok_s: 1.0, ttft_ms: 1.0, ..Default::default() }); + let mut baselines = baseline.clone(); + while baselines.len() < workloads.len() { baselines.push(fallback.clone()); } + let start = Instant::now(); + let mut trials: Vec = Vec::new(); + let mut used = 0usize; + + let mut evaluate = |knobs: &Knobs, subset: &[Workload]| -> Result { + let t0 = Instant::now(); + let (measurements, error) = match measure(knobs, subset) { + Ok(ms) if ms.iter().any(|m| m.valid()) => (ms, None), + Ok(ms) => (ms, Some("no valid measurement (all rates were zero or non-finite)".to_string())), + Err(e) => (vec![], Some(format!("{e:#}"))), + }; + let score = if error.is_some() { 0.0 } else { aggregate_score(&measurements, &baselines, obj) }; + Ok(Trial { knobs: knobs.clone(), measurements, score, error, elapsed_ms: t0.elapsed().as_millis(), workloads: subset.len() }) + }; + + // Stage A: coarse joint sweep, on the cheapest (first) workload. These scores are only used to pick starting + // points for Stage B; they are never compared with full-matrix scores or allowed to win. + let coarse = cfg.coarse.min(cfg.samples / 3).min(16).max(1); + for i in 0..coarse { + let k = quantize(space, &low_discrepancy(i, space.len(), cfg.seed)); + let trial = evaluate(&k, &workloads[..1])?; + used += 1; + trials.push(trial); + if used >= cfg.samples { break } + } + + // Stage B: multi-start coordinate descent on the full matrix. + let mut seeds: Vec<(Knobs, f64)> = trials.iter().filter(|t| t.error.is_none()) + .map(|t| (t.knobs.clone(), t.score)).collect(); + seeds.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); + seeds.dedup_by(|a, b| a.0 == b.0); + seeds.truncate(cfg.starts.max(1)); + if seeds.is_empty() { seeds.push((default_knobs(space), 0.0)); } + + let mut stop_reason = "budget".to_string(); + for (cur, _seed_score) in seeds.into_iter() { + // Re-measure the seed on the full matrix before comparing it with full-matrix candidates. Otherwise a point + // that only wins on the shortest prompt would start with an inflated score and reject real improvements. + let mut cur_trial = if used < cfg.samples { + let t = evaluate(&cur, workloads)?; + used += 1; + trials.push(t.clone()); + t + } else { break }; + let mut stale = 0; + for _ in 0..cfg.patience.max(1) + 2 { + let mut improved = false; + for s in space { + let original = cur_trial.knobs.get(&s.name); + let mut local_best = cur_trial.clone(); + for &v in &s.values { + if Some(v) == original { continue } + if used >= cfg.samples { break; } + let mut candidate = cur_trial.knobs.clone(); + candidate.set(&s.name, v); + let t = evaluate(&candidate, workloads)?; + used += 1; + trials.push(t.clone()); + if t.error.is_none() && t.score > local_best.score { local_best = t; } + if used >= cfg.samples { break; } + } + match local_best.error.clone() { + None if local_best.score > cur_trial.score => { cur_trial = local_best; improved = true; } + _ => {} + } + if used >= cfg.samples { break; } + } + if !improved { stale += 1; if stale >= cfg.patience.max(1) { stop_reason = "converged".into(); } } + else { stale = 0; } + if used >= cfg.samples { break; } + if stop_reason == "converged" { break; } + } + if used >= cfg.samples { break; } + } + if used >= cfg.samples { stop_reason = "budget".into(); } + + // Stage C: one coordinate pass from the overall winner over the cheap knobs (reload knobs are handled by the + // coarse sweep and the seeds, since each change there requires a fresh model load). + let best_so_far = trials.iter().filter(|t| t.error.is_none() && t.workloads == workloads.len()) + .max_by(|a, b| a.score.partial_cmp(&b.score).unwrap_or(std::cmp::Ordering::Equal)).cloned(); + let mut best = best_so_far.unwrap_or_else(|| Trial { + knobs: default_knobs(space), measurements: vec![], score: 0.0, + error: Some("no successful full-matrix measurement".into()), elapsed_ms: 0, workloads: 0, + }); + if used < cfg.samples { + for s in space.iter().filter(|s| !s.reload) { + let original = best.knobs.get(&s.name); + for &v in &s.values { + if Some(v) == original || used >= cfg.samples { continue } + let mut candidate = best.knobs.clone(); + candidate.set(&s.name, v); + let t = evaluate(&candidate, workloads)?; + used += 1; + trials.push(t.clone()); + if t.error.is_none() && t.score > best.score { best = t; } + } + } + } + if used >= cfg.samples { stop_reason = "budget".into(); } + Ok(SearchResult { + best, baseline, trials, samples_used: used, stop_reason, + elapsed_ms: start.elapsed().as_millis(), seed: cfg.seed, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn space() -> Vec { + vec![KnobSpec::new("chunk", [128.0, 512.0, 2048.0], false), + KnobSpec::new("kv", [0.0, 1.0], true)] + } + fn workloads() -> Vec { vec![Workload::new(128, 16, "prose"), Workload::new(512, 16, "prose")] } + fn base() -> Measurement { Measurement { prefill_tok_s: 100.0, decode_tok_s: 20.0, ttft_ms: 100.0, ..Default::default() } } + + #[test] + fn objective_is_a_geometric_mean_and_normalized() { + let o = Objective::balanced(); + let same = Measurement { prefill_tok_s: 100.0, decode_tok_s: 20.0, ttft_ms: 100.0, ..Default::default() }; + assert!((o.score(&same, &base()) - 1.0).abs() < 1e-9); + let better = Measurement { prefill_tok_s: 200.0, decode_tok_s: 10.0, ttft_ms: 50.0, ..Default::default() }; + // 2^0.25 * 0.5^0.35 * 2^0.40 + let expected = 2f64.powf(0.25) * 0.5f64.powf(0.35) * 2f64.powf(0.40); + assert!((o.score(&better, &base()) - expected).abs() < 1e-9); + assert!(o.score(&better, &base()) > 1.0, "balanced gains should win"); + let mixed = Measurement { prefill_tok_s: 1000.0, decode_tok_s: 2.0, ttft_ms: 500.0, ..Default::default() }; + assert!(o.score(&mixed, &base()) < 1.0, "a big regression must not be hidden by one gain"); + } + + #[test] + fn objective_presets_and_unknown_name() { + assert!((Objective::interactive().ttft - 0.5).abs() < 1e-9); + assert!((Objective::batch().prefill - 0.5).abs() < 1e-9); + assert!(Objective::only("decode").unwrap().decode == 1.0); + assert!(Objective::only("nope").is_err()); + } + + #[test] + fn low_discrepancy_is_deterministic_and_spread() { + let a = low_discrepancy(7, 3, 42); + let b = low_discrepancy(7, 3, 42); + assert_eq!(a, b); + assert!(a.iter().all(|v| (0.0..1.0).contains(v))); + let pts: Vec<_> = (0..16).map(|i| low_discrepancy(i, 2, 1)).collect(); + let xs: std::collections::BTreeSet<_> = pts.iter().map(|p| format!("{:.2}", p[0])).collect(); + assert!(xs.len() >= 8, "coarse points should cover the first dimension: {xs:?}"); + } + + #[test] + fn search_respects_the_sample_budget_and_finds_the_best_region() { + // Synthetic landscape: chunk 512 with kv 1 is best. The closure never sees more calls than the budget. + let mut calls = 0; + let cfg = SearchConfig { samples: 12, coarse: 4, starts: 2, patience: 1, seed: 5 }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |k, _| { + calls += 1; + let chunk = k.i("chunk").unwrap(); + let kv = k.i("kv").unwrap(); + let boost = if chunk == 512 { 2.0 } else { 1.0 } * if kv == 1 { 1.5 } else { 1.0 }; + Ok(vec![Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ttft_ms: 100.0 / boost, ..Default::default() }]) + }).unwrap(); + assert!(calls <= cfg.samples, "used {calls} above budget {}", cfg.samples); + assert_eq!(r.samples_used, calls); + assert_eq!(r.best.knobs.i("chunk"), Some(512)); + assert_eq!(r.best.knobs.i("kv"), Some(1)); + assert!(r.best.score > 1.0); + assert_eq!(r.stop_reason, "budget"); + } + + #[test] + fn short_prompt_only_gains_cannot_win_the_search() { + // kv=1 wins at 128 tokens but loses badly at 512. A coarse trial measured only on the first workload must + // not become the final best point. + let cfg = SearchConfig { samples: 14, coarse: 6, starts: 3, patience: 1, seed: 3 }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |k, subset| { + let kv = k.i("kv").unwrap(); + Ok(subset.iter().map(|w| { + let boost = if kv == 1 { if w.pp == 128 { 2.0 } else { 0.25 } } else { 1.0 }; + Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, + ttft_ms: 100.0 / boost, ..Default::default() } + }).collect()) + }).unwrap(); + assert_eq!(r.best.knobs.i("kv"), Some(0)); + assert!(r.best.measurements.len() == 2, "the winner must be measured on the full matrix"); + assert!(r.trials.iter().filter(|t| t.workloads == 1).all(|t| t.score < r.best.score + 1e-9 || t.knobs != r.best.knobs)); + } + + #[test] + fn failed_measurements_are_recorded_and_never_win() { + let cfg = SearchConfig { samples: 8, coarse: 4, starts: 1, patience: 1, seed: 2 }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), vec![base(), base()], |k, _| { + if k.i("kv") == Some(1) { anyhow::bail!("out of memory") } + Ok(vec![base(), base()]) + }).unwrap(); + assert_eq!(r.best.knobs.i("kv"), Some(0)); + assert!(r.trials.iter().any(|t| t.error.as_deref().is_some_and(|e| e.contains("out of memory")))); + } + + #[test] + fn aggregate_score_ignores_invalid_workloads() { + let bad = Measurement::default(); + let bases = [base(), base()]; + assert!((aggregate_score(&[base(), bad.clone()], &bases, &Objective::balanced()) - 1.0).abs() < 1e-9); + assert_eq!(aggregate_score(&[bad], &bases, &Objective::balanced()), 0.0); + } +} diff --git a/src/lib.rs b/src/lib.rs index 54f6a169..281c6419 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ pub mod memory; pub mod term; +pub mod calibrate; /// `--ctx` when it was given on the command line, else 0. The models outside the main engine (Inkling 2, Hy4, GLM, /// DeepSeek, Gemma 4) read it through [`ctx_limit`]. diff --git a/src/main.rs b/src/main.rs index ce0df099..0e1a7e43 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,10 @@ use clap::{Args, Parser, Subcommand}; use anyhow::Context; use rusting_strata::memory; +use rusting_strata::calibrate::{self, KnobSpec, Knobs, Measurement, Objective, SearchConfig, Workload}; +use std::cell::RefCell; +use std::process::{Command, Stdio}; +use std::sync::atomic::AtomicUsize; use rusting_strata::{say, term}; use rusting_strata::model::{Model, State}; use rusting_strata::{backend, gpu_model::GpuModel}; @@ -361,6 +365,29 @@ impl Engine { if self.kv != "f16" && std::env::var_os("STRATA_KV").is_none() { set_kv_env(&self.kv); } } + /// Models on their own code path never call `Engine::runner`, the only place that reads a calibration file. + /// Apply the measured chunk and context through the environment those engines actually read. + fn own_calib(&self, model: &Path) { + let path = calibration_path(model, self.backend.as_deref().unwrap_or("cuda"), &self.device); + let (Ok(bytes), Some(&d)) = (std::fs::read(&path), self.device.first()) else { return }; + let Ok(v) = serde_json::from_slice::(&bytes) else { return }; + let gpu = backend::open(self.backend.as_deref(), d).ok().map(|b| b.device().to_string()).unwrap_or_default(); + if !calibration_fits(&v, &gpu) { return; } + if v["bytes"].as_u64().is_some_and(|n| std::fs::metadata(model).is_ok_and(|m| m.len() != n)) { return; } + if std::env::var_os("STRATA_DS_CHUNK").is_none() { + if let Some(n) = v["chunk"].as_u64().filter(|&n| (1..=(1 << 20)).contains(&n)) { + // GLM reads its own variable; Hy4, DeepSeek and Inkling 2 read STRATA_DS_CHUNK. + unsafe { std::env::set_var("STRATA_DS_CHUNK", n.to_string()); } + unsafe { std::env::set_var("STRATA_GLM_CHUNK", n.to_string()); } + } + } + if rusting_strata::CTX.load(std::sync::atomic::Ordering::Relaxed) == 0 { + if let Some(n) = v["ctx_recommended"].as_u64().filter(|&n| (256..=(1 << 20)).contains(&n)) { + rusting_strata::CTX.store(n as usize, std::sync::atomic::Ordering::Relaxed); + } + } + } + /// Fills settings not given on the command line from the model's calibration file, else built-in defaults. fn ram_cap(&self) -> Option { memory::ram_cap((self.ram_margin as u64) << 20, (self.max_ram as u64) << 20) } /// A copy with the load options of an `/api/load` body applied (`ctx`, `kv`, `cache_ram`, `vram_margin`, `mtp`, @@ -409,6 +436,14 @@ impl Engine { say!("warning: {} was measured on another file with this name ({n} bytes): ignored", path.display()); v = serde_json::Value::Null; } + // The context size chosen by calibration is advisory: apply it only when --ctx was not given on the command + // line. CTX is set by start() only for an explicit --ctx (including one in calibrate spec's own arguments), + // so an explicit 4096 is never silently replaced by a recommendation. + if rusting_strata::CTX.load(std::sync::atomic::Ordering::Relaxed) == 0 { + if let Some(n) = v["ctx_recommended"].as_u64().filter(|&n| (256..=(1 << 20)).contains(&n)) { + self.ctx = n as usize; + } + } if !v.is_null() { say!("calibration: {}", path.display()); } else if bk.is_some() { say!("warning: not calibrated on this machine, so the prefill chunk, MTP drafts and the short-prompt threshold are defaults: run `rustingstrata calibrate --model {}` (a few minutes, once per model)", model.display()); } let get = |k: &str| v[k].as_u64().map(|x| x as usize); @@ -845,6 +880,12 @@ fn bench_record(meta: &BenchMeta, results: &[BenchResult], expert: Option<&Exper "pp": r.pp, "prefill_tok_s": {"mean": r.prefill.mean, "min": r.prefill.min, "max": r.prefill.max}, "decode_tok_s": {"mean": r.decode.mean, "min": r.decode.min, "max": r.decode.max}, + // Time to the first generated token. The prompt prefill produces the logits of that token, so for every + // engine its latency is the prefill latency (model loading is not part of a request's TTFT). Convert the + // throughput back into seconds per prompt, not the other way round. + "ttft_ms": {"mean": 1000.0 * r.pp as f64 / r.prefill.mean.max(1e-6), + "min": 1000.0 * r.pp as f64 / r.prefill.max.max(1e-6), + "max": 1000.0 * r.pp as f64 / r.prefill.min.max(1e-6)}, }); if r.bytes_per_token > 0 { o["expert"] = json!({ @@ -945,13 +986,13 @@ enum Cmd { #[command(flatten)] engine: Engine, }, - /// Measure prefill chunk, MTP drafts per step and the short-prompt threshold on this machine (GPU) and write - /// them to the model's calibration file, which later runs read unless flags override. + /// Benchmark a budgeted search over prefill chunk, context, KV and draft settings on this machine (GPU), and + /// write the best point to the model's calibration file, which later runs read unless flags override. Calibrate { /// The GGUF to calibrate, or a folder: every model in it (and its subfolders, as the chat page lists them) - /// is calibrated in turn. + /// is calibrated in turn. With the `spec` subcommand this may be omitted in favour of its own --model. #[arg(long)] - model: PathBuf, + model: Option, /// GPU context length used while measuring and assumed for the results. #[arg(long, default_value_t = 4096)] ctx: usize, @@ -983,6 +1024,59 @@ enum Cmd { /// calibrate the drafts with it. #[arg(long)] draft_model: Option, + + /// Hard cap on benchmark samples: the search stops when this many have been taken, or earlier when it has + /// converged. One sample benchmarks the whole workload matrix (all --pp lengths of one task). + #[arg(long, default_value_t = 24)] + samples: usize, + /// Benchmark repetitions inside each sample; their mean is used and run-to-run spread is reported. + #[arg(long, default_value_t = 3)] + reps: usize, + /// Warm-up runs before each sample, discarded (the first run fills the page cache and compiles pipelines). + #[arg(long, default_value_t = 1)] + warmup: usize, + /// Prompt depths of the workload matrix, comma-separated. + #[arg(long, value_delimiter = ',', default_value = "128,512,2048")] + pp: Vec, + /// Tokens greedily decoded per workload. + #[arg(long, default_value_t = 128)] + tg: usize, + /// Which signals to balance: interactive favours first-token latency, batch favours throughput. + #[arg(long, value_parser = ["interactive", "balanced", "batch"], default_value = "balanced")] + profile: String, + /// Optimize a single signal instead of the balanced objective. + #[arg(long, value_parser = ["prefill", "decode", "ttft"])] + objective: Option, + /// Explicit weights overriding --profile: prefill,decode,ttft (normalized to sum to one). + #[arg(long)] + weights: Option, + /// Context lengths to search, comma-separated (each needs a fresh model load). [default: 4096,8192] + #[arg(long, value_delimiter = ',')] + ctx_values: Option>, + /// KV cache formats to search, comma-separated. [default: f16] + #[arg(long, value_delimiter = ',', value_parser = ["f16", "q8", "q4", "q2"])] + kv_values: Option>, + /// Prefill chunk sizes to search, comma-separated. [default: 256,512,1024,2048,4096] + #[arg(long, value_delimiter = ',')] + chunk_values: Option>, + /// Extra task corpus: `user:PATH` (a prompt file), `coding` or `prose`. Repeatable. + #[arg(long)] + task: Vec, + /// Deterministic seed for the low-discrepancy coarse sweep and the search. + #[arg(long, default_value_t = 1)] + seed: u64, + /// Print the derived knob space, workload matrix and sample plan, then exit without benchmarking. + #[arg(long)] + dry_run: bool, + /// Per-sample time limit in seconds (0 = no limit). A timeout is recorded as a failed sample. + #[arg(long, default_value_t = 0)] + timeout: u64, + /// Keep the full benchmark report and sample trace in this directory. + #[arg(long)] + out: Option, + /// Sweep spec-type and draft settings for different tasks instead of tuning the engine knobs. + #[command(subcommand)] + sub: Option, }, /// Check that every Vulkan pipeline this model needs fits the device's `maxComputeSharedMemorySize`, naming the /// kernel, specialization, bytes needed and limit when one does not; exits non-zero on overflow. No model is @@ -1061,6 +1155,60 @@ enum Cmd { }, } +/// `rustingstrata calibrate spec …`: sweep speculative-decoding settings per task. +#[derive(Subcommand, Clone, Debug)] +enum CalibrateSub { + /// Measure every combination of spec type, draft count and n-gram size on each task corpus, and store the best + /// per task in the calibration file. Inkling 2 uses these with (or instead of) a DSpark draft; the main engine + /// combines them with its MTP head. + Spec { + /// The model to sweep (a folder is not accepted: the sweep writes one calibration file). + #[arg(long)] + model: PathBuf, + /// Tasks: `prose`, `coding`, `user:PATH` (a prompt file). Repeatable. + #[arg(long, value_delimiter = ',', default_value = "prose,coding")] + tasks: Vec, + /// Spec types: none, suffix, ngram-simple, ngram-map-k, ngram-map-k4v, ngram-mod, ngram-cache. + #[arg(long, value_delimiter = ',', default_value = "none,ngram-simple,ngram-mod,ngram-cache")] + spec_types: Vec, + /// Maximum drafts verified per step. + #[arg(long, value_delimiter = ',', default_value = "4,8,16")] + draft_max: Vec, + /// N-gram lookup key lengths. + #[arg(long, value_delimiter = ',', default_value = "3,6,12")] + ngram_n: Vec, + /// MTP draft counts to combine with the lookup (main engine only). + #[arg(long, value_delimiter = ',', default_value = "0,2")] + mtp: Vec, + #[arg(long)] + draft_model: Option, + #[arg(long)] + backend: Option, + #[arg(long, value_delimiter = ',', default_value = "0")] + device: Vec, + #[arg(long, default_value_t = 4096)] + ctx: usize, + #[arg(long, default_value = "512")] + vram_margin: Vec, + #[arg(long, value_parser = ["f16", "q8", "q4", "q2"], default_value = "f16")] + kv: String, + #[arg(long, default_value_t = 512)] + pp: usize, + #[arg(long, default_value_t = 128)] + tg: usize, + #[arg(long, default_value_t = 3)] + reps: usize, + #[arg(long, default_value_t = 24)] + samples: usize, + #[arg(long, default_value_t = 1)] + seed: u64, + #[arg(long)] + out: Option, + #[arg(long)] + dry_run: bool, + }, +} + fn main() { if let Err(e) = start() { say!("error: {e:#}"); @@ -1144,6 +1292,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { println!("{}", serde_json::json!({"argmax": argmax, "top5": top5})); } Cmd::Generate { model, prompt, n, image, mut engine } => { + engine.own_calib(&model); engine.ds_env(); let g = Gguf::open(&model)?; engine.own_warn(&g); @@ -1276,12 +1425,14 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { engine.own_warn(&g); engine.ctx = engine.ctx.max(pp.iter().max().unwrap_or(&0) + tg); if let Some(arch) = g.get("general.architecture").ok().and_then(|v| v.as_str()) { - if arch == "deepseek41" || arch == "glm5-next" || arch == rusting_strata::hy4::ARCH || rusting_strata::inkling2::is_arch(arch) { + if arch == "deepseek41" || arch == "glm5-next" || arch == "gemma4" || arch == rusting_strata::hy4::ARCH || rusting_strata::inkling2::is_arch(arch) { engine.ds_env(); // A --ctx below the test grows to fit it, as on the main engine. if rusting_strata::CTX.load(std::sync::atomic::Ordering::Relaxed) != 0 { rusting_strata::CTX.store(engine.ctx, std::sync::atomic::Ordering::Relaxed); } return if arch == "deepseek41" { bench_deepseek(&g, &model, &pp, tg, reps, json_out, &mut engine) + } else if arch == "gemma4" { + bench_gemma4(&g, &model, &pp, tg, reps, json_out, &mut engine) } else if arch == rusting_strata::hy4::ARCH { bench_hy4(&g, &model, &pp, tg, reps, json_out, &mut engine) } else if rusting_strata::inkling2::is_arch(arch) { @@ -1337,44 +1488,68 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { reps, }; let unix_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map_or(0, |d| d.as_secs()); - let record = bench_record(&meta, &results, r.expert_summary().as_ref(), unix_time); + let mut record = bench_record(&meta, &results, r.expert_summary().as_ref(), unix_time); + let drafts = if let Runner::Gpu(g) = &r { g.drafts } else { (0, 0) }; + record["drafts"] = json!({"made": drafts.0, "accepted": drafts.1}); let mut line = serde_json::to_string(&record)?; line.push('\n'); std::fs::write(&path, line).with_context(|| format!("writing the JSON record to {}", path.display()))?; } } - Cmd::Calibrate { model, ctx, vram_margin, backend, device, split, kv, lora, gpu: _, mtp_model, draft_model } => { + Cmd::Calibrate { model, ctx, vram_margin, backend, device, split, kv, lora, gpu: _, mtp_model, draft_model, + samples, reps, warmup, pp, tg, profile, objective, weights, ctx_values, kv_values, chunk_values, task, seed, + dry_run, timeout, out, sub } => { set_kv_env(&kv); // read by Gpu::new and Vk::new if !lora.is_empty() { say!("note: --lora is ignored by calibrate; calibration uses the base model"); } - let margins = vram_margins(&vram_margin, &device)?.into_iter().map(|mb| mb << 20).collect::>(); - let split = split_arg(split.as_deref(), device.len())?; - // The architecture of a file that runs on its own code path, where nothing reads a calibration file. - let own_arch = |p: &std::path::Path| { - let arch = Gguf::open(p).ok()?.get("general.architecture").ok()?.as_str()?.to_string(); - rusting_strata::config::OWN_ARCHS.contains(&arch.as_str()).then_some(arch) - }; - if !model.is_dir() { - if let Some(arch) = own_arch(&model) { - say!("nothing to calibrate: '{arch}' models run on their own code path, which reads no calibration file. Run chat, generate, bench or serve with this model as it is."); - return Ok(()); - } - return calibrate(&model, draft_model.as_deref().or(mtp_model.as_deref()), ctx, &margins, backend.as_deref(), &device, split); + if split.is_some() { say!("note: --split is ignored by v2 calibrate; measurements use the free-VRAM split"); } + let objective = if let Some(name) = &objective { (Objective::only(name)?, name.clone()) } + else if let Some(w) = &weights { + let parts: Vec = w.split(',').map(|x| x.trim().parse::()).collect::>()?; + anyhow::ensure!(parts.len() == 3, "--weights needs three numbers: prefill,decode,ttft"); + (Objective { prefill: parts[0], decode: parts[1], ttft: parts[2] }, format!("weights {w}")) + } else { (match profile.as_str() { "interactive" => Objective::interactive(), "batch" => Objective::batch(), _ => Objective::balanced() }, profile.clone()) }; + + if let Some(CalibrateSub::Spec { model, tasks, spec_types, draft_max, ngram_n, mtp, draft_model, backend, + device, ctx, vram_margin, kv, pp, tg, reps, samples, seed, out, dry_run }) = sub { + let mut s = CalibSettings::new(model); + s.backend = backend; s.device = device; s.vram_margin = vram_margin; s.kv = kv.clone(); + s.kv_values = vec![kv]; s.ctx = ctx; s.ctx_values = vec![ctx]; + s.tasks = tasks; s.spec_types = spec_types; s.draft_max = draft_max; s.ngram_n = ngram_n; + s.mtp_values = mtp; s.pp = vec![pp]; s.tg = tg; s.reps = reps; s.samples = samples; + s.seed = seed; s.out = out; s.dry_run = dry_run; + s.aux = draft_model.map(|p| ("--draft-model", p)); + (s.objective, s.objective_name, s.profile) = (objective.0, objective.1, profile.clone()); + return calibrate_spec(&s); } - anyhow::ensure!(draft_model.is_none() && mtp_model.is_none(), "--mtp-model and --draft-model belong to one model: give --model a file"); + + let Some(model) = model else { anyhow::bail!("--model PATH is required (or use `calibrate spec --model PATH`)") }; + let mut settings = CalibSettings::new(model.clone()); + settings.backend = backend; + settings.device = device; + settings.vram_margin = vram_margin; + settings.kv = kv.clone(); + settings.kv_values = kv_values.unwrap_or_else(|| vec![kv]); + settings.chunk_values = chunk_values.unwrap_or_else(|| vec![256, 512, 1024, 2048, 4096]); + settings.ctx = ctx; + // Search the requested context and its double by default: context size changes KV cost and the sweet + // spot of the prefill chunk, so fixing it would miss part of the optimum. + settings.ctx_values = ctx_values.unwrap_or_else(|| vec![ctx, (ctx * 2).min(65536)]); + settings.aux = draft_model.map(|p| ("--draft-model", p)).or_else(|| mtp_model.map(|p| ("--mtp-model", p))); + settings.samples = samples; settings.reps = reps; settings.warmup = warmup; settings.pp = pp; + settings.tg = tg; settings.tasks = task; + settings.seed = seed; settings.dry_run = dry_run; settings.timeout = timeout; settings.out = out; + (settings.objective, settings.objective_name, settings.profile) = (objective.0, objective.1, profile); + if settings.pp.is_empty() || settings.pp.iter().any(|&n| n == 0) { anyhow::bail!("--pp needs at least one positive prompt depth"); } + if settings.samples == 0 { anyhow::bail!("--samples must be positive"); } + if !model.is_dir() { return calibrate_v2(&settings); } let list = rusting_strata::serve::list_models(&model); anyhow::ensure!(!list.is_empty(), "no .gguf models in {}", model.display()); + anyhow::ensure!(settings.aux.is_none(), "--mtp-model and --draft-model belong to one model: give --model a file"); let mut failed = vec![]; for (k, (id, path, _)) in list.iter().enumerate() { say!("calibrate {}/{}: {id}", k + 1, list.len()); - if let Some(arch) = own_arch(path) { - say!("calibrate {id}: skipped, calibrate measures the main engine only and '{arch}' models run on their own code path"); - continue; - } - // One model that fails (too big, not a model) does not stop the others. - if let Err(e) = calibrate(path, None, ctx, &margins, backend.as_deref(), &device, split.clone()) { - say!("calibrate {id}: failed: {e:#}"); - failed.push(id.as_str()); - } + settings.model = path.clone(); + if let Err(e) = calibrate_v2(&settings) { say!("calibrate {id}: failed: {e:#}"); failed.push(id.as_str()); } } anyhow::ensure!(failed.is_empty(), "calibration failed for {}", failed.join(", ")); } @@ -1440,6 +1615,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { } Cmd::Chat { model, system, n, image, mut engine } => { let think = engine.think_default; + engine.own_calib(&model); engine.ds_env(); let g = Gguf::open(&model)?; engine.own_warn(&g); @@ -1948,6 +2124,50 @@ fn $name(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: } bench_tokenwise!(bench_hy4, rusting_strata::hy4::forward::Hy4Model); +/// `strata bench` for Gemma 4. Its `gpu_defaults` is private to the module, so mirror the three variables its +/// generate/chat paths set; the timing loop is otherwise the shared token-by-token one. +fn bench_gemma4(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: Option, engine: &mut Engine) -> anyhow::Result<()> { + rusting_strata::deepseek::chat::gpu_defaults(); + for (k, v) in [("STRATA_DS_GPU_EXPERTS", "11"), ("STRATA_DS_NOEVICT", "1")] { + if std::env::var_os(k).is_none() { unsafe { std::env::set_var(k, v) } } + } + let tok = Tokenizer::from_gguf(g)?; + let mut m = rusting_strata::gemma4::forward::Gemma4Model::new(g)?; + let eos = tok.eos_ids(); + let mut results = Vec::with_capacity(pp.len()); + for &n in pp { + let ids = prose(&tok, n)?; + let (mut p, mut d) = (Vec::new(), Vec::new()); + for _ in 0..reps { + m.reset(); + let t = Instant::now(); + let logits = m.prefill(&ids); + p.push(n as f64 / t.elapsed().as_secs_f64()); + let t = Instant::now(); + let k = decode_greedy_big(&mut |t| m.step(t), logits, &eos, tg); + d.push(k as f64 / t.elapsed().as_secs_f64()); + } + let (prefill, decode_stat) = (Stat::of(&p), Stat::of(&d)); + println!("pp {n:6}: prefill {} tok/s | tg {tg}: decode {} tok/s", prefill.text(), decode_stat.text()); + results.push(BenchResult { pp: n, prefill, decode: decode_stat, bytes_per_token: 0, decode_median: 0.0 }); + } + let expert = big_expert_stats(m.cfg.n_layer, m.cfg.n_expert); + let backend = rusting_strata::deepseek::mat::dev_info().map_or("cpu", |i| i.0); + let meta = BenchMeta { + backend, + backend_arg: engine.backend.as_deref(), + device: if backend == "cpu" { &[] } else { &engine.device }, + model, + ctx: engine.ctx, + chunk: 1, + kv: &engine.kv, + mtp: 0, + tg, + reps, + }; + write_bench_json(json_out, &meta, &results, expert.as_ref()) +} + /// `strata bench` for Inkling 2 (uses GPU argmax decode, plus `--draft-model` DSpark / `--spec-type` context lookup). fn bench_inkling2(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: Option, engine: &mut Engine) -> anyhow::Result<()> { rusting_strata::deepseek::chat::gpu_defaults(); @@ -2067,9 +2287,468 @@ fn best(f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result { Ok(b) } -/// With `aux` (`--mtp-model`/`--draft-model`) the drafts are measured with that file, and runs given the same file use -/// the measured draft count. -fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], mut split: Option>) -> anyhow::Result<()> { +/// Settings shared by the v2 calibration workflow and its `spec` subcommand. +#[derive(Clone, Debug)] +struct CalibSettings { + model: PathBuf, + backend: Option, + device: Vec, + vram_margin: Vec, + kv: String, + /// (flag, path): an MTP head or a draft model used for every measurement. + aux: Option<(&'static str, PathBuf)>, + ctx: usize, + samples: usize, + reps: usize, + warmup: usize, + pp: Vec, + tg: usize, + objective: Objective, + objective_name: String, + profile: String, + ctx_values: Vec, + kv_values: Vec, + chunk_values: Vec, + tasks: Vec, + seed: u64, + dry_run: bool, + timeout: u64, + out: Option, + /// Only used by the `spec` subcommand. + spec_types: Vec, + draft_max: Vec, + ngram_n: Vec, + mtp_values: Vec, +} + +impl CalibSettings { + fn new(model: PathBuf) -> Self { + Self { + model, backend: None, device: vec![0], vram_margin: vec!["512".into()], kv: "f16".into(), + aux: None, ctx: 4096, samples: 24, reps: 3, warmup: 0, pp: vec![128, 512, 2048], tg: 128, + objective: Objective::balanced(), objective_name: "balanced".into(), profile: "balanced".into(), + ctx_values: vec![4096, 8192], kv_values: vec!["f16".into()], + chunk_values: vec![256, 512, 1024, 2048, 4096], tasks: vec!["prose".into()], + seed: 1, dry_run: false, timeout: 0, out: None, + spec_types: vec![], draft_max: vec![], ngram_n: vec![], mtp_values: vec![], + } + } +} + +/// Physical core count, with a deterministic fallback so calibration never depends on this optional probe. +fn calib_threads() -> usize { + physical_cores().unwrap_or_else(|| std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4)) +} + +fn calib_work_dir() -> anyhow::Result { + let d = rusting_strata::expert_cache::cache_dir().join("calibrate"); + std::fs::create_dir_all(&d)?; + Ok(d) +} + +static CALIB_SEQ: AtomicUsize = AtomicUsize::new(0); + +/// A short, fixed coding corpus for the built-in `coding` task. The prose paragraph routes few experts; real code +/// repeats punctuation and identifiers, which changes both n-gram acceptance and the prefill cost. +const CALIB_CODE: &str = r#"fn parse_config(path: &str) -> Result { + let text = std::fs::read_to_string(path)?; + let mut config = Config::default(); + for (line_no, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { continue; } + let mut parts = line.splitn(2, '='); + let key = parts.next().unwrap().trim(); + let value = parts.next().ok_or(Error::Syntax(line_no))?.trim(); + match key { + "threads" => config.threads = value.parse()?, + "chunk" => config.chunk = value.parse()?, + "kv" => config.kv = value.to_string(), + _ => return Err(Error::UnknownKey(line_no)), + } + } + Ok(config) +} +"#; + +/// Resolve a task label to a prompt file. `None` means the built-in prose (no `--prompt-file`). +fn calib_prompt(task: &str, dir: &Path) -> anyhow::Result> { + match task { + "prose" => Ok(None), + "coding" => { + let p = dir.join("task-coding.txt"); + std::fs::write(&p, CALIB_CODE)?; + Ok(Some(p)) + } + t if t.starts_with("user:") => { + let p = PathBuf::from(&t[5..]); + anyhow::ensure!(p.is_file(), "task prompt file {} does not exist", p.display()); + Ok(Some(p)) + } + other => anyhow::bail!("unknown task {other:?} (expected prose, coding or user:PATH)"), + } +} + +struct BenchSample { + measurements: Vec, + backend: String, +} + +fn run_capped(mut c: Command, secs: u64) -> anyhow::Result { + if secs == 0 { return Ok(c.output()?); } + let mut child = c.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?; + let deadline = Instant::now() + Duration::from_secs(secs); + loop { + if child.try_wait()?.is_some() { break; } + if Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); // reap the child before returning the error + anyhow::bail!("sample timed out after {secs}s"); + } + std::thread::sleep(Duration::from_millis(100)); + } + Ok(child.wait_with_output()?) +} + +/// Draft counts are in the main engine's bench JSON; the arch-specific benchners print them. Accept both. +fn parse_drafts(v: &serde_json::Value, stdout: &str) -> (usize, usize) { + let made = v["drafts"]["made"].as_u64(); + let accepted = v["drafts"]["accepted"].as_u64(); + if let (Some(a), Some(b)) = (made, accepted) { return (a as usize, b as usize); } + if let Some(pos) = stdout.find("drafts accepted ") { + let rest = &stdout[pos + "drafts accepted ".len()..]; + if let Some(tok) = rest.split_whitespace().next() { + let mut it = tok.split('/'); + if let (Some(a), Some(b)) = (it.next(), it.next()) { + if let (Ok(accepted), Ok(made)) = (a.parse::(), b.parse::()) { + return (made, accepted); + } + } + } + } + (0, 0) +} + +/// One measurement sample: run `bench` as a child process with the candidate knobs applied, then read its JSON. +/// Using the public bench command as the measurement channel is what makes calibration work with every architecture: +/// there is one code path that times a prompt and a decode, and calibration never duplicates it. +fn bench_sample(s: &CalibSettings, knobs: &Knobs, task: &str, pps: &[usize]) -> anyhow::Result { + let dir = calib_work_dir()?; + let id = CALIB_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let json = dir.join(format!("bench-{}-{id}.json", std::process::id())); + let prompt = calib_prompt(task, &dir)?; + let exe = std::env::current_exe().context("finding this executable")?; + let ctx = knobs.i("ctx").unwrap_or(s.ctx); + let kv_idx = knobs.i("kv").unwrap_or(0).min(s.kv_values.len().saturating_sub(1)); + let kv = s.kv_values.get(kv_idx).map(String::as_str).unwrap_or("f16"); + let chunk = knobs.i("chunk").unwrap_or(4096); + let mtp = knobs.i("mtp").unwrap_or(0); + let short = knobs.i("short").unwrap_or(32); + let threads = knobs.i("threads").unwrap_or_else(calib_threads); + + let build = |reps: usize| { + let mut c = Command::new(&exe); + c.arg("bench") + .arg("--model").arg(&s.model) + .arg("--gpu") + .arg("--pp").arg(pps.iter().map(|n| n.to_string()).collect::>().join(",")) + .arg("--tg").arg(s.tg.to_string()) + .arg("--reps").arg(reps.to_string()) + .arg("--ctx").arg(ctx.to_string()) + .arg("--kv").arg(kv) + .arg("--chunk").arg(chunk.to_string()) + .arg("--mtp").arg(mtp.to_string()) + .arg("--threads").arg(threads.to_string()) + .arg("--short").arg(short.to_string()) + .arg("--device").arg(s.device.iter().map(|d| d.to_string()).collect::>().join(",")) + .arg("--json-out").arg(&json); + if let Some(b) = &s.backend { c.arg("--backend").arg(b); } + if let Some((flag, p)) = &s.aux { c.arg(flag).arg(p); } + if let Some(p) = &prompt { c.arg("--prompt-file").arg(p); } + if !s.vram_margin.is_empty() { c.arg("--vram-margin").arg(s.vram_margin.join(",")); } + // The architectures outside the main engine take their chunk from the environment at prefill time. + c.env("STRATA_DS_CHUNK", chunk.to_string()); + c.env("STRATA_GLM_CHUNK", chunk.to_string()); + if !s.spec_types.is_empty() { + let ti = knobs.i("spec_type").unwrap_or(0).min(s.spec_types.len() - 1); + let di = knobs.i("draft_max").unwrap_or(0).min(s.draft_max.len() - 1); + let ni = knobs.i("ngram_n").unwrap_or(0).min(s.ngram_n.len() - 1); + c.arg("--spec-type").arg(s.spec_types[ti].clone()); + c.arg("--spec-draft-n-max").arg(s.draft_max[di].to_string()); + c.arg("--spec-ngram-size-n").arg(s.ngram_n[ni].to_string()); + } + c + }; + if s.warmup > 0 { let _ = run_capped(build(1), s.timeout)?; } + let out = run_capped(build(s.reps), s.timeout)?; + let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); + if !out.status.success() { + let _ = std::fs::remove_file(&json); + anyhow::bail!("bench failed: {}{}", stdout, String::from_utf8_lossy(&out.stderr)); + } + let text = std::fs::read_to_string(&json).with_context(|| format!("reading {}", json.display()))?; + let v: serde_json::Value = match serde_json::from_str(&text) { + Ok(v) => v, + Err(e) => { let _ = std::fs::remove_file(&json); return Err(e.into()); } + }; + if v["schema"] != "strata.bench.v1" { + let _ = std::fs::remove_file(&json); + anyhow::bail!("bench wrote an unexpected schema"); + } + let rows = v["results"].as_array().context("bench JSON has no results")?; + let (made, accepted) = parse_drafts(&v, &stdout); + let mut ms = Vec::with_capacity(pps.len()); + for &pp in pps { + let r = rows.iter().find(|r| r["pp"].as_u64() == Some(pp as u64)) + .with_context(|| format!("bench JSON has no pp {pp}"))?; + let num = |key: &str| r[key]["mean"].as_f64().unwrap_or(0.0); + ms.push(Measurement { + prefill_tok_s: num("prefill_tok_s"), + decode_tok_s: num("decode_tok_s"), + ttft_ms: num("ttft_ms"), + drafts_offered: made, + drafts_accepted: accepted, + }); + } + let _ = std::fs::remove_file(&json); + Ok(BenchSample { measurements: ms, backend: v["backend"].as_str().unwrap_or("cuda").to_string() }) +} + +/// Group workloads by task, keeping their order, so one sample can benchmark several prompt depths of a corpus in a +/// single child process while different corpora use different `--prompt-file`s. +fn workload_groups(ws: &[Workload]) -> Vec<(String, Vec<(usize, Workload)>)> { + let mut out: Vec<(String, Vec<(usize, Workload)>)> = Vec::new(); + for (i, w) in ws.iter().enumerate() { + if let Some(g) = out.iter_mut().find(|g| g.0 == w.task) { g.1.push((i, w.clone())); } + else { out.push((w.task.clone(), vec![(i, w.clone())])); } + } + out +} + +fn measure_fn<'a>(s: &'a CalibSettings, backend: &'a RefCell) -> impl FnMut(&Knobs, &[Workload]) -> anyhow::Result> + 'a { + move |knobs, ws| { + let mut out: Vec<(usize, Measurement)> = Vec::with_capacity(ws.len()); + for (task, group) in workload_groups(ws) { + let pps: Vec = group.iter().map(|(_, w)| w.pp).collect(); + let sample = bench_sample(s, knobs, &task, &pps)?; + if backend.borrow().is_empty() { *backend.borrow_mut() = sample.backend.clone(); } + for ((i, _), m) in group.into_iter().zip(sample.measurements) { out.push((i, m)); } + } + // Restore the caller's workload order: the JSON report indexes both arrays by the same position. + out.sort_by_key(|(i, _)| *i); + Ok(out.into_iter().map(|(_, m)| m).collect()) + } +} + +/// The search space for the main engine and for the models that run on their own code path. Only a handful of values +/// per knob: the coarse sweep plus refinement finds a better point in this small space than a fixed one-way grid. +fn build_space(arch: &str, s: &CalibSettings) -> Vec { + let own = rusting_strata::config::OWN_ARCHS.contains(&arch); + let threads = calib_threads(); + let mut space = vec![ + KnobSpec::new("ctx", s.ctx_values.iter().map(|n| *n as f64), true), + KnobSpec::new("kv", (0..s.kv_values.len()).map(|i| i as f64), true), + KnobSpec::new("chunk", s.chunk_values.iter().map(|n| *n as f64), false), + ]; + if own { + // Their chunk is read from the environment at prefill time; MTP drafts belong to the `spec` sweep where the + // model supports them. + space.push(KnobSpec::new("short", [32.0], false)); + space.push(KnobSpec::new("threads", [threads as f64], false)); + } else { + space.push(KnobSpec::new("mtp", [0.0, 1.0, 2.0, 4.0], false)); + space.push(KnobSpec::new("short", [16.0, 32.0, 64.0, 128.0], false)); + space.push(KnobSpec::new("threads", [(threads.max(2) / 2) as f64, threads as f64], false)); + } + space +} + +fn default_knobs(space: &[KnobSpec]) -> Knobs { + let mut k = Knobs::default(); + for s in space { if let Some(v) = s.values.first() { k.set(&s.name, *v); } } + k +} + +/// Write the small file that later runs read, keeping every key of the v1 format. The full trace is written beside it +/// when `--out` is given, so a calibration can be audited or reproduced from its seed. +/// The physical device the search measured on, for the v1 `gpu` compatibility check. +fn calib_gpu_name(s: &CalibSettings) -> String { + s.device.first().and_then(|&d| backend::open(s.backend.as_deref(), d).ok()) + .map(|b| b.device().to_string()).unwrap_or_default() +} + +fn write_report(s: &CalibSettings, result: &calibrate::SearchResult) -> anyhow::Result<()> { + if let Some(out) = &s.out { + std::fs::create_dir_all(out)?; + let stem = s.model.file_stem().and_then(|x| x.to_str()).unwrap_or("model"); + let report = out.join(format!("strata-{stem}-calib-report.json")); + std::fs::write(&report, serde_json::to_string_pretty(result)?)?; + say!("full benchmark report: {}", report.display()); + } + Ok(()) +} + +fn write_calibration(s: &CalibSettings, result: &calibrate::SearchResult, workloads: &[Workload], arch: &str, backend: &str, gpu: &str) -> anyhow::Result { + let path = calibration_path(&s.model, backend, &s.device); + std::fs::create_dir_all(path.parent().unwrap())?; + let mut v: serde_json::Value = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + let best = &result.best; + let kv_idx = best.knobs.i("kv").unwrap_or(0).min(s.kv_values.len().saturating_sub(1)); + let first = best.measurements.first().cloned().unwrap_or_default(); + let ctx = best.knobs.i("ctx").unwrap_or(s.ctx); + v["schema"] = json!(2); + v["arch"] = json!(arch); + v["chunk"] = json!(best.knobs.i("chunk").unwrap_or(4096)); + v["mtp"] = json!(best.knobs.i("mtp").unwrap_or(0)); + v["short"] = json!(best.knobs.i("short").unwrap_or(32)); + v["threads"] = json!(best.knobs.i("threads").unwrap_or_else(calib_threads)); + v["ctx"] = json!(ctx); + v["ctx_recommended"] = json!(ctx); + v["kv"] = json!(s.kv_values.get(kv_idx).map(String::as_str).unwrap_or("f16")); + v["gpu"] = json!(gpu); + v["bytes"] = json!(std::fs::metadata(&s.model)?.len()); + v["measured"] = json!({ + "prefill_tok_s": round1(first.prefill_tok_s), + "decode_tok_s": round1(first.decode_tok_s), + "ttft_ms": round1(first.ttft_ms), + }); + v["best"] = serde_json::to_value(&best.knobs)?; + v["search"] = json!({ + "samples_used": result.samples_used, + "score": round1(result.best.score * 1000.0) / 1000.0, + "stop_reason": result.stop_reason, + "elapsed_ms": result.elapsed_ms, + "seed": result.seed, + "objective": s.objective_name, + "profile": s.profile, + }); + v["workloads"] = serde_json::to_value(workloads)?; + if let Some(a) = &s.aux { if let Some(name) = a.1.file_name() { v["aux"] = name.to_string_lossy().into(); } } + std::fs::write(&path, serde_json::to_string_pretty(&v)?)?; + write_report(s, result)?; + Ok(path) +} + +/// Pure merge used by a spec sweep: it must not replace the engine knobs measured by a previous run. +fn merge_spec_calibration(mut old: serde_json::Value, spec: &serde_json::Value, arch: &str, gpu: &str, bytes: u64) -> serde_json::Value { + old["schema"] = json!(2); + old["arch"] = json!(arch); + old["gpu"] = json!(gpu); + old["bytes"] = json!(bytes); + old["spec"] = spec.clone(); + old +} + +/// A spec sweep only adds its `spec` section: it must not replace the engine knobs measured by a previous run. +fn write_spec_calibration(s: &CalibSettings, result: &calibrate::SearchResult, arch: &str, backend: &str, gpu: &str, spec: &serde_json::Value) -> anyhow::Result { + let path = calibration_path(&s.model, backend, &s.device); + std::fs::create_dir_all(path.parent().unwrap())?; + let old: serde_json::Value = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + let mut v = merge_spec_calibration(old, spec, arch, gpu, std::fs::metadata(&s.model)?.len()); + v["spec_search"] = json!({"samples_used": result.samples_used, + "score": round1(result.best.score * 1000.0) / 1000.0, + "stop_reason": result.stop_reason, "seed": result.seed}); + std::fs::write(&path, serde_json::to_string_pretty(&v)?)?; + write_report(s, result)?; + Ok(path) +} + +/// The universal calibration workflow. Every supported architecture goes through here; the measurement is delegated +/// to `bench`, so there is no arch-specific timing code to keep in sync. +fn calibrate_v2(s: &CalibSettings) -> anyhow::Result<()> { + let g = Gguf::open(&s.model)?; + let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or("unknown").to_string(); + let space = build_space(&arch, s); + let tasks: Vec = if s.tasks.is_empty() { vec!["prose".into()] } else { s.tasks.clone() }; + let workloads: Vec = tasks.iter().flat_map(|task| { + s.pp.iter().map(move |&pp| Workload::new(pp, s.tg, task)) + }).collect(); + say!("calibrate {arch}: {} workloads, {}-sample budget, objective {}", workloads.len(), s.samples, s.objective_name); + for w in &workloads { say!(" {}", w.label()); } + say!("knobs: {}", space.iter().map(|k| format!("{}=[{}]{}", k.name, k.values.iter().map(|v| format!("{v:.0}")).collect::>().join(","), if k.reload { " (reload)" } else { "" })).collect::>().join(" ")); + if s.dry_run { say!("dry run: no measurements taken"); return Ok(()); } + + let backend = RefCell::new(String::new()); + let mut measure = measure_fn(s, &backend); + let base_knobs = default_knobs(&space); + say!("baseline: {}", base_knobs.label()); + let baseline = measure(&base_knobs, &workloads)?; + let cfg = SearchConfig { samples: s.samples, coarse: (s.samples / 3).min(8), starts: 3, patience: 2, seed: s.seed }; + let result = calibrate::search(&space, &workloads, &cfg, &s.objective, baseline, &mut measure)?; + anyhow::ensure!(result.best.error.is_none(), "no successful measurement; calibration not written"); + let backend_name = if backend.borrow().is_empty() { "cuda".to_string() } else { backend.borrow().clone() }; + say!("best {}: score {:.3} vs baseline ({:.1} samples, {}, {:.1}s)", result.best.knobs.label(), result.best.score, + result.samples_used, result.stop_reason, result.elapsed_ms as f64 / 1000.0); + let path = write_calibration(s, &result, &workloads, &arch, &backend_name, &calib_gpu_name(s))?; + println!("{}\nwritten to {}", serde_json::to_string_pretty(&serde_json::from_str::(&std::fs::read_to_string(&path)?)?)?, path.display()); + Ok(()) +} + +/// Every spec knob is stored as an index into the flag's value list: the search only sees small contiguous ranges +/// and `bench_sample` can index the list directly. +fn spec_space(s: &CalibSettings) -> Vec { + vec![ + KnobSpec::new("spec_type", (0..s.spec_types.len()).map(|i| i as f64), false), + KnobSpec::new("draft_max", (0..s.draft_max.len()).map(|i| i as f64), false), + KnobSpec::new("ngram_n", (0..s.ngram_n.len()).map(|i| i as f64), false), + KnobSpec::new("mtp", (0..s.mtp_values.len()).map(|i| i as f64), false), + ] +} + +/// The `spec` subcommand: one task-specific sweep of speculative settings, written under `spec` in the calibration +/// file. It uses the same budgeted search, with each task as its own workload so acceptance can differ by corpus. +fn calibrate_spec(s: &CalibSettings) -> anyhow::Result<()> { + let g = Gguf::open(&s.model)?; + let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or("unknown").to_string(); + let space = spec_space(s); + let workloads: Vec = s.tasks.iter().map(|t| Workload::new(s.pp[0], s.tg, t)).collect(); + say!("spec sweep {arch}: {} tasks x {} types x {} drafts x {} n-grams x {} mtp", workloads.len(), s.spec_types.len(), s.draft_max.len(), s.ngram_n.len(), s.mtp_values.len()); + if s.dry_run { say!("dry run: no measurements taken"); return Ok(()); } + let backend = RefCell::new(String::new()); + let mut measure = measure_fn(s, &backend); + let baseline = measure(&default_knobs(&space), &workloads)?; + let cfg = SearchConfig { samples: s.samples, coarse: (s.samples / 3).min(8), starts: 3, patience: 2, seed: s.seed }; + let result = calibrate::search(&space, &workloads, &cfg, &s.objective, baseline, &mut measure)?; + anyhow::ensure!(result.best.error.is_none(), "no successful spec measurement; calibration not written"); + let idx = |name: &str, len: usize| result.best.knobs.i(name).unwrap_or(0).min(len.saturating_sub(1)); + let mut spec = serde_json::Map::new(); + for (i, w) in workloads.iter().enumerate() { + let m = result.best.measurements.get(i).cloned().unwrap_or_default(); + let share = if m.drafts_offered > 0 { round1(10000.0 * m.drafts_accepted as f64 / m.drafts_offered as f64) / 100.0 } else { 0.0 }; + spec.insert(w.task.clone(), json!({ + "spec_type": s.spec_types[idx("spec_type", s.spec_types.len())], + "draft_max": s.draft_max[idx("draft_max", s.draft_max.len())], + "ngram_n": s.ngram_n[idx("ngram_n", s.ngram_n.len())], + "mtp": s.mtp_values[idx("mtp", s.mtp_values.len())], + "decode_tok_s": round1(m.decode_tok_s), + "ttft_ms": round1(m.ttft_ms), + "acceptance_pct": share, + })); + } + let backend_name = if backend.borrow().is_empty() { "cuda".to_string() } else { backend.borrow().clone() }; + let path = write_spec_calibration(s, &result, &arch, &backend_name, &calib_gpu_name(s), &serde_json::Value::Object(spec))?; + say!("spec sweep written to {}", path.display()); + Ok(()) +} + +/// Compatibility wrapper used by the chat page's calibrate button and by any code calling the old six-argument +/// function. It maps the previous defaults onto the v2 workflow. +fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], _split: Option>) -> anyhow::Result<()> { + let mut s = CalibSettings::new(model.to_path_buf()); + s.aux = aux.map(|p| ("--draft-model", p.to_path_buf())); + s.ctx = ctx; + s.ctx_values = vec![ctx]; + s.backend = kind.map(str::to_string); + s.device = device.to_vec(); + s.vram_margin = margin.iter().map(|m| (m >> 20).to_string()).collect(); + s.samples = 12; + s.pp = vec![512]; + calibrate_v2(&s) +} + +/// The original chunk/MTP/short/split grid search, kept for reference but no longer dispatched: the v2 workflow below +/// measures through `bench` so it covers every architecture. +#[allow(dead_code)] +fn calibrate_legacy(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], mut split: Option>) -> anyhow::Result<()> { let g = Gguf::open(model)?; let aux_g = open_mtp_gguf(aux)?; let m = Model::load_with_aux(&g, aux_g.as_ref(), &[])?; @@ -2832,6 +3511,7 @@ fn serve_model(model: &Path, mut engine: Engine, s: &Serving, w: &mut Option 1.5 s, slowest 100 tok/s -> 3 s. + assert!((ttft["mean"].as_f64().unwrap() - 2000.0).abs() < 1e-6); + assert!((ttft["min"].as_f64().unwrap() - 1500.0).abs() < 1e-6); + assert!((ttft["max"].as_f64().unwrap() - 3000.0).abs() < 1e-6); + } + #[test] fn bench_record_omits_expert_without_a_cache() { let v = parsed(&bench_record(&meta(), &[result(512, Stat { mean: 1.0, min: 1.0, max: 1.0 }, Stat { mean: 2.0, min: 2.0, max: 2.0 })], None, 0)); @@ -3646,3 +4338,114 @@ mod bench_tests { assert!(Cli::try_parse_from(["rustingstrata", "bench", "--model", "m.gguf", "--json-out", "/tmp/x.json"]).is_ok()); } } + +#[cfg(test)] +mod calibrate_cli_tests { + use super::*; + + #[test] + fn cli_parses_the_v2_calibration_flags() { + let cli = Cli::try_parse_from([ + "rustingstrata", "calibrate", "--model", "m.gguf", "--samples", "7", "--reps", "2", + "--pp", "128,512", "--tg", "16", "--profile", "interactive", "--task", "user:prompts.txt", + "--ctx-values", "4096,8192", "--kv-values", "f16,q8", "--seed", "9", "--dry-run", + ]).unwrap(); + match cli.cmd.unwrap() { + Cmd::Calibrate { samples, reps, pp, tg, profile, task, ctx_values, kv_values, seed, dry_run, sub, .. } => { + assert_eq!((samples, reps, tg, seed), (7, 2, 16, 9)); + assert_eq!(pp, vec![128, 512]); + assert_eq!(profile, "interactive"); + assert_eq!(task, vec!["user:prompts.txt"]); + assert_eq!(ctx_values, Some(vec![4096, 8192])); + assert_eq!(kv_values, Some(vec!["f16".into(), "q8".into()])); + assert!(dry_run); + assert!(sub.is_none()); + } + _other => panic!("wrong command"), + } + } + + #[test] + fn cli_parses_the_spec_subcommand() { + let cli = Cli::try_parse_from([ + "rustingstrata", "calibrate", "spec", "--model", "m.gguf", "--tasks", "prose,coding", + "--spec-types", "none,ngram-simple,ngram-mod", "--draft-max", "4,8", "--ngram-n", "3,6", + "--samples", "5", "--dry-run", + ]).unwrap(); + match cli.cmd.unwrap() { + Cmd::Calibrate { sub: Some(CalibrateSub::Spec { model, tasks, spec_types, draft_max, ngram_n, samples, dry_run, .. }), .. } => { + assert_eq!(model, PathBuf::from("m.gguf")); + assert_eq!(tasks, vec!["prose", "coding"]); + assert_eq!(spec_types, vec!["none", "ngram-simple", "ngram-mod"]); + assert_eq!((draft_max, ngram_n, samples), (vec![4, 8], vec![3, 6], 5)); + assert!(dry_run); + } + _other => panic!("wrong command"), + } + } + + #[test] + fn draft_counts_are_read_from_both_json_and_stdout() { + let v = serde_json::json!({"drafts": {"made": 300, "accepted": 285}}); + assert_eq!(parse_drafts(&v, ""), (300, 285)); + // The arch-specific benchners print "accepted /". + assert_eq!(parse_drafts(&serde_json::Value::Null, "speculative drafts accepted 285/300 (95.0%)"), (300, 285)); + assert_eq!(parse_drafts(&serde_json::Value::Null, "no drafts here"), (0, 0)); + } + + #[test] + fn workload_groups_keep_task_and_depth_order() { + let ws = vec![ + Workload::new(128, 16, "prose"), Workload::new(512, 16, "coding"), + Workload::new(2048, 16, "prose"), Workload::new(96, 16, "coding"), + ]; + let g = workload_groups(&ws); + assert_eq!(g.iter().map(|x| x.0.as_str()).collect::>(), vec!["prose", "coding"]); + assert_eq!(g[0].1.iter().map(|(_, w)| w.pp).collect::>(), vec![128, 2048]); + assert_eq!(g[1].1.iter().map(|(_, w)| w.pp).collect::>(), vec![512, 96]); + assert_eq!(g[0].1[0].0, 0); + assert_eq!(g[0].1[1].0, 2); + } + + #[test] + fn spec_space_stores_indices_not_actual_values() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.spec_types = vec!["none".into(), "ngram-simple".into(), "ngram-mod".into(), "ngram-cache".into()]; + s.draft_max = vec![4, 8, 16]; + s.ngram_n = vec![3, 6, 12]; + s.mtp_values = vec![0, 2]; + let space = spec_space(&s); + assert_eq!(space[0].values, vec![0.0, 1.0, 2.0, 3.0]); + assert_eq!(space[1].values, vec![0.0, 1.0, 2.0]); + assert_eq!(space[2].values, vec![0.0, 1.0, 2.0]); + assert_eq!(space[3].values, vec![0.0, 1.0]); + } + + #[test] + fn a_spec_sweep_preserves_the_engine_calibration() { + let old = serde_json::json!({"chunk": 2048, "mtp": 2, "ctx": 8192, "short": 32, "threads": 6, + "measured": {"prefill_tok_s": 100}, "best": {"chunk": 2048}}); + let spec = serde_json::json!({"prose": {"spec_type": "ngram-mod"}}); + let v = merge_spec_calibration(old, &spec, "inkling2_loop", "RTX", 1234); + assert_eq!(v["chunk"], 2048); + assert_eq!(v["mtp"], 2); + assert_eq!(v["ctx"], 8192); + assert_eq!(v["measured"]["prefill_tok_s"], 100); + assert_eq!(v["spec"]["prose"]["spec_type"], "ngram-mod"); + assert_eq!(v["gpu"], "RTX"); + assert_eq!(v["bytes"], 1234); + } + + #[test] + fn knob_space_covers_main_engine_and_own_arch_models() { + let s = CalibSettings::new(PathBuf::from("m.gguf")); + let main = build_space("qwen35moe", &s); + let names: Vec<_> = main.iter().map(|k| k.name.as_str()).collect(); + assert_eq!(names, vec!["ctx", "kv", "chunk", "mtp", "short", "threads"]); + assert!(main.iter().find(|k| k.name == "ctx").unwrap().reload); + assert!(!main.iter().find(|k| k.name == "chunk").unwrap().reload); + let own = build_space("inkling2_loop", &s); + let names: Vec<_> = own.iter().map(|k| k.name.as_str()).collect(); + assert_eq!(names, vec!["ctx", "kv", "chunk", "short", "threads"]); + } +}