"""tools/image/sdcpp_noise/apply.py - put Strata's noise generator into a stable-diffusion.cpp checkout at the pinned commit (tools/image/qimage.py SD_CPP_COMMIT). Idempotent; sd-cli keeps stable-diffusion.cpp's own noise unless it is started with --model-args strata_noise=1 (serve/images.py adds that when the config's images "noise" is "strata"). python tools/image/sdcpp_noise/apply.py third_party/stable-diffusion.cpp patch a checkout (any backend) python tools/image/sdcpp_noise/apply.py --prepare DIR only the generator's files, for the proof programs in tools/image/gate/noise Three files go into src/core/ (strata_noise.hpp and its table, strata_philox_rng.hpp) and strata_sin_exc_data.inc is written 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 file is read at run time), and StableDiffusionGGML::init (src/pipeline/diffusion_engine.cpp) gets one include and one block that swaps the default Philox RNG for ours when the model args ask for it.""" from __future__ import annotations import shutil import sys from pathlib import Path HERE = Path(__file__).resolve().parent MARK = "// strata: noise generator" FILES = ("strata_noise.hpp", "strata_noise_tables.inc", "strata_philox_rng.hpp") BIN = "strata_sin_exc.bin" INCLUDE_OLD = '#include "core/rng_philox.hpp"\n' INCLUDE_NEW = INCLUDE_OLD + '#include "core/strata_philox_rng.hpp" ' + MARK + "\n" INIT_OLD = """ rng = get_rng(sd_ctx_params->rng_type); if (sd_ctx_params->sampler_rng_type != RNG_TYPE_COUNT && sd_ctx_params->sampler_rng_type != sd_ctx_params->rng_type) { sampler_rng = get_rng(sd_ctx_params->sampler_rng_type); } else { sampler_rng = rng; } """ INIT_NEW = INIT_OLD + """ """ + MARK + """ (--model-args strata_noise=1): Strata's Philox for the default --rng cuda if (strata_noise::requested(sd_ctx_params->model_args)) { if (sd_ctx_params->rng_type == CUDA_RNG) { rng = std::make_shared(); LOG_INFO("strata noise generator: on"); } else { LOG_WARN("strata noise generator: it replaces the default --rng cuda only; the noise stays stable-diffusion.cpp's"); } if (sd_ctx_params->sampler_rng_type == RNG_TYPE_COUNT || sd_ctx_params->sampler_rng_type == sd_ctx_params->rng_type) { sampler_rng = rng; } else if (sd_ctx_params->sampler_rng_type == CUDA_RNG) { sampler_rng = std::make_shared(); } } """ def data_inc(data: bytes) -> str: """The table file as C source: static const unsigned char STRATA_SIN_EXC_DATA[] = {...};""" rows = [", ".join("0x%02x" % b for b in data[i:i + 24]) for i in range(0, len(data), 24)] return ("// generated by tools/image/sdcpp_noise/apply.py from strata_sin_exc.bin (%d bytes); do not edit\n" "static const unsigned char STRATA_SIN_EXC_DATA[] = {\n %s\n};\n" % (len(data), ",\n ".join(rows))) def prepare(dst: Path) -> None: """The generator's files and the generated table source into the folder `dst`.""" dst = Path(dst) dst.mkdir(parents=True, exist_ok=True) for name in FILES: shutil.copyfile(HERE / name, dst / name) (dst / "strata_sin_exc_data.inc").write_bytes(data_inc((HERE / BIN).read_bytes()).encode("ascii")) def edit(path: Path, old: str, new: str) -> None: text = path.read_text(encoding="utf-8") if new in text: return if text.count(old) != 1: raise SystemExit(f"{path}: the expected code is not there (another stable-diffusion.cpp commit?)") path.write_bytes(text.replace(old, new).encode("utf-8")) def apply(sd: Path) -> None: sd = Path(sd) prepare(sd / "src" / "core") engine = sd / "src" / "pipeline" / "diffusion_engine.cpp" edit(engine, INCLUDE_OLD, INCLUDE_NEW) edit(engine, INIT_OLD, INIT_NEW) if __name__ == "__main__": if len(sys.argv) == 3 and sys.argv[1] == "--prepare": prepare(Path(sys.argv[2])) print("noise generator files written to", sys.argv[2]) elif len(sys.argv) == 2 and not sys.argv[1].startswith("-"): apply(Path(sys.argv[1])) print("Strata noise generator applied") else: raise SystemExit(__doc__)