bench.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. //! `sm121 bench` — run `tool-eval-bench` against a live serve and land the
  2. //! reports in the repo.
  3. //!
  4. //! The bench tool needs babysitting this command does instead of the
  5. //! operator: it must run in a scratch cwd (it writes
  6. //! `runs/<date>/<run>.md` relative to cwd), needs an absolute `--json-file`
  7. //! path, and the `.md` report must be copied into
  8. //! `recipes/<lane>/reports/<UTC-date>_<label>.{md,json,log}` by hand.
  9. //! Campaign convention (seed 42, hardmode, perf, concurrency 1,2) is the
  10. //! default; `sm121 bench -d` prints the exact command.
  11. use std::fs;
  12. use std::io::{Read, Write};
  13. use std::path::{Path, PathBuf};
  14. use std::process::Stdio;
  15. use std::sync::{Arc, Mutex};
  16. use std::time::SystemTime;
  17. use anyhow::Result;
  18. use crate::ansi::strip_ansi_step;
  19. use crate::config::{Config, Recipe, load_recipe, select_cluster_by_name};
  20. /// Fields of the `sm121 bench` subcommand (mirrored by the clap variant in
  21. /// `cli.rs`). Served model name and port come from the recipe
  22. /// (`--served-model-name` in args / `port`); the bench binary is looked up on PATH.
  23. #[derive(Clone)]
  24. pub struct Args {
  25. pub recipe: String,
  26. pub cluster: String,
  27. pub label: String,
  28. pub concurrency: String,
  29. pub seed: u64,
  30. /// Scenario streams run concurrently (tool `--parallel`). None = the
  31. /// tool default (serial), preserving earlier lanes' comparability.
  32. pub parallel: Option<u32>,
  33. /// Skip the scenario phase (tool `--perf-only`).
  34. pub perf_only: bool,
  35. /// Local tokenizer source for llama-benchy (tool `--tokenizer`): a
  36. /// tokenizer.json or a dir holding one. Needed when the served model
  37. /// id is not resolvable in the local HF cache (custom export lanes).
  38. pub tokenizer: Option<String>,
  39. }
  40. /// Served model name from the recipe's `--served-model-name` arg.
  41. fn served_model(recipe: &Recipe) -> Option<String> {
  42. let args = recipe.args.to_vec();
  43. args.iter()
  44. .position(|s| s == "--served-model-name")
  45. .and_then(|i| args.get(i + 1))
  46. .cloned()
  47. }
  48. /// Keep the label filesystem-safe.
  49. fn sanitize(label: &str) -> String {
  50. label
  51. .chars()
  52. .map(|c| {
  53. if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
  54. c
  55. } else {
  56. '-'
  57. }
  58. })
  59. .collect()
  60. }
  61. /// Tee one output pipe to the console and the log file.
  62. ///
  63. /// The console copy keeps the child's ANSI colors; the file copy is
  64. /// stripped (state machine below) so the saved .log stays readable in
  65. /// `sm121 report` and under grep/less.
  66. ///
  67. /// The read buffer must not be empty: `read()` on a zero-length slice
  68. /// returns 0 (interpreted as EOF), so an empty `Vec` would silently sever
  69. /// the pipe — the child then dies on its first stderr write with EPIPE
  70. /// (silent exit 120 in CPython).
  71. fn pump<R: Read>(mut reader: R, to_console: bool, file: Arc<Mutex<fs::File>>) {
  72. let mut buf = vec![0u8; 8192];
  73. let mut carry = Vec::new(); // trailing partial escape across chunks
  74. let mut clean = Vec::new();
  75. loop {
  76. let n = match reader.read(&mut buf) {
  77. Ok(n) => n,
  78. Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
  79. Err(e) => panic!("reading bench output pipe: {e}"),
  80. };
  81. if n == 0 {
  82. break;
  83. }
  84. if to_console {
  85. std::io::stdout().write_all(&buf[..n]).ok();
  86. }
  87. carry.extend_from_slice(&buf[..n]);
  88. strip_ansi_step(&mut carry, &mut clean);
  89. if !clean.is_empty() {
  90. if let Ok(mut f) = file.lock() {
  91. f.write_all(&clean).ok();
  92. }
  93. clean.clear();
  94. }
  95. }
  96. }
  97. /// Run the bench tool in `cwd`, teeing stdout+stderr to the console and the
  98. /// log file; returns the exit code.
  99. ///
  100. /// `append_log = false` truncates the log (main campaign phase); `true`
  101. /// appends (the depth-suite phase shares one log so its rows land in the
  102. /// report's Throughput table).
  103. ///
  104. /// The child runs under a pty (`script -q /dev/null`) instead of raw pipes:
  105. /// tool-eval-bench's rich Live display deadlocks on a non-tty stdout pipe
  106. /// right after the perf phase (deterministic on the 2x lane; 4x runs got
  107. /// lucky) while it runs clean on a tty, exactly as in an interactive
  108. /// terminal (2026-09-09). `script` is BSD/macOS form (the launcher is a
  109. /// Mac tool); if it is absent we fall back to the direct exec.
  110. ///
  111. /// The pty makes the tool think it is interactive — rich redraws its
  112. /// spinner/progress bars in place (\r soup on one line) and that soup
  113. /// leaked into the saved .log, even shadowing real parser cells
  114. /// (glm53-flash-eugr-2x, 2026-09-12). `TTY_COMPATIBLE=0` is rich's own
  115. /// knob for this: the console renders non-interactively (progress bars
  116. /// stay silent during the run, one final frame at the end) while the pty
  117. /// keeps the deadlock workaround intact. `NO_COLOR=1` covers non-rich
  118. /// output. Verified locally under `script`: 1.3 KB/8 CR of soup → 141
  119. /// bytes/1 static final frame.
  120. fn run_tool(
  121. bin: &str,
  122. args: &[String],
  123. cwd: &Path,
  124. log_path: &Path,
  125. append_log: bool,
  126. ) -> Result<i32> {
  127. let file = Arc::new(Mutex::new(if append_log {
  128. fs::OpenOptions::new()
  129. .create(true)
  130. .append(true)
  131. .open(log_path)?
  132. } else {
  133. fs::File::create(log_path)?
  134. }));
  135. let mut cmd = if std::process::Command::new("/usr/bin/script")
  136. .arg("-q")
  137. .arg("/dev/null")
  138. .arg("true")
  139. .output()
  140. .is_ok()
  141. {
  142. // Wrap in `sh` + `stty -onlcr`: the macOS pty's ONLCR would turn every
  143. // `\n` the tool writes into `\r\n` on disk, and the report viewer
  144. // then renders each line twice (blank line after every line).
  145. // `stty -onlcr` disables the post-processing at the source; `exec`
  146. // replaces the shell so the tool keeps the pty and the exit code.
  147. let mut c = std::process::Command::new("/usr/bin/script");
  148. c.arg("-q");
  149. c.arg("/dev/null");
  150. c.arg("sh");
  151. c.arg("-c");
  152. c.arg("stty -onlcr 2>/dev/null; exec \"$@\"");
  153. c.arg("sh"); // $0 inside the -c script
  154. c.arg(bin);
  155. c.args(args);
  156. c
  157. } else {
  158. let mut c = std::process::Command::new(bin);
  159. c.args(args);
  160. c
  161. };
  162. cmd.current_dir(cwd);
  163. cmd.env("TTY_COMPATIBLE", "0");
  164. cmd.env("NO_COLOR", "1");
  165. cmd.stdout(Stdio::piped());
  166. cmd.stderr(Stdio::piped());
  167. let mut child = cmd.spawn()?;
  168. let stdout_pipe = child.stdout.take().expect("stdout pipe");
  169. let stderr_pipe = child.stderr.take().expect("stderr pipe");
  170. let f1 = file.clone();
  171. let t1 = std::thread::spawn(move || pump(stdout_pipe, true, f1));
  172. let t2 = std::thread::spawn(move || pump(stderr_pipe, false, file));
  173. let status = child.wait()?;
  174. t1.join().ok();
  175. t2.join().ok();
  176. Ok(status.code().unwrap_or(-1))
  177. }
  178. /// Newest `.md` under `scratch/runs/` (the tool's `runs/<date>/<run>.md`).
  179. fn latest_md(scratch: &Path) -> Option<PathBuf> {
  180. let runs = scratch.join("runs");
  181. let mut best: Option<(std::time::SystemTime, PathBuf)> = None;
  182. let mut stack = vec![runs];
  183. while let Some(dir) = stack.pop() {
  184. let entries = fs::read_dir(dir).ok()?;
  185. for e in entries.flatten() {
  186. let p = e.path();
  187. if p.is_dir() {
  188. stack.push(p);
  189. } else if p.extension().is_some_and(|x| x == "md") {
  190. let t = e
  191. .metadata()
  192. .and_then(|m| m.modified())
  193. .ok()
  194. .unwrap_or(SystemTime::UNIX_EPOCH);
  195. if best.as_ref().is_none_or(|(bt, _)| t > *bt) {
  196. best = Some((t, p));
  197. }
  198. }
  199. }
  200. }
  201. best.map(|(_, p)| p)
  202. }
  203. /// Run the bench and land `recipes/<lane>/reports/<stamp>_<label>.{md,json,log}`.
  204. pub async fn run(config: &Config, a: &Args, dry_run: bool) -> Result<()> {
  205. let recipe = load_recipe(&a.recipe, &config.recipe_sources).await?;
  206. let file = crate::config::recipe_file(&a.recipe, &config.recipe_sources)
  207. .ok_or_else(|| anyhow::anyhow!("recipe file not found for '{}'", a.recipe))?
  208. .canonicalize()?;
  209. let cluster = select_cluster_by_name(config, &a.cluster)?;
  210. let head = match cluster.nodes.iter().find(|n| n.rank == 0) {
  211. Some(n) => n,
  212. None => cluster
  213. .nodes
  214. .first()
  215. .ok_or_else(|| anyhow::anyhow!("cluster '{}' has no nodes", cluster.name))?,
  216. };
  217. let port = recipe.port;
  218. let model = served_model(&recipe).ok_or_else(|| {
  219. anyhow::anyhow!(
  220. "recipe '{}' has no --served-model-name in args — add it to the recipe",
  221. a.recipe
  222. )
  223. })?;
  224. let base_url = format!("http://{}:{}/v1", head.ssh_ip, port);
  225. let stamp = crate::stamp::utc_stamp();
  226. let label = sanitize(&a.label);
  227. let stem = format!("{stamp}_{label}");
  228. let reports_dir = file
  229. .parent()
  230. .ok_or_else(|| anyhow::anyhow!("no parent dir for {}", file.display()))?
  231. .join("reports");
  232. let json_path = reports_dir.join(format!("{stamp}_{label}.json"));
  233. let log_path = reports_dir.join(format!("{stamp}_{label}.log"));
  234. let scratch = dirs::home_dir()
  235. .ok_or_else(|| anyhow::anyhow!("no home dir"))?
  236. .join(".cache")
  237. .join("sm121")
  238. .join("bench")
  239. .join(format!("{stamp}_{label}"));
  240. let bin = "tool-eval-bench".to_string();
  241. let depth_scratch = scratch.with_file_name(format!("{stem}_depth"));
  242. let depth_args =
  243. crate::bench_depth::depth_args(&base_url, &model, a.seed, a.tokenizer.as_ref());
  244. let mut args = vec![
  245. "--base-url".into(),
  246. base_url.clone(),
  247. "--model".into(),
  248. model.clone(),
  249. "--seed".into(),
  250. a.seed.to_string(),
  251. "--hardmode".into(),
  252. "--perf".into(),
  253. "--concurrency".into(),
  254. a.concurrency.clone(),
  255. "--json-file".into(),
  256. json_path.to_string_lossy().to_string(),
  257. ];
  258. if let Some(p) = a.parallel {
  259. args.push("--parallel".into());
  260. args.push(p.to_string());
  261. }
  262. if a.perf_only {
  263. args.push("--perf-only".into());
  264. }
  265. if let Some(tok) = &a.tokenizer {
  266. args.push("--tokenizer".into());
  267. args.push(tok.clone());
  268. }
  269. if dry_run {
  270. println!("bench: cwd {}", scratch.display());
  271. println!("bench: {} {}", bin, args.join(" "));
  272. println!("bench: depth suite: {} {}", bin, depth_args.join(" "));
  273. println!("bench: reports -> {}", reports_dir.display());
  274. println!(
  275. "bench: run package -> {}.recipe.toml + {}.manifest.json",
  276. stem, stem
  277. );
  278. return Ok(());
  279. }
  280. fs::create_dir_all(&scratch)?;
  281. fs::create_dir_all(&reports_dir)?;
  282. eprintln!("bench: waiting for {base_url} ...");
  283. crate::readiness::wait_ready(&base_url, crate::readiness::BENCH_WAIT_SECS).await?;
  284. eprintln!("bench: API ready — running {} (seed {})", bin, a.seed);
  285. let code = run_tool(&bin, &args, &scratch, &log_path, false)?;
  286. if code != 0 {
  287. anyhow::bail!(
  288. "bench: tool exited with {code} (log: {})",
  289. log_path.display()
  290. );
  291. }
  292. // Phase 2 — context-depth suite (16K..256K @ c2, 2 repeats): appended
  293. // to the same log so `parse_perf_rows` picks its rows up too. A depth
  294. // failure must not cost the finished quality run — warn, keep going.
  295. eprintln!(
  296. "bench: depth suite: {} @ c{}, {} repeats{}",
  297. crate::bench_depth::DEPTHS,
  298. crate::bench_depth::CONCURRENCY,
  299. crate::bench_depth::RUNS,
  300. if a.tokenizer.is_some() {
  301. " (+tokenizer)"
  302. } else {
  303. ""
  304. }
  305. );
  306. fs::create_dir_all(&depth_scratch)?;
  307. let dcode = run_tool(&bin, &depth_args, &depth_scratch, &log_path, true)?;
  308. if dcode != 0 {
  309. eprintln!(
  310. "bench: WARNING depth suite exited with {dcode} — main report unaffected ({})",
  311. log_path.display()
  312. );
  313. }
  314. let md_src = latest_md(&scratch)
  315. .ok_or_else(|| anyhow::anyhow!("no report .md under {}", scratch.join("runs").display()))?;
  316. let md_dest = reports_dir.join(format!("{stamp}_{label}.md"));
  317. fs::copy(&md_src, &md_dest)?;
  318. // The `--json-file` dispatch path drops the perf section from the md —
  319. // re-attach it from the llama-benchy table in the log.
  320. if crate::bench_report::ensure_throughput_section(&md_dest, &log_path).is_ok_and(|m| m) {
  321. eprintln!("bench: appended the perf table to the report md");
  322. }
  323. // Summary: final score from the JSON + the perf table from the log.
  324. // Perf-only runs have no quality score and the tool writes no JSON —
  325. // the run package is skipped for them (the campaign run is the record).
  326. let j = match a.perf_only {
  327. true => {
  328. eprintln!("bench: perf-only run (no quality score, no run package)");
  329. None
  330. }
  331. false => {
  332. let j: serde_json::Value = serde_json::from_str(&fs::read_to_string(&json_path)?)?;
  333. let sc = &j["scores"];
  334. let final_score = sc["final_score"].as_u64();
  335. if let Some(score) = final_score {
  336. let completion = sc["completion_rate"]
  337. .as_f64()
  338. .map(|v| v.to_string())
  339. .unwrap_or_default();
  340. eprintln!(
  341. "bench: final score {score} / {} ({} points), completion {completion}",
  342. sc["max_points"], sc["total_points"]
  343. );
  344. } else {
  345. eprintln!("bench: perf-only run (no quality score)");
  346. }
  347. Some(j)
  348. }
  349. };
  350. for line in fs::read_to_string(&log_path)?.lines() {
  351. if line.contains("pp2048") && line.contains("tg128") {
  352. println!("{line}");
  353. }
  354. }
  355. if let Some(j) = &j {
  356. crate::bench_artifacts::write_run_package(&crate::bench_artifacts::RunPackage {
  357. config,
  358. cluster: &cluster,
  359. recipe: &recipe,
  360. recipe_file: &file,
  361. stem: stem.as_str(),
  362. reports_dir: &reports_dir,
  363. bench_args: &args,
  364. bench_json: j,
  365. })
  366. .await?;
  367. }
  368. eprintln!("bench: reports landed in {}", reports_dir.display());
  369. Ok(())
  370. }
  371. #[cfg(test)]
  372. mod tests {
  373. use super::*;
  374. use std::process::Command;
  375. /// Regression: the pump must not treat a not-yet-written pipe as EOF.
  376. /// `read()` into a zero-length buffer returns 0, which the old pump
  377. /// treated as EOF — closing the pipe and killing the child on its first
  378. /// stderr write with EPIPE (silent exit 120 in CPython).
  379. #[test]
  380. fn pump_keeps_pipe_open_until_child_exits() {
  381. let tmp =
  382. std::env::temp_dir().join(format!("sm121-bench-pump-test-{}", std::process::id()));
  383. fs::create_dir_all(&tmp).unwrap();
  384. let log = tmp.join("pump.log");
  385. let mut child = Command::new("sh")
  386. .args(["-c", "sleep 0.3; echo late-output >&2"])
  387. .stdout(Stdio::piped())
  388. .stderr(Stdio::piped())
  389. .spawn()
  390. .unwrap();
  391. let out = child.stdout.take().unwrap();
  392. let err = child.stderr.take().unwrap();
  393. let f = Arc::new(Mutex::new(fs::File::create(&log).unwrap()));
  394. let f1 = f.clone();
  395. let t1 = std::thread::spawn(move || pump(out, false, f1));
  396. let t2 = std::thread::spawn(move || pump(err, false, f));
  397. let status = child.wait().unwrap();
  398. t1.join().unwrap();
  399. t2.join().unwrap();
  400. let body = fs::read_to_string(&log).unwrap();
  401. assert_eq!(status.code(), Some(0), "child must not hit EPIPE: {body}");
  402. assert!(body.contains("late-output"), "piped stderr lost: {body:?}");
  403. let _ = fs::remove_dir_all(&tmp);
  404. }
  405. #[test]
  406. fn sanitize_replaces_bad_chars() {
  407. assert_eq!(sanitize("arm B: 2x"), "arm-B--2x");
  408. assert_eq!(sanitize("ok_name-2.v3"), "ok_name-2.v3");
  409. }
  410. /// The non-interactive env must reach the child through the `script`
  411. /// pty wrapper — rich reads TTY_COMPATIBLE from the child's env. Also:
  412. /// `stty -onlcr` must hold, so the saved log is LF-only (CRLF made the
  413. /// report viewer render every line twice).
  414. #[test]
  415. fn run_tool_passes_non_interactive_env() {
  416. let tmp = std::env::temp_dir().join(format!("sm121-bench-env-test-{}", std::process::id()));
  417. fs::create_dir_all(&tmp).unwrap();
  418. let log = tmp.join("env.log");
  419. let code = run_tool(
  420. "sh",
  421. &[
  422. "-c".to_string(),
  423. "echo TTY=$TTY_COMPATIBLE NO=$NO_COLOR".to_string(),
  424. ],
  425. &tmp,
  426. &log,
  427. false,
  428. )
  429. .unwrap();
  430. let body = fs::read_to_string(&log).unwrap();
  431. let _ = fs::remove_dir_all(&tmp);
  432. assert_eq!(code, 0, "exit code, log: {body:?}");
  433. assert!(body.contains("TTY=0"), "TTY_COMPATIBLE lost: {body:?}");
  434. assert!(body.contains("NO=1"), "NO_COLOR lost: {body:?}");
  435. assert!(!body.contains('\r'), "pty ONLCR leaked CRLF: {body:?}");
  436. }
  437. /// The append mode must not truncate the main phase's log — the depth
  438. /// suite shares it so one report carries both tables.
  439. #[test]
  440. fn run_tool_append_keeps_prior_output() {
  441. let tmp =
  442. std::env::temp_dir().join(format!("sm121-bench-append-test-{}", std::process::id()));
  443. fs::create_dir_all(&tmp).unwrap();
  444. let log = tmp.join("append.log");
  445. let run =
  446. |a: &str, append| run_tool("sh", &["-c".into(), a.into()], &tmp, &log, append).unwrap();
  447. assert_eq!(run("echo main", false), 0);
  448. assert!(fs::read_to_string(&log).unwrap().contains("main\n"));
  449. assert_eq!(run("echo depth", true), 0);
  450. let body = fs::read_to_string(&log).unwrap();
  451. let (i1, i2) = (body.find("main\n"), body.find("depth\n"));
  452. assert!(
  453. i1.is_some() && i2.is_some_and(|d| i1.unwrap() < d),
  454. "append truncated the log: {body:?}"
  455. );
  456. let _ = fs::remove_dir_all(&tmp);
  457. }
  458. #[test]
  459. fn served_model_parsed_from_args() {
  460. let content = fs::read_to_string("recipes/glm53-flash-r27-spark/recipe.toml")
  461. .expect("repo recipe for test");
  462. let r: Recipe = toml::from_str(&content).expect("recipe toml");
  463. assert_eq!(served_model(&r).as_deref(), Some("glm53"));
  464. let mut r2 = r.clone();
  465. r2.args = crate::pre_serve::RecipeArgs::List(vec!["--trust-remote-code".into()]);
  466. assert!(served_model(&r2).is_none());
  467. }
  468. }