// strata_noise.hpp - Strata's own Philox noise generator: it reproduces stable-diffusion.cpp 2988060's default // noise (--rng cuda, src/core/rng_philox.hpp) as its Linux x86 GCC build produces it, on every operating system and // CPU, using integer arithmetic only: no maths-library call and nothing an FMA contraction can change. // tools/image/sdcpp_noise/apply.py copies this file into a stable-diffusion.cpp checkout (src/core/) and writes the // table below as strata_sin_exc_data.inc beside it; sd-cli uses it only with --model-args strata_noise=1. // // The x86 GCC stream, per value (rng_philox.hpp box_muller): // u = float(x) * 2^-32 + 2^-33 (float ops; the product is exact) // v = float(y) * C + C/2, C = 2^-32 * 6.2831855f (float ops: two roundings; FMA would make it one) // s = float( sqrt( -2 * log(double(u)) ) ) (glibc double log, IEEE sqrt) // r = float( double(s) * sin(double(v)) ) (glibc double sin) // Here log and sin are computed in 128-bit fixed point (Q8.120: 2 x uint64, 120 fraction bits, error a few units // of 2^-120) and rounded to double; sqrt is an exact integer square root rounded to double. // // Where everything comes from. All code here is our own; no third-party maths code (glibc, ARM optimized-routines, // CORE-MATH, ...) was copied or ported. The methods are textbook: log via ln m = ln c_j + 2 atanh(t) after a 64-point // table step, sin/cos via angle addition from i/64 (52 table points) and Taylor series. The constants ln 2 and pi/2 // (below) and the tables (strata_noise_tables.inc) were computed with Python's decimal module at 70 digits by // make_tables.py, rounded to the nearest 2^-120. The Philox4x32-10 counter logic follows the published algorithm // (Salmon et al., SC 2011) as stable-diffusion.cpp (MIT) uses it. The only floating-point operations left are casts // (integer -> float, double -> float), one float multiply done exactly in double then rounded, one float add and one // double multiply, all exactly specified by IEEE 754; the float adds are isolated by a volatile so they cannot be fused. // // glibc's double sin is not correctly rounded for 109,290 of the 83,886,081 reachable v (one unit off); those are // 92,529 distinct floats, 16,761 of them listed twice with the same flag. They are // in strata_sin_exc.bin (packed by tools/image/gate/noise/make_sin_exceptions.py from check_domain.cpp's exhaustive // list against glibc on x86-64, each re-checked against a 50-digit decimal sin) and compiled in through // strata_sin_exc_data.inc (generated by apply.py). glibc's double log is off by one unit for 21,841 reachable u, but // the float s is the same for every one of them, so log needs no table. // Build flag for the proof programs only: -DSTRATA_NOISE_NO_SIN_EXC leaves the table out (the correctly rounded sin). #pragma once #include #include #include #include #include namespace strata_noise { struct U128 { uint64_t hi, lo; }; static inline U128 u128(uint64_t hi, uint64_t lo) { return U128{hi, lo}; } static inline U128 add(U128 a, U128 b) { U128 r{a.hi + b.hi, a.lo + b.lo}; r.hi += r.lo < a.lo; return r; } static inline U128 sub(U128 a, U128 b) { U128 r{a.hi - b.hi, a.lo - b.lo}; r.hi -= a.lo < b.lo; return r; } static inline bool lt(U128 a, U128 b) { return a.hi < b.hi || (a.hi == b.hi && a.lo < b.lo); } static inline bool is0(U128 a) { return (a.hi | a.lo) == 0; } static inline U128 shl(U128 a, int n) { if (n == 0) return a; if (n >= 64) return U128{a.lo << (n - 64), 0}; return U128{(a.hi << n) | (a.lo >> (64 - n)), a.lo << n}; } static inline U128 shr(U128 a, int n) { if (n == 0) return a; if (n >= 64) return U128{0, a.hi >> (n - 64)}; return U128{a.hi >> n, (a.lo >> n) | (a.hi << (64 - n))}; } static inline int msb(U128 a) { // index of the top set bit, -1 for 0 int n = 127; uint64_t w = a.hi; if (!w) { w = a.lo; n = 63; if (!w) return -1; } while (!(w >> 63)) { w <<= 1; --n; } return n; } // (a * b) >> 120 (Q8.120 product, truncated), with 32-bit limbs static inline U128 mulfx(U128 a, U128 b) { uint32_t x[4] = {(uint32_t) a.lo, (uint32_t) (a.lo >> 32), (uint32_t) a.hi, (uint32_t) (a.hi >> 32)}; uint32_t y[4] = {(uint32_t) b.lo, (uint32_t) (b.lo >> 32), (uint32_t) b.hi, (uint32_t) (b.hi >> 32)}; uint64_t r[8] = {0, 0, 0, 0, 0, 0, 0, 0}; for (int i = 0; i < 4; ++i) { uint64_t c = 0; for (int j = 0; j < 4; ++j) { uint64_t t = (uint64_t) x[i] * y[j] + r[i + j] + c; r[i + j] = t & 0xffffffffu; c = t >> 32; } r[i + 4] = c; } uint64_t o[4]; for (int k = 0; k < 4; ++k) o[k] = ((r[3 + k] >> 24) | (r[4 + k] << 8)) & 0xffffffffu; return U128{(o[3] << 32) | o[2], (o[1] << 32) | o[0]}; } static inline U128 divsmall(U128 a, uint32_t d) { uint32_t l[4] = {(uint32_t) (a.hi >> 32), (uint32_t) a.hi, (uint32_t) (a.lo >> 32), (uint32_t) a.lo}; uint64_t rem = 0; uint32_t q[4]; for (int i = 0; i < 4; ++i) { uint64_t cur = (rem << 32) | l[i]; q[i] = (uint32_t) (cur / d); rem = cur % d; } return U128{((uint64_t) q[0] << 32) | q[1], ((uint64_t) q[2] << 32) | q[3]}; } static inline U128 mulsmall(U128 a, uint32_t k) { uint64_t l0 = (a.lo & 0xffffffffu) * k, l1 = (a.lo >> 32) * k + (l0 >> 32); uint64_t h0 = (a.hi & 0xffffffffu) * k + (l1 >> 32), h1 = (a.hi >> 32) * k + (h0 >> 32); return U128{(h1 << 32) | (h0 & 0xffffffffu), (l1 << 32) | (l0 & 0xffffffffu)}; } static const U128 LN2 = {0x00b17217f7d1cf79ull, 0xabc9e3b39803f2f7ull}; // ln 2 * 2^120 static const U128 PIO2 = {0x01921fb54442d184ull, 0x69898cc51701b83aull}; // pi/2 * 2^120 static const U128 ONE = {0x0100000000000000ull, 0}; // 1 * 2^120 static inline uint64_t dbits(double d) { uint64_t b; std::memcpy(&b, &d, 8); return b; } static inline double bitsd(uint64_t b) { double d; std::memcpy(&d, &b, 8); return d; } static inline uint32_t fbits(float f) { uint32_t b; std::memcpy(&b, &f, 4); return b; } // a Q8.120 magnitude (> 0) rounded to the nearest double (ties to even); value = F * 2^-120 static inline double fx_to_double(U128 f, bool neg) { int p = msb(f); if (p < 0) return neg ? -0.0 : 0.0; uint64_t mant; bool up = false; if (p >= 52) { int drop = p - 52; U128 m = shr(f, drop); mant = m.lo; if (drop > 0) { U128 rest = sub(f, shl(m, drop)); U128 half = shl(u128(0, 1), drop - 1); if (lt(half, rest)) up = true; else if (!lt(rest, half) && !lt(half, rest)) up = (mant & 1); // exact tie } } else { mant = shl(f, 52 - p).lo; } int e = p - 120; // value = mant * 2^(e - 52) if (up && ++mant == (1ull << 53)) { mant >>= 1; ++e; } uint64_t bits = ((uint64_t) (e + 1023) << 52) | (mant & ((1ull << 52) - 1)); return bitsd(bits | (neg ? (1ull << 63) : 0)); } #include "strata_noise_tables.inc" #ifndef STRATA_NOISE_NO_SIN_EXC #include "strata_sin_exc_data.inc" // static const unsigned char STRATA_SIN_EXC_DATA[] (apply.py writes it) #endif // -log(u) as Q8.120 for a float u in (0, 1] // m = M / 2^23 in [1, 2) is split as m = c_j * (1 + small): ln m = ln c_j + 2 atanh((m - c_j) / (m + c_j)), with // |t| <= 2^-8, so the atanh series needs 8 terms for 2^-120 (ln c_j: the table) static inline U128 neglog_fx(float u) { uint32_t b = fbits(u); int e = (int) ((b >> 23) & 0xff) - 127; // u is normal here (>= 2^-33) uint32_t M = (b & 0x7fffff) | 0x800000; U128 lnm{0, 0}; if (M != 0x800000) { uint32_t j = (M - 0x800000u) >> 17; uint32_t Cj = 0x800000u + (j << 17) + (1u << 16); bool negt = M < Cj; uint64_t num = negt ? Cj - M : M - Cj, den = (uint64_t) M + Cj, rem = num; U128 t{0, 0}; for (int k = 0; k < 4; ++k) { // t = num / den, 4 x 30-bit long-division steps uint64_t q = (rem << 30) / den; rem = (rem << 30) % den; t = add(shl(t, 30), u128(0, q)); } U128 t2 = mulfx(t, t), pw = t, sum{0, 0}; for (uint32_t k = 0; !is0(pw) && k < 40; ++k) { sum = add(sum, divsmall(pw, 2 * k + 1)); pw = mulfx(pw, t2); } lnm = negt ? sub(LNC[j], shl(sum, 1)) : add(LNC[j], shl(sum, 1)); } // -log u = (-e) ln2 - ln m ; e <= 0 return sub(mulsmall(LN2, (uint32_t) (-e)), lnm); } // sin and cos of a small d (|d| <= 1/128) as Q8.120 magnitudes (Taylor series) static inline U128 sin_small(U128 d) { U128 x2 = mulfx(d, d), term = d, sum = d; for (uint32_t k = 1; k < 20; ++k) { term = divsmall(mulfx(term, x2), (2 * k) * (2 * k + 1)); if (is0(term)) break; sum = (k & 1) ? sub(sum, term) : add(sum, term); } return sum; } static inline U128 cos_small(U128 d) { U128 x2 = mulfx(d, d), term = ONE, sum = ONE; for (uint32_t k = 1; k < 20; ++k) { term = divsmall(mulfx(term, x2), (2 * k - 1) * (2 * k)); if (is0(term)) break; sum = (k & 1) ? sub(sum, term) : add(sum, term); } return sum; } // sin(x) or cos(x) for x in [0, pi/4]: x = a + d with a = i/64 (table) and |d| <= 1/128 static inline U128 sincos_fx(U128 x, bool want_cos) { const U128 half = shl(u128(0, 1), 113); // 1/128 const uint32_t i = (uint32_t) shr(add(x, half), 114).lo; const U128 a = shl(u128(0, i), 114); const bool dneg = lt(x, a); const U128 d = dneg ? sub(a, x) : sub(x, a); const U128 sd = sin_small(d), cd = cos_small(d); const U128 p = mulfx(want_cos ? COSA[i] : SINA[i], cd); const U128 q = mulfx(want_cos ? SINA[i] : COSA[i], sd); // sin(a+d) = sin a cos d + cos a sin d ; cos(a+d) = cos a cos d - sin a sin d ; sin d is odd in d const bool plus = want_cos ? dneg : !dneg; return plus ? add(p, q) : sub(p, q); } static inline U128 sin_fx(U128 x) { return sincos_fx(x, false); } static inline U128 cos_fx(U128 x) { return sincos_fx(x, true); } // sin(double(v)) rounded to double, for a float v in (0, 8) static inline double sin_cr(float v) { uint32_t b = fbits(v); int e = (int) ((b >> 23) & 0xff) - 127; uint64_t M = (b & 0x7fffff) | 0x800000; // v = M * 2^(e - 23), exact in Q8.120 U128 x = shl(u128(0, M), 120 - 23 + e); // e >= -31 here, so the shift is >= 66 int q = 0; while (!lt(x, PIO2)) { x = sub(x, PIO2); ++q; } // q in 0..4: the largest v (6.2831855f) is just above 2 pi // x in [0, pi/2): sin(v) = +sin x, +cos x, -sin x, -cos x for q = 0..3 U128 pio4 = shr(PIO2, 1); bool use_cos = (q & 1) != 0; U128 r; if (lt(pio4, x)) { // use the complement pi/2 - x U128 y = sub(PIO2, x); r = use_cos ? sin_fx(y) : cos_fx(y); } else { r = use_cos ? cos_fx(x) : sin_fx(x); } return fx_to_double(r, (q & 2) != 0); } // sin(double(v)) as glibc (x86-64) returns it: the correctly rounded value, except at the v listed in // strata_sin_exc.bin, where glibc is one unit off. The table is the compiled-in STRATA_SIN_EXC_DATA, decoded once // (magic "OWN5SEX1", uint32 count, then per entry a varint of ((bits - previous bits) << 1 | down)). struct SinExc { std::vector keys; std::vector down; }; static inline SinExc decode_sin_exc(const unsigned char* d, size_t size) { SinExc e; if (size < 12 || std::memcmp(d, "OWN5SEX1", 8) != 0) { std::fprintf(stderr, "strata noise: bad table\n"); std::abort(); } const uint32_t n = (uint32_t) d[8] | ((uint32_t) d[9] << 8) | ((uint32_t) d[10] << 16) | ((uint32_t) d[11] << 24); size_t i = 12; uint64_t prev = 0; e.keys.reserve(n); e.down.reserve(n); for (uint32_t k = 0; k < n; ++k) { uint64_t v = 0; for (int sh = 0;; sh += 7) { if (i >= size || sh > 56) { std::fprintf(stderr, "strata noise: bad table\n"); std::abort(); } const uint8_t b = d[i++]; v |= (uint64_t) (b & 0x7f) << sh; if (!(b & 0x80)) break; } prev += v >> 1; e.keys.push_back((uint32_t) prev); e.down.push_back((uint8_t) (v & 1)); } if (i != size) { std::fprintf(stderr, "strata noise: bad table\n"); std::abort(); } return e; } static inline const SinExc& sin_exc() { #ifdef STRATA_NOISE_NO_SIN_EXC static const SinExc e; #else static const SinExc e = decode_sin_exc(STRATA_SIN_EXC_DATA, sizeof STRATA_SIN_EXC_DATA); #endif return e; } static inline double sin_x86(float v) { double d = sin_cr(v); const SinExc& e = sin_exc(); if (!e.keys.empty()) { const uint32_t key = fbits(v); size_t lo = 0, hi = e.keys.size(); while (lo < hi) { const size_t mid = (lo + hi) / 2; if (e.keys[mid] < key) lo = mid + 1; else hi = mid; } if (lo < e.keys.size() && e.keys[lo] == key) d = bitsd(dbits(d) + (e.down[lo] ? (uint64_t) -1 : (uint64_t) 1)); } return d; } // log(double(u)) rounded to double, for a float u in (0, 1] static inline double log_cr(float u) { if (fbits(u) == 0x3f800000u) return 0.0; // log 1 = +0 return fx_to_double(neglog_fx(u), true); } // 128-bit integer square root (floor) static inline U128 isqrt128(U128 n) { U128 res{0, 0}, bit = shl(u128(0, 1), (msb(n) & ~1)); while (!is0(bit)) { U128 rb = add(res, bit); if (!lt(n, rb)) { n = sub(n, rb); res = add(shr(res, 1), bit); } else res = shr(res, 1); bit = shr(bit, 2); } return res; } // sqrt(d) correctly rounded (ties to even) for a positive normal double d, with integers only static inline double sqrt_cr(double d) { uint64_t b = dbits(d); int E = (int) ((b >> 52) & 0x7ff) - 1075; // d = mant * 2^E uint64_t mant = (b & ((1ull << 52) - 1)) | (1ull << 52); if (E & 1) { mant <<= 1; E -= 1; } // even exponent U128 n = shl(u128(0, mant), 56); // n = mant * 2^56, isqrt has 54-55 bits U128 q = isqrt128(n); bool exact = is0(sub(n, mulfx(shl(q, 60), shl(q, 60)))); // q^2 == n ? (q < 2^56: (q<<60)^2 >> 120 = q^2) int p = msb(q); // 54 or 55 -> round to 53 bits int drop = p - 52; uint64_t qm = q.lo >> drop, rest = q.lo & ((1ull << drop) - 1), half = 1ull << (drop - 1); bool up = rest > half || (rest == half && (!exact || (qm & 1))); int e = E / 2 - 28 + drop; // value = qm * 2^e if (up && ++qm == (1ull << 53)) { qm >>= 1; ++e; } uint64_t bits = ((uint64_t) (e + 52 + 1023) << 52) | (qm & ((1ull << 52) - 1)); return bitsd(bits); } // one Box-Muller value as sd.cpp's x86 GCC build computes it static inline float box_muller(uint32_t cx, uint32_t cy) { const float x = (float) cx, y = (float) cy; // u: float(x) * 2^-32 is exact; + 2^-33 is one float add volatile float ux = (float) ((double) x * 0x1p-32); const float u = ux + 0x1p-33f; // v: the float product y * C rounded once (exact in double first), then one float add const float C = 0x1p-32f * 6.2831855f; volatile float vy = (float) ((double) y * (double) C); const float v = vy + C / 2; const double L = log_cr(u); float s; if (L == 0.0) s = -0.0f; // sqrt(-2 * +0.0) = sqrt(-0.0) = -0.0, as in the reference else s = (float) sqrt_cr(-2.0 * L); return (float) ((double) s * sin_x86(v)); } // PhiloxRNG::randn(n) after manual_seed(seed), first call (offset 0); the k-th call uses offset k static inline std::vector randn(uint64_t seed, uint32_t n, uint32_t offset = 0) { std::vector out(n); const uint32_t M0 = 0xD2511F53u, M1 = 0xCD9E8D57u, W0 = 0x9E3779B9u, W1 = 0xBB67AE85u; for (uint32_t i = 0; i < n; ++i) { uint32_t c0 = offset, c1 = 0, c2 = i, c3 = 0; uint32_t k0 = (uint32_t) seed, k1 = (uint32_t) (seed >> 32); for (int r = 0; r < 10; ++r) { uint64_t v1 = (uint64_t) c0 * M0, v2 = (uint64_t) c2 * M1; uint32_t n0 = (uint32_t) (v2 >> 32) ^ c1 ^ k0, n1 = (uint32_t) v2; uint32_t n2 = (uint32_t) (v1 >> 32) ^ c3 ^ k1, n3 = (uint32_t) v1; c0 = n0; c1 = n1; c2 = n2; c3 = n3; if (r < 9) { k0 += W0; k1 += W1; } } out[i] = box_muller(c0, c1); } return out; } } // namespace strata_noise