okami.mom/strata

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

Niko1221Merge f-own-5 fccdb48a3 (image noise switch, step 1 only) into f-own-int150c2394f

main
6.8 KiB139 linesraw
1"""OWN-5: build sd-cli on a test box the way setup.py's build_image_engine does (tools/image/qimage.py's CMake
2definitions, Release, the native runner applied on CUDA / HIP), in this lane's own folder.
3
4    python3 -I -B build_sd.py <root> <backend cuda|hip|vulkan|cpu> [arch] [--min-free-gb N] [--jobs N]
5
6<root> holds repo.tgz (git archive of f-own-5) and sdsrc.tgz (the pinned stable-diffusion.cpp tree, .strata-pin
7inside).  Results: <root>/repo, <root>/sd-<backend>, <root>/build-<backend>/bin/sd-cli, <root>/build-<backend>.json.
8HIP: ROCm from the pip SDK in /data/Strata/.venv (as the engine builds on p620) unless ROCM_PATH is set.
9Vulkan: the LunarG SDK (qimage.VULKAN_SDK_*) unpacked into <root>/vulkan-sdk when the box has no glslc."""
10from __future__ import annotations
11
12import hashlib
13import json
14import os
15import shutil
16import subprocess
17import sys
18import tarfile
19import time
20import urllib.request
21from pathlib import Path
22
23
24def free_gb(p: Path) -> float:
25    return shutil.disk_usage(p).free / 1e9
26
27
28def sh(cmd, env=None, log=None):
29    print("+", " ".join(str(c) for c in cmd), flush=True)
30    if log:
31        with open(log, "w") as f:
32            r = subprocess.run([str(c) for c in cmd], env=env, stdout=f, stderr=subprocess.STDOUT)
33        if r.returncode:
34            print(open(log, errors="replace").read()[-6000:])
35    else:
36        r = subprocess.run([str(c) for c in cmd], env=env)
37    if r.returncode:
38        raise SystemExit(f"FAILED ({r.returncode}): {cmd[0]}")
39
40
41def main() -> int:
42    a = sys.argv[1:]
43    root, backend = Path(a[0]).expanduser().resolve(), a[1]
44    arch = a[2] if len(a) > 2 and not a[2].startswith("--") else None
45    min_free = float(a[a.index("--min-free-gb") + 1]) if "--min-free-gb" in a else 15.0
46    jobs = a[a.index("--jobs") + 1] if "--jobs" in a else str(max(2, (os.cpu_count() or 4) // 2))
47    t0 = time.time()
48    print(f"free before: {free_gb(root):.1f} GB (floor {min_free})", flush=True)
49    if free_gb(root) < min_free + 3:
50        raise SystemExit("ABORT: not enough disk")
51    repo = root / "repo"
52    if not (repo / "tools" / "image" / "qimage.py").is_file():
53        repo.mkdir(exist_ok=True)
54        with tarfile.open(root / "repo.tgz") as t:
55            t.extractall(repo)
56    sys.path.insert(0, str(repo / "tools" / "image"))
57    import qimage as QI
58    src = root / f"sd-{backend}"
59    if not QI.source_ok(src):
60        shutil.rmtree(src, ignore_errors=True)
61        tmp = root / f"_sd-{backend}"
62        shutil.rmtree(tmp, ignore_errors=True)
63        tmp.mkdir()
64        with tarfile.open(root / "sdsrc.tgz") as t:
65            t.extractall(tmp)
66        shutil.move(str(next(tmp.iterdir())), str(src))
67        tmp.rmdir()
68    if not QI.source_ok(src):
69        raise SystemExit("the unpacked source does not carry the pinned .strata-pin")
70    if backend in QI.NATIVE_BACKENDS:
71        sh([sys.executable, "-I", "-B", repo / "tools" / "image" / "sdcpp_native" / "apply.py", src])
72    env = dict(os.environ)
73    extra = []
74    if backend == "hip":
75        hp = Path(env.get("ROCM_PATH") or "/data/Strata/.venv/lib/python3.12/site-packages/_rocm_sdk_devel")
76        site = hp.parent
77        libw = next((p for p in site.glob("_rocm_sdk_libraries_*")), None)
78        core = site / "_rocm_sdk_core"
79        env.update(HIP_PLATFORM="amd", ROCM_PATH=str(hp), HIP_PATH=str(hp))
80        env["LD_LIBRARY_PATH"] = os.pathsep.join(str(d) for d in (hp / "lib", libw / "lib" if libw else hp, core / "lib")
81                                                 ) + os.pathsep + env.get("LD_LIBRARY_PATH", "")
82        env["PATH"] = f"{hp / 'bin'}{os.pathsep}{env['PATH']}"
83        defs = QI.cmake_defs("hip", arch=arch, rocm=hp)
84        if libw:
85            defs = [d.replace("-DCMAKE_PREFIX_PATH=", f"-DCMAKE_PREFIX_PATH={libw};") for d in defs]
86    elif backend == "cuda":
87        nvcc = shutil.which("nvcc") or "/usr/local/cuda/bin/nvcc"
88        cuda_root = Path(nvcc).resolve().parent.parent
89        env["PATH"] = f"{cuda_root / 'bin'}{os.pathsep}{env['PATH']}"
90        defs = QI.cmake_defs("cuda", arch=arch, cuda_root=cuda_root) + [f"-DCMAKE_CUDA_COMPILER={nvcc}"]
91    elif backend == "vulkan":
92        defs = QI.cmake_defs("vulkan")
93        if not shutil.which("glslc"):
94            sdk = root / "vulkan-sdk" / QI.VULKAN_SDK_VERSION / "x86_64"
95            if not (sdk / "bin" / "glslc").exists():
96                tar = root / f"vulkansdk-{QI.VULKAN_SDK_VERSION}.tar.xz"
97                if not tar.exists() or tar.stat().st_size != QI.VULKAN_SDK_SIZE:
98                    print("downloading the LunarG Vulkan SDK", flush=True)
99                    # urllib's default User-Agent gets 403 from sdk.lunarg.com; curl's is accepted
100                    sh(["curl", "-L", "--fail", "--retry", "5", "-s", "-S", "-o", tar, QI.VULKAN_SDK_URL])
101                h = hashlib.sha256()
102                with open(tar, "rb") as f:
103                    for b in iter(lambda: f.read(1 << 20), b""):
104                        h.update(b)
105                if tar.stat().st_size != QI.VULKAN_SDK_SIZE or h.hexdigest() != QI.VULKAN_SDK_SHA256:
106                    raise SystemExit("the Vulkan SDK download does not match its pinned size / sha256")
107                with tarfile.open(tar) as t:
108                    t.extractall(root / "vulkan-sdk", filter="data")
109                tar.unlink()
110            env["VULKAN_SDK"] = str(sdk)
111            env["PATH"] = f"{sdk / 'bin'}{os.pathsep}{env['PATH']}"
112            loader = sdk / "lib" / "VulkanLoader" / "lib"
113            env["LD_LIBRARY_PATH"] = f"{loader}{os.pathsep}{env.get('LD_LIBRARY_PATH', '')}"
114            extra = [f"-DVulkan_LIBRARY={loader / 'libvulkan.so'}", f"-DVulkan_INCLUDE_DIR={sdk / 'include'}",
115                     f"-DVulkan_GLSLC_EXECUTABLE={sdk / 'bin' / 'glslc'}"]
116    else:
117        defs = QI.cmake_defs("cpu")
118    bdir = root / f"build-{backend}"
119    gen = ["-G", "Ninja"] if shutil.which("ninja") else ["-G", "Unix Makefiles"]
120    conf = ["cmake", *gen, "-S", src, "-B", bdir, "-DCMAKE_BUILD_TYPE=Release",
121            "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON", *defs, *extra]
122    sh(conf, env=env, log=root / f"cfg-{backend}.log")
123    sh(["nice", "-n", "15", "cmake", "--build", bdir, "--target", "sd-cli", "-j", jobs], env=env,
124       log=root / f"build-{backend}.log")
125    exe = bdir / "bin" / "sd-cli"
126    if not exe.exists():
127        raise SystemExit(f"no {exe}")
128    info = {**QI.build_stamp(backend, arch), "configure": [str(c) for c in conf], "generator": gen[1],
129            "minutes": round((time.time() - t0) / 60, 1), "exe": str(exe), "exe_bytes": exe.stat().st_size,
130            "env_ld": env.get("LD_LIBRARY_PATH", ""), "env_path": env["PATH"]}
131    (root / f"build-{backend}.json").write_text(json.dumps(info, indent=1))
132    print(json.dumps({k: info[k] for k in ("backend", "arch", "minutes", "exe_bytes", "generator")}))
133    print(f"free after: {free_gb(root):.1f} GB", flush=True)
134    print("BUILD-OK")
135    return 0
136
137
138if __name__ == "__main__":
139    sys.exit(main())