okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-029-par-harness1fb3e9a32

main
3.6 KiB69 linesraw
1"""Self-test of tools/par_load.py and par_analyze.py against an in-process fake SSE server."""
2import json, os, sys, tempfile, threading, time, unittest
3from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
4sys.path.insert(0, os.path.dirname(__file__))
5import par_load, par_analyze
6
7
8class H(BaseHTTPRequestHandler):
9    def log_message(self, *a): pass
10    def do_GET(self):
11        self.send_response(200); self.end_headers(); self.wfile.write(b'{"ok":1}')
12    def do_POST(self):
13        n = int(self.headers["Content-Length"]); b = json.loads(self.rfile.read(n))
14        text = b["messages"][0]["content"]
15        pt = len(text.split()) + 10
16        if not b["stream"]:
17            self.send_response(200); self.end_headers()
18            self.wfile.write(json.dumps({"usage": {"prompt_tokens": pt, "completion_tokens": 1}}).encode()); return
19        self.send_response(200); self.send_header("Content-Type", "text/event-stream"); self.end_headers()
20        k = min(b["max_tokens"], 12)
21        for i in range(k):
22            time.sleep(0.01)
23            self.wfile.write(("data: " + json.dumps({"choices": [{"delta": {"content": "w "}}]}) + "\n\n").encode()); self.wfile.flush()
24        # two tokens per chunk at the end would make SSE counts wrong: usage is the truth
25        self.wfile.write(("data: " + json.dumps({"choices": [{"delta": {}, "finish_reason": "length"}], "usage": {"prompt_tokens": pt, "completion_tokens": k + 3}}) + "\n\n").encode())
26        self.wfile.write(b"data: [DONE]\n\n"); self.wfile.flush()
27
28
29class T(unittest.TestCase):
30    @classmethod
31    def setUpClass(cls):
32        cls.s = ThreadingHTTPServer(("127.0.0.1", 0), H)
33        threading.Thread(target=cls.s.serve_forever, daemon=True).start()
34        cls.url = f"http://127.0.0.1:{cls.s.server_address[1]}"
35    @classmethod
36    def tearDownClass(cls): cls.s.shutdown()
37
38    def run_(self, *args):
39        out = tempfile.mktemp(suffix=".json")
40        rc = par_load.main([self.url, "--out", out, *args])
41        return rc, json.load(open(out))
42
43    def test_w2_usage_tokens(self):
44        rc, L = self.run_("--workload", "w2", "--conc", "1,2", "--rounds", "2", "--max-tokens", "12", "--prompt-tokens", "200")
45        self.assertEqual(rc, 0); self.assertTrue(L["valid"])
46        b = L["blocks"][1]
47        self.assertEqual(b["tokens"], 4 * 15)             # usage says 15, SSE chunks were 12
48        self.assertEqual(b["requests"], 4)
49        self.assertIsNotNone(b["ttft_p50"]); self.assertIsNotNone(b["tpot_p50"])
50
51    def test_w4_w6_open(self):
52        rc, L = self.run_("--workload", "w4", "--conc", "2", "--rounds", "1", "--joiner-at", "0.05", "--joiner-tokens", "400", "--prompt-tokens", "100")
53        self.assertEqual(rc, 0); self.assertIn("joiner_ttft", L["blocks"][0])
54        rc, L = self.run_("--workload", "w6", "--conc", "2", "--rounds", "1", "--share", "0,0.9", "--prompt-tokens", "300")
55        self.assertEqual(len(L["blocks"]), 2)
56        rc, L = self.run_("--workload", "w2", "--open-rates", "20", "--duration", "1", "--drain-s", "5", "--max-tokens", "8", "--prompt-tokens", "100")
57        self.assertEqual(rc, 0); self.assertEqual(L["blocks"][0]["unfinished"], 0)
58
59    def test_analyze(self):
60        rows = []
61        for i, (a, b) in enumerate([(10, 21), (10, 20), (11, 22)]):
62            rows += [("x", {"workload": "w2", "level": 4, "arm": "A", "pair": str(i), "agg_tps": a, "errors": 0}),
63                     ("x", {"workload": "w2", "level": 4, "arm": "B", "pair": str(i), "agg_tps": b, "errors": 0})]
64        r = par_analyze.analyze(rows, "agg_tps")
65        self.assertAlmostEqual(r[0]["geomean"], 2.0, delta=0.06); self.assertEqual(r[0]["pairs_better"], 3)
66
67
68if __name__ == "__main__":
69    unittest.main()