okami.mom/strata

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

waveringanaedge0-strata: add the engine for Edge0 145B and Edge0 120Bfd19246dc

main
14.2 KiB286 linesraw
1// src/kernels/gdn_chunk_parity.cpp - v100/gdn-chunk: the chunked GDN prompt recurrence vs the token recurrence
2// and a host reference (GPU, synthetic, no model).
3//
4// The chunked path (src/prefill/gdn_chunk.cu) computes the SAME recurrence in a different summation order:
5// a 64-token chunk becomes one triangular solve and a batch of matmuls instead of 64 sequential rank-1 steps.
6// That is FP32-level, NOT bit-exact - the precedent is qsa_prompt_attn.hpp.  So this test does not ask for
7// equality; it measures the error of both GPU paths against a double-precision transcription of the same
8// recurrence (`ref/gdn.py`'s, as re-pinned by gdn_parity) and asserts bounds:
9//
10//   1. the recurrence vs the host reference: the FP32 floor of the old path,
11//   2. the chunked path vs the host reference: the number that matters for the model,
12//   3. chunked vs recurrence directly: the observable switch STRATA_GDN_CHUNK flips.
13//
14// Both GPU paths go through the REAL dispatch (`gdn_recurrence`), A/B'd with the env switch, so the tail
15// (< 64 tokens) and the output norm are part of what is compared - the recurrence kernels' raw FP32 output for
16// the kernel comparisons (0.1.38's gdn_out_norm_kernel leaves it in place and writes only the FP16 copy), and
17// the norm's FP16 output once against the host reference's normalized values.
18#include "strata/prefill/gdn_chunk.hpp"
19#include "strata/prefill/kernels.hpp"
20
21#include <cuda_runtime.h>
22#include <cuda_fp16.h>
23
24#include <cmath>
25#include <cstdio>
26#include <cstdlib>
27#include <cstring>
28#include <limits>
29#include <string>
30#include <vector>
31
32#if defined(_WIN32)   // MSVC has no setenv / unsetenv
33#define setenv(k, v, o) _putenv_s((k), (v))
34#define unsetenv(k) _putenv_s((k), "")
35#endif
36
37namespace {
38
39constexpr int S = 128, HK = 16, HV = 48, C = 10240;
40
41void check(cudaError_t e, const char* what) {
42    if (e != cudaSuccess) {
43        std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
44        std::exit(1);
45    }
46}
47
48// the FP16 store's value back as FP32, for the one normalized-output comparison
49float half_to_float(uint16_t u) {
50    __half h;
51    std::memcpy(&h, &u, 2);
52    return __half2float(h);
53}
54
55// deterministic LCG - the same inputs on every machine and every run
56struct Rng {
57    uint64_t s;
58    explicit Rng(uint64_t seed) : s(seed) {}
59    float uni() {
60        s = s * 6364136223846793005ULL + 1442695040888963407ULL;
61        return (float) ((s >> 40) * (1.0 / 16777216.0));
62    }
63};
64
65/// The GDN chunk as a double-precision transcription of the recurrence in strata/kernels/gdn.hpp: the state
66/// (S, h_v, S) f32 layout, decay BEFORE the rank-1 update, modulo head pairing.  `yraw_out` is the raw output
67/// the recurrence kernels leave for gdn_out_norm_kernel; `y_out` is the norm's value, formed exactly as
68/// gdn_out_norm_kernel forms it (sqrt(S) in the oc scale, +eps on the SCALED squared norm).
69void ref_full(const std::vector<float>& st0, const std::vector<float>& h, const std::vector<float>& gate,
70              const std::vector<float>& beta, const std::vector<float>& z, const std::vector<float>& gamma,
71              float eps, int64_t T, std::vector<float>& yraw_out, std::vector<float>& y_out,
72              std::vector<float>& st_out) {
73    std::vector<double> st((size_t) S * HV * S);
74    for (size_t i = 0; i < st.size(); ++i) st[i] = (double) st0[i];
75    y_out.assign((size_t) T * HV * S, 0.0f);
76    yraw_out.assign((size_t) T * HV * S, 0.0f);
77    std::vector<double> o(S);
78    for (int64_t t = 0; t < T; ++t) {
79        for (int hh = 0; hh < HV; ++hh) {
80            const int qh = hh % HK;
81            const double dec = std::exp((double) gate[(size_t) t * HV + hh]);
82            const double b = (double) beta[(size_t) t * HV + hh];
83            for (int j = 0; j < S; ++j) {
84                double sk = 0.0;
85                for (int i = 0; i < S; ++i) sk += st[((size_t) i * HV + hh) * S + j] * (double) h[(size_t) t * C + HK * S + qh * S + i];
86                const double d = ((double) h[(size_t) t * C + 2 * HK * S + hh * S + j] - dec * sk) * b;
87                for (int i = 0; i < S; ++i) {
88                    double& w = st[((size_t) i * HV + hh) * S + j];
89                    w = dec * w + (double) h[(size_t) t * C + HK * S + qh * S + i] * d;
90                }
91                double dot = 0.0;
92                for (int i = 0; i < S; ++i) dot += st[((size_t) i * HV + hh) * S + j] * (double) h[(size_t) t * C + qh * S + i];
93                o[j] = dot / std::sqrt((double) S);  // the oc scale of gdn_rec_cols_kernel
94            }
95            double ss = 0.0;
96            for (int j = 0; j < S; ++j) ss += o[j] * o[j];
97            const double rs = 1.0 / std::sqrt(ss / (double) S + (double) eps);
98            for (int j = 0; j < S; ++j) {
99                yraw_out[((size_t) t * HV + hh) * S + j] = (float) o[j];
100                const double sig = 1.0 / (1.0 + std::exp(-(double) z[(size_t) t * HV * S + hh * S + j]));
101                y_out[((size_t) t * HV + hh) * S + j] = (float) (o[j] * rs * (double) gamma[j] * sig);
102            }
103        }
104    }
105    st_out.resize(st.size());
106    for (size_t i = 0; i < st.size(); ++i) st_out[i] = (float) st[i];
107}
108
109struct Err {
110    float abs_ = 0, rel_ = 0;
111    void see(float a, float b) {
112        const float d = std::fabs(a - b);
113        const float m = std::fabs(b);
114        // a NaN or inf anywhere is a hard error: an unordered comparison would otherwise leave the max at 0
115        if (!std::isfinite(a) || !std::isfinite(b)) {
116            abs_ = rel_ = std::numeric_limits<float>::infinity();
117            return;
118        }
119        if (d > abs_) abs_ = d;
120        const float r = d / (m + 1e-4f);
121        if (r > rel_) rel_ = r;
122    }
123};
124
125int failures = 0;
126
127void expect(const char* what, const Err& e, float bound_abs, float bound_rel) {
128    const bool ok = e.rel_ <= bound_rel && e.abs_ <= bound_abs;
129    std::printf("  %-38s max abs %.3e  max rel %.3e  (bounds abs %.1e rel %.1e) %s\n", what, e.abs_, e.rel_,
130                bound_abs, bound_rel, ok ? "ok" : "FAIL");
131    if (!ok) ++failures;
132}
133
134void run_case(int64_t T, uint64_t seed) {
135    std::printf("T = %lld%s\n", (long long) T, (T % 64) ? "  (tail: T % 64 != 0)" : "");
136    Rng rng(seed);
137    std::vector<float> h((size_t) T * C), gate((size_t) T * HV), beta((size_t) T * HV), z((size_t) T * HV * S),
138        gamma(S), st0((size_t) S * HV * S);
139    for (int64_t t = 0; t < T; ++t) {
140        for (int qh = 0; qh < HK; ++qh) {  // q and k: L2-normalised rows, as gdn_conv leaves them
141            for (int part = 0; part < 2; ++part) {
142                double ss = 0;
143                float row[S];
144                for (int i = 0; i < S; ++i) {
145                    row[i] = rng.uni() - 0.5f;
146                    ss += (double) row[i] * row[i];
147                }
148                const float nrm = (float) (1.0 / std::sqrt(ss + 1e-5));
149                for (int i = 0; i < S; ++i) h[(size_t) t * C + (part ? HK * S : 0) + qh * S + i] = row[i] * nrm;
150            }
151        }
152        for (int hh = 0; hh < HV; ++hh) {
153            for (int j = 0; j < S; ++j)  // v: O(1) rows
154                h[(size_t) t * C + 2 * HK * S + hh * S + j] = rng.uni() - 0.5f;
155            gate[(size_t) t * HV + hh] = -0.02f - 0.3f * rng.uni();
156            beta[(size_t) t * HV + hh] = 1.0f / (1.0f + std::exp(-(4.0f * rng.uni() - 2.0f)));
157            for (int j = 0; j < S; ++j) z[((size_t) t * HV + hh) * S + j] = 2.0f * rng.uni() - 1.0f;
158        }
159    }
160    for (int j = 0; j < S; ++j) gamma[j] = 0.5f + 2.0f * rng.uni();
161    for (size_t i = 0; i < st0.size(); ++i) st0[i] = 0.1f * (rng.uni() - 0.5f);
162    const float eps = 1e-5f;
163
164    std::vector<float> y_ref, yraw_ref, st_ref;
165    ref_full(st0, h, gate, beta, z, gamma, eps, T, yraw_ref, y_ref, st_ref);
166
167    float *d_st = nullptr, *d_h = nullptr, *d_g = nullptr, *d_b = nullptr, *d_z = nullptr, *d_ga = nullptr,
168          *d_y = nullptr, *d_st0 = nullptr;
169    uint16_t* d_y16 = nullptr;
170    check(cudaMalloc(&d_st, st0.size() * 4), "malloc");
171    check(cudaMalloc(&d_st0, st0.size() * 4), "malloc");
172    check(cudaMalloc(&d_h, h.size() * 4), "malloc");
173    check(cudaMalloc(&d_g, gate.size() * 4), "malloc");
174    check(cudaMalloc(&d_b, beta.size() * 4), "malloc");
175    check(cudaMalloc(&d_z, z.size() * 4), "malloc");
176    check(cudaMalloc(&d_ga, gamma.size() * 4), "malloc");
177    check(cudaMalloc(&d_y, y_ref.size() * 4), "malloc");
178    check(cudaMalloc(&d_y16, y_ref.size() * 2), "malloc");
179    check(cudaMemcpy(d_st0, st0.data(), st0.size() * 4, cudaMemcpyHostToDevice), "H2D");
180    check(cudaMemcpy(d_h, h.data(), h.size() * 4, cudaMemcpyHostToDevice), "H2D");
181    check(cudaMemcpy(d_g, gate.data(), gate.size() * 4, cudaMemcpyHostToDevice), "H2D");
182    check(cudaMemcpy(d_b, beta.data(), beta.size() * 4, cudaMemcpyHostToDevice), "H2D");
183    check(cudaMemcpy(d_z, z.data(), z.size() * 4, cudaMemcpyHostToDevice), "H2D");
184    check(cudaMemcpy(d_ga, gamma.data(), gamma.size() * 4, cudaMemcpyHostToDevice), "H2D");
185
186    std::vector<float> y_gpu(y_ref.size()), st_gpu(st0.size());
187    std::vector<float> y_rec(y_ref.size()), st_rec(st0.size()), y_warp(y_ref.size()), st_warp(st0.size()),
188        y_fast(y_ref.size()), st_fast(st0.size()), y_fma(y_ref.size()), st_fma(st0.size());
189    auto run = [&](const char* chunk, const char* warp, std::vector<float>& y, std::vector<float>& st,
190                   std::vector<float>* y16f = nullptr) {
191        setenv("STRATA_GDN_CHUNK", chunk, 1);
192        setenv("STRATA_GDN_REC_WARP", warp, 1);
193        check(cudaMemcpy(d_st, d_st0, st0.size() * 4, cudaMemcpyDeviceToDevice), "D2D");
194        strata::prefill::gdn_recurrence(d_st, d_h, d_g, d_b, d_z, d_ga, eps, d_y, d_y16, T, nullptr);
195        check(cudaDeviceSynchronize(), "sync");
196        check(cudaMemcpy(y.data(), d_y, y.size() * 4, cudaMemcpyDeviceToHost), "D2H");
197        check(cudaMemcpy(st.data(), d_st, st.size() * 4, cudaMemcpyDeviceToHost), "D2H");
198        if (y16f != nullptr) {
199            std::vector<uint16_t> h16(y.size());
200            check(cudaMemcpy(h16.data(), d_y16, h16.size() * 2, cudaMemcpyDeviceToHost), "D2H");
201            y16f->resize(y.size());
202            for (size_t i = 0; i < y.size(); ++i) (*y16f)[i] = half_to_float(h16[i]);
203        }
204    };
205    std::vector<float> y16_rec;
206    run("0", "0", y_rec, st_rec, &y16_rec);  // the old pipelined recurrence (+ the norm's FP16 output)
207    run("0", "1", y_warp, st_warp);  // the sync-free warp recurrence - must be BIT-EXACT vs the above
208    run("0", "2", y_fast, st_fast);  // the chain-split recurrence (the V100 default)
209    run("1", "0", y_gpu, st_gpu);    // the chunked path's wmma variant
210    run("2", "0", y_fma, st_fma);    // the chunked path's FP32 FMA variant
211
212    size_t bits = 0;
213    for (size_t i = 0; i < y_ref.size(); ++i)
214        if (std::memcmp(&y_rec[i], &y_warp[i], 4) != 0) ++bits;
215    for (size_t i = 0; i < st_ref.size(); ++i)
216        if (std::memcmp(&st_rec[i], &st_warp[i], 4) != 0) ++bits;
217    std::printf("  %-38s %s\n", "warp recurrence vs pipelined (bits)", bits ? "FAIL" : "bit-exact");
218    if (bits) ++failures;
219
220    Err e_yr, e_y, e_yf, e_ym, e_yc, e_yn, e_sr, e_s, e_sf, e_sm, e_sc;
221    for (size_t i = 0; i < y_ref.size(); ++i) {
222        e_yr.see(y_rec[i], yraw_ref[i]);
223        e_yf.see(y_fast[i], yraw_ref[i]);
224        e_ym.see(y_fma[i], yraw_ref[i]);
225        e_y.see(y_gpu[i], yraw_ref[i]);
226        e_yc.see(y_gpu[i], y_rec[i]);
227        e_yn.see(y16_rec[i], y_ref[i]);
228    }
229    for (size_t i = 0; i < st_ref.size(); ++i) {
230        e_sr.see(st_rec[i], st_ref[i]);
231        e_sf.see(st_fast[i], st_ref[i]);
232        e_sm.see(st_fma[i], st_ref[i]);
233        e_s.see(st_gpu[i], st_ref[i]);
234        e_sc.see(st_gpu[i], st_rec[i]);
235    }
236    // The bounds are the measured errors of this build on the V100 with ~3x margin (rel uses a 1e-4 floor on
237    // the reference magnitude).  The recurrence is the FP32 floor; the FMA chunked path reorders the sums
238    // (FP32-level, not bit-exact - qsa_prompt_attn.hpp's precedent); the wmma chunked path additionally
239    // stages q/k/v and the state through FP16 (the reference's f32 -> f16 staging), which is the error level
240    // llama.cpp-v100's FlashQLA sm70 path ships with.  The y rows compared here are the recurrence kernels'
241    // raw output (0.1.38's norm keeps its FP32 store out); the last line reads the norm's FP16 copy instead.
242    expect("recurrence vs host ref (y)", e_yr, 5e-6f, 1e-2f);
243    expect("chain-split recurrence (y)", e_yf, 1e-5f, 2e-2f);
244    expect("chunked FMA vs host ref (y)", e_ym, 1e-5f, 2e-2f);
245    expect("chunked wmma vs host ref (y)", e_y, 6e-3f, 5e1f);
246    expect("chunked wmma vs recurrence (y)", e_yc, 6e-3f, 5e1f);
247    expect("output norm (FP16) vs host ref (y)", e_yn, 8e-3f, 5e-2f);
248    expect("recurrence vs host ref (state)", e_sr, 1e-7f, 5e-4f);
249    expect("chain-split recurrence (state)", e_sf, 5e-7f, 2e-3f);
250    expect("chunked FMA vs host ref (state)", e_sm, 5e-7f, 2e-3f);
251    expect("chunked wmma vs host ref (state)", e_s, 3e-4f, 2e0f);
252    expect("chunked wmma vs recurrence (state)", e_sc, 3e-4f, 2e0f);
253
254    cudaFree(d_st); cudaFree(d_st0); cudaFree(d_h); cudaFree(d_g); cudaFree(d_b); cudaFree(d_z);
255    cudaFree(d_ga); cudaFree(d_y); cudaFree(d_y16);
256}
257
258}  // namespace
259
260int main(int argc, char** argv) {
261    bool selftest = false;
262    for (int i = 1; i < argc; ++i) {
263        if (std::strcmp(argv[i], "--selftest") == 0) selftest = true;
264        else { std::fprintf(stderr, "usage: gdn_chunk_parity [--selftest]\n"); return 2; }
265    }
266    {
267        // the kkt stage needs 2*64*129 floats (66 KB) of dynamic shared memory: a card whose opt-in limit is lower
268        // (Pascal: 48 KB) cannot launch it, and the engine dispatch never selects the chunked path there
269        int dev = 0, smem = 0;
270        cudaGetDevice(&dev);
271        cudaDeviceGetAttribute(&smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev);
272        if (smem < 2 * 64 * 129 * 4) {
273            std::printf("gdn_chunk_parity: the card's shared-memory opt-in (%d B) is below the kkt stage's need, skipped\n", smem);
274            return 77;
275        }
276    }
277    if (!strata::prefill::gdn_chunk_available())
278        std::printf("note: not a V100 (cc 7.0) - the parity still runs; the engine dispatch keeps the recurrence\n");
279    run_case(64, 1);
280    run_case(128, 2);
281    run_case(200, 3);  // tail: T % 64 = 8
282    run_case(320, 4);
283    std::printf("\ngdn_chunk: %d failures\n", failures);
284    if (selftest && failures == 0) std::printf("gdn_chunk_parity OK\n");
285    return failures ? 1 : 0;
286}