bench.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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::{Duration, Instant, SystemTime, UNIX_EPOCH};
  17. use anyhow::Result;
  18. use crate::config::{
  19. Config, Recipe, default_config_dir, load_recipe, local_path, select_cluster_by_name,
  20. };
  21. /// Fields of the `sm121 bench` subcommand (mirrored by the clap variant in
  22. /// `cli.rs`). Served model name and port come from the recipe
  23. /// (`--served-model-name` in args / `port`); the bench binary is looked up on PATH.
  24. #[derive(Clone)]
  25. pub struct Args {
  26. pub recipe: String,
  27. pub cluster: String,
  28. pub label: String,
  29. pub concurrency: String,
  30. pub seed: u64,
  31. }
  32. /// How long to poll the API for readiness before giving up.
  33. const READY_TIMEOUT_SECS: u64 = 900;
  34. /// Readiness poll interval.
  35. const READY_POLL_SECS: u64 = 5;
  36. /// Locate the recipe file (same search order as [`load_recipe`]) so reports
  37. /// land next to it.
  38. fn recipe_file(recipe_name: &str, sources: &[String]) -> Option<PathBuf> {
  39. let mut paths: Vec<PathBuf> = vec![
  40. PathBuf::from(format!("recipes/{}/recipe.toml", recipe_name)),
  41. PathBuf::from(format!("{}/recipe.toml", recipe_name)),
  42. ];
  43. for src in sources {
  44. paths.push(local_path(src).join(recipe_name).join("recipe.toml"));
  45. }
  46. if let Some(dir) = default_config_dir() {
  47. paths.push(dir.join("recipes").join(recipe_name).join("recipe.toml"));
  48. }
  49. paths.into_iter().find(|p| p.is_file())
  50. }
  51. /// Served model name from the recipe's `--served-model-name` arg.
  52. fn served_model(recipe: &Recipe) -> Option<String> {
  53. let args = recipe.args.to_vec();
  54. args.iter()
  55. .position(|s| s == "--served-model-name")
  56. .and_then(|i| args.get(i + 1))
  57. .cloned()
  58. }
  59. /// `YYYY-MM-DD_HHMMSS` in UTC (no chrono dependency).
  60. fn utc_stamp() -> String {
  61. let secs: i64 = SystemTime::now()
  62. .duration_since(UNIX_EPOCH)
  63. .map(|d| d.as_secs() as i64)
  64. .unwrap_or(0);
  65. let (h, m, s) = ((secs % 86400) / 3600, (secs % 3600) / 60, secs % 60);
  66. let (y, mo, d) = civil_date(secs / 86400);
  67. format!(
  68. "{y:04}-{mo:02}-{d:02}_{h:02}{m:02}{s:02}",
  69. y = y,
  70. mo = mo,
  71. d = d
  72. )
  73. }
  74. /// Days since 1970-01-01 → (year, month, day); Howard Hinnant's civil_from_days.
  75. fn civil_date(z: i64) -> (i64, i64, i64) {
  76. let z = z + 719_468;
  77. let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
  78. let doe = z - era * 146_097;
  79. let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
  80. let y = yoe + era * 400;
  81. let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
  82. let mp = (5 * doy + 2) / 153;
  83. let d = doy - (153 * mp + 2) / 5 + 1;
  84. let mo = if mp < 10 { mp + 3 } else { mp - 9 };
  85. let y = if mo <= 2 { y + 1 } else { y };
  86. (y, mo, d)
  87. }
  88. /// Keep the label filesystem-safe.
  89. fn sanitize(label: &str) -> String {
  90. label
  91. .chars()
  92. .map(|c| {
  93. if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
  94. c
  95. } else {
  96. '-'
  97. }
  98. })
  99. .collect()
  100. }
  101. /// Poll `GET <base>/models` until it answers (engine up).
  102. async fn wait_ready(base_url: &str) -> Result<()> {
  103. let client = reqwest::Client::builder()
  104. .timeout(Duration::from_secs(10))
  105. .build()?;
  106. let deadline = Instant::now() + Duration::from_secs(READY_TIMEOUT_SECS);
  107. let mut since_last_note = Instant::now();
  108. loop {
  109. match client.get(format!("{base_url}/models")).send().await {
  110. Ok(r) if r.status().is_success() => return Ok(()),
  111. Ok(_) => {}
  112. Err(_) => {}
  113. }
  114. if since_last_note.elapsed() >= Duration::from_secs(30) {
  115. since_last_note = Instant::now();
  116. eprintln!(
  117. "bench: waiting for API at {base_url} (up to {} s)...",
  118. READY_TIMEOUT_SECS
  119. );
  120. }
  121. if Instant::now() > deadline {
  122. anyhow::bail!("bench: API at {base_url} not ready after {READY_TIMEOUT_SECS} s");
  123. }
  124. tokio::time::sleep(Duration::from_secs(READY_POLL_SECS)).await;
  125. }
  126. }
  127. /// Tee one output pipe to the console and the log file.
  128. /// Tee one output pipe to the console and the log file.
  129. ///
  130. /// The read buffer must not be empty: `read()` on a zero-length slice
  131. /// returns 0 (interpreted as EOF), so an empty `Vec` would silently sever
  132. /// the pipe — the child then dies on its first stderr write with EPIPE
  133. /// (silent exit 120 in CPython).
  134. fn pump<R: Read>(mut reader: R, to_console: bool, file: Arc<Mutex<fs::File>>) {
  135. let mut buf = vec![0u8; 8192];
  136. loop {
  137. let n = match reader.read(&mut buf) {
  138. Ok(n) => n,
  139. Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
  140. Err(e) => panic!("reading bench output pipe: {e}"),
  141. };
  142. if n == 0 {
  143. break;
  144. }
  145. if to_console {
  146. std::io::stdout().write_all(&buf[..n]).ok();
  147. }
  148. if let Ok(mut f) = file.lock() {
  149. f.write_all(&buf[..n]).ok();
  150. }
  151. }
  152. }
  153. /// Run the bench tool in `cwd`, teeing stdout+stderr to the console and the
  154. /// log file; returns the exit code.
  155. ///
  156. /// The child runs under a pty (`script -q /dev/null`) instead of raw pipes:
  157. /// tool-eval-bench's rich Live display deadlocks on a non-tty stdout pipe
  158. /// right after the perf phase (deterministic on the 2x lane; 4x runs got
  159. /// lucky) while it runs clean on a tty, exactly as in an interactive
  160. /// terminal (2026-09-09). `script` is BSD/macOS form (the launcher is a
  161. /// Mac tool); if it is absent we fall back to the direct exec.
  162. fn run_tool(bin: &str, args: &[String], cwd: &Path, log_path: &Path) -> Result<i32> {
  163. let file = Arc::new(Mutex::new(fs::File::create(log_path)?));
  164. let mut cmd = if std::process::Command::new("/usr/bin/script")
  165. .arg("-q")
  166. .arg("/dev/null")
  167. .arg("true")
  168. .output()
  169. .is_ok()
  170. {
  171. let mut c = std::process::Command::new("/usr/bin/script");
  172. c.args(["-q", "/dev/null", bin]);
  173. c.args(args);
  174. c
  175. } else {
  176. let mut c = std::process::Command::new(bin);
  177. c.args(args);
  178. c
  179. };
  180. cmd.current_dir(cwd);
  181. cmd.stdout(Stdio::piped());
  182. cmd.stderr(Stdio::piped());
  183. let mut child = cmd.spawn()?;
  184. let stdout_pipe = child.stdout.take().expect("stdout pipe");
  185. let stderr_pipe = child.stderr.take().expect("stderr pipe");
  186. let f1 = file.clone();
  187. let t1 = std::thread::spawn(move || pump(stdout_pipe, true, f1));
  188. let t2 = std::thread::spawn(move || pump(stderr_pipe, false, file));
  189. let status = child.wait()?;
  190. t1.join().ok();
  191. t2.join().ok();
  192. Ok(status.code().unwrap_or(-1))
  193. }
  194. /// Newest `.md` under `scratch/runs/` (the tool's `runs/<date>/<run>.md`).
  195. fn latest_md(scratch: &Path) -> Option<PathBuf> {
  196. let runs = scratch.join("runs");
  197. let mut best: Option<(std::time::SystemTime, PathBuf)> = None;
  198. let mut stack = vec![runs];
  199. while let Some(dir) = stack.pop() {
  200. let entries = fs::read_dir(dir).ok()?;
  201. for e in entries.flatten() {
  202. let p = e.path();
  203. if p.is_dir() {
  204. stack.push(p);
  205. } else if p.extension().is_some_and(|x| x == "md") {
  206. let t = e
  207. .metadata()
  208. .and_then(|m| m.modified())
  209. .ok()
  210. .unwrap_or(SystemTime::UNIX_EPOCH);
  211. if best.as_ref().is_none_or(|(bt, _)| t > *bt) {
  212. best = Some((t, p));
  213. }
  214. }
  215. }
  216. }
  217. best.map(|(_, p)| p)
  218. }
  219. /// Run the bench and land `recipes/<lane>/reports/<stamp>_<label>.{md,json,log}`.
  220. pub async fn run(config: &Config, a: &Args, dry_run: bool) -> Result<()> {
  221. let recipe = load_recipe(&a.recipe, &config.recipe_sources).await?;
  222. let file = recipe_file(&a.recipe, &config.recipe_sources)
  223. .ok_or_else(|| anyhow::anyhow!("recipe file not found for '{}'", a.recipe))?
  224. .canonicalize()?;
  225. let cluster = select_cluster_by_name(config, &a.cluster)?;
  226. let head = match cluster.nodes.iter().find(|n| n.rank == 0) {
  227. Some(n) => n,
  228. None => cluster
  229. .nodes
  230. .first()
  231. .ok_or_else(|| anyhow::anyhow!("cluster '{}' has no nodes", cluster.name))?,
  232. };
  233. let port = recipe.port;
  234. let model = served_model(&recipe).ok_or_else(|| {
  235. anyhow::anyhow!(
  236. "recipe '{}' has no --served-model-name in args — add it to the recipe",
  237. a.recipe
  238. )
  239. })?;
  240. let base_url = format!("http://{}:{}/v1", head.ssh_ip, port);
  241. let stamp = utc_stamp();
  242. let label = sanitize(&a.label);
  243. let reports_dir = file
  244. .parent()
  245. .ok_or_else(|| anyhow::anyhow!("no parent dir for {}", file.display()))?
  246. .join("reports");
  247. let json_path = reports_dir.join(format!("{stamp}_{label}.json"));
  248. let log_path = reports_dir.join(format!("{stamp}_{label}.log"));
  249. let scratch = dirs::home_dir()
  250. .ok_or_else(|| anyhow::anyhow!("no home dir"))?
  251. .join(".cache")
  252. .join("sm121")
  253. .join("bench")
  254. .join(format!("{stamp}_{label}"));
  255. let bin = "tool-eval-bench".to_string();
  256. let args = vec![
  257. "--base-url".into(),
  258. base_url.clone(),
  259. "--model".into(),
  260. model.clone(),
  261. "--seed".into(),
  262. a.seed.to_string(),
  263. "--hardmode".into(),
  264. "--perf".into(),
  265. "--concurrency".into(),
  266. a.concurrency.clone(),
  267. "--json-file".into(),
  268. json_path.to_string_lossy().to_string(),
  269. ];
  270. if dry_run {
  271. println!("bench: cwd {}", scratch.display());
  272. println!("bench: {} {}", bin, args.join(" "));
  273. println!("bench: reports -> {}", reports_dir.display());
  274. return Ok(());
  275. }
  276. fs::create_dir_all(&scratch)?;
  277. fs::create_dir_all(&reports_dir)?;
  278. eprintln!("bench: waiting for {base_url} ...");
  279. wait_ready(&base_url).await?;
  280. eprintln!("bench: API ready — running {} (seed {})", bin, a.seed);
  281. let code = run_tool(&bin, &args, &scratch, &log_path)?;
  282. if code != 0 {
  283. anyhow::bail!(
  284. "bench: tool exited with {code} (log: {})",
  285. log_path.display()
  286. );
  287. }
  288. let md_src = latest_md(&scratch)
  289. .ok_or_else(|| anyhow::anyhow!("no report .md under {}", scratch.join("runs").display()))?;
  290. let md_dest = reports_dir.join(format!("{stamp}_{label}.md"));
  291. fs::copy(&md_src, &md_dest)?;
  292. // Summary: final score from the JSON + the perf table from the log.
  293. let j: serde_json::Value = serde_json::from_str(&fs::read_to_string(&json_path)?)?;
  294. let sc = &j["scores"];
  295. let completion = sc["completion_rate"]
  296. .as_f64()
  297. .map(|v| v.to_string())
  298. .unwrap_or_default();
  299. eprintln!(
  300. "bench: final score {} / {} ({} points), completion {completion}",
  301. sc["final_score"], sc["max_points"], sc["total_points"]
  302. );
  303. for line in fs::read_to_string(&log_path)?.lines() {
  304. if line.contains("pp2048") && line.contains("tg128") {
  305. println!("{line}");
  306. }
  307. }
  308. eprintln!("bench: reports landed in {}", reports_dir.display());
  309. Ok(())
  310. }
  311. #[cfg(test)]
  312. mod tests {
  313. use super::*;
  314. use std::process::Command;
  315. #[test]
  316. fn stamp_format() {
  317. let s = utc_stamp();
  318. assert_eq!(s.len(), 17, "{s}");
  319. assert_eq!(&s[4..5], "-");
  320. assert_eq!(&s[7..8], "-");
  321. assert_eq!(&s[10..11], "_");
  322. }
  323. #[test]
  324. fn civil_date_known_values() {
  325. assert_eq!(civil_date(0), (1970, 1, 1));
  326. assert_eq!(civil_date(19_723), (2024, 1, 1));
  327. assert_eq!(civil_date(20_818), (2026, 12, 31));
  328. }
  329. /// Regression: the pump must not treat a not-yet-written pipe as EOF.
  330. /// `read()` into a zero-length buffer returns 0, which the old pump
  331. /// treated as EOF — closing the pipe and killing the child on its first
  332. /// stderr write with EPIPE (silent exit 120 in CPython).
  333. #[test]
  334. fn pump_keeps_pipe_open_until_child_exits() {
  335. let tmp =
  336. std::env::temp_dir().join(format!("sm121-bench-pump-test-{}", std::process::id()));
  337. fs::create_dir_all(&tmp).unwrap();
  338. let log = tmp.join("pump.log");
  339. let mut child = Command::new("sh")
  340. .args(["-c", "sleep 0.3; echo late-output >&2"])
  341. .stdout(Stdio::piped())
  342. .stderr(Stdio::piped())
  343. .spawn()
  344. .unwrap();
  345. let out = child.stdout.take().unwrap();
  346. let err = child.stderr.take().unwrap();
  347. let f = Arc::new(Mutex::new(fs::File::create(&log).unwrap()));
  348. let f1 = f.clone();
  349. let t1 = std::thread::spawn(move || pump(out, false, f1));
  350. let t2 = std::thread::spawn(move || pump(err, false, f));
  351. let status = child.wait().unwrap();
  352. t1.join().unwrap();
  353. t2.join().unwrap();
  354. let body = fs::read_to_string(&log).unwrap();
  355. assert_eq!(status.code(), Some(0), "child must not hit EPIPE: {body}");
  356. assert!(body.contains("late-output"), "piped stderr lost: {body:?}");
  357. let _ = fs::remove_dir_all(&tmp);
  358. }
  359. #[test]
  360. fn sanitize_replaces_bad_chars() {
  361. assert_eq!(sanitize("arm B: 2x"), "arm-B--2x");
  362. assert_eq!(sanitize("ok_name-2.v3"), "ok_name-2.v3");
  363. }
  364. #[test]
  365. fn served_model_parsed_from_args() {
  366. let content = fs::read_to_string("recipes/glm53-flash-r27-spark/recipe.toml")
  367. .expect("repo recipe for test");
  368. let r: Recipe = toml::from_str(&content).expect("recipe toml");
  369. assert_eq!(served_model(&r).as_deref(), Some("glm53"));
  370. let mut r2 = r.clone();
  371. r2.args = crate::pre_serve::RecipeArgs::List(vec!["--trust-remote-code".into()]);
  372. assert!(served_model(&r2).is_none());
  373. }
  374. }