interplane.Get Omega
Read in your language

benchmarks-mv

Measurement harnesses and evidence bundles for AIEN on the NVIDIA DGX Spark GB10. Speed is reported against the machine's physical limit and my own previous run. Attachment of AienOS.

Brought by drakestapleton

branch main Branches Tags History

benchmarks-mv / src / perf_index.rs

399 lines · 13952 bytes Raw Blame History
1//! Generator for `docs/PERF_INDEX.md`, the discovery index of records, artifacts, sources, studies and issues.
2//!
3//! Every cell is copied from a file in the repository (or, for a date the file does not
4//! carry, from `git log` of that file). Nothing is summarized, ranked or judged, and the
5//! output is sorted so that regenerating it on an unchanged tree gives the same bytes.
6
7use serde_json::Value;
8use std::collections::{BTreeMap, BTreeSet};
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::process::Command;
12
13/// Where the index is written, relative to the repository root.
14pub const INDEX_PATH: &str = "docs/PERF_INDEX.md";
15
16const COMMIT_FIELDS: [&str; 4] = [
17 "source.commit",
18 "benchmarks_git_sha",
19 "benchmark_commit",
20 "commit",
21];
22const DATE_FIELDS: [&str; 4] = ["timestamp_utc", "timestamp", "created_utc", "date"];
23const WORKLOAD_FIELDS: [&str; 2] = ["workload.name", "run_id"];
24const SCHEMA_FIELDS: [&str; 2] = ["schema", "schema_version"];
25
26/// Build the full index text for the repository at `root`.
27pub fn generate(root: &Path) -> String {
28 let mut out = String::new();
29 out.push_str("# Performance discovery index (generated, not an authority)\n\n");
30 out.push_str(
31 "Generated by `cargo run --release --bin bench_index` from the files in this repository; \
32do not edit by hand. Every status, commit and date is copied from the file named in its row \
33(the field it came from is in brackets), so this page is only as true as those files. \
34Architecture and plans live in aien-spark/aien-architecture. Records are validated by \
35`cargo run --release --bin bench_verify_records` (see README, \"Evidence integrity\").\n\n",
36 );
37
38 out.push_str("## Records and artifacts\n\n");
39 out.push_str("Scanned: `records/`, `artifacts/`, `data/`, `prime-drag-race/results/`.\n\n");
40 out.push_str("| Path | Kind | Schema | Status | Workload | Commit | Date |\n");
41 out.push_str("| :--- | :--- | :--- | :--- | :--- | :--- | :--- |\n");
42 let mut rows = Vec::new();
43 for (dir, kind) in [
44 ("records", "record"),
45 ("artifacts", "artifact"),
46 ("data", "dataset"),
47 ("prime-drag-race/results", "summary"),
48 ] {
49 rows.extend(evidence_rows(root, dir, kind));
50 }
51 rows.sort();
52 if rows.is_empty() {
53 out.push_str("| (none) | | | | | | |\n");
54 }
55 for r in rows {
56 out.push_str(&r);
57 }
58
59 out.push_str("\n## Active source paths\n\n");
60 out.push_str("Scanned: `src/**/*.rs`, `prime-drag-race/src/**/*.rs`. The text is the first `//!` line, else the first `///` line.\n\n");
61 out.push_str("| Path | First doc line |\n| :--- | :--- |\n");
62 let mut sources = Vec::new();
63 for dir in ["src", "prime-drag-race/src"] {
64 files_with_ext(&root.join(dir), "rs", &mut sources);
65 }
66 sources.sort();
67 for p in &sources {
68 let text = fs::read_to_string(p).unwrap_or_default();
69 out.push_str(&format!(
70 "| `{}` | {} |\n",
71 rel(root, p),
72 cell(&first_doc_line(&text))
73 ));
74 }
75
76 out.push_str("\n## Performance studies\n\n");
77 out.push_str("Scanned: `docs/*.md` (except this file), `prime-drag-race/*.md`. The text is the first `# ` line.\n\n");
78 out.push_str("| Path | Title |\n| :--- | :--- |\n");
79 let studies = study_files(root);
80 for p in &studies {
81 let text = fs::read_to_string(p).unwrap_or_default();
82 let title = text
83 .lines()
84 .find_map(|l| l.strip_prefix("# "))
85 .unwrap_or("(no title line)")
86 .trim()
87 .to_string();
88 out.push_str(&format!("| `{}` | {} |\n", rel(root, p), cell(&title)));
89 }
90
91 out.push_str("\n## Owning issues\n\n");
92 out.push_str("Issue references (`aien-spark/<repo>#N`, `aien-dev/<repo>#N`, GitHub issue or pull links, and `## Owning issue` sections) found in the studies and records above.\n\n");
93 out.push_str("| Issue | Mentioned in |\n| :--- | :--- |\n");
94 let mut issues: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
95 let mut scanned = studies.clone();
96 files_with_ext(&root.join("records"), "json", &mut scanned);
97 scanned.sort();
98 for p in &scanned {
99 let text = fs::read_to_string(p).unwrap_or_default();
100 for issue in issue_refs(&text) {
101 issues.entry(issue).or_default().insert(rel(root, p));
102 }
103 }
104 if issues.is_empty() {
105 out.push_str("| (none) | |\n");
106 }
107 for (issue, paths) in &issues {
108 let list: Vec<String> = paths.iter().map(|p| format!("`{p}`")).collect();
109 out.push_str(&format!("| {} | {} |\n", cell(issue), list.join(", ")));
110 }
111 out
112}
113
114/// One table row per JSON file, except that a SHA256SUMS bundle directory is one row.
115fn evidence_rows(root: &Path, dir: &str, kind: &str) -> Vec<String> {
116 let base = root.join(dir);
117 let mut json = Vec::new();
118 files_with_ext(&base, "json", &mut json);
119 let mut sums = Vec::new();
120 files_with_name(&base, "SHA256SUMS", &mut sums);
121 let bundles: BTreeSet<PathBuf> = sums
122 .iter()
123 .filter_map(|p| p.parent().map(Path::to_path_buf))
124 .collect();
125 let mut rows = Vec::new();
126 for b in &bundles {
127 let listed = fs::read_to_string(b.join("SHA256SUMS"))
128 .map(|t| t.lines().filter(|l| !l.trim().is_empty()).count())
129 .unwrap_or(0);
130 let mut members: Vec<&PathBuf> = json.iter().filter(|p| p.parent() == Some(b)).collect();
131 // manifest.json first: it carries the run identity in the existing bundles.
132 members.sort_by_key(|p| (p.file_name().is_none_or(|n| n != "manifest.json"), *p));
133 let docs: Vec<Value> = members
134 .iter()
135 .filter_map(|p| serde_json::from_str(&fs::read_to_string(p).ok()?).ok())
136 .collect();
137 let pick = |fields: &[&str]| docs.iter().find_map(|d| first_field(d, fields));
138 let date = pick(&DATE_FIELDS).unwrap_or_else(|| git_date(root, &b.join("SHA256SUMS")));
139 rows.push(row(
140 &format!("{}/", rel(root, b)),
141 &format!("{kind} bundle ({listed} files in SHA256SUMS)"),
142 pick(&SCHEMA_FIELDS),
143 pick(&["status"]),
144 pick(&WORKLOAD_FIELDS),
145 pick(&COMMIT_FIELDS).map(|c| mark_commit(&c)),
146 date,
147 ));
148 }
149 for p in json
150 .iter()
151 .filter(|p| p.parent().is_none_or(|d| !bundles.contains(d)))
152 {
153 let doc: Option<Value> = fs::read_to_string(p)
154 .ok()
155 .and_then(|t| serde_json::from_str(&t).ok());
156 let f = |fields: &[&str]| doc.as_ref().and_then(|d| first_field(d, fields));
157 let date = f(&DATE_FIELDS).unwrap_or_else(|| git_date(root, p));
158 let kind = if doc.is_none() {
159 format!("{kind} (not valid JSON)")
160 } else {
161 kind.to_string()
162 };
163 rows.push(row(
164 &rel(root, p),
165 &kind,
166 f(&SCHEMA_FIELDS),
167 f(&["status"]),
168 f(&WORKLOAD_FIELDS),
169 f(&COMMIT_FIELDS).map(|c| mark_commit(&c)),
170 date,
171 ));
172 }
173 rows
174}
175
176fn row(
177 path: &str,
178 kind: &str,
179 schema: Option<String>,
180 status: Option<String>,
181 workload: Option<String>,
182 commit: Option<String>,
183 date: String,
184) -> String {
185 let o = |v: Option<String>| cell(&v.unwrap_or_else(|| "-".into()));
186 format!(
187 "| `{path}` | {} | {} | {} | {} | {} | {} |\n",
188 cell(kind),
189 o(schema),
190 o(status),
191 o(workload),
192 o(commit),
193 cell(&date)
194 )
195}
196
197/// First present scalar among `fields`, as `value [field]`.
198fn first_field(doc: &Value, fields: &[&str]) -> Option<String> {
199 fields.iter().find_map(|f| {
200 let v = f.split('.').try_fold(doc, |cur, k| cur.get(k))?;
201 let s = match v {
202 Value::String(s) => s.clone(),
203 Value::Number(n) => n.to_string(),
204 Value::Bool(b) => b.to_string(),
205 _ => return None,
206 };
207 Some(format!("{s} [{f}]"))
208 })
209}
210
211fn mark_commit(c: &str) -> String {
212 let value = c.split(" [").next().unwrap_or(c);
213 if crate::evidence::is_commit(value) {
214 c.to_string()
215 } else {
216 format!("{c} (not a full commit id)")
217 }
218}
219
220/// Date of the commit that first added the file, or "not committed".
221fn git_date(root: &Path, file: &Path) -> String {
222 let out = Command::new("git")
223 .arg("-C")
224 .arg(root)
225 .args(["log", "--diff-filter=A", "--format=%cs", "--"])
226 .arg(rel(root, file))
227 .output();
228 match out {
229 Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
230 .lines()
231 .last()
232 .map(|d| format!("{d} [git: first commit]"))
233 .unwrap_or_else(|| "not committed".into()),
234 _ => "no git history".into(),
235 }
236}
237
238fn first_doc_line(text: &str) -> String {
239 let find = |prefix: &str| {
240 text.lines()
241 .map(str::trim_start)
242 .find_map(|l| l.strip_prefix(prefix).map(|r| r.trim().to_string()))
243 .filter(|s| !s.is_empty())
244 };
245 find("//!")
246 .or_else(|| find("///").map(|s| format!("(item doc) {s}")))
247 .unwrap_or_else(|| "(no doc comment)".into())
248}
249
250fn study_files(root: &Path) -> Vec<PathBuf> {
251 let mut out = Vec::new();
252 for dir in ["docs", "prime-drag-race"] {
253 if let Ok(entries) = fs::read_dir(root.join(dir)) {
254 for e in entries.filter_map(Result::ok) {
255 let p = e.path();
256 if p.is_file()
257 && p.extension().is_some_and(|x| x == "md")
258 && rel(root, &p) != INDEX_PATH
259 {
260 out.push(p);
261 }
262 }
263 }
264 }
265 out.sort();
266 out
267}
268
269/// Normalized issue references found in `text`.
270pub fn issue_refs(text: &str) -> BTreeSet<String> {
271 let mut out = BTreeSet::new();
272 for owner in ["aien-spark/", "aien-dev/"] {
273 let mut rest = text;
274 while let Some(i) = rest.find(owner) {
275 let after = &rest[i + owner.len()..];
276 let repo_len = after
277 .find(|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.'))
278 .unwrap_or(after.len());
279 let repo = after[..repo_len].trim_end_matches('.');
280 let tail = &after[repo_len..];
281 let number = if let Some(t) = tail.strip_prefix('#') {
282 leading_digits(t)
283 } else if let Some(t) = tail
284 .strip_prefix("/issues/")
285 .or_else(|| tail.strip_prefix("/pull/"))
286 {
287 leading_digits(t)
288 } else {
289 ""
290 };
291 if !repo.is_empty() && !number.is_empty() {
292 out.insert(format!("{owner}{repo}#{number}"));
293 }
294 rest = after;
295 }
296 }
297 // Bare #N under an "## Owning issue" heading: the repository is not named in the text.
298 let mut in_owning = false;
299 for line in text.lines() {
300 if line.starts_with('#') {
301 in_owning = line
302 .trim_start_matches('#')
303 .trim()
304 .eq_ignore_ascii_case("owning issue");
305 continue;
306 }
307 if !in_owning {
308 continue;
309 }
310 let mut rest = line;
311 while let Some(i) = rest.find('#') {
312 let before = rest[..i].chars().last();
313 let digits = leading_digits(&rest[i + 1..]);
314 if !digits.is_empty()
315 && before
316 .is_none_or(|c| !c.is_ascii_alphanumeric() && c != '-' && c != '_' && c != '.')
317 {
318 out.insert(format!("#{digits} (repository not named)"));
319 }
320 rest = &rest[i + 1..];
321 }
322 }
323 out
324}
325
326fn leading_digits(s: &str) -> &str {
327 let n = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
328 &s[..n]
329}
330
331fn files_with_ext(dir: &Path, ext: &str, out: &mut Vec<PathBuf>) {
332 walk(dir, &mut |p| {
333 if p.extension().is_some_and(|x| x == ext) {
334 out.push(p.to_path_buf());
335 }
336 });
337}
338
339fn files_with_name(dir: &Path, name: &str, out: &mut Vec<PathBuf>) {
340 walk(dir, &mut |p| {
341 if p.file_name().is_some_and(|n| n == name) {
342 out.push(p.to_path_buf());
343 }
344 });
345}
346
347fn walk(dir: &Path, f: &mut dyn FnMut(&Path)) {
348 let Ok(entries) = fs::read_dir(dir) else {
349 return;
350 };
351 let mut paths: Vec<PathBuf> = entries.filter_map(Result::ok).map(|e| e.path()).collect();
352 paths.sort();
353 for p in paths {
354 if p.file_name().is_some_and(|n| n == "target" || n == ".git") {
355 continue;
356 }
357 if p.is_dir() {
358 walk(&p, f);
359 } else {
360 f(&p);
361 }
362 }
363}
364
365fn rel(root: &Path, p: &Path) -> String {
366 crate::evidence::display_path(root, p)
367}
368
369fn cell(s: &str) -> String {
370 s.replace('|', "\\|").replace('\n', " ")
371}
372
373#[cfg(test)]
374mod tests {
375 use super::*;
376
377 #[test]
378 fn finds_issue_references() {
379 let text = "See aien-spark/omega#308, https://github.com/aien-dev/benchmarks/issues/12 and aien-spark/aienos.\n\
380## Owning issue\n\nTracked in #233 and aien-spark/aien-architecture#233.\n## Next\n#9 is not owned here\n";
381 let got: Vec<String> = issue_refs(text).into_iter().collect();
382 assert_eq!(
383 got,
384 vec![
385 "#233 (repository not named)",
386 "aien-dev/benchmarks#12",
387 "aien-spark/aien-architecture#233",
388 "aien-spark/omega#308",
389 ]
390 );
391 }
392
393 #[test]
394 fn doc_line_fallbacks() {
395 assert_eq!(first_doc_line("//! Module.\n/// Item."), "Module.");
396 assert_eq!(first_doc_line("use x;\n/// Item."), "(item doc) Item.");
397 assert_eq!(first_doc_line("fn main() {}"), "(no doc comment)");
398 }
399}