Skip to content

calibrate: budgeted search via bench, chunk/MTP/short against current defaults - #91

Open
sayampy wants to merge 4 commits into
RustingStudio:mainfrom
sayampy:pr/calibrate-small
Open

sayampy wants to merge 4 commits into
RustingStudio:mainfrom
sayampy:pr/calibrate-small

Conversation

@sayampy

@sayampy sayampy commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Reduced-scope calibrate, rebased on current main. Only split: #89 is the tiny bench-JSON change; this PR keeps the code and its documentation together.

Why the rest is not split further

The CLI needs the search core, the spec sweep needs the same measurement channel and knob machinery, and own-arch support needs the child-process bench. Splitting them would duplicate code or create stacked PRs that do not work independently. Declaring that explicitly rather than producing PRs that cannot stand alone.

What it does

calibrate measures through the binary's own bench command (child process, strata.bench.v1 JSON). The search in src/calibrate.rs uses a deterministic low-discrepancy coarse sweep, multi-start coordinate descent and a final polish, with a hard --samples budget and early stopping.

Review findings addressed in this branch:

  • The baseline is today's defaults per engine: chunk 4096 for the main engine, 256 (Gemma 4), 512 (GLM), 1024 (Hy4) and 256 (Inkling 2, which clamps its GPU prefill there). DeepSeek reads no chunk and has no chunk knob: its run measures the baseline and writes identity plus measured rates, dropping any stale knobs. The baseline is a trial at score 1.0, and neither the engine search nor calibrate spec writes a point that scores below it; a failed baseline warns and searches from a neutral reference.
  • short candidates are 32 plus one threshold just above each --pp depth, so every value flips at least one workload into the short-prompt path. The default 128,512,2048 matrix gives short=[32,129,513,2049] instead of the inert 16,32,64,128.
  • The file is written under the backend the bench child actually opened, not the --backend request or cuda: a CUDA to Vulkan fallback writes the file later runs look for. own_calib resolves the opened backend the same way runner does.
  • own_calib respects explicit STRATA_DS_CHUNK / STRATA_GLM_CHUNK / STRATA_G4_CHUNK and restores the variables it set before another model loads, so an uncalibrated model does not inherit the previous model's chunk in serve.
  • CTX is never touched by own_calib; no ctx_recommended, KV or threads are written by v2.
  • Only prefill and decode feed the score (TTFT is prefill for greedy decoding); no objective profiles.
  • spec_baseline adds missing defaults to the lists and resolves the MTP value 0 to its index; the spec sweep passes resolved --mtp values to bench.
  • stop_reason is reset per start, records converged when every descent converges, and evaluated (knob point, workload set) pairs are memoized so duplicate samples are not spent on full model reloads; the baseline is memoized too.
  • --dry-run validates that --pp + --tg fits --ctx; chunks larger than --ctx (and, for Inkling 2, larger than its 256 cap) are dropped from the space.
  • A new calibration clears a stale v1 split key so no outdated layer split is applied at load.
  • Gemma 4 bench uses the module's own gpu_defaults() and records the chunk actually applied through STRATA_G4_CHUNK.
  • --warmup defaults to 0 (no second model load per sample); child output goes to files, not pipes; missing JSON fields fail the sample; calibrate_legacy and dead helpers are removed.

All OWN_ARCHS are measured; main-engine models also search mtp on models with a draft head and short. calibrate spec sweeps per task and only adds its spec section. Full usage guide is in docs/CALIBRATION.md; the docs no longer describe the removed layer-split sweep or say the own-path architectures are uncalibrated. No benchmark numbers were added under docs/.

Validation

cargo check --release and cargo build --release are clean; the full cargo test --release suite is green. The branch is rebased on current origin/main, so GitHub can create the merge cleanly.

Earlier validation (pre-review, RTX 3050 Laptop, 13.6 GB models, --reps 3, small budgets, means of three runs): Tiel score 1.52, decode 18.9 → 32.7 tok/s at 128 tokens; Inkling 2 score 1.146, prefill 32.7 → 42.1 tok/s. Superseded by the fresh numbers below.

