Skip to content

Universal calibrate v2: budgeted joint search, TTFT-aware objective, all architectures - #87

Closed
sayampy wants to merge 1 commit into
RustingStudio:mainfrom
sayampy:feat/universal-calibrate-v2
Closed

sayampy wants to merge 1 commit into
RustingStudio:mainfrom
sayampy:feat/universal-calibrate-v2

Conversation

@sayampy

@sayampy sayampy commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

What this changes

rustingstrata calibrate was a fixed grid over four chunk sizes, one 4096-token prompt, prefill throughput only, and it refused to run on the six architectures that have their own code path. It is now a universal, budgeted benchmark of every supported model.

The measurement channel is the existing bench command: calibration spawns the binary's own bench with candidate knobs and reads strata.bench.v1 JSON. There is one timing implementation for all engines, so nothing can drift between bench and calibrate. bench now also emits TTFT (prompt latency) and draft acceptance, giving the search three signals.

Search

src/calibrate.rs holds the model-agnostic search:

  • Objective — weighted geometric mean of prefill throughput, decode throughput and TTFT, each relative to its own per-workload baseline. Presets interactive (TTFT 0.50), balanced (0.40), batch (0.10); --objective for a single signal; --weights for exact control. A geometric mean cannot hide a regression in one signal behind a gain in another.
  • Strategy — deterministic low-discrepancy coarse sweep over the joint space, multi-start coordinate descent (each seed re-measured on the full matrix before comparison), then a final polish. Coarse trials are never compared with full-matrix scores. Failed points (OOM, timeout) are kept in the trace and never win.
  • Budget — --samples N is a hard cap with early stopping on stagnation. --seed makes the run reproducible. --out DIR writes every trial, its knobs, measurements, errors and timing.
  • Workloads — --pp depths × task corpora: built-in prose, built-in coding, and --task user:PATH. Real prompts matter because acceptance and routing depend on the text.

Knobs and coverage

Context length, KV format, chunk, MTP drafts, short-prompt threshold and threads are searched (previously only chunk, MTP, short and multi-GPU split). All OWN_ARCHS are calibrated — Inkling 2, Hy4, GLM, DeepSeek, Gemma 4 — instead of being skipped; Gemma 4 gains a bench path, and the own-arch engines apply the measured chunk/context through the environment variables they already read. Multi-GPU works with the free-VRAM split; the old split sweep is intentionally not in v2 and --split is ignored with a note.

calibrate spec sweeps spec type / draft count / n-gram size per task and writes only a spec section, preserving an earlier engine calibration.

Compatibility

The JSON keeps every v1 key so older binaries still read it. v2 adds schema, arch, best, search, workloads, ctx_recommended, spec. ctx_recommended is applied only when --ctx was not given on the command line, so an explicit value always wins. Filename conventions for backend/devices are unchanged.

Usage guide

Full guide: docs/CALIBRATION.md.

M=path/to/model.gguf

# Preview the derived knob space and workload matrix (no weights loaded):
rustingstrata calibrate --model $M --dry-run

# Balanced default (24 samples, pp 128/512/2048):
rustingstrata calibrate --model $M

# Interactive model, small search space, two real corpora:
rustingstrata calibrate --model $M --profile interactive \
  --chunk-values 512,1024,2048,4096 --ctx-values 4096,8192 \
  --task prose --task user:prompts.txt --pp 128,512,2048 \
  --tg 128 --samples 32 --out ./calib-reports

# Per-task speculative sweep (Inkling 2 with its DSpark draft):
rustingstrata calibrate spec --model $M \
  --draft-model draft.gguf --tasks prose,coding \
  --spec-types ngram-simple,ngram-mod,ngram-cache \
  --draft-max 4,8,16 --ngram-n 3,6,12 --samples 16

# Every model in a folder:
rustingstrata calibrate --model ~/models

Successful calibrations are read automatically by later chat/generate/serve runs unless a flag overrides them.

Benchmarks

Machine: RTX 3050 Laptop 4 GB, both models ~13.6 GB (mostly offloaded), page cache warmed by the baseline, --reps 1, greedy, prose, --tg 16, seed 1. These are search-validation runs (means of one sample), not peak-speed records. Full traces are in the --out reports; method and tables are in docs/BENCHMARKS.md.

