Skip to content

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

fix(bench): propagate multi-stream request errors and stop sampling (#56)

Afloat1a97c3adf201
diff --git a/bench/multi.py b/bench/multi.py
index 196912c..f8fe90d 100644
--- a/bench/multi.py
+++ b/bench/multi.py
@@ -7,7 +7,8 @@ alone on the same server (per-stream identity: a stream's reply must equal the s
single-stream `--no-spec` servers given the first prompt alone (the per-stream baseline). Memory sampled per request.
python3 multi.py --out ~/res/multi --rounds 3
"""
-import argparse, json, os, random, threading, time
+import argparse, json, os, random, time
+from concurrent.futures import ThreadPoolExecutor
from bench2 import start, stop, post, Sampler
ARMS = {
@@ -44,6 +45,7 @@ def main():
random.Random(f"m{rd}").shuffle(order)
for arm in order:
port, proc, log = start(arm, ARMS[arm], a.out, f"r{rd}")
+ smp = None
try:
post(port, {"messages": [{"role": "user", "content": "Say hi."}], "max_tokens": 8, "temperature": 0,
"chat_template_kwargs": {"enable_thinking": False}})
@@ -51,8 +53,10 @@ def main():
if arm.endswith("_m4"):
res = [None] * 4
t0 = time.time()
- th = [threading.Thread(target=req, args=(port, p, res, i)) for i, p in enumerate(ps)]
- [t.start() for t in th]; [t.join() for t in th]
+ with ThreadPoolExecutor(max_workers=4) as pool:
+ requests = [pool.submit(req, port, p, res, i) for i, p in enumerate(ps)]
+ for request in requests:
+ request.result() # propagate a failed stream before reading partial results
wall = max(x[2] for x in res) - t0
ntok = sum(x[0]["timings"]["predicted_n"] for x in res)
smp.halt = True
@@ -74,6 +78,9 @@ def main():
f.write(json.dumps(row) + "\n"); f.flush()
print(arm, rd, round(row["agg_tok_s"], 2), row.get("identical_to_alone"), flush=True)
finally:
+ if smp is not None:
+ smp.halt = True
+ smp.join()
stop(proc)
print("MULTI_DONE", flush=True)
diff --git a/bench/test_multi_errors.py b/bench/test_multi_errors.py
new file mode 100644
index 0000000..3cd2b36
--- /dev/null
+++ b/bench/test_multi_errors.py
@@ -0,0 +1,63 @@
+import contextlib
+import io
+import json
+import os
+from pathlib import Path
+import tempfile
+import time
+import unittest
+from unittest.mock import Mock, patch
+
+import multi
+
+
+class MultiRequestErrorTest(unittest.TestCase):
+ def run_round(self, failure):
+ sampler = Mock(halt=False, anon=1, avail=1)
+ proc = Mock(pid=1)
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ prompts = [{"id": str(i), "messages": []} for i in range(4)]
+ (root / "prompts24.jsonl").write_text("".join(json.dumps(p) + "\n" for p in prompts))
+ out = root / "results"
+ old = os.getcwd()
+
+ def request(port, prompt, result, index):
+ if failure and index == 2:
+ raise RuntimeError("request for stream 2 failed")
+ reply = {"timings": {"predicted_n": 1, "predicted_per_second": 1},
+ "choices": [{"message": {"content": prompt["id"]}}]}
+ result[index] = (reply, 0.1, time.time())
+
+ try:
+ os.chdir(root)
+ with patch.object(multi, "ARMS", {"test_m4": {}}), \
+ patch.object(multi, "start", return_value=(1, proc, "unused")), \
+ patch.object(multi, "stop") as stop, patch.object(multi, "post"), \
+ patch.object(multi, "req", side_effect=request), \
+ patch.object(multi, "Sampler", return_value=sampler), \
+ patch("threading.excepthook"), \
+ patch("sys.argv", ["multi.py", "--out", str(out), "--rounds", "1"]), \
+ contextlib.redirect_stdout(io.StringIO()):
+ if failure:
+ with self.assertRaisesRegex(RuntimeError, "stream 2 failed"):
+ multi.main()
+ else:
+ multi.main()
+ stop.assert_called_once_with(proc)
+ self.assertTrue(sampler.halt)
+ sampler.join.assert_called_once()
+ rows = (out / "multi.jsonl").read_text().splitlines()
+ self.assertEqual(len(rows), 0 if failure else 1)
+ finally:
+ os.chdir(old)
+
+ def test_worker_failure_reaches_caller_and_cleans_up(self):
+ self.run_round(True)
+
+ def test_successful_round_also_joins_sampler(self):
+ self.run_round(False)
+
+
+if __name__ == "__main__":
+ unittest.main()