okami.mom/strata

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

Niko1221Merge f-142b-serve into f-1426e1085c1d

main
6.0 KiB111 linesraw
1"""Interleaved A/B of per-request strata_tune settings (no restart), with rotated arm order.
2usage: python3 ab.py MODE ROUNDS 'A_json' 'B_json' ['C_json' ...]
3  MODE: solo  = one 300-token decode per round and arm (tok/s from the stream)
4        c2    = 2 concurrent 300-token decodes (aggregate tok/s)
5        read  = 24k-token fresh read, 1 token out (prefill tok/s)
6        mix   = a fresh ~48k read while one stream decodes (read tok/s + the stream's tok/s overall)
7Order: round r visits the arms starting at arm (r mod n) (A,B / B,A / A,B ...), so no arm always follows the same
8neighbour; every arm gets a fresh unique prompt. Give the same JSON twice as arms A and B to run an A/A control
9(it shows the bias of the method). Prints per-arm median/mean/min/max, the paired ratio against arm A (median of per-round
10ratios), and the mean ratio by position in the round."""
11import json, statistics as st, sys, threading, time, urllib.request
12
13MODE, ROUNDS = sys.argv[1], int(sys.argv[2])
14ARMS = [json.loads(a) for a in sys.argv[3:]]
15N = len(ARMS)
16BASE = "http://127.0.0.1:8000"
17MODEL = "qwen3.8-flash-next-ud-q4_k_xl"
18KEY = open("/opt/hyperqwen-swift/api_key.txt").read().strip()
19H = {"Content-Type": "application/json", "Authorization": "Bearer " + KEY}
20SALT = int(time.time()) % 100000
21TOP = ["the history of navigation", "how a jet engine works", "the life cycle of a star", "the rules of chess",
22       "the economics of container shipping", "how vaccines train the immune system", "the design of suspension bridges",
23       "how compilers optimize loops"]
24
25
26def hay(n, seed):
27    w = ["amber", "birch", "cedar", "delta", "ember", "fjord", "grove", "harbor", "iris", "juniper"]
28    return "\n".join(f"Entry {i} (run {seed}): the {w[(i * 3 + seed) % 10]} station {(i * 7 + seed * 13) % 997} logged activity." for i in range(n))
29
30
31def run(prompt, mt, tune, out, key):
32    body = {"model": MODEL, "messages": [{"role": "user", "content": prompt}], "max_tokens": mt, "temperature": 0.0, "stream": True,
33            "stream_options": {"include_usage": True}, "chat_template_kwargs": {"enable_thinking": False}}
34    if tune:
35        body["strata_tune"] = tune
36    r = urllib.request.Request(BASE + "/v1/chat/completions", json.dumps(body).encode(), H)
37    t0 = time.time(); first = last = None; ct = pt = 0
38    with urllib.request.urlopen(r, timeout=1800) as f:
39        for raw in f:
40            l = raw.decode().strip()
41            if not l.startswith("data:") or l.endswith("[DONE]"):
42                continue
43            d = json.loads(l[5:])
44            if d.get("usage"):
45                ct, pt = d["usage"]["completion_tokens"], d["usage"]["prompt_tokens"]
46            for c in d.get("choices", []):
47                if c.get("delta", {}).get("content"):
48                    now = time.time(); first = first or now; last = now
49    out[key] = dict(ct=ct, pt=pt, t0=t0, first=first, last=last, end=time.time(),
50                    dec=((ct - 1) / (last - first)) if first and last and last > first and ct > 1 else float("nan"))
51
52
53def one(arm, rnd, ai):
54    tag = f"{SALT}-{rnd}-{ai}"
55    out = {}
56    if MODE == "solo":
57        run(f"[{tag}] Write a long detailed explanation of {TOP[rnd % 8]}.", 300, arm, out, 0)   # same topic for every arm of a round
58        return out[0]["dec"]
59    if MODE == "long":   # decode on a ~60k-token context: a shared prefix (read once, then cached), a unique question per arm and round
60        run(hay(2500, SALT) + f"\n\n[{tag}] Question: write a long detailed explanation of {TOP[rnd % 8]}, citing the entries above where useful.", 300, arm, out, 0)
61        return out[0]["dec"]
62    if MODE == "c2":
63        ts = [threading.Thread(target=run, args=(f"[{tag}-{i}] Write a long detailed essay about {TOP[(rnd + i) % 8]}.", 300, arm, out, i)) for i in range(2)]
64        for t in ts: t.start()
65        for t in ts: t.join()
66        return sum(o["dec"] for o in out.values())
67    if MODE == "read":
68        run(hay(1000, SALT * 7 + rnd * 3 + ai) + "\n\nQ: say OK.", 1, arm, out, 0)
69        return out[0]["pt"] / (out[0]["end"] - out[0]["t0"])
70    if MODE == "mix":
71        d = threading.Thread(target=run, args=(f"[{tag}] Write a very long essay about {TOP[rnd % 8]}.", 900, arm, out, "d")); d.start()
72        time.sleep(6)
73        run(hay(2000, SALT * 11 + rnd * 5 + ai) + "\n\nQ: say OK.", 1, arm, out, "big")
74        d.join()
75        read_s = out["big"]["end"] - out["big"]["t0"]
76        return (out["big"]["pt"] / read_s, out["d"]["ct"] / (out["d"]["end"] - out["d"]["t0"]))
77    raise SystemExit("bad mode")
78
79
80for _ in range(3):
81    run(f"[{SALT}w{_}] Say hi.", 8, {}, {}, 0)
82res = [[] for _ in ARMS]
83pos = [[] for _ in ARMS]
84for r in range(ROUNDS):
85    order = [(r + k) % N for k in range(N)]
86    for p, ai in enumerate(order):
87        v = one(ARMS[ai], r, ai)
88        res[ai].append(v); pos[ai].append(p)
89        print(f"round {r} pos {p} arm {ai} {json.dumps(ARMS[ai])}: {round(v, 1) if isinstance(v, float) else tuple(round(x, 1) for x in v)}", flush=True)
90
91
92def scal(x, k=0):
93    return x[k] if isinstance(x, tuple) else x
94
95
96for k, label in ((0, "main metric"),) + (((1, "stream tok/s during the read"),) if MODE == "mix" else ()):
97    print(f"\n== {MODE}: {label} ==")
98    base = [scal(x, k) for x in res[0]]
99    for ai, arm in enumerate(ARMS):
100        v = [scal(x, k) for x in res[ai]]
101        ratios = [b / a for a, b in zip(base, v) if a == a and b == b and a > 0]
102        print(f"arm {ai} {json.dumps(arm):<44} median {st.median(v):7.1f} mean {st.mean(v):7.1f} min {min(v):7.1f} max {max(v):7.1f}"
103              + (f" | vs A: median ratio {st.median(ratios):.3f} mean {st.mean(ratios):.3f} (n={len(ratios)})" if ai else ""))
104    # position bias: mean of (value / round mean) by position in the round
105    byp = {}
106    for r in range(ROUNDS):
107        vals = [scal(res[ai][r], k) for ai in range(N)]
108        m = st.mean(vals)
109        for ai in range(N):
110            byp.setdefault(pos[ai][r], []).append(scal(res[ai][r], k) / m)
111    print("position bias (value / round mean): " + ", ".join(f"pos{p}: {st.mean(v):.3f}" for p, v in sorted(byp.items())))