okami.mom/strata

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

did-technomancerbench: community results for an RX 6800 on Windows (0.1.39 against 0.1.38) (#815)0b65d593c

main
18.0 KiB269 linesraw
1"""bench-local/strata_eval.py - a small capability check of a running Strata server (http://127.0.0.1:8080).
2
3Sections: coding tasks with hidden tests, reasoning puzzles per thinking level, tool calling, JSON output,
4conversation follow-up (prefix reuse) and a Ukrainian check.  Writes results.json next to this file.
5"""
6from __future__ import annotations
7
8import json
9import re
10import subprocess
11import sys
12import tempfile
13import time
14from pathlib import Path
15
16import requests
17
18URL = "http://127.0.0.1:8080/v1/chat/completions"
19HERE = Path(__file__).parent
20OUT = {"coding": [], "reasoning": [], "tools": [], "json": [], "followup": [], "ukrainian": []}
21
22
23def chat(messages, effort="none", max_tokens=4000, **extra):
24    t = time.time()
25    r = requests.post(URL, json={"model": "strata", "messages": messages, "max_tokens": max_tokens,
26                                 "reasoning_effort": effort, "temperature": 0, **extra}, timeout=1800).json()
27    wall = time.time() - t
28    if "choices" not in r:
29        return {"error": json.dumps(r)[:400], "wall": wall}
30    m, tm = r["choices"][0]["message"], r.get("timings", {})
31    return {"content": m.get("content") or "", "reasoning": m.get("reasoning_content") or "",
32            "tool_calls": m.get("tool_calls"), "finish": r["choices"][0].get("finish_reason"), "wall": round(wall, 1),
33            "out_tokens": tm.get("predicted_n"), "tok_s": tm.get("predicted_per_second"),
34            "prompt_n": tm.get("prompt_n"), "cache_n": tm.get("cache_n"), "prompt_s": round(tm.get("prompt_ms", 0) / 1000, 1)}
35
36
37# ------------------------------------------------------------------------------------------------ coding
38CODING = [
39    ("merge_intervals", "Write `merge_intervals(intervals)`: takes a list of [start, end] pairs (any order), merges "
40     "overlapping or touching ones and returns them sorted as a list of lists.",
41     "assert merge_intervals([[1,3],[2,6],[8,10],[15,18]]) == [[1,6],[8,10],[15,18]]\n"
42     "assert merge_intervals([[1,4],[4,5]]) == [[1,5]]\nassert merge_intervals([]) == []\n"
43     "assert merge_intervals([[5,7],[1,2],[2,3],[6,6]]) == [[1,3],[5,7]]\n"),
44    ("lru_cache", "Write a class `LRUCache(capacity)` with `get(key)` (returns -1 when missing) and `put(key, value)`; "
45     "both O(1); the least recently used key is evicted when over capacity.",
46     "c = LRUCache(2); c.put(1,1); c.put(2,2); assert c.get(1) == 1; c.put(3,3); assert c.get(2) == -1\n"
47     "c.put(4,4); assert c.get(1) == -1 and c.get(3) == 3 and c.get(4) == 4\n"
48     "c.put(3,30); c.put(5,5); assert c.get(4) == -1 and c.get(3) == 30\n"),
49    ("parse_duration", "Write `parse_duration(s)`: parses strings like '1d2h30m15s', '90m', '45s' (units d, h, m, s, "
50     "each at most once, in that order, any subset) and returns total seconds as int. Raise ValueError for anything "
51     "else (empty string, unknown unit, wrong order, repeated unit, negative numbers, spaces).",
52     "assert parse_duration('1d2h30m15s') == 95415\nassert parse_duration('90m') == 5400\n"
53     "assert parse_duration('45s') == 45\nassert parse_duration('2h5s') == 7205\n"
54     "for bad in ['', '5x', '30m1h', '1h1h', '-5m', '1h 5m', 'h', '10']:\n"
55     "    try:\n        parse_duration(bad); raise AssertionError(bad)\n    except ValueError:\n        pass\n"),
56    ("top_k_frequent", "Write `top_k_frequent(words, k)`: the k most frequent words, most frequent first; ties broken "
57     "alphabetically.",
58     "assert top_k_frequent(['i','love','leetcode','i','love','coding'], 2) == ['i','love']\n"
59     "assert top_k_frequent(['b','a','c','a','b','c'], 2) == ['a','b']\n"
60     "assert top_k_frequent(['x'], 1) == ['x']\n"),
61    ("eval_expr", "Write `eval_expr(s)`: evaluates an arithmetic expression string with + - * /, parentheses, unary "
62     "minus, integers and decimals, and spaces. Standard precedence, / is true division. Do not use eval or exec. "
63     "Return a float.",
64     "assert abs(eval_expr('1 + 2 * 3') - 7) < 1e-9\nassert abs(eval_expr('(1 + 2) * 3') - 9) < 1e-9\n"
65     "assert abs(eval_expr('-3 + 5') - 2) < 1e-9\nassert abs(eval_expr('2 * -(3 + 1) / 4') + 2) < 1e-9\n"
66     "assert abs(eval_expr('10 / 4 - 0.5') - 2) < 1e-9\nassert abs(eval_expr('2 - 3 - 4') + 5) < 1e-9\n"
67     "assert abs(eval_expr('((2))*(3+(4*5))') - 46) < 1e-9\n"),
68    ("int_to_roman", "Write `int_to_roman(n)` for 1 <= n <= 3999 and `roman_to_int(s)` as its inverse.",
69     "assert int_to_roman(1994) == 'MCMXCIV' and int_to_roman(3999) == 'MMMCMXCIX' and int_to_roman(4) == 'IV'\n"
70     "assert all(roman_to_int(int_to_roman(i)) == i for i in range(1, 4000))\n"),
71    ("dijkstra", "Write `dijkstra(graph, src)`: graph is a dict {node: {neighbor: weight}} with non-negative weights "
72     "(directed). Return a dict of shortest distances from src to every node that appears in the graph (as a key or "
73     "as a neighbor); unreachable nodes get float('inf').",
74     "g = {'a': {'b': 1, 'c': 4}, 'b': {'c': 2, 'd': 6}, 'c': {'d': 3}, 'e': {'a': 1}}\n"
75     "d = dijkstra(g, 'a')\nassert d == {'a': 0, 'b': 1, 'c': 3, 'd': 6, 'e': float('inf')}, d\n"),
76    ("bsearch_fix", "This function should return the index of the LEFTMOST occurrence of x in the sorted list a, or "
77     "-1. It has bugs. Return the fixed function, same name.\n\n```python\ndef bsearch(a, x):\n    lo, hi = 0, len(a)\n"
78     "    while lo < hi:\n        mid = (lo + hi) // 2\n        if a[mid] <= x:\n            lo = mid\n        else:\n"
79     "            hi = mid - 1\n    return lo if a[lo] == x else -1\n```",
80     "assert bsearch([1,2,2,2,3], 2) == 1\nassert bsearch([], 1) == -1\nassert bsearch([1,3,5], 4) == -1\n"
81     "assert bsearch([1,3,5], 5) == 2\nassert bsearch([2,2,2], 2) == 0\nassert bsearch([1,3,5], 0) == -1\n"
82     "assert bsearch([1,3,5], 9) == -1\n"),
83    ("flatten_json", "Write `flatten_json(obj, sep='.')`: flattens nested dicts and lists into one dict; list items "
84     "use their index as the key part. Empty dicts and empty lists are kept as values.",
85     "assert flatten_json({'a': {'b': 1, 'c': [10, {'d': 2}]}, 'e': 3}) == {'a.b': 1, 'a.c.0': 10, 'a.c.1.d': 2, 'e': 3}\n"
86     "assert flatten_json({'a': {}, 'b': []}) == {'a': {}, 'b': []}\n"
87     "assert flatten_json({'x': {'y': {'z': None}}}, sep='/') == {'x/y/z': None}\n"),
88    ("lcs", "Write `lcs(a, b)`: returns one longest common subsequence of two strings (as a string).",
89     "def ok(a, b, n):\n    r = lcs(a, b)\n    def sub(s, t):\n        it = iter(t)\n        return all(ch in it for ch in s)\n"
90     "    assert len(r) == n and sub(r, a) and sub(r, b), r\n"
91     "ok('ABCBDAB', 'BDCABA', 4); ok('', 'abc', 0); ok('abc', 'abc', 3); ok('AGGTAB', 'GXTXAYB', 4)\n"),
92    ("rate_limiter", "Write a class `RateLimiter(max_calls, period)` with `allow(now)`: returns True and records the "
93     "call if fewer than max_calls were allowed in the half-open window (now - period, now], else False. `now` is a "
94     "float in seconds and never decreases.",
95     "r = RateLimiter(2, 10)\nassert r.allow(0) and r.allow(1) and not r.allow(2)\nassert not r.allow(9.9)\n"
96     "assert r.allow(10)\nassert not r.allow(10.5)\nassert r.allow(11) and not r.allow(11)\n"),
97    ("csv_parse", "Write `parse_csv_line(line)`: splits one CSV line into fields. Fields may be quoted with double "
98     "quotes; quoted fields may contain commas and doubled quotes (\"\") meaning one quote. No csv module.",
99     "assert parse_csv_line('a,b,c') == ['a','b','c']\nassert parse_csv_line('a,\"b,c\",d') == ['a','b,c','d']\n"
100     "assert parse_csv_line('\"he said \"\"hi\"\"\",x') == ['he said \"hi\"','x']\n"
101     "assert parse_csv_line('a,,') == ['a','','']\nassert parse_csv_line('') == ['']\n"),
102]
103
104
105def extract_code(text):
106    blocks = re.findall(r"```(?:python|py)?\s*\n(.*?)```", text, re.S)
107    return max(blocks, key=len) if blocks else text
108
109
110def run_tests(code, tests):
111    with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="utf-8") as f:
112        f.write(code + "\n\n" + tests + "\nprint('PASS')\n")
113        path = f.name
114    try:
115        p = subprocess.run([sys.executable, "-I", path], capture_output=True, text=True, timeout=20)
116        return "PASS" in p.stdout, (p.stderr.strip().splitlines() or [""])[-1][:200]
117    except subprocess.TimeoutExpired:
118        return False, "timeout"
119    finally:
120        Path(path).unlink(missing_ok=True)
121
122
123def coding():
124    for effort in ("none", "medium"):
125        for name, task, tests in CODING:
126            r = chat([{"role": "user", "content": task + "\n\nPython 3, standard library only. Reply with one "
127                       "```python code block containing the complete solution."}], effort, 6000)
128            ok, err = (False, r["error"]) if "error" in r else run_tests(extract_code(r["content"]), tests)
129            OUT["coding"].append({"task": name, "effort": effort, "pass": ok, "err": err,
130                                  **{k: r.get(k) for k in ("wall", "out_tokens", "tok_s", "finish")}})
131            print(f"coding {effort:6} {name:16} {'PASS' if ok else 'FAIL'} {r.get('wall')} s {r.get('out_tokens')} tok  {err}", flush=True)
132
133
134# ------------------------------------------------------------------------------------------------ reasoning
135PUZZLES = [
136    ("A bat and a ball cost 1.10 in total. The bat costs 1.00 more than the ball. How much does the ball cost?", "0.05"),
137    ("Sally has 3 brothers. Each brother has 2 sisters. How many sisters does Sally have?", "1"),
138    ("If 5 machines take 5 minutes to make 5 widgets, how many minutes do 100 machines take to make 100 widgets?", "5"),
139    ("Today is Wednesday. What day of the week is it 100 days from now? Answer with the English day name.", "friday"),
140    ("Скільки разів літера 'р' зустрічається у слові 'прапорщик'? Відповідь числом.", "2"),
141    ("Compute 487 * 263. Answer with the number.", "128081"),
142    ("A farmer has chickens and rabbits: 35 heads and 94 legs. How many rabbits?", "12"),
143    ("I have 3 apples. Yesterday I ate 2 apples. How many apples do I have now?", "3"),
144    ("Three boxes: one has two gold coins, one two silver, one a gold and a silver. You pick a box at random and "
145     "draw a gold coin. What is the probability the other coin in that box is gold? Answer as a fraction a/b.", "2/3"),
146    ("A snail climbs a 10 m wall: up 3 m each day, slides down 2 m each night. On which day does it reach the top? "
147     "Answer with the number.", "8"),
148    ("Alice is taller than Bob. Bob is taller than Carol. Dave is shorter than Carol. Eve is taller than Alice. "
149     "Who is the second tallest? Answer with the name.", "alice"),
150    ("What is the smallest positive integer divisible by each of 1 through 10? Answer with the number.", "2520"),
151]
152
153
154def reasoning():
155    for effort in ("none", "low", "high"):
156        for q, want in PUZZLES:
157            r = chat([{"role": "user", "content": q + "\nEnd your reply with a line 'ANSWER: <answer>'."}], effort, 8000)
158            m = re.findall(r"ANSWER:\s*(.+)", r.get("content", ""))
159            got = m[-1].strip().strip(".*` ").lower().replace(",", "").replace(" ", "").lstrip("$") if m else ""
160            ok = bool(re.match(re.escape(want) + r"(?![0-9/.])", got))
161            OUT["reasoning"].append({"q": q[:50], "effort": effort, "pass": ok, "got": got[:30],
162                                     **{k: r.get(k) for k in ("wall", "out_tokens", "tok_s")}})
163            print(f"reason {effort:5} {'PASS' if ok else 'FAIL'} {r.get('wall')} s {r.get('out_tokens')} tok  {q[:40]!r} -> {got[:20]!r}", flush=True)
164
165
166# ------------------------------------------------------------------------------------------------ tools
167TOOLS = [
168    {"type": "function", "function": {"name": "read_file", "description": "Read a text file from the project.",
169     "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}},
170    {"type": "function", "function": {"name": "run_command", "description": "Run a shell command and return its output.",
171     "parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}},
172    {"type": "function", "function": {"name": "web_search", "description": "Search the web.",
173     "parameters": {"type": "object", "properties": {"query": {"type": "string"},
174                    "max_results": {"type": "integer"}}, "required": ["query"]}}},
175]
176TOOL_CASES = [
177    ("Open src/main.py and tell me what the entry function is called.", "read_file", "path", "main.py"),
178    ("How many Python files are in this repository? Use the shell.", "run_command", "command", ""),
179    ("What is the latest stable version of Rust? Look it up.", "web_search", "query", "rust"),
180    ("Знайди в інтернеті, яка зараз остання версія Python.", "web_search", "query", "python"),
181    ("What is 2 + 2?", None, None, None),
182]
183
184
185def tools():
186    for q, want, arg, needle in TOOL_CASES:
187        r = chat([{"role": "user", "content": q}], "none", 1500, tools=TOOLS)
188        calls = r.get("tool_calls") or []
189        name = calls[0]["function"]["name"] if calls else None
190        try:
191            args = json.loads(calls[0]["function"]["arguments"]) if calls else {}
192            valid = True
193        except ValueError:
194            args, valid = {}, False
195        ok = name == want and valid and (want is None or (arg in args and needle.lower() in str(args[arg]).lower()))
196        OUT["tools"].append({"q": q[:50], "want": want, "got": name, "args": args, "pass": ok, "wall": r.get("wall")})
197        print(f"tools {'PASS' if ok else 'FAIL'} want {want} got {name} {args}", flush=True)
198    # a two-step round trip: the call, its result, then the answer
199    msgs = [{"role": "user", "content": "Read config.toml and tell me which port the server listens on."}]
200    r = chat(msgs, "none", 1500, tools=TOOLS)
201    calls = r.get("tool_calls") or []
202    ok = False
203    if calls:
204        msgs += [{"role": "assistant", "content": r["content"], "tool_calls": calls},
205                 {"role": "tool", "tool_call_id": calls[0].get("id", "call_0"),
206                  "content": "[server]\nhost = \"0.0.0.0\"\nport = 9137\nworkers = 4\n"}]
207        r2 = chat(msgs, "none", 1500, tools=TOOLS)
208        ok = "9137" in r2.get("content", "")
209    OUT["tools"].append({"q": "round trip (read_file -> answer)", "pass": ok})
210    print(f"tools round trip {'PASS' if ok else 'FAIL'}", flush=True)
211
212
213# ------------------------------------------------------------------------------------------------ JSON
214def json_out():
215    schema = {"type": "object", "properties": {"name": {"type": "string"}, "year": {"type": "integer"},
216              "languages": {"type": "array", "items": {"type": "string"}}}, "required": ["name", "year", "languages"],
217              "additionalProperties": False}
218    text = ("Guido van Rossum started Python in 1989 and released it in 1991. He also worked with C and ABC. "
219            "Extract: the person's name, the release year, and the languages mentioned.")
220    for label, extra in (("json_schema", {"response_format": {"type": "json_schema", "json_schema":
221                                          {"name": "person", "schema": schema, "strict": True}}}),
222                         ("prompt only", {})):
223        r = chat([{"role": "user", "content": text + ("" if extra else " Reply with JSON only: "
224                                                       "{\"name\": str, \"year\": int, \"languages\": [str]}")}],
225                 "none", 600, **extra)
226        try:
227            d = json.loads(re.sub(r"^```(?:json)?|```$", "", r.get("content", "").strip(), flags=re.M).strip())
228            ok = d.get("year") == 1991 and "rossum" in d.get("name", "").lower() and len(d.get("languages", [])) == 3
229        except ValueError:
230            d, ok = r.get("content", r.get("error", ""))[:200], False
231        OUT["json"].append({"mode": label, "pass": ok, "got": d})
232        print(f"json {label} {'PASS' if ok else 'FAIL'} {d}", flush=True)
233
234
235# ------------------------------------------------------------------------------------------------ follow-up
236def followup():
237    src = (HERE.parent / "serve" / "mcp.py").read_text(encoding="utf-8")[:30000]
238    msgs = [{"role": "user", "content": "Here is a Python file:\n\n" + src + "\n\nName the main class in one line."}]
239    r1 = chat(msgs, "none", 200)
240    msgs += [{"role": "assistant", "content": r1.get("content", "")},
241             {"role": "user", "content": "Which transports does it implement? One line."}]
242    r2 = chat(msgs, "none", 200)
243    for label, r in (("first turn", r1), ("follow-up", r2)):
244        OUT["followup"].append({"turn": label, **{k: r.get(k) for k in ("prompt_n", "cache_n", "prompt_s", "wall",
245                                                                         "tok_s", "content")}})
246        print(f"followup {label}: read {r.get('prompt_n')} tok in {r.get('prompt_s')} s, reused {r.get('cache_n')}, "
247              f"wall {r.get('wall')} s | {r.get('content', '')[:120]!r}", flush=True)
248
249
250# ------------------------------------------------------------------------------------------------ Ukrainian
251def ukrainian():
252    qs = ["Поясни трьома реченнями, чим процес відрізняється від потоку в операційній системі.",
253          "Переклади українською: 'The quick brown fox jumps over the lazy dog, but the dog had already filed a "
254          "bug report about it.'",
255          "Напиши commit message українською для зміни: додано перевірку заголовка Host у HTTP-сервері проти DNS "
256          "rebinding. Один рядок заголовка і два речення опису."]
257    for q in qs:
258        r = chat([{"role": "user", "content": q}], "none", 500)
259        OUT["ukrainian"].append({"q": q, "a": r.get("content"), "tok_s": r.get("tok_s"), "wall": r.get("wall")})
260        print(f"uk {r.get('tok_s')} tok/s | {r.get('content', '')[:300]!r}", flush=True)
261
262
263if __name__ == "__main__":
264    want = sys.argv[1:] or ["tools", "json", "followup", "ukrainian", "coding", "reasoning"]
265    for name in want:
266        {"coding": coding, "reasoning": reasoning, "tools": tools, "json": json_out, "followup": followup,
267         "ukrainian": ukrainian}[name]()
268        (HERE / "results.json").write_text(json.dumps(OUT, ensure_ascii=False, indent=1), encoding="utf-8")
269    print("DONE", flush=True)