Tiel-Coder-35B-A3B-MTP-UD-IQ3_XXS (qwen35moe)

10 samples, 114.5 s, 0 failures, score 1.299 vs baseline.
Baseline: chunk 1024, ctx 2048, mtp 0. Best: chunk 4096, ctx 2048, mtp 1.

workload prefill decode TTFT
128-token 109.8 → 126.8 tok/s 17.3 → 28.6 tok/s 1165.8 → 1009.5 ms
512-token 230.3 → 306.3 tok/s 20.1 → 24.4 tok/s 2223.2 → 1671.6 ms

The win is joint: the MTP draft helps decode, the larger chunk helps prefill, and the objective balances both against TTFT.

Inkling-2-Mini-UD-Q3_K_XL (inkling2_loop)

8 samples, 314.2 s, 0 failures, score 1.166 vs baseline. This model was previously uncalibratable.
Baseline: chunk 256, ctx 2048. Best: chunk 256, ctx 4096.

workload prefill decode TTFT
128-token 23.1 → 29.3 tok/s 7.2 → 8.3 tok/s 5541 → 4369 ms
512-token 45.2 → 50.4 tok/s 7.4 → 8.1 tok/s 11327 → 10159 ms

Spec sweep

8 samples, score 1.077 vs baseline. Winner for both prose and coding: ngram-cache, 4 drafts, n-gram size 6. The sweep left the engine calibration (chunk 256, ctx 4096) intact in the JSON. Acceptance reported as 0% because these short prompts produced no drafts to accept; the timing gain is from the lookup path.

Verification

  • cargo check --release clean, cargo build --release clean.
  • cargo test --release: all suites green (108 lib tests including 7 search tests, 29 bin tests including 9 calibration CLI/JSON tests, all integration suites).
  • Reviewed independently; findings on spec index mapping, spec write clobbering the engine calibration, coarse-vs-full score comparison, TTFT conversion, Gemma 4 coverage, failed searches writing files, and GPU compatibility metadata were fixed before the benchmarks above were rerun.

Notes / deliberate limitations

  • Multi-GPU layer-split search from v1 is not part of v2; measurements use the free-VRAM split.
  • The hardware here is a 4 GB laptop GPU with 13.6 GB models, so results are offload-heavy and the budgets are small; on a larger card the search will find a different optimum, which is the point of per-machine calibration.
  • ctx_recommended is advisory by design: explicit --ctx always wins.

…afts

The old `calibrate` measured a fixed grid of chunks, a single prompt, prefill
throughput only, and skipped the six architectures that run on their own code
path. This replaces it with one workflow for every supported model.

Measurement is delegated to `bench` as a child process and read from the
strata.bench.v1 JSON, so there is a single timing implementation. `bench` now
also records TTFT (prompt latency) and draft acceptance, which gives the
search three signals: prefill throughput, decode throughput and time to the
first token. The objective is a weighted geometric mean, with interactive,
balanced and batch presets, single-signal modes and explicit weights.

The search lives in the new `src/calibrate.rs`: a deterministic low-discrepancy
coarse sweep over the joint knob space, multi-start coordinate descent with
full-matrix re-measurement of each seed, and a final polish. `--samples` is a
hard cap with early stopping; failed points stay in the trace and never win.
Coarse trials are never compared with full-matrix scores. Baselines are
per-workload. Workloads are prompt depths x task corpora (`prose`, `coding`,
`user:PATH`), so short prompts and real text both count. The search is
reproducible from its recorded seed.

Knobs now include context length and KV format (the old command only varied
chunk, MTP drafts, short threshold and multi-GPU split). The v2 JSON keeps all
v1 keys, adds the full search metadata and workload matrix, and stores
`ctx_recommended`, applied only when --ctx was not given explicitly.
`--out DIR` writes the complete trial trace.

`calibrate spec` sweeps spec type / draft count / n-gram size per task and only
adds a `spec` section to the file, preserving an earlier engine calibration.

Coverage: all OWN_ARCHS are measured, including Gemma 4, which gains a bench
path. Own-arch models now apply the measured chunk and context through their
environment variables at load time. Multi-GPU still uses the free-VRAM split;
the v1 split sweep is intentionally not part of v2 (documented).

