okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1#!/usr/bin/env python3 2"""Make a local, unpublished engine package for the component folder (strata_control/engine_component.py). 3 4python 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 8python 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 : 49digest = hashlib .sha256 () 50with path .open ("rb" )as stream : 51for block in iter (lambda :stream .read (1 << 20 ),b"" ): 52digest .update (block ) 53return digest .hexdigest () 54 55 56def wanted (path :Path )-> bool : 57name = path .name .lower () 58return (name .endswith ((".dll" ,".so" ,".dylib" ,".metallib" ))or ".so." in name or name == "build.json" 59or 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.""" 67if isinstance (value ,str ): 68value = re .split (r"[;,\s]+" ,value ) 69found :set [int ]= set () 70for item in value or []: 71m = re .fullmatch (r"(?:sm_|compute_)?(\d+)(?:a|f)?(?:-real|-virtual)?" ,str (item ).strip ().lower ()) 72if m : 73found .add (int (m .group (1 ))) 74return found 75 76 77def check_picture_reader (src :Path ,backend :str ,target :str ,archs :tuple [str , ...],* ,variant :str = "" , 78allow_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 82code for must be there. A reader reused from an older build (the Windows zips' strata-vision.exe, unchanged since 0.1.44, had no 83sm_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. 86Returns notes to print.""" 87reader = next ((n for n in READER_NAMES if (src / n ).is_file ()),None ) 88notes :list [str ]= [] 89if target .startswith ("macos" ): 90if reader is None and not allow_none : 91raise 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)." ) 94if reader is None : 95notes .append ("no picture reader in this macOS package: pictures are off for it" ) 96return notes 97if backend != "cuda" : 98return notes 99if reader is None : 100notes .append ("no picture reader in this CUDA package: the engine answers text only (the app says pictures need the reader)" ) 101return notes 102needed = {n for n in _arch_numbers ([a for a in archs if str (a ).lower ().startswith ("sm_" )])} 103have :set [int ]= set () 104build_json = src / "BUILD.json" 105try : 106have = _arch_numbers (json .loads (build_json .read_text (encoding = "utf-8-sig" )).get ("vision_archs" )) 107except (OSError ,ValueError ,AttributeError ): 108pass 109missing = sorted (needed - have ) 110if missing and not allow_stale : 111what = ("BUILD.json has no vision_archs: the reader's build is not recorded" if not have 112else "the reader has no code for " + ", " .join (f"sm_ { n } " for n in missing )) 113raise 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)." ) 117if missing : 118notes .append ("picture reader NOT built for " + ", " .join (f"sm_ { n } " for n in missing )+ " (allowed by --allow-stale-vision)" ) 119return 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 124call this after building strata-vision.exe; check_picture_reader compares it with the package's archs).""" 125path = stage / "BUILD.json" 126try : 127data = json .loads (path .read_text (encoding = "utf-8-sig" ))if path .is_file ()else {} 128except (OSError ,ValueError ): 129data = {} 130data ["vision_archs" ]= ";" .join (str (n )for n in sorted (_arch_numbers (archs ))) 131path .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.""" 136try : 137head = subprocess .run (["git" ,"-C" ,str (repo ),"rev-parse" ,"--short=12" ,"HEAD" ],capture_output = True , 138text = True ,timeout = 20 ).stdout .strip () 139dirty = subprocess .run (["git" ,"-C" ,str (repo ),"status" ,"--porcelain" ,"--untracked-files=no" ], 140capture_output = True ,text = True ,timeout = 60 ).stdout .strip () 141except (OSError ,subprocess .SubprocessError ): 142return "unknown" 143return (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.""" 148chosen :set [str ]= set () 149for path in sorted (src .rglob ("*" )if (tree or include )else src .iterdir ()): 150if path .is_symlink ()or not path .is_file (): 151continue 152rel = path .relative_to (src ).as_posix () 153if rel == ec .MANIFEST : 154continue 155top_level = "/" not in rel 156if tree or (top_level and wanted (path ))or any (fnmatch .fnmatch (rel ,pattern )for pattern in include ): 157chosen .add (rel ) 158for path in sorted ((src / "tuning" ).glob ("*.txt" ))if (src / "tuning" ).is_dir ()else []: 159if path .is_file ()and not path .is_symlink ():# the hipBLASLt tuning tables of an AMD package (strata_control/hipblaslt_tuning.py) 160chosen .add (path .relative_to (src ).as_posix ()) 161chosen .discard (entrypoint ) 162return [entrypoint ]+ sorted (chosen ) 163 164 165def build (src :Path ,backend :str ,version :str ,target :str ,out :Path ,* ,entry :str | None = None , 166archs :tuple [str , ...]= (),min_driver :dict | None = None ,build_id :str | None = None , 167min_runtime :str | None = None ,notes :str = "" ,tree :bool = False ,include :list [str ]| None = None , 168variant :str = "" ,search :list [Path ]| None = None ,allow_libs :list [str ]| None = None , 169check_reader :bool = False ,allow_stale_vision :bool = False ,allow_no_reader :bool = False , 170shape :str = "" )-> Path : 171if shape : 172if not shape_engine .valid (shape ): 173raise SystemExit (f"--shape { shape !r } is not a model shape name (the compiled geometry's name, like q4_lite: lower case, digits and _)" ) 174if backend not in BACKEND_MATRIX : 175raise SystemExit (f"unknown backend { backend !r } " ) 176if backend != "cpu" and not archs : 177raise SystemExit (f"a { backend } package needs at least one --arch (sm_86, gfx1201, ...)" ) 178if 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") 181raise 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)" ) 183if backend == "hip" : 184from strata_control import hipblaslt_tuning 185problems = hipblaslt_tuning .check_stage (src ,archs ) 186if problems : 187raise SystemExit ("refusing to package the AMD engine:\n " + "\n " .join (problems )) 188entrypoint = entry or ("strata.exe" if target .startswith ("windows" )else "strata" ) 189if not (src / entrypoint ).is_file (): 190raise SystemExit (f" { src / entrypoint } does not exist" ) 191if check_reader :# the release recipes and the CLI ask for it; the library call keeps its old behaviour 192for note in check_picture_reader (src ,backend ,target ,archs ,variant = variant ,allow_stale = allow_stale_vision , 193allow_none = allow_no_reader ): 194"note: " + note ) 195folder = out / (f" { version } - { target } - { backend } " + (f"- { variant } " if variant else "" )) 196if folder .exists (): 197raise SystemExit (f" { folder } already exists; remove it first (packages are immutable)" ) 198staging = out / f". { folder . name } .partial" 199if staging .exists (): 200shutil .rmtree (staging ) 201staging .mkdir (parents = True ) 202try : 203files = [] 204for rel in select (src ,entrypoint ,tree = tree ,include = include or []): 205destination = staging / rel 206destination .parent .mkdir (parents = True ,exist_ok = True ) 207shutil .copy2 (src / rel ,destination ) 208files .append ({"path" :rel ,"sha256" :sha256 (destination ),"bytes" :destination .stat ().st_size }) 209files += _bundle_missing_libraries (staging ,target , [f ["path" ]for f in files ],search or [],allow_libs or []) 210component_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) 211manifest = {"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 } 215if shape : 216manifest ["shape" ]= shape 217if variant : 218manifest ["variant" ]= variant 219if min_runtime : 220manifest ["min_runtime" ]= min_runtime 221if notes : 222manifest ["notes" ]= notes 223 (staging / ec .MANIFEST ).write_text (json .dumps (manifest ,indent = 1 )+ "\n" ,encoding = "utf-8" ) 224if os .name != "nt" : 225for exe_name in (entrypoint ,"strata-vision" ,"strata-vision-hip" ):# the programs setup starts: executable in the tar 226if (staging / exe_name ).is_file (): 227 (staging / exe_name ).chmod (0o755 ) 228ec .verify (ec .read_manifest (staging ,component_id ),full = True ) 229staging .rename (folder ) 230except BaseException : 231shutil .rmtree (staging ,ignore_errors = True ) 232raise 233return 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.""" 238if not target .startswith ("windows" ): 239return [] 240found :list [Path ]= [] 241for var in ("CUDA_PATH" ,"HIP_PATH" ): 242root = os .environ .get (var ) 243if root : 244found += [Path (root )/ "bin" / "x64" ,Path (root )/ "bin" ] 245found += [Path (x )for x in os .environ .get ("PATH" ,"" ).split (os .pathsep )if x ] 246return [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 252runs on a PC that has the toolkit, the person's PC does not. Anything still missing refuses the package.""" 253added :list [dict ]= [] 254roots = search or _default_search (target ) 255for _ in range (8 ):# a copied DLL can import more DLLs 256missing = [(f ,n )for f ,n in binary_deps .uncovered (staging )if n .lower ()not in {a .lower ()for a in allow }] 257if not missing : 258return added 259progressed = False 260for _file ,name in sorted (set (missing ),key = lambda x :x [1 ].lower ()): 261if not target .startswith ("windows" ): 262continue 263hit = next ((d / name for d in roots if (d / name ).is_file ()),None ) 264if hit is None : 265hit = next ((c for d in roots for c in d .glob ("*" )if c .name .lower ()== name .lower ()and c .is_file ()),None ) 266if hit is None or (staging / hit .name ).exists (): 267continue 268shutil .copy2 (hit ,staging / hit .name ) 269added .append ({"path" :hit .name ,"sha256" :sha256 (staging / hit .name ),"bytes" : (staging / hit .name ).stat ().st_size }) 270progressed = True 271f"bundled { hit . name } (imported by the engine; from { hit . parent } )" ) 272if not progressed : 273break 274left = [(f ,n )for f ,n in binary_deps .uncovered (staging )if n .lower ()not in {a .lower ()for a in allow }] 275if left : 276lines = "\n" .join (f" { f } needs { n } " for f ,n in sorted (set (left ))) 277raise SystemExit ("refusing to package: these libraries are neither bundled nor part of the OS or the GPU driver, so a clean PC could not " 278f"start the engine (0xC0000135 / 'library not found'):\n { lines } \nGive --search <folder holding them> or fix the build." ) 279return 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).""" 284return sha256 (folder / ec .MANIFEST ) 285 286 287def main (argv :list [str ]| None = None )-> int : 288ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 289ap .add_argument ("--verify" ,type = Path ,metavar = "FOLDER" ,help = "hash-check an existing package and exit" ) 290ap .add_argument ("--src" ,type = Path ) 291ap .add_argument ("--backend" ,choices = sorted (BACKEND_MATRIX )) 292ap .add_argument ("--version" ) 293ap .add_argument ("--platform" ,default = None ,help = "default: this machine" ) 294ap .add_argument ("--out" ,type = Path ,help = "the component folder's engine/ directory" ) 295ap .add_argument ("--entrypoint" ,default = None ) 296ap .add_argument ("--arch" ,"--cuda-arch" ,dest = "arch" ,action = "append" ,default = [], 297help = "sm_86 (code for that card), compute_89 (PTX), gfx1201, ...; repeat for several" ) 298ap .add_argument ("--min-driver" ,action = "append" ,default = [],metavar = "VENDOR=VERSION" , 299help = "the oldest driver, e.g. nvidia=580.65; repeat for several vendors" ) 300ap .add_argument ("--variant" ,default = "" ,help = "tag when one backend has several builds (cuda13, cuda12); goes in the folder name" ) 301ap .add_argument ("--build-id" ,default = None ,help = "default: the source commit of this checkout" ) 302ap .add_argument ("--min-runtime" ,default = None ) 303ap .add_argument ("--notes" ,default = "" ) 304ap .add_argument ("--tree" ,action = "store_true" ,help = "every regular file under --src, recursively" ) 305ap .add_argument ("--search" ,action = "append" ,default = [],type = Path ,metavar = "DIR" , 306help = "folder to copy a missing imported DLL from (default on Windows: CUDA_PATH/bin/x64, HIP_PATH/bin, PATH)" ) 307ap .add_argument ("--allow-lib" ,action = "append" ,default = [],metavar = "NAME" , 308help = "an imported library that really is provided by the target system (rare; named so the check passes)" ) 309ap .add_argument ("--shape" ,default = "" ,metavar = "GEOMETRY" , 310help = "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)" ) 312ap .add_argument ("--include" ,action = "append" ,default = [],metavar = "GLOB" ,help = "more files, relative to --src" ) 313ap .add_argument ("--stamp-vision" ,type = Path ,metavar = "STAGE" ,help = "write --vision-archs into STAGE/BUILD.json and exit" ) 314ap .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'" ) 315ap .add_argument ("--allow-stale-vision" ,action = "store_true" , 316help = "package a CUDA picture reader whose BUILD.json vision_archs do not cover the package's archs (it will fail on those cards)" ) 317ap .add_argument ("--no-picture-reader" ,action = "store_true" ,help = "ship a macOS package without strata-vision on purpose (pictures stay off)" ) 318a = ap .parse_args (argv ) 319if a .verify : 320try : 321component = ec .read_manifest_any (a .verify ) 322ec .verify (component ,full = True ) 323except ec .ComponentProblem as exc : 324f" { a . verify } : REFUSED: { exc } " ) 325return 1 326bad = binary_deps .uncovered (a .verify ) 327if bad : 328for rel ,name in bad : 329f" { a . verify } : REFUSED: { rel } needs { name } , which is neither bundled nor an OS / GPU driver library" ) 330return 1 331f" { a . verify } : ok ( { len ( component . files ) } files, manifest sha256 { package_sha256 ( a . verify ) } )" ) 332return 0 333if a .stamp_vision : 334if not _arch_numbers (a .vision_archs ): 335ap .error ("--stamp-vision needs --vision-archs, for example '60;61;70;75;80;86;89'" ) 336stamp_vision_archs (a .stamp_vision ,a .vision_archs ) 337f" { a . stamp_vision / 'BUILD.json' } : vision_archs { a . vision_archs } " ) 338return 0 339for needed in ("src" ,"backend" ,"version" ,"out" ): 340if getattr (a ,needed )is None : 341ap .error (f"-- { needed } is required" ) 342drivers = {} 343for item in a .min_driver : 344vendor ,_ ,version = item .partition ("=" ) 345if not vendor or not version : 346ap .error (f"--min-driver { item !r } is not VENDOR=VERSION" ) 347drivers [vendor ]= version 348a .out .mkdir (parents = True ,exist_ok = True ) 349folder = build (a .src ,a .backend ,a .version ,a .platform or host_platform (),a .out ,entry = a .entrypoint , 350archs = tuple (a .arch ),min_driver = drivers ,build_id = a .build_id ,min_runtime = a .min_runtime , 351notes = a .notes ,tree = a .tree ,include = a .include ,variant = a .variant , 352search = a .search ,allow_libs = a .allow_lib ,check_reader = True ,allow_stale_vision = a .allow_stale_vision , 353allow_no_reader = a .no_picture_reader ,shape = a .shape ) 354entries = [p for p in folder .rglob ("*" )if p .is_file ()] 355total = sum (p .stat ().st_size for p in entries ) 356f" { folder } ( { total / ( 1 << 20 ):.1f } MiB, { len ( entries ) } files, manifest sha256 { package_sha256 ( folder ) } )" ) 357return 0 358 359 360if __name__ == "__main__" : 361raise SystemExit (main ())