okami.mom/strata

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

Hugua700bench: RX 6800M (gfx1031) community report - self-built HIP engine on Windows (#1078)1be67e894

main
8.6 KiB208 linesraw
1#!/usr/bin/env python3
2"""Strata community benchmark harness (RX 6800M / gfx1031).
3
4Reports what the project's template asks for, using the server's own `timings`
5object -- the same source the existing community reports use.
6
7Design notes
8  * Prompts are built from this repository's own source files so anyone can repeat
9    them (the 2x Arc Pro B60 report does the same). Actual prompt token counts come
10    from the response (`timings.prompt_n`), never from an estimate.
11  * One request at a time. A warm-up request runs first and is not counted: the
12    first request after a load is cold (empty expert cache) and is far slower.
13  * Each configuration is repeated RUNS times; the summary keeps every run and
14    reports the median and the range, per the template.
15  * Recall checks put a needle at a chosen depth and verify the answer.
16
17Usage
18  python strata-bench.py --sizes 512,2048 --runs 3 --tag default
19  python strata-bench.py --sizes 8192 --runs 3 --tag f16   # engine started with STRATA_HIP_PROMPT_F16=1
20"""
21from __future__ import annotations
22
23import argparse
24import json
25import os
26import random
27import statistics
28import time
29import urllib.error
30import urllib.request
31from pathlib import Path
32
33REPO = Path(r"F:\Strata")
34URL = "http://127.0.0.1:8080/v1/chat/completions"
35OUT = Path(r"F:\harness\strata-bench")
36MAX_TOKENS = 256
37NEEDLE = "XYLOPHONE-7742"
38
39# Filler sources: the repository's own files, read in a fixed order so the prompt
40# is reproducible. CHARS_PER_TOKEN is only used to size the build; the real count
41# comes back from the server.
42SOURCES = [
43    REPO / "tools" / "iq_pack.py",
44    REPO / "tools" / "make_profile.py",
45    REPO / "tools" / "bench_prefill.py",
46    REPO / "setup.py",
47    REPO / "serve" / "server.py",
48]
49CHARS_PER_TOKEN = 3.6          # measured after the first run; only a sizing hint
50
51
52def filler_text() -> str:
53    parts = []
54    for p in SOURCES:
55        try:
56            parts.append(p.read_text(encoding="utf-8", errors="replace"))
57        except OSError:
58            continue
59    return "\n\n# ---- next file ----\n\n".join(parts)
60
61
62FILLER = filler_text()
63
64
65def build_prompt(approx_tokens: int, needle_depth: float | None = None,
66                 nonce: str | None = None) -> str:
67    """A block of source plus an instruction.
68
69    `nonce` is prefixed so every measured run has a different token prefix:
70    Strata reuses a cached conversation prefix, so without it runs 2..N only read
71    a handful of new tokens and their prompt speed is not comparable to run 1.
72    The template's "Reused tokens" column exists for exactly this.
73    """
74    head = f"# benchmark run {nonce}\n" if nonce else ""
75    if approx_tokens <= 64:
76        return head + "Write a Python function that returns the n-th Fibonacci number."
77    body = FILLER[: int(approx_tokens * CHARS_PER_TOKEN)]
78    if needle_depth is not None:
79        pos = int(len(body) * needle_depth)
80        pos = body.rfind("\n", 0, pos) or pos
81        body = body[:pos] + f"\n# RECORD-KEY: {NEEDLE}\n" + body[pos:]
82        task = "What is the value of RECORD-KEY in the code above? Answer with the value only."
83    else:
84        task = ("Summarize what the code above does and name the three most important functions, "
85                "in about 200 words.")
86    return head + body + "\n\n# ---- task ----\n" + task
87
88
89def call(prompt: str, max_tokens: int = MAX_TOKENS):
90    body = {
91        "model": "qwen3.8-flash-next-abliterated-q2_0",
92        "messages": [{"role": "user", "content": prompt}],
93        "max_tokens": max_tokens,
94        "temperature": 0,                                    # greedy, as in the Arc report
95        "chat_template_kwargs": {"enable_thinking": False},
96    }
97    req = urllib.request.Request(URL, data=json.dumps(body).encode(),
98                                 headers={"Content-Type": "application/json",
99                                          "Authorization": "Bearer local"})
100    t0 = time.time()
101    try:
102        with urllib.request.urlopen(req, timeout=3600) as r:
103            d = json.load(r)
104    except urllib.error.HTTPError as e:
105        return {"error": f"HTTP {e.code}: {e.read().decode('utf-8', 'replace')[:200]}",
106                "wall_s": time.time() - t0}
107    except Exception as e:
108        return {"error": f"{type(e).__name__}: {e}", "wall_s": time.time() - t0}
109    wall = time.time() - t0
110    t = d.get("timings") or {}
111    msg = d["choices"][0]["message"]
112    return {
113        "wall_s": round(wall, 2),
114        "prompt_n": t.get("prompt_n"),
115        "cache_n": t.get("cache_n"),
116        "prompt_ms": t.get("prompt_ms"),
117        "prompt_tok_s": t.get("prompt_per_second"),
118        "predicted_n": t.get("predicted_n"),
119        "predicted_ms": t.get("predicted_ms"),
120        "decode_tok_s": t.get("predicted_per_second"),
121        "draft_n": t.get("draft_n"),
122        "draft_accepted": t.get("draft_n_accepted"),
123        "finish": d["choices"][0].get("finish_reason"),
124        "answer_head": (msg.get("content") or "").strip()[:160],
125    }
126
127
128def med_range(vals):
129    vals = [v for v in vals if isinstance(v, (int, float))]
130    if not vals:
131        return "n/a"
132    if len(vals) == 1:
133        return f"{vals[0]:.1f} (single run)"
134    return f"{statistics.median(vals):.1f} ({min(vals):.1f}-{max(vals):.1f})"
135
136
137def main():
138    ap = argparse.ArgumentParser()
139    ap.add_argument("--sizes", default="512,2048")
140    ap.add_argument("--runs", type=int, default=3)
141    ap.add_argument("--tag", default="default")
142    ap.add_argument("--recall", action="store_true", help="也做 recall 校验(在 2048 提示里插针)")
143    ap.add_argument("--skip-warmup", action="store_true")
144    args = ap.parse_args()
145
146    OUT.mkdir(parents=True, exist_ok=True)
147    sizes = [int(x) for x in args.sizes.split(",") if x.strip()]
148    print(f"tag={args.tag}  sizes={sizes}  runs={args.runs}  max_tokens={MAX_TOKENS}")
149    print(f"filler={len(FILLER)} chars from {len(SOURCES)} repo files\n")
150
151    if not args.skip_warmup:
152        print("warm-up (not counted) ...", flush=True)
153        w = call(build_prompt(64), max_tokens=16)
154        print(f"  warm-up: {w.get('prompt_n')} prompt tokens, "
155              f"{w.get('prompt_tok_s')} prompt tok/s, {w.get('decode_tok_s')} decode tok/s, "
156              f"wall {w.get('wall_s')}s\n")
157
158    out = {"tag": args.tag, "max_tokens": MAX_TOKENS, "runs_per_config": args.runs,
159           "warmup": not args.skip_warmup, "configs": []}
160
161    for size in sizes:
162        rows = []
163        for i in range(1, args.runs + 1):
164            # 每次一个不一样的 nonce:否则服务端复用前缀缓存,第 2..N 次只读几个新 token
165            prompt = build_prompt(size, nonce=f"{args.tag}-{size}-{i}-{random.randrange(10**9)}")
166            r = call(prompt)
167            r["run"] = i
168            rows.append(r)
169            if "error" in r:
170                print(f"  [{size}] run {i}: ERROR {r['error'][:110]}", flush=True)
171            else:
172                print(f"  [{size}] run {i}: prompt {r['prompt_n']} tok @ {r['prompt_tok_s']:.1f} tok/s, "
173                      f"gen {r['predicted_n']} tok @ {r['decode_tok_s']:.1f} tok/s, "
174                      f"TTFT {r['prompt_ms']/1000:.1f}s, wall {r['wall_s']}s", flush=True)
175        cfg = {
176            "requested_tokens": size,
177            "prompt_n": rows[0].get("prompt_n") if rows else None,
178            "cache_n": [r.get("cache_n") for r in rows],
179            "generated_n": [r.get("predicted_n") for r in rows],
180            "runs": len(rows),
181            "prompt_tok_s_median_range": med_range([r.get("prompt_tok_s") for r in rows]),
182            "decode_tok_s_median_range": med_range([r.get("decode_tok_s") for r in rows]),
183            "ttft_s_median_range": med_range([(r.get("prompt_ms") or 0) / 1000 for r in rows]),
184            "wall_s": [r.get("wall_s") for r in rows],
185            "rows": rows,
186        }
187        out["configs"].append(cfg)
188        print(f"  ⇒ {size}: prompt {cfg['prompt_n']} tok | prompt tok/s {cfg['prompt_tok_s_median_range']} "
189              f"| decode tok/s {cfg['decode_tok_s_median_range']} | TTFT {cfg['ttft_s_median_range']}\n",
190              flush=True)
191
192    if args.recall:
193        prompt = build_prompt(2048, needle_depth=0.5, nonce=f"recall-{random.randrange(10**9)}")
194        r = call(prompt, max_tokens=32)
195        ok = NEEDLE.lower() in (r.get("answer_head") or "").lower()
196        r["needle"] = NEEDLE
197        r["needle_found"] = ok
198        out["recall"] = r
199        print(f"recall @50% of ~2048: prompt {r.get('prompt_n')} tok -> "
200              f"{'FOUND ✅' if ok else 'MISSED ❌'}  answer={r.get('answer_head')!r}")
201
202    path = OUT / f"strata-bench-{args.tag}.json"
203    path.write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
204    print(f"\nwrote {path}")
205
206
207if __name__ == "__main__":
208    main()