Fresh calibration with the code in this branch, on an RTX 3050 Laptop (4 GB, not the maintainer's 3060), --ctx 4096, 128/512-token prompts and 32 generated tokens:

  • Tiel Coder 35B A3B MTP UD-IQ3_XXS (qwen35moe, the Qwen-architecture model used for the earlier numbers): 12 samples, --reps 2, score 1.505, winner chunk=1024 mtp=1 short=32. At 128pp: prefill 75.7 → 130.1 tok/s, decode 17.6 → 31.3 tok/s; at 512pp: prefill 267.1 → 331.9, decode 22.2 → 30.0.
  • Inkling-2-Mini-UD-Q3_K_XL: 8-sample budget, --reps 3, score 1.000, winner chunk=256 (the engine's GPU clamp), converged after one sample; prefill 27.2 tok/s, decode 7.1 tok/s at 128pp.

The full output, the workload table, the earlier pre-review numbers and the note about the standalone Qwen GGUF that cannot load on this machine are in the comment below.

@aletheore

aletheore Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["src/gemma4/mod.rs"]
    n1["lib.rs"]
    n2["src/cuda/mod.rs"]
    n3["src/deepseek/chat.rs"]
    n4["mat.rs"]
    n5["expert_cache.rs"]
    n6["src/gemma4/forward.rs"]
    n7["gguf.rs"]
    n8["src/glm/forward.rs"]
    n9["src/glm/mod.rs"]
    n10["gpu_model.rs"]
    n11["prefill.rs"]
    n12["src/hy4/chat.rs"]
    n13["src/hy4/mod.rs"]
    n14["src/inkling2/chat.rs"]
    n15["src/inkling2/mod.rs"]
    n16["model.rs"]
    n17["ngram.rs"]
    n18["serve.rs"]
    n19["preflight.rs"]
    n20["weights.rs"]
    n0 --> n6
    n1 --> n2
    n1 --> n3
    n1 --> n4
    n1 --> n5
    n1 --> n7
    n1 --> n8
    n1 --> n9
    n1 --> n10
    n1 --> n11
    n1 --> n12
    n1 --> n13
    n1 --> n14
    n1 --> n15
    n1 --> n16
    n1 --> n17
    n1 --> n18
    n1 --> n19
    n1 --> n20
    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 changed
    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
    class n20 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 · +3/-1
  • docs/CALIBRATION.md · added · +190/-0
  • docs/MODELS.md · modified · +3/-2
  • docs/USAGE.md · modified · +14/-18
  • src/calibrate.rs · +490/-0 · new file, 40 symbols
  • src/gemma4/mod.rs · modified · +1/-1 · 1 other dependent
  • src/lib.rs · modified · +1/-0 · 18 other dependents
  • src/main.rs · modified · +1082/-183 · +52 functions, -3 functions, +4 classes

Aggregate deltas

  • Modules: +1
  • Dependency graph edges: +3
  • Commits: 4

Comment thread src/main.rs
}
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,

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

Stale v1 split key survives a new calibration and is still applied at load. write_calibration starts from the existing file and only inserts new keys, so a v1 split written by the removed multi-GPU sweep is never cleared. The new calibrate no longer measures or writes a split, but calibrated_split still reads the stale one, so runs keep an outdated layer split the new calibration did not choose.

Prompt for your AI agent
File: src/main.rs
Line: 2440
Symbol: Next
Issue: Stale v1 `split` key survives a new calibration and is still applied at load. write_calibration starts from the existing file and only inserts new keys, so a v1 `split` written by the removed multi-GPU sweep is never cleared. The new calibrate no longer measures or writes a split, but calibrated_split still reads the stale one, so runs keep an outdated layer split the new calibration did not choose.
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
let (Ok(bytes), Some(&d)) = (std::fs::read(&path), self.device.first()) else { return };
let Ok(v) = serde_json::from_slice::<serde_json::Value>(&bytes) else { return };
let gpu = backend::open(self.backend.as_deref(), d).ok().map(|b| b.device().to_string()).unwrap_or_default();
if !calibration_fits(&v, &gpu) { return; }

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

own_calib overwrites STRATA_*_CHUNK even when the user set them explicitly. own_calib calls set_var for STRATA_DS_CHUNK, STRATA_GLM_CHUNK and STRATA_G4_CHUNK unconditionally, with no check for an existing value. A user who exports STRATA_DS_CHUNK to force a chunk gets the calibrated value instead, which contradicts the documented rule that flags and explicit settings override the file.

Prompt for your AI agent
File: src/main.rs
Line: 380
Symbol: with
Issue: own_calib overwrites STRATA_*_CHUNK even when the user set them explicitly. own_calib calls set_var for STRATA_DS_CHUNK, STRATA_GLM_CHUNK and STRATA_G4_CHUNK unconditionally, with no check for an existing value. A user who exports STRATA_DS_CHUNK to force a chunk gets the calibrated value instead, which contradicts the documented rule that flags and explicit settings override the file.
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
.arg("--ctx").arg(s.ctx.to_string())
.arg("--kv").arg(&s.kv)
.arg("--chunk").arg(chunk.to_string())
.arg("--mtp").arg(mtp.to_string())

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

Dropped ctx guard

chunk and pp values above --ctx are not filtered. The old calibrate filtered chunks to c <= ctx and required n_pf >= 512. build_space always adds 4096 and passes every --chunk-values entry through, and no check compares --pp/--tg against --ctx. With --ctx 2048, every 4096 sample or long-pp sample fails, and the run ends as 'no successful measurement' with no useful diagnosis.

Prompt for your AI agent
File: src/main.rs
Line: 2410
Symbol: Serving
Issue: Dropped ctx guard: chunk and pp values above --ctx are not filtered. The old calibrate filtered chunks to c <= ctx and required n_pf >= 512. build_space always adds 4096 and passes every --chunk-values entry through, and no check compares --pp/--tg against --ctx. With --ctx 2048, every 4096 sample or long-pp sample fails, and the run ends as 'no successful measurement' with no useful diagnosis.
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

// 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();

@aletheore aletheore Bot Nov 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 18ff535d3ac6.


🟡 Medium · Correctness · 4 of 10

stop_reason is hardcoded to "budget", so convergence is never recorded. Stage B sets a per-start stop_reason to "converged", but the function ends with let stop_reason = "budget". The SearchResult, and the search.stop_reason written to the calibration file, claim the budget ran out even when every descent converged early. This misleads anyone auditing a run.

Prompt for your AI agent
File: src/calibrate.rs
Line: 290
Issue: stop_reason is hardcoded to "budget", so convergence is never recorded. Stage B sets a per-start stop_reason to "converged", but the function ends with `let stop_reason = "budget"`. The SearchResult, and the search.stop_reason written to the calibration file, claim the budget ran out even when every descent converged early. This misleads anyone auditing a run.
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
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());
}

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

A failing baseline aborts calibration instead of recording the failure. calibrate_v2 measures the baseline with measure(&base_knobs, &workloads)?, so an error from the chunk-4096 default (for example OOM on a small GPU) returns immediately. The old code tolerated large-chunk failures and kept the chunks measured so far, and the search could still find a working chunk. The new code never reaches the search.

Prompt for your AI agent
File: src/main.rs
Line: 2550
Symbol: Job
Issue: A failing baseline aborts calibration instead of recording the failure. calibrate_v2 measures the baseline with `measure(&base_knobs, &workloads)?`, so an error from the chunk-4096 default (for example OOM on a small GPU) returns immediately. The old code tolerated large-chunk failures and kept the chunks measured so far, and the search could still find a working chunk. The new code never reaches the search.
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
/// 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<PathBuf> {
let path = calibration_path(&s.model, backend, &s.device);
std::fs::create_dir_all(path.parent().unwrap())?;

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 · 6 of 10

spec_baseline is not the current defaults when lists lack them. spec_baseline uses position(...).unwrap_or(0) for 'none', 16 and 12, and sets mtp to the literal 0.0 as an index. If --spec-types omits 'none', or --mtp is given as '2,0', the baseline silently becomes a different spec setting, so the reported speedup is measured against the wrong reference.