Validation on RTX 3050 Laptop 4 GB (full traces in docs/BENCHMARKS.md):
- Tiel qwen35moe 13.6 GB, 10 samples, score 1.299 vs baseline: 128-token
  decode 17.3 -> 28.6 tok/s with MTP 1, TTFT 1166 -> 1010 ms.
- Inkling-2-Mini-UD-Q3_K_XL, 8 samples, score 1.166: 128-token prefill
  23.1 -> 29.3 tok/s, TTFT 5541 -> 4369 ms. Previously uncalibratable.
- spec sweep on Inkling 2 picks ngram-cache/4/6 per task without disturbing
  the engine calibration.

Docs: new docs/CALIBRATION.md usage guide, README quick-start and docs/USAGE
updates, benchmark section with method and numbers. 14 new unit tests cover
the objective, score comparisons, budget, failed trials, CLI parsing, spec
index mapping, JSON preservation and TTFT conversion. Full release suite green.
@aletheore

aletheore Bot commented Nov 23, 2026

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["lib.rs"]
    n1["src/cuda/mod.rs"]
    n2["src/deepseek/chat.rs"]
    n3["mat.rs"]
    n4["expert_cache.rs"]
    n5["src/gemma4/mod.rs"]
    n6["gguf.rs"]
    n7["forward.rs"]
    n8["src/glm/mod.rs"]
    n9["gpu_model.rs"]
    n10["prefill.rs"]
    n11["src/hy4/chat.rs"]
    n12["src/hy4/mod.rs"]
    n13["src/inkling2/chat.rs"]
    n14["src/inkling2/mod.rs"]
    n15["model.rs"]
    n16["ngram.rs"]
    n17["serve.rs"]
    n18["preflight.rs"]
    n19["weights.rs"]
    n0 --> n1
    n0 --> n2
    n0 --> n3
    n0 --> n4
    n0 --> n5
    n0 --> n6
    n0 --> n7
    n0 --> n8
    n0 --> n9
    n0 --> n10
    n0 --> n11
    n0 --> n12
    n0 --> n13
    n0 --> n14
    n0 --> n15
    n0 --> n16
    n0 --> n17
    n0 --> n18
    n0 --> n19
    classDef changed fill:#d9772c,color:#fff,stroke:#b85f1c;
    classDef changedFinding fill:#c0392b,color:#fff,stroke:#922b21;
    classDef dependent fill:#f2f0ec,color:#18140f,stroke:#d6d0c5;
    class n0 changed
    class n1 dependent
    class n2 dependent
    class n3 dependent
    class n4 dependent
    class n5 dependent
    class n6 dependent
    class n7 dependent
    class n8 dependent
    class n9 dependent
    class n10 dependent
    class n11 dependent
    class n12 dependent
    class n13 dependent
    class n14 dependent
    class n15 dependent
    class n16 dependent
    class n17 dependent
    class n18 dependent
    class n19 dependent
Loading

What changed
Deterministic, computed from this commit's real scan and import graph - posted on every run, whether or not Flash Review found anything.

  • README.md · modified · +4/-1
  • docs/BENCHMARKS.md · modified · +43/-0
  • docs/CALIBRATION.md · added · +199/-0
  • docs/USAGE.md · modified · +6/-5
  • src/calibrate.rs · +431/-0 · new file, 38 symbols
  • src/lib.rs · modified · +1/-0 · 19 other dependents
  • src/main.rs · modified · +836/-33 · +30 functions, -3 functions, +3 classes, -1 class

Aggregate deltas

  • Modules: +1
  • Dependency graph edges: +2
  • Commits: -3

