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
16.2 KiB347 linesraw
1// strata_noise.hpp - Strata's own Philox noise generator: it reproduces stable-diffusion.cpp 2988060's default
2// noise (--rng cuda, src/core/rng_philox.hpp) as its Linux x86 GCC build produces it, on every operating system and
3// CPU, using integer arithmetic only: no maths-library call and nothing an FMA contraction can change.
4// tools/image/sdcpp_noise/apply.py copies this file into a stable-diffusion.cpp checkout (src/core/) and writes the
5// table below as strata_sin_exc_data.inc beside it; sd-cli uses it only with --model-args strata_noise=1.
6//
7// The x86 GCC stream, per value (rng_philox.hpp box_muller):
8//   u = float(x) * 2^-32 + 2^-33                      (float ops; the product is exact)
9//   v = float(y) * C + C/2,  C = 2^-32 * 6.2831855f   (float ops: two roundings; FMA would make it one)
10//   s = float( sqrt( -2 * log(double(u)) ) )           (glibc double log, IEEE sqrt)
11//   r = float( double(s) * sin(double(v)) )            (glibc double sin)
12// Here log and sin are computed in 128-bit fixed point (Q8.120: 2 x uint64, 120 fraction bits, error a few units
13// of 2^-120) and rounded to double; sqrt is an exact integer square root rounded to double.
14//
15// Where everything comes from.  All code here is our own; no third-party maths code (glibc, ARM optimized-routines,
16// CORE-MATH, ...) was copied or ported.  The methods are textbook: log via ln m = ln c_j + 2 atanh(t) after a 64-point
17// table step, sin/cos via angle addition from i/64 (52 table points) and Taylor series.  The constants ln 2 and pi/2
18// (below) and the tables (strata_noise_tables.inc) were computed with Python's decimal module at 70 digits by
19// make_tables.py, rounded to the nearest 2^-120.  The Philox4x32-10 counter logic follows the published algorithm
20// (Salmon et al., SC 2011) as stable-diffusion.cpp (MIT) uses it.  The only floating-point operations left are casts
21// (integer -> float, double -> float), one float multiply done exactly in double then rounded, one float add and one
22// double multiply, all exactly specified by IEEE 754; the float adds are isolated by a volatile so they cannot be fused.
23//
24// glibc's double sin is not correctly rounded for 109,290 of the 83,886,081 reachable v (one unit off); those are
25// 92,529 distinct floats, 16,761 of them listed twice with the same flag.  They are
26// in strata_sin_exc.bin (packed by tools/image/gate/noise/make_sin_exceptions.py from check_domain.cpp's exhaustive
27// list against glibc on x86-64, each re-checked against a 50-digit decimal sin) and compiled in through
28// strata_sin_exc_data.inc (generated by apply.py).  glibc's double log is off by one unit for 21,841 reachable u, but
29// the float s is the same for every one of them, so log needs no table.
30// Build flag for the proof programs only: -DSTRATA_NOISE_NO_SIN_EXC leaves the table out (the correctly rounded sin).
31#pragma once
32#include <cstdint>
33#include <cstdio>
34#include <cstdlib>
35#include <cstring>
36#include <vector>
37
38namespace strata_noise {
39
40struct U128 { uint64_t hi, lo; };
41
42static inline U128 u128(uint64_t hi, uint64_t lo) { return U128{hi, lo}; }
43static 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; }
44static 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; }
45static inline bool lt(U128 a, U128 b) { return a.hi < b.hi || (a.hi == b.hi && a.lo < b.lo); }
46static inline bool is0(U128 a) { return (a.hi | a.lo) == 0; }
47static inline U128 shl(U128 a, int n) {
48    if (n == 0) return a;
49    if (n >= 64) return U128{a.lo << (n - 64), 0};
50    return U128{(a.hi << n) | (a.lo >> (64 - n)), a.lo << n};
51}
52static inline U128 shr(U128 a, int n) {
53    if (n == 0) return a;
54    if (n >= 64) return U128{0, a.hi >> (n - 64)};
55    return U128{a.hi >> n, (a.lo >> n) | (a.hi << (64 - n))};
56}
57static inline int msb(U128 a) {   // index of the top set bit, -1 for 0
58    int n = 127;
59    uint64_t w = a.hi;
60    if (!w) { w = a.lo; n = 63; if (!w) return -1; }
61    while (!(w >> 63)) { w <<= 1; --n; }
62    return n;
63}
64// (a * b) >> 120 (Q8.120 product, truncated), with 32-bit limbs
65static inline U128 mulfx(U128 a, U128 b) {
66    uint32_t x[4] = {(uint32_t) a.lo, (uint32_t) (a.lo >> 32), (uint32_t) a.hi, (uint32_t) (a.hi >> 32)};
67    uint32_t y[4] = {(uint32_t) b.lo, (uint32_t) (b.lo >> 32), (uint32_t) b.hi, (uint32_t) (b.hi >> 32)};
68    uint64_t r[8] = {0, 0, 0, 0, 0, 0, 0, 0};
69    for (int i = 0; i < 4; ++i) {
70        uint64_t c = 0;
71        for (int j = 0; j < 4; ++j) {
72            uint64_t t = (uint64_t) x[i] * y[j] + r[i + j] + c;
73            r[i + j] = t & 0xffffffffu;
74            c = t >> 32;
75        }
76        r[i + 4] = c;
77    }
78    uint64_t o[4];
79    for (int k = 0; k < 4; ++k) o[k] = ((r[3 + k] >> 24) | (r[4 + k] << 8)) & 0xffffffffu;
80    return U128{(o[3] << 32) | o[2], (o[1] << 32) | o[0]};
81}
82static inline U128 divsmall(U128 a, uint32_t d) {
83    uint32_t l[4] = {(uint32_t) (a.hi >> 32), (uint32_t) a.hi, (uint32_t) (a.lo >> 32), (uint32_t) a.lo};
84    uint64_t rem = 0;
85    uint32_t q[4];
86    for (int i = 0; i < 4; ++i) {
87        uint64_t cur = (rem << 32) | l[i];
88        q[i] = (uint32_t) (cur / d);
89        rem = cur % d;
90    }
91    return U128{((uint64_t) q[0] << 32) | q[1], ((uint64_t) q[2] << 32) | q[3]};
92}
93static inline U128 mulsmall(U128 a, uint32_t k) {
94    uint64_t l0 = (a.lo & 0xffffffffu) * k, l1 = (a.lo >> 32) * k + (l0 >> 32);
95    uint64_t h0 = (a.hi & 0xffffffffu) * k + (l1 >> 32), h1 = (a.hi >> 32) * k + (h0 >> 32);
96    return U128{(h1 << 32) | (h0 & 0xffffffffu), (l1 << 32) | (l0 & 0xffffffffu)};
97}
98
99static const U128 LN2  = {0x00b17217f7d1cf79ull, 0xabc9e3b39803f2f7ull};   // ln 2   * 2^120
100static const U128 PIO2 = {0x01921fb54442d184ull, 0x69898cc51701b83aull};   // pi/2   * 2^120
101static const U128 ONE  = {0x0100000000000000ull, 0};                       // 1      * 2^120
102
103static inline uint64_t dbits(double d) { uint64_t b; std::memcpy(&b, &d, 8); return b; }
104static inline double bitsd(uint64_t b) { double d; std::memcpy(&d, &b, 8); return d; }
105static inline uint32_t fbits(float f) { uint32_t b; std::memcpy(&b, &f, 4); return b; }
106
107// a Q8.120 magnitude (> 0) rounded to the nearest double (ties to even); value = F * 2^-120
108static inline double fx_to_double(U128 f, bool neg) {
109    int p = msb(f);
110    if (p < 0) return neg ? -0.0 : 0.0;
111    uint64_t mant;
112    bool up = false;
113    if (p >= 52) {
114        int drop = p - 52;
115        U128 m = shr(f, drop);
116        mant = m.lo;
117        if (drop > 0) {
118            U128 rest = sub(f, shl(m, drop));
119            U128 half = shl(u128(0, 1), drop - 1);
120            if (lt(half, rest)) up = true;
121            else if (!lt(rest, half) && !lt(half, rest)) up = (mant & 1);   // exact tie
122        }
123    } else {
124        mant = shl(f, 52 - p).lo;
125    }
126    int e = p - 120;               // value = mant * 2^(e - 52)
127    if (up && ++mant == (1ull << 53)) { mant >>= 1; ++e; }
128    uint64_t bits = ((uint64_t) (e + 1023) << 52) | (mant & ((1ull << 52) - 1));
129    return bitsd(bits | (neg ? (1ull << 63) : 0));
130}
131
132#include "strata_noise_tables.inc"
133#ifndef STRATA_NOISE_NO_SIN_EXC
134#include "strata_sin_exc_data.inc"   // static const unsigned char STRATA_SIN_EXC_DATA[] (apply.py writes it)
135#endif
136
137// -log(u) as Q8.120 for a float u in (0, 1]
138// 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
139// |t| <= 2^-8, so the atanh series needs 8 terms for 2^-120 (ln c_j: the table)
140static inline U128 neglog_fx(float u) {
141    uint32_t b = fbits(u);
142    int e = (int) ((b >> 23) & 0xff) - 127;          // u is normal here (>= 2^-33)
143    uint32_t M = (b & 0x7fffff) | 0x800000;
144    U128 lnm{0, 0};
145    if (M != 0x800000) {
146        uint32_t j = (M - 0x800000u) >> 17;
147        uint32_t Cj = 0x800000u + (j << 17) + (1u << 16);
148        bool negt = M < Cj;
149        uint64_t num = negt ? Cj - M : M - Cj, den = (uint64_t) M + Cj, rem = num;
150        U128 t{0, 0};
151        for (int k = 0; k < 4; ++k) {                // t = num / den, 4 x 30-bit long-division steps
152            uint64_t q = (rem << 30) / den;
153            rem = (rem << 30) % den;
154            t = add(shl(t, 30), u128(0, q));
155        }
156        U128 t2 = mulfx(t, t), pw = t, sum{0, 0};
157        for (uint32_t k = 0; !is0(pw) && k < 40; ++k) {
158            sum = add(sum, divsmall(pw, 2 * k + 1));
159            pw = mulfx(pw, t2);
160        }
161        lnm = negt ? sub(LNC[j], shl(sum, 1)) : add(LNC[j], shl(sum, 1));
162    }
163    // -log u = (-e) ln2 - ln m ; e <= 0
164    return sub(mulsmall(LN2, (uint32_t) (-e)), lnm);
165}
166
167// sin and cos of a small d (|d| <= 1/128) as Q8.120 magnitudes (Taylor series)
168static inline U128 sin_small(U128 d) {
169    U128 x2 = mulfx(d, d), term = d, sum = d;
170    for (uint32_t k = 1; k < 20; ++k) {
171        term = divsmall(mulfx(term, x2), (2 * k) * (2 * k + 1));
172        if (is0(term)) break;
173        sum = (k & 1) ? sub(sum, term) : add(sum, term);
174    }
175    return sum;
176}
177static inline U128 cos_small(U128 d) {
178    U128 x2 = mulfx(d, d), term = ONE, sum = ONE;
179    for (uint32_t k = 1; k < 20; ++k) {
180        term = divsmall(mulfx(term, x2), (2 * k - 1) * (2 * k));
181        if (is0(term)) break;
182        sum = (k & 1) ? sub(sum, term) : add(sum, term);
183    }
184    return sum;
185}
186// sin(x) or cos(x) for x in [0, pi/4]: x = a + d with a = i/64 (table) and |d| <= 1/128
187static inline U128 sincos_fx(U128 x, bool want_cos) {
188    const U128 half = shl(u128(0, 1), 113);          // 1/128
189    const uint32_t i = (uint32_t) shr(add(x, half), 114).lo;
190    const U128 a = shl(u128(0, i), 114);
191    const bool dneg = lt(x, a);
192    const U128 d = dneg ? sub(a, x) : sub(x, a);
193    const U128 sd = sin_small(d), cd = cos_small(d);
194    const U128 p = mulfx(want_cos ? COSA[i] : SINA[i], cd);
195    const U128 q = mulfx(want_cos ? SINA[i] : COSA[i], sd);
196    // 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
197    const bool plus = want_cos ? dneg : !dneg;
198    return plus ? add(p, q) : sub(p, q);
199}
200static inline U128 sin_fx(U128 x) { return sincos_fx(x, false); }
201static inline U128 cos_fx(U128 x) { return sincos_fx(x, true); }
202
203// sin(double(v)) rounded to double, for a float v in (0, 8)
204static inline double sin_cr(float v) {
205    uint32_t b = fbits(v);
206    int e = (int) ((b >> 23) & 0xff) - 127;
207    uint64_t M = (b & 0x7fffff) | 0x800000;          // v = M * 2^(e - 23), exact in Q8.120
208    U128 x = shl(u128(0, M), 120 - 23 + e);          // e >= -31 here, so the shift is >= 66
209    int q = 0;
210    while (!lt(x, PIO2)) { x = sub(x, PIO2); ++q; }  // q in 0..4: the largest v (6.2831855f) is just above 2 pi
211    // x in [0, pi/2): sin(v) = +sin x, +cos x, -sin x, -cos x for q = 0..3
212    U128 pio4 = shr(PIO2, 1);
213    bool use_cos = (q & 1) != 0;
214    U128 r;
215    if (lt(pio4, x)) {                               // use the complement pi/2 - x
216        U128 y = sub(PIO2, x);
217        r = use_cos ? sin_fx(y) : cos_fx(y);
218    } else {
219        r = use_cos ? cos_fx(x) : sin_fx(x);
220    }
221    return fx_to_double(r, (q & 2) != 0);
222}
223
224// sin(double(v)) as glibc (x86-64) returns it: the correctly rounded value, except at the v listed in
225// strata_sin_exc.bin, where glibc is one unit off.  The table is the compiled-in STRATA_SIN_EXC_DATA, decoded once
226// (magic "OWN5SEX1", uint32 count, then per entry a varint of ((bits - previous bits) << 1 | down)).
227struct SinExc { std::vector<uint32_t> keys; std::vector<uint8_t> down; };
228static inline SinExc decode_sin_exc(const unsigned char* d, size_t size) {
229    SinExc e;
230    if (size < 12 || std::memcmp(d, "OWN5SEX1", 8) != 0) { std::fprintf(stderr, "strata noise: bad table\n"); std::abort(); }
231    const uint32_t n = (uint32_t) d[8] | ((uint32_t) d[9] << 8) | ((uint32_t) d[10] << 16) | ((uint32_t) d[11] << 24);
232    size_t i = 12;
233    uint64_t prev = 0;
234    e.keys.reserve(n);
235    e.down.reserve(n);
236    for (uint32_t k = 0; k < n; ++k) {
237        uint64_t v = 0;
238        for (int sh = 0;; sh += 7) {
239            if (i >= size || sh > 56) { std::fprintf(stderr, "strata noise: bad table\n"); std::abort(); }
240            const uint8_t b = d[i++];
241            v |= (uint64_t) (b & 0x7f) << sh;
242            if (!(b & 0x80)) break;
243        }
244        prev += v >> 1;
245        e.keys.push_back((uint32_t) prev);
246        e.down.push_back((uint8_t) (v & 1));
247    }
248    if (i != size) { std::fprintf(stderr, "strata noise: bad table\n"); std::abort(); }
249    return e;
250}
251static inline const SinExc& sin_exc() {
252#ifdef STRATA_NOISE_NO_SIN_EXC
253    static const SinExc e;
254#else
255    static const SinExc e = decode_sin_exc(STRATA_SIN_EXC_DATA, sizeof STRATA_SIN_EXC_DATA);
256#endif
257    return e;
258}
259static inline double sin_x86(float v) {
260    double d = sin_cr(v);
261    const SinExc& e = sin_exc();
262    if (!e.keys.empty()) {
263        const uint32_t key = fbits(v);
264        size_t lo = 0, hi = e.keys.size();
265        while (lo < hi) {
266            const size_t mid = (lo + hi) / 2;
267            if (e.keys[mid] < key) lo = mid + 1; else hi = mid;
268        }
269        if (lo < e.keys.size() && e.keys[lo] == key)
270            d = bitsd(dbits(d) + (e.down[lo] ? (uint64_t) -1 : (uint64_t) 1));
271    }
272    return d;
273}
274
275// log(double(u)) rounded to double, for a float u in (0, 1]
276static inline double log_cr(float u) {
277    if (fbits(u) == 0x3f800000u) return 0.0;           // log 1 = +0
278    return fx_to_double(neglog_fx(u), true);
279}
280
281// 128-bit integer square root (floor)
282static inline U128 isqrt128(U128 n) {
283    U128 res{0, 0}, bit = shl(u128(0, 1), (msb(n) & ~1));
284    while (!is0(bit)) {
285        U128 rb = add(res, bit);
286        if (!lt(n, rb)) { n = sub(n, rb); res = add(shr(res, 1), bit); }
287        else res = shr(res, 1);
288        bit = shr(bit, 2);
289    }
290    return res;
291}
292// sqrt(d) correctly rounded (ties to even) for a positive normal double d, with integers only
293static inline double sqrt_cr(double d) {
294    uint64_t b = dbits(d);
295    int E = (int) ((b >> 52) & 0x7ff) - 1075;         // d = mant * 2^E
296    uint64_t mant = (b & ((1ull << 52) - 1)) | (1ull << 52);
297    if (E & 1) { mant <<= 1; E -= 1; }               // even exponent
298    U128 n = shl(u128(0, mant), 56);                 // n = mant * 2^56, isqrt has 54-55 bits
299    U128 q = isqrt128(n);
300    bool exact = is0(sub(n, mulfx(shl(q, 60), shl(q, 60))));   // q^2 == n ?  (q < 2^56: (q<<60)^2 >> 120 = q^2)
301    int p = msb(q);                                  // 54 or 55 -> round to 53 bits
302    int drop = p - 52;
303    uint64_t qm = q.lo >> drop, rest = q.lo & ((1ull << drop) - 1), half = 1ull << (drop - 1);
304    bool up = rest > half || (rest == half && (!exact || (qm & 1)));
305    int e = E / 2 - 28 + drop;                       // value = qm * 2^e
306    if (up && ++qm == (1ull << 53)) { qm >>= 1; ++e; }
307    uint64_t bits = ((uint64_t) (e + 52 + 1023) << 52) | (qm & ((1ull << 52) - 1));
308    return bitsd(bits);
309}
310
311// one Box-Muller value as sd.cpp's x86 GCC build computes it
312static inline float box_muller(uint32_t cx, uint32_t cy) {
313    const float x = (float) cx, y = (float) cy;
314    // u: float(x) * 2^-32 is exact; + 2^-33 is one float add
315    volatile float ux = (float) ((double) x * 0x1p-32);
316    const float u = ux + 0x1p-33f;
317    // v: the float product y * C rounded once (exact in double first), then one float add
318    const float C = 0x1p-32f * 6.2831855f;
319    volatile float vy = (float) ((double) y * (double) C);
320    const float v = vy + C / 2;
321    const double L = log_cr(u);
322    float s;
323    if (L == 0.0) s = -0.0f;                          // sqrt(-2 * +0.0) = sqrt(-0.0) = -0.0, as in the reference
324    else s = (float) sqrt_cr(-2.0 * L);
325    return (float) ((double) s * sin_x86(v));
326}
327
328// PhiloxRNG::randn(n) after manual_seed(seed), first call (offset 0); the k-th call uses offset k
329static inline std::vector<float> randn(uint64_t seed, uint32_t n, uint32_t offset = 0) {
330    std::vector<float> out(n);
331    const uint32_t M0 = 0xD2511F53u, M1 = 0xCD9E8D57u, W0 = 0x9E3779B9u, W1 = 0xBB67AE85u;
332    for (uint32_t i = 0; i < n; ++i) {
333        uint32_t c0 = offset, c1 = 0, c2 = i, c3 = 0;
334        uint32_t k0 = (uint32_t) seed, k1 = (uint32_t) (seed >> 32);
335        for (int r = 0; r < 10; ++r) {
336            uint64_t v1 = (uint64_t) c0 * M0, v2 = (uint64_t) c2 * M1;
337            uint32_t n0 = (uint32_t) (v2 >> 32) ^ c1 ^ k0, n1 = (uint32_t) v2;
338            uint32_t n2 = (uint32_t) (v1 >> 32) ^ c3 ^ k1, n3 = (uint32_t) v1;
339            c0 = n0; c1 = n1; c2 = n2; c3 = n3;
340            if (r < 9) { k0 += W0; k1 += W1; }
341        }
342        out[i] = box_muller(c0, c1);
343    }
344    return out;
345}
346
347}  // namespace strata_noise