Prompt for your AI agent
File: src/main.rs
Line: 2600
Symbol: Sched
Issue: spec_baseline is not the current defaults when lists lack them. spec_baseline uses position(...).unwrap_or(0) for 'none', 16 and 12, and sets mtp to the literal 0.0 as an index. If --spec-types omits 'none', or --mtp is given as '2,0', the baseline silently becomes a different spec setting, so the reported speedup is measured against the wrong reference.
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
backend: String,
}

struct CappedOutput {

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

Calibration file is written under the detected backend but read under cuda. write_calibration names the file from the backend reported by bench, which may be vulkan or cpu when none was given on the command line. own_calib and the engine read calibration_path with unwrap_or("cuda"), so they look for a different file name and the calibration is never applied, with no warning.

Prompt for your AI agent
File: src/main.rs
Line: 2330
Symbol: interface_args
Issue: Calibration file is written under the detected backend but read under cuda. write_calibration names the file from the backend reported by bench, which may be vulkan or cpu when none was given on the command line. own_calib and the engine read calibration_path with unwrap_or("cuda"), so they look for a different file name and the calibration is never applied, with no warning.
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 Outdated
for i in 0..coarse {
let k = quantize(space, &low_discrepancy(i, space.len(), cfg.seed));
let trial = evaluate(&k, &workloads[..1])?;
used += 1;

@aletheore aletheore Bot Nov 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 18ff535d3ac6.


🔵 Low · Performance · 8 of 10

No memo of evaluated knob points; repeated samples are spent on duplicates. Coordinate descent and multi-start re-evaluate the same knob points (a seed can equal a previous winner, and coarse points can repeat). Each repeat costs a full bench child process that reloads the model, but the budget counts it as new. seeds.dedup_by only removes adjacent duplicates after sorting by score, so equal points survive. Each duplicate reduces the samples left for real search.

Prompt for your AI agent
File: src/calibrate.rs
Line: 236
Issue: No memo of evaluated knob points; repeated samples are spent on duplicates. Coordinate descent and multi-start re-evaluate the same knob points (a seed can equal a previous winner, and coarse points can repeat). Each repeat costs a full bench child process that reloads the model, but the budget counts it as new. seeds.dedup_by only removes adjacent duplicates after sorting by score, so equal points survive. Each duplicate reduces the samples left for real search.
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

/// 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

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

own_calib opens the GGUF and initialises a GPU backend on every start. generate, chat and serve all call own_calib, which runs Gguf::open, reads the file, and calls backend::open to obtain the device name. For main-engine models that do not use the own-arch path, this adds GPU initialisation and a second header read on every start. The device name could be cached in the calibration file or fetched only when a calibration file exists.

Prompt for your AI agent
File: src/main.rs
Line: 370
Symbol: with
Issue: own_calib opens the GGUF and initialises a GPU backend on every start. generate, chat and serve all call own_calib, which runs Gguf::open, reads the file, and calls backend::open to obtain the device name. For main-engine models that do not use the own-arch path, this adds GPU initialisation and a second header read on every start. The device name could be cached in the calibration file or fetched only when a calibration file exists.
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
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.

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 · 10 of 10

bench_gemma4 records chunk 1 and copies gemma4 env constants. BenchMeta sets chunk: 1 even though bench_sample applies the candidate through STRATA_G4_CHUNK, so the JSON records a chunk that was not measured. The hardcoded STRATA_DS_GPU_EXPERTS=11 and NOEVICT values duplicate private gemma4 defaults and can drift, so calibration would measure a different configuration than generate or chat uses.

Prompt for your AI agent
File: src/main.rs
Line: 2085
Symbol: best
Issue: bench_gemma4 records chunk 1 and copies gemma4 env constants. BenchMeta sets chunk: 1 even though bench_sample applies the candidate through STRATA_G4_CHUNK, so the JSON records a chunk that was not measured. The hardcoded STRATA_DS_GPU_EXPERTS=11 and NOEVICT values duplicate private gemma4 defaults and can drift, so calibration would measure a different configuration than generate or chat uses.
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 pull request adds early device validation (backend::check_devices) to the calibrate_v2 and calibrate_spec entry points, so a bad --device value fails before the GGUF model file is read. It affects users running the calibration tooling, who get faster failure on misconfigured devices; the title also describes broader budgeted-search changes that are not visible in this excerpt.

Merge confidence Review effort Merge risk
2 / 5 1 / 5 Medium
Area Files Lines
src 1 +2 −0

2 finding(s) posted as inline review comment(s). 21 earlier finding(s) from previous pushes still open.

# Severity Category Where
1 🔵 Low Maintainability main.rs:2731 New device check in calibrate_v2 has no visible test that a bad --device fails before the GGUF is read. A…
2 🔵 Low Performance main.rs:2809 check_devices now runs in calibrate_spec, which may repeat a probe already done on the same path. If…
- 🟠 High Correctness main.rs:2440 Earlier finding, still open
- 🟠 High Correctness main.rs:380 Earlier finding, still open
- 🟠 High Correctness main.rs:2410 Earlier finding, still open
- 🟡 Medium Correctness main.rs:2550 Earlier finding, still open
- 🟡 Medium Correctness main.rs:2600 Earlier finding, still open
- 🟡 Medium Correctness main.rs:2330 Earlier finding, still open
- 🔵 Low Performance main.rs:370 Earlier finding, still open
- 🟡 Medium Correctness main.rs:2085 Earlier finding, still open
- 🟠 High Correctness main.rs:2410 Earlier finding, still open
- 🟠 High Correctness main.rs:380 Earlier finding, still open
- 🔵 Low Maintainability main.rs:1466 Earlier finding, still open
- 🟡 Medium Correctness main.rs:2315 Earlier finding, still open
- 🟡 Medium Correctness main.rs:2340 Earlier finding, still open
- 🟠 High Correctness main.rs:2762 Earlier finding, still open
- 🟠 High Correctness main.rs:2821 Earlier finding, still open
- 🟠 High Correctness main.rs:386 Earlier finding, still open
- 🔵 Low Performance main.rs:393 Earlier finding, still open
- 🟠 High Correctness calibrate.rs:116 Earlier finding, still open
- 🟠 High Correctness calibrate.rs:117 Earlier finding, still open
- 🟠 High Correctness calibrate.rs:317 Earlier finding, still open
- 🔵 Low Performance main.rs:393 Earlier finding, still open
Review details

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

Fix all with your agent
File: src/main.rs
Line: 2731
Symbol: calibrate_v2
Issue: New device check in calibrate_v2 has no visible test that a bad --device fails before the GGUF is read. A later refactor moves check_devices below the GGUF read or below check_workload_ctx. A bad --device then fails only after the model is loaded, and nothing in the diff catches the regression.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/main.rs
Line: 2809
Symbol: calibrate_spec
Issue: check_devices now runs in calibrate_spec, which may repeat a probe already done on the same path. If calibrate_spec is reached from a path that already ran check_devices, such as a shared dispatcher, the backend probe runs twice. That adds start-up latency and can initialise GPU state twice. The check should live once in the shared entry point.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Comment thread src/calibrate.rs
}
}

/// Score of a full workload matrix: geometric mean over workloads, so each prompt depth counts equally. Every depth

@aletheore aletheore Bot Nov 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of df37bb56787d.


🟠 High · Correctness · 1 of 6

Invalid per-workload measurements are silently skipped in the score. A candidate where one workload reports zero or non-finite decode rate (while another workload is valid) is not flagged as an error because evaluate only requires any valid measurement. aggregate_score then averages only the valid workloads, so this candidate can have a higher score than a full-matrix config and win the search, even though the broken workload was never measured properly.

Prompt for your AI agent
File: src/calibrate.rs
Line: 109
Issue: Invalid per-workload measurements are silently skipped in the score. A candidate where one workload reports zero or non-finite decode rate (while another workload is valid) is not flagged as an error because evaluate only requires any valid measurement. aggregate_score then averages only the valid workloads, so this candidate can have a higher score than a full-matrix config and win the search, even though the broken workload was never measured properly.
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
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.

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 6

Baseline measurement runs outside the --samples budget. calibrate_v2 calls measure(&base_knobs, &workloads) before search, and that call is not counted in used. With --samples 24 the run performs 25 full-matrix bench children (more with --warmup and per-task groups), breaking the documented hard cap and the time estimate users plan around.

Prompt for your AI agent
File: src/main.rs
Line: 2410
Symbol: Serving
Issue: Baseline measurement runs outside the --samples budget. calibrate_v2 calls measure(&base_knobs, &workloads) before search, and that call is not counted in `used`. With --samples 24 the run performs 25 full-matrix bench children (more with --warmup and per-task groups), breaking the documented hard cap and the time estimate users plan around.
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
let (Ok(bytes), Some(&d)) = (std::fs::read(&path), self.device.first()) else { return };
let Ok(v) = serde_json::from_slice::<serde_json::Value>(&bytes) else { return };
let gpu = backend::open(self.backend.as_deref(), d).ok().map(|b| b.device().to_string()).unwrap_or_default();
if !calibration_fits(&v, &gpu) { return; }

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 6

Calibrated chunk env var is sticky, so later models in serve get the wrong chunk. own_calib writes STRATA_DS/GLM/G4_CHUNK into the process environment, and chunk_env_updates skips any variable that is already present. In serve, when a second own-arch model is loaded, its calibrated chunk is skipped because the first model's value is still set, so it runs with the first model's chunk and the calibration is ignored.

Prompt for your AI agent
File: src/main.rs
Line: 380
Symbol: with
Issue: Calibrated chunk env var is sticky, so later models in serve get the wrong chunk. own_calib writes STRATA_DS/GLM/G4_CHUNK into the process environment, and chunk_env_updates skips any variable that is already present. In serve, when a second own-arch model is loaded, its calibrated chunk is skipped because the first model's value is still set, so it runs with the first model's chunk and the calibration is ignored.
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
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"); }

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 6

Multi-GPU layer-split calibration is removed with no replacement. The v1 path measured and stored a faster layer split across devices, and calibrated_split reads it back. The v2 flow ignores --split and drop_split deletes any stored split on every write. A user with several GPUs loses the measured split silently and falls back to the free-VRAM split, which the old comments say can be slower.

Prompt for your AI agent
File: src/main.rs
Line: 1466
Symbol: run
Issue: Multi-GPU layer-split calibration is removed with no replacement. The v1 path measured and stored a faster layer split across devices, and calibrated_split reads it back. The v2 flow ignores --split and drop_split deletes any stored split on every write. A user with several GPUs loses the measured split silently and falls back to the free-VRAM split, which the old comments say can be slower.
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
"threads" => config.threads = value.parse()?,
"chunk" => config.chunk = value.parse()?,
"kv" => config.kv = value.to_string(),
_ => return Err(Error::UnknownKey(line_no)),

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 6

Baseline is not today's default when the chunk is filtered out by ctx. build_space drops chunks above --ctx and only adds 4096 when ctx >= 4096. With --ctx 2048 or a user list that omits 4096, baseline_knobs falls back to values[0] for chunk. The dry-run prints a baseline that is not the current default, and every score is measured against the wrong reference.

Prompt for your AI agent
File: src/main.rs
Line: 2315
Issue: Baseline is not today's default when the chunk is filtered out by ctx. build_space drops chunks above --ctx and only adds 4096 when ctx >= 4096. With --ctx 2048 or a user list that omits 4096, baseline_knobs falls back to values[0] for chunk. The dry-run prints a baseline that is not the current default, and every score is measured against the wrong reference.
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
}
}

struct BenchSample {

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 · 6 of 6

Baseline error is discarded, so the reason for failure is lost. baseline_samples maps Err(_) to an empty vector and the caller prints only a generic warning. A real configuration problem, such as a missing bench flag or a bad model path, is shown as an OOM guess and the user cannot tell why the baseline failed.

Prompt for your AI agent
File: src/main.rs
Line: 2340
Symbol: interface_args
Issue: Baseline error is discarded, so the reason for failure is lost. baseline_samples maps Err(_) to an empty vector and the caller prints only a generic warning. A real configuration problem, such as a missing bench flag or a bad model path, is shown as an OOM guess and the user cannot tell why the baseline failed.
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 docs/CALIBRATION.md Outdated

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. 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.

@aletheore aletheore Bot Nov 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 36fb21c76f6d.


🟠 High · Correctness · 1 of 7

Baseline section says the score is relative to today's defaults, but a failed baseline falls back to a neutral reference, which the doc never mentions. The baseline measurement fails. The run warns and searches from a neutral reference, yet the doc still says the reported score is relative to the defaults. A user reading the score compares it to the wrong baseline and misjudges the speedup.

Prompt for your AI agent
File: docs/CALIBRATION.md
Line: 46
Issue: Baseline section says the score is relative to today's defaults, but a failed baseline falls back to a neutral reference, which the doc never mentions. The baseline measurement fails. The run warns and searches from a neutral reference, yet the doc still says the reported score is relative to the defaults. A user reading the score compares it to the wrong baseline and misjudges the speedup.
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 docs/CALIBRATION.md
this workflow and `--split` is ignored with a note.

## Flags

@aletheore aletheore Bot Nov 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of df37bb56787d.


🟠 High · Correctness · 2 of 7

--reps multiplies measurements, but the docs say --samples is a hard cap on samples without saying whether reps count toward it. A user sets --samples 24 with the default --reps 3 and expects 24 measurements. If reps are not counted, the run takes three times the expected time. If they are counted, the coarse sweep and descent get only a third of the budget. Either way the budget is misread.

Prompt for your AI agent
File: docs/CALIBRATION.md
Line: 103
Issue: --reps multiplies measurements, but the docs say --samples is a hard cap on samples without saying whether reps count toward it. A user sets --samples 24 with the default --reps 3 and expects 24 measurements. If reps are not counted, the run takes three times the expected time. If they are counted, the coarse sweep and descent get only a third of the budget. Either way the budget is misread.
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 docs/CALIBRATION.md Outdated

## The calibration file

The file keeps every v1 key (`chunk`, `mtp`, `short`, `ctx`, `gpu`, `bytes`, `measured`, `aux`, `split`), so older

@aletheore aletheore Bot Nov 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 36fb21c76f6d.


🟠 High · Correctness · 3 of 7

The v1 compatibility section promises a split key, but the doc also says the layer-split sweep is removed and --split is ignored, so nothing writes it. Older binaries that read split from the file get no value, or a stale one, because the new calibrate never writes it. The doc gives no source for the key, so the compatibility guarantee cannot be relied on.

Prompt for your AI agent
File: docs/CALIBRATION.md
Line: 147
Issue: The v1 compatibility section promises a `split` key, but the doc also says the layer-split sweep is removed and `--split` is ignored, so nothing writes it. Older binaries that read `split` from the file get no value, or a stale one, because the new calibrate never writes it. The doc gives no source for the key, so the compatibility guarantee cannot be relied on.
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 docs/CALIBRATION.md

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:

@aletheore aletheore Bot Nov 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of df37bb56787d.


🟡 Medium · Correctness · 4 of 7

The score formula covers one workload, but the matrix has several prompt depths and tasks, and the doc never says how they are combined. A user cannot tell whether the score is a mean over all workloads, a minimum, or per-workload. A candidate that wins on prose but regresses on coding may still be reported as the winner, and the user cannot check this from the doc.

Prompt for your AI agent
File: docs/CALIBRATION.md
Line: 39
Issue: The score formula covers one workload, but the matrix has several prompt depths and tasks, and the doc never says how they are combined. A user cannot tell whether the score is a mean over all workloads, a minimum, or per-workload. A candidate that wins on prose but regresses on coding may still be reported as the winner, and the user cannot check this from the doc.
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 docs/CALIBRATION.md
1. **Baseline** — current defaults, measured on the full workload matrix (not counted in the budget).
2. **Coarse sweep** — up to `min(samples/3, 8)` points from a low-discrepancy (radical-inverse) sequence over the
joint knob space. Their scores only pick starting points; they are never compared with full-matrix scores and
cannot win.

@aletheore aletheore Bot Nov 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of df37bb56787d.


🔵 Low · 5 of 7

Final polish is described as one more pass, but the doc does not say whether its samples count against the --samples budget. A user with --samples 16 finds the run used more samples than the cap because polish is outside the budget. The stated hard cap is then not accurate.

Prompt for your AI agent
File: docs/CALIBRATION.md
Line: 76
Issue: Final polish is described as one more pass, but the doc does not say whether its samples count against the --samples budget. A user with --samples 16 finds the run used more samples than the cap because polish is outside the budget. The stated hard cap is then not accurate.
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 docs/USAGE.md Outdated
`~/.cache/rusting_strata/strata-<model>.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-<model>.json` unless flags override. See [CALIBRATION.md](CALIBRATION.md) for
the budgeted search and the `calibrate spec` sweep.

@aletheore aletheore Bot Nov 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 36fb21c76f6d.


🔵 Low · 6 of 7

USAGE gives the calibration file path without the backend and device suffixes that CALIBRATION.md says the filename encodes. A user looks for strata-<model>.json as USAGE describes, but the file was written as strata-<model>-vulkan-dev0-1.json. They find no calibration and assume calibrate did not run.

Prompt for your AI agent
File: docs/USAGE.md
Line: 116
Issue: USAGE gives the calibration file path without the backend and device suffixes that CALIBRATION.md says the filename encodes. A user looks for strata-<model>.json as USAGE describes, but the file was written as strata-<model>-vulkan-dev0-1.json. They find no calibration and assume calibrate did not run.
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 docs/CALIBRATION.md Outdated

The filename encodes backend and device order (`-vulkan`, `-dev0-1`), so calibrations for different setups do not
overwrite each other. As before, `XDG_CACHE_HOME` moves the folder, and a file measured on another GPU or another
file of the same name (different size) is ignored with a warning.

@aletheore aletheore Bot Nov 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 36fb21c76f6d.


🔵 Low · 7 of 7

The sentence about files being ignored is garbled

it reads as if a different-size file and a different-GPU file are the same case. A reader cannot tell whether a file is ignored for measuring on another GPU, for having the same name but a different size, or for both. They may keep a stale file they expected to be rejected, or delete a valid one.

Prompt for your AI agent
File: docs/CALIBRATION.md
Line: 173
Issue: The sentence about files being ignored is garbled: it reads as if a different-size file and a different-GPU file are the same case. A reader cannot tell whether a file is ignored for measuring on another GPU, for having the same name but a different size, or for both. They may keep a stale file they expected to be rejected, or delete a valid one.
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.

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Ty, this is the shape I asked for after #87, small and it merges clean. I only read it so far, nothing was run. A few things can make the calibration wrong or ignored:

The file is written under --backend or "cuda" (calib_backend_name), but the main engine reads the name of the backend that really opened. On a machine where CUDA does not load and it falls back to Vulkan, calibrate writes one file and every run looks for another.

The baseline is never a trial, and the best searched point is written even when its score is under 1.0. So it can write a setting that is slower than the default.

short is searched over 16/32/64/128, but the workloads are pp 128/512/2048 and short only acts on prompts shorter than it. So no candidate changes anything and the value written is noise.

The baseline chunk is 4096 for every arch, but Gemma 4, GLM and Hy4 have defaults of 256, 512 and 1024, Inkling 2 clamps to 256 and DeepSeek reads no chunk at all.

In serve own_calib sets the chunk variables and nothing restores them, so the next model that has no calibration runs with the chunk of the model before it.

Also the docs still say calibrate does not cover these archs and still describe the layer split calibration.

When these are fixed I will run it on the 3060 and merge.

@sayampy

sayampy commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@Vasyl-Trefilov Copy that

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

One ask: the numbers in the description are from before the review fixes. When you push the next fixes, please run calibrate again on your laptop (one Qwen model and Inkling 2 is enough) and post the output, so we have numbers for the code that gets merged.

@sayampy

sayampy commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Review fixes + fresh benchmarks (previous numbers kept for comparison)

All items from Vasyl's review are addressed in the pushed commits (now rebased on current origin/main, so the PR merges cleanly). Earlier information is kept below so the new numbers can be compared with it.

Earlier validation (pre-review, from the original description — RTX 3050 Laptop, 13.6 GB models, --reps 3, small budgets, means of three runs): Tiel score 1.52, decode 18.9 → 32.7 tok/s at 128 tokens; Inkling 2 score 1.146, prefill 32.7 → 42.1 tok/s. Those numbers came from the code before the review fixes. The fresh numbers at the end of this comment are from the code that is actually being merged.

Fixes

  • Backend name. calibrate derives the file suffix from the backend the bench child actually opened (strata.bench.v1 backend), not from --backend/cuda; own_calib resolves the opened backend the same way runner does. A CUDA→Vulkan fallback writes the file every later run looks for.
  • Baseline / slower settings. The baseline is a real trial at score 1.0 and competes with the candidates. Both the engine search and calibrate spec refuse to write when the winner scores below 1.0; no slower-than-default file is produced.
  • short is no longer noise. Candidates are 32 plus one threshold just above each --pp depth, so each value flips at least one workload into the short-prompt path. With the defaults the space is short=[32,129,513,2049] instead of 16,32,64,128.
  • Per-arch defaults. Baseline chunk is now 4096 (main engine), 256 (Gemma 4), 512 (GLM), 1024 (Hy4), 256 (Inkling 2, which also caps its search at 256). DeepSeek reads no chunk, so it has no chunk knob: a run measures the baseline and writes identity + measured rates only, with no stale chunk/mtp/short.
  • serve env leak. Chunk variables set by a calibration are recorded and restored before another model loads, so an uncalibrated model no longer inherits the previous one's chunk.
  • Upstream compatibility. The rebase keeps the new bench draft JSON, backend::check_devices before the GGUF is read, and the HIP backend changes; no upstream behavior was dropped.
  • Docs. CALIBRATION.md, USAGE.md and MODELS.md no longer say the own-path archs are uncalibrated and no longer describe the removed layer-split sweep. No benchmark numbers were added to docs/.

Benchmarks submitted (full output)

Machine: RTX 3050 Laptop 4 GB, CUDA, --ctx 4096, 128/512-token prompts, 32 generated tokens, seed 1. This is not the maintainer's 3060.

Tiel Coder 35B A3B MTP UD-IQ3_XXS (qwen35moe, the Qwen-architecture model used for the earlier numbers; the standalone Qwen3.6-35B-A3B GGUF on this machine fails to load with missing tensor blk.0.attn_qkv.weight). Command: rustingstrata calibrate --model … --gpu --backend cuda --pp 128,512 --tg 32 --ctx 4096 --samples 12 --reps 2 --out ….

calibrate qwen35moe: 2 workloads, 12-sample budget, scoring prefill and decode equally
  128pp/32tg/prose
  512pp/32tg/prose
knobs: chunk=[256,512,1024,2048,4096]  mtp=[0,1,2,4]  short=[32,129,513]
baseline (current defaults): chunk=4096 mtp=0 short=32
baseline (current defaults): chunk=4096 mtp=0 short=32
cuda device 0: NVIDIA GeForce RTX 3050 Laptop GPU, sm_86
cuda shared memory: opt-in 101376 B per block, attn_decode_gqa*: 2112 B static, dynamic max 73728 B, carveout default
cuda shared memory: opt-in 101376 B per block, attn_prefill_*: 0 B static, dynamic max 72704 B, carveout default
cuda shared memory: opt-in 101376 B per block, gemvn_*: 0 B static, dynamic max 101376 B, carveout default
best chunk=1024 mtp=1 short=32: score 1.505 vs baseline (12 samples, budget, 138.0s)
full benchmark report: /tmp/opencode/calib-tiel/strata-Tiel-Coder-35B-A3B-MTP-UD-IQ3_XXS-calib-report.json
(abridged calibration JSON: unchanged v1 keys omitted)
{
  "arch": "qwen35moe",
  "best": {"chunk": 1024.0, "mtp": 1.0, "short": 32.0},
  "bytes": 13600579424,
  "chunk": 1024,
  "ctx": 4096,
  "gpu": "NVIDIA GeForce RTX 3050 Laptop GPU",
  "measured": {"decode_tok_s": 31.3, "prefill_tok_s": 130.1},
  "mtp": 1,
  "schema": 2,
  "search": {"elapsed_ms": 138004, "samples_used": 12, "score": 1.5051, "seed": 1, "stop_reason": "budget"},
  "short": 32,
  "workloads": [{"pp": 128, "task": "prose", "tg": 32}, {"pp": 512, "task": "prose", "tg": 32}]
}
written to /home/sayam/.cache/rusting_strata/strata-Tiel-Coder-35B-A3B-MTP-UD-IQ3_XXS.json

Baseline trial vs winner, from the --out trace (prefill / decode, tok/s):

workload baseline chunk 4096, mtp 0 best chunk 1024, mtp 1
128pp/32tg 75.7 / 17.6 130.1 / 31.3
512pp/32tg 267.1 / 22.2 331.9 / 30.0

Score 1.5051.

Inkling-2-Mini-UD-Q3_K_XL (inkling2_loop). Command: rustingstrata calibrate --model … --gpu --backend cuda --pp 128,512 --tg 32 --ctx 4096 --samples 8 --reps 3 --out ….

calibrate inkling2_loop: 2 workloads, 8-sample budget, scoring prefill and decode equally
  128pp/32tg/prose
  512pp/32tg/prose
knobs: chunk=[256]
baseline (current defaults): chunk=256
baseline (current defaults): chunk=256
cuda device 0: NVIDIA GeForce RTX 3050 Laptop GPU, sm_86
cuda shared memory: opt-in 101376 B per block, attn_decode_gqa*: 2112 B static, dynamic max 73728 B, carveout default
cuda shared memory: opt-in 101376 B per block, attn_prefill_*: 0 B static, dynamic max 72704 B, carveout default
cuda shared memory: opt-in 101376 B per block, gemvn_*: 0 B static, dynamic max 101376 B, carveout default
best chunk=256: score 1.000 vs baseline (1 samples, converged, 32.0s)
full benchmark report: /tmp/opencode/calib-inkling/strata-Inkling-2-Mini-UD-Q3_K_XL-calib-report.json
(abridged calibration JSON: unchanged v1 keys and the pre-existing spec section omitted)
{
  "arch": "inkling2_loop",
  "best": {"chunk": 256.0},
  "bytes": 13631779296,
  "chunk": 256,
  "ctx": 4096,
  "gpu": "NVIDIA GeForce RTX 3050 Laptop GPU",
  "measured": {"decode_tok_s": 7.1, "prefill_tok_s": 27.2},
  "mtp": 0,
  "schema": 2,
  "search": {"elapsed_ms": 32050, "samples_used": 1, "score": 1.0, "seed": 1, "stop_reason": "converged"},
  "short": 32,
  "workloads": [{"pp": 128, "task": "prose", "tg": 32}, {"pp": 512, "task": "prose", "tg": 32}]
}
written to /home/sayam/.cache/rusting_strata/strata-Inkling-2-Mini-UD-Q3_K_XL.json

Inkling 2's GPU path clamps the chunk to 256, so there is one real candidate: the baseline wins, the search converges after one sample, and the written chunk is 256 rather than a fabricated 4096. The full per-sample traces are in the --out report files named above; the numbers here are the submitted benchmarks for this branch.

Comment thread src/main.rs
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 {

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 4

Score tie with the baseline (1.0) still writes a calibration, contrary to the documented rule. CALIBRATION.md says that if no candidate beats the baseline, no calibration is written and the defaults stay in force. The guard is result.best.score < 1.0, so when the best point is the baseline itself (score exactly 1.0) the run proceeds to write a file that just records today's defaults. Later runs then load that file and pick up a setting that was never shown to win.

Prompt for your AI agent
File: src/main.rs
Line: 2762
Symbol: serve_slots
Issue: Score tie with the baseline (1.0) still writes a calibration, contrary to the documented rule. CALIBRATION.md says that if no candidate beats the baseline, no calibration is written and the defaults stay in force. The guard is `result.best.score < 1.0`, so when the best point is the baseline itself (score exactly 1.0) the run proceeds to write a file that just records today's defaults. Later runs then load that file and pick up a setting that was never shown to win.
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
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 {

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 4

Same tie bug in calibrate_spec

spec section written when best equals baseline. When no spec candidate beats the baseline, the best trial is the baseline at score 1.0. The < 1.0 check does not return early, so a spec section is written even though the documented contract says nothing is written unless a point wins.

Prompt for your AI agent
File: src/main.rs
Line: 2821
Symbol: open_mtp_gguf
Issue: Same tie bug in calibrate_spec: spec section written when best equals baseline. When no spec candidate beats the baseline, the best trial is the baseline at score 1.0. The `< 1.0` check does not return early, so a spec section is written even though the documented contract says nothing is written unless a point wins.
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
/// 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();

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 4

Restoring chunk env vars at model load can change a still-running model's chunk in serve. In serve, the previous model may still be handling requests when a new model's own_calib calls restore_calib_env and set_var. The SAFETY comment only covers the new model's threads, but the old model's prefill reads STRATA_*_CHUNK at that time, so its chunk changes mid-session and calibrated settings are applied inconsistently. Reading env vars during set_var is also unsound on Unix.

Prompt for your AI agent
File: src/main.rs
Line: 386
Symbol: runner
Issue: Restoring chunk env vars at model load can change a still-running model's chunk in serve. In `serve`, the previous model may still be handling requests when a new model's own_calib calls restore_calib_env and set_var. The SAFETY comment only covers the new model's threads, but the old model's prefill reads STRATA_*_CHUNK at that time, so its chunk changes mid-session and calibrated settings are applied inconsistently. Reading env vars during set_var is also unsound on Unix.
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
// 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 };

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 · 4 of 4

own_calib now opens the GPU backend on every load just to read its name. Each own-arch model load now calls backend::open once in own_calib, and then the engine opens the backend again for the model itself. GPU initialisation is repeated on the start-up path, adding latency and VRAM churn, and it can fail earlier than before when no calibration file exists at all.

Prompt for your AI agent
File: src/main.rs
Line: 393
Symbol: runner
Issue: own_calib now opens the GPU backend on every load just to read its name. Each own-arch model load now calls backend::open once in own_calib, and then the engine opens the backend again for the model itself. GPU initialisation is repeated on the start-up path, adding latency and VRAM churn, and it can fail earlier than before when no calibration file exists at all.
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
let mut acc = 0.0;
let mut n = 0;
for (i, m) in ms.iter().enumerate() {
if !m.valid() { continue; }

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 4

aggregate_score silently drops invalid workloads, so a candidate that fails part of the matrix can win on the rest. A candidate OOMs or returns zero prefill on the 2048-token workload but succeeds on the 128 and 512 workloads. aggregate_score skips the bad entry with continue and averages the remaining two, so the candidate scores well and is written as the winner. The docs say a failing candidate never wins, but this one only fails partially and is then recorded as a clean full-matrix result.

Prompt for your AI agent
File: src/calibrate.rs
Line: 116
Symbol: aggregate_score
Issue: aggregate_score silently drops invalid workloads, so a candidate that fails part of the matrix can win on the rest. A candidate OOMs or returns zero prefill on the 2048-token workload but succeeds on the 128 and 512 workloads. aggregate_score skips the bad entry with `continue` and averages the remaining two, so the candidate scores well and is written as the winner. The docs say a failing candidate never wins, but this one only fails partially and is then recorded as a clean full-matrix result.
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
let mut n = 0;
for (i, m) in ms.iter().enumerate() {
if !m.valid() { continue; }
let base = bases.get(i).unwrap_or(&fallback);

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 4

A failed baseline workload is used as a zero reference, not a neutral 1x, which inflates scores and breaks the baseline-is-1.0 invariant. The baseline run succeeds on two workloads and returns a zeroed Measurement for the third. bases[i] is then all zeros, so the ratio becomes m/0, which clamps to 1e3 for every candidate. That workload contributes the same huge factor to all scores, weakening the comparison there. The baseline trial no longer scores 1.0, so the test invariant that the baseline wins at 1.0 does not hold.

Prompt for your AI agent
File: src/calibrate.rs
Line: 117
Symbol: aggregate_score
Issue: A failed baseline workload is used as a zero reference, not a neutral 1x, which inflates scores and breaks the baseline-is-1.0 invariant. The baseline run succeeds on two workloads and returns a zeroed Measurement for the third. bases[i] is then all zeros, so the ratio becomes m/0, which clamps to 1e3 for every candidate. That workload contributes the same huge factor to all scores, weakening the comparison there. The baseline trial no longer scores 1.0, so the test invariant that the baseline wins at 1.0 does not hold.
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
}

// 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())

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 4

The winner is the maximum of single noisy trials, and it is never re-checked head-to-head against the baseline. The baseline is measured once. If that single measurement runs slow, every candidate looks like a gain. The search then picks, by maximum over many noisy samples, a chunk or MTP value that is really no better than the defaults, and writes it. Nothing re-measures the winner against the baseline before it is saved, even though the module claims to be noise-aware.

Prompt for your AI agent
File: src/calibrate.rs
Line: 317
Symbol: search
Issue: The winner is the maximum of single noisy trials, and it is never re-checked head-to-head against the baseline. The baseline is measured once. If that single measurement runs slow, every candidate looks like a gain. The search then picks, by maximum over many noisy samples, a chunk or MTP value that is really no better than the defaults, and writes it. Nothing re-measures the winner against the baseline before it is saved, even though the module claims to be noise-aware.
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
// 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 };

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 · 4 of 4

own_calib opens a GPU backend on every generate, chat and serve load, even for CPU runs, just to read the device name. A user runs generate on a DeepSeek or Gemma 4 model without a GPU flag. own_calib still calls backend::open, which can initialise CUDA or Vulkan and pay driver startup time. The only result is a file path, and on CPU-only machines the open fails after the cost is paid. On a serve process that switches models, this repeats on every switch.

Prompt for your AI agent
File: src/main.rs
Line: 393
Symbol: own_calib
Issue: own_calib opens a GPU backend on every generate, chat and serve load, even for CPU runs, just to read the device name. A user runs `generate` on a DeepSeek or Gemma 4 model without a GPU flag. own_calib still calls backend::open, which can initialise CUDA or Vulkan and pay driver startup time. The only result is a file path, and on CPU-only machines the open fails after the cost is paid. On a `serve` process that switches models, this repeats on every switch.
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
/// 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

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 · 1 of 2

New device check in calibrate_v2 has no visible test that a bad --device fails before the GGUF is read. A later refactor moves check_devices below the GGUF read or below check_workload_ctx. A bad --device then fails only after the model is loaded, and nothing in the diff catches the regression.

Prompt for your AI agent
File: src/main.rs
Line: 2731
Symbol: calibrate_v2
Issue: New device check in calibrate_v2 has no visible test that a bad --device fails before the GGUF is read. A later refactor moves check_devices below the GGUF read or below check_workload_ctx. A bad --device then fails only after the model is loaded, and nothing in the diff catches the regression.
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
/// 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)?;

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 · 2 of 2

check_devices now runs in calibrate_spec, which may repeat a probe already done on the same path. If calibrate_spec is reached from a path that already ran check_devices, such as a shared dispatcher, the backend probe runs twice. That adds start-up latency and can initialise GPU state twice. The check should live once in the shared entry point.

Prompt for your AI agent
File: src/main.rs
Line: 2809
Symbol: calibrate_spec
Issue: check_devices now runs in calibrate_spec, which may repeat a probe already done on the same path. If calibrate_spec is reached from a path that already ran check_devices, such as a shared dispatcher, the backend probe runs twice. That adds start-up latency and can initialise GPU state twice. The check should live once in the shared entry 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.

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