okami.mom/strata

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

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
4.2 KiB100 linesraw
1#!/usr/bin/env python3
2"""Stop, edit and resend, over and over (#879, #606): every answer must be real text, never a repeated token.
3
4The reports are an all-logits NaN (one token repeated, "!!!!") after a request was stopped and the next one, an edit
5or a resend of the same prompt, started while the engine was still winding the first down.  This drives that loop
6against a running server: stream an answer, read a few lines, close the connection (the client's Stop), wait 0 to
7~0.4 s (sometimes not at all, sometimes a second request already running), send the edited prompt, and check the
8answer.  Run the engine with STRATA_DBG_NAN=1 to get the first non-finite layer named in its log.
9
10  STRATA_KEY=... python3 research/tools/live-probes-2026-10/stop_resend_test.py http://127.0.0.1:8090 [rounds=40] [seed=1]
11
12Exit 0 when every answer was real text, 1 otherwise.
13"""
14import json
15import os
16import random
17import re
18import sys
19import threading
20import time
21import urllib.request
22
23BASE = sys.argv[1].rstrip("/") if len(sys.argv) > 1 else "http://127.0.0.1:8080"
24ROUNDS = int(sys.argv[2]) if len(sys.argv) > 2 else 40
25SEED = int(sys.argv[3]) if len(sys.argv) > 3 else 1
26KEY = os.environ.get("STRATA_KEY", "")
27URL = BASE + "/v1/chat/completions"
28
29LONG = ["Describe the weather in Montpellier in great detail, at length.",
30        "Write a long story about a lighthouse keeper.",
31        "Explain how a bicycle works, in as much detail as you can."]
32SHORT = [("Reply with exactly one word: the color of the sky on a clear day.", "blue"),
33         ("Reply with exactly one word: the opposite of cold.", "hot|warm"),
34         ("What is 2 plus 3? Reply with the number only.", "5|five")]
35
36
37def req(content, stream, max_tokens):
38    body = json.dumps({"model": "m", "max_tokens": max_tokens, "temperature": 0, "stream": stream,
39                       "messages": [{"role": "user", "content": content}],
40                       "chat_template_kwargs": {"enable_thinking": False}}).encode()
41    return urllib.request.Request(URL, data=body, headers={"Content-Type": "application/json",
42                                                           "Authorization": f"Bearer {KEY}"})
43
44
45def stop_after(content, lines):
46    r = urllib.request.urlopen(req(content, True, 400), timeout=600)
47    for _ in range(lines):
48        r.readline()
49    r.close()
50
51
52def answer(content, max_tokens=40):
53    with urllib.request.urlopen(req(content, False, max_tokens), timeout=600) as r:
54        m = json.load(r)["choices"][0]["message"]
55    return ((m.get("content") or "") + " " + (m.get("reasoning_content") or m.get("reasoning") or "")).strip()
56
57
58def garbage(text):
59    """Empty, one character or one token repeated (the NaN signature: '!!!!!!', 'the the the the')."""
60    t = text.strip()
61    if len(t) < 1:
62        return True
63    if len(t) >= 8 and len(set(t.replace(" ", ""))) <= 2:
64        return True
65    words = re.findall(r"\S+", t)
66    return len(words) >= 6 and len(set(words)) == 1
67
68
69def main():
70    rnd = random.Random(SEED)
71    bad = 0
72    for i in range(ROUNDS):
73        long_p = rnd.choice(LONG)
74        q, want = rnd.choice(SHORT)
75        mode = rnd.choice(("stop-resend", "stop-edit", "overlap"))
76        bg = None
77        try:
78            if mode == "overlap":                  # the next request is already running while the first one is stopped
79                bg = threading.Thread(target=lambda: answer(rnd.choice(LONG), 60))
80                bg.start()
81                time.sleep(rnd.uniform(0, 0.3))
82            stop_after(long_p, rnd.randint(1, 8))
83            time.sleep(rnd.choice((0, 0, 0.05, 0.2, 0.4)))
84            text = answer(long_p if mode == "stop-resend" else q, 40 if mode == "stop-resend" else 30)
85        except Exception as e:                      # a refused or dropped request is a failure of its own
86            print(f"{i:3d} {mode}: ERROR {e!r}", flush=True)
87            bad += 1
88            continue
89        finally:
90            if bg:
91                bg.join()
92        ok = not garbage(text) and (mode == "stop-resend" or re.search(want, text, re.I) is not None)
93        bad += not ok
94        print(f"{i:3d} {mode}: {'ok' if ok else 'BAD'} {text[:70]!r}", flush=True)
95    print(f"{ROUNDS} rounds, {bad} bad")
96    return 1 if bad else 0
97
98
99if __name__ == "__main__":
100    sys.exit(main())