okami.mom/strata

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

xyzzingCommunity benchmark: RX 7900 XTX 24 GB — ROCm 7.1.1 vs ROCm 10.2 nightly, serve-path decode (Qwen3.8-Flash-Next IQ3_S) (#745)8d6ae0cd8

main
13.6 KiB284 linesraw
1#!/usr/bin/env python3
2"""hipblaslt1005_driver.py - unconfound the 128K prefill comparison in PR #745.
3
4T4 (record-autotune-128k-pr-20261004.json) measured the ROCm 10.2 nightly arm without a
5matching hipBLASLt tuning table (its 100500-era library refuses the gfx1100-100100 table),
6so its prefill number carried the #505 table-version fallback, not the toolchain.  This
7driver A/Bs the SAME nightly engine on the SAME workload with and without a freshly tuned
8gfx1100-hipblaslt-100500 table (tuned on this host against the nightly SDK's own
9libhipblaslt by build-hip-0138/tune_hipblaslt under LD_LIBRARY_PATH).
10
11Methodology = rates_amd.py: one-shot `strata generate`, greedy, 256 generated tokens,
12prefill_tok_s = prompt_tokens / GPU_timeline_s, decode from the engine's own decode line,
13median of 3 clean cells per arm (STALL_FRAC flagging, flagged cells never published).
14One 1k cell on the table arm is the decode sanity check (decode is O(1) in context).
15
16Cells run one at a time inside a systemd-run --user scope with MemoryMax (the desktop
17protection), gated on MemAvailable, and each cell first checks no stale engine process
18holds the GPU (the P1 KFD-pid check).
19"""
20import json
21import os
22import re
23import subprocess
24import sys
25import time
26
27TS = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())
28OUT = f"/home/zacch/projects/strata-amd/artifacts/rocm/results/record-hipblaslt-100500-{TS}.json"
29LOGDIR = "/home/zacch/projects/strata-amd/artifacts/rocm/logs"
30
31SDK = "/home/zacch/strata-rocm-experiments/20261003-231142/sdk"
32EXE = "/home/zacch/strata-rocm-experiments/20261003-231142/build-nightly/strata"
33TABLE = "/home/zacch/strata-rocm-experiments/20261003-231142/gfx1100-hipblaslt-100500.txt"
34
35# the nightly candidate's exact serving args (serve-nightly-8082.json) - the config the
36# PR's r10 numbers and runs.json describe.
37COMMON = [
38    "--pack", "/home/zacch/projects/strata-amd/packs/iq3_s",
39    "--native", "/home/zacch/models/flash-next-iq3s/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf",
40    "--ple-gguf", "/home/zacch/models/flash-next-iq3s/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf",
41    "--mtp", "/mnt/LINUXWINSHARE/Backup/models/mtp/rt",
42    "--expert-profile", "/home/zacch/projects/strata-amd/Strata/data/expert-profile.bin",
43    "--expert-cache", "auto", "--spec", "3",
44    "--kv", "int8", "--kv-resident", "32768", "--prefill", "8192",
45    # without an explicit reserve the cache auto-sizes against ~all free VRAM and the later
46    # cublasCreate fails ALLOC (cell 1 of run 5: engine fully loaded, then status 2).  3072
47    # matches serve-nightly-8082.json exactly.
48    "--vram-reserve-mib", "3072",
49]
50ARM_ENV = {
51    "nightly-100500": {"STRATA_HIPBLASLT_TUNING": TABLE},
52    "nightly-notable": {},
53}
54BASE_ENV = {
55    "LD_LIBRARY_PATH": f"{SDK}/lib",
56    "STRATA_PREFILL_RING": "96",
57    "STRATA_GR_V3": "1",
58    "STRATA_SELECT_WMMA": "1",
59    "STRATA_PREFILL_TIMING": "1",
60    "HIP_VISIBLE_DEVICES": "0",
61    "HOME": "/home/zacch",
62}
63
64TOKENS = "/home/zacch/projects/strata-amd/artifacts/rocm/workloads/qsa-profile-%d.tokens"
65PLAN = [
66    # (arm, tier, prompt tokens, token file, --max-context)
67    ("nightly-100500", "1k",   1024,   TOKENS % 1024,   9216),
68    ("nightly-100500", "128k", 131072, TOKENS % 131072, 139264),
69    ("nightly-notable", "128k", 131072, TOKENS % 131072, 139264),
70]
71PER_ARM = 3          # clean cells per (arm, tier); the 1k sanity tier needs only 1
72SANITY = {("nightly-100500", "1k")}
73STALL_FRAC = 0.4
74
75PRE_RE = re.compile(r"prefill timing: (\d+) tokens, GPU timeline ([\d.]+) ms, wall ([\d.]+) ms")
76DEC_RE = re.compile(r"decode\s+(\d+) tokens? in ([\d.]+)\s*(ms|s)\s*->\s*([\d.]+) tok/s", re.I)
77SPEC_RE = re.compile(r"spec accept[^%]*?([\d.]+)%")
78TTFT_RE = re.compile(r"ttft[^0-9]*([\d.]+)\s*s", re.I)
79LT_ENABLED_RE = re.compile(r"hipBLASLt tuning enabled \((\d+) rows, (\S+), version (\d+)\)")
80LT_REFUSED_RE = re.compile(r"prefill gemm: (.*mismatch.*|.*cannot open.*|.*invalid.*); using hipBLASEx")
81
82
83def mem_available_gb():
84    for line in open("/proc/meminfo"):
85        if line.startswith("MemAvailable:"):
86            return int(line.split()[1]) / 1e6
87    return 0.0
88
89
90def stale_engine_holders():
91    out = subprocess.run(["ps", "-eo", "pid,cmd"], capture_output=True, text=True).stdout
92    hits = []
93    for l in out.splitlines():
94        if ("build-nightly/strata" in l or "build-hip" in l and "/strata" in l) \
95                and "ps -eo" not in l and "appimage" not in l.lower():
96            hits.append(l.strip())
97    return hits
98
99
100def vram_used_mib():
101    try:
102        return int(open("/sys/class/drm/card1/device/mem_info_vram_used").read()) // 1048576
103    except OSError:
104        return 0
105
106
107def wait_headroom(need_gb=58, timeout_s=1800):
108    # 58 GB RAM + < 2600 MiB VRAM, not the campaigns' 66/70-RAM-only gate: those assumed the
109    # 51 GB-resident 8081 co-running and nothing else touching VRAM.  The resident is stopped
110    # for this run; the desktop is protected by the per-cell MemoryMax/MemoryHigh scope.
111    # VRAM must be gated per cell because a previous cell's pages drain asynchronously
112    # (a shrunken expert cache silently poisons every later cell otherwise), and RAM because
113    # this engine refuses rc=1 below its own startup demand.
114    t0 = time.time()
115    while time.time() - t0 < timeout_s:
116        if mem_available_gb() >= need_gb and vram_used_mib() < 2600:
117            return True
118        time.sleep(10)
119    return False
120
121
122def run_cell(arm, tier, tokfile, ctx, seq):
123    """One one-shot generate inside a MemoryMax scope; returns the parsed cell dict."""
124    log_path = f"{LOGDIR}/t1005-raw-{arm}-{tier}-{seq}.log"
125    env = dict(BASE_ENV)
126    env.update(ARM_ENV[arm])
127    envstr = " ".join(f"{k}={json.dumps(str(v))}" if "(" in str(v) or " " in str(v) else f"{k}={v}"
128                      for k, v in env.items())
129    cmd = (" ".join(["--tokens-file", tokfile, "--max-new", "256", "--max-context", str(ctx)] + COMMON))
130    unit = f"t1005-{seq}"
131    # --wait is load-bearing: without it systemd-run only SUBMITS the unit (rc 0, no engine
132    # output in our log - cell 1 of the first run proved it).  --pipe is equally load-bearing:
133    # without it the unit's stdout/stderr go to the journal and a failed cell's error is
134    # invisible (cell 1 of the third run: rc=1 with only systemd's summary in the log).
135    scope = ["systemd-run", "--user", "--collect", "--wait", "--pipe", f"--unit={unit}",
136             "-p", "MemoryMax=66G", "-p", "MemoryHigh=61G", "-p", "Restart=no",
137             "/usr/sbin/bash", "-c",
138             f"cd /home/zacch/projects/strata-amd && exec env {envstr} {EXE} {cmd}"]
139    with open(log_path, "w") as lf:
140        t0 = time.time()
141        p = subprocess.run(scope, stdout=lf, stderr=subprocess.STDOUT, timeout=3600)
142        wall = time.time() - t0
143    out = open(log_path, errors="replace").read()
144    cell = {"arm": arm, "tier": tier, "exit": p.returncode, "wall_s": round(wall, 1),
145            "raw_log": log_path,
146            "conditions": {"loadavg": open("/proc/loadavg").read().split()[:3],
147                           "mem_available_gb": round(mem_available_gb(), 1)}}
148    m = LT_ENABLED_RE.search(out)
149    if m:
150        cell["lt_table"] = {"rows": int(m.group(1)), "arch": m.group(2), "version": int(m.group(3))}
151    else:
152        r = LT_REFUSED_RE.search(out)
153        cell["lt_table"] = {"engaged": False, "refusal": r.group(1) if r else "no tuning line found"}
154    m = PRE_RE.search(out)
155    if m:
156        cell["prompt_tokens"] = int(m.group(1))
157        gpu_s = float(m.group(2)) / 1000.0
158        cell["prefill_gpu_s"] = round(gpu_s, 4)
159        cell["prefill_tok_s"] = round(cell["prompt_tokens"] / gpu_s, 2) if gpu_s else None
160    m = DEC_RE.search(out)
161    if m:
162        cell["decoded"] = int(m.group(1))
163        cell["decode_wall_s"] = round(float(m.group(2)) / (1000.0 if m.group(3).lower() == "ms" else 1.0), 3)
164        cell["decode_tok_s"] = round(float(m.group(4)), 2)
165    m = SPEC_RE.search(out)
166    if m:
167        cell["spec_accept"] = round(float(m.group(1)) / 100.0, 3)
168    m = TTFT_RE.search(out)
169    if m:
170        cell["ttft_s"] = round(float(m.group(1)), 2)
171    return cell
172
173
174def median(xs):
175    xs = sorted(xs)
176    n = len(xs)
177    return None if not n else xs[n // 2] if n % 2 else round((xs[n // 2 - 1] + xs[n // 2]) / 2, 2)
178
179
180def main():
181    if not os.path.exists(TABLE):
182        sys.exit(f"table missing: {TABLE} - tune it first (see record-hipblaslt-100500)")
183    state = {"record": "hipblaslt-100500-unconfound", "at": TS,
184             "pr": "https://github.com/Niko1221/Strata/pull/745",
185             "method": ("rates_amd.py methodology on the PR #745 nightly candidate (ROCm 10.2 "
186                        "nightly SDK + rocWMMA, spec 3): one-shot strata generate, greedy, 256 "
187                        "generated tokens; prefill_tok_s = prompt_tokens / GPU_timeline_s; median "
188                        "of 3 clean cells per arm (STALL_FRAC=0.4 flagging, flagged cells never "
189                        "published); arms differ ONLY in STRATA_HIPBLASLT_TUNING "
190                        "(gfx1100-hipblaslt-100500.txt tuned on this host vs unset)."),
191             "engine": EXE, "sdk": SDK, "table": TABLE, "table_provenance": {
192                 "tuner": "/home/zacch/projects/strata/build-hip-0138/tune_hipblaslt under "
193                          "LD_LIBRARY_PATH=<sdk>/lib",
194                 "shapes": "artifacts/rocm/tables/hipblaslt-shapes-canon.json (16 shapes x "
195                           "{4096,8192} buckets, union of shipped gfx1100 tables + upstream "
196                           "gfx1201-100500 set)",
197                 "tuner_log": "artifacts/rocm/logs/tune-hipblaslt-100500.log"},
198             "cells": [], "verdict": None}
199    if os.path.exists(OUT):
200        state["cells"] = json.load(open(OUT)).get("cells", [])
201
202    def clean_cells(arm, tier):
203        cs = [c for c in state["cells"] if c["arm"] == arm and c["tier"] == tier
204              and c["exit"] == 0 and c.get("decode_tok_s") and c.get("prefill_tok_s")
205              and not c.get("stall_flag")]
206        return cs
207
208    def flag_stalls():
209        for arm, tier, _, _, _ in PLAN:
210            need = 1 if (arm, tier) in SANITY else PER_ARM
211            cs = [c for c in state["cells"] if c["arm"] == arm and c["tier"] == tier
212                  and c["exit"] == 0 and c.get("decode_tok_s") and c.get("prefill_tok_s")]
213            bd = max((c["decode_tok_s"] for c in cs), default=0.0)
214            bp = max((c["prefill_tok_s"] for c in cs), default=0.0)
215            for c in cs:
216                d = bool(bd and c["decode_tok_s"] < STALL_FRAC * bd)
217                pp = bool(bp and c["prefill_tok_s"] < STALL_FRAC * bp)
218                c["stall_flag"] = bool(d or pp)
219                c["stall_why"] = "decode" if d and pp else "prefill" if pp else "decode" if d else ""
220
221    seq = len(state["cells"])
222    consecutive_fail = 0
223    for arm, tier, _, tokfile, ctx in PLAN:
224        while len(clean_cells(arm, tier)) < (1 if (arm, tier) in SANITY else PER_ARM):
225            if consecutive_fail >= 3:
226                state["verdict"] = "aborted: 3 consecutive cell failures"
227                break
228            if not wait_headroom():
229                state["verdict"] = "incomplete: MemAvailable gate timed out"
230                break
231            stale = stale_engine_holders()
232            if stale:
233                print("stale engine holders, waiting:", stale, flush=True)
234                time.sleep(20)
235                continue
236            flag_stalls()
237            seq += 1
238            print(f"cell {seq}: {arm} {tier} (vram={vram_used_mib()}MiB "
239                  f"avail={mem_available_gb():.0f}GB) ...", flush=True)
240            cell = run_cell(arm, tier, tokfile, ctx, seq)
241            state["cells"].append(cell)
242            flag_stalls()
243            json.dump(state, open(OUT, "w"), indent=1)
244            print(f"  rc={cell['exit']} lt={cell['lt_table']} prefill={cell.get('prefill_tok_s')} "
245                  f"decode={cell.get('decode_tok_s')}", flush=True)
246            consecutive_fail = consecutive_fail + 1 if (cell["exit"] != 0 or
247                                                        not cell.get("decode_tok_s")) else 0
248        else:
249            continue
250        break
251
252    # verdict: medians per arm at 128k, table effect on the nightly stack
253    flag_stalls()
254    verdict = {"128k": {}, "1k_sanity": None}
255    for arm in ARM_ENV:
256        cs = clean_cells(arm, "128k")
257        if cs:
258            verdict["128k"][arm] = {
259                "n": len(cs),
260                "prefill_tok_s_median": median([c["prefill_tok_s"] for c in cs]),
261                "prefill_range": [min(c["prefill_tok_s"] for c in cs), max(c["prefill_tok_s"] for c in cs)],
262                "decode_tok_s_median": median([c["decode_tok_s"] for c in cs]),
263                "decode_range": [min(c["decode_tok_s"] for c in cs), max(c["decode_tok_s"] for c in cs)],
264            }
265    sanity = clean_cells("nightly-100500", "1k")
266    if sanity:
267        verdict["1k_sanity"] = {"decode_tok_s": sanity[0]["decode_tok_s"],
268                                "prefill_tok_s": sanity[0]["prefill_tok_s"]}
269    a, b = verdict["128k"].get("nightly-100500"), verdict["128k"].get("nightly-notable")
270    if a and b and a["prefill_tok_s_median"] and b["prefill_tok_s_median"]:
271        verdict["prefill_table_effect_pct"] = round(
272            100.0 * (a["prefill_tok_s_median"] / b["prefill_tok_s_median"] - 1.0), 2)
273        verdict["conclusion"] = (
274            "prefill gain from the 100500 table on the nightly stack; the T4 r10 deficit was the "
275            "table-version fallback" if verdict["prefill_table_effect_pct"] > 10.0 else
276            "prefill NOT recovered by the table - the T4 r10 deficit is NOT purely the "
277            "table-version effect; report as measured")
278    state["verdict"] = verdict
279    json.dump(state, open(OUT, "w"), indent=1)
280    print(json.dumps(verdict, indent=1), flush=True)
281
282
283if __name__ == "__main__":
284    main()