okami.mom/strata

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

Niko1221Merge f-142b-serve into f-1426e1085c1d

main
13.1 KiB248 linesraw
1#!/usr/bin/env python3
2"""Recompute the published measurements without a GPU or model downloads."""
3import argparse
4import csv
5import gzip
6import hashlib
7import io
8import json
9import math
10from pathlib import Path
11import statistics
12import subprocess
13import tarfile
14import tempfile
15
16ROOT = Path(__file__).resolve().parent
17BUNDLE = json.loads(gzip.decompress((ROOT / "data/measurements.json.gz").read_bytes()))
18WORK = ("input_ids_sha256", "output_ids", "generated", "finish", "reused",
19        "prompt_read", "drafts_accepted", "drafts_offered")
20METRICS = ("prompt_ms", "decode_ms", "ttft_s", "wall_s")
21
22
23def read(path):
24    path = str(path)
25    local = ROOT / path
26    return json.loads(local.read_text()) if local.exists() else BUNDLE["json"][path]
27
28
29def check_csv(path, expected):
30    with (ROOT / path).open(newline="") as stream:
31        rows = list(csv.DictReader(stream))
32    normalized = [{key: "" if value is None else str(value) for key, value in row.items()}
33                  for row in expected]
34    assert rows == normalized, f"{path}: CSV differs from the complete measurement records"
35
36
37def check_tables():
38    rows = []
39    for path, result in BUNDLE["json"].items():
40        if not path.endswith("/results.json"):
41            continue
42        source, session = path.split("/")[-3:-1]
43        entry = {"pair": "", "arm": "candidate"}
44        if source != "current-speed":
45            matrix = read(f"evidence/{source}/matrix.json")
46            entry = next(item for item in matrix["sessions"] if item["name"] == session)
47        for record in result["records"]:
48            keys = ("phase", "repeat", "input_tokens", "base_tokens", "increment", "prompt_read",
49                    "reused", "generated", "prompt_ms", "decode_ms", "ttft_s", "wall_s",
50                    "drafts_accepted", "drafts_offered", "input_ids_sha256")
51            rows.append({"source": source, "session": session, "pair": entry["pair"], "arm": entry["arm"],
52                         **{key: record.get(key, "") for key in keys},
53                         "output_ids_sha256": hashlib.sha256(json.dumps(record["output_ids"]).encode()).hexdigest()})
54    # The fresh-speed session is listed first; paired sessions retain their recorded order.
55    rows.sort(key=lambda row: row["source"] != "current-speed")
56    check_csv("data/requests.csv", rows)
57    rows = []
58    for name in ("pr1107-incremental-five-pairs-iq3s", "pr1107-incremental-screen-iq2xs",
59                 "pr1107-fresh-screen-iq3s", "pr1107-fresh-screen-iq2xs"):
60        for row in read(f"evidence/{name}/summary.json")["rows"]:
61            for metric in METRICS:
62                rows.append({"comparison": name, "history_or_input_tokens": row["history_or_input_tokens"],
63                             "increment": row["increment"], "pairs": len(row["pairs"]),
64                             "metric": metric, **row[metric]})
65    check_csv("data/comparisons.csv", rows)
66    rows = []
67    for row in read("current-speed/summary.json")["rows"]:
68        rows.append({**{key: row[key] for key in ("input_tokens", "output_tokens", "repeats")},
69                     **{metric + "_" + stat: row[metric][stat]
70                        for metric in ("prefill_tokens_per_s", "decode_tokens_per_s", "ttft_s", "wall_s")
71                        for stat in ("median", "min", "max")}})
72    check_csv("data/fresh-speed.csv", rows)
73
74
75def same(a, b):
76    assert math.isclose(a, b, rel_tol=1e-10, abs_tol=1e-10), (a, b)
77
78
79def measured(record, incremental=False):
80    assert record["generated"] == len(record["output_ids"]) == 256
81    assert record["finish"] == "length"
82    assert all(math.isfinite(record[k]) and record[k] > 0 for k in METRICS)
83    expected_read = record["increment"] if incremental else record["input_tokens"]
84    expected_reuse = record["base_tokens"] if incremental else 0
85    assert record["prompt_read"] == expected_read
86    assert record["reused"] == expected_reuse
87    assert record["prompt_tokens"] == record["input_tokens"] == expected_read + expected_reuse
88
89
90def compare_summary(groups, summary):
91    assert len(groups) == len(summary["rows"])
92    for row in summary["rows"]:
93        key = (row["history_or_input_tokens"], row["increment"])
94        pairs = groups[key]
95        assert len(pairs) == len(row["pairs"])
96        assert row["identical_work"]
97        for saved in row["pairs"]:
98            pair = pairs[saved["index"]]
99            a, b = pair["baseline"], pair["candidate"]
100            assert all(a[k] == b[k] for k in WORK)
101            assert saved["differing_work_fields"] == []
102            for metric in METRICS:
103                same(saved[metric]["baseline"], a[metric])
104                same(saved[metric]["candidate"], b[metric])
105                same(saved[metric]["time_reduction_pct"], 100 * (1 - b[metric] / a[metric]))
106        for metric in METRICS:
107            reductions = [100 * (1 - p["candidate"][metric] / p["baseline"][metric]) for p in pairs.values()]
108            expected = {
109                "median_paired_time_reduction_pct": statistics.median(reductions),
110                "min_paired_time_reduction_pct": min(reductions),
111                "max_paired_time_reduction_pct": max(reductions),
112                "faster_pairs": sum(x > 0 for x in reductions),
113                "regressions_over_2pct": sum(x < -2 for x in reductions),
114                **{arm + "_median": statistics.median(p[arm][metric] for p in pairs.values())
115                   for arm in ("baseline", "candidate")},
116            }
117            for name, value in expected.items():
118                same(row[metric][name], value)
119
120
121def check_matrix(name, expected_pairs, expected_count):
122    directory = Path("evidence") / name
123    matrix = read(directory / "matrix.json")
124    assert matrix["complete"] and matrix["pairs"] == expected_pairs
125    assert len(matrix["sessions"]) == expected_pairs * 2
126    incremental = matrix["mode"] == "incremental"
127    shapes = {(n, inc) for n in matrix["lengths"] for inc in matrix["increments"]} if incremental else {(n, 0) for n in matrix["lengths"]}
128    groups, count = {}, 0
129    for session in matrix["sessions"]:
130        assert session["status"] == "passed" and session["returncode"] == 0
131        result = read(directory / session["name"] / "results.json")
132        assert result["binary_sha256"] == matrix["configs"][session["arm"]]["binary_sha256"]
133        assert result["fixtures_sha256"] == matrix["fixtures_sha256"]
134        device = read(directory / (session["name"] + "-launch.json"))["device"]
135        assert device["hip_device_count"] == 1 and device["bdf"] == "0000:63:00.0"
136        formal = [r for r in result["records"] if r["phase"] == "measurement"]
137        warmups = [r for r in result["records"] if r["phase"] == "shape_warmup"]
138        assert len(formal) == len(warmups) == len(shapes)
139        actual = set()
140        for r in formal:
141            measured(r, incremental)
142            key = (r["base_tokens"], r["increment"]) if incremental else (r["input_tokens"], 0)
143            assert key not in actual
144            actual.add(key)
145            pair = groups.setdefault(key, {}).setdefault(session["pair"], {})
146            assert session["arm"] not in pair
147            pair[session["arm"]] = r
148        assert actual == shapes
149        count += len(formal)
150    assert count == expected_count
151    compare_summary(groups, read(directory / "summary.json"))
152    return groups, count
153
154
155def check_sources():
156    layout = read("source-layout.json")
157    repo = subprocess.check_output(["git", "rev-parse", "--show-toplevel"], cwd=ROOT, text=True).strip()
158    archive = subprocess.check_output(["git", "archive", layout["public_base_commit"],
159                                       "CMakeLists.txt", "src", "include", "tests"], cwd=repo)
160    with tempfile.TemporaryDirectory(prefix="r9700-report-source-") as tmp:
161        with tarfile.open(fileobj=io.BytesIO(archive)) as stream:
162            stream.extractall(tmp, filter="data")
163        for arm, patch in (("baseline", "measured-baseline.patch"), ("candidate", "pr1107-candidate.patch")):
164            subprocess.run(["git", "apply", "--unidiff-zero", str(ROOT / "patches" / patch)], cwd=tmp, check=True)
165            for name, expected in layout["source_sha256"][arm].items():
166                assert hashlib.sha256((Path(tmp) / name).read_bytes()).hexdigest() == expected, (arm, name)
167    print("Archived patches reproduce all changed measured engine sources.")
168
169
170def main():
171    parser = argparse.ArgumentParser(description=__doc__)
172    parser.add_argument("--check-sources", action="store_true", help="also reconstruct source in a temporary directory using the local git object database")
173    parser.add_argument("--extract", type=Path, help="after verification, unpack complete JSON records and engine logs into a new directory")
174    args = parser.parse_args()
175    assert BUNDLE["schema"] == 1
176    assert BUNDLE["source_commit"] == "17006083063b4443458f6f0b3f5c8325cf9cca2a"
177    exports = {}
178    for line in (ROOT / "SHA256SUMS").read_text().splitlines():
179        expected, name = line.split("  ", 1)
180        assert name not in exports
181        exports[name] = expected
182        assert hashlib.sha256((ROOT / name).read_bytes()).hexdigest() == expected, name
183    actual = {p.relative_to(ROOT).as_posix() for p in ROOT.rglob("*")
184              if p.is_file() and "__pycache__" not in p.parts and p.name != "SHA256SUMS"}
185    assert set(exports) == actual, "SHA256SUMS does not cover the report files"
186    current = read("current-speed/iq3_s-session/results.json")
187    summary = read("current-speed/summary.json")
188    formal = [r for r in current["records"] if r["phase"] == "measurement"]
189    assert len(formal) == 12
190    assert len([r for r in current["records"] if r["phase"] == "shape_warmup"]) == 4
191    fixtures = json.loads(gzip.decompress((ROOT / "current-speed/fixtures.json.gz").read_bytes()))
192    for fixture in fixtures["fixtures"]:
193        assert len(fixture["ids"]) == fixture["tokens"]
194        assert hashlib.sha256(json.dumps(fixture["ids"]).encode()).hexdigest() == fixture["ids_sha256"]
195    hashes = {f["tokens"]: f["ids_sha256"] for f in fixtures["fixtures"]}
196    device = read("current-speed/iq3_s-launch.json")["device"]
197    assert device["hip_device_count"] == 1 and device["bdf"] == "0000:63:00.0"
198    assert current["binary_sha256"] == read("source-layout.json")["binary_sha256"]["candidate"]
199    for row in summary["rows"]:
200        records = [r for r in formal if r["input_tokens"] == row["input_tokens"]]
201        assert sorted(r["repeat"] for r in records) == [0, 1, 2]
202        for r in records:
203            measured(r)
204            assert r["input_ids_sha256"] == hashes[r["input_tokens"]]
205        for key, values in {
206            "prefill_tokens_per_s": [r["prompt_read"] * 1000 / r["prompt_ms"] for r in records],
207            "decode_tokens_per_s": [r["generated"] * 1000 / r["decode_ms"] for r in records],
208            "ttft_s": [r["ttft_s"] for r in records], "wall_s": [r["wall_s"] for r in records],
209        }.items():
210            for stat, value in (("median", statistics.median(values)), ("min", min(values)), ("max", max(values))):
211                same(row[key][stat], value)
212    first, n1 = check_matrix("pr1107-incremental-screen-iq3s", 2, 20)
213    confirm, n2 = check_matrix("pr1107-incremental-confirm-iq3s", 3, 30)
214    for key, pairs in confirm.items():
215        first[key].update({index + 2: pair for index, pair in pairs.items()})
216    compare_summary(first, read("evidence/pr1107-incremental-five-pairs-iq3s/summary.json"))
217    _, n3 = check_matrix("pr1107-incremental-screen-iq2xs", 2, 20)
218    _, n4 = check_matrix("pr1107-fresh-screen-iq3s", 2, 12)
219    _, n5 = check_matrix("pr1107-fresh-screen-iq2xs", 2, 12)
220    results = [value for name, value in BUNDLE["json"].items() if name.endswith("/results.json")]
221    log_names = {name.removesuffix("results.json") + "engine.log"
222                 for name in BUNDLE["json"] if name.endswith("/results.json")}
223    assert set(BUNDLE["logs"]) == log_names and len(log_names) == 23
224    check_tables()
225    coverage = {"scope": "Recomputed archived evidence, not new GPU measurements or automatic performance acceptance",
226                "paired_formal_requests": n1+n2+n3+n4+n5, "current_speed_formal_requests": len(formal),
227                "retained_records_including_warmups": sum(len(result["records"]) for result in results),
228                "engine_logs_verified": len(log_names), "exported_artifact_hashes_verified": len(exports),
229                "all_workload_performance_acceptance": False}
230    assert coverage["paired_formal_requests"] == 94 and coverage["retained_records_including_warmups"] == 213
231    if args.check_sources:
232        check_sources()
233    assert read("coverage.json") == coverage
234    if args.extract:
235        args.extract.mkdir(parents=True, exist_ok=False)
236        for kind in ("json", "logs"):
237            for name, value in BUNDLE[kind].items():
238                relative = Path(name)
239                assert not relative.is_absolute() and ".." not in relative.parts
240                path = args.extract / relative
241                path.parent.mkdir(parents=True, exist_ok=True)
242                path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n" if kind == "json" else value)
243        print(f"Complete measurement records and engine logs extracted to {args.extract}")
244    print(json.dumps(coverage, indent=2))
245
246
247if __name__ == "__main__":
248    main()