okami.mom/strata

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

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

main
6.3 KiB133 linesraw
1"""thread_bench.py - velocita' di generazione a contesto lungo su un thread VERO di Jan.
2
3Gemello di long_bench.py: invece di un file di testo manda i messaggi di un thread di Jan (messages.jsonl), in
4ordine, piu' una domanda fissa in fondo che chiede almeno 600 parole, cosi' ogni corsa genera esattamente
5--max-tokens token. Testo dei messaggi: le parti `text`; le chiamate ai tool scritte come testo nel messaggio
6dell'assistente; i ragionamenti vecchi tolti (il template non li rimanda comunque).
7
8    1. run-thread.bat sp05     (oppure sp06, sp07) e aspetta "ready"
9    2. python thread_bench.py --label thread-sp05-0.1.36 --runs 9
10    3. chiudi il server, avvia l'altro braccio, ripeti
11    4. python perm_test.py thread-sp05-0.1.36 thread-sp06-0.1.36
12
13La prima richiesta paga la lettura a freddo (campione singolo, non entra nelle corse). Le corse riusano il prefisso
14in cache. Contatore della porta (guard.py): una richiesta estranea rende la misura SPORCA e il file non si salva.
15Il risultato va in C:\\strata-lab\\results\\pw-<label>.json, stesso schema di pw_bench / long_bench.
16"""
17from __future__ import annotations
18
19import argparse
20import json
21import statistics
22import sys
23import time
24import urllib.request
25from pathlib import Path
26
27from guard import report_extra, requests_total
28
29THREAD = r"C:\strata-lab\jan-threads\nasdaqpredictor-50c5608c-2026-10-02\messages.jsonl"
30QUESTION = ("Riassumi in dettaglio tutto il lavoro svolto in questa conversazione: per ogni fase indica cosa e' "
31            "stato fatto, quali file e quali risultati numerici sono stati prodotti e quali decisioni sono state "
32            "prese. Scrivi almeno 600 parole.")
33
34
35def part_text(x) -> str:
36    if isinstance(x, str):
37        return x
38    if isinstance(x, dict) and "value" in x:
39        return str(x["value"])
40    return json.dumps(x, ensure_ascii=False)
41
42
43def thread_messages(path: str) -> list[dict]:
44    msgs = []
45    for line in open(path, encoding="utf-8"):
46        m = json.loads(line)
47        pieces = []
48        for c in m["content"]:
49            if c["type"] == "text":
50                pieces.append(part_text(c["text"]))
51            elif c["type"] == "tool_call":
52                pieces.append(f"[tool {c.get('tool_name')}]\n{part_text(c.get('input'))}\n"
53                              f"[risultato]\n{part_text(c.get('output'))}")
54        msgs.append({"role": m["role"], "content": "\n\n".join(p for p in pieces if p)})
55    return msgs
56
57
58def one(url: str, messages: list[dict], max_tokens: int, timeout: float) -> dict:
59    body = {"model": "strata", "max_tokens": max_tokens, "temperature": 0,
60            "chat_template_kwargs": {"enable_thinking": False},
61            "messages": messages + [{"role": "user", "content": QUESTION}]}
62    req = urllib.request.Request(url.rstrip("/") + "/v1/chat/completions", data=json.dumps(body).encode(),
63                                 headers={"Content-Type": "application/json"})
64    t0 = time.time()
65    with urllib.request.urlopen(req, timeout=timeout) as r:
66        out = json.loads(r.read())
67    wall = time.time() - t0
68    t = out["timings"]
69    text = out["choices"][0]["message"].get("content") or ""
70    return {"tok_s": t["predicted_per_second"], "n": t["predicted_n"], "wall_s": round(wall, 1),
71            "cache_n": t["cache_n"], "prompt_n": t["prompt_n"], "prompt_ms": t["prompt_ms"],
72            "prompt_per_second": t["prompt_per_second"],
73            "draft_n": t.get("draft_n"), "draft_n_accepted": t.get("draft_n_accepted"),
74            "finish": out["choices"][0].get("finish_reason"), "text_head": text[:80]}
75
76
77def main() -> int:
78    ap = argparse.ArgumentParser()
79    ap.add_argument("--label", required=True, help="es. thread-sp05-0.1.36")
80    ap.add_argument("--thread", default=THREAD)
81    ap.add_argument("--url", default="http://127.0.0.1:8080")
82    ap.add_argument("--max-tokens", type=int, default=512)
83    ap.add_argument("--runs", type=int, default=9)
84    ap.add_argument("--timeout", type=float, default=7200)
85    a = ap.parse_args()
86
87    out = Path(r"C:\strata-lab\results") / f"pw-{a.label}.json"
88    if out.exists():
89        print(f"{out} esiste gia': scegli un'altra etichetta")
90        return 1
91    messages = thread_messages(a.thread)
92    print(f"thread: {a.thread}, {len(messages)} messaggi, {sum(len(m['content']) for m in messages)} caratteri",
93          flush=True)
94    reqs_before = requests_total(a.url)
95
96    print("lettura a freddo (campione singolo, scalda la cache del prompt) ...", flush=True)
97    cold = one(a.url, messages, a.max_tokens, a.timeout)
98    print(f"  prompt {cold['prompt_n']} token in {cold['prompt_ms'] / 1000:.1f} s "
99          f"({cold['prompt_per_second']} tok/s), cache_n {cold['cache_n']}; "
100          f"generazione {cold['tok_s']} tok/s su {cold['n']} token", flush=True)
101
102    runs = []
103    for i in range(a.runs):
104        r = one(a.url, messages, a.max_tokens, a.timeout)
105        runs.append(r)
106        acc = f"{r['draft_n_accepted'] / r['draft_n']:.3f}" if r["draft_n"] else "-"
107        print(f"corsa {i + 1}: {r['tok_s']} tok/s, {r['n']} token, {r['wall_s']} s, "
108              f"cache_n {r['cache_n']}, prompt_n {r['prompt_n']}, bozze accettate {acc}", flush=True)
109
110    reqs_after = requests_total(a.url)
111    clean = report_extra(reqs_after - reqs_before - 1 - a.runs, "il banco", reqs_before, reqs_after)
112    ns = {r["n"] for r in runs}
113    if len(ns) != 1:
114        print(f"ATTENZIONE: le corse non hanno generato lo stesso numero di token ({sorted(ns)}): "
115              "il confronto non e' alla pari")
116    if any(r["cache_n"] == 0 for r in runs):
117        print("ATTENZIONE: qualche corsa ha riletto il prompt da zero (cache_n 0): non e' il regime voluto")
118    speeds = [r["tok_s"] for r in runs]
119    acc_all = [r["draft_n_accepted"] / r["draft_n"] for r in runs if r["draft_n"]]
120    print(f"\n{a.label}: mediana {statistics.median(speeds)} tok/s, media {statistics.mean(speeds):.2f}, "
121          f"min {min(speeds)}, max {max(speeds)}"
122          + (f"; bozze accettate media {statistics.mean(acc_all):.3f}" if acc_all else ""))
123    if not clean:
124        print("NON salvato: misura sporca.")
125        return 1
126    out.write_text(json.dumps({"label": a.label, "max_tokens": a.max_tokens, "thread": a.thread,
127                               "question": QUESTION, "prefill_freddo": cold, "runs": runs}, indent=1))
128    print(f"salvato in {out}")
129    return 0
130
131
132if __name__ == "__main__":
133    sys.exit(main())