okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5649b9e52
main
1#!/usr/bin/env python3 2"""Build the Windows NVIDIA engine package (the cuda13 and cuda12 engine zips of the release feed). 3 4py -3 packaging\\build_cuda_windows.py cuda13 CUDA 13.0: sm_75 / 86 / 89 / 120 machine code + compute_120 PTX 5py -3 packaging\\build_cuda_windows.py cuda12 CUDA 12.9: sm_60 / 61 / 70 / 75 / 80 / 86 / 89 + compute_89 PTX, -DSTRATA_EXPERIMENTAL_SM60=ON 6 7Run it on a Windows PC with Visual Studio 2022 Build Tools (C++ workload), CMake + Ninja, Python 3.10+ and the CUDA toolkit of the variant 8(CUDA_PATH_V13_0 / CUDA_PATH_V12_9 as its installer sets them, or CUDA_PATH pointing at it). ggml and the picture reader's sources are the 9vendored third_party trees: nothing is downloaded. The package lands in OUT (default <repo>\\out-engine-win-<variant>). Nothing is uploaded. 10 11The steps are the release's: the engine configure line below, `strata` (+ `strata_kq` when the build tree has it), the picture reader for the 12same architectures (packaging\\build_vision_windows.bat), BUILD.json, then packaging/package_engine.py (which copies the CUDA DLLs strata.exe 13imports from the toolkit), --verify and binary_deps.py. 14 15Settings (environment, all optional): 16STRATA_CMAKE_EXTRA more engine configure arguments, e.g. -DSTRATA_MMQ=ON: the old engine with llama.cpp's MMQ and strata_kq.dll (A/B; 17the configure line names -DSTRATA_MMQ=OFF, and this comes after it) 18BUILD / BUILD_VISION_DIR / OUT the engine build folder, the reader's build folder, the package folder 19ARCHS the architecture list instead of the variant's (semicolons, e.g. 120; the last one also gets PTX), as in build_cuda_linux.sh 20BUILD_JOBS compile jobs (default 6: the CUDA compiler takes several GB of RAM per job) 21COMMIT the source commit for the build id (default: git rev-parse HEAD; required in a tree without .git) 22STRATA_GGML_DIR a llama.cpp checkout to take ggml (and the reader's sources) from instead (an override, kept for two releases) 23""" 24from __future__import annotations 25 26import json 27import os 28import re 29import shutil 30import subprocess 31import sys 32import tempfile 33from pathlib import Path 34 35REPO = Path (__file__ ).resolve ().parents [1 ] 36VARIANTS = { 37# variant: (CUDA version, archs, min driver, extra configure arguments) 38"cuda13" : ("13.0" , (75 ,86 ,89 ,120 ),"580.65" , []), 39"cuda12" : ("12.9" , (60 ,61 ,70 ,75 ,80 ,86 ,89 ),"576.02" , ["-DSTRATA_EXPERIMENTAL_SM60=ON" ]), 40} 41VCVARS = [Path (os .environ .get ("ProgramFiles" ,r"C:\Program Files" ))/ r"Microsoft Visual Studio\2022\BuildTools" , 42Path (os .environ .get ("ProgramFiles" ,r"C:\Program Files" ))/ r"Microsoft Visual Studio\2022\Community" , 43Path (os .environ .get ("ProgramFiles(x86)" ,r"C:\Program Files (x86)" ))/ r"Microsoft Visual Studio\2022\BuildTools" ] 44 45 46def fail (msg :str )-> None : 47raise SystemExit ("build_cuda_windows.py: " + msg ) 48 49 50def cuda_arch_list (archs )-> str : 51"""Every arch as machine code and PTX for the newest one: '75-real;86-real;89-real;120-real;120-virtual'.""" 52return ";" .join (["%d-real" % a for a in archs ]+ ["%d-virtual" % archs [- 1 ]]) 53 54 55def parse_archs (text :str )-> tuple [int , ...]: 56"""'75;86;89;120' (or commas / spaces) -> (75, 86, 89, 120); the last one also gets PTX.""" 57try : 58archs = tuple (int (x )for x in re .split (r"[;,\s]+" ,text .strip ())if x ) 59except ValueError : 60archs = () 61if not archs : 62fail ("ARCHS=%r is not a list of numbers like 75;86;89;120" % text ) 63return archs 64 65 66def configure_args (src :Path ,build :Path ,variant :str ,cuda :Path ,extra :list [str ],ggml_dir :str = "" , 67archs :tuple [int , ...]| None = None )-> list [str ]: 68"""The release's engine configure line (CMake defaults for everything it does not name).""" 69cu = cuda .as_posix () 70args = ["-G" ,"Ninja" ,"-S" ,str (src ),"-B" ,str (build ),"-DCMAKE_BUILD_TYPE=Release" ,"-DSTRATA_ENABLE_CUDA=ON" , 71"-DSTRATA_BUILD_TESTS=OFF" ,"-DSTRATA_NATIVE_EXPERTS=ON" ,"-DSTRATA_PORTABLE=ON" ,* VARIANTS [variant ][3 ], 72"-DSTRATA_MMQ=OFF" ,# without llama.cpp's MMQ, also in a build folder configured before (its cache says ON) 73"-DCMAKE_CUDA_ARCHITECTURES=" + cuda_arch_list (archs or VARIANTS [variant ][1 ]),"-DCMAKE_CUDA_COMPILER=%s/bin/nvcc.exe" % cu , 74"-DCUDAToolkit_ROOT=" + cu ] 75if ggml_dir : 76args .append ("-DSTRATA_GGML_DIR=" + ggml_dir .replace ("\\" ,"/" )) 77return args + extra 78 79 80def engine_targets (cmake :str ,build :Path ,env = None )-> list [str ]: 81"""['strata', 'strata_kq'] when the build tree has the strata_kq target (a build with llama.cpp's MMQ), ['strata'] when ninja names it 82unknown (STRATA_MMQ=OFF, the default). The tree is asked with a dry run, as packaging/engine_targets.sh does; any other failure stops the build.""" 83r = subprocess .run ([cmake ,"--build" ,str (build ),"--target" ,"strata_kq" ,"--" ,"-n" ],capture_output = True ,text = True ,env = env , 84errors = "replace" ) 85if r .returncode == 0 : 86return ["strata" ,"strata_kq" ] 87text = (r .stdout or "" )+ (r .stderr or "" ) 88if "unknown target 'strata_kq'" in text or re .search (r"No rule to make target.*strata_kq" ,text ): 89return ["strata" ] 90sys .stderr .write (text + "\n" ) 91fail ("cannot tell whether the build tree %s has the strata_kq target" % build ) 92return [] 93 94 95def find_cuda (variant :str )-> Path : 96cu = VARIANTS [variant ][0 ] 97for var in ("CUDA_PATH_V" + cu .replace ("." ,"_" ),"CUDA_PATH" ): 98root = os .environ .get (var ) 99if root and (Path (root )/ "bin" / "nvcc.exe" ).is_file (): 100out = subprocess .run ([str (Path (root )/ "bin" / "nvcc.exe" ),"--version" ],capture_output = True ,text = True ).stdout 101m = re .search (r"release (\d+\.\d+)" ,out ) 102if m and m .group (1 )== cu : 103return Path (root ) 104fail ("%s needs the CUDA %s toolkit (CUDA_PATH_V%s or CUDA_PATH)" % (variant ,cu ,cu .replace ("." ,"_" ))) 105return Path () 106 107 108def msvc_env ()-> dict : 109"""The environment of an x64 Native Tools prompt (vcvars64.bat), or this one when cl.exe is already on PATH.""" 110env = {k .upper ():v for k ,v in os .environ .items ()}# Windows names are case-insensitive: one key each (PATH, not Path and PATH) 111if shutil .which ("cl" ,path = env .get ("PATH" )): 112return env 113for vs in VCVARS : 114bat = vs / r"VC\Auxiliary\Build\vcvars64.bat" 115if bat .is_file (): 116r = subprocess .run ('cmd /d /s /c ""%s" >nul && set"' % bat ,capture_output = True ,text = True ,errors = "replace" ) 117for line in r .stdout .splitlines (): 118k ,sep ,v = line .partition ("=" ) 119if sep and k : 120env [k .upper ()]= v 121if shutil .which ("cl" ,path = env .get ("PATH" )): 122return env 123fail ("cl.exe not found: install Visual Studio 2022 Build Tools with the C++ workload, or run this from an x64 Native Tools prompt" ) 124return env 125 126 127def project_version (src :Path )-> str : 128m = re .search (r"project\([^)]*VERSION\s+([0-9][0-9.]*)" , (src / "CMakeLists.txt" ).read_text (encoding = "utf-8" )) 129if not m : 130fail ("no project VERSION in CMakeLists.txt" ) 131return m .group (1 ) 132 133 134def source_commit (src :Path )-> str : 135commit = os .environ .get ("COMMIT" ,"" ) 136if not commit : 137r = subprocess .run (["git" ,"-C" ,str (src ),"rev-parse" ,"HEAD" ],capture_output = True ,text = True ) 138commit = r .stdout .strip ()if r .returncode == 0 else "" 139if not re .fullmatch (r"[0-9a-f]{12,40}" ,commit ): 140fail ("set COMMIT=<hex> (no git commit found here)" ) 141return commit 142 143 144def run (cmd :list [str ],env :dict )-> None : 145"+ " + subprocess .list2cmdline (cmd ),flush = True ) 146if subprocess .run (cmd ,env = env ).returncode != 0 : 147fail ("failed: " + cmd [0 ]+ " " + " " .join (cmd [1 :3 ])) 148 149 150def main (argv :list [str ])-> int : 151if len (argv )!= 1 or argv [0 ]not in VARIANTS : 152__doc__ ) 153return 2 154variant = argv [0 ] 155if os .name != "nt" : 156fail ("this builds the Windows engine; on Linux use packaging/build_cuda_linux.sh" ) 157cu ,archs ,mindriver ,_ = VARIANTS [variant ] 158if os .environ .get ("ARCHS" ): 159archs = parse_archs (os .environ ["ARCHS" ]) 160src = REPO 161build = Path (os .environ .get ("BUILD" )or src / ("build-win-" + variant )) 162vision_dir = Path (os .environ .get ("BUILD_VISION_DIR" )or src / ("build-vision-%s-win" % variant )) 163out = Path (os .environ .get ("OUT" )or src / ("out-engine-win-" + variant )) 164jobs = os .environ .get ("BUILD_JOBS" )or "6" 165extra = (os .environ .get ("STRATA_CMAKE_EXTRA" )or "" ).split () 166version ,commit = project_version (src ),source_commit (src ) 167cuda = find_cuda (variant ) 168env = msvc_env () 169env ["CUDA_PATH" ]= str (cuda )# package_engine.py copies the DLLs strata.exe imports from here 170env ["PATH" ]= str (cuda / "bin" )+ os .pathsep + env .get ("PATH" ,"" ) 171cmake = shutil .which ("cmake" ,path = env ["PATH" ])or fail ("cmake not found" ) 172 173run ([cmake ,* configure_args (src ,build ,variant ,cuda ,extra ,os .environ .get ("STRATA_GGML_DIR" ,"" ),archs )],env ) 174targets = engine_targets (cmake ,build ,env ) 175"engine targets: " + " " .join (targets ),flush = True ) 176run ([cmake ,"--build" ,str (build ),"-j" ,jobs ,"--target" ,* targets ],env ) 177 178stage = Path (tempfile .mkdtemp (prefix = "strata-engine-stage-" )) 179try : 180for name in ("strata.exe" ,"strata_kq.dll" ): 181if (build / name ).is_file (): 182shutil .copy2 (build / name ,stage / name ) 183elif name in targets or name == "strata.exe" : 184fail ("the build made no %s" % name ) 185 (stage / "BUILD.json" ).write_text (json .dumps ({"version" :version ,"source" :"packaging/build_cuda_windows.py" ,"commit" :commit [:12 ], 186"archs" :list (archs ),"ptx" :True ,"cuda" :cu ,"vision" :"gpu-cuda" + cu .split ("." )[0 ], 187"portable" :True },indent = 1 ),encoding = "utf-8" ) 188venv = dict (env ,VISION_BUILD_DIR = str (vision_dir ),BUILD_JOBS = jobs ,VISION_ARCHS = ";" .join (str (a )for a in archs )) 189run (["cmd" ,"/d" ,"/c" ,str (src / "packaging" / "build_vision_windows.bat" ),variant ,str (stage )],venv )# writes vision_archs 190out .mkdir (parents = True ,exist_ok = True ) 191py = sys .executable 192cmd = [py ,str (src / "packaging" / "package_engine.py" ),"--src" ,str (stage ),"--backend" ,"cuda" ,"--version" ,version ,"--out" ,str (out ), 193* [x for a in archs for x in ("--arch" ,"sm_%d" % a )],"--arch" ,"compute_%d" % archs [- 1 ],"--min-driver" ,"nvidia=" + mindriver , 194"--variant" ,variant ,"--platform" ,"windows-x86_64" ,"--build-id" ,"%s+cuda%s" % (commit [:12 ],cu ), 195"--include" ,"strata-vision.exe" ,"--include" ,"strata_kq.dll" ] 196run (cmd ,env ) 197finally : 198shutil .rmtree (stage ,ignore_errors = True ) 199folder = out / ("%s-windows-x86_64-cuda-%s" % (version ,variant )) 200run ([sys .executable ,str (src / "packaging" / "package_engine.py" ),"--verify" ,str (folder )],env ) 201run ([sys .executable ,str (src / "packaging" / "binary_deps.py" ),str (folder )],env ) 202"built: %s" % folder ) 203return 0 204 205 206if __name__ == "__main__" : 207sys .exit (main (sys .argv [1 :]))