okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-029-gdn-cuda4746bfb16

main
10.6 KiB245 linesraw
1// tests/gdn/gdn_fixture.hpp - backend-independent fixtures and an FP64 oracle for the Flash-Next GDN prompt path.
2//
3// Plain C++17, no GPU headers: the CUDA harness (src/prefill/gdn_harness.cu) uses it today; the HIP and Metal/SYCL
4// harnesses are meant to include the same file, so every backend is judged against the same inputs and the same
5// reference.  Contract: docs/GDN_CONTRACT.md (shapes, layouts, what a candidate may change).
6//
7//   Fixture       raw inputs of one layer for T tokens: qkv [T][C], ab [T][2 HV], dt, ssm_a, conv_w [C][4], conv
8//                 history [C][3], the recurrent state [S][HV][S] (row, head, column), z [T][HV][S], gamma [S]
9//   RefResult     FP64 oracle for some value heads over the whole sequence: normalised output (what the out
10//                 projection reads, before the FP16 rounding), the final state of those heads, the conv history
11//   ErrStat       max_abs, normalized_max (max_abs / max|ref|), relative_L2 (gdn-research 06)
12// The oracle starts from the RAW inputs (conv, SiLU, L2 norm, gates, recurrence, output norm), so a bug shared by a
13// kernel and a test copy of it cannot hide.
14#pragma once
15
16#include <algorithm>
17#include <cmath>
18#include <cstdint>
19#include <cstdio>
20#include <cstring>
21#include <thread>
22#include <vector>
23
24namespace gdnfx {
25
26constexpr int S = 128, HK = 16, HV = 48, VPK = HV / HK, C = 2 * HK * S + HV * S;   // C = 10240
27constexpr float EPS = 1e-6f;                                                      // the engine's L2 / RMS epsilon
28
29struct Rng {   // splitmix64: identical on every platform and compiler
30    uint64_t s;
31    explicit Rng(uint64_t seed) : s(seed * 0x9E3779B97F4A7C15ULL + 0x1234567ULL) {}
32    uint64_t next() {
33        uint64_t z = (s += 0x9E3779B97F4A7C15ULL);
34        z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
35        z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
36        return z ^ (z >> 31);
37    }
38    double uni() { return (double) (next() >> 11) * (1.0 / 9007199254740992.0); }   // [0, 1)
39    double gauss() {
40        double u1 = uni(), u2 = uni();
41        if (u1 < 1e-300) u1 = 1e-300;
42        return std::sqrt(-2.0 * std::log(u1)) * std::cos(6.283185307179586 * u2);
43    }
44};
45
46struct FixtureSpec {
47    int64_t T = 0;
48    uint64_t seed = 1;
49    // state0: "random" (as after an earlier prompt chunk), "zero" (a fresh conversation), "big", "small"
50    const char* state = "random";
51    float v_scale = 1.0f;       // values x this (50: range stress)
52    float gate_scale = 1.0f;    // ssm_a x this (0.005: near-zero decay, 3: strong decay)
53    bool coherent_keys = false; // every token's k is a head constant plus a small variation (T = (I+A)^-1 large)
54    bool alt_beta = false;      // beta alternates 0.02 / 0.98 per token (endpoint regime)
55    bool tiny_k = false;        // every 7th token's k/q channels are ~1e-4 before the L2 norm (eps matters)
56};
57
58struct Fixture {
59    FixtureSpec spec;
60    int64_t T = 0;
61    std::vector<float> qkv, ab, dt, ssm_a, conv_w, hist, state0, z, gamma;
62};
63
64inline Fixture make_fixture(const FixtureSpec& sp) {
65    Fixture f;
66    f.spec = sp;
67    f.T = sp.T;
68    const int64_t T = sp.T;
69    Rng r(sp.seed);
70    f.qkv.resize((size_t) T * C);
71    f.ab.resize((size_t) T * 2 * HV);
72    f.dt.resize(HV);
73    f.ssm_a.resize(HV);
74    f.conv_w.resize((size_t) C * 4);
75    f.hist.resize((size_t) C * 3);
76    f.state0.resize((size_t) S * HV * S);
77    f.z.resize((size_t) T * HV * S);
78    f.gamma.resize(S);
79    for (auto& x : f.qkv) x = (float) r.gauss();
80    if (sp.coherent_keys) {
81        std::vector<float> base((size_t) HK * S);
82        for (auto& x : base) x = (float) r.gauss();
83        for (int64_t t = 0; t < T; ++t)
84            for (int i = 0; i < HK * S; ++i) {
85                float& x = f.qkv[(size_t) t * C + HK * S + i];   // k channels
86                x = base[i] + 0.05f * x;
87            }
88    }
89    if (sp.tiny_k)
90        for (int64_t t = 0; t < T; t += 7)
91            for (int i = 0; i < 2 * HK * S; ++i) f.qkv[(size_t) t * C + i] *= 1e-4f;
92    if (sp.v_scale != 1.0f)
93        for (int64_t t = 0; t < T; ++t)
94            for (int i = 0; i < HV * S; ++i) f.qkv[(size_t) t * C + 2 * HK * S + i] *= sp.v_scale;
95    for (auto& x : f.ab) x = (float) r.gauss();
96    if (sp.alt_beta)
97        for (int64_t t = 0; t < T; ++t)
98            for (int h = 0; h < HV; ++h) f.ab[(size_t) t * 2 * HV + HV + h] = (t & 1) ? 3.9f : -3.9f;
99    for (int h = 0; h < HV; ++h) {
100        f.dt[h] = (float) (0.5 * r.gauss() - 0.5);
101        const double u = r.uni();
102        f.ssm_a[h] = (float) (-(0.05 + 1.5 * u * u) * sp.gate_scale);
103    }
104    for (auto& x : f.conv_w) x = (float) (0.35 * r.gauss());
105    for (auto& x : f.hist) x = (float) r.gauss();
106    for (auto& x : f.z) x = (float) r.gauss();
107    for (auto& x : f.gamma) x = (float) (1.0 + 0.1 * r.gauss());
108    float ss = 0.05f;
109    if (!std::strcmp(sp.state, "zero")) ss = 0.0f;
110    else if (!std::strcmp(sp.state, "big")) ss = 2.5f;
111    else if (!std::strcmp(sp.state, "small")) ss = 5e-4f;
112    for (auto& x : f.state0) x = ss == 0.0f ? 0.0f : (float) (ss * r.gauss());
113    return f;
114}
115
116// ------------------------------------------------------------------------------------------------ FP64 oracle
117inline double sigm(double x) { return 1.0 / (1.0 + std::exp(-x)); }
118
119struct RefResult {
120    std::vector<int> heads;                 // value heads computed
121    std::vector<std::vector<double>> y;     // per head: [T][S] normalised output (before FP16)
122    std::vector<std::vector<double>> state; // per head: final [S][S] (row, column)
123    std::vector<float> hist;                // conv history after the whole sequence (exact: copies of inputs)
124};
125
126// One value head over tokens [0, T).  state_io: that head's [S][S] (row, column), updated in place.
127inline void ref_head(const Fixture& f, int vh, std::vector<double>& st, std::vector<double>& y) {
128    const int64_t T = f.T;
129    const int qh = vh % HK;
130    y.assign((size_t) T * S, 0.0);
131    std::vector<double> q(S), k(S), v(S), kv(S), delta(S), o(S);
132    auto in = [&](int64_t t, int c) -> double {
133        return t >= 0 ? (double) f.qkv[(size_t) t * C + c] : (double) f.hist[(size_t) c * 3 + (int) (t + 3)];
134    };
135    auto conv = [&](int64_t t, int c) -> double {
136        const double s = (double) f.conv_w[(size_t) c * 4] * in(t - 3, c) + (double) f.conv_w[(size_t) c * 4 + 1] * in(t - 2, c) +
137                         (double) f.conv_w[(size_t) c * 4 + 2] * in(t - 1, c) + (double) f.conv_w[(size_t) c * 4 + 3] * in(t, c);
138        return s / (1.0 + std::exp(-s));
139    };
140    for (int64_t t = 0; t < T; ++t) {
141        double qq = 0, kk = 0;
142        for (int i = 0; i < S; ++i) {
143            q[i] = conv(t, qh * S + i);
144            k[i] = conv(t, HK * S + qh * S + i);
145            v[i] = conv(t, 2 * HK * S + vh * S + i);
146            qq += q[i] * q[i];
147            kk += k[i] * k[i];
148        }
149        const double qs = 1.0 / std::sqrt(qq + (double) EPS), ks = 1.0 / std::sqrt(kk + (double) EPS);
150        for (int i = 0; i < S; ++i) { q[i] *= qs; k[i] *= ks; }
151        const double a = (double) f.ab[(size_t) t * 2 * HV + vh] + (double) f.dt[vh];
152        const double sp = a > 20.0 ? a : std::log1p(std::exp(a));
153        const double g = std::exp(sp * (double) f.ssm_a[vh]);
154        const double beta = sigm((double) f.ab[(size_t) t * 2 * HV + HV + vh]);
155        for (int c = 0; c < S; ++c) kv[c] = 0;
156        for (int i = 0; i < S; ++i) {
157            const double* row = &st[(size_t) i * S];
158            for (int c = 0; c < S; ++c) kv[c] += row[c] * k[i];
159        }
160        for (int c = 0; c < S; ++c) delta[c] = (v[c] - g * kv[c]) * beta;
161        for (int c = 0; c < S; ++c) o[c] = 0;
162        for (int i = 0; i < S; ++i) {
163            double* row = &st[(size_t) i * S];
164            for (int c = 0; c < S; ++c) {
165                row[c] = g * row[c] + k[i] * delta[c];
166                o[c] += row[c] * q[i];
167            }
168        }
169        double ss = 0;
170        for (int c = 0; c < S; ++c) { o[c] /= std::sqrt((double) S); ss += o[c] * o[c]; }
171        const double rn = 1.0 / std::sqrt(ss / S + (double) EPS);
172        for (int c = 0; c < S; ++c)
173            y[(size_t) t * S + c] = o[c] * rn * (double) f.gamma[c] * sigm((double) f.z[((size_t) t * HV + vh) * S + c]);
174    }
175}
176
177// The oracle for `heads`, one thread each (state taken from the fixture's state0, layout [row][head][col]).
178inline RefResult ref_run(const Fixture& f, const std::vector<int>& heads) {
179    RefResult r;
180    r.heads = heads;
181    r.y.resize(heads.size());
182    r.state.resize(heads.size());
183    std::vector<std::thread> th;
184    for (size_t n = 0; n < heads.size(); ++n)
185        th.emplace_back([&, n] {
186            const int vh = heads[n];
187            std::vector<double> st((size_t) S * S);
188            for (int i = 0; i < S; ++i)
189                for (int c = 0; c < S; ++c) st[(size_t) i * S + c] = (double) f.state0[((size_t) i * HV + vh) * S + c];
190            ref_head(f, vh, st, r.y[n]);
191            r.state[n] = std::move(st);
192        });
193    for (auto& t : th) t.join();
194    r.hist.resize((size_t) C * 3);
195    for (int c = 0; c < C; ++c)
196        for (int k = 0; k < 3; ++k) {
197            const int64_t t = f.T - 3 + k;
198            r.hist[(size_t) c * 3 + k] = t >= 0 ? f.qkv[(size_t) t * C + c] : f.hist[(size_t) c * 3 + (int) (t + 3)];
199        }
200    return r;
201}
202
203// ------------------------------------------------------------------------------------------------ metrics
204struct ErrStat {
205    double max_abs = 0, ref_max = 0, sq_diff = 0, sq_ref = 0;
206    long nonfinite = 0, n = 0;
207    void add(double got, double ref) {
208        ++n;
209        if (!std::isfinite(got)) { ++nonfinite; return; }
210        const double d = std::fabs(got - ref);
211        if (d > max_abs) max_abs = d;
212        const double a = std::fabs(ref);
213        if (a > ref_max) ref_max = a;
214        sq_diff += d * d;
215        sq_ref += ref * ref;
216    }
217    double normalized_max() const { return max_abs / std::max(ref_max, 1e-30); }
218    double rel_l2() const { return std::sqrt(sq_diff) / std::max(std::sqrt(sq_ref), 1e-30); }
219};
220
221inline uint64_t fnv1a(const void* p, size_t bytes) {
222    const unsigned char* b = (const unsigned char*) p;
223    uint64_t h = 1469598103934665603ULL;
224    for (size_t i = 0; i < bytes; ++i) { h ^= b[i]; h *= 1099511628211ULL; }
225    return h;
226}
227
228inline float half_to_float(uint16_t h) {   // IEEE binary16 -> float, host side
229    const uint32_t sign = (uint32_t) (h >> 15) << 31;
230    uint32_t e = (h >> 10) & 0x1f, m = h & 0x3ff, out;
231    if (e == 0) {
232        if (m == 0) out = sign;
233        else {
234            e = 127 - 15 + 1;
235            while (!(m & 0x400)) { m <<= 1; --e; }
236            out = sign | (e << 23) | ((m & 0x3ff) << 13);
237        }
238    } else if (e == 31) out = sign | 0x7f800000u | (m << 13);
239    else out = sign | ((e + 112) << 23) | (m << 13);
240    float f;
241    std::memcpy(&f, &out, 4);
242    return f;
243}
244
245}  // namespace gdnfx