okami.mom/strata

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

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

main
21.0 KiB361 linesraw
1#!/usr/bin/env python3
2"""Make a local, unpublished engine package for the component folder (strata_control/engine_component.py).
3
4    python packaging/package_engine.py --src <folder with strata[.exe] and its libraries> --backend cuda \
5        --version 0.1.45 --out <components>/engine --arch sm_86 --arch compute_89 \
6        --min-driver nvidia=580.65 [--build-id <id>] [--platform linux-x86_64] [--tree] [--include GLOB ...]
7
8    python packaging/package_engine.py --verify <components>/engine/<package folder>     # full hash check, exit 0 / 1
9
10The result is one folder `<out>/<version>-<platform>-<backend>/` holding the engine binary, the libraries it loads,
11BUILD.json when the source has one, and `engine-component.json` (schema 2: every file's SHA-256 and size, the arch
12list, the oldest driver, the engine build id, and an empty `signature` for S6). It is the thing Control resolves,
13checks and starts; it is not signed, not published, and nothing here uploads it. Signing is stream S6
14(`engine_component.register_signature_verifier`); `--sign-with` is deliberately absent until then.
15
16Files taken from --src, by default: the entrypoint, every `*.dll` / `*.so` / `*.so.*` / `*.dylib` / `*.metallib`
17beside it, `BUILD.json`, `LICENSE*`, the picture reader `strata-vision[.exe]` when the build has one (without it the
18engine answers text only: setup.py Control mode keeps the person's picture choice only when it is there). `--include GLOB` (repeatable, relative to --src, `**` allowed) adds more, for
19example `strata-vision.exe`, `strata-device.exe` or `rocm/**`. `--tree` takes every regular file under --src (the HIP
20package ships a `rocm/` tree of kernels). Symlinks are never followed or copied.
21"""
22
23from __future__ import annotations
24
25import argparse
26import fnmatch
27import hashlib
28import json
29import os
30import re
31import shutil
32import subprocess
33import sys
34from pathlib import Path
35
36ROOT = Path(__file__).resolve().parents[1]
37sys.path.insert(0, str(ROOT))
38
39sys.path.insert(0, str(Path(__file__).resolve().parent))
40
41import binary_deps  # noqa: E402
42from strata_control import engine_component as ec, shape_engine  # noqa: E402
43from strata_control.components import BACKEND_MATRIX, host_platform  # noqa: E402
44
45
46
47
48def sha256(path: Path) -> str:
49    digest = hashlib.sha256()
50    with path.open("rb") as stream:
51        for block in iter(lambda: stream.read(1 << 20), b""):
52            digest.update(block)
53    return digest.hexdigest()
54
55
56def wanted(path: Path) -> bool:
57    name = path.name.lower()
58    return (name.endswith((".dll", ".so", ".dylib", ".metallib")) or ".so." in name or name == "build.json"
59            or name.startswith("license") or name in ("strata-vision", "strata-vision.exe", "strata-vision-hip", "strata-vision-hip.exe"))   # the picture readers (CPU, AMD GPU) beside the engine
60
61
62READER_NAMES = ("strata-vision", "strata-vision.exe")
63
64
65def _arch_numbers(value) -> set[int]:
66    """The CUDA architectures in a BUILD.json `archs` / `vision_archs` value ("60;61;70", [60, "sm_61", "70-real"], ...), as numbers."""
67    if isinstance(value, str):
68        value = re.split(r"[;,\s]+", value)
69    found: set[int] = set()
70    for item in value or []:
71        m = re.fullmatch(r"(?:sm_|compute_)?(\d+)(?:a|f)?(?:-real|-virtual)?", str(item).strip().lower())
72        if m:
73            found.add(int(m.group(1)))
74    return found
75
76
77def check_picture_reader(src: Path, backend: str, target: str, archs: tuple[str, ...], *, variant: str = "",
78                         allow_stale: bool = False, allow_none: bool = False) -> list[str]:
79    """The picture reader of a package must run on every card and Mac the package does (tools tests: I1, I2, #3669, #3697).
80
81    * CUDA package with a reader: BUILD.json (beside the engine) must list `vision_archs`, and every `sm_NN` the package carries
82      code for must be there. A reader reused from an older build (the Windows zips' strata-vision.exe, unchanged since 0.1.44, had no
83      sm_60) stops with "device kernel image is invalid" on a Pascal card while the engine runs. Refused, unless allow_stale.
84    * macOS package without a reader: refused (a Mac with this package cannot read a picture), unless allow_none.
85    * CUDA package without a reader: allowed (text-only), reported in the returned notes so the build log says it.
86    Returns notes to print."""
87    reader = next((n for n in READER_NAMES if (src / n).is_file()), None)
88    notes: list[str] = []
89    if target.startswith("macos"):
90        if reader is None and not allow_none:
91            raise SystemExit("refusing to package the macOS engine without its picture reader: a Mac with this package could not read "
92                             "a picture (#3697). Build it with packaging/build_vision_mac.sh and copy strata-vision beside strata "
93                             "(or give --no-picture-reader to ship a text-only package on purpose).")
94        if reader is None:
95            notes.append("no picture reader in this macOS package: pictures are off for it")
96        return notes
97    if backend != "cuda":
98        return notes
99    if reader is None:
100        notes.append("no picture reader in this CUDA package: the engine answers text only (the app says pictures need the reader)")
101        return notes
102    needed = {n for n in _arch_numbers([a for a in archs if str(a).lower().startswith("sm_")])}
103    have: set[int] = set()
104    build_json = src / "BUILD.json"
105    try:
106        have = _arch_numbers(json.loads(build_json.read_text(encoding="utf-8-sig")).get("vision_archs"))
107    except (OSError, ValueError, AttributeError):
108        pass
109    missing = sorted(needed - have)
110    if missing and not allow_stale:
111        what = ("BUILD.json has no vision_archs: the reader's build is not recorded" if not have
112                else "the reader has no code for " + ", ".join(f"sm_{n}" for n in missing))
113        raise SystemExit(f"refusing to package the {variant or backend} engine with this picture reader: {what}. A reader reused from an "
114                         "older build stops with 'device kernel image is invalid' on a card it was not built for (#3669). Build it for the "
115                         "package's architectures (packaging/build_vision_windows.bat, packaging/build_cuda_linux.sh) and record them as "
116                         "vision_archs in BUILD.json (or give --allow-stale-vision).")
117    if missing:
118        notes.append("picture reader NOT built for " + ", ".join(f"sm_{n}" for n in missing) + " (allowed by --allow-stale-vision)")
119    return notes
120
121
122def stamp_vision_archs(stage: Path, archs: str) -> None:
123    """Record the architectures the picture reader in `stage` was built for as BUILD.json `vision_archs` (the build recipes for Windows
124    call this after building strata-vision.exe; check_picture_reader compares it with the package's archs)."""
125    path = stage / "BUILD.json"
126    try:
127        data = json.loads(path.read_text(encoding="utf-8-sig")) if path.is_file() else {}
128    except (OSError, ValueError):
129        data = {}
130    data["vision_archs"] = ";".join(str(n) for n in sorted(_arch_numbers(archs)))
131    path.write_text(json.dumps(data, indent=1) + chr(10), encoding="utf-8")
132
133
134def git_build_id(repo: Path = ROOT) -> str:
135    """The source commit of the engine build, `-dirty` when the tree had changes. `unknown` outside a checkout."""
136    try:
137        head = subprocess.run(["git", "-C", str(repo), "rev-parse", "--short=12", "HEAD"], capture_output=True,
138                              text=True, timeout=20).stdout.strip()
139        dirty = subprocess.run(["git", "-C", str(repo), "status", "--porcelain", "--untracked-files=no"],
140                               capture_output=True, text=True, timeout=60).stdout.strip()
141    except (OSError, subprocess.SubprocessError):
142        return "unknown"
143    return (head + ("-dirty" if dirty else "")) if head else "unknown"
144
145
146def select(src: Path, entrypoint: str, *, tree: bool, include: list[str]) -> list[str]:
147    """Relative POSIX paths to package, entrypoint first, the rest sorted."""
148    chosen: set[str] = set()
149    for path in sorted(src.rglob("*") if (tree or include) else src.iterdir()):
150        if path.is_symlink() or not path.is_file():
151            continue
152        rel = path.relative_to(src).as_posix()
153        if rel == ec.MANIFEST:
154            continue
155        top_level = "/" not in rel
156        if tree or (top_level and wanted(path)) or any(fnmatch.fnmatch(rel, pattern) for pattern in include):
157            chosen.add(rel)
158    for path in sorted((src / "tuning").glob("*.txt")) if (src / "tuning").is_dir() else []:
159        if path.is_file() and not path.is_symlink():      # the hipBLASLt tuning tables of an AMD package (strata_control/hipblaslt_tuning.py)
160            chosen.add(path.relative_to(src).as_posix())
161    chosen.discard(entrypoint)
162    return [entrypoint] + sorted(chosen)
163
164
165def build(src: Path, backend: str, version: str, target: str, out: Path, *, entry: str | None = None,
166          archs: tuple[str, ...] = (), min_driver: dict | None = None, build_id: str | None = None,
167          min_runtime: str | None = None, notes: str = "", tree: bool = False, include: list[str] | None = None,
168          variant: str = "", search: list[Path] | None = None, allow_libs: list[str] | None = None,
169          check_reader: bool = False, allow_stale_vision: bool = False, allow_no_reader: bool = False,
170          shape: str = "") -> Path:
171    if shape:
172        if not shape_engine.valid(shape):
173            raise SystemExit(f"--shape {shape!r} is not a model shape name (the compiled geometry's name, like q4_lite: lower case, digits and _)")
174    if backend not in BACKEND_MATRIX:
175        raise SystemExit(f"unknown backend {backend!r}")
176    if backend != "cpu" and not archs:
177        raise SystemExit(f"a {backend} package needs at least one --arch (sm_86, gfx1201, ...)")
178    if backend == "cuda" and variant == "cuda12" and not any(a in ("sm_60", "sm_61", "sm_70") for a in archs):
179        # #3503: the cuda12 package is what the feed and docs/DOCKER.md offer to GTX 10 / P100 / V100; one built for
180        # sm_75 and up starts a restart loop on those cards ("this PC's GPU is sm_60")
181        raise SystemExit("refusing to package the cuda12 engine without sm_60, sm_61 or sm_70: it is the Pascal and Volta build "
182                         "(CUDA 12.9, -DSTRATA_EXPERIMENTAL_SM60=ON, --arch sm_60 --arch sm_61 --arch sm_70 ...; see packaging/build_cuda_linux.sh)")
183    if backend == "hip":
184        from strata_control import hipblaslt_tuning
185        problems = hipblaslt_tuning.check_stage(src, archs)
186        if problems:
187            raise SystemExit("refusing to package the AMD engine:\n  " + "\n  ".join(problems))
188    entrypoint = entry or ("strata.exe" if target.startswith("windows") else "strata")
189    if not (src / entrypoint).is_file():
190        raise SystemExit(f"{src / entrypoint} does not exist")
191    if check_reader:                       # the release recipes and the CLI ask for it; the library call keeps its old behaviour
192        for note in check_picture_reader(src, backend, target, archs, variant=variant, allow_stale=allow_stale_vision,
193                                         allow_none=allow_no_reader):
194            print("note: " + note)
195    folder = out / (f"{version}-{target}-{backend}" + (f"-{variant}" if variant else ""))
196    if folder.exists():
197        raise SystemExit(f"{folder} already exists; remove it first (packages are immutable)")
198    staging = out / f".{folder.name}.partial"
199    if staging.exists():
200        shutil.rmtree(staging)
201    staging.mkdir(parents=True)
202    try:
203        files = []
204        for rel in select(src, entrypoint, tree=tree, include=include or []):
205            destination = staging / rel
206            destination.parent.mkdir(parents=True, exist_ok=True)
207            shutil.copy2(src / rel, destination)
208            files.append({"path": rel, "sha256": sha256(destination), "bytes": destination.stat().st_size})
209        files += _bundle_missing_libraries(staging, target, [f["path"] for f in files], search or [], allow_libs or [])
210        component_id = shape_engine.component_id(shape) if shape else ec.COMPONENT_ID     # the engine of a model shape is its own component (strata_control/shape_engine.py)
211        manifest = {"schema_version": ec.SCHEMA_VERSION, "id": component_id, "name": component_id,
212                    "version": version, "platform": target, "backend": backend, "archs": list(archs),
213                    "min_driver": dict(min_driver or {}), "build_id": build_id or git_build_id(),
214                    "entrypoint": entrypoint, "files": files, "signature": None}
215        if shape:
216            manifest["shape"] = shape
217        if variant:
218            manifest["variant"] = variant
219        if min_runtime:
220            manifest["min_runtime"] = min_runtime
221        if notes:
222            manifest["notes"] = notes
223        (staging / ec.MANIFEST).write_text(json.dumps(manifest, indent=1) + "\n", encoding="utf-8")
224        if os.name != "nt":
225            for exe_name in (entrypoint, "strata-vision", "strata-vision-hip"):      # the programs setup starts: executable in the tar
226                if (staging / exe_name).is_file():
227                    (staging / exe_name).chmod(0o755)
228        ec.verify(ec.read_manifest(staging, component_id), full=True)
229        staging.rename(folder)
230    except BaseException:
231        shutil.rmtree(staging, ignore_errors=True)
232        raise
233    return folder
234
235
236def _default_search(target: str) -> list[Path]:
237    """Where a Windows build finds the redistributable DLLs its engine imports: the CUDA/HIP toolkits and PATH."""
238    if not target.startswith("windows"):
239        return []
240    found: list[Path] = []
241    for var in ("CUDA_PATH", "HIP_PATH"):
242        root = os.environ.get(var)
243        if root:
244            found += [Path(root) / "bin" / "x64", Path(root) / "bin"]
245    found += [Path(x) for x in os.environ.get("PATH", "").split(os.pathsep) if x]
246    return [d for d in found if d.is_dir()]
247
248
249def _bundle_missing_libraries(staging: Path, target: str, rels: list[str], search: list[Path], allow: list[str]) -> list[dict]:
250    """Every library the package's binaries import must be in the package, or belong to the OS or the GPU driver
251    (binary_deps.py). Windows builds copy a missing one from the search folders (the CUDA toolkit's bin/x64, PATH): the packager
252    runs on a PC that has the toolkit, the person's PC does not. Anything still missing refuses the package."""
253    added: list[dict] = []
254    roots = search or _default_search(target)
255    for _ in range(8):                                   # a copied DLL can import more DLLs
256        missing = [(f, n) for f, n in binary_deps.uncovered(staging) if n.lower() not in {a.lower() for a in allow}]
257        if not missing:
258            return added
259        progressed = False
260        for _file, name in sorted(set(missing), key=lambda x: x[1].lower()):
261            if not target.startswith("windows"):
262                continue
263            hit = next((d / name for d in roots if (d / name).is_file()), None)
264            if hit is None:
265                hit = next((c for d in roots for c in d.glob("*") if c.name.lower() == name.lower() and c.is_file()), None)
266            if hit is None or (staging / hit.name).exists():
267                continue
268            shutil.copy2(hit, staging / hit.name)
269            added.append({"path": hit.name, "sha256": sha256(staging / hit.name), "bytes": (staging / hit.name).stat().st_size})
270            progressed = True
271            print(f"bundled {hit.name} (imported by the engine; from {hit.parent})")
272        if not progressed:
273            break
274    left = [(f, n) for f, n in binary_deps.uncovered(staging) if n.lower() not in {a.lower() for a in allow}]
275    if left:
276        lines = "\n".join(f"  {f} needs {n}" for f, n in sorted(set(left)))
277        raise SystemExit("refusing to package: these libraries are neither bundled nor part of the OS or the GPU driver, so a clean PC could not "
278                         f"start the engine (0xC0000135 / 'library not found'):\n{lines}\nGive --search <folder holding them> or fix the build.")
279    return added
280
281
282def package_sha256(folder: Path) -> str:
283    """One digest for the whole package: SHA-256 of the manifest file (it holds every file's hash)."""
284    return sha256(folder / ec.MANIFEST)
285
286
287def main(argv: list[str] | None = None) -> int:
288    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
289    ap.add_argument("--verify", type=Path, metavar="FOLDER", help="hash-check an existing package and exit")
290    ap.add_argument("--src", type=Path)
291    ap.add_argument("--backend", choices=sorted(BACKEND_MATRIX))
292    ap.add_argument("--version")
293    ap.add_argument("--platform", default=None, help="default: this machine")
294    ap.add_argument("--out", type=Path, help="the component folder's engine/ directory")
295    ap.add_argument("--entrypoint", default=None)
296    ap.add_argument("--arch", "--cuda-arch", dest="arch", action="append", default=[],
297                    help="sm_86 (code for that card), compute_89 (PTX), gfx1201, ...; repeat for several")
298    ap.add_argument("--min-driver", action="append", default=[], metavar="VENDOR=VERSION",
299                    help="the oldest driver, e.g. nvidia=580.65; repeat for several vendors")
300    ap.add_argument("--variant", default="", help="tag when one backend has several builds (cuda13, cuda12); goes in the folder name")
301    ap.add_argument("--build-id", default=None, help="default: the source commit of this checkout")
302    ap.add_argument("--min-runtime", default=None)
303    ap.add_argument("--notes", default="")
304    ap.add_argument("--tree", action="store_true", help="every regular file under --src, recursively")
305    ap.add_argument("--search", action="append", default=[], type=Path, metavar="DIR",
306                    help="folder to copy a missing imported DLL from (default on Windows: CUDA_PATH/bin/x64, HIP_PATH/bin, PATH)")
307    ap.add_argument("--allow-lib", action="append", default=[], metavar="NAME",
308                    help="an imported library that really is provided by the target system (rare; named so the check passes)")
309    ap.add_argument("--shape", default="", metavar="GEOMETRY",
310                    help="package the engine of a model shape (the name the engine was compiled for, -DSTRATA_GEOMETRY=q4_lite): its own component strata-q4-lite, installed "
311                         "next to the Strata engine and never in place of it (strata_control/shape_engine.py)")
312    ap.add_argument("--include", action="append", default=[], metavar="GLOB", help="more files, relative to --src")
313    ap.add_argument("--stamp-vision", type=Path, metavar="STAGE", help="write --vision-archs into STAGE/BUILD.json and exit")
314    ap.add_argument("--vision-archs", default="", help="with --stamp-vision: the architectures the reader was built for, e.g. '60;61;70;75;80;86;89'")
315    ap.add_argument("--allow-stale-vision", action="store_true",
316                    help="package a CUDA picture reader whose BUILD.json vision_archs do not cover the package's archs (it will fail on those cards)")
317    ap.add_argument("--no-picture-reader", action="store_true", help="ship a macOS package without strata-vision on purpose (pictures stay off)")
318    a = ap.parse_args(argv)
319    if a.verify:
320        try:
321            component = ec.read_manifest_any(a.verify)
322            ec.verify(component, full=True)
323        except ec.ComponentProblem as exc:
324            print(f"{a.verify}: REFUSED: {exc}")
325            return 1
326        bad = binary_deps.uncovered(a.verify)
327        if bad:
328            for rel, name in bad:
329                print(f"{a.verify}: REFUSED: {rel} needs {name}, which is neither bundled nor an OS / GPU driver library")
330            return 1
331        print(f"{a.verify}: ok ({len(component.files)} files, manifest sha256 {package_sha256(a.verify)})")
332        return 0
333    if a.stamp_vision:
334        if not _arch_numbers(a.vision_archs):
335            ap.error("--stamp-vision needs --vision-archs, for example '60;61;70;75;80;86;89'")
336        stamp_vision_archs(a.stamp_vision, a.vision_archs)
337        print(f"{a.stamp_vision / 'BUILD.json'}: vision_archs {a.vision_archs}")
338        return 0
339    for needed in ("src", "backend", "version", "out"):
340        if getattr(a, needed) is None:
341            ap.error(f"--{needed} is required")
342    drivers = {}
343    for item in a.min_driver:
344        vendor, _, version = item.partition("=")
345        if not vendor or not version:
346            ap.error(f"--min-driver {item!r} is not VENDOR=VERSION")
347        drivers[vendor] = version
348    a.out.mkdir(parents=True, exist_ok=True)
349    folder = build(a.src, a.backend, a.version, a.platform or host_platform(), a.out, entry=a.entrypoint,
350                   archs=tuple(a.arch), min_driver=drivers, build_id=a.build_id, min_runtime=a.min_runtime,
351                   notes=a.notes, tree=a.tree, include=a.include, variant=a.variant,
352                   search=a.search, allow_libs=a.allow_lib, check_reader=True, allow_stale_vision=a.allow_stale_vision,
353                   allow_no_reader=a.no_picture_reader, shape=a.shape)
354    entries = [p for p in folder.rglob("*") if p.is_file()]
355    total = sum(p.stat().st_size for p in entries)
356    print(f"{folder}  ({total / (1 << 20):.1f} MiB, {len(entries)} files, manifest sha256 {package_sha256(folder)})")
357    return 0
358
359
360if __name__ == "__main__":
361    raise SystemExit(main())