Skip to content

Fast local LLM inference on plain CPUs. No GPU, 8 GB of RAM. OpenAI-compatible server.

fix(bench): recover interrupted final JSONL records when resuming (#52)

Afloatb8a5793aa581
diff --git a/bench/bench2.py b/bench/bench2.py
index e92b660..ebba8e2 100644
--- a/bench/bench2.py
+++ b/bench/bench2.py
@@ -26,6 +26,7 @@ import sys
import threading
import time
import urllib.request
+from result_rows import read_rows
def free_port() -> int:
@@ -156,8 +157,7 @@ def main() -> None:
os.makedirs(os.path.join(outdir, "outputs", arm), exist_ok=True)
done = set()
if os.path.exists(a.out):
- for l in open(a.out):
- r = json.loads(l)
+ for r in read_rows(a.out):
if "error" not in r:
done.add((r["prompt_id"], r["arm"], r["rep"]))
host = socket.gethostname()
diff --git a/bench/ctxrun.py b/bench/ctxrun.py
index 46e0e20..e17cd17 100644
--- a/bench/ctxrun.py
+++ b/bench/ctxrun.py
@@ -14,6 +14,7 @@ cgroup memory.current/peak/anon/file/shmem (in a container the 16 GB limit is th
major faults of the server during the request, and whether the server survived (exit code / signal if not).
"""
import argparse, hashlib, json, os, random, shlex, signal, socket, subprocess, sys, threading, time, urllib.request
+from result_rows import read_rows
HOST = socket.gethostname()
@@ -125,17 +126,14 @@ def main():
for d in ("logs", "outputs"):
os.makedirs(os.path.join(outdir, d), exist_ok=True)
done = set()
- if os.path.exists(a.out):
- for l in open(a.out):
- r = json.loads(l)
- done.add((r["round"], r["ctx"], r["arm"], r["mode"]))
+ previous = read_rows(a.out) if os.path.exists(a.out) else []
+ for r in previous:
+ done.add((r["round"], r["ctx"], r["arm"], r["mode"]))
print(f"# {len(plan)} jobs, {len(done)} done", file=sys.stderr, flush=True)
failed = {} # jobs with "stop_on_fail": an arm that failed a fill at C skips later fills at >= C
- if os.path.exists(a.out):
- for l in open(a.out):
- r = json.loads(l)
- if r["mode"] == "fill" and r["status"] != "ok":
- failed[r["arm"]] = min(failed.get(r["arm"], 1 << 30), r["ctx_n"])
+ for r in previous:
+ if r["mode"] == "fill" and r["status"] != "ok":
+ failed[r["arm"]] = min(failed.get(r["arm"], 1 << 30), r["ctx_n"])
for j in plan:
key = (j["round"], j["ctx"], j["arm"], j["mode"])
if key in done:
diff --git a/bench/result_rows.py b/bench/result_rows.py
new file mode 100644
index 0000000..1f70f71
--- /dev/null
+++ b/bench/result_rows.py
@@ -0,0 +1,29 @@
+"""Read resumable benchmark output and repair only an unfinished final record."""
+import json
+import sys
+
+
+def read_rows(path):
+ rows = []
+ needs_newline = False
+ with open(path, "r+b") as stream:
+ while True:
+ offset = stream.tell()
+ line = stream.readline()
+ if not line:
+ break
+ needs_newline = not line.endswith(b"\n")
+ if not line.strip():
+ continue
+ try:
+ rows.append(json.loads(line))
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ if not needs_newline:
+ raise # a complete corrupt record must not be silently discarded
+ stream.seek(offset)
+ stream.truncate()
+ print(f"Discarded an incomplete final result row in {path}; completed rows were kept.", file=sys.stderr)
+ return rows
+ if needs_newline:
+ stream.write(b"\n") # do not concatenate the next appended JSON object
+ return rows
diff --git a/bench/test_result_resume.py b/bench/test_result_resume.py
new file mode 100644
index 0000000..6898802
--- /dev/null
+++ b/bench/test_result_resume.py
@@ -0,0 +1,67 @@
+import contextlib
+import io
+import json
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import patch
+
+import bench2
+import ctxrun
+
+
+class ResultResumeTest(unittest.TestCase):
+ def check_resume(self, runner, tail, terminated=True, invalid=False):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ if runner is bench2:
+ row = {"prompt_id": "one", "arm": "test", "rep": 0}
+ (root / "arms.json").write_text('{"test": {"cmd": "unused"}}')
+ (root / "prompts.json").write_text('{"id":"one","task":"test","messages":[]}\n')
+ else:
+ row = {"round": 0, "ctx": "8192", "ctx_n": 8192, "arm": "test", "mode": "fill", "status": "ok"}
+ (root / "arms.json").write_text('{}')
+ (root / "prompts.json").write_text('{"prompts": {}}')
+ (root / "plan.jsonl").write_text(json.dumps(row) + "\n")
+ path = root / "results.jsonl"
+ complete = json.dumps(row).encode()
+ original = complete + (b"\n" if terminated else b"") + tail
+ path.write_bytes(original)
+ argv = ["runner.py", "--arms", str(root / "arms.json"), "--prompts", str(root / "prompts.json"),
+ "--out", str(path)]
+ if runner is ctxrun:
+ argv += ["--plan", str(root / "plan.jsonl")]
+ with patch("sys.argv", argv), patch.object(runner.subprocess, "Popen") as spawn, \
+ contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
+ if invalid:
+ with self.assertRaises(json.JSONDecodeError):
+ runner.main()
+ else:
+ runner.main()
+ spawn.assert_not_called()
+ if invalid:
+ self.assertEqual(path.read_bytes(), original)
+ else:
+ self.assertEqual(path.read_bytes(), complete + b"\n")
+ with path.open("ab") as stream:
+ stream.write(b'{"next":true}\n')
+ self.assertEqual(len([json.loads(line) for line in path.read_bytes().splitlines()]), 2)
+
+ def test_server_benchmark_recovers_truncated_tail(self):
+ self.check_resume(bench2, b'{"prompt_id":')
+
+ def test_context_runner_recovers_truncated_tail(self):
+ self.check_resume(ctxrun, b'{"round":')
+
+ def test_truncated_utf8_tail_is_recoverable(self):
+ self.check_resume(bench2, b'{"text":"\xe4\xb8')
+
+ def test_complete_row_without_newline_is_preserved(self):
+ self.check_resume(bench2, b"", terminated=False)
+
+ def test_corrupt_complete_record_is_not_discarded(self):
+ self.check_resume(bench2, b'{broken}\n', invalid=True)
+
+
+if __name__ == "__main__":
+ unittest.main()