okami.mom/strata

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

Niko1221Merge f-141-fixb: Python, docs and bench fixes and portsef8071303

main
5.7 KiB118 linesraw
1"""tools/needle_bench.py - needle-in-a-haystack recall through a running Strata server.
2
3A long text is built from files in this repository (its docs and source code, and the llama.cpp docs setup downloads
4into third_party/), a code word is hidden in it at a chosen depth, and the model is asked for it through the normal
5API (thinking off, greedy). One line per test: length, depth, found or not, prompt tokens, time.
6
7    python tools/needle_bench.py                                  # 32K at depths 10/50/90, http://127.0.0.1:8080
8    python tools/needle_bench.py --lengths 32k,128k,262k --depths 10,50,90 --url http://127.0.0.1:8081
9    python tools/needle_bench.py --out needles.json --api-key KEY
10
11The lengths are targets, 2% under so that "128k" fits a 128K context: the text is cut by characters (about 3.2 per
12token), and the line reports the prompt's real token count from the server. A length the server's context cannot hold is skipped.
13"""
14from __future__ import annotations
15
16import argparse
17import json
18import random
19import sys
20import time
21import urllib.error
22import urllib.request
23from pathlib import Path
24
25ROOT = Path(__file__).resolve().parent.parent
26SOURCES = [("docs", "*.md"), ("src", "*.cpp"), ("src", "*.cu"), ("include", "*.hpp"), ("serve", "*.py"), ("tools", "*.py"),
27           ("third_party/llama.cpp/docs", "*.md")]
28WORDS = ["amber", "falcon", "quartz", "willow", "copper", "harbor", "saffron", "glacier", "orchid", "lantern",
29         "meadow", "cobalt", "juniper", "tundra", "velvet", "ember"]
30CHARS_PER_TOKEN = 3.2
31
32
33def haystack(n_chars: int) -> str:
34    """Deterministic filler: the repository's text files in a fixed order, repeated if needed."""
35    files = []
36    for d, pat in SOURCES:
37        files += sorted((ROOT / d).rglob(pat))
38    parts, total = [], 0
39    while total < n_chars:
40        for f in files:
41            try:
42                t = f.read_text(encoding="utf-8", errors="replace")
43            except OSError:
44                continue
45            parts.append(f"\n\n=== {f.relative_to(ROOT).as_posix()} ===\n{t}")
46            total += len(parts[-1])
47            if total >= n_chars:
48                break
49        if not files:
50            raise SystemExit("no text files found to build the haystack from")
51    return "".join(parts)[:n_chars]
52
53
54def ask(url: str, key: str, prompt: str, timeout: float) -> tuple[str, int, float]:
55    body = {"model": "strata", "max_tokens": 40, "temperature": 0,
56            "chat_template_kwargs": {"enable_thinking": False},
57            "messages": [{"role": "user", "content": prompt}]}
58    headers = {"Content-Type": "application/json"}
59    if key:
60        headers["Authorization"] = "Bearer " + key
61    t0 = time.time()
62    req = urllib.request.Request(url.rstrip("/") + "/v1/chat/completions", data=json.dumps(body).encode(), headers=headers)
63    with urllib.request.urlopen(req, timeout=timeout) as r:
64        out = json.loads(r.read())
65    return (out["choices"][0]["message"].get("content") or ""), out["usage"]["prompt_tokens"], time.time() - t0
66
67
68def main() -> int:
69    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
70    ap.add_argument("--url", default="http://127.0.0.1:8080")
71    ap.add_argument("--api-key", default="")
72    ap.add_argument("--lengths", default="32k", help="comma-separated, e.g. 1k,32k,128k,262k")
73    ap.add_argument("--depths", default="10,50,90", help="where the code word sits, percent of the text")
74    ap.add_argument("--timeout", type=float, default=1800)
75    ap.add_argument("--out", help="also write the results as JSON")
76    a = ap.parse_args()
77    try:
78        with urllib.request.urlopen(a.url.rstrip("/") + "/metrics", timeout=10) as r:
79            ctx = int((json.loads(r.read()).get("engine") or {}).get("max_context") or 0)
80    except (OSError, ValueError):
81        ctx = 0
82    rnd = random.Random(7)
83    rows, found = [], 0
84    for L in a.lengths.split(","):
85        tokens = int(float(L.lower().rstrip("k")) * 1024) if L.lower().endswith("k") else int(L)
86        tokens = int(tokens * 0.98)                        # "128k" fits a 128K context with room to answer
87        if ctx and tokens + 200 > ctx:
88            print(f"{L:>5}: skipped (the server's context is {ctx})")
89            continue
90        text = haystack(int(tokens * CHARS_PER_TOKEN))
91        for d in (int(x) for x in a.depths.split(",")):
92            word = f"{rnd.choice(WORDS)}-{rnd.choice(WORDS)}-{rnd.randint(100, 999)}"
93            cut = int(len(text) * d / 100)
94            cut = text.rfind("\n", 0, cut) + 1 or cut          # at a line start
95            needle = f"\nThe secret code word for this text is: {word}. Remember it.\n"
96            prompt = (text[:cut] + needle + text[cut:] +
97                      "\n\nWhat is the secret code word mentioned in the text above? Reply with the code word only.")
98            try:
99                answer, n, secs = ask(a.url, a.api_key, prompt, a.timeout)
100            except (OSError, urllib.error.HTTPError) as e:
101                print(f"{L:>5} depth {d:>3}%: request failed ({e})")
102                rows.append({"length": L, "depth": d, "error": str(e)})
103                continue
104            ok = word in answer
105            found += ok
106            print(f"{L:>5} depth {d:>3}%: {'FOUND' if ok else 'missed'}  ({n:,} prompt tokens, {secs:.0f} s)"
107                  + ("" if ok else f"  answer: {answer.strip()[:80]!r}"), flush=True)
108            rows.append({"length": L, "depth": d, "prompt_tokens": n, "seconds": round(secs, 1), "found": ok,
109                         "word": word, "answer": answer.strip()[:200]})
110    done = [r for r in rows if "found" in r]
111    print(f"{found} of {len(done)} found")
112    if a.out:
113        Path(a.out).write_text(json.dumps(rows, indent=1), encoding="utf-8")
114    return 0 if done and found == len(done) else 1
115
116
117if __name__ == "__main__":
118    sys.exit(main())