okami.mom/strata

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

Niko1221Merge f-142c-small into f-142407ea8192

main
10.7 KiB208 linesraw
1"""Matched OpenAI-compatible smoke benchmark; never executes generated code/tools."""
2import argparse
3import ctypes
4import json
5import threading
6import time
7import urllib.request
8from pathlib import Path
9
10AUTH_HEADERS = {}
11
12
13class MemoryStatus(ctypes.Structure):
14    _fields_ = [("length", ctypes.c_ulong), ("load", ctypes.c_ulong)] + [
15        (name, ctypes.c_ulonglong) for name in
16        ("total_physical", "available_physical", "total_pagefile", "available_pagefile",
17         "total_virtual", "available_virtual", "available_extended")
18    ]
19
20
21def available_ram():
22    status = MemoryStatus()
23    status.length = ctypes.sizeof(status)
24    if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
25        raise ctypes.WinError()
26    return status.available_physical / 2**30
27
28
29def get_json(base, route):
30    req = urllib.request.Request(base + route, headers=AUTH_HEADERS)
31    with urllib.request.urlopen(req, timeout=10) as response:
32        return json.load(response)
33
34
35def assert_idle(base):
36    slots = get_json(base, "/slots")
37    if not isinstance(slots, list):
38        raise RuntimeError("Unrecognized slots response; cannot confirm idle")
39    if any(slot.get("is_processing") for slot in slots):
40        raise RuntimeError("Model is already working; not interrupting it")
41
42
43def request(base, model, label, prompt, run, tools=None, *, response_format=None, reasoning_effort="low", max_tokens=1024):
44    assert_idle(base)
45    # Different first messages minimize shared-prefix reuse; residual cache is reported.
46    payload = {
47        "model": model, "messages": [{"role": "user", "content": f"Benchmark {label} run {run}.\n{prompt}"}],
48        "temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0,
49        "repeat_penalty": 1.0, "repetition_penalty": 1.0,
50        "presence_penalty": 0.0, "frequency_penalty": 0.0,
51        "reasoning_effort": reasoning_effort, "seed": 42, "max_tokens": max_tokens,
52        "cache_prompt": False, "strata_checkpoint": False,
53        "experimental_speed_projection": False,
54        "stream": True, "stream_options": {"include_usage": True},
55    }
56    if tools:
57        payload.update(tools=tools, tool_choice="auto")
58    if response_format is not None:
59        payload['response_format']=response_format
60    before = available_ram()
61    samples = [before]
62    stop = threading.Event()
63
64    def sample():
65        while not stop.wait(0.5):
66            samples.append(available_ram())
67
68    monitor = threading.Thread(target=sample, daemon=True)
69    monitor.start()
70    started = time.perf_counter()
71    first_delta = first_content = None
72    text, reasoning, calls = "", "", {}
73    usage, timings, finish = {}, {}, None
74    error = None
75    try:
76        req = urllib.request.Request(base + "/v1/chat/completions", json.dumps(payload).encode(),
77                                     {"Content-Type": "application/json", **AUTH_HEADERS})
78        with urllib.request.urlopen(req, timeout=900) as response:
79            for raw in response:
80                line = raw.decode("utf-8").strip()
81                if not line.startswith("data:"):
82                    continue
83                data = line[5:].strip()
84                if data == "[DONE]":
85                    break
86                event = json.loads(data)
87                if event.get("error"):
88                    raise RuntimeError(str(event["error"]))
89                if event.get("usage"):
90                    usage = event["usage"]
91                if event.get("timings"):
92                    timings = event["timings"]
93                for choice in event.get("choices", []):
94                    delta = choice.get("delta", {})
95                    content = delta.get("content") or ""
96                    thought = delta.get("reasoning_content") or delta.get("reasoning") or ""
97                    if content or thought or delta.get("tool_calls"):
98                        first_delta = first_delta if first_delta is not None else time.perf_counter() - started
99                    if content:
100                        first_content = first_content if first_content is not None else time.perf_counter() - started
101                    text += content
102                    reasoning += thought
103                    for call in delta.get("tool_calls", []):
104                        target = calls.setdefault(call.get("index", 0), {"name": "", "arguments": ""})
105                        function = call.get("function", {})
106                        target["name"] += function.get("name") or ""
107                        target["arguments"] += function.get("arguments") or ""
108                    finish = choice.get("finish_reason") or finish
109    except Exception as exc:
110        error = str(exc)
111    finally:
112        elapsed = time.perf_counter() - started
113        stop.set()
114        monitor.join(timeout=2)
115        samples.append(available_ram())
116    return {
117        "case": label, "run": run, "wall_seconds": round(elapsed, 3),
118        "first_token_seconds": first_delta, "first_answer_seconds": first_content,
119        "usage": usage, "timings": timings, "finish_reason": finish,
120        "answer": text, "reasoning": reasoning, "tool_calls": list(calls.values()),
121        "available_ram_before_GiB": before, "minimum_available_ram_GiB": min(samples),
122        "available_ram_after_GiB": samples[-1], "error": error,
123    }
124
125
126def validate(row, strict=False):
127    if row["error"] or row["finish_reason"] == "length":
128        return False
129    if row["case"] == "tool_call":
130        calls = row["tool_calls"]
131        try:
132            return len(calls) == 1 and calls[0]["name"] == "read_file" and json.loads(calls[0]["arguments"]) == {"path": "package.json"}
133        except (ValueError, KeyError):
134            return False
135    raw_answer = row["answer"].strip()
136    if not strict and raw_answer.startswith("```") and raw_answer.endswith("```"):
137        raw_answer = "\n".join(raw_answer.splitlines()[1:-1])
138    try:
139        answer = json.loads(raw_answer)
140    except ValueError:
141        return False
142    if row["case"] == "quote_math":
143        expected = {"subtotal": 780, "discounted": 702, "tax": 91.26, "total": 793.26}
144        return isinstance(answer, dict) and answer.keys() == expected.keys() and all(
145            isinstance(answer[k], (int, float)) and abs(answer[k] - v) < 0.005 for k, v in expected.items())
146    if row["case"] == "validation_logic":
147        return answer == {"accepted": [0, 1.5, 3], "rejected": [None, "4", -2]}
148    return answer == {"start": "CLENEX-4181", "middle": "STRATA-8081", "end": "LONDON-9060"}
149
150
151def main():
152    parser = argparse.ArgumentParser()
153    parser.add_argument("--base")
154    parser.add_argument("--model")
155    parser.add_argument("--rescore", type=Path)
156    parser.add_argument("--connection", type=Path)
157    parser.add_argument("--output", type=Path, required=True)
158    parser.add_argument("--runs", type=int, default=2)
159    args = parser.parse_args()
160    if args.output.exists():
161        raise SystemExit("Output already exists; choose a new filename to preserve results")
162    if args.rescore:
163        results = json.loads(args.rescore.read_text(encoding="utf-8"))
164        results["scoring_note"] = "Content accuracy and exact output formatting are scored separately; original evidence retained."
165        for row in results["results"]:
166            row["original_check_passed"] = row["check_passed"]
167            row["check_passed"] = validate(row)
168            row["strict_format_passed"] = validate(row, strict=True)
169        args.output.write_text(json.dumps(results, indent=2), encoding="utf-8")
170        print(json.dumps({"content_passed": sum(r["check_passed"] for r in results["results"]),
171                          "strict_format_passed": sum(r["strict_format_passed"] for r in results["results"]),
172                          "total": len(results["results"])}))
173        return
174    if args.connection:
175        conn = json.loads(args.connection.read_text(encoding="utf-8-sig"))
176        args.base = conn["baseURL"].removesuffix("/v1")
177        args.model = conn["model"]
178        AUTH_HEADERS["Authorization"] = "Bearer " + Path(conn["keyFile"]).read_text().strip()
179    if not args.base or not args.model:
180        parser.error("--base and --model are required for live benchmarking")
181    assert_idle(args.base)
182    cases = [
183        ("quote_math", "An office quote includes four visits at $120 each, three floor jobs at $85 each, and $45 materials. Apply 10% discount to the subtotal then 13% tax. Return only JSON with numeric subtotal, discounted, tax and total.", None),
184        ("validation_logic", 'Accept only JSON numbers which are finite and nonnegative (zero is valid); reject null, strings and negatives. Classify [0, null, "4", -2, 1.5, 3]. Return only JSON with arrays accepted and rejected, preserving their relative order.', None),
185        ("tool_call", "Use the read_file tool to inspect package.json before suggesting a test command. Do not guess its contents. Call the tool exactly once; no other actions.", [{"type": "function", "function": {"name": "read_file", "description": "Read a file in the current project", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"], "additionalProperties": False}}}]),
186    ]
187    filler = "This is irrelevant background about routine office cleaning schedules. Ignore it when extracting marked keys.\n"
188    for label, repeats in [("recall_short", 25), ("recall_long", 300)]:
189        document = "START_KEY=CLENEX-4181\n" + filler * repeats + "MIDDLE_KEY=STRATA-8081\n" + filler * repeats + "END_KEY=LONDON-9060\n"
190        cases.append((label, document + 'Return only JSON with start, middle and end holding the three marked key values.', None))
191    results = {"started_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "base": args.base,
192               "model": args.model, "runs": args.runs, "results": [],
193               "notes": "Same text/settings; token counts may differ. RAM is whole-system, sampled at 0.5 s. No generated tools/code are executed. TTFT includes reasoning. Low effort can mean different budgets across models. This compares whole stacks, not model or engine in isolation."}
194    args.output.parent.mkdir(parents=True, exist_ok=True)
195    for label, prompt, tools in cases:
196        for run in range(1, args.runs + 1):
197            row = request(args.base, args.model, label, prompt, run, tools)
198            row["check_passed"] = validate(row)
199            row["strict_format_passed"] = validate(row, strict=True)
200            results["results"].append(row)
201            args.output.write_text(json.dumps(results, indent=2), encoding="utf-8")
202            print(json.dumps({k: row[k] for k in ("case", "run", "wall_seconds", "usage", "timings", "check_passed", "error")}), flush=True)
203            if row["error"]:
204                raise SystemExit("Request failed; stopping instead of retrying or restarting the server")
205
206
207if __name__ == "__main__":
208    main()