bench.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. //! `sm121 bench` — run `tool-eval-bench` against a live serve and land the
  2. //! reports in `recipes/<lane>/reports/`. The tool needs a scratch cwd (it
  3. //! writes `runs/<date>/<run>.md` relative to cwd), an absolute `--json-file`
  4. //! path, and the `.md` copied into the lane — this command does the
  5. //! babysitting. Campaign convention (seed 42, hardmode, perf, c1,2) is the
  6. //! default; `sm121 bench -d` prints the exact command.
  7. use std::fs;
  8. use std::path::PathBuf;
  9. use anyhow::Result;
  10. use crate::bench_target::{pick_head, run_tool, sanitize, served_model};
  11. use crate::config::{Config, load_recipe, select_cluster_by_name};
  12. /// Fields of the `sm121 bench` subcommand (mirrored by the clap variant in
  13. /// `cli.rs`). Served name/port come from the recipe; the tool is on PATH.
  14. #[derive(Clone)]
  15. pub struct Args {
  16. pub recipe: String,
  17. pub cluster: String,
  18. pub label: Option<String>,
  19. pub concurrency: String,
  20. pub seed: u64,
  21. /// Scenario streams run concurrently (tool `--parallel`; None = serial).
  22. pub parallel: Option<u32>,
  23. /// Skip the scenario phase (tool `--perf-only`).
  24. pub perf_only: bool,
  25. /// Run the context-depth suite (16K..256K) after the main pass — off by
  26. /// default (a full sweep takes ~45 min on a 2x lane).
  27. pub depth: bool,
  28. /// Local tokenizer source for llama-benchy (tool `--tokenizer`): a
  29. /// tokenizer.json or a dir holding one. Needed when the served model
  30. /// id is not resolvable in the local HF cache (custom export lanes).
  31. pub tokenizer: Option<String>,
  32. /// When set, the tool-eval-bench invocation runs on this host over SSH
  33. /// (the local machine only orchestrates), keeping the bench client's own
  34. /// network (e.g. a WiFi laptop) off the measurement path. The tokenizer
  35. /// is uploaded to the host; the report + run package land locally. The
  36. /// host must have `tool-eval-bench` on PATH and reach the serve.
  37. pub ssh_host: Option<String>,
  38. /// Bench target node within the cluster (default: rank 0). Use when the
  39. /// serve was launched with `serve --node <n>` — a pinned/solo run may
  40. /// live on a non-rank-0 node, and benching the wrong head measures a
  41. /// different (or no) engine.
  42. pub node: Option<String>,
  43. /// Disable thinking/reasoning in the harness (tool `--no-think`, sets
  44. /// `enable_thinking=false`). Needed for thinking-by-default models (Ling,
  45. /// GLM-4.5-style) whose long default reasoning blows the per-turn timeout
  46. /// and excludes most scenarios.
  47. pub no_think: bool,
  48. /// Per-turn request timeout seconds forwarded to the harness (tool
  49. /// `--timeout`). Raise above the 120 s default for slow/thinking models.
  50. pub timeout: Option<u64>,
  51. }
  52. /// Served model name from the recipe's `--served-model-name` arg.
  53. /// Run the bench and land `recipes/<lane>/reports/<stamp>_<label>.{md,json,log}`.
  54. pub async fn run(config: &Config, a: &Args, dry_run: bool) -> Result<()> {
  55. let recipe = load_recipe(&a.recipe, &config.recipe_sources).await?;
  56. let file = crate::config::recipe_file(&a.recipe, &config.recipe_sources)
  57. .ok_or_else(|| anyhow::anyhow!("recipe file not found for '{}'", a.recipe))?
  58. .canonicalize()?;
  59. let cluster = select_cluster_by_name(config, &a.cluster)?;
  60. let head = pick_head(&cluster.nodes, &cluster.name, a.node.as_deref())?;
  61. let port = recipe.port;
  62. let model = served_model(&recipe).ok_or_else(|| {
  63. anyhow::anyhow!(
  64. "recipe '{}' has no --served-model-name in args — add it to the recipe",
  65. a.recipe
  66. )
  67. })?;
  68. let base_url = format!("http://{}:{}/v1", head.ssh_ip, port);
  69. let stamp = crate::stamp::utc_stamp();
  70. // Label: required for quality runs, optional for perf-only (default `perf`).
  71. let label = match (&a.label, a.perf_only) {
  72. (Some(l), _) => sanitize(l),
  73. (None, true) => String::from("perf"),
  74. (None, false) => {
  75. anyhow::bail!("--label is required for a quality run (the campaign record)")
  76. }
  77. };
  78. let stem = format!("{stamp}_{label}");
  79. let reports_dir = file
  80. .parent()
  81. .ok_or_else(|| anyhow::anyhow!("no parent dir for {}", file.display()))?
  82. .join("reports");
  83. let log_path = reports_dir.join(format!("{stamp}_{label}.log"));
  84. let ssh_host = a.ssh_host.as_deref();
  85. // The local scratch dir (the report reads the md + json from here). For
  86. // the remote host the tool writes to a remote scratch dir; its md/json are
  87. // downloaded here after the run so the local report generation is unchanged.
  88. let scratch = dirs::home_dir()
  89. .ok_or_else(|| anyhow::anyhow!("no home dir"))?
  90. .join(".cache/sm121/bench")
  91. .join(&stem);
  92. // The scratch dir the tool writes to (local by default, or the remote host
  93. // when `--ssh-host` is set — the bench client's network then stays off the
  94. // measurement path).
  95. let tool_scratch = if ssh_host.is_some() {
  96. PathBuf::from(format!("/tmp/sm121-bench-{stem}"))
  97. } else {
  98. scratch.clone()
  99. };
  100. // The local json path (the report reads it).
  101. let json_path = reports_dir.join(format!("{stamp}_{label}.json"));
  102. // The json path the tool writes to (local by default, or the remote host).
  103. let tool_json = if ssh_host.is_some() {
  104. tool_scratch.join(format!("{stem}.json"))
  105. } else {
  106. json_path.clone()
  107. };
  108. let bin = "tool-eval-bench".to_string();
  109. // The tokenizer path the tool uses (local by default, or the remote
  110. // scratch dir when `--ssh-host` is set — the tokenizer is uploaded there).
  111. let tool_tokenizer = if ssh_host.is_some() {
  112. a.tokenizer.as_ref().map(|tok| {
  113. let name = tok.rsplit('/').next().unwrap_or("tokenizer");
  114. tool_scratch.join(name).to_string_lossy().to_string()
  115. })
  116. } else {
  117. a.tokenizer.clone()
  118. };
  119. let depth_scratch = tool_scratch.with_file_name(format!("{stem}_depth"));
  120. let depth_args =
  121. crate::bench_depth::depth_args(&base_url, &model, a.seed, tool_tokenizer.as_ref());
  122. let mut args = vec![
  123. "--base-url".into(),
  124. base_url.clone(),
  125. "--model".into(),
  126. model.clone(),
  127. "--seed".into(),
  128. a.seed.to_string(),
  129. "--hardmode".into(),
  130. "--perf".into(),
  131. // Warm-prefix decode: without it llama-benchy's default branch
  132. // serializes dual 67K prefills (c2 collapses to 13.7 t/s — an
  133. // admission artifact, not the engine; 2026-09-29 diagnosis).
  134. "--benchy-args=--enable-prefix-caching".into(),
  135. "--concurrency".into(),
  136. a.concurrency.clone(),
  137. "--json-file".into(),
  138. tool_json.to_string_lossy().to_string(),
  139. ];
  140. if let Some(p) = a.parallel {
  141. args.push("--parallel".into());
  142. args.push(p.to_string());
  143. }
  144. if a.perf_only {
  145. args.push("--perf-only".into());
  146. }
  147. if let Some(tok) = &tool_tokenizer {
  148. args.push("--tokenizer".into());
  149. args.push(tok.clone());
  150. }
  151. if a.no_think {
  152. args.push("--no-think".into());
  153. }
  154. if let Some(t) = a.timeout {
  155. args.push("--timeout".into());
  156. args.push(t.to_string());
  157. }
  158. if dry_run {
  159. println!("bench: cwd {}", tool_scratch.display());
  160. println!("bench: {} {}", bin, args.join(" "));
  161. println!("bench: depth suite: {} {}", bin, depth_args.join(" "));
  162. println!(
  163. "bench: reports -> {} (run package: {}.recipe.toml + {}.manifest.json)",
  164. reports_dir.display(),
  165. stem,
  166. stem
  167. );
  168. return Ok(());
  169. }
  170. if let Some(host) = ssh_host {
  171. crate::bench_remote::prepare(host, &tool_scratch, &a.tokenizer)?;
  172. } else {
  173. fs::create_dir_all(&scratch)?;
  174. }
  175. fs::create_dir_all(&reports_dir)?;
  176. eprintln!("bench: waiting for {base_url} ...");
  177. crate::readiness::wait_ready(&base_url, crate::readiness::BENCH_WAIT_SECS).await?;
  178. eprintln!("bench: API ready — running {} (seed {})", bin, a.seed);
  179. let code = run_tool(&bin, &args, &tool_scratch, &log_path, false, ssh_host)?;
  180. if code != 0 {
  181. anyhow::bail!(
  182. "bench: tool exited with {code} (log: {})",
  183. log_path.display()
  184. );
  185. }
  186. // Phase 2 — context-depth suite (16K..256K @ c2, 2 repeats): appended
  187. // to the same log so `parse_perf_rows` picks its rows up too. A depth
  188. // failure must not cost the finished quality run — warn, keep going.
  189. // Opt-in (`--depth`): a full sweep takes ~45 min on a 2x lane.
  190. if a.depth {
  191. eprintln!(
  192. "bench: depth suite: {} @ c{}, {} repeats{}",
  193. crate::bench_depth::DEPTHS,
  194. crate::bench_depth::CONCURRENCY,
  195. crate::bench_depth::RUNS,
  196. if a.tokenizer.is_some() {
  197. " (+tokenizer)"
  198. } else {
  199. ""
  200. }
  201. );
  202. fs::create_dir_all(&depth_scratch)?;
  203. let dcode = run_tool(&bin, &depth_args, &depth_scratch, &log_path, true, ssh_host)?;
  204. if dcode != 0 {
  205. eprintln!(
  206. "bench: WARNING depth suite exited with {dcode} — main report unaffected ({})",
  207. log_path.display()
  208. );
  209. }
  210. } else {
  211. eprintln!("bench: depth suite skipped (opt-in: --depth)");
  212. }
  213. // Remote host: download the json + the md from the remote scratch dir so
  214. // the local report generation is unchanged.
  215. if let Some(host) = ssh_host {
  216. crate::bench_remote::collect(
  217. host,
  218. &tool_json,
  219. &json_path,
  220. &tool_scratch,
  221. &scratch,
  222. !a.perf_only,
  223. )?;
  224. }
  225. let md_src = crate::bench_io::latest_md(&scratch)
  226. .ok_or_else(|| anyhow::anyhow!("no report .md under {}", scratch.join("runs").display()))?;
  227. let md_dest = reports_dir.join(format!("{stamp}_{label}.md"));
  228. fs::copy(&md_src, &md_dest)?;
  229. // The `--json-file` dispatch path drops the perf section from the md —
  230. // re-attach it from the llama-benchy table in the log.
  231. if crate::bench_report::ensure_throughput_section(&md_dest, &log_path).is_ok_and(|m| m) {
  232. eprintln!("bench: appended the perf table to the report md");
  233. }
  234. // Summary: final score from the JSON + the perf table from the log.
  235. // Perf-only runs have no quality score and the tool writes no JSON —
  236. // the run package is skipped for them (the campaign run is the record).
  237. let j = match a.perf_only {
  238. true => {
  239. eprintln!("bench: perf-only run (no quality score, no run package)");
  240. None
  241. }
  242. false => {
  243. let j: serde_json::Value = serde_json::from_str(&fs::read_to_string(&json_path)?)?;
  244. let sc = &j["scores"];
  245. let final_score = sc["final_score"].as_u64();
  246. if let Some(score) = final_score {
  247. let completion = sc["completion_rate"]
  248. .as_f64()
  249. .map(|v| v.to_string())
  250. .unwrap_or_default();
  251. eprintln!(
  252. "bench: final score {score} / {} ({} points), completion {completion}",
  253. sc["max_points"], sc["total_points"]
  254. );
  255. } else {
  256. eprintln!("bench: perf-only run (no quality score)");
  257. }
  258. Some(j)
  259. }
  260. };
  261. for line in fs::read_to_string(&log_path)?.lines() {
  262. if line.contains("pp2048") && line.contains("tg128") {
  263. println!("{line}");
  264. }
  265. }
  266. if let Some(j) = &j {
  267. crate::bench_artifacts::write_run_package(&crate::bench_artifacts::RunPackage {
  268. config,
  269. cluster: &cluster,
  270. recipe: &recipe,
  271. recipe_file: &file,
  272. stem: stem.as_str(),
  273. reports_dir: &reports_dir,
  274. bench_args: &args,
  275. bench_json: j,
  276. })
  277. .await?;
  278. }
  279. eprintln!("bench: reports landed in {}", reports_dir.display());
  280. Ok(())
  281. }
  282. #[cfg(test)]
  283. mod tests {
  284. use super::*;
  285. use crate::config::{Node, Recipe};
  286. use std::process::{Command, Stdio};
  287. use std::sync::{Arc, Mutex};
  288. fn node(name: &str, rank: u32) -> Node {
  289. Node {
  290. name: name.to_string(),
  291. ssh_ip: "192.0.2.1".into(),
  292. ib_ip: None,
  293. rank,
  294. host_key: None,
  295. entity: None,
  296. }
  297. }
  298. #[test]
  299. fn pick_head_defaults_to_rank0() {
  300. let nodes = vec![node("a.lan", 2), node("b.lan", 0), node("c.lan", 1)];
  301. assert_eq!(pick_head(&nodes, "c", None).unwrap().name, "b.lan");
  302. }
  303. #[test]
  304. fn pick_head_node_override_tolerates_lan_suffix() {
  305. let nodes = vec![node("a.lan", 2), node("b.lan", 0)];
  306. assert_eq!(pick_head(&nodes, "c", Some("a")).unwrap().name, "a.lan");
  307. assert_eq!(pick_head(&nodes, "c", Some("b.lan")).unwrap().name, "b.lan");
  308. assert!(pick_head(&nodes, "c", Some("zzz")).is_err());
  309. }
  310. /// Regression: the pump must not treat a not-yet-written pipe as EOF.
  311. /// `read()` into a zero-length buffer returns 0, which the old pump
  312. /// treated as EOF — closing the pipe and killing the child on its first
  313. /// stderr write with EPIPE (silent exit 120 in CPython).
  314. #[test]
  315. fn pump_keeps_pipe_open_until_child_exits() {
  316. let tmp =
  317. std::env::temp_dir().join(format!("sm121-bench-pump-test-{}", std::process::id()));
  318. fs::create_dir_all(&tmp).unwrap();
  319. let log = tmp.join("pump.log");
  320. let mut child = Command::new("sh")
  321. .args(["-c", "sleep 0.3; echo late-output >&2"])
  322. .stdout(Stdio::piped())
  323. .stderr(Stdio::piped())
  324. .spawn()
  325. .unwrap();
  326. let out = child.stdout.take().unwrap();
  327. let err = child.stderr.take().unwrap();
  328. let f = Arc::new(Mutex::new(fs::File::create(&log).unwrap()));
  329. let f1 = f.clone();
  330. let t1 = std::thread::spawn(move || crate::bench_io::pump(out, false, f1));
  331. let t2 = std::thread::spawn(move || crate::bench_io::pump(err, false, f));
  332. let status = child.wait().unwrap();
  333. t1.join().unwrap();
  334. t2.join().unwrap();
  335. let body = fs::read_to_string(&log).unwrap();
  336. assert_eq!(status.code(), Some(0), "child must not hit EPIPE: {body}");
  337. assert!(body.contains("late-output"), "piped stderr lost: {body:?}");
  338. let _ = fs::remove_dir_all(&tmp);
  339. }
  340. #[test]
  341. fn sanitize_replaces_bad_chars() {
  342. assert_eq!(sanitize("arm B: 2x"), "arm-B--2x");
  343. assert_eq!(sanitize("ok_name-2.v3"), "ok_name-2.v3");
  344. }
  345. /// The non-interactive env must reach the child through the `script`
  346. /// pty wrapper — rich reads TTY_COMPATIBLE from the child's env. Also:
  347. /// `stty -onlcr` must hold, so the saved log is LF-only (CRLF made the
  348. /// report viewer render every line twice).
  349. #[test]
  350. fn run_tool_passes_non_interactive_env() {
  351. let tmp = std::env::temp_dir().join(format!("sm121-bench-env-test-{}", std::process::id()));
  352. fs::create_dir_all(&tmp).unwrap();
  353. let log = tmp.join("env.log");
  354. let code = run_tool(
  355. "sh",
  356. &[
  357. "-c".to_string(),
  358. "echo TTY=$TTY_COMPATIBLE NO=$NO_COLOR".to_string(),
  359. ],
  360. &tmp,
  361. &log,
  362. false,
  363. None,
  364. )
  365. .unwrap();
  366. let body = fs::read_to_string(&log).unwrap();
  367. let _ = fs::remove_dir_all(&tmp);
  368. assert_eq!(code, 0, "exit code, log: {body:?}");
  369. assert!(body.contains("TTY=0"), "TTY_COMPATIBLE lost: {body:?}");
  370. assert!(body.contains("NO=1"), "NO_COLOR lost: {body:?}");
  371. assert!(!body.contains('\r'), "pty ONLCR leaked CRLF: {body:?}");
  372. }
  373. /// The append mode must not truncate the main phase's log — the depth
  374. /// suite shares it so one report carries both tables.
  375. #[test]
  376. fn run_tool_append_keeps_prior_output() {
  377. let tmp =
  378. std::env::temp_dir().join(format!("sm121-bench-append-test-{}", std::process::id()));
  379. fs::create_dir_all(&tmp).unwrap();
  380. let log = tmp.join("append.log");
  381. let run = |a: &str, append| {
  382. run_tool("sh", &["-c".into(), a.into()], &tmp, &log, append, None).unwrap()
  383. };
  384. assert_eq!(run("echo main", false), 0);
  385. assert!(fs::read_to_string(&log).unwrap().contains("main\n"));
  386. assert_eq!(run("echo depth", true), 0);
  387. let body = fs::read_to_string(&log).unwrap();
  388. let (i1, i2) = (body.find("main\n"), body.find("depth\n"));
  389. assert!(
  390. i1.is_some() && i2.is_some_and(|d| i1.unwrap() < d),
  391. "append truncated the log: {body:?}"
  392. );
  393. let _ = fs::remove_dir_all(&tmp);
  394. }
  395. #[test]
  396. fn served_model_parsed_from_args() {
  397. let content = "name = \"t\"\ndocker_image = \"x:1\"\nmodel = \"org/m\"\nargs = [\"--served-model-name\", \"glm53\"]\n";
  398. let r: Recipe = toml::from_str(content).expect("recipe toml");
  399. assert_eq!(served_model(&r).as_deref(), Some("glm53"));
  400. let mut r2 = r.clone();
  401. r2.args = crate::pre_serve::RecipeArgs::List(vec!["--trust-remote-code".into()]);
  402. assert!(served_model(&r2).is_none());
  403. }
  404. }