Repository navigation
Conversation
…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 evidence diffgraph 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
What changed
Aggregate deltas
|
| 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); |
There was a problem hiding this comment.
🟠 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.
| match local_best.error.clone() { | ||
| None if local_best.score > cur_trial.score => { cur_trial = local_best; improved = true; } | ||
| _ => {} | ||
| } |
There was a problem hiding this comment.
🟠 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.
|
|
||
| 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()?; |
There was a problem hiding this comment.
🟠 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.
| 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), |
There was a problem hiding this comment.
🔵 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.
| .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"), |
There was a problem hiding this comment.
🟡 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.
| } | ||
| c | ||
| }; | ||
| if s.warmup > 0 { let _ = run_capped(build(1), s.timeout)?; } |
There was a problem hiding this comment.
🔵 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.
| /// 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")] { |
There was a problem hiding this comment.
🟡 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.
| device: if backend == "cpu" { &[] } else { &engine.device }, | ||
| model, | ||
| ctx: engine.ctx, | ||
| chunk: 1, |
There was a problem hiding this comment.
🟡 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.
| 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)); | ||
| } |
There was a problem hiding this comment.
🔵 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.
| #[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)?; |
There was a problem hiding this comment.
🔵 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 Flash Lite reviewWhat this PR does. This PR replaces
10 finding(s) posted as inline review comment(s).
Review detailsReviewed 7 file(s); skipped 0. Dismissed 0; outside PR diff 0. Grounding: 10 of 10 proposed finding(s). Fix all with your agentBlast 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.
Indirectly affected: The graph is large; this list is capped and not exhaustive. |
|
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:
Smaller:
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 |
|
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, 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! |
|
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. |
What this changes
rustingstrata calibratewas 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
benchcommand: calibration spawns the binary's ownbenchwith candidate knobs and readsstrata.bench.v1JSON. There is one timing implementation for all engines, so nothing can drift betweenbenchandcalibrate.benchnow also emits TTFT (prompt latency) and draft acceptance, giving the search three signals.Search
src/calibrate.rsholds the model-agnostic search:interactive(TTFT 0.50),balanced(0.40),batch(0.10);--objectivefor a single signal;--weightsfor exact control. A geometric mean cannot hide a regression in one signal behind a gain in another.--samples Nis a hard cap with early stopping on stagnation.--seedmakes the run reproducible.--out DIRwrites every trial, its knobs, measurements, errors and timing.--ppdepths × 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_ARCHSare calibrated — Inkling 2, Hy4, GLM, DeepSeek, Gemma 4 — instead of being skipped; Gemma 4 gains abenchpath, 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--splitis ignored with a note.calibrate specsweeps spec type / draft count / n-gram size per task and writes only aspecsection, 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_recommendedis applied only when--ctxwas 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.Successful calibrations are read automatically by later
chat/generate/serveruns 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--outreports; method and tables are indocs/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.
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.
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 --releaseclean,cargo build --releaseclean.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).Notes / deliberate limitations
ctx_recommendedis advisory by design: explicit--ctxalways wins.