okami.mom/strata

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

sarge18Community benchmark: 2x Tesla P40 22 GB (Pascal, experimental CUDA 12), single card and layer split (#1028)3f4d44ece

main
32.4 KiB476 linesraw
1#!/usr/bin/env python3
2"""bench.py - engine-agnostic benchmark: speed + accuracy + completeness + reliability.
3
4One client for Strata / llama-server (OpenAI /v1/chat/completions, streaming) and Ollama (/api/chat, streaming).
5Everything is graded against ground truth computed or executed here - never model self-report:
6  reasoning   40 programmatic questions (answers computed in Python, fixed seed)
7  code        12 functions graded by executing hidden tests in a subprocess
8  tools       8 tool-call cases (name + args exact, plus restraint cases that must NOT call a tool)
9  complete    6 completeness tasks (exact lists / required sections / valid JSON) + finish_reason
10  longctx     needle recall at several prompt sizes (3 facts at 20/50/80 % depth)
11  speed       fixed-size prompts: decode tok/s, prefill tok/s, TTFT (client-side AND server-reported)
12Every record keeps the raw output, finish_reason, token counts and the effective request, so a score can be re-derived.
13
14--selftest runs the graders against an oracle (must be 100 %) and a garbage engine (must be 0 %) - run it before trusting numbers.
15Stdlib only (runs inside a no-network namespace as an unprivileged user).
16"""
17import argparse, http.client, json, os, random, re, subprocess, sys, tempfile, time, datetime, urllib.parse
18
19SEED = 1234
20
21# --------------------------------------------------------------------------- engines
22class Result(dict):
23    pass
24
25def _post_stream(url, payload, timeout):
26    u = urllib.parse.urlparse(url)
27    conn = http.client.HTTPConnection(u.hostname, u.port, timeout=timeout)
28    conn.request("POST", u.path, body=json.dumps(payload), headers={"Content-Type": "application/json", "Host": "127.0.0.1:%d" % u.port})
29    resp = conn.getresponse()
30    if resp.status != 200:
31        body = resp.read(2000).decode("utf-8", "replace")
32        conn.close()
33        raise RuntimeError("HTTP %d: %s" % (resp.status, body))
34    return conn, resp
35
36def call_openai(base, model, messages, max_tokens, think, tools, timeout):
37    payload = {"model": model, "messages": messages, "stream": True, "stream_options": {"include_usage": True},
38               "temperature": 0, "top_k": 1, "top_p": 1, "seed": 1, "max_tokens": max_tokens,
39               "chat_template_kwargs": {"enable_thinking": bool(think)}}
40    if not think:
41        payload["reasoning_effort"] = "none"   # Strata honours this; llama-server ignores unknown fields
42    if tools:
43        payload["tools"] = tools
44    t0 = time.time(); first = None
45    text, reasoning, finish, usage, timings = [], [], None, None, None
46    tcalls = {}
47    conn, resp = _post_stream(base + "/v1/chat/completions", payload, timeout)
48    try:
49        for raw in resp:
50            line = raw.decode("utf-8", "replace").strip()
51            if not line.startswith("data:"):
52                continue
53            data = line[5:].strip()
54            if data == "[DONE]":
55                break
56            ch = json.loads(data)
57            if ch.get("usage"):
58                usage = ch["usage"]
59            if ch.get("timings"):
60                timings = ch["timings"]
61            for c in ch.get("choices", []):
62                d = c.get("delta", {})
63                if d.get("content"):
64                    first = first or time.time(); text.append(d["content"])
65                rc = d.get("reasoning_content") or d.get("reasoning")
66                if rc:
67                    first = first or time.time(); reasoning.append(rc)
68                for tc in d.get("tool_calls") or []:
69                    first = first or time.time()
70                    slot = tcalls.setdefault(tc.get("index", 0), {"name": "", "arguments": ""})
71                    f = tc.get("function", {})
72                    slot["name"] += f.get("name") or ""
73                    slot["arguments"] += f.get("arguments") or ""
74                if c.get("finish_reason"):
75                    finish = c["finish_reason"]
76    finally:
77        conn.close()
78    t1 = time.time()
79    calls = []
80    for k in sorted(tcalls):
81        try:
82            args = json.loads(tcalls[k]["arguments"] or "{}")
83        except Exception:
84            args = {"_unparsed": tcalls[k]["arguments"]}
85        calls.append({"name": tcalls[k]["name"], "arguments": args})
86    ct = (usage or {}).get("completion_tokens")
87    return Result(text="".join(text), reasoning="".join(reasoning), finish_reason=finish, tool_calls=calls,
88                  prompt_tokens=(usage or {}).get("prompt_tokens"), completion_tokens=ct,
89                  t_total=t1 - t0, t_first=(first - t0) if first else None, server_timings=timings, error=None)
90
91def call_ollama(base, model, messages, max_tokens, think, tools, timeout, num_ctx):
92    payload = {"model": model, "messages": messages, "stream": True, "think": bool(think),
93               "options": {"num_ctx": num_ctx, "num_predict": max_tokens, "temperature": 0, "top_k": 1, "top_p": 1,
94                           "seed": 1, "repeat_penalty": 1.0}}
95    if tools:
96        payload["tools"] = tools
97    t0 = time.time(); first = None
98    text, reasoning, final, calls = [], [], {}, []
99    conn, resp = _post_stream(base + "/api/chat", payload, timeout)
100    try:
101        for raw in resp:
102            line = raw.decode("utf-8", "replace").strip()
103            if not line:
104                continue
105            ch = json.loads(line)
106            m = ch.get("message", {})
107            if m.get("content"):
108                first = first or time.time(); text.append(m["content"])
109            if m.get("thinking"):
110                first = first or time.time(); reasoning.append(m["thinking"])
111            for tc in m.get("tool_calls") or []:
112                first = first or time.time()
113                f = tc.get("function", {})
114                calls.append({"name": f.get("name", ""), "arguments": f.get("arguments", {})})
115            if ch.get("done"):
116                final = ch
117    finally:
118        conn.close()
119    t1 = time.time()
120    ns = lambda k: (final.get(k) or 0) / 1e9
121    st = {"prompt_n": final.get("prompt_eval_count"), "prompt_ms": ns("prompt_eval_duration") * 1000,
122          "predicted_n": final.get("eval_count"), "predicted_ms": ns("eval_duration") * 1000,
123          "load_ms": ns("load_duration") * 1000}
124    if st["prompt_ms"]:
125        st["prompt_per_second"] = (st["prompt_n"] or 0) / (st["prompt_ms"] / 1000)
126    if st["predicted_ms"]:
127        st["predicted_per_second"] = (st["predicted_n"] or 0) / (st["predicted_ms"] / 1000)
128    return Result(text="".join(text), reasoning="".join(reasoning), finish_reason=final.get("done_reason"),
129                  tool_calls=calls, prompt_tokens=final.get("prompt_eval_count"), completion_tokens=final.get("eval_count"),
130                  t_total=t1 - t0, t_first=(first - t0) if first else None, server_timings=st, error=None)
131
132class Oracle:
133    """Engine stand-in for --selftest: returns the task's known-correct answer (or garbage)."""
134    def __init__(self, good): self.good = good
135    def __call__(self, task):
136        if task.get("tools"):
137            calls = task["oracle_calls"] if self.good else [{"name": "bogus", "arguments": {}}]
138            return Result(text="", reasoning="", finish_reason="tool_calls" if calls else "stop", tool_calls=calls if self.good or True else [],
139                          prompt_tokens=1, completion_tokens=1, t_total=0.01, t_first=0.01, server_timings=None, error=None)
140        txt = task["oracle"] if self.good else "I do not know."
141        return Result(text=txt, reasoning="", finish_reason="stop", tool_calls=[], prompt_tokens=1, completion_tokens=1,
142                      t_total=0.01, t_first=0.01, server_timings=None, error=None)
143
144# --------------------------------------------------------------------------- tasks: reasoning (programmatic)
145def norm(s):
146    s = s.strip().strip("`*\"'").rstrip(".").strip()
147    s = s.replace(",", "") if re.fullmatch(r"-?[\d,]+(\.\d+)?", s) else s
148    return s.lower()
149
150def last_answer(text):
151    m = re.findall(r"ANSWER:\s*(.+)", text)
152    return m[-1].strip() if m else None
153
154def grade_answer(task, res):
155    a = last_answer(res["text"])
156    return a is not None and norm(a) == norm(task["expected"]), {"got": a, "expected": task["expected"]}
157
158FMT = "\n\nThink briefly if needed, then give the final result on the last line formatted exactly as 'ANSWER: <answer>'."
159
160def make_reasoning():
161    import datetime as dt
162    r = random.Random(SEED); out = []
163    def add(q, exp):
164        out.append({"id": "reason-%02d" % (len(out) + 1), "category": "reasoning", "messages": [{"role": "user", "content": q + FMT}],
165                    "max_tokens": 1024, "expected": str(exp), "oracle": "ANSWER: %s" % exp, "grader": "answer"})
166    for _ in range(8):
167        a, b = r.randint(120, 9800), r.randint(12, 990); add("What is %d * %d?" % (a, b), a * b)
168    for _ in range(5):
169        a, b, c, d = r.randint(100, 999), r.randint(100, 999), r.randint(3, 40), r.randint(3, 40); add("Compute %d + %d - %d * %d." % (a, b, c, d), a + b - c * d)
170    words = ["strawberry", "mississippi", "bookkeeper", "committee", "rhythm", "banana bandana", "assassin", "occurrence", "parallel lines", "successful"]
171    for w in r.sample(words, 5):
172        ch = r.choice(sorted(set(w.replace(" ", ""))))
173        add("How many times does the letter '%s' appear in the text \"%s\"? (case-insensitive)" % (ch, w), w.lower().count(ch))
174    for _ in range(5):
175        d0 = dt.date(r.randint(2019, 2031), r.randint(1, 12), r.randint(1, 28)); n = r.randint(40, 900)
176        add("What day of the week is it %d days after %s? Answer with the weekday name only." % (n, d0.isoformat()), (d0 + dt.timedelta(days=n)).strftime("%A"))
177    for _ in range(2):
178        n = r.randint(200, 4000); add("Convert the decimal number %d to binary (digits only, no prefix)." % n, bin(n)[2:])
179    for _ in range(2):
180        n = r.randint(3000, 60000); add("Convert the decimal number %d to hexadecimal (uppercase, no prefix)." % n, "%X" % n)
181    for _ in range(4):
182        xs = r.sample(range(10, 99), 8); add("Here is a list: %s. What is the third largest number in it?" % xs, sorted(xs)[-3])
183    for _ in range(3):
184        a, b, m = r.randint(3, 12), r.randint(5, 40), r.randint(7, 97); add("What is %d^%d mod %d?" % (a, b, m), pow(a, b, m))
185    for _ in range(3):
186        v, t = r.randint(30, 90), r.randint(2, 9); add("A train travels at %d km/h for %d hours and then 2 more hours at %d km/h. What total distance in km did it cover?" % (v, t, v + 10), v * t + 2 * (v + 10))
187    for w in r.sample(["calculator", "photograph", "microscope"], 3):
188        add("Write the word '%s' backwards (letters only)." % w, w[::-1])
189    return out
190
191# --------------------------------------------------------------------------- tasks: code (executed hidden tests)
192CODE_TASKS = [
193 ("is_balanced", "is_balanced(s: str) -> bool: True if every (), [], {} in s is correctly nested and closed; ignore other characters.",
194  [(["([]{})"], True), (["([)]"], False), (["a(b)c]"], False), ([""], True), (["{[()()]}"], True), (["(("], False)]),
195 ("roman_to_int", "roman_to_int(s: str) -> int: convert a valid Roman numeral (1..3999) to an integer.",
196  [(["III"], 3), (["LVIII"], 58), (["MCMXCIV"], 1994), (["IV"], 4), (["MMMCMXCIX"], 3999)]),
197 ("merge_intervals", "merge_intervals(iv: list) -> list: iv is a list of [start, end] pairs; return merged overlapping/touching intervals sorted by start, as lists.",
198  [([[[1, 3], [2, 6], [8, 10], [15, 18]]], [[1, 6], [8, 10], [15, 18]]), ([[[1, 4], [4, 5]]], [[1, 5]]), ([[]], []), ([[[5, 7], [1, 2], [2, 3]]], [[1, 3], [5, 7]])]),
199 ("lcs_length", "lcs_length(a: str, b: str) -> int: length of the longest common subsequence.",
200  [(["abcde", "ace"], 3), (["abc", "def"], 0), (["", "abc"], 0), (["AGGTAB", "GXTXAYB"], 4)]),
201 ("flatten", "flatten(x) -> list: flatten arbitrarily nested lists of ints into one flat list, preserving order.",
202  [([[1, [2, [3, [4]], 5]]], [1, 2, 3, 4, 5]), ([[]], []), ([[[], [[]], 7]], [7])]),
203 ("top_words", "top_words(text: str, k: int) -> list: the k most frequent words (lowercase, words are runs of letters a-z/A-Z) as a list of [word, count], sorted by count descending then word ascending.",
204  [(["the cat and the hat and the bat", 2], [["the", 3], ["and", 2]]), (["A a b B c", 2], [["a", 2], ["b", 2]]), (["", 3], [])]),
205 ("rotate_matrix", "rotate_matrix(m: list) -> list: rotate a square matrix (list of lists) 90 degrees clockwise and return a new matrix.",
206  [([[[1, 2], [3, 4]]], [[3, 1], [4, 2]]), ([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]], [[7, 4, 1], [8, 5, 2], [9, 6, 3]]), ([[[5]]], [[5]])]),
207 ("valid_ipv4", "valid_ipv4(s: str) -> bool: True iff s is a valid dotted-quad IPv4 address: exactly 4 decimal parts 0-255, no leading zeros (except '0' itself), digits only.",
208  [(["192.168.1.1"], True), (["256.1.1.1"], False), (["01.2.3.4"], False), (["1.2.3"], False), (["1.2.3.4.5"], False), (["0.0.0.0"], True), (["a.b.c.d"], False), (["1..2.3"], False)]),
209 ("prime_factors", "prime_factors(n: int) -> list: prime factorization of n >= 2 as a sorted list with repetition.",
210  [([12], [2, 2, 3]), ([97], [97]), ([360], [2, 2, 2, 3, 3, 5]), ([2 ** 10], [2] * 10), ([1001], [7, 11, 13])]),
211 ("longest_palindrome", "longest_palindrome(s: str) -> str: the longest palindromic substring; on ties return the one that starts earliest; empty string for empty input.",
212  [(["babad"], "bab"), (["cbbd"], "bb"), (["a"], "a"), ([""], ""), (["forgeeksskeegfor"], "geeksskeeg")]),
213 ("eval_rpn", "eval_rpn(tokens: list) -> int: evaluate a Reverse Polish Notation expression given as a list of strings with + - * /; division truncates toward zero.",
214  [([["2", "1", "+", "3", "*"]], 9), ([["4", "13", "5", "/", "+"]], 6), ([["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]], 22), ([["7", "-2", "/"]], -3)]),
215 ("parse_duration", "parse_duration(s: str) -> int: convert strings like '1h30m15s', '45s', '2h', '10m5s' (any subset of h, m, s in that order) to total seconds; return 0 for an empty string.",
216  [(["1h30m15s"], 5415), (["45s"], 45), (["2h"], 7200), (["10m5s"], 605), ([""], 0)]),
217]
218
219def make_code():
220    out = []
221    for name, spec, tests in CODE_TASKS:
222        out.append({"id": "code-" + name, "category": "code", "max_tokens": 1500, "grader": "code", "fn": name, "tests": tests,
223                    "messages": [{"role": "user", "content": "Write a Python 3 function with this signature and behaviour:\n\n%s\n\nReturn only one ```python code block containing the function (and any imports/helpers it needs). No example usage, no prints." % spec}],
224                    "oracle": None})
225    return out
226
227REF_IMPL = {  # reference solutions used ONLY by --selftest to prove the hidden tests are correct and passable
228 "is_balanced": "def is_balanced(s):\n    st=[];p={')':'(',']':'[','}':'{'}\n    for c in s:\n        if c in '([{': st.append(c)\n        elif c in p:\n            if not st or st.pop()!=p[c]: return False\n    return not st",
229 "roman_to_int": "def roman_to_int(s):\n    v={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000};t=0\n    for i,c in enumerate(s):\n        t+= -v[c] if i+1<len(s) and v[c]<v[s[i+1]] else v[c]\n    return t",
230 "merge_intervals": "def merge_intervals(iv):\n    r=[]\n    for a,b in sorted(iv):\n        if r and a<=r[-1][1]: r[-1][1]=max(r[-1][1],b)\n        else: r.append([a,b])\n    return r",
231 "lcs_length": "def lcs_length(a,b):\n    d=[[0]*(len(b)+1) for _ in range(len(a)+1)]\n    for i in range(len(a)):\n        for j in range(len(b)):\n            d[i+1][j+1]=d[i][j]+1 if a[i]==b[j] else max(d[i][j+1],d[i+1][j])\n    return d[-1][-1]",
232 "flatten": "def flatten(x):\n    o=[]\n    for e in x:\n        o+= flatten(e) if isinstance(e,list) else [e]\n    return o",
233 "top_words": "import re,collections\ndef top_words(text,k):\n    c=collections.Counter(w.lower() for w in re.findall(r'[A-Za-z]+',text))\n    return [[w,n] for w,n in sorted(c.items(),key=lambda t:(-t[1],t[0]))[:k]]",
234 "rotate_matrix": "def rotate_matrix(m):\n    return [list(r) for r in zip(*m[::-1])]",
235 "valid_ipv4": "def valid_ipv4(s):\n    p=s.split('.')\n    return len(p)==4 and all(x.isdigit() and x.isascii() and (x=='0' or not x.startswith('0')) and int(x)<=255 for x in p)",
236 "prime_factors": "def prime_factors(n):\n    f=[];d=2\n    while d*d<=n:\n        while n%d==0: f.append(d);n//=d\n        d+=1\n    if n>1: f.append(n)\n    return f",
237 "longest_palindrome": "def longest_palindrome(s):\n    b=''\n    for i in range(len(s)):\n        for j in range(i,len(s)):\n            t=s[i:j+1]\n            if t==t[::-1] and len(t)>len(b): b=t\n    return b",
238 "eval_rpn": "def eval_rpn(tokens):\n    st=[]\n    for t in tokens:\n        if t in '+-*/' and len(t)==1:\n            b=st.pop();a=st.pop()\n            st.append(a+b if t=='+' else a-b if t=='-' else a*b if t=='*' else int(a/b))\n        else: st.append(int(t))\n    return st[0]",
239 "parse_duration": "import re\ndef parse_duration(s):\n    m=re.fullmatch(r'(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?',s)\n    h,mi,se=(int(x) if x else 0 for x in m.groups())\n    return h*3600+mi*60+se",
240}
241
242def extract_code(text):
243    blocks = re.findall(r"```(?:python|py)?\s*\n(.*?)```", text, re.S)
244    return max(blocks, key=len) if blocks else None
245
246def grade_code(task, res):
247    code = extract_code(res["text"])
248    if not code:
249        return False, {"error": "no code block"}
250    harness = code + "\n\nimport json,sys\n_T=json.loads(sys.stdin.read())\n_ok=0;_fail=[]\nfor a,e in _T:\n    try:\n        g=%s(*a)\n    except Exception as ex:\n        g='EXC '+type(ex).__name__\n    if g==e: _ok+=1\n    else: _fail.append([a,e,g])\nprint(json.dumps({'ok':_ok,'n':len(_T),'fail':_fail[:3]}))\n" % task["fn"]
251    with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:
252        f.write(harness); path = f.name
253    try:
254        p = subprocess.run([sys.executable, "-I", path], input=json.dumps(task["tests"]), capture_output=True, text=True, timeout=15)
255        out = json.loads(p.stdout.strip().splitlines()[-1]) if p.stdout.strip() else {"error": (p.stderr or "no output")[-300:]}
256    except subprocess.TimeoutExpired:
257        out = {"error": "timeout"}
258    except Exception as ex:
259        out = {"error": repr(ex)}
260    finally:
261        os.unlink(path)
262    return out.get("ok") == out.get("n") and "error" not in out, out
263
264# --------------------------------------------------------------------------- tasks: tool calling
265TOOLS = [
266 {"type": "function", "function": {"name": "get_weather", "description": "Get current weather for a city.", "parameters": {"type": "object", "properties": {"city": {"type": "string"}, "unit": {"type": "string", "enum": ["c", "f"]}}, "required": ["city", "unit"]}}},
267 {"type": "function", "function": {"name": "set_timer", "description": "Set a countdown timer.", "parameters": {"type": "object", "properties": {"minutes": {"type": "integer"}, "label": {"type": "string"}}, "required": ["minutes", "label"]}}},
268 {"type": "function", "function": {"name": "search_docs", "description": "Search the internal documentation.", "parameters": {"type": "object", "properties": {"query": {"type": "string"}, "limit": {"type": "integer"}}, "required": ["query", "limit"]}}},
269 {"type": "function", "function": {"name": "send_email", "description": "Send an email.", "parameters": {"type": "object", "properties": {"to": {"type": "string"}, "subject": {"type": "string"}, "body": {"type": "string"}}, "required": ["to", "subject", "body"]}}},
270]
271TOOL_CASES = [
272 ("What's the weather in Paris right now? I want Celsius.", ("get_weather", {"city": "paris", "unit": "c"})),
273 ("Tell me the temperature in Denver in Fahrenheit.", ("get_weather", {"city": "denver", "unit": "f"})),
274 ("Set a timer for 25 minutes labelled pasta.", ("set_timer", {"minutes": 25, "label": "pasta"})),
275 ("Look up 'rotate api keys' in the docs, give me the top 5 results.", ("search_docs", {"query": "rotate api keys", "limit": 5})),
276 ("Email bob@example.com with subject 'Lunch' and body 'Noon works for me.'", ("send_email", {"to": "bob@example.com", "subject": "lunch", "body": "noon works for me."})),
277 ("Remind me in 90 minutes to call mom, use the label 'call mom'.", ("set_timer", {"minutes": 90, "label": "call mom"})),
278 ("What is the capital of France?", None),
279 ("Explain in one sentence what a hash table is.", None),
280]
281
282def make_tools():
283    out = []
284    for i, (q, exp) in enumerate(TOOL_CASES, 1):
285        calls = [{"name": exp[0], "arguments": exp[1]}] if exp else []
286        out.append({"id": "tool-%02d" % i, "category": "tools", "max_tokens": 512, "grader": "tool", "expected_call": exp, "tools": TOOLS,
287                    "oracle_calls": calls, "oracle": None, "messages": [{"role": "system", "content": "You are a helpful assistant. Use a tool only when one is needed."}, {"role": "user", "content": q}]})
288    return out
289
290def _eqv(a, b):
291    if isinstance(a, str) and isinstance(b, str):
292        return a.strip().lower() == b.strip().lower()
293    return a == b
294
295def grade_tool(task, res):
296    exp, calls = task["expected_call"], res["tool_calls"]
297    if exp is None:
298        return (len(calls) == 0), {"calls": calls}
299    if not calls:
300        return False, {"calls": calls, "note": "no tool call"}
301    c = calls[0]
302    ok = c["name"] == exp[0] and set(c["arguments"].keys()) == set(exp[1].keys()) and all(_eqv(c["arguments"].get(k), v) for k, v in exp[1].items())
303    return ok, {"calls": calls}
304
305# --------------------------------------------------------------------------- tasks: completeness
306PRIMES = [p for p in range(2, 600) if all(p % d for d in range(2, int(p ** .5) + 1))][:100]
307ELEMENTS = ["H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg"]
308SECTIONS = ["Overview", "Installation", "Usage", "Configuration", "Troubleshooting", "License"]
309
310def make_complete():
311    def t(id, q, mt, kind, oracle, **kw):
312        d = {"id": "complete-" + id, "category": "complete", "max_tokens": mt, "grader": "complete", "kind": kind, "oracle": oracle,
313             "messages": [{"role": "user", "content": q}]}
314        d.update(kw); return d
315    js = json.dumps([{"id": i, "name": "item%d" % i, "squares": i * i} for i in range(1, 21)])
316    return [
317     t("primes100", "List the first 100 prime numbers, comma-separated, in ascending order. Output only the numbers.", 2048, "ints", ", ".join(map(str, PRIMES)), expected_ints=PRIMES),
318     t("count150", "Write the integers from 1 to 150 separated by single spaces. Output only the numbers.", 2048, "ints", " ".join(map(str, range(1, 151))), expected_ints=list(range(1, 151))),
319     t("alpha_rev", "Write the English alphabet in reverse order, uppercase letters separated by commas. Output only the letters.", 512, "letters", ", ".join(chr(c) for c in range(90, 64, -1)), expected_letters=[chr(c) for c in range(90, 64, -1)]),
320     t("sections", "Write a project README in Markdown with exactly these H2 sections, in this order: %s. Every section must contain at least 3 full sentences." % ", ".join(SECTIONS), 2048, "sections",
321       "\n".join("## %s\nThis is sentence one. This is sentence two. This is sentence three.\n" % s for s in SECTIONS)),
322     t("json20", "Output a JSON array of exactly 20 objects. Object i (i from 1 to 20) has keys \"id\" (= i), \"name\" (= \"item<i>\") and \"squares\" (= i*i). Output only the JSON.", 2048, "json", "```json\n%s\n```" % js),
323     t("elements", "Make a Markdown table of the first 12 chemical elements by atomic number with columns: Number, Symbol, Name.", 1024, "elements",
324       "| Number | Symbol | Name |\n|---|---|---|\n" + "\n".join("| %d | %s | x |" % (i + 1, s) for i, s in enumerate(ELEMENTS))),
325    ]
326
327def grade_complete(task, res):
328    txt, k = res["text"], task["kind"]
329    fin = res["finish_reason"] in ("stop", "end_turn", None) and res["finish_reason"] != "length"
330    info = {"finish_reason": res["finish_reason"]}
331    if k == "ints":
332        got = [int(x) for x in re.findall(r"\d+", txt)]
333        ok = got == task["expected_ints"]; info.update(got_n=len(got), want_n=len(task["expected_ints"]))
334    elif k == "letters":
335        got = re.findall(r"\b([A-Z])\b", txt); ok = got == task["expected_letters"]; info.update(got_n=len(got))
336    elif k == "sections":
337        heads = re.findall(r"^##\s+(.+?)\s*$", txt, re.M); ok = heads == SECTIONS
338        if ok:
339            parts = re.split(r"^##\s+.+$", txt, flags=re.M)[1:]
340            ok = len(parts) == 6 and all(len(re.findall(r"[.!?](\s|$)", p)) >= 3 for p in parts)
341        info["headings"] = heads
342    elif k == "json":
343        m = re.search(r"```(?:json)?\s*(.*?)```", txt, re.S); body = m.group(1) if m else txt
344        try:
345            arr = json.loads(body); ok = isinstance(arr, list) and len(arr) == 20 and all(o.get("id") == i + 1 and o.get("name") == "item%d" % (i + 1) and o.get("squares") == (i + 1) ** 2 for i, o in enumerate(arr))
346        except Exception as ex:
347            ok = False; info["error"] = repr(ex)[:120]
348    elif k == "elements":
349        syms = [c.strip() for line in txt.splitlines() if line.strip().startswith("|") for c in [line.split("|")[2]] if len(line.split("|")) > 3]
350        syms = [s for s in syms if s in ELEMENTS or re.fullmatch(r"[A-Z][a-z]?", s)]
351        ok = syms[:12] == ELEMENTS and len(syms) == 12; info["symbols"] = syms
352    else:
353        ok = False
354    info["finished"] = fin
355    return bool(ok and fin), info
356
357# --------------------------------------------------------------------------- tasks: long-context recall + speed prompts
358NOUNS = ["harbor", "lantern", "orchard", "bridge", "archive", "glacier", "market", "workshop", "canal", "observatory", "foundry", "meadow"]
359ADJ = ["quiet", "old", "crowded", "northern", "abandoned", "busy", "narrow", "famous", "remote", "sunlit"]
360VERB = ["recorded", "measured", "reported", "counted", "inspected", "catalogued"]
361CITY = ["Aldermoor", "Brindle", "Casterly", "Dunmere", "Eastwick", "Fairholt", "Greyvale", "Hollin"]
362
363def filler(n_chars, rnd):
364    parts, size = [], 0
365    while size < n_chars:
366        s = "The %s %s of %s %s %d %s during week %d of the survey. " % (rnd.choice(ADJ), rnd.choice(NOUNS), rnd.choice(CITY), rnd.choice(VERB), rnd.randint(11, 989), rnd.choice(NOUNS) + "s", rnd.randint(1, 52))
367        parts.append(s); size += len(s)
368    return parts
369
370def make_longctx(sizes_k):
371    out = []
372    for k in sizes_k:
373        rnd = random.Random(SEED + k)
374        parts = filler(int(k * 1024 * 3.6), rnd)  # ~3.6 chars/token for this filler -> approx k thousand tokens
375        names = rnd.sample(["Orion", "Vesper", "Calder", "Mistral", "Juniper", "Tamsin", "Quillon", "Bracken"], 3)
376        codes = ["%06d" % rnd.randint(100000, 999999) for _ in range(3)]
377        for frac, nm, cd in zip((0.2, 0.5, 0.8), names, codes):
378            parts.insert(int(len(parts) * frac), "NOTE: The access code for vault %s is %s. " % (nm, cd))
379        doc = "".join(parts)
380        q = "Below is a long survey log. Read it, then answer the question at the end.\n\n%s\n\nQuestion: What are the access codes for vaults %s, %s and %s? Reply exactly in the form '%s=<code>, %s=<code>, %s=<code>'." % (doc, names[0], names[1], names[2], names[0], names[1], names[2])
381        out.append({"id": "longctx-%dk" % k, "category": "longctx", "max_tokens": 200, "grader": "longctx", "names": names, "codes": codes,
382                    "messages": [{"role": "user", "content": q}], "oracle": ", ".join("%s=%s" % p for p in zip(names, codes))})
383    return out
384
385def grade_longctx(task, res):
386    hits = [bool(re.search(r"%s\s*=\s*%s" % (n, c), res["text"])) for n, c in zip(task["names"], task["codes"])]
387    return all(hits), {"hits": hits, "fraction": sum(hits) / 3}
388
389def make_speed(prompt_ks, gen_tokens):
390    out = [{"id": "speed-short", "category": "speed", "max_tokens": gen_tokens, "grader": "none", "oracle": "x",
391            "messages": [{"role": "user", "content": "Write a detailed explanation of how a refrigerator works, in plain prose, at least 400 words."}]}]
392    for k in prompt_ks:
393        rnd = random.Random(SEED + 100 + k)
394        doc = "".join(filler(int(k * 1024 * 3.6), rnd))
395        out.append({"id": "speed-prefill-%dk" % k, "category": "speed", "max_tokens": 64, "grader": "none", "oracle": "x",
396                    "messages": [{"role": "user", "content": "Summarize this log in two sentences.\n\n" + doc}]})
397    return out
398
399GRADERS = {"answer": grade_answer, "code": grade_code, "tool": grade_tool, "complete": grade_complete, "longctx": grade_longctx, "none": lambda t, r: (None, {})}
400
401# --------------------------------------------------------------------------- run
402def build_tasks(args):
403    cats = set(args.suite.split(","))
404    tasks = []
405    if "reasoning" in cats: tasks += make_reasoning()
406    if "code" in cats: tasks += make_code()
407    if "tools" in cats: tasks += make_tools()
408    if "complete" in cats: tasks += make_complete()
409    if "longctx" in cats: tasks += make_longctx([int(x) for x in args.longctx_k.split(",")])
410    if "speed" in cats: tasks += make_speed([int(x) for x in args.speed_k.split(",")], args.gen_tokens)
411    return tasks
412
413def selftest(args):
414    args.suite = "reasoning,code,tools,complete,longctx"; args.longctx_k = "1"
415    tasks = build_tasks(args)
416    bad = 0
417    for t in tasks:
418        if t["category"] == "code":
419            oracle = Result(text="```python\n%s\n```" % REF_IMPL[t["fn"]], finish_reason="stop", tool_calls=[])
420        elif t["category"] == "tools":
421            oracle = Oracle(True)(t)
422        else:
423            oracle = Oracle(True)(t)
424        good, _ = GRADERS[t["grader"]](t, oracle)
425        garb = Oracle(False)(t)
426        if t["category"] == "tools":   # garbage = a bogus call; restraint cases fail it too
427            garb = Result(text="", finish_reason="tool_calls", tool_calls=[{"name": "bogus", "arguments": {}}])
428        if t["category"] == "code": garb = Result(text="no code", finish_reason="stop", tool_calls=[])
429        gg, _ = GRADERS[t["grader"]](t, garb)
430        if not good or gg:
431            bad += 1; print("SELFTEST FAIL %s oracle_pass=%s garbage_pass=%s" % (t["id"], good, gg))
432    print("selftest: %d tasks, %d problems" % (len(tasks), bad))
433    return 1 if bad else 0
434
435def main():
436    ap = argparse.ArgumentParser()
437    ap.add_argument("--engine", choices=["openai", "ollama"]); ap.add_argument("--base", help="e.g. http://127.0.0.1:8080")
438    ap.add_argument("--model", default="m"); ap.add_argument("--arm", help="label for this arm, e.g. strata-iq2xs-p40x1")
439    ap.add_argument("--suite", default="speed,reasoning,code,tools,complete,longctx")
440    ap.add_argument("--think", choices=["off", "on"], default="off")
441    ap.add_argument("--reps", type=int, default=1); ap.add_argument("--num-ctx", type=int, default=32768)
442    ap.add_argument("--longctx-k", default="4,12,24"); ap.add_argument("--speed-k", default="4,16"); ap.add_argument("--gen-tokens", type=int, default=400)
443    ap.add_argument("--timeout", type=int, default=3600); ap.add_argument("--out", default="results/raw")
444    ap.add_argument("--only", help="comma list of task id prefixes"); ap.add_argument("--meta", default="{}", help="JSON string recorded in every record")
445    ap.add_argument("--selftest", action="store_true")
446    args = ap.parse_args()
447    if args.selftest:
448        sys.exit(selftest(args))
449    tasks = build_tasks(args)
450    if args.only:
451        pre = tuple(args.only.split(",")); tasks = [t for t in tasks if t["id"].startswith(pre)]
452    os.makedirs(args.out, exist_ok=True)
453    path = os.path.join(args.out, "%s.%s.jsonl" % (args.arm, datetime.datetime.now().strftime("%Y%m%dT%H%M%S")))
454    meta = json.loads(args.meta); think = args.think == "on"
455    print("arm=%s engine=%s tasks=%d reps=%d think=%s -> %s" % (args.arm, args.engine, len(tasks), args.reps, args.think, path), flush=True)
456    with open(path, "a") as fh:
457        for rep in range(args.reps):
458            for t in tasks:
459                rec = {"arm": args.arm, "rep": rep, "id": t["id"], "category": t["category"], "think": args.think, "ts": datetime.datetime.now().isoformat(timespec="seconds"), "meta": meta}
460                try:
461                    if args.engine == "openai":
462                        res = call_openai(args.base, args.model, t["messages"], t["max_tokens"], think, t.get("tools"), args.timeout)
463                    else:
464                        res = call_ollama(args.base, args.model, t["messages"], t["max_tokens"], think, t.get("tools"), args.timeout, args.num_ctx)
465                    ok, info = GRADERS[t["grader"]](t, res)
466                    rec.update(res=res, passed=ok, grade=info, error=None)
467                except Exception as ex:
468                    rec.update(res=None, passed=False if t["grader"] != "none" else None, grade={}, error="%s: %s" % (type(ex).__name__, ex))
469                fh.write(json.dumps(rec) + "\n"); fh.flush()
470                r = rec["res"] or {}
471                tp = (r.get("server_timings") or {}).get("predicted_per_second")
472                print("%-24s pass=%-5s fin=%-10s ptok=%-6s ctok=%-5s t=%6.1fs srv_tps=%s %s" % (t["id"], rec["passed"], r.get("finish_reason"), r.get("prompt_tokens"), r.get("completion_tokens"), r.get("t_total") or 0, "%.1f" % tp if tp else "-", rec["error"] or ""), flush=True)
473    print("done:", path)
474
475if __name__ == "__main__":
476    main()