okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
31.7 KiB450 linesraw
1#!/usr/bin/env python3
2"""A model release, planned: what would be built, signed and uploaded for a new model, from the intake report.  A DRY RUN.
3
4    python packaging/make_model_release.py --intake qwen4_intake.json --id qwen4-x --app-version 0.2.12 --sequence 123 \
5        --prev-upload C:/rc214e/FINAL2/UPLOAD [--revision <HF commit>] [--engine-version 0.1.58] [--case A|B] [--write OUTDIR]
6
7What it does: reads tools/qwen4_intake.py's JSON, takes the verdict (case A: the model runs on the engine as it is; case B: the
8engines have to be rebuilt for its shape; case C is refused) and prints the plan in the order of the 0.2.11 release
9(phaseA-tests/rel0211: final_rc1.py, publish211.sh, PUBLISH-PLAN.md):
10
11    case A  the feed (a `models` entry, the feed re-signed at the next sequence). No app rebuild: the app lists feed models
12            from the feed (the Settings update check is enough). `--with-app` adds the app steps when a release has app text anyway.
13            Engines and Controls stay as they are: same files, same names.
14    case B  the engine of the model's shape, as its own component (`--shape`, package_engine.py --shape, feed member shape_engines: strata_control/shape_engine.py),
15            plus the feed. The Strata engine, the Controls and the app are not rebuilt: a Control of 0.2.13 or later already installs and runs
16            a shape engine, and the model's family `qwen4exp_<shape>` makes it fetch it.
17
18Each step shows where it runs, a rough time, the command (printed, never run) and its outputs with sizes.  Sizes are those of the
19previous release's files (`--prev-upload`), so they are estimates for what gets rebuilt and exact for what stays.
20
21What it never does: sign, read or name a key, build, upload, tag, push or publish.  The steps that need the release key print
22`<FEED-KEY>` for the owner to fill in at that moment.  `--execute` is refused.  With `--write OUTDIR` (a new, empty folder) it also
23writes, as plain local files: the plan (md and json), the model's feed entry (DRAFT), and the release notes, model card and checklist
24filled from the report with every measured number left as `[FILL: ...]` (publish211.sh refuses a body that still has one).
25"""
26from __future__ import annotations
27
28import argparse
29import json
30import re
31import sys
32from pathlib import Path
33
34ROOT = Path(__file__).resolve().parents[1]
35#: The release templates (the notes and the model card; forms with {{keys}} this script fills and [FILL: ...] left for a person). A release-staff
36#: tool's data: the Terminal, Control and app packages do not carry packaging/. --templates names another folder (one that also holds CHECKLIST.md, say).
37TEMPLATES = ROOT / "packaging" / "templates" / "model-release"
38TEMPLATE_NAMES = ("RELEASE-NOTES.md", "MODEL-CARD.md", "CHECKLIST.md")
39sys.path.insert(0, str(ROOT))                         # strata_control.shape_engine (the shape names)
40
41# artifact names in a release upload folder (phaseA-tests/rel0211/PUBLISH-PLAN.md, scripts/relfinal/expect_rc1.py)
42ENGINE_RE = re.compile(r"^strata-engine-(?P<v>\d[\d.]*)-(?P<plat>.+?)\.(?:tar\.gz|zip)$")
43CONTROL_RE = re.compile(r"^strata-control-(?P<v>\d[\d.]*)-(?P<plat>.+?)\.(?:tar\.gz|zip)$")
44APP_RE = re.compile(r"^(Strata-\d[\d.]*-(windows-x64-setup\.exe|linux-x86_64\.AppImage|macos-arm64\.dmg)(\.sig)?|Strata\.app\.tar\.gz(\.sig)?)$")
45FEED_NAMES = ["strata-feed.json", "strata-feed.json.sig", "strata-feed-linux-aarch64.json", "strata-feed-linux-aarch64.json.sig"]
46SMALL_NAMES = ["SHA256SUMS.txt", "latest.json", "install.sh", "install.ps1", "install-manifest.txt"]
47
48# where each platform's Qwen engine is built (phaseA-tests/rel0211/RELEASE-STATE.md "Build plan" and the box rules)
49# (the Q4-P8 rehearsal of 2026-11-08, phaseA-tests/qwen4/RESULTS-Q4-P8.md section 5: five variants in 37 minutes)
50BUILD_BOX = {"linux-x86_64-cuda": "l620", "linux-x86_64-hip": "p620", "linux-x86_64-sycl": "p1006", "windows": "owner PC",
51             "macos": "m1002", "linux-aarch64": "the Spark (dgxspark)"}
52BOX_NOTE = {"l620": "jobq; the CUDA build with its packaging takes about 15 min",
53            "p620": "jobq; /data has little room, a package is about 4 GB",
54            "p1006": "jobq",
55            "owner PC": "jobq --lock heavy, 20 min per job at most (split the release set); never while a model runs",
56            "m1002": "builds the unsigned Mac package (jobq); the owner signs it on his Mac",
57            "the Spark (dgxspark)": "off limits unless the coordinator says"}
58
59
60def gib(n: int | None) -> str:
61    return "?" if n is None else ("%.2f GiB" % (n / 2**30) if n >= 2**30 else "%.1f MiB" % (n / 2**20))
62
63
64def box_for(plat: str) -> str:
65    for key, box in BUILD_BOX.items():
66        if plat.startswith(key) or key in plat:
67            return box
68    return "see the 0.2.11 build plan"
69
70
71def scan_upload(folder: Path | None) -> dict:
72    out = {"engine": [], "control": [], "app": [], "feed": [], "small": [], "other": []}
73    if folder is None:
74        return out
75    for p in sorted(folder.iterdir()):
76        if not p.is_file():
77            continue
78        n, size = p.name, p.stat().st_size
79        for key, rx in (("engine", ENGINE_RE), ("control", CONTROL_RE), ("app", APP_RE)):
80            m = rx.match(n)
81            if m:
82                out[key].append({"name": n, "size": size, "plat": m.groupdict().get("plat", ""), "version": m.groupdict().get("v", "")})
83                break
84        else:
85            out["feed" if n in FEED_NAMES else "small" if n in SMALL_NAMES else "other"].append({"name": n, "size": size})
86    return out
87
88
89def renamed(name: str, old: str, new: str) -> str:
90    return name.replace("-%s-" % old, "-%s-" % new, 1)
91
92
93def upload_minutes(nbytes: int) -> str:
94    """The 0.2.10 table: 8.7 GiB took 12 to 70 minutes between 200 and 20 Mbit/s."""
95    if not nbytes:
96        return "-"
97    lo, hi = nbytes * 8 / 200e6 / 60, nbytes * 8 / 20e6 / 60
98    return "%d to %d min (200 to 20 Mbit/s)" % (max(1, round(lo)), max(1, round(hi)))
99
100
101def plan(report: dict, set_index: int, a, prev: dict) -> dict:
102    s = report["sets"][set_index]
103    v = s.get("verdict", {})
104    case = a.case or v.get("case")
105    if case not in ("A", "B"):
106        raise SystemExit("case %s: %s. A model release is planned for case A or B only (run tools/qwen4_intake.py)."
107                         % (case, v.get("reading", "no verdict in the report")))
108    with_app = bool(a.with_app)                         # a feed model needs no app rebuild (the app lists it from the feed), case B included: the shape engine is fetched by the Control
109    steps: list[dict] = []
110    changed: list[dict] = []        # files that are new or different in the upload folder
111    kept: list[dict] = []
112
113    def step(sid, what, where, minutes, cmds, outputs=None, owner=False, note=None):
114        steps.append({"id": sid, "what": what, "where": where, "minutes": minutes, "commands": cmds, "outputs": outputs or [],
115                      "owner_only": owner, "note": note})
116
117    warn: list[str] = []
118    files = s["files"]
119    if any(not f.get("sha256") for f in files):
120        warn.append("some files in the report have no sha256: run the intake with --sha256 (local files) or on the Hugging Face repository (the LFS hash) before the entry is final")
121    if not a.revision:
122        warn.append("no --revision: the entry needs the pinned Hugging Face commit")
123    entry = model_entry(s, a)
124
125    n = 1
126    step("%d" % n, "Re-read the files at the pinned revision (headers only) and keep the report", "owner PC, python only", 1,
127         ["python tools/qwen4_intake.py --hf %s --rev %s%s --out intake-pinned.json" % (a.hf_repo or "<REPO>", a.revision or "<COMMIT>",
128                                                                                         (" --dir " + a.hf_dir) if a.hf_dir else "")]
129         if (a.hf_repo or not a.revision) else ["python tools/qwen4_intake.py <the folder> --sha256 --out intake-final.json"],
130         ["intake-pinned.json"])
131    n += 1
132    if case == "B":
133        shape = a.shape
134        comp = "strata-" + shape.replace("_", "-")
135        for e in prev["engine"]:
136            if e["name"].endswith((".tar.gz", ".zip")):
137                new = renamed(e["name"], e["version"], a.engine_version).replace("strata-engine-", comp + "-", 1)
138                changed.append({"name": new, "size": e["size"], "est": True, "why": "the engine of the shape %s, its own component" % shape})
139        kept += [{"name": e["name"], "size": e["size"], "why": "the Strata engine is not touched: Flash-Next and every other model keep it"} for e in prev["engine"]]
140        kept += [{"name": e["name"], "size": e["size"], "why": "no Control rebuild: a Control of 0.2.13 or later already knows shape engines"} for e in prev["control"]]
141        by_box: dict[str, list] = {}
142        for e in prev["engine"]:
143            by_box.setdefault(box_for(e["plat"]), []).append(e)
144        step("%d" % n, "A geometry header for the model's shape, made from the file", "owner PC (python)", 2,
145             ["# the shape fields the intake listed:"] + ["#   %s is %s (kernels built for %s)" % (d["key"], d["got"], d.get("kernels_built_for", d.get("limit")))
146                                                          for d in v.get("shape_fields_that_differ", [])]
147             + ["python tools/q4geo_synth.py --from-gguf <first shard> --header <geo.hpp> --label %s" % shape,
148                "# every build passes -DSTRATA_GEOMETRY_FILE=<geo.hpp> (Linux packaging scripts: STRATA_CMAKE_EXTRA=\"-DSTRATA_GEOMETRY_FILE=<geo.hpp>\"); give the engines their own version %s" % a.engine_version],
149             note="the engine built for this shape refuses Flash-Next files, so it ships as its own component named after the shape (%s) and never in place of the Strata engine (owner, 2026-11-08; RESULTS-SHAPE.md)" % comp)
150        n += 1
151        for box, es in sorted(by_box.items()):
152            step("%d" % n, "Build the %s engine packages on %s" % (shape, box), "%s (%s)" % (box, BOX_NOTE.get(box, "see the 0.2.11 build plan")), 25 if box.startswith("owner") else 15 if box == "l620" else 10,
153                 ["# per package, as in phaseA-tests/rel0211/scripts (build_*.sh), with the shape's header; then, instead of the usual package_engine.py call:",
154                  "python packaging/package_engine.py --src <stage> --backend <backend> --version %s --shape %s --min-runtime <the Control that knows shape engines> ...   # the usual --arch/--variant/--tree/--min-driver of that platform" % (a.engine_version, shape),
155                  "python packaging/feed_tool.py sign-package <package-folder> --key <FEED-KEY>   # OWNER'S KEY, not run here",
156                  "python packaging/feed_tool.py pack-engine <package-folder> --out <shape-packs> --url-prefix=   # the archive is %s-<version>-<platform>-<backend>, the entry names the shape" % comp],
157                 [renamed(e["name"], e["version"], a.engine_version).replace("strata-engine-", comp + "-", 1) + "  (" + gib(e["size"]) + ", estimated)" for e in es])
158            n += 1
159        step("%d" % n, "Mac: the owner signs and notarises the unsigned %s engine on his Mac, then it is signed into the feed" % shape, "the owner's Mac, about 45 min of his time", 45,
160             ["bash sign-and-notarize.sh --engine strata-engine-%s-macos-arm64-metal-unsigned-folder.tar.gz   # the code is generic: the entrypoint comes from the manifest (the package's id is %s)" % (a.engine_version, comp),
161              "python packaging/feed_tool.py sign-package <the signed folder> --key <FEED-KEY>   # OWNER'S KEY, not run here", "python packaging/feed_tool.py pack-engine <the signed folder> --out <shape-packs> --url-prefix="],
162             [comp + "-%s-macos-arm64-metal.tar.gz" % a.engine_version], owner=True,
163             note="a Mac installs a model of its own shape like every other platform (Terminal and app): the Mac engine of the shape is part of the release; after the Mac package exists and before build-feed")
164    else:
165        kept += [{"name": e["name"], "size": e["size"], "why": "same file, same name; the feed entry is reused"} for e in prev["engine"] + prev["control"]]
166
167    step("%d" % n, "The model's feed entry (a `models` member entry, DRAFT)", "owner PC, python only", 2,
168         ["python packaging/make_model_release.py --intake <report> --id %s ... --write <OUTDIR>   # writes models/%s.entry.json (the feed's schema; build-feed refuses every [FILL: ...] left in it) and models/%s.model.json (the older draft)" % (a.id, a.id, a.id)],
169         ["models/%s.entry.json" % a.id], note="the entry follows strata_control/feed.py (packaging/UPDATES.md): fill the [FILL: ...] values (about, licence_url, ram_gb) by hand or with --about/--licence-url/--ram-gb, then `feed_tool.py build-feed --models <OUTDIR>/models`")
170    n += 1
171    if with_app:
172        for e in prev["app"]:
173            nm = re.sub(r"Strata-\d[\d.]*-", "Strata-%s-" % a.app_version, e["name"])
174            changed.append({"name": nm, "size": e["size"], "est": True, "why": "app rebuilt with the Models page text"})
175        step("%d" % n, "App text for the model (Models page) and the app bundles", "owner PC (Windows installer), a Linux box (AppImage), m1002 (Mac, unsigned; the owner signs)", 40,
176             ["# edit apps/host/src (the model's name and one line), then the 0.2.11 app recipe: scripts/relwin/win_installer_rc1.ps1, the AppImage and Mac scripts",
177              "python packaging/feed_tool.py set-app-platform --app-json latest.json --target <target> --archive <installer> --sig <installer.sig> --version %s" % a.app_version],
178             [c["name"] for c in changed if APP_RE.match(c["name"])])
179        n += 1
180        changed.append({"name": "latest.json", "size": None, "est": True, "why": "updater json at %s" % a.app_version})
181    else:
182        kept += [{"name": e["name"], "size": e["size"], "why": "no app change"} for e in prev["app"]]
183    if with_app:
184        mac_extra = ""
185        step("%d" % n, "Mac: the owner signs and notarises the unsigned Mac files on his Mac", "the owner's Mac, about 45 min of his time", 45,
186             ["bash sign-and-notarize.sh Strata-%s-macos-arm64.dmg%s --updater-archive --out signed" % (a.app_version, mac_extra)],
187             ["the signed folder (dmg, Strata.app.tar.gz and its .sig)"], owner=True)
188        n += 1
189    feed_cmd = ("python packaging/feed_tool.py build-feed --out <RELEASE> --key <FEED-KEY> --sequence %d --engine <engine-entries> --carry-dsv41 <the last strata-feed.json> --carry-dsv41-base https://github.com/Niko1221/Strata/releases/download/<DSV41-TAG>/ "
190                "--drafters <drafter-entries> --models <models-folder> --control <control-entries>%s%s   # OWNER'S KEY; `--models` is Q4-PREP-B's change"
191                % (a.sequence, " --shapes <shape-entries>" if case == "B" else "", " --app-json latest.json" if with_app else ""))
192    step("%d" % n, "Sign the feeds at sequence %d (the shared one and linux-aarch64)" % a.sequence, "owner PC, with the owner's key at that moment", 3,
193         [feed_cmd, "python packaging/feed_tool.py verify-feed <RELEASE> --pub <FEED-KEY.pub.json>"],
194         list(FEED_NAMES), owner=True)
195    for x in FEED_NAMES:
196        changed.append({"name": x, "size": None, "est": False, "why": "signed at sequence %d" % a.sequence})
197    n += 1
198    changed.append({"name": "SHA256SUMS.txt", "size": None, "est": False, "why": "recomputed"})
199    step("%d" % n, "Assemble the upload folder and check it", "owner PC, python only", 5,
200         ["python phaseA-tests/rel0211/scripts/relfinal/final_rc1.py --mode real --work <FINAL> --key <FEED-KEY> --pub <FEED-KEY.pub.json>   # 0.2.11's assembly: hard links, SHA256SUMS; copy it for this version first",
201          "python phaseA-tests/rel0211/scripts/relfinal/check_sums_rc1.py --upload <UPLOAD>",
202          "python phaseA-tests/rel0211/scripts/relfinal/check_feeds_rc1.py --shared <UPLOAD>/strata-feed.json --arm <UPLOAD>/strata-feed-linux-aarch64.json --upload <UPLOAD> --pub <FEED-KEY.pub.json> --src <repo> --seq %d" % a.sequence],
203         ["the upload folder"])
204    n += 1
205    up = sum(c["size"] or 0 for c in changed)
206    step("%d" % n, "Publish (the owner's word first): draft release, upload, feed LAST, then flip Latest", "owner PC", None,
207         ["bash phaseA-tests/rel0211/publish211.sh   # the dry run of the 0.2.11 publish; copy it for this release (tag, sequence, folders) and print its plan",
208          "# the printed plan: gh release create <TAG> --draft ...; gh release upload ... (packages, Controls, installers, install files, strata-feed.json LAST); gh release edit <TAG> --draft=false --latest"],
209         ["upload: %s in %d files, %s" % (gib(up), len(changed), upload_minutes(up))], owner=True)
210    n += 1
211    step("%d" % n, "Verify from the public URLs", "any box", 20,
212         ["download every asset back and sha256sum -c SHA256SUMS.txt", "python packaging/feed_tool.py verify-feed <public strata-feed.json> --pub <FEED-KEY.pub.json>",
213          "a clean-home install and `strata update --check` on a Linux box: the sequence is %d and the model is listed" % a.sequence], [])
214    return {"id": a.id, "case": case, "set": s["files"][0]["name"], "steps": steps, "changed": changed, "kept": kept, "entry": entry,
215            "warnings": warn, "upload_bytes": up}
216
217
218def entry_family(s: dict, a) -> str:
219    """The family the feed entry carries: the GGUF architecture, and for a model of its own shape (case B) `qwen4exp_<shape>`, which makes a Control fetch that shape's engine
220    (strata_control/shape_engine.py) and makes an older Control, which does not know the family, leave the model out."""
221    arch = s.get("architecture")
222    shape = getattr(a, "shape", None)
223    if shape and arch == "qwen4exp":
224        from strata_control import shape_engine
225        return shape_engine.family_of(shape)
226    return arch
227
228
229def model_entry(s: dict, a) -> dict:
230    d = s.get("draft_catalog_entry", {})
231    g = s.get("general", {})
232    geo = s.get("geometry") or {}
233    ctx = (geo.get("keys") or {}).get("context_length")
234    return {
235        "_status": "DRAFT: made from the intake report by packaging/make_model_release.py; field names follow the Q4-PREP-B brief and are to be checked against strata_control/feed.py",
236        "id": a.id, "title": a.title or g.get("name") or d.get("title"), "by": d.get("by"),
237        "licence": {"name": g.get("license"), "url": g.get("license.link") or "[FILL: licence URL]"},
238        "family": entry_family(s, a), "hf": {"repo": a.hf_repo or "[FILL: repository]", "revision": a.revision or "[FILL: pinned commit]"},
239        "files": [{"name": f["name"], "size": f["size"], "sha256": f.get("sha256")} for f in s["files"]],
240        "mmproj": ({"name": s["projectors"][0]["file"], "size": s["projectors"][0]["size"]} if s.get("projectors") else None),
241        "drafter": "mtp" if s.get("mtp", {}).get("in_file") else "none",
242        "default_context": a.default_context if a.default_context else "[FILL: default context]", "context_trained": ctx,
243        "setup": d.get("models", {}),
244        "min_engine": a.min_engine or a.engine_version or "[FILL: minimum engine version]",
245        "pictures": bool(s.get("projectors") and all(p["supported"] for p in s["projectors"])),
246    }
247
248
249def feed_entry(s: dict, a) -> dict:
250    """The model's entry in the feed's `models` member, in the schema strata_control/feed.py reads (packaging/UPDATES.md). Every value the report cannot know
251    (about, licence, licence_url, ram_gb, quant name) is a "[FILL: ...]" text, which `feed_tool.py build-feed --models` refuses: it is filled by hand, then built."""
252    g = s.get("general", {})
253    d = s.get("draft_catalog_entry", {})
254    files = []
255    for f in s["files"]:
256        item = {"name": f["name"].rsplit("/", 1)[-1], "size": f["size"], "sha256": f.get("sha256") or "[FILL: sha256]"}
257        if "/" in f["name"]:
258            item["path"] = f["name"]
259        files.append(item)
260    first = s["files"][0]["name"]
261    quant = a.quant or a.hf_dir or (first.rsplit("/", 1)[0] if "/" in first else "[FILL: quant name]")
262    e = {"id": a.id, "title": a.title or g.get("name") or d.get("title") or a.id, "by": a.by or d.get("by") or "[FILL: who made the model]",
263         "about": a.about or "[FILL: one plain sentence]",
264         "licence": a.licence or g.get("license") or "[FILL: licence]",
265         "licence_url": a.licence_url or g.get("license.link") or "[FILL: https licence url]",
266         "family": entry_family(s, a), "repo": a.hf_repo or "[FILL: repository]", "revision": a.revision or "[FILL: pinned commit, 40 hex]",
267         "quants": [{"name": quant, "about": a.quant_about or "[FILL: one plain line]", "ram_gb": a.ram_gb if a.ram_gb else "[FILL: ram_gb, measured]", "files": files}],
268         "pictures": bool(s.get("projectors") and all(p["supported"] for p in s["projectors"])),
269         "drafter": "mtp" if s.get("mtp", {}).get("in_file") else "none",
270         "context": a.default_context if a.default_context else "[FILL: default context]",
271         "min_engine": a.min_engine or a.engine_version or "[FILL: minimum engine version]"}
272    if s.get("projectors"):
273        pr = s["projectors"][0]
274        e["mmproj"] = {"name": pr["file"], "size": pr["size"], "sha256": pr.get("sha256") or "[FILL: sha256]"}
275    if s.get("architecture") == "qwen35moe":
276        for k in ("kv_bytes_per_token", "state_gb"):
277            if d.get(k) is not None:
278                e[k] = d[k]
279    return e
280
281
282def builtin_sizes() -> set | None:
283    """The built-in size names (setup.py MODELS), which a feed size may not take: None when setup.py cannot be read here."""
284    import contextlib
285    import io
286    sys.path.insert(0, str(ROOT))
287    try:
288        with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
289            import setup as setup_mod
290        return set(setup_mod.MODELS)
291    except (Exception, SystemExit):                       # noqa: BLE001 - the launch line then names both possible spellings
292        return None
293
294
295def launch_lines(entry: dict, sizes: set | None) -> list[str]:
296    """The `strata launch` lines for each size of the feed entry, with the size name a person types: the quant's name, or <quant>-<id> when that
297    name is a built-in size (strata_control/feed_models.py _flash_next takes the same decision)."""
298    out = []
299    mid = entry.get("id")
300    for q in entry.get("quants") or []:
301        name = str(q.get("name"))
302        if sizes is None:
303            keys = [name, "%s-%s" % (name, mid)]
304        else:
305            keys = ["%s-%s" % (name, mid) if name in sizes else name]
306        for key in keys:
307            out.append("strata launch --family %s --model %s" % (mid, key.lower()))
308            out.append("strata launch --family %s --model %s --model-path <the folder with the files>   # files already on the computer (an Intel Arc card: always)" % (mid, key.lower()))
309    if sizes is None:
310        out.append("# setup.py could not be read here: the size is the first spelling unless its quant name is a built-in size")
311    return out
312
313
314def render_md(p: dict, a) -> str:
315    out = ["# Model release plan: %s (case %s)" % (p["id"], p["case"]), "",
316           "DRY RUN. Nothing was built, signed, uploaded or published. The set: `%s`." % p["set"], ""]
317    for w in p["warnings"]:
318        out.append("- WARNING: " + w)
319    out.append("")
320    for st in p["steps"]:
321        out.append("## Step %s: %s%s" % (st["id"], st["what"], "   [OWNER]" if st["owner_only"] else ""))
322        out.append("Where: %s. Time: %s." % (st["where"], ("about %d min" % st["minutes"]) if st["minutes"] else "the upload time below"))
323        if st.get("note"):
324            out.append("Note: " + st["note"])
325        out.append("")
326        out += ["    " + c for c in st["commands"]]
327        if st["outputs"]:
328            out.append("")
329            out += ["- " + o for o in st["outputs"]]
330        out.append("")
331    out.append("## Files in the upload folder")
332    out.append("")
333    out.append("| file | size | why |")
334    out.append("|---|---:|---|")
335    for c in p["changed"]:
336        out.append("| %s | %s%s | %s |" % (c["name"], gib(c["size"]) if c["size"] else "small", " (est.)" if c.get("est") and c["size"] else "", c["why"]))
337    out.append("")
338    out.append("Kept from the previous release (same files, not uploaded again): %d files, %s." % (len(p["kept"]), gib(sum(k["size"] or 0 for k in p["kept"]))))
339    out.append("")
340    out.append("New to upload: %s in %d files; %s." % (gib(p["upload_bytes"]), len(p["changed"]), upload_minutes(p["upload_bytes"])))
341    if p.get("launch"):
342        out.append("")
343        out.append("## How a person starts it (the size name as the Terminal takes it)")
344        out.append("")
345        out += ["    " + line for line in p["launch"]]
346    return "\n".join(out) + "\n"
347
348
349def fill(template: str, values: dict) -> str:
350    return re.sub(r"\{\{(\w+)\}\}", lambda m: str(values.get(m.group(1), m.group(0))), template)
351
352
353def template_values(s: dict, p: dict, a) -> dict:
354    g = s.get("general", {})
355    rows = "\n".join("| %s | %s | %s |" % (f["name"], ("%.1f GB" % (f["size"] / 1e9)), (f.get("sha256") or "[FILL: sha256]")[:16] + ("..." if f.get("sha256") else ""))
356                     for f in s["files"])
357    return {"model_title": a.title or g.get("name") or s["files"][0]["name"], "app_version": a.app_version, "engine_version": a.engine_version or "[FILL: engine version]",
358            "sequence": a.sequence, "case": p["case"], "file_rows": rows, "total_gb": "%.1f" % (s["size_bytes"] / 1e9),
359            "n_files": len(s["files"]), "licence": g.get("license") or "[FILL: licence]", "licence_url": g.get("license.link") or "[FILL: licence URL]",
360            "family": s.get("architecture"), "repo": a.hf_repo or "[FILL: repository]", "revision": a.revision or "[FILL: pinned commit]",
361            "drafter": "MTP (in the file)" if s.get("mtp", {}).get("in_file") else "none", "id": a.id,
362            "pictures": "yes" if p["entry"]["pictures"] else "no", "tool_calls": s.get("chat_template", {}).get("tool_call_format", "[FILL]")}
363
364
365def main(argv=None) -> int:
366    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
367    ap.add_argument("--intake", type=Path, required=True, help="the JSON report of tools/qwen4_intake.py")
368    ap.add_argument("--set", type=int, default=0, help="which set of the report (default 0)")
369    ap.add_argument("--id", required=True, help="the model's id in the feed")
370    ap.add_argument("--app-version", required=True)
371    ap.add_argument("--engine-version", help="case B: the version of the new shape engine")
372    ap.add_argument("--shape", help="case B: the name of the geometry the engines are compiled for (q4_lite): the engine ships as its own component strata-q4-<shape> and the model's family is qwen4exp_<shape>")
373    ap.add_argument("--min-engine", help="the minimum engine version for the model (case A: the engine that runs it)")
374    ap.add_argument("--sequence", type=int, required=True, help="the next feed sequence")
375    ap.add_argument("--prev-upload", type=Path, help="the previous release's upload folder (names and sizes)")
376    ap.add_argument("--case", choices=["A", "B"], help="override the report's verdict")
377    ap.add_argument("--revision", help="the pinned Hugging Face commit")
378    ap.add_argument("--hf-repo")
379    ap.add_argument("--hf-dir")
380    ap.add_argument("--default-context", type=int)
381    ap.add_argument("--title", help="the model's title in the feed entry and the notes (default: the file's general.name, e.g. 'Qwen3.8-Flash-Next GSQ-RCO')")
382    ap.add_argument("--by", help="the feed entry's `by` (who made the model)")
383    ap.add_argument("--about", help="the feed entry's one plain sentence")
384    ap.add_argument("--licence", help="the licence name (default: the file's general.license)")
385    ap.add_argument("--licence-url", help="the https address of the licence (default: general.license.link)")
386    ap.add_argument("--quant", help="the quant's name in the entry (default: --hf-dir, or the folder of the files)")
387    ap.add_argument("--quant-about", help="one plain line about the quant")
388    ap.add_argument("--ram-gb", type=float, help="the RAM the quant needs, measured (the intake's estimate is not used)")
389    ap.add_argument("--no-app", action="store_true", help="case B: no app change in this release (case A has none unless --with-app)")
390    ap.add_argument("--with-app", action="store_true", help="plan the app steps (Models page text, installers) too; a case-A feed model needs none")
391    ap.add_argument("--templates", type=Path, default=TEMPLATES,
392                    help="the folder with the templates: RELEASE-NOTES.md, MODEL-CARD.md and, if there, CHECKLIST.md (default: packaging/templates/model-release)")
393    ap.add_argument("--checklist", type=Path, help="the release checklist template by path (an internal work list, not in the repo); filled as CHECKLIST.md beside the "
394                                                    "notes and the model card, and used instead of a CHECKLIST.md in --templates")
395    ap.add_argument("--write", type=Path, metavar="OUTDIR", help="also write the plan, the entry and the filled templates into this new folder")
396    ap.add_argument("--json", action="store_true", help="print the plan as JSON")
397    ap.add_argument("--execute", action="store_true")
398    a = ap.parse_args(argv)
399    if a.execute:
400        print("REFUSED: make_model_release.py is a dry run. It signs, builds and uploads nothing; the steps that need the release key are printed for the owner.")
401        return 2
402    if a.checklist is not None and not a.checklist.is_file():
403        raise SystemExit("--checklist: no file %s" % a.checklist)
404    report = json.loads(a.intake.read_text(encoding="utf-8"))
405    if not 0 <= a.set < len(report["sets"]):
406        raise SystemExit("the report has %d set(s)" % len(report["sets"]))
407    s = report["sets"][a.set]
408    case = a.case or s.get("verdict", {}).get("case")
409    if case == "B" and not a.engine_version:
410        raise SystemExit("case B builds the engine of the new shape: give --engine-version")
411    if case == "B":
412        from strata_control import shape_engine
413        if not a.shape or not shape_engine.valid(a.shape):
414            raise SystemExit("case B: give --shape, the name of the geometry the engines are compiled for (like q4_lite: lower case, digits and _); that engine ships as its own component")
415    elif a.shape:
416        raise SystemExit("--shape is for case B (a model of a new shape); case A runs on the engines as they are")
417    if case == "A" and a.write and not a.min_engine:
418        raise SystemExit("case A: give --min-engine, the first engine version that runs the model (the entry needs it, and build-feed refuses an entry that still says [FILL])")
419    prev = scan_upload(a.prev_upload)
420    if a.prev_upload is None:
421        print("note: no --prev-upload, so sizes of the files that stay or get rebuilt are unknown", file=sys.stderr)
422    p = plan(report, a.set, a, prev)
423    p["launch"] = launch_lines(feed_entry(s, a), builtin_sizes())
424    if a.json:
425        print(json.dumps(p, indent=1))
426    else:
427        print(render_md(p, a))
428    if a.write:
429        if a.write.exists() and any(a.write.iterdir()):
430            raise SystemExit("--write needs a new or empty folder: %s" % a.write)
431        (a.write / "models").mkdir(parents=True, exist_ok=True)
432        (a.write / "PLAN.md").write_text(render_md(p, a), encoding="utf-8")
433        (a.write / "plan.json").write_text(json.dumps(p, indent=1), encoding="utf-8")
434        (a.write / "models" / ("%s.model.json" % a.id)).write_text(json.dumps(p["entry"], indent=1), encoding="utf-8")
435        (a.write / "models" / ("%s.entry.json" % a.id)).write_text(json.dumps(feed_entry(s, a), indent=1) + "\n", encoding="utf-8")
436        vals = template_values(s, p, a)
437        for name in TEMPLATE_NAMES:
438            t = a.templates / name if a.templates else None
439            if name == "CHECKLIST.md" and a.checklist is not None:
440                t = a.checklist
441            if t is not None and t.is_file():
442                (a.write / name).write_text(fill(t.read_text(encoding="utf-8"), vals), encoding="utf-8")
443            else:
444                print("note: no template %s in %s (give --templates)" % (name, a.templates), file=sys.stderr)
445        print("written to %s" % a.write, file=sys.stderr)
446    return 0
447
448
449if __name__ == "__main__":
450    raise SystemExit(main())