okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
5.6 KiB143 linesraw
1"""harness.py - drives strata-q36 / `strata` (qwen35moe) --serve over the engine protocol, for the q36-vp gates.
2
3    Eng(exe, args)            starts `exe --serve args`, waits for READY (INFO lines kept)
4    .solo(ids, n, keys, emb)  GEN / GENI one request -> (tokens, DONE line)
5    .batch(reqs)              reqs = [{"ids":[..], "n":N, "keys":"", "slot":b, "emb":path}]  admitted one after the
6                              other (BGEN, as the server does: one admission at a time), then every slot decodes
7                              together -> dict(tokens=[..per req], wall, steady_tok_s, ...)
8Run on the lent box; the box's lock / memory cap wrap the whole python call (see run.sh).
9"""
10import os, queue, subprocess, threading, time
11
12
13def load_prompts(path):
14    return [[int(x) for x in l.strip().split(",") if x] for l in open(path) if l.strip()]
15
16
17class Eng:
18    def __init__(self, exe, args, env=None, log=None, quiet=False):
19        e = dict(os.environ)
20        e.update(env or {})
21        self.logf = open(log, "w") if log else subprocess.DEVNULL
22        self.p = subprocess.Popen([exe, "--serve", *args], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
23                                  stderr=self.logf, text=True, bufsize=1, env=e)
24        self.q = queue.Queue()
25        self.info = {}
26        threading.Thread(target=self._pump, daemon=True).start()
27        t0 = time.time()
28        while True:
29            l = self.line(600)
30            if l is None:
31                raise SystemExit("engine ended before READY (see %s)" % log)
32            if l.startswith("INFO "):
33                for kv in l.split()[1:]:
34                    k, _, v = kv.partition("=")
35                    self.info[k] = v
36            if l.startswith("READY"):
37                self.ready = l
38                break
39        self.load_s = time.time() - t0
40
41    def _pump(self):
42        for l in self.p.stdout:
43            self.q.put(l.rstrip("\n"))
44        self.q.put(None)
45
46    def line(self, timeout=600):
47        try:
48            return self.q.get(timeout=timeout)
49        except queue.Empty:
50            raise SystemExit("engine silent for %ds" % timeout)
51
52    def send(self, s):
53        self.p.stdin.write(s + "\n")
54        self.p.stdin.flush()
55
56    def solo(self, ids, n, keys="", emb=None):
57        head = ("GENI %d" % n if emb else "GEN %d" % n) + (" " + keys if keys else "") + (" " + emb if emb else "")
58        t0 = time.time()
59        self.send(head + " " + ",".join(map(str, ids)))
60        toks, ttft, pp = [], None, []
61        while True:
62            l = self.line()
63            if l is None:
64                raise SystemExit("engine died")
65            if l.startswith("T "):
66                if ttft is None:
67                    ttft = time.time() - t0
68                toks.append(int(l.split()[1]))
69            elif l.startswith("PP "):
70                pp.append(l)
71            elif l.startswith("DONE"):
72                return toks, l, ttft, time.time() - t0
73            elif l.startswith("ERR"):
74                raise SystemExit("ERR: " + l)
75
76    def batch(self, reqs, hold_s=0.0):
77        """Admit every request (BGEN) in order, then read until every slot is done."""
78        toks = [[] for _ in reqs]
79        by_slot = {r["slot"]: i for i, r in enumerate(reqs)}
80        done = [False] * len(reqs)
81        t0 = time.time()
82        first_bt = None
83        admitted_at = None
84        stamps = []
85        for i, r in enumerate(reqs):
86            head = ("BGENI %d %d" if r.get("emb") else "BGEN %d %d") % (r["slot"], r["n"])
87            keys = r.get("keys", "")
88            self.send(head + (" " + keys if keys else "") + (" " + r["emb"] if r.get("emb") else "") + " " +
89                      ",".join(map(str, r["ids"])))
90            while True:
91                l = self.line()
92                if l is None:
93                    raise SystemExit("engine died")
94                if l.startswith("T "):
95                    toks[i].append(int(l.split()[1]))
96                elif l.startswith("BT "):
97                    f = l.split()
98                    j = by_slot[int(f[1])]
99                    toks[j].append(int(f[2]))
100                    if first_bt is None:
101                        first_bt = time.time()
102                elif l.startswith("BDONE "):
103                    done[by_slot[int(l.split()[1])]] = True
104                elif l.startswith("BADM "):
105                    f = l.split()
106                    if f[2] == "0":
107                        done[i] = True
108                    break
109                elif l.startswith("ERR"):
110                    raise SystemExit("ERR: " + l)
111            stamps.append(time.time() - t0)
112        admitted_at = time.time()
113        n_at_admit = sum(len(t) for t in toks)
114        while not all(done):
115            l = self.line()
116            if l is None:
117                raise SystemExit("engine died")
118            if l.startswith("BT "):
119                f = l.split()
120                toks[by_slot[int(f[1])]].append(int(f[2]))
121            elif l.startswith("BDONE "):
122                done[by_slot[int(l.split()[1])]] = True
123            elif l.startswith("ERR"):
124                raise SystemExit("ERR: " + l)
125        t1 = time.time()
126        tot = sum(len(t) for t in toks)
127        return {"tokens": toks, "wall": t1 - t0, "admit_s": admitted_at - t0, "admit_stamps": stamps,
128                "tail_tokens": tot - n_at_admit, "tail_s": t1 - admitted_at,
129                "tail_tok_s": (tot - n_at_admit) / max(1e-9, t1 - admitted_at)}
130
131    def close(self):
132        try:
133            self.send("STOP")
134        except Exception:
135            pass
136        try:
137            self.p.stdin.close()
138        except Exception:
139            pass
140        try:
141            self.p.wait(timeout=30)
142        except Exception:
143            self.p.kill()