okami.mom/strata

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

Niko1221Merge f-145-havok (#2364 multi-user series, opt-in)df44bcb71

main
17.8 KiB334 linesraw
1#!/usr/bin/env python3
2"""Batch slots, the parts batch_test.py does not reach (#465): a long prompt read WHILE other slots decode (its
3chunks interleaved with their windows), and a conversation's next turn continued from the slot that holds it.
4
5  1. solo references (GEN): A, then A's next turn (from the live session), B, C (a long prompt)
6  2. the same in the slots: A in slot 0, B in slot 1 next to it, then C in slot 2 while A and B decode - every slot's
7     tokens must equal its solo tokens
8  3. A's next turn (BGEN into slot 0, which still holds A): read from the slot, its tokens must equal the solo next turn
9  4. a long prompt D gives way (BYIELD) at its first chunk boundary, a short E is admitted, D goes on from its slot
10     while E decodes: both equal their solo tokens.  On a pipelined batch (a layer split, more than one group) a read
11     never gives way: D is then read whole into slot 2 and E admitted into slot 1 beside it; both must still equal
12     solo, only the give-way is not required (--yield auto; --yield expect requires it anyway)
13  6. A in a slot, stopped after 50 tokens and continued on the solo path (GEN of A + its tokens, from the slot): the
14     whole equals solo A (what the server does with a request left alone in a slot)
15  5. (a measurement) a solo next turn continued from a slot: the drafts accepted
16  7. F, A's history as a client sends it back without the reply's thinking, from slot 1's turn checkpoint: equal to
17     F solo (which continues from the same checkpoint of the live chain)
18     (after step 6 the solo path holds A's start, so F's start comes from the live chain or the prompt cache here)
19  7b. A in slot 1 to its end, --flush unrelated solo GENs, then F2 (A's question, another reply) into slot 2: its
20     start can only come from slot 1's turn checkpoint; equal to F2 solo.  The engine log line says which source was used.
21
22Exact comparisons need the same settings as batch_test.py (this script sets STRATA_IQ_MT_MIN=1):
23  python tools/batch_interleave_test.py --exe build/strata --config strata-<model>.json \\
24      --extra "--pcie-frac 0 --adapt-every 1000000 --no-prefill-borrow"
25Without --no-prefill-borrow the slots decoding during C's read see the expert cache without the slots C's prompt
26borrowed (those experts run on the CPU, which rounds differently): A's and B's text may then drift from solo.
27"""
28import argparse, json, os, re, sys, time
29from pathlib import Path
30
31sys.path.insert(0, str(Path(__file__).resolve().parent))
32from batch_test import Engine, tokenizer  # noqa: E402
33
34LONG = ("The history of mathematics is long and full of surprising turns. Early civilizations counted with tally marks, "
35        "then with symbols, and later with place-value systems that made arithmetic far easier. ")
36
37
38def run(eng, out, line, slot=None):
39    """Send one GEN/BGEN; returns (tokens of the request line, the BADM flag) - BT/BDONE of other slots are kept."""
40    eng.send(line)
41    got = []
42    for l in out:
43        if l.startswith("T "):
44            got.append(int(l.split()[1]))
45        elif l.startswith(("BT ", "BDONE ")):
46            eng.pending.append(l)
47        elif l.startswith("ERR"):
48            raise SystemExit("engine: " + l)
49        elif slot is None and l.startswith("DONE"):
50            return got, None
51        elif slot is not None and l.startswith("BADM "):
52            return got, l.split()[2] == "1"
53    raise SystemExit(f"the engine ended during: {line[:40]} (see {eng.log_path})")
54
55
56def engine_pipelined(eng, extra):
57    """Does the engine run the batch in pipelined groups (a layer split, more than one group)?  Then a BYIELD is
58    dropped: a pipelined read never gives way."""
59    if "--batch-groups" in extra:
60        v = extra[extra.index("--batch-groups") + 1] if extra.index("--batch-groups") + 1 < len(extra) else ""
61        if v.isdigit():
62            return int(v) > 1
63    eng.log.flush()
64    m = re.search(r"--batch-groups auto: (\d+) groups? of", Path(eng.log_path).read_text(errors="replace"))
65    return bool(m) and int(m.group(1)) > 1
66
67
68def main():
69    ap = argparse.ArgumentParser()
70    ap.add_argument("--exe", required=True)
71    ap.add_argument("--config", required=True)
72    ap.add_argument("--max-new", type=int, default=200)
73    ap.add_argument("--long", type=int, default=5000, help="tokens of the long prompt C (several prompt chunks)")
74    ap.add_argument("--extra", default="")
75    ap.add_argument("--yield", dest="yield_mode", choices=("auto", "expect", "skip"), default="auto",
76                    help="step 4's give-way: auto = expect a YIELDED unless the batch is pipelined (the engine log "
77                         "says '--batch-groups auto: N groups' with N > 1, or --extra has --batch-groups N > 1), "
78                         "where a read never gives way; expect = always required; skip = never required")
79    ap.add_argument("--flush", type=int, default=8,
80                    help="7b: unrelated solo GENs between A in slot 1 and F, so only the slot holds A's start (0: off)")
81    ap.add_argument("--dump", default="", help="write every solo and slot token list as JSON: an A/B of two builds")
82    a = ap.parse_args()
83    cfg = json.loads(Path(a.config).read_text())
84    tok = tokenizer(cfg["tokenizer"])
85
86    def chat(q):
87        return tok.encode(f"<|im_start|>user\n{q}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
88                          parse_special=True)
89    body = LONG * (a.long // max(1, len(tok.encode(LONG))) + 1)
90    A = chat("Write a Python function that merges overlapping intervals, then explain it.")
91    B = chat("Compare TCP and QUIC: handshake, congestion control, multiplexing.")
92    C = chat(body + "\nSummarize the text above in three sentences.")
93    D = chat(body + "\nWhat are the three most important ideas in the text above?")
94    E = chat("Describe the life cycle of a star like the Sun.")
95    print(f"prompts: A {len(A)}, B {len(B)}, C {len(C)} tokens", flush=True)
96    eng = Engine(a.exe, cfg, 3, {"STRATA_IQ_MT_MIN": "1"}, a.extra.split())
97    eng.pending = []
98    out = eng.lines()
99    ids = lambda v: ",".join(map(str, v))
100    M = a.max_new
101
102    # 1. solo
103    sA, _ = run(eng, out, f"GEN {M} {ids(A)}")
104    A2 = A + sA + chat("Now do the same in Rust.")
105    sA2, _ = run(eng, out, f"GEN {M} {ids(A2)}")
106    # F: A's history as a client sends it back WITHOUT the reply's thinking - it shares A only up to A's last turn
107    # boundary (the checkpoint there); solo it continues from that checkpoint of the live chain
108    turn_at = max(i for i, t in enumerate(A) if t == A[0])          # A[0] is <|im_start|>
109    F = A[:turn_at] + tok.encode("<|im_start|>assistant\nA short answer.<|im_end|>\n", parse_special=True) + \
110        chat("Now in Go.")
111    sF, _ = run(eng, out, f"GEN {M} {ids(F)}")
112    # F2 (step 7b): another reply to A's question - it too shares A only up to A's turn checkpoint
113    F2 = A[:turn_at] + tok.encode("<|im_start|>assistant\nAnother short answer.<|im_end|>\n", parse_special=True) + \
114        chat("Now in C.")
115    sF2, _ = run(eng, out, f"GEN {M} {ids(F2)}") if a.flush > 0 else ([], None)
116    sB, _ = run(eng, out, f"GEN {M} {ids(B)}")
117    sC, _ = run(eng, out, f"GEN {M} {ids(C)}")
118    sD, _ = run(eng, out, f"GEN {M} {ids(D)}")
119    sE, _ = run(eng, out, f"GEN {M} {ids(E)}")
120    print(f"solo: A {len(sA)}, A2 {len(sA2)}, B {len(sB)}, C {len(sC)}, D {len(sD)}, E {len(sE)} tokens", flush=True)
121
122    # 2. the slots: A, B, then the long C while they decode
123    got = {0: [], 1: [], 2: []}
124    done = {}
125    t0 = time.time()
126    for s, P in ((0, A), (1, B), (2, C)):
127        first, cont = run(eng, out, f"BGEN {s} {M} {ids(P)}", slot=s)
128        got[s] += first
129        if not cont:
130            done[s] = True
131    t_admit = time.time() - t0
132    during_c = sum(1 for l in eng.pending if l.startswith("BT "))   # windows the slots ran while C was admitted
133
134    def drain():
135        while eng.pending or len(done) < 3:
136            l = eng.pending.pop(0) if eng.pending else next(out)
137            if l.startswith("BT "):
138                _, s, y = l.split()
139                got[int(s)].append(int(y))
140            elif l.startswith("BDONE "):
141                done[int(l.split()[1])] = True
142            elif l.startswith("ERR"):
143                raise SystemExit("engine: " + l)
144    drain()
145    print(f"slots: admissions {t_admit:.1f}s; {during_c} slot tokens arrived while the admissions read their prompts",
146          flush=True)
147    ok = True
148    for s, ref, name in ((0, sA, "A"), (1, sB, "B"), (2, sC, "C")):
149        same = got[s] == ref
150        ok &= same
151        d = next((k for k in range(min(len(got[s]), len(ref))) if got[s][k] != ref[k]), None)
152        print(f"slot {s} ({name}): {len(got[s])} tokens, solo {len(ref)}: "
153              f"{'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True)
154
155    # 3. A's next turn from slot 0 (the engine's log says "slot 0 gave back ...")
156    first, cont = run(eng, out, f"BGEN 0 {M} {ids(A2)}", slot=0)
157    got2, done = first, {}
158    if cont:
159        while True:
160            l = eng.pending.pop(0) if eng.pending else next(out)
161            if l.startswith("BT 0 "):
162                got2.append(int(l.split()[2]))
163            elif l.startswith("BDONE 0 "):
164                break
165    same = got2 == sA2
166    ok &= same
167    d = next((k for k in range(min(len(got2), len(sA2))) if got2[k] != sA2[k]), None)
168    print(f"A's next turn from its slot: {len(got2)} tokens, solo {len(sA2)}: "
169          f"{'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True)
170    # 4. a long prompt D gives way (BYIELD) to a short E at its first chunk boundary, then goes on from its slot.
171    # On a pipelined batch (a layer split with more than one group) a read never gives way (generate.cpp: the BYIELD
172    # is dropped): D is then admitted whole into slot 2 and E goes into the free slot 1 while D decodes - both must
173    # still equal solo, only the give-way itself is not checked (--yield)
174    pipelined = engine_pipelined(eng, a.extra.split())
175    expect_yield = a.yield_mode == "expect" or (a.yield_mode == "auto" and not pipelined)
176    eng.send(f"BGEN 2 {M} {ids(D)}")
177    eng.send("BYIELD 2")
178    yielded, firstD, contD = None, [], None
179    for l in out:
180        if l.startswith("T "):
181            firstD.append(int(l.split()[1]))
182        elif l.startswith("YIELDED "):
183            yielded = l
184        elif l.startswith(("BT ", "BDONE ")):
185            eng.pending.append(l)
186        elif l.startswith("ERR"):
187            raise SystemExit("engine: " + l)
188        elif l.startswith("BADM 2 "):
189            contD = l.split()[2] == "1"
190            break
191    if yielded is not None:
192        print(f"D gave way: {yielded}", flush=True)
193    elif expect_yield:
194        print(f"D gave way: None (expected a YIELDED: batch {'pipelined' if pipelined else 'not pipelined'})",
195              flush=True)
196        ok = False
197    else:
198        print(f"D gave way: None - the batch is pipelined ({pipelined}), where a read never gives way; D stays in "
199              f"slot 2 ({len(firstD)} first tokens, {'continues' if contD else 'done'}), E goes into slot 1 beside it",
200              flush=True)
201    got4 = {1: [], 2: []}
202    first, cont1 = run(eng, out, f"BGEN 1 {M} {ids(E)}", slot=1)
203    got4[1] += first
204    if yielded is not None:
205        first, cont2 = run(eng, out, f"BGEN 2 {M} {ids(D)}", slot=2)
206        got4[2] += first
207    else:   # D never left slot 2: its tokens so far are the read's first ones plus the BT 2 lines kept in pending
208        got4[2] += firstD
209        cont2 = contD
210    done4 = {s for s, c in ((1, cont1), (2, cont2)) if not c}
211    while len(done4) < 2:
212        l = eng.pending.pop(0) if eng.pending else next(out)
213        if l.startswith("BT "):
214            _, s, y = l.split()
215            if int(s) in got4 and int(s) not in done4:
216                got4[int(s)].append(int(y))
217        elif l.startswith("BDONE "):
218            done4.add(int(l.split()[1]))
219        elif l.startswith("ERR"):
220            raise SystemExit("engine: " + l)
221    for s, ref, name in ((1, sE, "E (short, admitted while D waited)"), (2, sD, "D (gave way, then went on)" if yielded else "D (read whole, E admitted beside it)")):
222        same = got4[s] == ref
223        ok &= same
224        d = next((k for k in range(min(len(got4[s]), len(ref))) if got4[s][k] != ref[k]), None)
225        print(f"slot {s} {name}: {len(got4[s])} tokens, solo {len(ref)}: "
226              f"{'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True)
227    # 6. back to the solo path (what the server does with a request left alone in a slot): A in slot 1, BSTOP after
228    # 50 tokens, then GEN of A + what it produced - the engine continues from the slot with MTP drafts again
229    first, cont = run(eng, out, f"BGEN 1 {M} {ids(A)}", slot=1)
230    got6, sent = list(first), False
231    while cont:
232        l = eng.pending.pop(0) if eng.pending else next(out)
233        if l.startswith("BT 1 "):
234            got6.append(int(l.split()[2]))
235            if len(got6) >= 50 and not sent:
236                eng.send("BSTOP 1")
237                sent = True
238        elif l.startswith("BDONE 1 "):
239            break
240    tail6, _ = run(eng, out, f"GEN {M - len(got6)} {ids(A + got6)}") if len(got6) < M else ([], None)
241    same = got6 + tail6 == sA
242    ok &= same
243    both = got6 + tail6
244    d = next((k for k in range(min(len(both), len(sA))) if both[k] != sA[k]), None)
245    print(f"A in a slot, then solo again after {len(got6)} tokens: {len(both)} tokens, solo {len(sA)}: "
246          f"{'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True)
247
248    # 5. (a measurement, not a check) a SOLO next turn continued from slot 0: its tokens are exact either way, but the
249    # draft layer's own K/V was built for another conversation, so fewer drafts may be accepted than in a solo next
250    # turn whose drafter read the conversation (A2 in step 1)
251    A3 = A2 + got2 + chat("Now in Go.")
252    eng.send(f"GEN {M} {ids(A3)}")
253    for l in out:
254        if l.startswith(("BT ", "BDONE ")):
255            eng.pending.append(l)
256        elif l.startswith("DONE"):
257            f = l.split()
258            print(f"solo next turn from a slot: drafts accepted {f[6]} of {f[7]} ({f[1]} tokens in {f[4]} ms)",
259                  flush=True)
260            break
261    # 7. F, A's history without the reply's thinking, into slot 2 (its start comes from the live chain or the prompt
262    # cache: step 6's solo continuation took slot 1's contents back; 7b below makes a slot the only source)
263    first, cont = run(eng, out, f"BGEN 2 {M} {ids(F)}", slot=2)
264    got7 = list(first)
265    while cont:
266        l = eng.pending.pop(0) if eng.pending else next(out)
267        if l.startswith("BT 2 "):
268            got7.append(int(l.split()[2]))
269        elif l.startswith("BDONE 2 "):
270            break
271    same = got7 == sF
272    ok &= same
273    d = next((k for k in range(min(len(got7), len(sF))) if got7[k] != sF[k]), None)
274    print(f"F (A's history without the reply's thinking) in slot 2: {len(got7)} tokens, solo "
275          f"{len(sF)}: {'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True)
276    # 7b. step 7 where only a SLOT can give the start: after step 6 the solo path took slot 1's contents back, so the
277    # live chain (or the prompt cache) held A's start in step 7 and F came from there.  Here A runs to its end in
278    # slot 1, then --flush unrelated solo GENs push A out of the live session and the prompt cache's checkpoints; F2
279    # (A's question, another reply) into slot 2 can then only start from slot 1's turn checkpoint (slot 2 holds F,
280    # which shares no more with F2 than A does; the engine log line is printed) - its tokens must equal F2 solo
281    got7b = []
282    if a.flush > 0:
283        first, cont = run(eng, out, f"BGEN 1 {M} {ids(A)}", slot=1)
284        gotA = list(first)
285        while cont:
286            l = eng.pending.pop(0) if eng.pending else next(out)
287            if l.startswith("BT 1 "):
288                gotA.append(int(l.split()[2]))
289            elif l.startswith("BDONE 1 "):
290                break
291        same = gotA == sA
292        ok &= same
293        print(f"7b: A in slot 1 to its end: {len(gotA)} tokens, solo {len(sA)}: {'IDENTICAL' if same else 'DIFFERS'}",
294              flush=True)
295        for k in range(a.flush):
296            run(eng, out, f"GEN 8 {ids(chat(f'Unrelated question {k}: name one prime number above {100 * k}.'))}")
297        eng.log.flush()
298        mark = len(Path(eng.log_path).read_text(errors="replace"))
299        first, cont = run(eng, out, f"BGEN 2 {M} {ids(F2)}", slot=2)
300        got7b = list(first)
301        while cont:
302            l = eng.pending.pop(0) if eng.pending else next(out)
303            if l.startswith("BT 2 "):
304                got7b.append(int(l.split()[2]))
305            elif l.startswith("BDONE 2 "):
306                break
307        tail = Path(eng.log_path).read_text(errors="replace")[mark:]
308        src = [l for l in tail.splitlines() if "gave back" in l or "strata serve: prompt" in l][:2]
309        same = got7b == sF2
310        ok &= same
311        d = next((k for k in range(min(len(got7b), len(sF2))) if got7b[k] != sF2[k]), None)
312        print(f"7b: F2 after {a.flush} unrelated GENs, from slot 1: {len(got7b)} tokens, solo {len(sF2)}: "
313              f"{'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True)
314        for l in src:
315            print("  7b log:", l.split("strata ")[-1][:160], flush=True)
316    if a.dump:
317        Path(a.dump).write_text(json.dumps({
318            "solo": {"A": sA, "A2": sA2, "B": sB, "C": sC, "D": sD, "E": sE, "F": sF, "F2": sF2},
319            "slots": {"A": got[0], "B": got[1], "C": got[2], "A2": got2, "E": got4[1], "D": got4[2],
320                      "A_slot_then_solo": got6 + tail6, "F": got7, "F2": got7b},
321            "yielded": yielded is not None, "pipelined": pipelined}), encoding="utf-8")
322    eng.send("QUIT")
323    eng.p.wait(timeout=180)
324    log = Path(eng.log_path).read_text(errors="replace")
325    for l in log.splitlines():
326        if "drafts accepted" in l:
327            print("  log:", l.split("strata serve: ")[-1][:160], flush=True)
328    for key in ("gave back", "its turn checkpoint", "takes", "the prompt was read in", "gives way"):
329        print(f"engine log '{key}': {log.count(key)} lines", flush=True)
330    return 0 if ok else 2
331
332
333if __name__ == "__main__":
334    sys.exit(main())