okami.mom/strata

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

bitaccesscomauExact two-pass QSA prompt selection (opt-in STRATA_SELECT_TWO_PASS=1)386f9959f

main
21.0 KiB442 linesraw
1// tests/prefill/qsa_two_pass_test.cpp - STRATA_SELECT_TWO_PASS without a GPU (qsa_two_pass.hpp).
2//
3// 1. TF32: the host copy of cvt.rna.tf32.f32 rounds to nearest, ties away from zero.
4// 2. The bound: for random and adversarial indexer queries and keys, the single-pass score S1 and the 3xTF32 score S3
5//    are computed from the same TF32 operands as the kernels, with each MMA modelled two ways - exact then rounded to
6//    nearest (the most accurate hardware), and aligned to the largest addend with every addend and the result
7//    truncated to 24 bits (no guard bits, the least accurate model) - and |S1 - S3| must stay within eps.  The exact
8//    cross term |qh.kl + ql.kh| must stay within its Cauchy-Schwarz part.
9// 3. The cut-off rule: rows of 3xTF32 scores, single-pass scores anywhere inside [S3 - eps, S3 + eps] (pushed across
10//    the threshold where possible), ties at the threshold, every tail weight, short and long rows (the sampled
11//    candidate threshold), the identity: a host copy of the band kernel picks the blocks to score again, and the
12//    top-k of the resulting row (block_topk_kernel's rule) must be the top-k of the 3xTF32 row, id for id.
13// Exits non-zero on the first failure.  No GPU, no model.
14#include "strata/kernels/qsa_two_pass.hpp"
15
16#include <algorithm>
17#include <cmath>
18#include <cstdint>
19#include <cstdio>
20#include <cstdlib>
21#include <cstring>
22#include <limits>
23#include <random>
24#include <vector>
25
26namespace tp = strata::kernels::two_pass;
27
28namespace {
29
30int g_fail = 0;
31#define CHECK(cond, ...)                                                    \
32    do {                                                                    \
33        if (!(cond)) {                                                      \
34            std::fprintf(stderr, "FAIL %s:%d: ", __FILE__, __LINE__);       \
35            std::fprintf(stderr, __VA_ARGS__);                              \
36            std::fprintf(stderr, "\n");                                     \
37            ++g_fail;                                                       \
38            if (g_fail > 20) std::exit(1);                                  \
39        }                                                                   \
40    } while (0)
41
42float up(double x) {   // the smallest float >= x (x finite and in range)
43    float f = (float) x;
44    if ((double) f < x) f = std::nextafter(f, std::numeric_limits<float>::infinity());
45    return f;
46}
47float down(double x) {
48    float f = (float) x;
49    if ((double) f > x) f = std::nextafter(f, -std::numeric_limits<float>::infinity());
50    return f;
51}
52
53// Shewchuk's exact summation (Python's math.fsum): the sum of doubles, correctly rounded
54double fsum(const std::vector<double>& xs) {
55    std::vector<double> p;
56    for (double x : xs) {
57        size_t i = 0;
58        for (double y : p) {
59            if (std::fabs(x) < std::fabs(y)) std::swap(x, y);
60            const double hi = x + y, lo = y - (hi - x);
61            if (lo != 0.0) p[i++] = lo;
62            x = hi;
63        }
64        p.resize(i);
65        p.push_back(x);
66    }
67    double s = 0.0;
68    for (size_t i = p.size(); i-- > 0;) s += p[i];   // the partials are non-overlapping: this is the rounded sum
69    return s;
70}
71
72// ---- 1. TF32
73void test_tf32() {
74    auto bits = [](float f) { uint32_t b; std::memcpy(&b, &f, 4); return b; };
75    CHECK(tp::tf32_rna_host(1.0f) == 1.0f, "1.0");
76    CHECK(tp::tf32_rna_host(1.0f + 0x1p-11f) == 1.0f + 0x1p-10f, "a tie rounds away from zero");
77    CHECK(tp::tf32_rna_host(-(1.0f + 0x1p-11f)) == -(1.0f + 0x1p-10f), "a negative tie rounds away from zero");
78    CHECK(tp::tf32_rna_host(1.0f + 0x1p-12f) == 1.0f, "below the tie rounds down");
79    CHECK((bits(tp::tf32_rna_host(3.14159265f)) & 0x1fffu) == 0u, "the low 13 bits are zero");
80    std::mt19937 rng(7);
81    std::normal_distribution<float> nd;
82    for (int i = 0; i < 100000; ++i) {
83        const float x = nd(rng) * std::ldexp(1.0f, (int) (rng() % 40) - 20);
84        const float h = tp::tf32_rna_host(x);
85        CHECK(std::fabs((double) x - (double) h) <= std::ldexp(std::fabs((double) x), -11), "TF32 error %g", (double) x);
86    }
87}
88
89// ---- 2. the bound
90struct Op { float h, l; };   // tf32(x), tf32(x - tf32(x)): the kernels' split
91Op split(float x) {
92    const float h = tp::tf32_rna_host(x);
93    return {h, tp::tf32_rna_host(x - h)};
94}
95
96// one MMA: the accumulator c plus 8 exact products
97float mma_rn(float c, const double* p) {
98    std::vector<double> t(p, p + 8);
99    t.push_back(c);
100    return (float) fsum(t);
101}
102float trunc_to(double v, int e) {   // toward zero to a multiple of 2^e
103    const double q = std::ldexp(1.0, e);
104    return (float) (std::trunc(v / q) * q);
105}
106float mma_trunc(float c, const double* p) {
107    double t[9];
108    for (int i = 0; i < 8; ++i) t[i] = p[i];
109    t[8] = c;
110    int emax = std::numeric_limits<int>::min();
111    for (double v : t)
112        if (v != 0.0) { int e; std::frexp(v, &e); emax = std::max(emax, e); }
113    if (emax == std::numeric_limits<int>::min()) return 0.0f;
114    std::vector<double> a;
115    for (double v : t) {   // every addend kept to 24 bits below the largest one's leading bit, toward zero
116        const double q = std::ldexp(1.0, emax - 24);
117        a.push_back(std::trunc(v / q) * q);
118    }
119    const double s = fsum(a);
120    if (s == 0.0) return 0.0f;
121    int e;
122    std::frexp(s, &e);
123    return trunc_to(s, e - 24);   // the result truncated to FP32's 24 bits
124}
125
126struct Pair { std::vector<float> q, k; };   // q: 4 heads x 128, k: 128
127
128// The scores the kernels compute, per model: S1 (qh*kh, 16 MMAs per head) and S3 (ql*kh, qh*kl, qh*kh per step).
129void scores(const Pair& x, bool trunc, float& s1, float& s3, double cross[4], double hn[4][2], double kn[2]) {
130    std::vector<Op> k(128);
131    for (int i = 0; i < 128; ++i) k[i] = split(x.k[i]);
132    double kh2 = 0, kl2 = 0;
133    for (int i = 0; i < 128; ++i) { kh2 += (double) k[i].h * k[i].h; kl2 += (double) k[i].l * k[i].l; }
134    kn[0] = std::sqrt(kh2);
135    kn[1] = std::sqrt(kl2);
136    s1 = s3 = 0.0f;
137    for (int h = 0; h < 4; ++h) {
138        std::vector<Op> q(128);
139        for (int i = 0; i < 128; ++i) q[i] = split(x.q[h * 128 + i]);
140        double qh2 = 0, ql2 = 0;
141        for (int i = 0; i < 128; ++i) { qh2 += (double) q[i].h * q[i].h; ql2 += (double) q[i].l * q[i].l; }
142        hn[h][0] = std::sqrt(qh2);
143        hn[h][1] = std::sqrt(ql2);
144        std::vector<double> d;
145        for (int i = 0; i < 128; ++i) { d.push_back((double) q[i].h * k[i].l); d.push_back((double) q[i].l * k[i].h); }
146        cross[h] = fsum(d);
147        float c1 = 0.0f, c3 = 0.0f;
148        for (int st = 0; st < 16; ++st) {
149            double p_hh[8], p_lh[8], p_hl[8];
150            for (int j = 0; j < 8; ++j) {
151                const int i = 8 * st + j;
152                p_hh[j] = (double) q[i].h * k[i].h;
153                p_lh[j] = (double) q[i].l * k[i].h;
154                p_hl[j] = (double) q[i].h * k[i].l;
155            }
156            c1 = trunc ? mma_trunc(c1, p_hh) : mma_rn(c1, p_hh);
157            c3 = trunc ? mma_trunc(c3, p_lh) : mma_rn(c3, p_lh);   // the kernel's order: al*bh, ah*bl, ah*bh
158            c3 = trunc ? mma_trunc(c3, p_hl) : mma_rn(c3, p_hl);
159            c3 = trunc ? mma_trunc(c3, p_hh) : mma_rn(c3, p_hh);
160        }
161        s1 += c1 > 0.0f ? c1 : 0.0f;
162        s3 += c3 > 0.0f ? c3 : 0.0f;
163    }
164}
165
166// eps as the band kernel forms it (norms rounded up, the coefficients and eps rounded up)
167float eps_of(const double hn[4][2], const double kn[2]) {
168    double a = 0, c = 0;
169    for (int h = 0; h < 4; ++h) { a += hn[h][0]; c += hn[h][1]; }
170    a = up(a) * (1 + 1e-12);
171    c = up(c) * (1 + 1e-12);
172    double P, Q;
173    tp::coefficients(a, c, P, Q);
174    const float Pf = up(P), Qf = up(Q), kh = up(kn[0] * (1 + 1e-12)), kl = up(kn[1] * (1 + 1e-12));
175    return up((double) Pf * kl + (double) Qf * kh + (double) tp::kAbs);
176}
177
178void test_bound() {
179    std::mt19937 rng(20261024);
180    std::normal_distribution<float> nd;
181    std::uniform_int_distribution<int> small(-3, 3), expo(-12, 12), coin(0, 9);
182    // the worst rounding: mantissas just below a TF32 tie, so |x - tf32(x)| is nearly 2^-11 |x|
183    auto worst = [&](float sign) {
184        uint32_t b = 0x3f800000u | ((rng() & 0x3ffu) << 13) | 0x0fffu;   // ...0 1111 1111 1111 in the dropped bits
185        float f;
186        std::memcpy(&f, &b, 4);
187        return sign * std::ldexp(f, expo(rng) / 4);
188    };
189    const char* names[] = {"normal", "wide magnitudes and zeros", "small integers", "aligned worst rounding (q = k)",
190                           "worst rounding, signs of k"};
191    for (int mode = 0; mode < 5; ++mode) {
192        double worst_ratio[2] = {0, 0}, worst_cross = 0;
193        const int N = mode >= 3 ? 1500 : 3000;
194        for (int n = 0; n < N; ++n) {
195            Pair x;
196            x.q.resize(512);
197            x.k.resize(128);
198            for (int i = 0; i < 128; ++i) {
199                float v;
200                if (mode == 0) v = nd(rng);
201                else if (mode == 1) v = coin(rng) == 0 ? 0.0f : std::ldexp(nd(rng), expo(rng));
202                else if (mode == 2) v = (float) small(rng);
203                else v = worst(nd(rng) > 0 ? 1.0f : -1.0f);
204                x.k[i] = v;
205            }
206            for (int h = 0; h < 4; ++h)
207                for (int i = 0; i < 128; ++i) {
208                    float v;
209                    if (mode == 0) v = nd(rng);
210                    else if (mode == 1) v = coin(rng) == 0 ? 0.0f : std::ldexp(nd(rng), expo(rng));
211                    else if (mode == 2) v = (float) small(rng);
212                    else if (mode == 3) v = x.k[i];   // every head aligned with k, lo parts too: Cauchy-Schwarz is tight
213                    else v = worst(x.k[i] > 0 ? 1.0f : -1.0f);   // independent worst roundings, positive dot products
214                    x.q[h * 128 + i] = v;
215                }
216            for (int model = 0; model < 2; ++model) {
217                float s1, s3;
218                double cross[4], hn[4][2], kn[2];
219                scores(x, model == 1, s1, s3, cross, hn, kn);
220                const float e = eps_of(hn, kn);
221                const double d = std::fabs((double) s1 - (double) s3);
222                CHECK(d <= (double) e, "%s, %s model: |S1 - S3| = %.9g > eps %.9g", names[mode],
223                      model ? "truncating" : "rounding", d, (double) e);
224                worst_ratio[model] = std::max(worst_ratio[model], d / (double) e);
225                if (model == 0)
226                    for (int h = 0; h < 4; ++h) {
227                        const double cb = hn[h][0] * kn[1] + hn[h][1] * kn[0];
228                        CHECK(std::fabs(cross[h]) <= cb * (1 + 1e-12) + 1e-300, "%s: cross term %.9g > %.9g", names[mode],
229                              std::fabs(cross[h]), cb);
230                        if (cb > 0) worst_cross = std::max(worst_cross, std::fabs(cross[h]) / cb);
231                    }
232            }
233        }
234        std::printf("bound, %-36s: largest |S1 - S3| / eps %.4f (rounding MMA), %.4f (truncating MMA); "
235                    "cross term / its bound %.4f\n", names[mode], worst_ratio[0], worst_ratio[1], worst_cross);
236    }
237}
238
239// ---- 3. the cut-off rule
240constexpr int R = 4;
241uint32_t key(float s) { return tp::order_key_host(s); }
242
243// the largest key k with (sum of weights of entries with key >= k) >= width (block_topk_kernel's threshold)
244uint32_t kth(std::vector<std::pair<uint32_t, int>> kw, int64_t width) {
245    std::sort(kw.begin(), kw.end(), [](auto& a, auto& b) { return a.first > b.first; });
246    int64_t c = 0;
247    for (auto& [k, w] : kw) {
248        c += w;
249        if (c >= width) return k;
250    }
251    return 0u;   // fewer cells than the width: the radix scan ends at digit 0 every pass
252}
253
254// block_topk_kernel's ids: cells of blocks above the threshold, and the first (width - above) tied cells by index
255std::vector<int32_t> topk(const std::vector<float>& sc, int64_t n_kv, int64_t n_bid, int64_t width) {
256    std::vector<int32_t> out;
257    if (n_kv <= width) {
258        for (int64_t j = 0; j < n_kv; ++j) out.push_back((int32_t) j);
259        return out;
260    }
261    auto weight = [&](int64_t b) { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
262    std::vector<std::pair<uint32_t, int>> kw;
263    for (int64_t b = 0; b <= n_bid; ++b)
264        if (weight(b)) kw.push_back({key(sc[b]), weight(b)});
265    const uint32_t thr = kth(kw, width);
266    int64_t above = 0;
267    for (int64_t b = 0; b <= n_bid; ++b)
268        if (weight(b) && key(sc[b]) > thr) above += weight(b);
269    int64_t eq_left = width - above;
270    for (int64_t b = 0; b <= n_bid; ++b) {
271        const int w = weight(b);
272        if (!w) continue;
273        const uint32_t k = key(sc[b]);
274        if (k > thr) for (int c = 0; c < w; ++c) out.push_back((int32_t) (b * R + c));
275        else if (k == thr) for (int c = 0; c < w && eq_left > 0; ++c, --eq_left) out.push_back((int32_t) (b * R + c));
276    }
277    return out;
278}
279
280struct Band { int mode = 0; std::vector<int64_t> again; int64_t cand = 0; };
281
282// the band kernel on the host (tp_band_kernel, qsa_select.cu): the same steps and constants
283Band band(const std::vector<float>& s1, const std::vector<float>& eps, int64_t n_kv, int64_t n_bid, int64_t width) {
284    Band r;
285    if (n_kv <= width) return r;
286    const int64_t nb = n_bid + 1;
287    const int w_tail = (int) (n_kv - n_bid * R);
288    auto interval = [&](int64_t b, float& lo, float& hi, float& e) {
289        e = eps[b];
290        lo = down((double) s1[b] - (double) e);
291        hi = up((double) s1[b] + (double) e);
292    };
293    float F = -std::numeric_limits<float>::infinity();
294    if (nb > tp::kCandCap) {
295        int64_t stride = tp::kSampleStride;
296        while ((nb + stride - 1) / stride > tp::kCandCap) stride *= 2;
297        const int64_t ns = (nb + stride - 1) / stride;
298        std::vector<std::pair<uint32_t, int>> kw;
299        for (int64_t i = 0; i < ns; ++i) {
300            const int64_t b = i * stride;
301            uint32_t k = 0u;
302            if (b < n_bid) { float lo, hi, e; interval(b, lo, hi, e); k = key(lo); }
303            else if (w_tail > 0) k = key(s1[b]);
304            kw.push_back({k, 1});
305        }
306        const int64_t ks = 2 * ((width + R * stride - 1) / (R * stride)) + 16;
307        const uint32_t fk = kth(kw, std::min(ks, ns));
308        if (fk != 0u) F = tp::key_float_host(fk);
309    }
310    std::vector<int64_t> cand;
311    int64_t wf = 0;
312    float E = 0.0f;
313    for (int64_t b = 0; b < nb; ++b) {
314        float lo, hi, e = 0.0f;
315        int w;
316        if (b < n_bid) { w = R; interval(b, lo, hi, e); }
317        else { w = w_tail; if (!w) continue; lo = hi = s1[b]; }
318        if (lo >= F) wf += w;
319        if (hi >= F) { cand.push_back(b); E = std::max(E, e); }
320    }
321    r.cand = (int64_t) cand.size();
322    if ((int64_t) cand.size() > tp::kCandCap || wf < width) { r.mode = 2; return r; }
323    std::vector<std::pair<uint32_t, int>> kw;
324    for (int64_t b : cand) kw.push_back({key(s1[b]), b < n_bid ? R : w_tail});
325    const float T1 = tp::key_float_host(kth(kw, width));
326    const float lo_b = std::max(down((double) T1 - (double) E), F), hi_b = up((double) T1 + (double) E);
327    int res[8] = {};
328    for (int64_t b : cand) {
329        if (b >= n_bid) continue;
330        float lo, hi, e;
331        interval(b, lo, hi, e);
332        if (hi >= lo_b && lo <= hi_b) { r.again.push_back(b); ++res[b & 7]; }
333    }
334    for (int x : res) if (x > tp::kResCap) { r.mode = 2; return r; }
335    r.mode = 1;
336    return r;
337}
338
339void test_rule() {
340    std::mt19937 rng(424242);
341    std::normal_distribution<double> nd;
342    std::uniform_real_distribution<double> ud(0.0, 1.0);
343    const int64_t sizes[] = {300, 512, 600, 1500, 4000, 5119, 5120, 5121, 9000, 20000, 65000};
344    const char* kinds[] = {"continuous", "small integers (ties)", "a plateau at the threshold", "eps wide against the spread",
345                           "heavy tail", "every score equal"};
346    int64_t rows = 0, full = 0, again = 0, cand = 0;
347    for (int kind = 0; kind < 6; ++kind) {
348        const int64_t rows0 = rows, full0 = full, again0 = again;
349        for (int64_t n_bid : sizes) {
350            for (int tail = 0; tail < 4; ++tail) {
351                for (int rep = 0; rep < (n_bid > 20000 ? 2 : 4); ++rep) {
352                    const int64_t n_kv = n_bid * R + tail, width = std::min<int64_t>(n_kv, 2048 + R - 1);
353                    std::vector<float> s3((size_t) n_bid + 1), s1((size_t) n_bid + 1), eps((size_t) n_bid + 1);
354                    // kind 0: continuous; 1: small integers (ties); 2: a plateau at the threshold; 3: eps wide
355                    // against the spread; 4: heavy tail; 5: every score equal
356                    for (int64_t b = 0; b < n_bid; ++b) {
357                        double v;
358                        if (kind == 1) v = (double) (int) (ud(rng) * 40);
359                        else if (kind == 2) v = ud(rng) < 0.3 ? 7.0 : 7.0 + nd(rng);
360                        else if (kind == 4) v = std::exp(2.0 * nd(rng));
361                        else if (kind == 5) v = 3.0;
362                        else v = std::max(0.0, 2.0 + nd(rng));
363                        s3[b] = (float) v;
364                        const double scale = kind == 3 ? 0.3 : (kind == 1 ? 0.6 : 0.002);
365                        eps[b] = (float) (scale * (0.5 + ud(rng)));
366                    }
367                    s3[n_bid] = tail ? 1e9f + (float) ud(rng) : (float) ud(rng);   // the tail: exact, +1e9 with cells
368                    eps[n_bid] = 0.0f;
369                    // the 3xTF32 threshold, to push single-pass scores across it
370                    const std::vector<int32_t> ref = topk(s3, n_kv, n_bid, width);
371                    std::vector<std::pair<uint32_t, int>> kw;
372                    for (int64_t b = 0; b <= n_bid; ++b) {
373                        const int w = b < n_bid ? R : tail;
374                        if (w) kw.push_back({key(s3[b]), w});
375                    }
376                    const float T = n_kv > width ? tp::key_float_host(kth(kw, width)) : 0.0f;
377                    for (int64_t b = 0; b < n_bid; ++b) {
378                        // S1 inside [S3 - eps, S3 + eps]: towards and across the threshold where it can, else random
379                        const double e = eps[b] * (1.0 - 1e-6);
380                        double d;
381                        if (rep % 2 == 0) d = (s3[b] >= T ? -e : e);
382                        else d = (2.0 * ud(rng) - 1.0) * e;
383                        s1[b] = (float) ((double) s3[b] + d);
384                        if (std::fabs((double) s1[b] - (double) s3[b]) > eps[b]) s1[b] = s3[b];
385                    }
386                    s1[n_bid] = s3[n_bid];
387                    const Band bd = band(s1, eps, n_kv, n_bid, width);
388                    std::vector<float> row = s1;
389                    if (bd.mode == 2) row = s3;
390                    for (int64_t b : bd.again) row[b] = s3[b];
391                    const std::vector<int32_t> got = topk(row, n_kv, n_bid, width);
392                    CHECK(got == ref, "kind %d, %lld blocks, tail %d, rep %d: ids differ (mode %d, %zu scored again)", kind,
393                          (long long) n_bid, tail, rep, bd.mode, bd.again.size());
394                    ++rows;
395                    full += bd.mode == 2;
396                    again += (int64_t) bd.again.size();
397                    cand += bd.cand;
398                }
399            }
400        }
401        std::printf("rule, %-28s: %3lld rows, %3lld scored again in full, %.1f blocks scored again per row\n", kinds[kind],
402                    (long long) (rows - rows0), (long long) (full - full0),
403                    rows > rows0 ? (double) (again - again0) / (double) (rows - rows0) : 0.0);
404    }
405    std::printf("rule: %lld rows, ids identical in every one; %lld scored again in full (the list or the bound could not "
406                "settle them), %.1f blocks scored again and %.0f candidates per row\n", (long long) rows, (long long) full,
407                rows ? (double) again / rows : 0.0, rows ? (double) cand / rows : 0.0);
408    // the guard bites: keep the single-pass score of one block whose interval reaches the threshold, and the ids move
409    {
410        const int64_t n_bid = 1000, n_kv = n_bid * R, width = 2048 + R - 1;
411        std::vector<float> s3((size_t) n_bid + 1), s1((size_t) n_bid + 1), eps((size_t) n_bid + 1, 0.01f);
412        for (int64_t b = 0; b < n_bid; ++b) s3[b] = 1.0f + 0.001f * (float) b;   // distinct, rising
413        s3[n_bid] = 0.0f;
414        eps[n_bid] = 0.0f;
415        const std::vector<int32_t> ref = topk(s3, n_kv, n_bid, width);
416        // the 513th block from the top (block 487) sits at the threshold; its single-pass score 0.009 lower
417        for (int64_t b = 0; b <= n_bid; ++b) s1[b] = s3[b];
418        s1[487] = s3[487] - 0.009f;
419        s1[486] = s3[486] + 0.009f;
420        const Band bd = band(s1, eps, n_kv, n_bid, width);
421        CHECK(bd.mode == 1 && std::find(bd.again.begin(), bd.again.end(), 487) != bd.again.end(),
422              "block 487 must be scored again (mode %d)", bd.mode);
423        std::vector<float> row = s1;
424        for (int64_t b : bd.again) row[b] = s3[b];
425        CHECK(topk(row, n_kv, n_bid, width) == ref, "the guarded row must select today's ids");
426        CHECK(topk(s1, n_kv, n_bid, width) != ref, "without the re-score the ids must differ (the test bites)");
427    }
428}
429
430}  // namespace
431
432int main() {
433    test_tf32();
434    test_bound();
435    test_rule();
436    if (g_fail) {
437        std::fprintf(stderr, "FAILED: %d checks\n", g_fail);
438        return 1;
439    }
440    std::puts("PASS: qsa_two_pass_test (TF32 split, the bound under two MMA models, the cut-off rule)");
441    return 0;
442}