diff --git a/README.md b/README.md index 4402f59..70576c1 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,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, MTP drafts, short threshold 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 @@ -80,6 +81,7 @@ 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, 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/CALIBRATION.md b/docs/CALIBRATION.md new file mode 100644 index 0000000..a9da69b --- /dev/null +++ b/docs/CALIBRATION.md @@ -0,0 +1,190 @@ +# 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. + +Every architecture the binary supports is measured, including Inkling 2, Hy4, GLM, DeepSeek and Gemma 4, which the +old command skipped because they run on their own code path. Measurement is delegated to the existing `bench` +command (as a child process, reading its `strata.bench.v1` JSON), so there is a single timing implementation to trust. + +## Quick start + +```sh +M=path/to/model.gguf + +# See the derived knob space and workload matrix, without loading weights: +rustingstrata calibrate --model $M --dry-run + +# A normal calibration: 24 samples, prompt depths 128/512/2048: +rustingstrata calibrate --model $M + +# A smaller, explicit search with two real corpora: +rustingstrata calibrate --model $M --chunk-values 512,1024,2048,4096 \ + --task prose --task coding --pp 128,512,2048 --tg 128 --samples 32 \ + --out ./calib-reports + +# Every model in a folder, one after another: +rustingstrata calibrate --model ~/models +``` + +The command prints the workload matrix and knob space, then the baseline and the winner, then the path of the JSON +file. `--out DIR` additionally writes a full trace of every sample as `strata--calib-report.json`. + +## What is optimized + +Two signals are measured per workload: **prefill throughput** (prompt tokens / prefill time) and **decode throughput** +(generated tokens / greedy decode time). Both are divided by their own baseline and combined with a geometric mean: + +``` +score = sqrt((prefill / baseline_prefill) · (decode / baseline_decode)) +``` + +An arithmetic mean would let a huge gain in one signal hide a regression in the other. Ratios are clamped to +`[1e-3, 1e3]` so a failed measurement cannot produce infinities. Several workloads are combined with a geometric mean, +so every prompt depth counts equally. Time to first token is *not* a separate signal: for greedy decoding the first +token's logits come out of the prefill, so TTFT would just reweight prefill. + +The baseline is what a user gets today **without** a calibration file: the engine's own chunk — 4096 for the main +engine, 256 (Gemma 4), 512 (GLM), 1024 (Hy4) and 256 (Inkling 2, which clamps its GPU prefill to that size) for the +architectures with their own forward, and no chunk at all for DeepSeek, which prefills one token at a time. Where the +knobs apply, the baseline also uses short-prompt threshold 32, the physical core count and no drafts. The reported +score is relative to that, not to the first point of the search space. + +Context length and KV format are deliberately not searched. They are memory choices the user makes; a noisy speed +win must not silently double someone's KV cache. `--ctx` and `--kv` only set the conditions of the measurement. + +## Workloads and tasks + +`--pp` lists prompt depths (default `128,512,2048`); `--tg` sets decoded tokens (default 128). All depths of one task +are measured in a single child process. + +- `prose` (default): the built-in repeated paragraph, a stable machine-level baseline. +- `coding`: a built-in code snippet; real punctuation and identifiers change routing and draft acceptance. +- `user:PATH`: your own prompt file, for RAG documents, long system prompts, etc. + +Repeat `--task` to mix corpora: + +```sh +rustingstrata calibrate --model $M --task prose --task user:prompts.txt --pp 256,2048 +``` + +## Search strategy + +The search is deterministic for a given `--seed` and bounded by `--samples`: + +1. **Baseline** — current defaults, measured on the full workload matrix (not counted in the budget). It is also a + trial in the search, so a candidate that scores below it cannot win. If no candidate beats it, no calibration is + written and the defaults stay in force. A failed baseline warns and scores against a neutral `1x` reference; such a + run writes a file only when a point beats that reference. +2. **Coarse sweep** — up to `min(samples/3, 8)` points from a low-discrepancy (radical-inverse) sequence over the + joint knob space. Their scores only pick starting points; they are never compared with full-matrix scores and + cannot win. +3. **Multi-start coordinate descent** — each start is re-measured on the full matrix, then each knob is tried at + every other value and the best move kept. The walk stops after two rounds without improvement. `stop_reason` is + reset for every start, so all of them get a full descent. +4. **Final polish** — one more pass over the cheap knobs from the overall winner. + +A candidate that fails (OOM, timeout, missing JSON fields) is recorded with its error and never wins; it still counts +against the budget. Every stage, including the final polish, draws from `--samples`; the baseline alone is outside the +budget. `--reps N` repetitions happen inside one sample and do not consume extra samples. `--timeout SECS` caps each +sample. `--warmup N` adds an extra discarded run per sample; it is off by default because it loads the model a second +time. + +### Knobs + +| knob | values | applies to | +| --- | --- | --- | +| `chunk` | `--chunk-values`, default `256,512,1024,2048,4096` | main engine and Gemma 4, GLM, Hy4, Inkling 2 (capped at 256); DeepSeek has no chunk knob | +| `mtp` | `0,1,2,4` | main-engine models with a draft head, otherwise `0` only | +| `short` | 32 plus one threshold just above each `--pp` depth (default `32,129,513,2049`) | main engine only | + +Each `short` threshold flips exactly one prompt depth into the short-prompt path: a prompt uses token-at-a-time +prefill when it is shorter than the threshold. The old fixed `16/32/64/128` list was below every default workload +depth, so no candidate changed anything and the value written was noise. + +Inkling 2, Hy4, GLM and Gemma 4 read their chunk from the environment at prefill time, so `bench_sample` sets +`STRATA_DS_CHUNK`, `STRATA_GLM_CHUNK` and `STRATA_G4_CHUNK` to the candidate value. Their engines apply a calibrated +chunk the same way at load time. In `serve`, those variables are restored before a different model is loaded, so a +model without a calibration never inherits the previous model's chunk. DeepSeek prefills one token at a time and +reads no chunk: its calibration records no chunk, MTP count or short threshold. The main engine reads `chunk`, `mtp` +and `short` from the file in the usual way. + +Multi-GPU runs (pass `--device 0,1`) keep the engine's free-VRAM layer split; calibration does not measure or write a +layer split, and `--split` is ignored with a note. + +## Flags + +| flag | default | meaning | +| --- | --- | --- | +| `--samples N` | 24 | hard cap on benchmark samples | +| `--reps N` | 3 | repetitions per point (their mean is used) | +| `--warmup N` | 0 | extra discarded run before each sample | +| `--pp A,B,C` | `128,512,2048` | prompt depths | +| `--tg N` | 128 | decoded tokens | +| `--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 | +| `--ctx`, `--kv` | 4096, f16 | conditions of the measurement, not searched | + +`--model` also accepts a folder: every `.gguf` in it and its subfolders is calibrated 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 settings **per task**: which spec type and how many drafts are best for coding +versus prose on this model. + +```sh +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 +``` + +Knobs: `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), `mtp` (MTP count, main engine only). The search +stores indices into those lists; the JSON report and the child `bench` command both receive the actual values. The +baseline is today's spec defaults (`none`, 16 drafts, n-gram 12, mtp 0). + +The result is written under `spec` in the same calibration file, keyed by task, with decode rate and draft acceptance +percentage of the winner. A spec sweep **only adds that section**: engine knobs measured by a previous `calibrate` +run are left untouched. + +## The calibration file + +The file keeps the v1 keys the engines read (`chunk`, `mtp`, `short`, `ctx`, `gpu`, `bytes`, `measured`, `aux`), so +older binaries still read it. A stale v1 `split` is deliberately dropped: v2 does not measure a layer split and +nothing writes that key. v2 adds: + +```json +{ + "schema": 2, + "arch": "qwen35moe", + "chunk": 2048, "mtp": 2, "short": 32, + "ctx": 4096, + "measured": {"prefill_tok_s": 1057.0, "decode_tok_s": 26.7}, + "best": {"chunk": 2048, "mtp": 2, "short": 32}, + "search": {"samples_used": 24, "score": 1.234, "stop_reason": "budget", + "elapsed_ms": 123456, "seed": 1}, + "workloads": [{"pp": 128, "tg": 128, "task": "prose"}], + "spec": {"prose": {"spec_type": "ngram-mod", "draft_max": 8, "ngram_n": 6, + "acceptance_pct": 72.5}} +} +``` + +`ctx` records the context the measurement ran at; it is never a recommendation applied to later runs. There is no +`kv` or `threads` key from v2 — those remain the user's choice. `--out DIR` writes a separate +`strata--calib-report.json` with all trials, their knob points, measurements, errors and timings, useful for +auditing a surprising result or comparing two seeds. + +The filename encodes the backend that **actually opened** and the device order (`-vulkan`, `-dev0-1`), so a CUDA +to Vulkan fallback writes the file the runs will look for, and 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/MODELS.md b/docs/MODELS.md index 7fd1100..8da14a1 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -21,8 +21,9 @@ The engine picks the code path from `general.architecture` in the file. | [Hy4-flash](#hy4-flash-iq2_siq2_xxs-85-gb) | `hy_v4_flash` | own forward, matvecs and expert cache on CUDA or Vulkan, greedy only | | [Inkling 2 Mini](#inkling-2-mini-iq4_nl-176-gb) | `inkling2_loop`, `inkling2` | own forward, matvecs and expert cache on CUDA or Vulkan | -The models with their own forward open the GPU by themselves (no `--gpu` flag), have nothing to calibrate and load -from the chat page of one server like the others. Image input is in [VISION.md](VISION.md). +The models with their own forward open the GPU by themselves (no `--gpu` flag) and load from the chat page of one +server like the others. `rustingstrata calibrate` measures their prefill chunk too (DeepSeek has no chunk to tune); +they read it from the same calibration file at load time. Image input is in [VISION.md](VISION.md). ## Qwen models diff --git a/docs/USAGE.md b/docs/USAGE.md index 32e0375..f17ad13 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -112,8 +112,11 @@ 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, draft count and short-prompt threshold and later runs read them + from `~/.cache/rusting_strata/strata-[-backend][-dev…].json` unless flags override. The suffix uses the + backend that actually opened (so a CUDA to Vulkan fallback writes the Vulkan file). The models with their own + forward are calibrated too; see [CALIBRATION.md](CALIBRATION.md) for the budgeted search 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 @@ -136,9 +139,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`). @@ -239,19 +242,12 @@ first, which is not the order of `nvidia-smi`), on Vulkan too; the other Vulkan integrated ones. The load prints the card of every index (`cuda device 1: ...` or `vulkan device 1: ...`). The split by free VRAM does not know which card is faster or which sits on a slow PCIe link (x1 riser, x4 slot). -`rustingstrata calibrate --model M.gguf --device 0,1` measures it: it times prefill and decode with the split by free -VRAM, then with layers moved from one card to the other in steps of 15% of the layers, and follows the faster -direction for up to three rounds. A split that is more than 3% faster (prefill tok/s times decode tok/s; each split line prints this product as -a share of the best one so far) is written to the calibration file as layers per card, and later runs with the same -cards in the same `--device` order load with it. -A card with fewer layers keeps more of their experts in VRAM, so fewer are uploaded to it during prefill, and the other -card then keeps fewer of its own: the timings decide. The order of the cards is not searched: to compare, calibrate -`--device 1,0` too. Each order has its own file (`strata--dev0-1.json`, `-dev1-0.json`), and a run uses the -file of the order it is given. - -`--split 30,70` (or `STRATA_SPLIT=30,70`) sets the share of the layers per card by hand, in `--device` order, and -takes precedence over the calibrated split; `calibrate --split 30,70` measures chunk and drafts with that split and -stores it. The load prints each card's layers and its measured host-to-VRAM copy rate. AMD cards clock down in the gaps while the other card works; `echo high > +`--split 30,70` (or `STRATA_SPLIT=30,70`) sets the share of the layers per card by hand, in `--device` order; the load +prints each card's layers and its measured host-to-VRAM copy rate. `rustingstrata calibrate` does not measure or write +a split: it times the chunk, drafts and short-prompt threshold with the split the run will use, and `--split` is +accepted for symmetry but ignored with a note. To compare card orders, calibrate `--device 1,0` too: each order has +its own file (`strata--dev0-1.json`, `-dev1-0.json`), and a run uses the file of the order it is given. +AMD cards clock down in the gaps while the other card works; `echo high > /sys/class/drm/cardN/device/power_dpm_force_performance_level` (as root, per card) took a two-card split from 44 to 57 tok/s in one report. diff --git a/src/calibrate.rs b/src/calibrate.rs new file mode 100644 index 0000000..1d7bf32 --- /dev/null +++ b/src/calibrate.rs @@ -0,0 +1,490 @@ +//! 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 numbers. That makes the same search usable with every engine the binary supports. +//! +//! 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 baseline measured with the settings a user gets today, not the first point of the search space. + +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 avoid reloading on cheap changes. +#[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 of one workload measurement. Higher is better. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Measurement { + pub prefill_tok_s: f64, + pub decode_tok_s: f64, + #[serde(default)] + pub drafts_offered: usize, + #[serde(default)] + pub drafts_accepted: usize, +} + +impl Measurement { + pub fn valid(&self) -> bool { + [self.prefill_tok_s, self.decode_tok_s].iter().all(|v| v.is_finite() && *v > 0.0) + } +} + +/// Relative importance of prefill throughput and decode throughput. Each is divided by its own baseline, so the +/// units cancel. A weighted geometric mean (rather than an arithmetic one) cannot hide a regression in one signal +/// behind a large gain in the other. Time to first token is deliberately not a separate signal: for greedy decoding +/// it is the prefill time, so giving it a weight would just reweight prefill. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Objective { + pub prefill: f64, + pub decode: f64, +} + +impl Objective { + /// Balanced default: prompt handling and reply generation count equally. + pub fn balanced() -> Self { Self { prefill: 0.5, decode: 0.5 } } + fn normalized(&self) -> Self { + let sum = self.prefill + self.decode; + if sum <= 0.0 || !sum.is_finite() { return Self::balanced(); } + Self { prefill: self.prefill / sum, decode: self.decode / sum } + } + /// Score of one measurement relative to its baseline. + 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 o = self.normalized(); + pf.powf(o.prefill) * dec.powf(o.decode) + } +} + +/// Score of a full workload matrix: geometric mean over workloads, so each prompt depth counts equally. Every 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 workload matrix; it should apply the knobs, take its +/// own repetitions and return one measurement per workload. `baseline` has one measurement per workload, taken with +/// `baseline_knobs` (the settings a user gets without a calibration file). The baseline competes in the search: a +/// candidate slower than today's defaults must not be written as the winner. +pub fn search(space: &[KnobSpec], workloads: &[Workload], cfg: &SearchConfig, obj: &Objective, + baseline_knobs: &Knobs, 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, ..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(); + // The baseline is a real trial, measured outside the sample budget. Its ratios against itself are 1.0, so the + // search can never pick a slower point unless the baseline measurement itself failed. + trials.push(Trial { + knobs: baseline_knobs.clone(), + measurements: baseline.clone(), + score: aggregate_score(&baseline, &baselines, obj), + error: if baseline.iter().any(|m| m.valid()) { None } else { Some("baseline measurement failed".to_string()) }, + elapsed_ms: 0, + workloads: workloads.len(), + }); + 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() }) + }; + + // One bench child per distinct (knob point, workload set): repeats cost a full model load and consume budget + // without adding information. `seen` is shared by every stage, including all starts. + let mut seen: std::collections::HashSet<(String, usize)> = std::collections::HashSet::new(); + // The baseline was measured outside the budget: never spend a sample repeating it. + seen.insert((baseline_knobs.label(), workloads.len())); + let mut eval_unique = |knobs: &Knobs, subset: &[Workload]| -> Result> { + if !seen.insert((knobs.label(), subset.len())) { return Ok(None); } + evaluate(knobs, subset).map(Some) + }; + + // 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)); + if let Some(trial) = eval_unique(&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 converged_all = true; + for (cur, _seed_score) in seeds.into_iter() { + let mut stop_reason = "budget".to_string(); + // 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 { break } else if let Some(t) = eval_unique(&cur, workloads)? { + used += 1; + trials.push(t.clone()); + t + } else { + trials.iter().find(|t| t.workloads == workloads.len() && t.knobs == cur).cloned() + .unwrap_or_else(|| Trial { knobs: cur.clone(), measurements: vec![], score: 0.0, error: None, + elapsed_ms: 0, workloads: workloads.len() }) + }; + 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 || used >= cfg.samples { continue } + let mut candidate = cur_trial.knobs.clone(); + candidate.set(&s.name, v); + if let Some(t) = eval_unique(&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 || stop_reason == "converged" { break; } + } + if used >= cfg.samples { converged_all = false; break; } + if stop_reason != "converged" { converged_all = false; } + } + + // Stage C: one coordinate pass from the overall winner over the cheap knobs. + 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); + if let Some(t) = eval_unique(&candidate, workloads)? { + used += 1; + trials.push(t.clone()); + if t.error.is_none() && t.score > best.score { best = t; } + } + } + } + } + let stop_reason = if used >= cfg.samples || !converged_all { "budget" } else { "converged" }.to_string(); + 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", [256.0, 1024.0, 4096.0], false), + KnobSpec::new("mtp", [0.0, 1.0, 2.0], false)] + } + 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, ..Default::default() } } + fn baseline_knobs() -> Knobs { let mut k = Knobs::default(); k.set("chunk", 256.0); k.set("mtp", 0.0); k } + + #[test] + fn objective_is_a_geometric_mean_of_two_signals() { + let o = Objective::balanced(); + assert!((o.score(&base(), &base()) - 1.0).abs() < 1e-9); + let better = Measurement { prefill_tok_s: 200.0, decode_tok_s: 10.0, ..Default::default() }; + assert!((o.score(&better, &base()) - 1.0).abs() < 1e-9, "2x prefill and 0.5x decode cancel"); + let gain = Measurement { prefill_tok_s: 200.0, decode_tok_s: 40.0, ..Default::default() }; + assert!((o.score(&gain, &base()) - 2.0).abs() < 1e-9); + let mixed = Measurement { prefill_tok_s: 1000.0, decode_tok_s: 1.0, ..Default::default() }; + assert!(o.score(&mixed, &base()) < 1.0, "a big regression must not be hidden by one gain"); + } + + #[test] + fn low_discrepancy_is_deterministic_and_spread() { + assert_eq!(low_discrepancy(7, 3, 42), low_discrepancy(7, 3, 42)); + 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() { + 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(), &baseline_knobs(), vec![base(), base()], |k, _| { + calls += 1; + let boost = if k.i("chunk") == Some(1024) { 2.0 } else { 1.0 } * if k.i("mtp") == Some(1) { 1.5 } else { 1.0 }; + Ok(vec![Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.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(1024)); + assert_eq!(r.best.knobs.i("mtp"), Some(1)); + assert!(r.best.score > 1.0); + } + + #[test] + fn every_start_gets_a_full_descent_not_one_round() { + // A flat landscape never converges: each of the three starts must run several full rounds. With the old + // stop_reason leak, starts 2 and 3 got a single round after start 1 converged. + // A bigger space gives each start real room to move: scores improve with both knob values, so no start + // converges immediately. (Measured points are memoized, so call-count-based landscapes are not useful.) + let big: Vec = vec![ + KnobSpec::new("chunk", (1..=8).map(|i| i as f64 * 100.0), false), + KnobSpec::new("mtp", (0..8).map(|i| i as f64), false), + ]; + let cfg = SearchConfig { samples: 40, coarse: 3, starts: 3, patience: 2, seed: 9 }; + let r = search(&big, &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |k, _| { + let boost = 1.0 + k.i("chunk").unwrap() as f64 / 1000.0 + k.i("mtp").unwrap() as f64 / 100.0; + Ok(vec![Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ..Default::default() }]) + }).unwrap(); + assert!(r.samples_used > 25, "each start should get several rounds, not one: {}", r.samples_used); + } + + #[test] + fn short_prompt_only_gains_cannot_win_the_search() { + let cfg = SearchConfig { samples: 14, coarse: 6, starts: 3, patience: 1, seed: 3 }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |k, subset| { + let mtp = k.i("mtp").unwrap(); + Ok(subset.iter().map(|w| { + let boost = if mtp == 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, ..Default::default() } + }).collect()) + }).unwrap(); + assert_ne!(r.best.knobs.i("mtp"), Some(1), "the short-prompt-only gain must not win"); + assert_eq!(r.best.measurements.len(), 2); + } + + #[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(), &baseline_knobs(), vec![base(), base()], |k, _| { + if k.i("mtp") == Some(1) { anyhow::bail!("out of memory") } + Ok(vec![base(), base()]) + }).unwrap(); + assert_ne!(r.best.knobs.i("mtp"), Some(1)); + assert!(r.trials.iter().any(|t| t.error.as_deref().is_some_and(|e| e.contains("out of memory")))); + } + + #[test] + fn an_empty_baseline_still_allows_the_search_to_run() { + let cfg = SearchConfig { samples: 10, coarse: 3, starts: 1, patience: 1, seed: 6 }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![], |_, _| { + Ok(vec![Measurement { prefill_tok_s: 100.0, decode_tok_s: 20.0, ..Default::default() }]) + }).unwrap(); + assert!(r.best.error.is_none()); + assert!(r.samples_used > 0); + } + + #[test] + fn the_same_knob_point_is_never_measured_twice() { + let cfg = SearchConfig { samples: 60, coarse: 6, starts: 3, patience: 2, seed: 7 }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |k, _| { + let boost = 1.0 + k.i("chunk").unwrap() as f64 / 10000.0 + k.i("mtp").unwrap() as f64 / 10.0; + Ok(vec![Measurement { prefill_tok_s: 100.0 * boost, decode_tok_s: 20.0 * boost, ..Default::default() }]) + }).unwrap(); + let keys: std::collections::HashSet<_> = r.trials.iter() + .map(|t| (t.knobs.label(), t.workloads)).collect(); + assert_eq!(keys.len(), r.trials.len(), "a repeated sample never adds information"); + assert!(r.trials.len() > cfg.coarse, "the search should still do real refinement"); + } + + #[test] + fn every_start_converging_is_recorded_as_converged() { + // A flat landscape: no move ever improves, so all starts stop on patience before the budget is used. + let cfg = SearchConfig { samples: 60, coarse: 3, starts: 2, patience: 2, seed: 4 }; + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &baseline_knobs(), vec![base(), base()], |_, _| { + Ok(vec![base(), base()]) + }).unwrap(); + assert!(r.samples_used < cfg.samples, "should stop early: {}", r.samples_used); + assert_eq!(r.stop_reason, "converged"); + } + + #[test] + fn a_slower_candidate_can_never_beat_the_baseline() { + let cfg = SearchConfig { samples: 20, coarse: 6, starts: 3, patience: 2, seed: 11 }; + let base_knobs = baseline_knobs(); + let r = search(&space(), &workloads(), &cfg, &Objective::balanced(), &base_knobs, + vec![base(), base()], |_, _| { + Ok(vec![Measurement { prefill_tok_s: 50.0, decode_tok_s: 10.0, ..Default::default() }]) + }).unwrap(); + assert_eq!(r.best.knobs, base_knobs, "a slower point must not be written"); + assert!((r.best.score - 1.0).abs() < 1e-9, "the baseline wins at score 1.0"); + assert!(r.trials.iter().any(|t| t.knobs == base_knobs && t.score == 1.0)); + } + + #[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/gemma4/mod.rs b/src/gemma4/mod.rs index 25b9bd7..d3a7458 100644 --- a/src/gemma4/mod.rs +++ b/src/gemma4/mod.rs @@ -101,7 +101,7 @@ fn strip_thinking(text: &str) -> String { /// GPU on, the weights in 90% of the free VRAM (a fixed 11 GB overcommitted a 12 GB card that other programs /// use, and left a larger card half empty). -fn gpu_defaults() { +pub fn gpu_defaults() { if std::env::var_os("STRATA_G4_CPU").is_some() { return; } for (k, v) in [("STRATA_DS_GPU", "1"), ("STRATA_DS_GPU_FRACTION", "0.9"), ("STRATA_DS_NOEVICT", "1")] { if std::env::var_os(k).is_none() { unsafe { std::env::set_var(k, v) } } diff --git a/src/lib.rs b/src/lib.rs index 2af3bcb..e654b99 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 4c20e0a..498d530 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}; @@ -351,6 +355,19 @@ impl Runner<'_> { } } +/// Chunk variables an `own_calib` call set, with the value each had before it. `serve` loads several models in one +/// process; without restoring them, a model with no calibration runs with the previous model's chunk. +static CALIB_ENV: std::sync::Mutex)>> = std::sync::Mutex::new(Vec::new()); + +/// Undo the chunk variables set by the previous `own_calib` call, before a new model applies its own calibration. +fn restore_calib_env() { + let saved = std::mem::take(&mut *CALIB_ENV.lock().unwrap_or_else(|e| e.into_inner())); + for (key, old) in saved { + // SAFETY: called before a model is loaded, before any thread of that model reads these variables. + unsafe { match old { Some(v) => std::env::set_var(key, v), None => std::env::remove_var(key) } } + } +} + impl Engine { /// Hand `--backend`, `--device`, and `--kv` to the DeepSeek, GLM, Gemma 4 and Inkling 2 paths. fn ds_env(&self) { @@ -361,6 +378,35 @@ 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 through the environment those engines actually read. Context and threads are not + /// searched (they are memory choices), so this never touches the global CTX: doing that once made an explicit + /// --ctx look implicit to the main engine's runner. + fn own_calib(&self, model: &Path) { + restore_calib_env(); + let Ok(g) = Gguf::open(model) else { return }; + let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or(""); + if !rusting_strata::config::OWN_ARCHS.contains(&arch) { return; } + // Like `runner`, look up the file under the backend that really opened: with no --backend, CUDA may fall + // back to Vulkan, and `calibrate` writes the file under that name. + let Some(&d) = self.device.first() else { return }; + let Ok(b) = backend::open(self.backend.as_deref(), d) else { return }; + let path = calibration_path(model, b.name(), &self.device); + let Ok(bytes) = std::fs::read(&path) else { return }; + let Ok(v) = serde_json::from_slice::(&bytes) else { return }; + let gpu = b.device(); + 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; } + // GLM reads its own variable, Gemma 4 its own, the others read STRATA_DS_CHUNK. Explicit values win. + if let Some(n) = v["chunk"].as_u64() { + let mut saved = CALIB_ENV.lock().unwrap_or_else(|e| e.into_inner()); + for (k, value) in chunk_env_updates(n as usize, |k| std::env::var_os(k).is_some()) { + saved.push((k, std::env::var_os(k))); + unsafe { std::env::set_var(k, value); } + } + } + } + /// 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`, @@ -410,7 +456,7 @@ impl Engine { v = serde_json::Value::Null; } 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()); } + 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 {}` (once per model; `--samples` bounds the run)", model.display()); } let get = |k: &str| v[k].as_u64().map(|x| x as usize); if let Some(dp) = &self.draft_model { anyhow::ensure!(dp.exists(), "draft model path does not exist: {}", dp.display()); @@ -720,28 +766,22 @@ fn calibrated_split(v: &serde_json::Value, devices: &[usize], gpus: &[String]) - (l.len() == devices.len()).then_some(l) } -/// The splits one move away from `cur` (layers per device): `step` layers moved between two neighbouring devices, -/// each device keeping at least one layer. -fn split_moves(cur: &[usize], step: usize) -> Vec> { - let mut v = vec![]; - for i in 0..cur.len().saturating_sub(1) { - for (a, b) in [(i, i + 1), (i + 1, i)] { - if cur[a] > step { - let mut c = cur.to_vec(); - (c[a], c[b]) = (c[a] - step, c[b] + step); - v.push(c); - } - } - } - v -} - /// Whether calibration file `v` may be used on `gpu` (`Backend::device`). A file names the GPU it was measured on; /// one without a name (written before that was recorded, or the driver gave none) is accepted. fn calibration_fits(v: &serde_json::Value, gpu: &str) -> bool { v["gpu"].as_str().is_none_or(|g| g.is_empty() || gpu.is_empty() || g == gpu) } +/// Values a calibrated chunk may write to the environment. An explicit value set by the user must win, so the +/// caller skips names that are already present. +fn chunk_env_updates(n: usize, present: impl Fn(&str) -> bool) -> Vec<(&'static str, String)> { + if !(1..=(1 << 20)).contains(&n) { return vec![]; } + ["STRATA_DS_CHUNK", "STRATA_GLM_CHUNK", "STRATA_G4_CHUNK"].into_iter() + .filter(|k| !present(k)) + .map(|k| (k, n.to_string())) + .collect() +} + impl Engine { pub fn lora_specs(&self) -> Vec<(String, f32)> { self.lora.iter().map(|s| { @@ -845,6 +885,7 @@ 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}, + }); 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, MTP drafts and the short-prompt threshold on this machine, + /// 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,44 @@ 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, + /// Extra discarded run before each sample (off by default: it loads the model a second time). + #[arg(long, default_value_t = 0)] + 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, + /// 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 +1140,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 +1277,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 +1410,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) { @@ -1346,38 +1482,48 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { 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, 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 calibrate; measurements use the free-VRAM split"); } + + 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; + s.ctx = 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)); + ensure_spec_defaults(&mut s); + 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; + settings.chunk_values = chunk_values.unwrap_or_else(|| vec![256, 512, 1024, 2048, 4096]); + settings.ctx = ctx; + 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; + 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(", ")); } @@ -1443,6 +1589,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); @@ -1968,6 +2115,54 @@ 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<()> { + // Use the engine's own defaults so the bench measures the same configuration as chat and generate. + rusting_strata::gemma4::gpu_defaults(); + 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, + // The chunk bench_sample applied through STRATA_G4_CHUNK, not the old token-at-a-time placeholder. + chunk: gemma_bench_chunk(std::env::var("STRATA_G4_CHUNK").ok().as_deref()), + kv: &engine.kv, + mtp: 0, + tg, + reps, + }; + write_bench_json(json_out, &meta, &results, expert.as_ref()) +} + +/// The Gemma 4 prefill chunk used by this process; 256 is the engine's default. +fn gemma_bench_chunk(v: Option<&str>) -> usize { + v.and_then(|s| s.parse().ok()).unwrap_or(256) +} + /// `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(); @@ -2076,145 +2271,597 @@ fn bench_glm(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_ write_bench_json(json_out, &meta, &results, expert.as_ref()) } -/// Best (lowest) of three timings of `f`, in seconds. -fn best(f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result { - let mut b = f64::INFINITY; - for _ in 0..3 { - let t = Instant::now(); - f()?; - b = b.min(t.elapsed().as_secs_f64()); +/// 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, + 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, + 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![], + } } - 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<()> { - backend::check_devices(kind, device)?; // before the GGUF is read: a bad --device fails here, not after the load - let g = Gguf::open(model)?; - let aux_g = open_mtp_gguf(aux)?; - let m = Model::load_with_aux(&g, aux_g.as_ref(), &[])?; - // Most drafts per step to measure: a DFlash block, else as many as the runs default to. - let kload = m.cfg.dflash.as_ref().map_or(if m.draft_model.is_some() { 4 } else { 3 }, |d| d.block_size.saturating_sub(1).max(1)); - let tok = Tokenizer::from_gguf(&g)?; - let n_pf = 4096.min(ctx.saturating_sub(256)); - anyhow::ensure!(n_pf >= 512, "--ctx too small to calibrate"); - let pf = prose(&tok, n_pf)?; - let load = |chunk: usize, split: Option<&[f64]>| -> anyhow::Result { - let bk = backend::open_all(kind, device)?; - let mut gm = GpuModel::load_split_margins(&m, bk, ctx, chunk, margin, split, kload, 1).context(LOAD_HINT)?; - gm.adapt_every = 0; // fixed placement: steadier timings - Ok(gm) - }; +fn calib_work_dir() -> anyhow::Result { + let d = rusting_strata::expert_cache::cache_dir().join("calibrate"); + std::fs::create_dir_all(&d)?; + Ok(d) +} - let mut chunk = (0, 0.0); - for c in [512, 1024, 2048, 4096].into_iter().filter(|&c| c <= ctx) { - // A larger chunk's prefill scratch may not fit beside a long --ctx: keep the chunks measured so far. - let mut gm = match load(c, split.as_deref()) { Ok(gm) => gm, Err(e) if chunk.0 > 0 => { say!("chunk {c:5}: {e:#}"); break } Err(e) => return Err(e) }; - let t = best(&mut || { gm.reset()?; gm.prefill(&pf).map(drop) })?; - let tps = n_pf as f64 / t; - say!("chunk {c:5}: prefill {n_pf} tok {tps:.0} tok/s"); - if tps > chunk.1 { chunk = (c, tps); } - } - - let dec = tok.encode("Write a long story about a dragon.")?; - // Several devices and no split given by hand: measure other layer splits and keep the fastest. The split by free - // VRAM does not know a card's speed or its PCIe link; the timings do. A card with fewer layers keeps more of - // their experts in VRAM (fewer uploads over its link in prefill), and the other cards then keep fewer. - if device.len() > 1 && split.is_none() { - // Prefill of the long prompt and decode after the short one, in tok/s, with the layers per device. - let measure = |s: Option<&[f64]>| -> anyhow::Result<(Vec, f64, f64)> { - let mut gm = load(chunk.0, s)?; - gm.k = 1; - let layers = gm.part_layers(); - let mut r = Runner::Gpu(Box::new(gm)); - let tp = best(&mut || { r.reset()?; r.prefill(&pf).map(drop) })?; - let mut toks = 0; - let td = best(&mut || { - r.reset()?; - let l = r.prefill(&dec)?; - toks = decode(&mut r, &tok, false, &mut Sampler::greedy(), l, 64, None, &mut |_| Ok(false))?.0.len(); - Ok(()) - })?; - Ok((layers, n_pf as f64 / tp, toks as f64 / td)) - }; - let (base, mut bp, mut bd) = measure(None)?; - say!("split {base:?} (by free VRAM): prefill {bp:.0} tok/s, decode {bd:.1} tok/s"); - // ponytail: a fixed step of 15% of the layers and three rounds; a finer search if a report shows the best - // split lies between two steps. - let step = (m.cfg.n_layer * 3 / 20).max(1); - let (mut cur, mut seen) = (base.clone(), vec![base.clone()]); - for _ in 0..3 { - let mut better = None; - for c in split_moves(&cur, step) { - if seen.contains(&c) { continue; } - seen.push(c.clone()); - match measure(Some(&c.iter().map(|&x| x as f64).collect::>())) { - Ok((_, p, d)) => { - say!("split {c:?}: prefill {p:.0} tok/s, decode {d:.1} tok/s, prefill x decode {:.3} of the best so far", p * d / (bp * bd)); - // Prefill and decode count the same; 3% over the best so far, above the run-to-run spread. - if p * d > 1.03 * bp * bd { (bp, bd, better) = (p, d, Some(c)); } - } - Err(e) => say!("split {c:?}: {e:#}"), +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, +} + +struct CappedOutput { + success: bool, + stdout: String, + stderr: String, +} + +/// Run a child with a time limit. Output goes to files rather than pipes: polling a piped child without draining +/// it can deadlock once the pipe fills, and a bench failure prints a stack trace and a usage block. +fn run_capped(mut c: Command, secs: u64, dir: &Path, id: usize) -> anyhow::Result { + let out = dir.join(format!("calib-{id}-out.txt")); + let err = dir.join(format!("calib-{id}-err.txt")); + c.stdout(Stdio::from(std::fs::File::create(&out)?)).stderr(Stdio::from(std::fs::File::create(&err)?)); + let mut child = c.spawn()?; + if secs > 0 { + 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 + let _ = std::fs::remove_file(&out); + let _ = std::fs::remove_file(&err); + anyhow::bail!("sample timed out after {secs}s"); + } + std::thread::sleep(Duration::from_millis(100)); + } + } + let status = child.wait()?; + let stdout = std::fs::read_to_string(&out).unwrap_or_default(); + let stderr = std::fs::read_to_string(&err).unwrap_or_default(); + let _ = std::fs::remove_file(&out); + let _ = std::fs::remove_file(&err); + Ok(CappedOutput { success: status.success(), stdout, stderr }) +} + +/// 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); } } - match better { Some(c) => cur = c, None => break } - } - if cur != base { - chunk.1 = bp; - split = Some(cur.iter().map(|&x| x as f64).collect()); - } - } - - let mut gm = load(chunk.0, split.as_deref())?; - let mut short = usize::MAX; - for n in [8, 16, 32, 64, 128] { - let p = &pf[..n]; - gm.short = usize::MAX; - let ts = best(&mut || { gm.reset()?; gm.prefill(p).map(drop) })?; - gm.short = 0; - let tb = best(&mut || { gm.reset()?; gm.prefill(p).map(drop) })?; - say!("prompt {n:4}: steps {:.1} ms, batched {:.1} ms", ts * 1e3, tb * 1e3); - if tb < ts && short == usize::MAX { short = n; } - } - if short == usize::MAX { short = 256; } - - let drafts = m.cfg.n_nextn > 0 || m.cfg.dflash.is_some() || m.cfg.eagle3.is_some() || m.draft_model.is_some(); - let kmax = if drafts { gm.k } else { 0 }; - let mut r = Runner::Gpu(Box::new(gm)); - let mut mtp = (0, 0.0); - for k in (0..=kmax).filter(|&k| k <= 4 || k % 2 == 0 || k == kmax) { - if let Runner::Gpu(g) = &mut r { g.k = k.max(1); } - let mut toks = 0; - let t = best(&mut || { - r.reset()?; - let l = r.prefill(&dec)?; - toks = decode(&mut r, &tok, k > 0, &mut Sampler::greedy(), l, 128, None, &mut |_| Ok(false))?.0.len(); - Ok(()) - })?; - // `best` times prefill too; it is the same for every k, so the ranking holds. - let tps = toks as f64 / t; - say!("mtp {k}: decode {toks} tok {tps:.1} tok/s"); - if tps > mtp.1 { mtp = (k, tps); } - } - - let Runner::Gpu(g) = &r else { unreachable!() }; - let path = calibration_path(model, g.gpu.name(), device); - std::fs::create_dir_all(path.parent().unwrap())?; - // The file size tells another file of the same name (another repo or quant source) from this one. - let mut v = json!({"chunk": chunk.0, "mtp": mtp.0, "short": short, "ctx": ctx, "gpu": g.gpu.device(), "bytes": std::fs::metadata(model)?.len(), - "measured": {"prefill_tok_s": chunk.1.round(), "decode_tok_s": (mtp.1 * 10.0).round() / 10.0}}); - if let Some(a) = aux.and_then(|a| a.file_name()) { v["aux"] = a.to_string_lossy().into(); } - // Only a split that was measured as faster, or given by hand: without one, later runs split by the free VRAM - // they find. - if split.is_some() { - v["split"] = json!({"devices": device, "gpus": g.parts().map(|p| p.gpu.device()).collect::>(), "layers": g.part_layers()}); + } + } + (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 chunk = knobs.i("chunk").unwrap_or(4096); + let short = knobs.i("short").unwrap_or(32); + // In a spec sweep the mtp knob holds an index into --mtp; in the main search it is the value itself. + let mtp = if s.mtp_values.is_empty() { knobs.i("mtp").unwrap_or(0) } + else { s.mtp_values[knobs.i("mtp").unwrap_or(0).min(s.mtp_values.len() - 1)] }; + + 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(s.ctx.to_string()) + .arg("--kv").arg(&s.kv) + .arg("--chunk").arg(chunk.to_string()) + .arg("--mtp").arg(mtp.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 read their chunk from the environment at prefill time. + c.env("STRATA_DS_CHUNK", chunk.to_string()); + c.env("STRATA_GLM_CHUNK", chunk.to_string()); + c.env("STRATA_G4_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, &dir, id)?; } + let out = run_capped(build(s.reps), s.timeout, &dir, id + 1)?; + if !out.success { + let _ = std::fs::remove_file(&json); + anyhow::bail!("bench failed: {}{}", out.stdout, 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, &out.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 rate = |key: &str| -> anyhow::Result { + r[key]["mean"].as_f64().with_context(|| format!("bench JSON pp {pp} has no {key}.mean")) + }; + ms.push(Measurement { + prefill_tok_s: rate("prefill_tok_s")?, + decode_tok_s: rate("decode_tok_s")?, + 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()) + } +} + +/// A failed baseline (typically OOM at the default chunk) must not abort the run: the search can still find a +/// working point. Returning no baseline makes `search` use its neutral fallback for scoring. +fn baseline_samples(r: anyhow::Result>) -> (Vec, bool) { + match r { Ok(v) => (v, true), Err(_) => (vec![], false) } +} + +/// Whether the model has a draft head: an MTP head in the file, a DFlash/EAGLE3 head, or an auxiliary draft. +fn model_has_mtp(g: &Gguf, aux: bool) -> bool { + if aux { return true; } + let arch = g.get("general.architecture").ok().and_then(|v| v.as_str()).unwrap_or(""); + let nextn = g.get(&format!("{arch}.nextn_predict_layers")).ok().and_then(|v| v.as_u64()).unwrap_or(0); + nextn > 0 || g.meta.keys().any(|k| k.starts_with("dflash.") || k.starts_with("eagle3.")) +} + +/// The chunk a user gets without a calibration file. `None`: the engine prefills one token at a time and reads no +/// chunk at all, so there is no chunk to search and none to write. +fn arch_default_chunk(arch: &str) -> Option { + if arch == "gemma4" { Some(256) } + else if arch == "glm5-next" { Some(512) } + else if arch == rusting_strata::hy4::ARCH { Some(1024) } + else if rusting_strata::inkling2::is_arch(arch) { Some(256) } // its GPU prefill clamps to 256 + else if arch == "deepseek41" { None } + else { Some(4096) } +} + +/// The search space. Context and KV format are deliberately absent: they are memory choices the user makes, not +/// speed knobs to be silently changed by a calibration. An own-arch model only has its chunk (read from the +/// environment at prefill time); main-engine models also have MTP drafts and the short-prompt threshold. +fn build_space(arch: &str, s: &CalibSettings, has_mtp: bool) -> Vec { + let own = rusting_strata::config::OWN_ARCHS.contains(&arch); + let mut space = Vec::new(); + if let Some(default_chunk) = arch_default_chunk(arch) { + // A chunk larger than the context cannot be used: drop it instead of spending samples on guaranteed failures. + let mut chunks: Vec = s.chunk_values.iter().map(|n| *n as f64).filter(|&c| c <= s.ctx as f64).collect(); + // Inkling 2 clamps its GPU chunk to 256: larger values measure the same point under another label. + if rusting_strata::inkling2::is_arch(arch) { chunks.retain(|&c| c <= 256.0); } + // The engine's own default must be in the space; otherwise the baseline would be a point nobody searches. + if default_chunk <= s.ctx && !chunks.contains(&(default_chunk as f64)) { chunks.push(default_chunk as f64); } + if chunks.is_empty() { chunks.push(s.ctx.min(default_chunk) as f64); } + chunks.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + space.push(KnobSpec::new("chunk", chunks, false)); + } + if !own { + let mtp: Vec = if has_mtp { vec![0.0, 1.0, 2.0, 4.0] } else { vec![0.0] }; + // `short` skips chunked prefill for prompts shorter than the threshold. The old 16/32/64/128 candidates + // never crossed a workload depth (128/512/2048), so every candidate measured the same timings. One + // threshold just above each --pp depth flips exactly that depth into the short path; 32 is the default. + let mut short: Vec = vec![32.0]; + short.extend(s.pp.iter().map(|&pp| pp.saturating_add(1) as f64)); + short.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + short.dedup(); + debug_assert!(short.contains(&32.0)); + space.push(KnobSpec::new("mtp", mtp, false)); + space.push(KnobSpec::new("short", short, false)); + } + space +} + +/// A prompt plus its reply must fit the context the measurement will run at; the old calibrate checked this and the +/// diagnostic is much more useful than a run of failed samples ending in "no successful measurement". +fn check_workload_ctx(s: &CalibSettings) -> anyhow::Result<()> { + for &pp in &s.pp { + anyhow::ensure!(pp + s.tg <= s.ctx, "--pp {pp} + --tg {} exceeds --ctx {}; raise --ctx or shorten the workload", s.tg, s.ctx); + } + Ok(()) +} + +/// The baseline must be what a user runs today without a calibration file: the engine's own chunk (4096 for the +/// main engine, 256/512/1024 for Gemma 4/GLM/Hy4, 256 for Inkling 2, none for DeepSeek), short 32, the physical +/// core count (left to the engine's own default), and no drafts. Not the first point of the search space. +fn baseline_knobs(space: &[KnobSpec], arch: &str) -> Knobs { + let mut k = Knobs::default(); + let default_chunk = arch_default_chunk(arch).unwrap_or(4096) as f64; + for s in space { + let v = match s.name.as_str() { + "chunk" => default_chunk, + "short" => 32.0, + "mtp" => 0.0, + _ => s.values.first().copied().unwrap_or(0.0), + }; + k.set(&s.name, if s.values.contains(&v) { v } else { s.values[0] }); + } + k +} + +/// The backend a run will look up: the one the bench child really opened, not the `--backend` request. Without a +/// request CUDA falls back to Vulkan on some machines; writing under "cuda" would make every run miss the file. +/// The request is only a fallback when nothing was measured. +fn calib_backend_name(s: &CalibSettings, measured: &RefCell) -> String { + let real = measured.borrow().clone(); + if real.is_empty() { s.backend.clone().unwrap_or_else(|| "cuda".into()) } else { real } +} + +/// The physical device the search measured on, for the v1 `gpu` compatibility check. +fn calib_gpu_name(s: &CalibSettings, backend_name: &str) -> String { + s.device.first().and_then(|&d| backend::open(Some(backend_name), 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(()) +} + +/// The v2 search does not measure a layer split, so a stale v1 `split` must not survive into the file it rewrites. +fn drop_split(v: &mut serde_json::Value) { + if let Some(o) = v.as_object_mut() { o.remove("split"); } +} + +/// An engine with no tunable knobs (DeepSeek reads no chunk) still gets a file: later runs stop warning and a later +/// `calibrate spec` has somewhere to put its result. Only identity and measured rates are recorded; a stale chunk +/// left by an older file of this name must not survive. +fn write_knobless_calibration(s: &CalibSettings, baseline: &[Measurement], 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(); + drop_split(&mut v); + let first = baseline.iter().find(|m| m.valid()).cloned().unwrap_or_default(); + v["schema"] = json!(2); + v["arch"] = json!(arch); + 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), + }); + v["workloads"] = serde_json::to_value(workloads)?; + if let Some(o) = v.as_object_mut() { for k in ["chunk", "mtp", "short", "best", "search"] { o.remove(k); } } + std::fs::write(&path, serde_json::to_string_pretty(&v)?)?; + Ok(path) +} + +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(); + drop_split(&mut v); + let best = &result.best; + let first = best.measurements.first().cloned().unwrap_or_default(); + 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["ctx"] = json!(s.ctx); // the context the measurement ran at; never a recommendation to apply later + 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), + }); + 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, + }); + 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)?)?; - println!("{v}\nwritten to {}", path.display()); + 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<()> { + backend::check_devices(s.backend.as_deref(), &s.device)?; // before the GGUF is read: a bad --device fails here + check_workload_ctx(s)?; + 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 has_mtp = model_has_mtp(&g, s.aux.is_some()); + let space = build_space(&arch, s, has_mtp); + 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, scoring prefill and decode equally", workloads.len(), s.samples); + 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(","))).collect::>().join(" ")); + say!("baseline (current defaults): {}", baseline_knobs(&space, &arch).label()); + 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 = baseline_knobs(&space, &arch); + say!("baseline (current defaults): {}", base_knobs.label()); + let (baseline, ok) = baseline_samples(measure(&base_knobs, &workloads)); + if !ok { say!("warning: baseline failed (e.g. OOM at the default chunk); searching from a neutral reference"); } + let backend_name = calib_backend_name(s, &backend); + let gpu = calib_gpu_name(s, &backend_name); + if space.is_empty() { + let path = write_knobless_calibration(s, &baseline, &workloads, &arch, &backend_name, &gpu)?; + say!("{arch}: this engine reads no chunk, MTP count or short threshold; nothing to tune"); + say!("written to {}", path.display()); + return Ok(()); + } + 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, &Objective::balanced(), &base_knobs, baseline, &mut measure)?; + anyhow::ensure!(result.best.error.is_none(), "no successful measurement; calibration not written"); + // The baseline competes at score 1.0, so this only happens when the baseline measurement itself failed. Never + // write a setting that cannot be shown to beat the defaults. + if result.best.score < 1.0 { + say!("best score {:.3} is below today's defaults; keeping the defaults and not writing a calibration", result.best.score); + return Ok(()); + } + 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, &gpu)?; + 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 baseline can only be the current defaults if those defaults are in the candidate lists. +fn ensure_spec_defaults(s: &mut CalibSettings) { + if !s.spec_types.iter().any(|t| t == "none") { s.spec_types.push("none".into()); } + if !s.draft_max.contains(&16) { s.draft_max.push(16); } + if !s.ngram_n.contains(&12) { s.ngram_n.push(12); } + if !s.mtp_values.contains(&0) { s.mtp_values.push(0); } +} + +/// The spec settings a user gets without a calibration file, expressed as indices into the --lists. +fn spec_baseline(s: &CalibSettings) -> Knobs { + let mut k = Knobs::default(); + k.set("spec_type", s.spec_types.iter().position(|t| t == "none").unwrap_or(0) as f64); + k.set("draft_max", s.draft_max.iter().position(|&n| n == 16).unwrap_or(0) as f64); + k.set("ngram_n", s.ngram_n.iter().position(|&n| n == 12).unwrap_or(0) as f64); + k.set("mtp", s.mtp_values.iter().position(|&n| n == 0).unwrap_or(0) as f64); + k +} + +/// 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<()> { + backend::check_devices(s.backend.as_deref(), &s.device)?; + check_workload_ctx(s)?; + 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 base = spec_baseline(s); + let (baseline, ok) = baseline_samples(measure(&base, &workloads)); + if !ok { say!("warning: baseline failed; searching from a neutral reference"); } + say!("baseline (current defaults): {}", base.label()); + 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, &Objective::balanced(), &base, baseline, &mut measure)?; + anyhow::ensure!(result.best.error.is_none(), "no successful spec measurement; calibration not written"); + if result.best.score < 1.0 { + say!("best spec score {:.3} is below today's defaults; keeping the defaults and not writing a spec section", result.best.score); + return Ok(()); + } + 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), + "acceptance_pct": share, + })); + } + let backend_name = calib_backend_name(s, &backend); + let path = write_spec_calibration(s, &result, &arch, &backend_name, &calib_gpu_name(s, &backend_name), &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.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) +} + + /// Which tokens end a DRY match: those whose text has a newline, colon, double quote or asterisk (llama.cpp's /// default breakers). Built once per model, as decoding the whole vocabulary takes a moment. fn dry_breakers(tok: &Tokenizer, model: &str) -> std::sync::Arc> { @@ -2878,6 +3525,7 @@ fn serve_model(model: &Path, mut engine: Engine, s: &Serving, w: &mut Option, _>(anyhow::anyhow!("out of memory"))); + assert!(!ok); + assert!(ms.is_empty()); + } + + #[test] + fn spec_defaults_are_added_when_the_lists_omit_them() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.spec_types = vec!["ngram-simple".into()]; + s.draft_max = vec![4, 8]; + s.ngram_n = vec![3, 6]; + s.mtp_values = vec![2, 0]; + ensure_spec_defaults(&mut s); + assert!(s.spec_types.contains(&"none".to_string())); + assert!(s.draft_max.contains(&16)); + assert!(s.ngram_n.contains(&12)); + let b = spec_baseline(&s); + // The mtp knob is an index: index 1 is the value 0, not the value 1. + assert_eq!(b.i("mtp"), Some(1)); + assert_eq!(s.mtp_values[b.i("mtp").unwrap()], 0); + } + + #[test] + fn the_calibration_file_is_named_like_the_reader_looks_for_it() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + let measured = RefCell::new(String::new()); + assert_eq!(calib_backend_name(&s, &measured), "cuda"); + // CUDA requested but Vulkan really opened: runs look for the Vulkan file, so that is where we write. + *measured.borrow_mut() = "vulkan".into(); + assert_eq!(calib_backend_name(&s, &measured), "vulkan"); + s.backend = Some("cuda".into()); + assert_eq!(calib_backend_name(&s, &measured), "vulkan"); + } + + #[test] + fn gemma_bench_reports_the_chunk_it_actually_used() { + assert_eq!(gemma_bench_chunk(Some("512")), 512); + assert_eq!(gemma_bench_chunk(Some("nonsense")), 256); + assert_eq!(gemma_bench_chunk(None), 256); + } + + #[test] + fn a_new_calibration_clears_the_stale_v1_split() { + let mut v = serde_json::json!({"chunk": 4096, "split": {"devices": [0, 1], "layers": [12, 28]}, "gpu": "RTX"}); + drop_split(&mut v); + assert!(v.get("split").is_none()); + assert_eq!(v["chunk"], 4096); + assert_eq!(v["gpu"], "RTX"); + } + + #[test] + fn explicit_chunk_environment_variables_are_not_overwritten() { + let all = chunk_env_updates(512, |_| false); + assert_eq!(all.iter().map(|(k, _)| *k).collect::>(), + vec!["STRATA_DS_CHUNK", "STRATA_GLM_CHUNK", "STRATA_G4_CHUNK"]); + assert!(all.iter().all(|(_, v)| v == "512")); + let kept = chunk_env_updates(512, |k| k == "STRATA_DS_CHUNK"); + assert_eq!(kept.iter().map(|(k, _)| *k).collect::>(), + vec!["STRATA_GLM_CHUNK", "STRATA_G4_CHUNK"]); + assert!(chunk_env_updates(512, |_| true).is_empty()); + } + + #[test] + fn calibration_chunk_environment_is_restored_for_the_next_model() { + const KEY: &str = "STRATA_TEST_CALIB_RESTORE"; + let original = std::env::var_os(KEY); + unsafe { std::env::remove_var(KEY) } + CALIB_ENV.lock().unwrap().push((KEY, original.clone())); + unsafe { std::env::set_var(KEY, "256") } + assert_eq!(std::env::var_os(KEY).as_deref(), Some(std::ffi::OsStr::new("256"))); + restore_calib_env(); + assert_eq!(std::env::var_os(KEY), original, "the next model must not inherit this chunk"); + } + + #[test] + fn workloads_must_fit_the_context_being_measured() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.ctx = 2048; s.pp = vec![128, 4096]; s.tg = 16; + let e = check_workload_ctx(&s).unwrap_err(); + assert!(e.to_string().contains("exceeds --ctx 2048"), "{e}"); + s.pp = vec![128, 512]; + assert!(check_workload_ctx(&s).is_ok()); + } + + #[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", "--chunk-values", "1024,2048", "--task", "user:prompts.txt", + "--seed", "9", "--dry-run", + ]).unwrap(); + match cli.cmd.unwrap() { + Cmd::Calibrate { samples, reps, pp, tg, chunk_values, task, seed, dry_run, sub, .. } => { + assert_eq!((samples, reps, tg, seed), (7, 2, 16, 9)); + assert_eq!(pp, vec![128, 512]); + assert_eq!(chunk_values, Some(vec![1024, 2048])); + assert_eq!(task, vec!["user:prompts.txt"]); + 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_is_only_chunk_mtp_and_short() { + let s = CalibSettings::new(PathBuf::from("m.gguf")); + let main = build_space("qwen35moe", &s, true); + let names: Vec<_> = main.iter().map(|k| k.name.as_str()).collect(); + assert_eq!(names, vec!["chunk", "mtp", "short"]); + let base = baseline_knobs(&main, "qwen35moe"); + assert_eq!((base.i("chunk"), base.i("mtp"), base.i("short")), (Some(4096), Some(0), Some(32))); + + // No MTP head: don't spend samples on drafts that the engine cannot use. + let no_head = build_space("qwen35moe", &s, false); + assert_eq!(no_head[1].values, vec![0.0]); + + // Own-arch models have only the chunk knob. + let own = build_space("inkling2_loop", &s, false); + assert_eq!(own.iter().map(|k| k.name.as_str()).collect::>(), vec!["chunk"]); + } + + #[test] + fn chunks_larger_than_the_context_are_dropped() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.ctx = 2048; + let space = build_space("qwen35moe", &s, true); + let chunks = &space[0].values; + assert!(chunks.iter().all(|&c| c <= 2048.0), "{chunks:?}"); + assert!(!chunks.contains(&4096.0)); + assert!(!chunks.is_empty()); + s.ctx = 4096; + assert!(build_space("qwen35moe", &s, true)[0].values.contains(&4096.0)); + } + + #[test] + fn the_baseline_chunk_is_each_engines_own_default() { + let s = CalibSettings::new(PathBuf::from("m.gguf")); + for (arch, want) in [("gemma4", 256), ("glm5-next", 512), ("hy_v4_flash", 1024), + ("inkling2_loop", 256), ("inkling2", 256), ("qwen35moe", 4096)] { + let space = build_space(arch, &s, true); + let base = baseline_knobs(&space, arch); + assert_eq!(base.i("chunk"), Some(want), "{arch}"); + assert!(space[0].values.contains(&(want as f64)), "{arch} baseline must be searchable"); + } + // DeepSeek prefills one token at a time: there is no chunk to search or write. + assert!(build_space("deepseek41", &s, true).is_empty()); + assert_eq!(arch_default_chunk("deepseek41"), None); + } + + #[test] + fn inkling_chunks_larger_than_its_gpu_cap_are_not_searched() { + let s = CalibSettings::new(PathBuf::from("m.gguf")); + let space = build_space("inkling2_loop", &s, false); + assert!(space[0].values.iter().all(|&c| c <= 256.0), "{:?}", space[0].values); + } + + #[test] + fn short_candidates_cross_the_workload_depths() { + let s = CalibSettings::new(PathBuf::from("m.gguf")); + let space = build_space("qwen35moe", &s, true); + let short = &space.last().unwrap().values; + assert_eq!(short, &vec![32.0, 129.0, 513.0, 2049.0]); + // Every threshold above its depth makes that workload take the short path; none is inert. + for &pp in &s.pp { assert!(short.iter().any(|&t| t > pp as f64 && t <= (pp + 1) as f64)); } + } + + #[test] + fn spec_baseline_uses_current_defaults_not_first_list_values() { + let mut s = CalibSettings::new(PathBuf::from("m.gguf")); + s.spec_types = vec!["ngram-simple".into(), "none".into()]; + s.draft_max = vec![4, 8, 16]; + s.ngram_n = vec![3, 6, 12]; + let b = spec_baseline(&s); + assert_eq!((b.i("spec_type"), b.i("draft_max"), b.i("ngram_n"), b.i("mtp")), + (Some(1), Some(2), Some(2), Some(0))); + } +}