okami.mom/strata

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

Niko1221Version 0.2.15 / Control 0.1.61: app and Terminal 0.2.15, Control 0.1.61; every engine package stays 0.1.60 (the v0.2.14 files, carried by absolute url)e39a52e33

main
10.7 KiB225 linesraw
1#!/usr/bin/env python3
2"""The capability table: what each model family runs on, per kind of hardware.
3
4    python tools/capability_table.py --check     fail when a page or the table disagrees with the data
5    python tools/capability_table.py --write     rebuild docs/CAPABILITIES.md and the summaries in the other pages
6
7Inputs: docs/data/capabilities.json (what the docs commit to) and docs/data/release.json (the packages in the release).  The
8"packaged" column is read from the release's package names, never typed.  Checks:
9  * a family marked "yes" or "untested" on some hardware has a package for it in the release, and one marked "no" has none;
10  * every package of a family lands in a column of the table;
11  * docs/CAPABILITIES.md and every `<!-- cap:... -->` block in AI_SETUP and AI_REFERENCE are what the
12    generator would write (so a page cannot keep a sentence the table contradicts).
13Block syntax in a page:  <!-- cap:summary:FAMILY -->text<!-- /cap -->   <!-- cap:cell:FAMILY:COLUMN -->text<!-- /cap -->
14Standard library only.
15"""
16import argparse
17import json
18import os
19import re
20import sys
21
22sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23import doc_pages  # noqa: E402
24
25ROOT = doc_pages.ROOT
26DATA = os.path.join(ROOT, "docs", "data", "capabilities.json")
27RELEASE = os.path.join(ROOT, "docs", "data", "release.json")
28OUT = "docs/CAPABILITIES.md"
29PAGES = ["docs/AI_SETUP.md", "docs/AI_REFERENCE.md"]
30
31ASSET_RE = re.compile(r"^strata-(engine|dsv41)-(\d+(?:\.\d+)*)-(windows|linux|macos)-(x86_64|aarch64|arm64)-(cuda|hip|sycl|metal)(?:-(.+?))?\.(?:tar\.gz|zip)$")
32COLUMN_OF = {("windows", "cuda"): "nvidia_win", ("linux", "cuda", "x86_64"): "nvidia_linux", ("linux", "cuda", "aarch64"): "nvidia_spark",
33             ("windows", "hip"): "amd_win", ("linux", "hip"): "amd_linux", ("linux", "sycl"): "intel_linux", ("macos", "metal"): "mac"}
34PKG_RE = re.compile(r"^strata-(control|dsv41|engine)-(\d+(?:\.\d+)*)-(.+?)\.(?:tar\.gz|zip)$")
35KIND_WORDS = {"control": "Control", "dsv41": "DeepSeek engines", "engine": "engines"}
36MARK_RE = re.compile(r"<!-- cap:(\S+?) -->(.*?)<!-- /cap -->", re.S)
37STATUS_WORD = {"yes": "supported", "untested": "package present, untested", "no": "does not run"}
38
39
40def read_json(path):
41    with open(path, encoding="utf-8") as f:
42        return json.load(f)
43
44
45def column_for(os_name, arch, backend):
46    return COLUMN_OF.get((os_name, backend, arch)) or COLUMN_OF.get((os_name, backend))
47
48
49def packages(release, family):
50    """column id -> sorted list of 'variant' strings for the family's packages in the release."""
51    found = {}
52    wanted = family.get("backends")
53    for name in release["assets"]:
54        if not name.startswith(family["asset_prefix"]):
55            continue
56        m = ASSET_RE.match(name)
57        if not m:
58            continue
59        kind, ver, os_name, arch, backend, variant = m.groups()
60        if wanted and backend not in wanted:
61            continue
62        col = column_for(os_name, arch, backend)
63        found.setdefault(col, []).append((backend + ("-" + variant if variant else ""), ver))
64    return {c: sorted(v) for c, v in found.items()}
65
66
67def validate(cap, release):
68    problems = []
69    ids = [c["id"] for c in cap["columns"]]
70    for fam in cap["families"]:
71        pk = packages(release, fam)
72        for col in pk:
73            if col not in ids:
74                problems.append("%s: a package lands in column %r, which the table does not have" % (fam["id"], col))
75        for col in ids:
76            cell = fam["cells"].get(col)
77            if cell is None:
78                problems.append("%s: no cell for %s" % (fam["id"], col))
79                continue
80            has = bool(pk.get(col))
81            if cell["supported"] in ("yes", "untested") and not has:
82                problems.append("%s on %s is marked %s but the release has no package for it" % (fam["id"], col, cell["supported"]))
83            if cell["supported"] == "no" and has:
84                problems.append("%s on %s is marked 'no' but the release has a package for it (%s)" % (fam["id"], col, ", ".join(v for v, _ in pk[col])))
85            if cell["supported"] not in STATUS_WORD:
86                problems.append("%s on %s: unknown status %r" % (fam["id"], col, cell["supported"]))
87    return problems
88
89
90def carried(release):
91    """version -> kind -> platforms of the packages in the asset list that are not at the release's Control / engine version
92    (a package carried over from an earlier release unchanged)."""
93    out = {}
94    for name in release["assets"]:
95        m = PKG_RE.match(name)
96        if m and m.group(2) != release["control_version" if m.group(1) == "control" else "engine_version"]:
97            out.setdefault(m.group(2), {}).setdefault(m.group(1), []).append(m.group(3))
98    return out
99
100
101def versions_line(release):
102    c, e = release["control_version"], release["engine_version"]
103    if c == e or c.startswith(e + "."):                     # one version (a Control-only hotfix part counts as the same build)
104        s = "App and Terminal %s, Control and engines %s" % (release["product_version"], e)
105    else:                                                   # 0.2.15: Control 0.1.61 with the 0.1.60 engines of v0.2.14
106        s = "App and Terminal %s, Control %s, engines %s" % (release["product_version"], c, e)
107    for ver, kinds in sorted(carried(release).items()):
108        s += "; these packages stay at %s: %s" % (ver, "; ".join("%s %s" % (KIND_WORDS[k], ", ".join(sorted(p)))
109                                                                for k, p in sorted(kinds.items())))
110    return s + ". App, Control and engine versions differ on purpose."
111
112
113def label(cap, col):
114    return next(c["label"] for c in cap["columns"] if c["id"] == col)
115
116
117def cell_text(cap, fam, col):
118    c = fam["cells"][col]
119    if c["supported"] == "yes":
120        return "runs" + (" (%s)" % c["hardware"] if c["hardware"] else "")
121    if c["supported"] == "untested":
122        return "package present, not tested"
123    return "does not run"
124
125
126def summary(cap, fam):
127    yes = ["%s%s" % (label(cap, c["id"]), " (%s)" % fam["cells"][c["id"]]["hardware"] if fam["cells"][c["id"]]["hardware"] else "")
128           for c in cap["columns"] if fam["cells"][c["id"]]["supported"] == "yes"]
129    untested = [label(cap, c["id"]) for c in cap["columns"] if fam["cells"][c["id"]]["supported"] == "untested"]
130    no = [label(cap, c["id"]) for c in cap["columns"] if fam["cells"][c["id"]]["supported"] == "no"]
131    s = "%s runs in the desktop app and in the Terminal. Hardware: %s." % (fam["name"], "; ".join(yes))
132    if untested:
133        s += " Package present but not tested: %s." % ", ".join(untested)
134    if no:
135        s += " Does not run on: %s." % ", ".join(no)
136    return s + " Per-hardware limits and measurements: [CAPABILITIES.md](CAPABILITIES.md#%s)." % fam["id"]
137
138
139def block(cap, release, key):
140    parts = key.split(":")
141    fams = {f["id"]: f for f in cap["families"]}
142    if parts[0] == "summary":
143        return summary(cap, fams[parts[1]])
144    if parts[0] == "cell":
145        return cell_text(cap, fams[parts[1]], parts[2])
146    raise KeyError(key)
147
148
149def page(cap, release):
150    cols = cap["columns"]
151    out = ["# Which model runs on which hardware", "",
152           "This page is built by `tools/capability_table.py` from [docs/data/capabilities.json](data/capabilities.json) and the package names of release %s ([docs/data/release.json](data/release.json)). Do not edit it by hand." % release["tag"],
153           "",
154           "- **Packaged**: the engine packages in the release for that hardware. Read from the release's file names.",
155           "- **Supported**: what these docs commit to. *untested* means a package exists and nothing is claimed.",
156           "- **Measured**: where numbers for that combination are published. Empty means none are published; it does not mean the combination fails.",
157           "",
158           versions_line(release),
159           "", "## At a glance", "",
160           "| Model | " + " | ".join(c["label"] for c in cols) + " |",
161           "| --- |" + " --- |" * len(cols)]
162    for fam in cap["families"]:
163        out.append("| [%s](#%s) | %s |" % (fam["name"], fam["id"], " | ".join(
164            {"yes": "yes", "untested": "untested", "no": "no"}[fam["cells"][c["id"]]["supported"]] for c in cols)))
165    for fam in cap["families"]:
166        pk = packages(release, fam)
167        out += ["", '<a id="%s"></a>' % fam["id"], "", "## " + fam["name"], "", "Model guide: [%s](%s)." % (fam["guide"].split("#")[0], fam["guide"]), "",
168                "| Hardware | Packaged | Supported | Limits | Measured |", "| --- | --- | --- | --- | --- |"]
169        for c in cols:
170            cell = fam["cells"][c["id"]]
171            packed = ", ".join("`%s`" % v for v, _ in pk.get(c["id"], [])) or "none"
172            what = STATUS_WORD[cell["supported"]]
173            if cell["hardware"]:
174                what += ": " + cell["hardware"]
175            out.append("| %s | %s | %s | %s | %s |" % (c["label"], packed, what, cell["limits"] or "-", cell["measured"] or "-"))
176    return "\n".join(out) + "\n"
177
178
179def read(rel_path):
180    with open(os.path.join(ROOT, rel_path), encoding="utf-8", newline="") as f:
181        return f.read()
182
183
184def write_file(rel_path, text):
185    with open(os.path.join(ROOT, rel_path), "w", encoding="utf-8", newline="") as f:
186        f.write(text)
187
188
189def render(cap, release, text):
190    return MARK_RE.sub(lambda m: "<!-- cap:%s -->%s<!-- /cap -->" % (m.group(1), block(cap, release, m.group(1))), text)
191
192
193def main(argv=None):
194    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
195    g = ap.add_mutually_exclusive_group(required=True)
196    g.add_argument("--check", action="store_true")
197    g.add_argument("--write", action="store_true")
198    args = ap.parse_args(argv)
199    cap, release = read_json(DATA), read_json(RELEASE)
200    problems = validate(cap, release)
201    if args.write and not problems:
202        write_file(OUT, page(cap, release))
203        for p in PAGES:
204            text = read(p)
205            new = render(cap, release, text)
206            if new != text:
207                write_file(p, new)
208    if not problems:
209        want = page(cap, release)
210        if not os.path.exists(os.path.join(ROOT, OUT)) or read(OUT).replace("\r\n", "\n") != want:
211            problems.append("%s is not what tools/capability_table.py would write (run --write)" % OUT)
212        for p in PAGES:
213            text = read(p)
214            if not MARK_RE.search(text):
215                problems.append("%s has no <!-- cap:... --> block" % p)
216            elif render(cap, release, text) != text:
217                problems.append("%s: a <!-- cap:... --> block is out of date (run --write)" % p)
218    for p in problems:
219        print("FAIL " + p)
220    print("capability table: %s" % ("%d problem(s)" % len(problems) if problems else "ok"))
221    return 1 if problems else 0
222
223
224if __name__ == "__main__":
225    sys.exit(main())