Comment thread src/main.rs
let kv_idx = knobs.i("kv").unwrap_or(0).min(s.kv_values.len().saturating_sub(1));
let kv = s.kv_values.get(kv_idx).map(String::as_str).unwrap_or("f16");
let chunk = knobs.i("chunk").unwrap_or(4096);
let mtp = knobs.i("mtp").unwrap_or(0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 1 of 10

Spec sweep passes the mtp knob's index, not its value, as the --mtp draft count. In calibrate spec, spec_space stores mtp as an index into mtp_values (default [0,2]), but bench_sample reads knobs.i("mtp") and passes that index as --mtp. Index 1 runs bench with --mtp 1 while calibrate_spec reports mtp 2 as the winner, so the stored winner and the measured workload disagree.

Prompt for your AI agent
File: src/main.rs
Line: 2444
Symbol: Next
Issue: Spec sweep passes the mtp knob's index, not its value, as the --mtp draft count. In calibrate spec, spec_space stores mtp as an index into mtp_values (default [0,2]), but bench_sample reads knobs.i("mtp") and passes that index as --mtp. Index 1 runs bench with --mtp 1 while calibrate_spec reports mtp 2 as the winner, so the stored winner and the measured workload disagree.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/calibrate.rs
match local_best.error.clone() {
None if local_best.score > cur_trial.score => { cur_trial = local_best; improved = true; }
_ => {}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 2 of 10

Once stop_reason is 'converged', every later start breaks after one round. stop_reason is set to "converged" when the first seed stagnates. The check if stop_reason == "converged" { break; } then runs on the next seed's first round even if that round improved, so seeds 2 and 3 get a single pass. The multi-start search loses most of its refinement and can settle for a worse local optimum.

Prompt for your AI agent
File: src/calibrate.rs
Line: 290
Issue: Once stop_reason is 'converged', every later start breaks after one round. stop_reason is set to "converged" when the first seed stagnates. The check `if stop_reason == "converged" { break; }` then runs on the next seed's first round even if that round improved, so seeds 2 and 3 get a single pass. The multi-start search loses most of its refinement and can settle for a worse local optimum.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/main.rs

fn run_capped(mut c: Command, secs: u64) -> anyhow::Result<std::process::Output> {
if secs == 0 { return Ok(c.output()?); }
let mut child = c.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 3 of 10

Timed child process is polled without draining its stdout/stderr pipes. With --timeout set, run_capped spawns bench with piped stdout/stderr and only polls try_wait. If the child writes more than the pipe buffer (about 64 KB of progress or log output), it blocks on write. The sample then fails as a timeout even though the bench was healthy.

Prompt for your AI agent
File: src/main.rs
Line: 2398
Issue: Timed child process is polled without draining its stdout/stderr pipes. With --timeout set, run_capped spawns bench with piped stdout/stderr and only polls try_wait. If the child writes more than the pipe buffer (about 64 KB of progress or log output), it blocks on write. The sample then fails as a timeout even though the bench was healthy.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/main.rs
v = serde_json::Value::Null;
}
// The context size chosen by calibration is advisory: apply it only when --ctx was not given on the command
// line. CTX is set by start() only for an explicit --ctx (including one in calibrate spec's own arguments),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Maintainability · 4 of 10

own_calib writes calibrated ctx into the global CTX, which other code reads as 'explicit'. own_calib stores ctx_recommended into rusting_strata::CTX for any model, not only own-code-path ones. Later checks that treat CTX == 0 as 'no explicit --ctx' now see a non-zero value, so the runner's recommendation is skipped and the calibrated context is treated as an explicit user choice.

Prompt for your AI agent
File: src/main.rs
Line: 440
Symbol: runner
Issue: own_calib writes calibrated ctx into the global CTX, which other code reads as 'explicit'. own_calib stores ctx_recommended into rusting_strata::CTX for any model, not only own-code-path ones. Later checks that treat CTX == 0 as 'no explicit --ctx' now see a non-zero value, so the runner's recommendation is skipped and the calibrated context is treated as an explicit user choice.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/main.rs
.with_context(|| format!("bench JSON has no pp {pp}"))?;
let num = |key: &str| r[key]["mean"].as_f64().unwrap_or(0.0);
ms.push(Measurement {
prefill_tok_s: num("prefill_tok_s"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Correctness · 5 of 10

Missing bench JSON fields become 0, which inflates scores via invalid baselines. bench_sample's num closure returns 0.0 for a missing key. If the baseline run gets a zero decode or TTFT, aggregate_score divides by that zero base (clamped to 1e3) and does not skip it, since only candidate measurements are checked with valid(). Every candidate then gets an inflated score and the search picks a bad point.

Prompt for your AI agent
File: src/main.rs
Line: 2505
Symbol: wants_model
Issue: Missing bench JSON fields become 0, which inflates scores via invalid baselines. bench_sample's num closure returns 0.0 for a missing key. If the baseline run gets a zero decode or TTFT, aggregate_score divides by that zero base (clamped to 1e3) and does not skip it, since only candidate measurements are checked with valid(). Every candidate then gets an inflated score and the search picks a bad point.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/main.rs
}
c
};
if s.warmup > 0 { let _ = run_capped(build(1), s.timeout)?; }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Performance · 6 of 10

Warmup runs a full extra child process, reloading the model, for every sample. Each sample with warmup > 0 runs build(1) as a separate bench process before build(reps). Each process loads a multi-GB model, so the default warmup of 1 roughly doubles the wall time of every sample, and the 24-sample default takes twice as long as needed.

Prompt for your AI agent
File: src/main.rs
Line: 2481
Symbol: serve
Issue: Warmup runs a full extra child process, reloading the model, for every sample. Each sample with warmup > 0 runs build(1) as a separate bench process before build(reps). Each process loads a multi-GB model, so the default warmup of 1 roughly doubles the wall time of every sample, and the 24-sample default takes twice as long as needed.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/main.rs
/// 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<PathBuf>, engine: &mut Engine) -> anyhow::Result<()> {
rusting_strata::deepseek::chat::gpu_defaults();
for (k, v) in [("STRATA_DS_GPU_EXPERTS", "11"), ("STRATA_DS_NOEVICT", "1")] {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Correctness · 7 of 10

bench_gemma4 comment and code disagree

'three variables' but two are mirrored. The comment says gpu_defaults is private and that three variables are mirrored, but the loop sets only STRATA_DS_GPU_EXPERTS and STRATA_DS_NOEVICT. The call goes to deepseek::chat::gpu_defaults, which is a different module. If the Gemma generate path sets a third variable, bench measures a configuration the user never runs.

Prompt for your AI agent
File: src/main.rs
Line: 2131
Symbol: calibrate
Issue: bench_gemma4 comment and code disagree: 'three variables' but two are mirrored. The comment says gpu_defaults is private and that three variables are mirrored, but the loop sets only STRATA_DS_GPU_EXPERTS and STRATA_DS_NOEVICT. The call goes to deepseek::chat::gpu_defaults, which is a different module. If the Gemma generate path sets a third variable, bench measures a configuration the user never runs.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/main.rs
device: if backend == "cpu" { &[] } else { &engine.device },
model,
ctx: engine.ctx,
chunk: 1,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Correctness · 8 of 10

Gemma bench ignores the chunk knob but records chunk 1, so chunk sweeps are wasted. bench_gemma4 calls m.prefill(&ids) with no chunk parameter and hard-codes chunk: 1 in BenchMeta. For gemma4, the chunk knob therefore has no effect on the measurement, so calibration spends samples on identical timings and writes a chunk value that was never applied.

Prompt for your AI agent
File: src/main.rs
Line: 2162
Symbol: calibrate
Issue: Gemma bench ignores the chunk knob but records chunk 1, so chunk sweeps are wasted. bench_gemma4 calls m.prefill(&ids) with no chunk parameter and hard-codes chunk: 1 in BenchMeta. For gemma4, the chunk knob therefore has no effect on the measurement, so calibration spends samples on identical timings and writes a chunk value that was never applied.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/main.rs
space.push(KnobSpec::new("mtp", [0.0, 1.0, 2.0, 4.0], false));
space.push(KnobSpec::new("short", [16.0, 32.0, 64.0, 128.0], false));
space.push(KnobSpec::new("threads", [(threads.max(2) / 2) as f64, threads as f64], false));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Performance · 9 of 10

MTP counts are searched even for models with no MTP head. build_space always includes mtp=[0,1,2,4] for the main engine. On a model without an MTP head or --mtp-model, every mtp>0 sample fails. Failed samples still consume the budget, so a large share of the default 24 samples can be wasted on errors.

Prompt for your AI agent
File: src/main.rs
Line: 2561
Symbol: chat
Issue: MTP counts are searched even for models with no MTP head. build_space always includes mtp=[0,1,2,4] for the main engine. On a model without an MTP head or --mtp-model, every mtp>0 sample fails. Failed samples still consume the budget, so a large share of the default 24 samples can be wasted on errors.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/main.rs
#[allow(dead_code)]
fn calibrate_legacy(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], mut split: Option<Vec<f64>>) -> anyhow::Result<()> {
let g = Gguf::open(model)?;
let aux_g = open_mtp_gguf(aux)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Maintainability · 10 of 10

calibrate_legacy is dead code kept behind #[allow(dead_code)]. The v1 grid search is no longer dispatched and is marked #[allow(dead_code)], so the compiler will not flag it. It is hundreds of lines that must be maintained against the shared Engine and Gguf APIs, and it can drift from the v2 path without anyone noticing.

Prompt for your AI agent
File: src/main.rs
Line: 2753
Symbol: serve_slots
Issue: calibrate_legacy is dead code kept behind #[allow(dead_code)]. The v1 grid search is no longer dispatched and is marked #[allow(dead_code)], so the compiler will not flag it. It is hundreds of lines that must be maintained against the shared Engine and Gguf APIs, and it can drift from the v2 path without anyone noticing.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

@aletheore

aletheore Bot commented Nov 23, 2026

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. This PR replaces rustingstrata calibrate with a v2 that searches chunk size, context, KV format, MTP drafts, and threads jointly under a fixed sample budget, scoring them by a weighted geometric mean of prefill, decode, and time to first token. It measures every architecture through the existing bench path, so Inkling 2, Hy4, GLM, DeepSeek, and Gemma 4 are now calibrated too, and it adds a calibrate spec subcommand and a --dry-run flag.

Merge confidence Review effort Merge risk
2 / 5 5 / 5 Medium
Area Files Lines
docs 3 +248 −5
src 3 +1268 −33
(root) 1 +4 −1

10 finding(s) posted as inline review comment(s).

# Severity Category Where
1 🟠 High Correctness main.rs:2444 Spec sweep passes the mtp knob's index, not its value, as the --mtp draft count. In calibrate spec…
2 🟠 High Correctness calibrate.rs:290 Once stop_reason is 'converged', every later start breaks after one round. stop_reason is set to "converged"…
3 🟠 High Correctness main.rs:2398 Timed child process is polled without draining its stdout/stderr pipes. With --timeout set, run_capped spawns…
4 🔵 Low Maintainability main.rs:440 own_calib writes calibrated ctx into the global CTX, which other code reads as 'explicit'. own_calib stores…
5 🟡 Medium Correctness main.rs:2505 Missing bench JSON fields become 0, which inflates scores via invalid baselines. bench_sample's num closure…
6 🔵 Low Performance main.rs:2481 Warmup runs a full extra child process, reloading the model, for every sample. Each sample with warmup > 0…
7 🟡 Medium Correctness main.rs:2131 bench_gemma4 comment and code disagree
8 🟡 Medium Correctness main.rs:2162 Gemma bench ignores the chunk knob but records chunk 1, so chunk sweeps are wasted. bench_gemma4 calls…
9 🔵 Low Performance main.rs:2561 MTP counts are searched even for models with no MTP head. build_space always includes mtp=[0,1,2,4] for the…
10 🔵 Low Maintainability main.rs:2753 calibrate_legacy is dead code kept behind #[allow(dead_code)]. The v1 grid search is no longer dispatched and…
Review details

Reviewed 7 file(s); skipped 0. Dismissed 0; outside PR diff 0. Grounding: 10 of 10 proposed finding(s).

Fix all with your agent
File: src/main.rs
Line: 2444
Symbol: Next
Issue: Spec sweep passes the mtp knob's index, not its value, as the --mtp draft count. In calibrate spec, spec_space stores mtp as an index into mtp_values (default [0,2]), but bench_sample reads knobs.i("mtp") and passes that index as --mtp. Index 1 runs bench with --mtp 1 while calibrate_spec reports mtp 2 as the winner, so the stored winner and the measured workload disagree.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/calibrate.rs
Line: 290
Issue: Once stop_reason is 'converged', every later start breaks after one round. stop_reason is set to "converged" when the first seed stagnates. The check `if stop_reason == "converged" { break; }` then runs on the next seed's first round even if that round improved, so seeds 2 and 3 get a single pass. The multi-start search loses most of its refinement and can settle for a worse local optimum.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/main.rs
Line: 2398
Issue: Timed child process is polled without draining its stdout/stderr pipes. With --timeout set, run_capped spawns bench with piped stdout/stderr and only polls try_wait. If the child writes more than the pipe buffer (about 64 KB of progress or log output), it blocks on write. The sample then fails as a timeout even though the bench was healthy.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/main.rs
Line: 440
Symbol: runner
Issue: own_calib writes calibrated ctx into the global CTX, which other code reads as 'explicit'. own_calib stores ctx_recommended into rusting_strata::CTX for any model, not only own-code-path ones. Later checks that treat CTX == 0 as 'no explicit --ctx' now see a non-zero value, so the runner's recommendation is skipped and the calibrated context is treated as an explicit user choice.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/main.rs
Line: 2505
Symbol: wants_model
Issue: Missing bench JSON fields become 0, which inflates scores via invalid baselines. bench_sample's num closure returns 0.0 for a missing key. If the baseline run gets a zero decode or TTFT, aggregate_score divides by that zero base (clamped to 1e3) and does not skip it, since only candidate measurements are checked with valid(). Every candidate then gets an inflated score and the search picks a bad point.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/main.rs
Line: 2481
Symbol: serve
Issue: Warmup runs a full extra child process, reloading the model, for every sample. Each sample with warmup > 0 runs build(1) as a separate bench process before build(reps). Each process loads a multi-GB model, so the default warmup of 1 roughly doubles the wall time of every sample, and the 24-sample default takes twice as long as needed.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/main.rs
Line: 2131
Symbol: calibrate
Issue: bench_gemma4 comment and code disagree: 'three variables' but two are mirrored. The comment says gpu_defaults is private and that three variables are mirrored, but the loop sets only STRATA_DS_GPU_EXPERTS and STRATA_DS_NOEVICT. The call goes to deepseek::chat::gpu_defaults, which is a different module. If the Gemma generate path sets a third variable, bench measures a configuration the user never runs.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/main.rs
Line: 2162
Symbol: calibrate
Issue: Gemma bench ignores the chunk knob but records chunk 1, so chunk sweeps are wasted. bench_gemma4 calls m.prefill(&ids) with no chunk parameter and hard-codes chunk: 1 in BenchMeta. For gemma4, the chunk knob therefore has no effect on the measurement, so calibration spends samples on identical timings and writes a chunk value that was never applied.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/main.rs
Line: 2561
Symbol: chat
Issue: MTP counts are searched even for models with no MTP head. build_space always includes mtp=[0,1,2,4] for the main engine. On a model without an MTP head or --mtp-model, every mtp>0 sample fails. Failed samples still consume the budget, so a large share of the default 24 samples can be wasted on errors.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/main.rs
Line: 2753
Symbol: serve_slots
Issue: calibrate_legacy is dead code kept behind #[allow(dead_code)]. The v1 grid search is no longer dispatched and is marked #[allow(dead_code)], so the compiler will not flag it. It is hundreds of lines that must be maintained against the shared Engine and Gguf APIs, and it can drift from the v2 path without anyone noticing.
Make the smallest change that fixes this, add a test, and change nothing unrelated.
Blast radius: 53 other file(s) depend on what this PR changes (19 directly, 34 indirectly)

Computed from the import graph of this exact commit, not guessed by a model. It sees imports only, so dynamic imports, reflection and non-code references are not counted.

  • src/lib.rs is imported by src/cuda/mod.rs, src/deepseek/chat.rs, src/deepseek/mat.rs, src/expert_cache.rs (+15 more)

Indirectly affected: examples/gguf_dump.rs, src/backend.rs, src/chat.rs, src/config.rs, src/cpu_moe.rs, src/cpu_worker.rs (+28 more)

The graph is large; this list is capped and not exhaustive.

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Thanks again, already third PR today if I am correct, this is a lot of work and the direction is right: one calibrate for every architecture, a budget, child bench processes. I can't merge it as it is. I merged the branch onto main (clean), built it (no warnings) and ran the calibrate, binary and serve tests (7, 29 and 31 pass). The card here was in use, so I have no timing of a full run yet; the points below come from the code, from --dry-run and from a unit probe of search().

Blockers:

  1. The recommended ctx never reaches a Qwen model. own_calib runs first in chat, generate and serve and stores ctx_recommended into the global CTX. runner then sees CTX != 0, takes it for an explicit --ctx and skips its own block, so self.ctx stays at 4096. Only the models with their own forward (ctx_limit) get the value.

  2. The baseline is not what users run today. It is the first value of every knob: chunk 256, short 16, half the cores (dry run on a 6-core box: "baseline: chunk=256 ... short=16 threads=3"). The defaults without a calibration file are chunk 4096, short 32, all physical cores. So "score 1.17 against baseline" is not a gain over the current default. Please measure the baseline with the current defaults.

  3. TTFT is not a third signal. bench writes ttft_ms = 1000 * pp / prefill, so base.ttft / m.ttft is the prefill ratio again. The objective is prefill^(wp + wt) * decode^wd: "balanced" is 0.65 / 0.35, "interactive" 0.70 / 0.30. Either measure the time to the first token for real (load excluded) or drop the weight.

  4. ctx is picked by speed and then applied to every later run without --ctx. A noise win doubles the KV cache for the user. The Inkling result in the PR ("ctx 4096 beats 2048", --reps 1) looks like that. ctx is a memory choice of the user; I would not search it. The same holds for threads, which runner now reads from the file.

  5. Gemma 4 is measured in another configuration than chat runs. On main, chat and generate give the weights 90% of the free VRAM (STRATA_DS_GPU_FRACTION); bench_gemma4 sets the old fixed STRATA_DS_GPU_EXPERTS=11. The chunk knob does nothing there: main reads STRATA_G4_CHUNK and neither bench_sample nor own_calib sets it, yet a chunk is written to the file. Please rebase on main first.

  6. calibrate spec passes the index of the mtp knob as --mtp (index 1 runs --mtp 1 and the report says 2).

  7. search(): stop_reason is never reset, so every start after the first converged one gets one round. Probe with a flat landscape and a large budget: 25 full samples for start 1, 13 each for starts 2 and 3.

  8. docs/BENCHMARKS.md gets numbers from an RTX 3050 Laptop with --reps 1. The numbers in the docs come from the reference machine, and one repetition is not a result. Please take the section out; the PR text is the right place for it.

Smaller:

  • With the default budget of 24, 8 samples go to the coarse sweep on the 128-token prompt only and can never win. The 16 full samples reach 13 different points of the 320 in the Qwen space (same for seeds 1, 2 and 3): one pass around one start. Each sample loads the model twice (warm-up and measure). The warning at load still promises "a few minutes".
  • mtp=[0,1,2,4] is searched on models with no MTP head (bench --mtp 2 on Qwen3 0.6B runs with no error): 3 of the 12 neighbours are wasted.
  • kv is written to the file and nothing reads it.
  • run_capped does not drain the pipes while it waits (only with --timeout).
  • A baseline entry with missing JSON fields is not checked.
  • calibrate_legacy is dead code under #[allow(dead_code)]; please delete it. With it goes the layer split of two cards, which v2 does not measure.
  • docs/CALIBRATION.md: the example has "ttft_ms": 0.9 next to a prefill of 1057 tok/s.

What I would merge quickly: a smaller PR with the child-process bench, the search over chunk, mtp and short against the current defaults, own-architecture support (chunk only), --dry-run, and fixes for 6 and 7. ctx, threads and the objective profiles can come after, with numbers from several repetitions. Thanks again

@sayampy

sayampy commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review and for taking the time to merge, build and test everything. Really appreciate it!

You're right about the bugs, especially the CTX ordering, MTP index, and outdated basseline. The TTFT calculation also needs fixing. And yeah, ctx and threads are more about memory constraints than speed, so they probably shouldn't be part of the search.

I'll split this into a smaller PR as you suggested. It'll focus on the child-process benchmark, --dry-run, a budgeted search over chunk/MTP/short using current defaults, own-architecture chunk support, and the MTP index and stop_reason fixes.

I'll also drop ctx and threads from the default search, remove the TTFT weight and objective profiles for now, delete calibrate_legacy, rebase on main and fix Gemma 4's chunk variable. I'll move the benchmark numbers to the PR description and include multiple runs instead of relying on single-run laptop results.

Does this scope look good to you before I put up the PR?

Thanks again for taking the time to go through all of this!

@sayampy

sayampy commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #89 (bench JSON draft counts) and #91 (the reduced-scope calibrate: child-process bench, budgeted search over chunk/MTP/short against current defaults, own-arch support, --dry-run, spec fixes). Those two are independent and rebased on current main. Thanks again for the review — all the blockers are addressed there.

@sayampy sayampy closed this Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants