Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
244 changes: 203 additions & 41 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -924,6 +924,29 @@ impl Engine {
fn mtp(&self) -> usize { self.mtp.unwrap_or(0) }
fn aux_model_path(&self) -> Option<&Path> { self.draft_model.as_deref().or(self.mtp_model.as_deref()) }

fn calib_aux(&self) -> Option<(&'static str, PathBuf)> {
self.draft_model.clone().map(|p| ("--draft-model", p))
.or_else(|| self.mtp_model.clone().map(|p| ("--mtp-model", p)))
}

/// The `CalibSetup` flags matching this `Engine`, so web-triggered calibration measures the same run `serve` loads.
fn calib_setup(&self) -> CalibSetup {
CalibSetup {
k: self.k.clone(),
v: self.v.clone(),
ple: None, // `serve` sets `STRATA_PLE` before calibrating; `CalibSetup::args` does not emit `--ple`
threads: self.threads,
cache_ram: (self.cache_ram != 4096).then_some(self.cache_ram),
ram_margin: (self.ram_margin != 512).then_some(self.ram_margin),
max_ram: (self.max_ram != 0).then_some(self.max_ram),
arena: self.arena,
pin: self.pin,
prefill_cpu: self.prefill_cpu,
cpu_frac: self.cpu_frac,
host_share: (self.host_share != 0).then_some(self.host_share),
}
}

/// Says which draft options do nothing for a model outside the main engine (`config::OWN_ARCHS`).
fn own_warn(&self, g: &Gguf) {
let Some(arch) = g.get("general.architecture").ok().and_then(|v| v.as_str()) else { return };
Expand Down Expand Up @@ -2814,8 +2837,13 @@ fn run(cmd: Cmd) -> anyhow::Result<()> {
set_kv_env_for(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?;
s.stats.lock().unwrap().unload(Some(s.name(&p)));
vram_margins(&engine.vram_margin, &engine.device)
.and_then(|mb| calibrate(&p, engine.aux_model_path(), engine.ctx, &mb.into_iter().map(|mb| mb << 20).collect::<Vec<_>>(), engine.backend.as_deref(), &engine.device,
split_arg(engine.split.as_deref(), engine.device.len())?))
.and_then(|mb| {
let _ = split_arg(engine.split.as_deref(), engine.device.len())?;
if engine.split.is_some() {
say!("note: --split is ignored by calibrate; measurements use the free-VRAM split");
}
calibrate(&p, &engine, &mb)

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 2

split is validated then discarded, never forwarded to calibration serve --split 0.7,0.3 loads a sharded run, but calibrate() no longer receives split (old _split was also ignored) and serve_calib_settings has no split field, so bench measures an unsharded run and its VRAM margins/perf do not match serve.

Prompt for your AI agent
File: src/main.rs
Line: 2842
Symbol: run
Issue: split is validated then discarded, never forwarded to calibration serve --split 0.7,0.3 loads a sharded run, but calibrate() no longer receives split (old _split was also ignored) and serve_calib_settings has no split field, so bench measures an unsharded run and its VRAM margins/perf do not match serve.
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good to double-check, though not forwarding --split matches v2 calibration's documented behavior in docs/CALIBRATION.md ("With several GPUs (--device 0,1) calibrate keeps the free-VRAM layer split. --split is ignored with a note.") and Cmd::Calibrate (src/main.rs), as well as main before this PR (_split). Multi-GPU sharding is still active during calibration because --device is forwarded to bench (using the free-VRAM split).

In 4446f8f, serve now also emits the same note: --split is ignored by calibrate; measurements use the free-VRAM split message when --split is set (after keeping the existing split_arg validation), and the test verifies --device 1,0 is forwarded while bench.split stays None.

})
} else { Ok(()) };
// The page's CPU threads: the load runs in a pool of its own, as rayon's global pool is built once.
let run = cal.and_then(|()| match engine.threads.filter(|_| engine.threads != threads0) {
Expand Down Expand Up @@ -3349,6 +3377,46 @@ fn parse_drafts(v: &serde_json::Value, stdout: &str) -> (usize, usize) {
(0, 0)
}

/// Build the `bench` child-process argument vector for one calibration measurement sample.
fn bench_sample_args(s: &CalibSettings, knobs: &Knobs, pps: &[usize], reps: usize, json: &Path, prompt: Option<&Path>) -> Vec<std::ffi::OsString> {
let chunk = knobs.i("chunk").unwrap_or(4096);
let short = knobs.i("short").unwrap_or(32);
// In a spec sweep the mtp knob holds an index into --mtp; in the main search it is the value itself.
let mtp = if s.mtp_values.is_empty() { knobs.i("mtp").unwrap_or(0) }
else { s.mtp_values[knobs.i("mtp").unwrap_or(0).min(s.mtp_values.len() - 1)] };
let mut args: Vec<std::ffi::OsString> = vec![
"bench".into(),
"--model".into(), s.model.as_os_str().to_os_string(),
"--gpu".into(),
"--pp".into(), pps.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(",").into(),
"--tg".into(), s.tg.to_string().into(),
"--reps".into(), reps.to_string().into(),
"--ctx".into(), s.ctx.to_string().into(),
"--kv".into(), s.kv.clone().into(),
"--chunk".into(), chunk.to_string().into(),
"--mtp".into(), mtp.to_string().into(),
"--short".into(), short.to_string().into(),
"--device".into(), s.device.iter().map(|d| d.to_string()).collect::<Vec<_>>().join(",").into(),
"--json-out".into(), json.as_os_str().to_os_string(),
];
args.extend(s.extra.iter().map(std::ffi::OsString::from));
if let Some(b) = &s.backend { args.extend(["--backend".into(), b.clone().into()]); }
if let Some((flag, p)) = &s.aux { args.extend([(*flag).into(), p.as_os_str().to_os_string()]); }
if let Some(p) = prompt { args.extend(["--prompt-file".into(), p.as_os_str().to_os_string()]); }
if !s.vram_margin.is_empty() { args.extend(["--vram-margin".into(), s.vram_margin.join(",").into()]); }
if !s.spec_types.is_empty() {
let ti = knobs.i("spec_type").unwrap_or(0).min(s.spec_types.len() - 1);
let di = knobs.i("draft_max").unwrap_or(0).min(s.draft_max.len() - 1);
let ni = knobs.i("ngram_n").unwrap_or(0).min(s.ngram_n.len() - 1);
args.extend([
"--spec-type".into(), s.spec_types[ti].clone().into(),
"--spec-draft-n-max".into(), s.draft_max[di].to_string().into(),
"--spec-ngram-size-n".into(), s.ngram_n[ni].to_string().into(),
]);
}
args
}

/// One measurement sample: run `bench` as a child process with the candidate knobs applied, then read its JSON.
/// Using the public bench command as the measurement channel is what makes calibration work with every architecture:
/// there is one code path that times a prompt and a decode, and calibration never duplicates it.
Expand All @@ -3359,43 +3427,14 @@ fn bench_sample(s: &CalibSettings, knobs: &Knobs, task: &str, pps: &[usize]) ->
let prompt = calib_prompt(task, &dir)?;
let exe = std::env::current_exe().context("finding this executable")?;
let chunk = knobs.i("chunk").unwrap_or(4096);
let short = knobs.i("short").unwrap_or(32);
// In a spec sweep the mtp knob holds an index into --mtp; in the main search it is the value itself.
let mtp = if s.mtp_values.is_empty() { knobs.i("mtp").unwrap_or(0) }
else { s.mtp_values[knobs.i("mtp").unwrap_or(0).min(s.mtp_values.len() - 1)] };

let build = |reps: usize| {
let mut c = Command::new(&exe);
c.arg("bench")
.arg("--model").arg(&s.model)
.arg("--gpu")
.arg("--pp").arg(pps.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(","))
.arg("--tg").arg(s.tg.to_string())
.arg("--reps").arg(reps.to_string())
.arg("--ctx").arg(s.ctx.to_string())
.arg("--kv").arg(&s.kv)
.arg("--chunk").arg(chunk.to_string())
.arg("--mtp").arg(mtp.to_string())
.arg("--short").arg(short.to_string())
.arg("--device").arg(s.device.iter().map(|d| d.to_string()).collect::<Vec<_>>().join(","))
.arg("--json-out").arg(&json)
.args(&s.extra);
if let Some(b) = &s.backend { c.arg("--backend").arg(b); }
if let Some((flag, p)) = &s.aux { c.arg(flag).arg(p); }
if let Some(p) = &prompt { c.arg("--prompt-file").arg(p); }
if !s.vram_margin.is_empty() { c.arg("--vram-margin").arg(s.vram_margin.join(",")); }
c.args(bench_sample_args(s, knobs, pps, reps, &json, prompt.as_deref()));
// The architectures outside the main engine read their chunk from the environment at prefill time.
c.env("STRATA_DS_CHUNK", chunk.to_string());
c.env("STRATA_GLM_CHUNK", chunk.to_string());
c.env("STRATA_G4_CHUNK", chunk.to_string());
if !s.spec_types.is_empty() {
let ti = knobs.i("spec_type").unwrap_or(0).min(s.spec_types.len() - 1);
let di = knobs.i("draft_max").unwrap_or(0).min(s.draft_max.len() - 1);
let ni = knobs.i("ngram_n").unwrap_or(0).min(s.ngram_n.len() - 1);
c.arg("--spec-type").arg(s.spec_types[ti].clone());
c.arg("--spec-draft-n-max").arg(s.draft_max[di].to_string());
c.arg("--spec-ngram-size-n").arg(s.ngram_n[ni].to_string());
}
c
};
if s.warmup > 0 { let _ = run_capped(build(1), s.timeout, &dir, id)?; }
Expand Down Expand Up @@ -3863,18 +3902,24 @@ fn calibrate_spec(s: &CalibSettings) -> anyhow::Result<()> {
Ok(())
}

/// Compatibility wrapper used by the chat page's calibrate button and by any code calling the old six-argument
/// function. It maps the previous defaults onto the v2 workflow.
fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], _split: Option<Vec<f64>>) -> anyhow::Result<()> {
/// Build the v2 calibration settings for the chat page's calibrate button from `serve`'s current `Engine`.
fn serve_calib_settings(model: &Path, engine: &Engine, margins_mb: &[usize]) -> CalibSettings {
let mut s = CalibSettings::new(model.to_path_buf());
s.aux = aux.map(|p| ("--draft-model", p.to_path_buf()));
s.ctx = ctx;
s.backend = kind.map(str::to_string);
s.device = device.to_vec();
s.vram_margin = margin.iter().map(|m| (m >> 20).to_string()).collect();
s.aux = engine.calib_aux();
s.ctx = engine.ctx;
s.kv = engine.kv.clone();
s.extra = engine.calib_setup().args();
s.backend = engine.backend.clone();
s.device = engine.device.clone();
s.vram_margin = margins_mb.iter().map(usize::to_string).collect();
s.samples = 12;
s.pp = vec![512];
calibrate_v2(&s)
s
}

/// Calibrate triggered by the chat page's calibrate button, forwarding the server's active KV and setup options.
fn calibrate(model: &Path, engine: &Engine, margins_mb: &[usize]) -> anyhow::Result<()> {
calibrate_v2(&serve_calib_settings(model, engine, margins_mb))
}


Expand Down Expand Up @@ -6061,6 +6106,123 @@ mod calibrate_cli_tests {
assert_eq!(setup.args(), ["--v", "q4"]);
}

#[test]
fn serve_calibrate_forwards_kv_setup_and_aux_flag() {
let cli = Cli::try_parse_from([
"rustingstrata", "serve", "--model", "m.gguf", "--gpu",
"--ctx", "32768", "--kv", "turbo4-3", "--k", "q8", "--v", "f16",
"--threads", "6", "--cache-ram", "0", "--ram-margin", "1024", "--max-ram", "8192",
"--cpu-frac", "0.5", "--host-share", "4", "--arena", "--pin", "--prefill-cpu",
"--backend", "vulkan", "--device", "1,0", "--split", "30,70", "--vram-margin", "0:512,1:256",
"--mtp-model", "head.gguf",
]).unwrap();
let Some(Cmd::Serve { engine, .. }) = cli.cmd else { panic!("wrong command") };
let mb = vram_margins(&engine.vram_margin, &engine.device).unwrap();
let s = serve_calib_settings(Path::new("m.gguf"), &engine, &mb);
assert_eq!(s.ctx, 32768);
assert_eq!(s.kv, "turbo4-3");
assert_eq!(s.backend.as_deref(), Some("vulkan"));
assert_eq!(s.device, vec![1, 0]);
assert_eq!(s.vram_margin, vec!["256", "512"]);
assert_eq!(s.aux, Some(("--mtp-model", PathBuf::from("head.gguf"))));
assert_eq!(s.extra, [
"--k", "q8", "--v", "f16", "--threads", "6", "--cache-ram", "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.

🔵 Low · Maintainability · 2 of 2

Test hand-builds bench_args instead of calling bench_sample/calibrate_v2 arg construction The round-trip test manually assembles bench args (order, --gpu, aux placement, extra placement) rather than invoking the actual bench_sample code. Any divergence in real bench_sample (ordering, env handling, extra flags) passes this test while breaking web calibration in production.

Prompt for your AI agent
File: src/main.rs
Line: 6115
Symbol: spec_space_stores_indices_not_actual_values
Issue: Test hand-builds bench_args instead of calling bench_sample/calibrate_v2 arg construction The round-trip test manually assembles bench args (order, --gpu, aux placement, extra placement) rather than invoking the actual bench_sample code. Any divergence in real bench_sample (ordering, env handling, extra flags) passes this test while breaking web calibration in production.
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch — fixed in 4446f8f by extracting bench_sample_args(...) from bench_sample and having serve_calibrate_forwards_kv_setup_and_aux_flag parse the production bench_sample_args output directly via Cli::try_parse_from.

"--ram-margin", "1024", "--max-ram", "8192", "--cpu-frac", "0.5", "--host-share", "4",
"--arena", "--pin", "--prefill-cpu",
]);

// Every forwarded flag must round-trip cleanly through `bench_sample_args` into `Cmd::Bench`.
let mut bench_args = vec![std::ffi::OsString::from("rustingstrata")];
bench_args.extend(bench_sample_args(&s, &Knobs::default(), &s.pp, s.reps, Path::new("out.json"), None));

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 1

Test uses Knobs::default() so mtp/spec/chunk/short knob selection is never exercised bench_sample_args is tested only with default knobs (all indices 0/defaults), so off-by-one, min-clamping, mtp_values index-vs-value, and spec_type/draft_max/ngram_n selection bugs in the extracted function would pass the test while failing in real sweeps with non-zero knobs.

Prompt for your AI agent
File: src/main.rs
Line: 6136
Symbol: serve_calibrate_forwards_kv_setup_and_aux_flag
Issue: Test uses Knobs::default() so mtp/spec/chunk/short knob selection is never exercised bench_sample_args is tested only with default knobs (all indices 0/defaults), so off-by-one, min-clamping, mtp_values index-vs-value, and spec_type/draft_max/ngram_n selection bugs in the extracted function would pass the test while failing in real sweeps with non-zero knobs.
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch — added bench_sample_args_maps_direct_and_indexed_knobs in 9947bc3 covering non-default direct knobs (chunk, short, mtp without --spec-*), spec sweep index-to-value lookup where index != value (mtp_values, spec_types, draft_max, ngram_n), and upper-bound clamping across all four spec lists, verified via Cli::try_parse_from into Cmd::Bench.

let Some(Cmd::Bench { engine: bench, .. }) = Cli::try_parse_from(&bench_args).unwrap().cmd else { panic!("wrong command") };
assert_eq!(bench.ctx, 32768);
assert_eq!(bench.kv, "turbo4-3");
assert_eq!(bench.k.as_deref(), Some("q8"));
assert_eq!(bench.v.as_deref(), Some("f16"));
assert_eq!(bench.threads, Some(6));
assert_eq!(bench.cache_ram, 0);
assert_eq!(bench.ram_margin, 1024);
assert_eq!(bench.max_ram, 8192);
assert_eq!(bench.cpu_frac, Some(0.5));
assert_eq!(bench.host_share, 4);
assert!(bench.arena && bench.pin && bench.prefill_cpu);
assert_eq!(bench.backend.as_deref(), Some("vulkan"));
assert_eq!(bench.device, vec![1, 0]);
// `calibrate` intentionally uses the free-VRAM split across `--device` and ignores `--split` (docs/CALIBRATION.md).
assert_eq!(bench.split, None);
assert_eq!(bench.vram_margin, vec!["256", "512"]);
assert_eq!(bench.mtp_model, Some(PathBuf::from("head.gguf")));
assert_eq!(bench.draft_model, None);

// Web load options clear stale --k/--v when `kv` is changed and update `threads`/`cache_ram`.
let updated = engine.with(&json!({"kv": "q4", "threads": 8, "cache_ram": 4096})).unwrap();
let s2 = serve_calib_settings(Path::new("m.gguf"), &updated, &[256, 512]);
assert_eq!(s2.kv, "q4");
assert!(!s2.extra.iter().any(|a| a == "--k" || a == "--v" || a == "--cache-ram"));
assert!(s2.extra.windows(2).any(|w| w == ["--threads", "8"]));

// `--draft-model` maps to `--draft-model` (and takes precedence over `--mtp-model`), while defaults emit no extra flags.
let cli_draft = Cli::try_parse_from([
"rustingstrata", "serve", "--model", "m.gguf", "--gpu",
"--mtp-model", "head.gguf", "--draft-model", "draft.gguf",
]).unwrap();
let Some(Cmd::Serve { engine: e_draft, .. }) = cli_draft.cmd else { panic!("wrong command") };
let s_draft = serve_calib_settings(Path::new("m.gguf"), &e_draft, &[512]);
assert_eq!(s_draft.kv, "f16");
assert_eq!(s_draft.aux, Some(("--draft-model", PathBuf::from("draft.gguf"))));
assert!(s_draft.extra.is_empty());
}

#[test]
fn bench_sample_args_maps_direct_and_indexed_knobs() {
let parse = |args: Vec<std::ffi::OsString>| {
let mut argv = vec![std::ffi::OsString::from("rustingstrata")];
argv.extend(args);
let Some(Cmd::Bench { engine, .. }) = Cli::try_parse_from(&argv).unwrap().cmd else { panic!("wrong command") };
engine
};

// Main calibration: chunk, short, and mtp knobs are literal values (no --spec-* flags).
let s = CalibSettings::new(PathBuf::from("m.gguf"));
let mut main_knobs = Knobs::default();
main_knobs.set("chunk", 1024.0);
main_knobs.set("short", 513.0);
main_knobs.set("mtp", 3.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.

🔵 Low · Maintainability · 1 of 1

Test never exercises KV, CalibSetup, or aux-model forwarding claimed by the PR All three bench_sample_args calls pass None for the final argument and never set CalibSettings.kv or extra/setup fields, so a regression dropping --kv, setup flags, or mislabeling --draft-model/--mtp-model still passes this test.

Prompt for your AI agent
File: src/main.rs
Line: 6190
Symbol: the_baseline_chunk_is_each_engines_own_default
Issue: Test never exercises KV, CalibSetup, or aux-model forwarding claimed by the PR All three bench_sample_args calls pass None for the final argument and never set CalibSettings.kv or extra/setup fields, so a regression dropping --kv, setup flags, or mislabeling --draft-model/--mtp-model still passes this test.
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This commit only added bench_sample_args_maps_direct_and_indexed_knobs to cover non-default direct/indexed/clamped knobs (addressing the previous comment); KV, CalibSetup, --vram-margin, --device, and --mtp-model/--draft-model forwarding through bench_sample_args are already covered right above in serve_calibrate_forwards_kv_setup_and_aux_flag (src/main.rs:6110-6174).

let main_args = bench_sample_args(&s, &main_knobs, &[512], 2, Path::new("out.json"), None);
assert!(!main_args.iter().any(|a| a == "--spec-type"));
let bench = parse(main_args);
assert_eq!((bench.chunk, bench.short, bench.mtp), (Some(1024), Some(513), Some(3)));

// Spec sweep: mtp, spec_type, draft_max, and ngram_n are indices (distinct from values) and clamp at len - 1.
let mut spec = CalibSettings::new(PathBuf::from("m.gguf"));
spec.spec_types = vec!["none".into(), "ngram-simple".into(), "ngram-mod".into()];
spec.draft_max = vec![4, 10, 16];
spec.ngram_n = vec![3, 7, 12];
spec.mtp_values = vec![0, 4, 2];
let mut spec_knobs = Knobs::default();
spec_knobs.set("mtp", 1.0); // index 1 -> value 4 (not literal 1)
spec_knobs.set("spec_type", 2.0); // index 2 -> "ngram-mod"
spec_knobs.set("draft_max", 1.0); // index 1 -> value 10 (not literal 1)
spec_knobs.set("ngram_n", 99.0); // out-of-range -> clamps to last element 12
let bench = parse(bench_sample_args(&spec, &spec_knobs, &[512], 2, Path::new("out.json"), None));
assert_eq!(bench.mtp, Some(4));
assert_eq!(bench.spec_type, "ngram-mod");
assert_eq!(bench.spec_draft_n_max, 10);
assert_eq!(bench.spec_ngram_size_n, 12);

// Out-of-range mtp / spec_type / draft_max indices also clamp safely to the last entry.
let mut clamped = Knobs::default();
clamped.set("mtp", 99.0);
clamped.set("spec_type", 99.0);
clamped.set("draft_max", 99.0);
clamped.set("ngram_n", 1.0); // index 1 -> value 7
let bench = parse(bench_sample_args(&spec, &clamped, &[512], 2, Path::new("out.json"), None));
assert_eq!(bench.mtp, Some(2));
assert_eq!(bench.spec_type, "ngram-mod");
assert_eq!(bench.spec_draft_n_max, 16);
assert_eq!(bench.spec_ngram_size_n, 7);
}

#[test]
fn cli_parses_the_spec_subcommand() {
let cli = Cli::try_parse_from([
Expand Down
Loading