okami.mom/strata

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

Niko1221Merge f-own-5 56630caca into f-own-int (round 14: Strata's own VAE decoder for sd-cli and the images "vae_decoder" switch)736266e87

main
5.2 KiB104 linesraw
1"""tools/image/install.py - image generation (Qwen-Image-2.1-Turbo) for an existing Strata install, or on its own:
2compiles sd-cli for the backend (setup.py's build_image_engine), downloads and checks the three model files, and
3writes the "images" section into a run config (or prints it).  setup.py --images qwen-image does the same inside
4the normal setup; this is the way to add it without running the whole setup again.
5
6    python tools/image/install.py --config strata-q2_0.json                 (backend and size picked for this PC)
7    python tools/image/install.py --backend vulkan --quant Q8_0 --models-dir ~/models --print
8    python tools/image/install.py --backend hip --arch gfx1103 --build-only
9
10--gpu-policy auto|keep|shrink|unload: what the text model does during an image job (serve/images.py).
11"""
12from __future__ import annotations
13
14import argparse
15import json
16import sys
17from pathlib import Path
18
19ROOT = Path(__file__).resolve().parents[2]
20sys.path.insert(0, str(ROOT))
21sys.path.insert(0, str(ROOT / "tools"))
22sys.path.insert(0, str(ROOT / "tools" / "image"))
23import qimage as QI  # noqa: E402
24
25
26def detect_gpu(S) -> tuple[dict | None, bool]:
27    """setup.py's view of this PC's GPU: (gpu dict, AMD?) - an NVIDIA card first, else an AMD one, else none."""
28    try:
29        g = S.gpu_info()
30        if g:
31            return {**g, "vendor": "nvidia"}, False
32    except Exception:                                   # noqa: BLE001 - no NVIDIA driver
33        pass
34    try:
35        amd = S.amd_gpus_win() if S.WIN else S.amd_gpus()
36        if amd:
37            g = min(amd, key=S.amd_rank)
38            return S.amd_apply_uma(dict(g)), True
39    except Exception:                                   # noqa: BLE001
40        pass
41    return None, False
42
43
44def main(argv=None) -> int:
45    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
46    ap.add_argument("--backend", choices=QI.BACKENDS)
47    ap.add_argument("--arch", help="the GPU architecture to compile for (CUDA: 86, ...; HIP: gfx1103, ...)")
48    ap.add_argument("--quant", choices=QI.QUANTS)
49    ap.add_argument("--gpu-gb", type=float, help="the GPU memory the quant is picked for (default: detected)")
50    ap.add_argument("--models-dir", help="where the model files go (default: the data folder's models)")
51    ap.add_argument("--config", help="a run config (strata-<model>.json) to write the \"images\" section into")
52    ap.add_argument("--gpu-policy", choices=["auto", "keep", "shrink", "unload"], default="auto")
53    ap.add_argument("--gpu", type=int, help="the GPU's number for the image job (default: the backend's first)")
54    ap.add_argument("--native", choices=["on", "off"], default="off",
55                    help="EXPERIMENTAL: Strata's own DiT runner on CUDA / HIP (the config's \"native\")")
56    ap.add_argument("--noise", choices=["on", "off"], default="off", help=argparse.SUPPRESS)
57    ap.add_argument("--vae", choices=["on", "off"], default="off", help=argparse.SUPPRESS)
58    ap.add_argument("--build-only", action="store_true", help="compile sd-cli only")
59    ap.add_argument("--print", action="store_true", help="print the images section instead of writing it")
60    ap.add_argument("--yes", action="store_true")
61    a = ap.parse_args(argv)
62    import setup as S
63    gpu, amd = detect_gpu(S) if not (a.backend and (a.arch or a.backend in ("vulkan", "cpu"))) else (None, False)
64    gpu = dict(gpu or {})
65    if a.arch:
66        gpu["arch"] = a.arch
67    if a.gpu_gb is not None:
68        gpu["vram_gb"] = a.gpu_gb
69    ns = argparse.Namespace(images="qwen-image", image_backend=a.backend, image_quant=a.quant,
70                            image_gpu_policy=a.gpu_policy, yes=a.yes)
71    backend, quant, gb = S.image_backend_choice(ns, gpu or None, amd or a.backend == "hip")
72    if backend in ("cuda", "hip") and not gpu.get("arch"):
73        S.fail(f"the {backend} build needs the GPU's architecture", "pass --arch (e.g. 86 or gfx1103)")
74    S.ok(f"image generation: {quant} on {backend}" + (f" ({gb:.0f} GB GPU memory)" if gb else ""))
75    exe, lib_dirs = S.build_image_engine(backend, gpu, a.noise == "on", a.vae == "on")
76    if a.build_only:
77        return 0
78    if a.models_dir:
79        models = Path(a.models_dir).expanduser()
80    else:
81        data, _ = S.data_folder(None)
82        models = data / "models"
83    S.say("  " + QI.LICENSE_NOTE)
84    for name in (quant, "vae", "llm"):
85        repo, path, size, sha = QI.FILES[name]
86        dst = QI.local_path(models, name)
87        S.download(QI.file_url(name, S.hf_endpoint()), dst, f"image model: {Path(path).name}")
88        S.verify_sha256(dst, size, sha)
89    section = QI.image_config(backend, quant, exe, models, uma=QI.is_apu(gpu), gpu=a.gpu, lib_dirs=lib_dirs,
90                              policy=a.gpu_policy, native=a.native == "on", noise=a.noise == "on",
91                              vae=a.vae == "on")
92    if a.print or not a.config:
93        print(json.dumps({"images": section}, indent=1))
94        return 0
95    path = Path(a.config)
96    cfg = json.loads(path.read_text(encoding="utf-8-sig")) if path.is_file() else {}
97    cfg["images"] = section
98    S.write_config(path, cfg)
99    S.ok(f"{path.name}: image generation added (POST /v1/images/generations once the server starts again)")
100    return 0
101
102
103if __name__ == "__main__":
104    sys.exit(main())