diff --git a/README.md b/README.md index 0ca2ea7..4525fef 100644 --- a/README.md +++ b/README.md @@ -230,7 +230,7 @@ Each run makes a folder `results/----/`: | file | what | |---|---| -| `results.html` | the report; open it in a browser | +| `results.html` | the report; open it in a browser. Launch command in a dropdown; `results.json` and `meta.json` keep every value | | `results.json` | the results, with all notes | | `meta.json` | every raw value, plus energy, % of bandwidth and the warnings | | `summary.txt` | the summary printed at the end | diff --git a/bench.sh b/bench.sh index c55a6a8..795246a 100755 --- a/bench.sh +++ b/bench.sh @@ -803,6 +803,9 @@ elif rebar != "unknown" and mine.get("resizable_bar", "").split()[-1:] != [rebar print("bench.sh: warning: " + msg, file=sys.stderr) open(os.environ["WARNINGS"], "a", encoding="utf-8").write(msg + "\n") PY +# Fewer badges in the report header; results.json and meta.json keep every value. +python3 "$here/report-header.py" "$run_dir" || warn "report header not tidied, results.html is as BetterBench wrote it" + # Energy per token and decode as % of memory bandwidth, from what the run # measured. They come after the run, so they go to meta.json ("post_run"), # not into the notes of results.json. @@ -1433,6 +1436,177 @@ for _ in range(3): best = max(best, 20 * 2 * x.numel() * 4 / (time.perf_counter() - t) / 1e9) print(f"{best:.0f} {mib}") __BENCH_STANDARD_EOF__ +cat > "$d/report-header.py" <<'__BENCH_STANDARD_EOF__' +#!/usr/bin/env python3 +"""Tidy the header of BetterBench's results.html, in place, after a run. + + report-header.py RUN_DIR + +Fewer badges, nothing measured changes: the model badge takes over the model_file details; +PCIe, ReBAR and the power limit join the gpu badge; corpus, passes, temperature and prefix +cache join the run badge; the endpoint badge goes; launch and env flags become a dropdown +holding the real launch command (server-cmd.txt). A warning badge that is not one of the +usual values stays on its own. Everything outside the header is left byte for byte, and +results.json and meta.json keep every value, including the model hash. + +BENCH_MODEL_LIBRARY (default /mnt/model-library, laid out as ORG/MODEL) is where the org in +the model badge comes from when the model is a local folder. +""" +import glob +import html as htmllib +import os +import re +import sys + +DOT = " · " +FLAG_BADGES = {"launch": ("Launch flags", " "), "env_flags": ("Environment flags", "=")} +CHIP_END = "" +RUN_BADGES = r"corpus v\S+|\d+ passes/cat|temp \S+|greedy|(cold|warm) prefix cache( \(nonce\))?" +CSS = """ + .flags { background:var(--surface); border:1px solid var(--border); border-radius:10px; font-size:13px; min-width:0; } + .flags summary { cursor:pointer; padding:9px 14px; color:var(--ink-2); font-family:var(--mono); font-size:12px; } + .flags-body { border-top:1px solid var(--border); padding:2px 14px 13px; } + .flags pre { margin:12px 0 0; font-family:var(--mono); font-size:12px; line-height:1.6; color:var(--ink); overflow-x:auto; } + .flags h2 { all:unset; display:block; font-family:var(--mono); font-size:10.5px; letter-spacing:.1em; + text-transform:uppercase; color:var(--muted); margin:12px 0 6px; } + .flags dl { display:grid; grid-template-columns:max-content minmax(0,1fr); gap:3px 14px; margin:0; + font-family:var(--mono); font-size:12px; } + .flags dt { color:var(--muted); } + .flags dd { margin:0; color:var(--ink); overflow-wrap:anywhere; } + @media (max-width:560px) { .flags dl { grid-template-columns:minmax(0,1fr); gap:0; } .flags dd { margin-bottom:6px; } } +""" + + +def tokens(cmd): + """Shell words with their quotes kept, so the printed command can be pasted as is.""" + return re.findall(r"(?:'[^']*'|\"(?:[^\"\\]|\\.)*\"|[^\s'\"])+", cmd) + + +def show_command(cmd): + """One option per line. Anything that is not one plain command (a script, a compose file) is shown as written.""" + one = re.sub(r"\\\r?\n", " ", cmd).strip() + squeeze = lambda s: re.sub(r"\s", "", s) + if "\n" in one or squeeze("".join(tokens(one))) != squeeze(one): + return cmd.strip() + lines = [] + for tok in tokens(one): + flag = tok.lstrip("'\"").startswith("-") + if not lines or flag: + lines.append([tok]) + elif not lines[-1][0].lstrip("'\"").startswith("-"): # the leading words (docker run), then image and path + lines[-1].append(tok) if len(lines) == 1 else lines.append([tok]) + elif len(lines[-1]) == 1 and "=" not in lines[-1][0]: # the value of a "--flag value" pair + lines[-1].append(tok) + else: + lines.append([tok]) + return " \\\n".join((" " if i else "") + " ".join(line) for i, line in enumerate(lines)) + + +def flag_section(heading, value, sep): + rows = "" + for piece in value.split(DOT): + key, _, val = piece.partition(sep) + rows += f"
{key}
{val or 'on'}
" + return f"

{heading}

{rows}
" + + +def model_org(name): + """'Org/' from the model library. A local parent folder is not an org (it can be any folder).""" + library = os.environ.get("BENCH_MODEL_LIBRARY", "/mnt/model-library") + hits = glob.glob(os.path.join(glob.escape(library), "*", glob.escape(name))) if name else [] + return os.path.basename(os.path.dirname(hits[0])) + "/" if len(hits) == 1 else "" + + +def model_badge(model_file, cmd, fallback): + """'Model: Org/name · size'. The location goes; a path inside a container is resolved through its mount.""" + pieces = model_file.split(DOT) + where = "" if re.fullmatch(r"[\d.]+ GB|sha256 .*", pieces[0]) else pieces.pop(0) + size = [p for p in pieces if p.endswith(" GB")] + if where.startswith(("/", ".", "~")): + mount = re.search(r"(?:-v|--volume)[\s=]+([^\s:]+):" + re.escape(where) + r"(?::\w+)?(?:\s|$)", cmd) + name = htmllib.escape(os.path.basename((mount.group(1) if mount else where).rstrip("/")), quote=False) + label = model_org(name) + name + else: # a Hugging Face repo id already says org/name + label = where + return "Model: " + DOT.join([label or fallback] + size) + + +def build(html, cmd): + m = re.search(r'
(.*?)
(?=\s*)', html, re.S) + if not m: + sys.exit("badge row not found") + chips = re.findall(r'.*?(?=|$)', m.group(1), re.S) + if len(chips) != m.group(1).count('class="chip"'): + sys.exit("could not parse every badge") + + keep, flags, gpu_extra, run_extra, model_chip = [], {}, {}, [], None + text_of = lambda chip: re.sub(r"<[^>]+>", "", chip).strip() + for chip in chips: + text = text_of(chip) + key, sep, value = text.partition(": ") + if key in FLAG_BADGES and sep: + flags[key] = value + elif key in ("pcie", "power_limit") and sep: + gpu_extra[key] = value + elif key == "model_file" and sep: + model_chip = chip + elif "http" in chip: # the endpoint: an address, of no use to a reader + continue + elif re.fullmatch(RUN_BADGES, text): + run_extra.append(text) + else: + keep.append(chip) + + def add_to(prefix, extra): + hits = [i for i, c in enumerate(keep) if text_of(c).startswith(prefix)] + if len(hits) != 1: + sys.exit(f"no single '{prefix}' badge to add {extra} to") + keep[hits[0]] = keep[hits[0]][:-len(CHIP_END)] + DOT + DOT.join(extra) + CHIP_END + + if run_extra: + add_to("run: ", run_extra) + extra = ([f"PCIe {gpu_extra['pcie']}"] if "pcie" in gpu_extra else []) + \ + ([f"{gpu_extra['power_limit']} limit"] if "power_limit" in gpu_extra else []) + if extra: + add_to("gpu: ", extra) + + # the first badge repeats the page title; show the model file details there instead + if model_chip: + title = re.search(r"

(.*?)

", html, re.S) + title = title.group(1) if title else None + if keep and text_of(keep[0]) == title: + badge = model_badge(text_of(model_chip).partition(": ")[2], cmd, title) + keep[0] = keep[0][:-len(title + CHIP_END)] + badge + CHIP_END + else: + keep.insert(0, model_chip) + + new = f'
{"".join(keep)}
' + if cmd.strip(): + new += ('\n
Deploy command
' + f'
{htmllib.escape(show_command(cmd), quote=False)}
') + elif flags: + body = "".join(flag_section(FLAG_BADGES[k][0], flags[k], FLAG_BADGES[k][1]) for k in FLAG_BADGES if k in flags) + new += ('\n
Launch and environment flags' + f'
{body}
') + out = html[:m.start()] + new + html[m.end():] + return out.replace("", CSS + "", 1) + + +if __name__ == "__main__": + run_dir = sys.argv[1] + report = os.path.join(run_dir, "results.html") + cmd_path = os.path.join(run_dir, "server-cmd.txt") + with open(report, encoding="utf-8") as f: + original = f.read() + cmd = "" + if os.path.exists(cmd_path): + with open(cmd_path, encoding="utf-8", errors="replace") as f: + cmd = f.read() + result = build(original, cmd) + with open(report + ".tmp", "w", encoding="utf-8") as f: + f.write(result) + os.replace(report + ".tmp", report) +__BENCH_STANDARD_EOF__ cat > "$d/config.json" <<'__BENCH_STANDARD_EOF__' { "temperature": 0.7, diff --git a/dev/DETAILS.md b/dev/DETAILS.md index 5135dcc..4c88cfd 100644 --- a/dev/DETAILS.md +++ b/dev/DETAILS.md @@ -151,3 +151,7 @@ BetterBench 0.6.1 is the oldest version that works (`BETTERBENCH_MIN_VERSION` in `standard.env`). Newer ones run too, and their version goes into the `run` note. Bump `STANDARD_VERSION` when `config.json`, the minimum BetterBench or the recorded fields change. + +`report-header.py` tidies the header of `results.html` after the run: it changes only how the +badges are shown, not what is recorded, so it needs no version bump. If it cannot read the page +it warns and leaves the report as BetterBench wrote it. diff --git a/dev/bench.sh b/dev/bench.sh index 98ffde8..fb65503 100755 --- a/dev/bench.sh +++ b/dev/bench.sh @@ -793,6 +793,9 @@ elif rebar != "unknown" and mine.get("resizable_bar", "").split()[-1:] != [rebar print("bench.sh: warning: " + msg, file=sys.stderr) open(os.environ["WARNINGS"], "a", encoding="utf-8").write(msg + "\n") PY +# Fewer badges in the report header; results.json and meta.json keep every value. +python3 "$here/report-header.py" "$run_dir" || warn "report header not tidied, results.html is as BetterBench wrote it" + # Energy per token and decode as % of memory bandwidth, from what the run # measured. They come after the run, so they go to meta.json ("post_run"), # not into the notes of results.json. diff --git a/dev/build.sh b/dev/build.sh index 5eea84e..37aab7d 100755 --- a/dev/build.sh +++ b/dev/build.sh @@ -10,7 +10,7 @@ set -eu dev=$(cd "$(dirname "$0")" && pwd) out="$dev/../bench.sh" -files="bench.sh collect-env.sh gpu-power.sh mem-bw.py config.json standard.env models.txt" +files="bench.sh collect-env.sh gpu-power.sh mem-bw.py report-header.py config.json standard.env models.txt" eof=__BENCH_STANDARD_EOF__ . "$dev/standard.env" diff --git a/dev/report-header.py b/dev/report-header.py new file mode 100644 index 0000000..81edba2 --- /dev/null +++ b/dev/report-header.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Tidy the header of BetterBench's results.html, in place, after a run. + + report-header.py RUN_DIR + +Fewer badges, nothing measured changes: the model badge takes over the model_file details; +PCIe, ReBAR and the power limit join the gpu badge; corpus, passes, temperature and prefix +cache join the run badge; the endpoint badge goes; launch and env flags become a dropdown +holding the real launch command (server-cmd.txt). A warning badge that is not one of the +usual values stays on its own. Everything outside the header is left byte for byte, and +results.json and meta.json keep every value, including the model hash. + +BENCH_MODEL_LIBRARY (default /mnt/model-library, laid out as ORG/MODEL) is where the org in +the model badge comes from when the model is a local folder. +""" +import glob +import html as htmllib +import os +import re +import sys + +DOT = " · " +FLAG_BADGES = {"launch": ("Launch flags", " "), "env_flags": ("Environment flags", "=")} +CHIP_END = "
" +RUN_BADGES = r"corpus v\S+|\d+ passes/cat|temp \S+|greedy|(cold|warm) prefix cache( \(nonce\))?" +CSS = """ + .flags { background:var(--surface); border:1px solid var(--border); border-radius:10px; font-size:13px; min-width:0; } + .flags summary { cursor:pointer; padding:9px 14px; color:var(--ink-2); font-family:var(--mono); font-size:12px; } + .flags-body { border-top:1px solid var(--border); padding:2px 14px 13px; } + .flags pre { margin:12px 0 0; font-family:var(--mono); font-size:12px; line-height:1.6; color:var(--ink); overflow-x:auto; } + .flags h2 { all:unset; display:block; font-family:var(--mono); font-size:10.5px; letter-spacing:.1em; + text-transform:uppercase; color:var(--muted); margin:12px 0 6px; } + .flags dl { display:grid; grid-template-columns:max-content minmax(0,1fr); gap:3px 14px; margin:0; + font-family:var(--mono); font-size:12px; } + .flags dt { color:var(--muted); } + .flags dd { margin:0; color:var(--ink); overflow-wrap:anywhere; } + @media (max-width:560px) { .flags dl { grid-template-columns:minmax(0,1fr); gap:0; } .flags dd { margin-bottom:6px; } } +""" + + +def tokens(cmd): + """Shell words with their quotes kept, so the printed command can be pasted as is.""" + return re.findall(r"(?:'[^']*'|\"(?:[^\"\\]|\\.)*\"|[^\s'\"])+", cmd) + + +def show_command(cmd): + """One option per line. Anything that is not one plain command (a script, a compose file) is shown as written.""" + one = re.sub(r"\\\r?\n", " ", cmd).strip() + squeeze = lambda s: re.sub(r"\s", "", s) + if "\n" in one or squeeze("".join(tokens(one))) != squeeze(one): + return cmd.strip() + lines = [] + for tok in tokens(one): + flag = tok.lstrip("'\"").startswith("-") + if not lines or flag: + lines.append([tok]) + elif not lines[-1][0].lstrip("'\"").startswith("-"): # the leading words (docker run), then image and path + lines[-1].append(tok) if len(lines) == 1 else lines.append([tok]) + elif len(lines[-1]) == 1 and "=" not in lines[-1][0]: # the value of a "--flag value" pair + lines[-1].append(tok) + else: + lines.append([tok]) + return " \\\n".join((" " if i else "") + " ".join(line) for i, line in enumerate(lines)) + + +def flag_section(heading, value, sep): + rows = "" + for piece in value.split(DOT): + key, _, val = piece.partition(sep) + rows += f"
{key}
{val or 'on'}
" + return f"

{heading}

{rows}
" + + +def model_org(name): + """'Org/' from the model library. A local parent folder is not an org (it can be any folder).""" + library = os.environ.get("BENCH_MODEL_LIBRARY", "/mnt/model-library") + hits = glob.glob(os.path.join(glob.escape(library), "*", glob.escape(name))) if name else [] + return os.path.basename(os.path.dirname(hits[0])) + "/" if len(hits) == 1 else "" + + +def model_badge(model_file, cmd, fallback): + """'Model: Org/name · size'. The location goes; a path inside a container is resolved through its mount.""" + pieces = model_file.split(DOT) + where = "" if re.fullmatch(r"[\d.]+ GB|sha256 .*", pieces[0]) else pieces.pop(0) + size = [p for p in pieces if p.endswith(" GB")] + if where.startswith(("/", ".", "~")): + mount = re.search(r"(?:-v|--volume)[\s=]+([^\s:]+):" + re.escape(where) + r"(?::\w+)?(?:\s|$)", cmd) + name = htmllib.escape(os.path.basename((mount.group(1) if mount else where).rstrip("/")), quote=False) + label = model_org(name) + name + else: # a Hugging Face repo id already says org/name + label = where + return "Model: " + DOT.join([label or fallback] + size) + + +def build(html, cmd): + m = re.search(r'
(.*?)
(?=\s*)', html, re.S) + if not m: + sys.exit("badge row not found") + chips = re.findall(r'.*?(?=|$)', m.group(1), re.S) + if len(chips) != m.group(1).count('class="chip"'): + sys.exit("could not parse every badge") + + keep, flags, gpu_extra, run_extra, model_chip = [], {}, {}, [], None + text_of = lambda chip: re.sub(r"<[^>]+>", "", chip).strip() + for chip in chips: + text = text_of(chip) + key, sep, value = text.partition(": ") + if key in FLAG_BADGES and sep: + flags[key] = value + elif key in ("pcie", "power_limit") and sep: + gpu_extra[key] = value + elif key == "model_file" and sep: + model_chip = chip + elif "http" in chip: # the endpoint: an address, of no use to a reader + continue + elif re.fullmatch(RUN_BADGES, text): + run_extra.append(text) + else: + keep.append(chip) + + def add_to(prefix, extra): + hits = [i for i, c in enumerate(keep) if text_of(c).startswith(prefix)] + if len(hits) != 1: + sys.exit(f"no single '{prefix}' badge to add {extra} to") + keep[hits[0]] = keep[hits[0]][:-len(CHIP_END)] + DOT + DOT.join(extra) + CHIP_END + + if run_extra: + add_to("run: ", run_extra) + extra = ([f"PCIe {gpu_extra['pcie']}"] if "pcie" in gpu_extra else []) + \ + ([f"{gpu_extra['power_limit']} limit"] if "power_limit" in gpu_extra else []) + if extra: + add_to("gpu: ", extra) + + # the first badge repeats the page title; show the model file details there instead + if model_chip: + title = re.search(r"

(.*?)

", html, re.S) + title = title.group(1) if title else None + if keep and text_of(keep[0]) == title: + badge = model_badge(text_of(model_chip).partition(": ")[2], cmd, title) + keep[0] = keep[0][:-len(title + CHIP_END)] + badge + CHIP_END + else: + keep.insert(0, model_chip) + + new = f'
{"".join(keep)}
' + if cmd.strip(): + new += ('\n
Deploy command
' + f'
{htmllib.escape(show_command(cmd), quote=False)}
') + elif flags: + body = "".join(flag_section(FLAG_BADGES[k][0], flags[k], FLAG_BADGES[k][1]) for k in FLAG_BADGES if k in flags) + new += ('\n
Launch and environment flags' + f'
{body}
') + out = html[:m.start()] + new + html[m.end():] + return out.replace("", CSS + "", 1) + + +if __name__ == "__main__": + run_dir = sys.argv[1] + report = os.path.join(run_dir, "results.html") + cmd_path = os.path.join(run_dir, "server-cmd.txt") + with open(report, encoding="utf-8") as f: + original = f.read() + cmd = "" + if os.path.exists(cmd_path): + with open(cmd_path, encoding="utf-8", errors="replace") as f: + cmd = f.read() + result = build(original, cmd) + with open(report + ".tmp", "w", encoding="utf-8") as f: + f.write(result) + os.replace(report + ".tmp", report) diff --git a/dev/test.sh b/dev/test.sh index e879ed4..ac5a43a 100644 --- a/dev/test.sh +++ b/dev/test.sh @@ -66,6 +66,35 @@ bench "$LL" "$t/cmd1"; rc=$? run=$(sed -n 's/^done: //p' "$t/out") check "quick run finishes (no GPU, the sampler exits at once)" '[ $rc = 0 ] && [ -d "$run" ]' check "run folder has every file" 'for f in results.json results.html meta.json config.json server-cmd.txt summary.txt betterbench.log; do [ -s "$run/$f" ] || exit 1; done' +# the report header: fewer badges, nothing lost from the rest of the page +h="$run/results.html" +check "report header tidied without a warning" '! grep -q "report header not tidied" "$t/out" && grep -q "the numbers" "$h"' +check "model badge has name and size, no path or hash" 'grep -q "Model: test.gguf · 0.00 GB
" "$h" && ! grep -q "model_file:" "$h" && ! grep -q "sha256" "$h"' +check "pcie and power limit joined the gpu badge" 'grep -q "PCIe [^<]*· 200 W limit" "$h" && ! grep -q "power_limit:" "$h"' +check "corpus, passes, temp and cache joined the run badge" 'grep -q "run: [^<]*· corpus v1.0 · 5 passes/cat · temp 0.7 · cold prefix cache (nonce)" "$h"' +check "endpoint badge removed" '! grep -q "http" "$h"' +check "flags are a dropdown with the redacted command" 'grep -q "Deploy command" "$h" && grep -q "HF_TOKEN=<redacted>" "$h" && ! grep -q "launch: " "$h" && ! grep -q "env_flags: " "$h"' +# rh NAME MODEL_FILE [server-cmd.txt text]: the script alone on a one-badge-of-each page +rh() { + mkdir -p "$t/rh/$1"; rm -f "$t/rh/$1/server-cmd.txt" + printf '

m

mgpu: grun: rmodel_file: %slaunch: x 1env_flags: A=1
\n
' "$2" > "$t/rh/$1/results.html" + [ $# -gt 2 ] && printf '%s' "$3" > "$t/rh/$1/server-cmd.txt" + BENCH_MODEL_LIBRARY="$t/lib" python3 "$dev/report-header.py" "$t/rh/$1" +} +mkdir -p "$t/lib/SomeOrg/Local" +rh repo "Org/Repo · 3.00 GB · sha256 abc (standard: Q4)" +check "report: a repo id keeps its org" 'grep -q "Model: Org/Repo · 3.00 GB" "$t/rh/repo/results.html"' +rh lib "/model · 1.00 GB" "docker run -v /any/folder/Local:/model:ro img /model" +check "report: a mounted model gets its org from the library" 'grep -q "Model: SomeOrg/Local · 1.00 GB" "$t/rh/lib/results.html"' +rh nofile "1.00 GB" +check "report: no command falls back to the flags" 'grep -q "
A
1
" "$t/rh/nofile/results.html" && grep -q "Model: m · 1.00 GB" "$t/rh/nofile/results.html"' +rh wrap "/m" "$(printf 'srv \\\n --a 1 \\\n --b=2')" +check "report: a wrapped command is not wrapped twice" '[ "$(grep -c "\\\\$" "$t/rh/wrap/results.html")" = 2 ]' +rh script "/m" "$(printf 'a: 1\nb: 2')" +check "report: not one command, shown as written" 'grep -q "
a: 1$" "$t/rh/script/results.html"'
+printf '' > "$t/rh/nofile/results.html"
+check "report: an unknown page fails and stays as it was" '! python3 "$dev/report-header.py" "$t/rh/nofile" 2>/dev/null && [ "$(cat "$t/rh/nofile/results.html")" = "" ]'
+
 check "no empty power.csv without a GPU" '[ ! -e "$run/power.csv" ]'
 check "summary printed" 'grep -q "decode (batch 1)  52.0 t/s" "$t/out"'
 check "meta.json has post-run figures and warnings" 'python3 -c "import json,sys; m=json.load(open(sys.argv[1])); assert \"post_run\" in m and \"warnings\" in m" "$run/meta.json"'
diff --git a/dev/test/betterbench b/dev/test/betterbench
index aa67248..134b82d 100755
--- a/dev/test/betterbench
+++ b/dev/test/betterbench
@@ -17,5 +17,14 @@ res = {"single_stream": {"code": rec},
        "prefill": [{"target_depth": 4000, "pp_tps": [1500, 1600]}, {"target_depth": 64000, "skipped": True}],
        "env": {}, "argv": a}
 json.dump(res, open(out, "w"))
-open(out.replace(".json", ".html"), "w").write("")
+# The header as BetterBench renders it, for report-header.py
+model = a[a.index("--model") + 1]
+sw = ''
+chips = [sw + model, f'{a[a.index("--endpoint") + 1]}', "corpus v1.0", "5 passes/cat", "temp 0.7",
+         "cold prefix cache (nonce)", "8,192 tok context"]
+chips += [sw + n.replace("=", ": ", 1) for i, n in enumerate(a) if i and a[i - 1] == "--note"]
+bar = "".join(f'{c}' for c in chips)
+open(out.replace(".json", ".html"), "w").write(
+    f'

{model}

\n
{bar}
\n
' + '
the numbers
') print("[3/3] done")