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
4.3 KiB91 linesraw
1"""tools/image/sdcpp_noise/apply.py - put Strata's noise generator into a stable-diffusion.cpp checkout at the pinned
2commit (tools/image/qimage.py SD_CPP_COMMIT).  Idempotent; sd-cli keeps stable-diffusion.cpp's own noise unless it is
3started with --model-args strata_noise=1 (serve/images.py adds that when the config's images "noise" is "strata").
4
5    python tools/image/sdcpp_noise/apply.py third_party/stable-diffusion.cpp      patch a checkout (any backend)
6    python tools/image/sdcpp_noise/apply.py --prepare DIR                         only the generator's files, for the
7                                                                                  proof programs in tools/image/gate/noise
8
9Three files go into src/core/ (strata_noise.hpp and its table, strata_philox_rng.hpp) and strata_sin_exc_data.inc is
10written there from strata_sin_exc.bin (the 184 KB table of glibc's sin results that are one unit off, as a C array: no
11file is read at run time), and StableDiffusionGGML::init (src/pipeline/diffusion_engine.cpp) gets one include and one
12block that swaps the default Philox RNG for ours when the model args ask for it."""
13from __future__ import annotations
14
15import shutil
16import sys
17from pathlib import Path
18
19HERE = Path(__file__).resolve().parent
20MARK = "// strata: noise generator"
21FILES = ("strata_noise.hpp", "strata_noise_tables.inc", "strata_philox_rng.hpp")
22BIN = "strata_sin_exc.bin"
23
24INCLUDE_OLD = '#include "core/rng_philox.hpp"\n'
25INCLUDE_NEW = INCLUDE_OLD + '#include "core/strata_philox_rng.hpp"  ' + MARK + "\n"
26INIT_OLD = """    rng = get_rng(sd_ctx_params->rng_type);
27    if (sd_ctx_params->sampler_rng_type != RNG_TYPE_COUNT && sd_ctx_params->sampler_rng_type != sd_ctx_params->rng_type) {
28        sampler_rng = get_rng(sd_ctx_params->sampler_rng_type);
29    } else {
30        sampler_rng = rng;
31    }
32"""
33INIT_NEW = INIT_OLD + """    """ + MARK + """ (--model-args strata_noise=1): Strata's Philox for the default --rng cuda
34    if (strata_noise::requested(sd_ctx_params->model_args)) {
35        if (sd_ctx_params->rng_type == CUDA_RNG) {
36            rng = std::make_shared<StrataPhiloxRNG>();
37            LOG_INFO("strata noise generator: on");
38        } else {
39            LOG_WARN("strata noise generator: it replaces the default --rng cuda only; the noise stays stable-diffusion.cpp's");
40        }
41        if (sd_ctx_params->sampler_rng_type == RNG_TYPE_COUNT || sd_ctx_params->sampler_rng_type == sd_ctx_params->rng_type) {
42            sampler_rng = rng;
43        } else if (sd_ctx_params->sampler_rng_type == CUDA_RNG) {
44            sampler_rng = std::make_shared<StrataPhiloxRNG>();
45        }
46    }
47"""
48
49
50def data_inc(data: bytes) -> str:
51    """The table file as C source: static const unsigned char STRATA_SIN_EXC_DATA[] = {...};"""
52    rows = [", ".join("0x%02x" % b for b in data[i:i + 24]) for i in range(0, len(data), 24)]
53    return ("// generated by tools/image/sdcpp_noise/apply.py from strata_sin_exc.bin (%d bytes); do not edit\n"
54            "static const unsigned char STRATA_SIN_EXC_DATA[] = {\n    %s\n};\n" % (len(data), ",\n    ".join(rows)))
55
56
57def prepare(dst: Path) -> None:
58    """The generator's files and the generated table source into the folder `dst`."""
59    dst = Path(dst)
60    dst.mkdir(parents=True, exist_ok=True)
61    for name in FILES:
62        shutil.copyfile(HERE / name, dst / name)
63    (dst / "strata_sin_exc_data.inc").write_bytes(data_inc((HERE / BIN).read_bytes()).encode("ascii"))
64
65
66def edit(path: Path, old: str, new: str) -> None:
67    text = path.read_text(encoding="utf-8")
68    if new in text:
69        return
70    if text.count(old) != 1:
71        raise SystemExit(f"{path}: the expected code is not there (another stable-diffusion.cpp commit?)")
72    path.write_bytes(text.replace(old, new).encode("utf-8"))
73
74
75def apply(sd: Path) -> None:
76    sd = Path(sd)
77    prepare(sd / "src" / "core")
78    engine = sd / "src" / "pipeline" / "diffusion_engine.cpp"
79    edit(engine, INCLUDE_OLD, INCLUDE_NEW)
80    edit(engine, INIT_OLD, INIT_NEW)
81
82
83if __name__ == "__main__":
84    if len(sys.argv) == 3 and sys.argv[1] == "--prepare":
85        prepare(Path(sys.argv[2]))
86        print("noise generator files written to", sys.argv[2])
87    elif len(sys.argv) == 2 and not sys.argv[1].startswith("-"):
88        apply(Path(sys.argv[1]))
89        print("Strata noise generator applied")
90    else:
91        raise SystemExit(__doc__)