okami.mom/strata

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

Niko1221Merge f-mmq-default-off: build the engine without llama.cpp's MMQ kernels by default (-DSTRATA_MMQ=ON keeps the old path; linux-aarch64 unchanged)5649b9e52

main
11.0 KiB207 linesraw
1#!/usr/bin/env python3
2"""Build the Windows NVIDIA engine package (the cuda13 and cuda12 engine zips of the release feed).
3
4    py -3 packaging\\build_cuda_windows.py cuda13     CUDA 13.0: sm_75 / 86 / 89 / 120 machine code + compute_120 PTX
5    py -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):
16  STRATA_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;
17                      the configure line names -DSTRATA_MMQ=OFF, and this comes after it)
18  BUILD / BUILD_VISION_DIR / OUT   the engine build folder, the reader's build folder, the package folder
19  ARCHS               the architecture list instead of the variant's (semicolons, e.g. 120; the last one also gets PTX), as in build_cuda_linux.sh
20  BUILD_JOBS          compile jobs (default 6: the CUDA compiler takes several GB of RAM per job)
21  COMMIT              the source commit for the build id (default: git rev-parse HEAD; required in a tree without .git)
22  STRATA_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",
42          Path(os.environ.get("ProgramFiles", r"C:\Program Files")) / r"Microsoft Visual Studio\2022\Community",
43          Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / r"Microsoft Visual Studio\2022\BuildTools"]
44
45
46def fail(msg: str) -> None:
47    raise 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'."""
52    return ";".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."""
57    try:
58        archs = tuple(int(x) for x in re.split(r"[;,\s]+", text.strip()) if x)
59    except ValueError:
60        archs = ()
61    if not archs:
62        fail("ARCHS=%r is not a list of numbers like 75;86;89;120" % text)
63    return archs
64
65
66def configure_args(src: Path, build: Path, variant: str, cuda: Path, extra: list[str], ggml_dir: str = "",
67                   archs: tuple[int, ...] | None = None) -> list[str]:
68    """The release's engine configure line (CMake defaults for everything it does not name)."""
69    cu = cuda.as_posix()
70    args = ["-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]
75    if ggml_dir:
76        args.append("-DSTRATA_GGML_DIR=" + ggml_dir.replace("\\", "/"))
77    return 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
82    unknown (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."""
83    r = subprocess.run([cmake, "--build", str(build), "--target", "strata_kq", "--", "-n"], capture_output=True, text=True, env=env,
84                       errors="replace")
85    if r.returncode == 0:
86        return ["strata", "strata_kq"]
87    text = (r.stdout or "") + (r.stderr or "")
88    if "unknown target 'strata_kq'" in text or re.search(r"No rule to make target.*strata_kq", text):
89        return ["strata"]
90    sys.stderr.write(text + "\n")
91    fail("cannot tell whether the build tree %s has the strata_kq target" % build)
92    return []
93
94
95def find_cuda(variant: str) -> Path:
96    cu = VARIANTS[variant][0]
97    for var in ("CUDA_PATH_V" + cu.replace(".", "_"), "CUDA_PATH"):
98        root = os.environ.get(var)
99        if root and (Path(root) / "bin" / "nvcc.exe").is_file():
100            out = subprocess.run([str(Path(root) / "bin" / "nvcc.exe"), "--version"], capture_output=True, text=True).stdout
101            m = re.search(r"release (\d+\.\d+)", out)
102            if m and m.group(1) == cu:
103                return Path(root)
104    fail("%s needs the CUDA %s toolkit (CUDA_PATH_V%s or CUDA_PATH)" % (variant, cu, cu.replace(".", "_")))
105    return 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."""
110    env = {k.upper(): v for k, v in os.environ.items()}      # Windows names are case-insensitive: one key each (PATH, not Path and PATH)
111    if shutil.which("cl", path=env.get("PATH")):
112        return env
113    for vs in VCVARS:
114        bat = vs / r"VC\Auxiliary\Build\vcvars64.bat"
115        if bat.is_file():
116            r = subprocess.run('cmd /d /s /c ""%s" >nul && set"' % bat, capture_output=True, text=True, errors="replace")
117            for line in r.stdout.splitlines():
118                k, sep, v = line.partition("=")
119                if sep and k:
120                    env[k.upper()] = v
121            if shutil.which("cl", path=env.get("PATH")):
122                return env
123    fail("cl.exe not found: install Visual Studio 2022 Build Tools with the C++ workload, or run this from an x64 Native Tools prompt")
124    return env
125
126
127def project_version(src: Path) -> str:
128    m = re.search(r"project\([^)]*VERSION\s+([0-9][0-9.]*)", (src / "CMakeLists.txt").read_text(encoding="utf-8"))
129    if not m:
130        fail("no project VERSION in CMakeLists.txt")
131    return m.group(1)
132
133
134def source_commit(src: Path) -> str:
135    commit = os.environ.get("COMMIT", "")
136    if not commit:
137        r = subprocess.run(["git", "-C", str(src), "rev-parse", "HEAD"], capture_output=True, text=True)
138        commit = r.stdout.strip() if r.returncode == 0 else ""
139    if not re.fullmatch(r"[0-9a-f]{12,40}", commit):
140        fail("set COMMIT=<hex> (no git commit found here)")
141    return commit
142
143
144def run(cmd: list[str], env: dict) -> None:
145    print("+ " + subprocess.list2cmdline(cmd), flush=True)
146    if subprocess.run(cmd, env=env).returncode != 0:
147        fail("failed: " + cmd[0] + " " + " ".join(cmd[1:3]))
148
149
150def main(argv: list[str]) -> int:
151    if len(argv) != 1 or argv[0] not in VARIANTS:
152        print(__doc__)
153        return 2
154    variant = argv[0]
155    if os.name != "nt":
156        fail("this builds the Windows engine; on Linux use packaging/build_cuda_linux.sh")
157    cu, archs, mindriver, _ = VARIANTS[variant]
158    if os.environ.get("ARCHS"):
159        archs = parse_archs(os.environ["ARCHS"])
160    src = REPO
161    build = Path(os.environ.get("BUILD") or src / ("build-win-" + variant))
162    vision_dir = Path(os.environ.get("BUILD_VISION_DIR") or src / ("build-vision-%s-win" % variant))
163    out = Path(os.environ.get("OUT") or src / ("out-engine-win-" + variant))
164    jobs = os.environ.get("BUILD_JOBS") or "6"
165    extra = (os.environ.get("STRATA_CMAKE_EXTRA") or "").split()
166    version, commit = project_version(src), source_commit(src)
167    cuda = find_cuda(variant)
168    env = msvc_env()
169    env["CUDA_PATH"] = str(cuda)                         # package_engine.py copies the DLLs strata.exe imports from here
170    env["PATH"] = str(cuda / "bin") + os.pathsep + env.get("PATH", "")
171    cmake = shutil.which("cmake", path=env["PATH"]) or fail("cmake not found")
172
173    run([cmake, *configure_args(src, build, variant, cuda, extra, os.environ.get("STRATA_GGML_DIR", ""), archs)], env)
174    targets = engine_targets(cmake, build, env)
175    print("engine targets: " + " ".join(targets), flush=True)
176    run([cmake, "--build", str(build), "-j", jobs, "--target", *targets], env)
177
178    stage = Path(tempfile.mkdtemp(prefix="strata-engine-stage-"))
179    try:
180        for name in ("strata.exe", "strata_kq.dll"):
181            if (build / name).is_file():
182                shutil.copy2(build / name, stage / name)
183            elif name in targets or name == "strata.exe":
184                fail("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")
188        venv = dict(env, VISION_BUILD_DIR=str(vision_dir), BUILD_JOBS=jobs, VISION_ARCHS=";".join(str(a) for a in archs))
189        run(["cmd", "/d", "/c", str(src / "packaging" / "build_vision_windows.bat"), variant, str(stage)], venv)   # writes vision_archs
190        out.mkdir(parents=True, exist_ok=True)
191        py = sys.executable
192        cmd = [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"]
196        run(cmd, env)
197    finally:
198        shutil.rmtree(stage, ignore_errors=True)
199    folder = out / ("%s-windows-x86_64-cuda-%s" % (version, variant))
200    run([sys.executable, str(src / "packaging" / "package_engine.py"), "--verify", str(folder)], env)
201    run([sys.executable, str(src / "packaging" / "binary_deps.py"), str(folder)], env)
202    print("built: %s" % folder)
203    return 0
204
205
206if __name__ == "__main__":
207    sys.exit(main(sys.argv[1:]))