okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
150c2394f
main
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 ) { 48if (n == 0 )return a ; 49if (n >=64 )return U128 {a .lo << (n - 64 ),0 }; 50return U128 {(a .hi <<n ) | (a .lo >> (64 - n )),a .lo <<n }; 51} 52static inline U128 shr (U128 a ,int n ) { 53if (n == 0 )return a ; 54if (n >=64 )return U128 {0 ,a .hi >> (n - 64 )}; 55return 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 58int n = 127 ; 59uint64_t w = a .hi ; 60if (!w ) {w = a .lo ;n = 63 ;if (!w )return -1 ; } 61while (!(w >>63 )) {w <<=1 ;-- n ; } 62return n ; 63} 64// (a * b) >> 120 (Q8.120 product, truncated), with 32-bit limbs 65static inline U128 mulfx (U128 a ,U128 b ) { 66uint32_t x [4 ]= {(uint32_t )a .lo , (uint32_t ) (a .lo >>32 ), (uint32_t )a .hi , (uint32_t ) (a .hi >>32 )}; 67uint32_t y [4 ]= {(uint32_t )b .lo , (uint32_t ) (b .lo >>32 ), (uint32_t )b .hi , (uint32_t ) (b .hi >>32 )}; 68uint64_t r [8 ]= {0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 }; 69for (int i = 0 ;i < 4 ;++ i ) { 70uint64_t c = 0 ; 71for (int j = 0 ;j < 4 ;++ j ) { 72uint64_t t = (uint64_t )x [i ]* y [j ]+ r [i + j ]+ c ; 73r [i + j ]= t & 0xffffffffu ; 74c = t >>32 ; 75 } 76r [i + 4 ]= c ; 77 } 78uint64_t o [4 ]; 79for (int k = 0 ;k < 4 ;++ k )o [k ]= ((r [3 + k ] >>24 ) | (r [4 + k ] <<8 ))& 0xffffffffu ; 80return U128 {(o [3 ] <<32 ) |o [2 ], (o [1 ] <<32 ) |o [0 ]}; 81} 82static inline U128 divsmall (U128 a ,uint32_t d ) { 83uint32_t l [4 ]= {(uint32_t ) (a .hi >>32 ), (uint32_t )a .hi , (uint32_t ) (a .lo >>32 ), (uint32_t )a .lo }; 84uint64_t rem = 0 ; 85uint32_t q [4 ]; 86for (int i = 0 ;i < 4 ;++ i ) { 87uint64_t cur = (rem <<32 ) |l [i ]; 88q [i ]= (uint32_t ) (cur /d ); 89rem = cur %d ; 90 } 91return 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 ) { 94uint64_t l0 = (a .lo & 0xffffffffu )* k ,l1 = (a .lo >>32 )* k + (l0 >>32 ); 95uint64_t h0 = (a .hi & 0xffffffffu )* k + (l1 >>32 ),h1 = (a .hi >>32 )* k + (h0 >>32 ); 96return 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 ) { 109int p = msb (f ); 110if (p < 0 )return neg ?-0.0 :0.0 ; 111uint64_t mant ; 112bool up = false; 113if (p >=52 ) { 114int drop = p - 52 ; 115U128 m = shr (f ,drop ); 116mant = m .lo ; 117if (drop > 0 ) { 118U128 rest = sub (f ,shl (m ,drop )); 119U128 half = shl (u128 (0 ,1 ),drop - 1 ); 120if (lt (half ,rest ))up = true; 121else if (!lt (rest ,half )&& !lt (half ,rest ))up = (mant & 1 );// exact tie 122 } 123 }else { 124mant = shl (f ,52 - p ).lo ; 125 } 126int e = p - 120 ;// value = mant * 2^(e - 52) 127if (up && ++ mant == (1ull <<53 )) {mant >>=1 ;++ e ; } 128uint64_t bits = ((uint64_t ) (e + 1023 ) <<52 ) | (mant & ((1ull <<52 )- 1 )); 129return 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 ) { 141uint32_t b = fbits (u ); 142int e = (int ) ((b >>23 )& 0xff )- 127 ;// u is normal here (>= 2^-33) 143uint32_t M = (b & 0x7fffff ) |0x800000 ; 144U128 lnm {0 ,0 }; 145if (M != 0x800000 ) { 146uint32_t j = (M - 0x800000u ) >>17 ; 147uint32_t Cj = 0x800000u + (j <<17 )+ (1u <<16 ); 148bool negt = M < Cj ; 149uint64_t num = negt ?Cj - M :M - Cj ,den = (uint64_t )M + Cj ,rem = num ; 150U128 t {0 ,0 }; 151for (int k = 0 ;k < 4 ;++ k ) {// t = num / den, 4 x 30-bit long-division steps 152uint64_t q = (rem <<30 ) /den ; 153rem = (rem <<30 ) %den ; 154t = add (shl (t ,30 ),u128 (0 ,q )); 155 } 156U128 t2 = mulfx (t ,t ),pw = t ,sum {0 ,0 }; 157for (uint32_t k = 0 ; !is0 (pw )&& k < 40 ;++ k ) { 158sum = add (sum ,divsmall (pw ,2 * k + 1 )); 159pw = mulfx (pw ,t2 ); 160 } 161lnm = negt ?sub (LNC [j ],shl (sum ,1 )) :add (LNC [j ],shl (sum ,1 )); 162 } 163// -log u = (-e) ln2 - ln m ; e <= 0 164return 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 ) { 169U128 x2 = mulfx (d ,d ),term = d ,sum = d ; 170for (uint32_t k = 1 ;k < 20 ;++ k ) { 171term = divsmall (mulfx (term ,x2 ), (2 * k )* (2 * k + 1 )); 172if (is0 (term ))break ; 173sum = (k & 1 ) ?sub (sum ,term ) :add (sum ,term ); 174 } 175return sum ; 176} 177static inline U128 cos_small (U128 d ) { 178U128 x2 = mulfx (d ,d ),term = ONE ,sum = ONE ; 179for (uint32_t k = 1 ;k < 20 ;++ k ) { 180term = divsmall (mulfx (term ,x2 ), (2 * k - 1 )* (2 * k )); 181if (is0 (term ))break ; 182sum = (k & 1 ) ?sub (sum ,term ) :add (sum ,term ); 183 } 184return 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 ) { 188const U128 half = shl (u128 (0 ,1 ),113 );// 1/128 189const uint32_t i = (uint32_t )shr (add (x ,half ),114 ).lo ; 190const U128 a = shl (u128 (0 ,i ),114 ); 191const bool dneg = lt (x ,a ); 192const U128 d = dneg ?sub (a ,x ) :sub (x ,a ); 193const U128 sd = sin_small (d ),cd = cos_small (d ); 194const U128 p = mulfx (want_cos ?COSA [i ] :SINA [i ],cd ); 195const 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 197const bool plus = want_cos ?dneg : !dneg ; 198return 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 ) { 205uint32_t b = fbits (v ); 206int e = (int ) ((b >>23 )& 0xff )- 127 ; 207uint64_t M = (b & 0x7fffff ) |0x800000 ;// v = M * 2^(e - 23), exact in Q8.120 208U128 x = shl (u128 (0 ,M ),120 - 23 + e );// e >= -31 here, so the shift is >= 66 209int q = 0 ; 210while (!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 212U128 pio4 = shr (PIO2 ,1 ); 213bool use_cos = (q & 1 )!= 0 ; 214U128 r ; 215if (lt (pio4 ,x )) {// use the complement pi/2 - x 216U128 y = sub (PIO2 ,x ); 217r = use_cos ?sin_fx (y ) :cos_fx (y ); 218 }else { 219r = use_cos ?cos_fx (x ) :sin_fx (x ); 220 } 221return 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 ) { 229SinExc e ; 230if (size < 12 || std::memcmp (d ,"OWN5SEX1" ,8 )!= 0 ) { std::fprintf (stderr ,"strata noise: bad table\n" ); std::abort (); } 231const uint32_t n = (uint32_t )d [8 ] | ((uint32_t )d [9 ] <<8 ) | ((uint32_t )d [10 ] <<16 ) | ((uint32_t )d [11 ] <<24 ); 232size_t i = 12 ; 233uint64_t prev = 0 ; 234e .keys .reserve (n ); 235e .down .reserve (n ); 236for (uint32_t k = 0 ;k < n ;++ k ) { 237uint64_t v = 0 ; 238for (int sh = 0 ;;sh += 7 ) { 239if (i >=size || sh > 56 ) { std::fprintf (stderr ,"strata noise: bad table\n" ); std::abort (); } 240const uint8_t b = d [i ++ ]; 241v |= (uint64_t ) (b & 0x7f ) <<sh ; 242if (!(b & 0x80 ))break ; 243 } 244prev += v >>1 ; 245e .keys .push_back ((uint32_t )prev ); 246e .down .push_back ((uint8_t ) (v & 1 )); 247 } 248if (i != size ) { std::fprintf (stderr ,"strata noise: bad table\n" ); std::abort (); } 249return e ; 250} 251static inline const SinExc & sin_exc () { 252#ifdef STRATA_NOISE_NO_SIN_EXC 253static const SinExc e ; 254#else 255static const SinExc e = decode_sin_exc (STRATA_SIN_EXC_DATA ,sizeof STRATA_SIN_EXC_DATA ); 256#endif 257return e ; 258} 259static inline double sin_x86 (float v ) { 260double d = sin_cr (v ); 261const SinExc & e = sin_exc (); 262if (!e .keys .empty ()) { 263const uint32_t key = fbits (v ); 264size_t lo = 0 ,hi = e .keys .size (); 265while (lo < hi ) { 266const size_t mid = (lo + hi ) /2 ; 267if (e .keys [mid ]< key )lo = mid + 1 ;else hi = mid ; 268 } 269if (lo < e .keys .size ()&& e .keys [lo ]== key ) 270d = bitsd (dbits (d )+ (e .down [lo ] ? (uint64_t )-1 : (uint64_t )1 )); 271 } 272return d ; 273} 274 275// log(double(u)) rounded to double, for a float u in (0, 1] 276static inline double log_cr (float u ) { 277if (fbits (u )== 0x3f800000u )return 0.0 ;// log 1 = +0 278return fx_to_double (neglog_fx (u ), true); 279} 280 281// 128-bit integer square root (floor) 282static inline U128 isqrt128 (U128 n ) { 283U128 res {0 ,0 },bit = shl (u128 (0 ,1 ), (msb (n )& ~1 )); 284while (!is0 (bit )) { 285U128 rb = add (res ,bit ); 286if (!lt (n ,rb )) {n = sub (n ,rb );res = add (shr (res ,1 ),bit ); } 287else res = shr (res ,1 ); 288bit = shr (bit ,2 ); 289 } 290return 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 ) { 294uint64_t b = dbits (d ); 295int E = (int ) ((b >>52 )& 0x7ff )- 1075 ;// d = mant * 2^E 296uint64_t mant = (b & ((1ull <<52 )- 1 )) | (1ull <<52 ); 297if (E & 1 ) {mant <<=1 ;E -= 1 ; }// even exponent 298U128 n = shl (u128 (0 ,mant ),56 );// n = mant * 2^56, isqrt has 54-55 bits 299U128 q = isqrt128 (n ); 300bool exact = is0 (sub (n ,mulfx (shl (q ,60 ),shl (q ,60 ))));// q^2 == n ? (q < 2^56: (q<<60)^2 >> 120 = q^2) 301int p = msb (q );// 54 or 55 -> round to 53 bits 302int drop = p - 52 ; 303uint64_t qm = q .lo >>drop ,rest = q .lo & ((1ull <<drop )- 1 ),half = 1ull << (drop - 1 ); 304bool up = rest > half || (rest == half && (!exact || (qm & 1 ))); 305int e = E /2 - 28 + drop ;// value = qm * 2^e 306if (up && ++ qm == (1ull <<53 )) {qm >>=1 ;++ e ; } 307uint64_t bits = ((uint64_t ) (e + 52 + 1023 ) <<52 ) | (qm & ((1ull <<52 )- 1 )); 308return 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 ) { 313const float x = (float )cx ,y = (float )cy ; 314// u: float(x) * 2^-32 is exact; + 2^-33 is one float add 315volatile float ux = (float ) ((double )x * 0x1p-32 ); 316const float u = ux + 0x1p-33f ; 317// v: the float product y * C rounded once (exact in double first), then one float add 318const float C = 0x1p-32f * 6.2831855f ; 319volatile float vy = (float ) ((double )y * (double )C ); 320const float v = vy + C /2 ; 321const double L = log_cr (u ); 322float s ; 323if (L == 0.0 )s = -0.0f ;// sqrt(-2 * +0.0) = sqrt(-0.0) = -0.0, as in the reference 324else s = (float )sqrt_cr (-2.0 * L ); 325return (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 ); 331const uint32_t M0 = 0xD2511F53u ,M1 = 0xCD9E8D57u ,W0 = 0x9E3779B9u ,W1 = 0xBB67AE85u ; 332for (uint32_t i = 0 ;i < n ;++ i ) { 333uint32_t c0 = offset ,c1 = 0 ,c2 = i ,c3 = 0 ; 334uint32_t k0 = (uint32_t )seed ,k1 = (uint32_t ) (seed >>32 ); 335for (int r = 0 ;r < 10 ;++ r ) { 336uint64_t v1 = (uint64_t )c0 * M0 ,v2 = (uint64_t )c2 * M1 ; 337uint32_t n0 = (uint32_t ) (v2 >>32 ) ^c1 ^k0 ,n1 = (uint32_t )v2 ; 338uint32_t n2 = (uint32_t ) (v1 >>32 ) ^c3 ^k1 ,n3 = (uint32_t )v1 ; 339c0 = n0 ;c1 = n1 ;c2 = n2 ;c3 = n3 ; 340if (r < 9 ) {k0 += W0 ;k1 += W1 ; } 341 } 342out [i ]= box_muller (c0 ,c1 ); 343 } 344return out ; 345} 346 347}// namespace strata_noise