okami.mom/strata

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

homeofebench: community results, RTX 2080 Ti 11 GB + Threadripper 3960X, IQ3_S at 262K with KV streaming (#469)707fd49eb

main
5.7 KiB116 linesraw
1#!/usr/bin/env python3
2"""Image question with an exact expected answer, through a running Strata server with the vision encoder.
3
4Each run draws a new PNG (so the server's cache of encoded images cannot serve it): a code made of letters and digits
5in large type, a number of red circles and a number of blue squares, chosen per run. The model is asked for all
6three in a fixed format; the answer counts as correct only if all three match exactly. Streaming, greedy, reasoning
7off. Client time to the first token includes the image encode (strata-vision, which runs on the CPU in this
8configuration and takes its turn in the server's request FIFO) and the prompt read; the engine's prompt_ms covers
9only the read of the prompt with the image embeddings, so client TTFT minus prompt_ms approximates the encode time.
10
11    python image_check.py --key-config <server config.json> --runs 3 --engine-log ... --server-log ...
12"""
13from __future__ import annotations
14
15import argparse
16import base64
17import io
18import json
19import random
20import time
21from pathlib import Path
22
23from PIL import Image, ImageDraw, ImageFont
24
25from bench_server import stream
26from common import LogTail, Server, api_key, parse_engine, scrub_lines
27
28HERE = Path(__file__).resolve().parent
29QUESTION = ("Look at the image. What is the code written in black letters, how many red circles are there, and how "
30            "many blue squares are there? Answer in exactly this format and nothing else: CODE; circles; squares")
31
32
33def font(size):
34    for f in ("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
35              "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"):
36        try:
37            return ImageFont.truetype(f, size)
38        except OSError:
39            pass
40    return ImageFont.load_default(size)
41
42
43def draw(rnd: random.Random):
44    code = "".join(rnd.choice("ABCDEFGHJKLMNPRSTUVWXYZ") for _ in range(3)) + "-" + str(rnd.randint(10, 99))
45    circles, squares = rnd.randint(2, 5), rnd.randint(1, 4)
46    w, h = 768, 512
47    img = Image.new("RGB", (w, h), "white")
48    d = ImageDraw.Draw(img)
49    d.text((40, 30), code, fill="black", font=font(72))
50    boxes = []                                            # non-overlapping cells in the lower part
51    cells = [(x, y) for x in range(40, w - 100, 120) for y in (190, 330)]
52    rnd.shuffle(cells)
53    for i, (x, y) in enumerate(cells[:circles + squares]):
54        if i < circles:
55            d.ellipse((x, y, x + 90, y + 90), fill=(220, 30, 30), outline="black", width=2)
56        else:
57            d.rectangle((x, y, x + 90, y + 90), fill=(30, 60, 220), outline="black", width=2)
58        boxes.append((x, y))
59    buf = io.BytesIO()
60    img.save(buf, "PNG")
61    return buf.getvalue(), code, circles, squares
62
63
64def main():
65    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
66    ap.add_argument("--url", default="http://127.0.0.1:8080")
67    ap.add_argument("--key-config")
68    ap.add_argument("--engine-log", required=True)
69    ap.add_argument("--server-log", required=True)
70    ap.add_argument("--out", type=Path, default=HERE / "data")
71    ap.add_argument("--runs", type=int, default=3)
72    ap.add_argument("--seed", type=int, default=431)
73    a = ap.parse_args()
74    server = Server(a.url, api_key(a.key_config))
75    elog, slog = LogTail(a.engine_log), LogTail(a.server_log)
76    rnd = random.Random(a.seed)
77    for run in range(1, a.runs + 1):
78        png, code, circles, squares = draw(rnd)
79        (a.out / f"image-run{run}.png").write_bytes(png)
80        url = "data:image/png;base64," + base64.b64encode(png).decode()
81        req = {"model": "strata", "temperature": 0, "reasoning_effort": "none", "max_tokens": 40, "stream": True,
82               "stream_options": {"include_usage": True},
83               "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url}},
84                                                         {"type": "text", "text": QUESTION}]}]}
85        for attempt in range(1, 4):
86            status = server.wait_idle()
87            before = server.totals()
88            elog.mark(), slog.mark()
89            t0 = time.time()
90            res = stream(server, req, timeout=900)
91            time.sleep(1.5)
92            after = server.totals()
93            elines, slines = elog.since(), slog.since()
94            parsed = parse_engine(elines)
95            foreign = (after - before != 1) or len(parsed) != 1
96            expected = f"{code}; {circles}; {squares}"
97            got = res["text"].strip()
98            parts = [p.strip() for p in got.split(";")]
99            ok = parts == [code, str(circles), str(squares)]
100            eng = parsed[0] if parsed else {}
101            row = {"label": f"image-run{run}", "attempt": attempt, "epoch_start": t0, "image": f"image-run{run}.png",
102                   "image_px": [768, 512], "expected": expected, "answer": got, "correct": ok, **res,
103                   "engine": eng or None, "metrics_record": server.get("/metrics")["requests"][0],
104                   "approx_encode_s": (res["client_ttft_s"] - eng["prompt_ms_log"] / 1000) if eng and res["client_ttft_s"] else None,
105                   "status_before": status, "totals_before": before, "totals_after": after, "foreign_overlap": foreign,
106                   "engine_log": scrub_lines(elines), "server_log": scrub_lines(slines)}
107            name = f"image-run{run}" + (f"-discarded-{attempt}" if foreign else "")
108            (a.out / f"{name}.json").write_text(json.dumps(row, indent=1, ensure_ascii=False) + "\n")
109            print(f"image run {run}: expected {expected!r} got {got!r} -> {'OK' if ok else 'WRONG'}; "
110                  f"ttft {res['client_ttft_s']:.2f} s, {eng.get('line', '')}", flush=True)
111            if not foreign:
112                break
113
114
115if __name__ == "__main__":
116    main()