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
12.2 KiB224 linesraw
1// STRATA_SELECT_TWO_PASS (qsa_two_pass.hpp) against today's prompt scorer, GPU, synthetic, no model: for prompt
2// chunks of 256 queries at depths from 2K to 256K and several kinds of keys (normal, indexer-like, wide magnitudes,
3// small integers with exact ties, near-duplicate and duplicate keys), qsa_block_topk over the two-pass row must return
4// exactly the ids it returns over qsa_block_scores_tc's row, every scored-again block must hold today's score bit for
5// bit, and every kept single-pass score must lie inside its bound (qsa_two_pass_check's counters).  Then, for the
6// larger cases, the time of each scorer (one synthetic run, not a benchmark).  Needs CUDA sm_80+ (77 = skipped
7// otherwise, and on HIP).
8#include "strata/kernels/qsa.hpp"
9#include "strata/kernels/qsa_select.hpp"
10#include "strata/kernels/qsa_two_pass.hpp"
11
12#include <cuda_runtime.h>
13
14#include <algorithm>
15#include <cmath>
16#include <cstdint>
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20#include <random>
21#include <vector>
22
23namespace k = strata::kernels;
24namespace tp = strata::kernels::two_pass;
25
26namespace {
27void ck(cudaError_t e) {
28    if (e != cudaSuccess) {
29        std::fprintf(stderr, "CUDA: %s\n", cudaGetErrorString(e));
30        std::exit(2);
31    }
32}
33
34enum Kind { kNormal, kIndexer, kWide, kSmall, kNear, kDup, kKinds };
35const char* kKindName[kKinds] = {"normal", "indexer-like", "wide magnitudes", "small integers", "near-duplicate keys",
36                                 "duplicate keys"};
37
38struct Case { int64_t ctx, queries; Kind kind; bool time; };
39
40// stride: the score row's stride in blocks; 0 = the case's own (ctx / 4 + 2), else the engine's (--max-context 262144:
41// 65,538, so qsa_block_topk takes the engine's dispatch on this card)
42bool run(const Case& c, int64_t stride) {
43    const auto s = k::qsa_real_shapes();
44    const int64_t D = s.idx_dim, H = s.idx_n_head, own = c.ctx / s.idx_block + 2;
45    const int64_t max_blocks = stride > own ? stride : own;
46    const int64_t nq = c.queries, nq_cap = 256, cap = k::qsa_selection_width(k::kTopkMaxCells, s);
47    std::mt19937 rng(77001 + (unsigned) c.ctx + 13 * (unsigned) c.queries + 1009 * (unsigned) c.kind);
48    std::normal_distribution<float> nd(0.f, 1.f);
49    std::uniform_int_distribution<int> small(-3, 3), expo(-16, 16), coin(0, 9);
50    std::vector<float> pooled((size_t) (max_blocks * D)), dead((size_t) D), q((size_t) (nq * H * D));
51    auto unit = [&](float* v, int n, float norm) {
52        double ss = 0;
53        for (int i = 0; i < n; ++i) ss += (double) v[i] * v[i];
54        const float f = ss > 0 ? (float) (norm / std::sqrt(ss)) : 0.f;
55        for (int i = 0; i < n; ++i) v[i] *= f;
56    };
57    for (int64_t b = 0; b < max_blocks; ++b) {
58        float* kb = pooled.data() + b * D;
59        if (c.kind == kIndexer) {   // the mean of 4 RMS-normed cell keys, as the indexer pools them
60            for (int i = 0; i < D; ++i) kb[i] = 0.f;
61            for (int cell = 0; cell < 4; ++cell) {
62                float ck_[128];
63                for (int i = 0; i < D; ++i) ck_[i] = nd(rng);
64                unit(ck_, (int) D, std::sqrt((float) D));
65                for (int i = 0; i < D; ++i) kb[i] += 0.25f * ck_[i];
66            }
67        } else if (c.kind == kNear && b > 0 && coin(rng) < 5) {   // half the keys a hair from the one before
68            for (int i = 0; i < D; ++i) kb[i] = kb[i - D] * (1.0f + 1e-6f * nd(rng));
69        } else if (c.kind == kDup && b >= 8 && coin(rng) < 5) {   // half the keys copies of an earlier one: exact ties
70            const int64_t src = (int64_t) (rng() % (uint32_t) b);
71            std::memcpy(kb, pooled.data() + src * D, (size_t) D * 4);
72        } else {
73            for (int i = 0; i < D; ++i) {
74                if (c.kind == kWide) kb[i] = coin(rng) == 0 ? 0.f : std::ldexp(nd(rng), expo(rng));
75                else if (c.kind == kSmall) kb[i] = (float) small(rng);
76                else kb[i] = nd(rng);
77            }
78        }
79    }
80    for (auto& v : dead) v = nd(rng);
81    for (int64_t i = 0; i < nq; ++i)
82        for (int64_t h = 0; h < H; ++h) {
83            float* qh = q.data() + (i * H + h) * D;
84            if (c.kind == kIndexer) {   // RMS-normed, leaning towards a few keys (a peaked score row)
85                for (int j = 0; j < D; ++j) qh[j] = nd(rng);
86                for (int r = 0; r < 3; ++r) {
87                    const float* kb = pooled.data() + (int64_t) (rng() % (uint32_t) (max_blocks - 2)) * D;
88                    for (int j = 0; j < D; ++j) qh[j] += 0.5f * kb[j];
89                }
90                unit(qh, (int) D, std::sqrt((float) D));
91            } else {
92                for (int j = 0; j < D; ++j) {
93                    if (c.kind == kWide) qh[j] = coin(rng) == 0 ? 0.f : std::ldexp(nd(rng), expo(rng));
94                    else if (c.kind == kSmall) qh[j] = (float) small(rng);
95                    else qh[j] = nd(rng);
96                }
97            }
98        }
99    std::vector<int32_t> steps((size_t) (nq * k::kStepCount));
100    for (int64_t i = 0; i < nq; ++i) {
101        int32_t* st = steps.data() + i * k::kStepCount;
102        const int64_t pos = c.ctx - nq + i;
103        st[k::kStepPos] = (int32_t) pos;
104        st[k::kStepNKv] = (int32_t) (pos + 1);
105        st[k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block);
106        st[k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s);
107    }
108    const int64_t last_nbid = steps[(size_t) ((nq - 1) * k::kStepCount + k::kStepNBid)], active = last_nbid + 1;
109    float *dp, *dd, *dq, *ref, *two;
110    int32_t *dt, *ref_ids, *two_ids;
111    void* scratch;
112    const uint64_t sbytes = k::qsa_two_pass_scratch_bytes(nq_cap, max_blocks);
113    const size_t n_sc = (size_t) (nq * max_blocks), n_id = (size_t) (nq * cap);
114    ck(cudaMalloc(&dp, pooled.size() * 4)); ck(cudaMalloc(&dd, dead.size() * 4)); ck(cudaMalloc(&dq, q.size() * 4));
115    ck(cudaMalloc(&dt, steps.size() * 4)); ck(cudaMalloc(&ref, n_sc * 4)); ck(cudaMalloc(&two, n_sc * 4));
116    ck(cudaMalloc(&ref_ids, n_id * 4)); ck(cudaMalloc(&two_ids, n_id * 4)); ck(cudaMalloc(&scratch, sbytes));
117    ck(cudaMemcpy(dp, pooled.data(), pooled.size() * 4, cudaMemcpyHostToDevice));
118    ck(cudaMemcpy(dd, dead.data(), dead.size() * 4, cudaMemcpyHostToDevice));
119    ck(cudaMemcpy(dq, q.data(), q.size() * 4, cudaMemcpyHostToDevice));
120    ck(cudaMemcpy(dt, steps.data(), steps.size() * 4, cudaMemcpyHostToDevice));
121    ck(cudaMemset(ref, 0x7f, n_sc * 4)); ck(cudaMemset(two, 0x3e, n_sc * 4));
122    ck(cudaMemset(ref_ids, 0xff, n_id * 4)); ck(cudaMemset(two_ids, 0xee, n_id * 4));
123    if (!k::qsa_block_scores_tc(dp, dd, dq, dt, nq, max_blocks, s, ref, nullptr, active)) {
124        std::puts("SKIP: no tensor-core scorer on this card");
125        std::exit(77);
126    }
127    k::qsa_block_topk(ref, dt, nq, max_blocks, cap, s, ref_ids, nullptr, active);
128    unsigned long long st0[tp::kStatCount];
129    k::qsa_two_pass_stats(st0, true, nullptr);   // zero the counters
130    if (!k::qsa_two_pass_keys(dp, last_nbid, nq_cap, max_blocks, scratch, sbytes, nullptr) ||
131        !k::qsa_block_scores_two_pass(dp, dd, dq, dt, nq, nq_cap, max_blocks, s, two, scratch, sbytes, nullptr, active)) {
132        std::fprintf(stderr, "FAIL: the two-pass scorer did not run (ctx %lld)\n", (long long) c.ctx);
133        return false;
134    }
135    k::qsa_block_topk(two, dt, nq, max_blocks, cap, s, two_ids, nullptr, active);
136    k::qsa_two_pass_check(two, two_ids, ref, ref_ids, dt, nq, nq_cap, max_blocks, cap, scratch, nullptr);
137    ck(cudaDeviceSynchronize());
138    unsigned long long st[tp::kStatCount];
139    if (!k::qsa_two_pass_stats(st, true, nullptr)) { std::fprintf(stderr, "FAIL: counters\n"); return false; }
140    // the ids on the host too, every entry qsa_block_topk wrote
141    std::vector<int32_t> a(n_id), b(n_id);
142    ck(cudaMemcpy(a.data(), ref_ids, n_id * 4, cudaMemcpyDeviceToHost));
143    ck(cudaMemcpy(b.data(), two_ids, n_id * 4, cudaMemcpyDeviceToHost));
144    int64_t bad_q = 0, compared = 0;
145    for (int64_t i = 0; i < nq; ++i) {
146        const int64_t n_kv = steps[(size_t) (i * k::kStepCount + k::kStepNKv)];
147        const int64_t w = std::min<int64_t>(n_kv, steps[(size_t) (i * k::kStepCount + k::kStepWidth)]);
148        compared += w;
149        if (!std::equal(a.begin() + i * cap, a.begin() + i * cap + w, b.begin() + i * cap)) ++bad_q;
150    }
151    const bool ok = bad_q == 0 && st[tp::kChkIdQueries] == 0 && st[tp::kChkRescoredDiff] == 0 && st[tp::kChkKeptOut] == 0 &&
152                    st[tp::kChkQueries] == (unsigned long long) nq;
153    float ratio;
154    const uint32_t rb = (uint32_t) st[tp::kChkRatioMax];
155    std::memcpy(&ratio, &rb, 4);
156    const unsigned long long kept = st[tp::kStQueries] - st[tp::kStFull];
157    std::printf("%s ctx=%7lld stride=%5lld queries=%3lld %-20s: ids %lld queries differ (%lld ids compared); scored "
158                "again %llu (%.1f per query), %llu of %llu scored-again blocks not bitwise; flagged %llu (%llu tiles in "
159                "full); kept %llu, outside the bound %llu, max |S1-S3|/eps %.4f\n",
160                ok ? "ok  " : "FAIL", (long long) c.ctx, (long long) max_blocks, (long long) nq, kKindName[c.kind],
161                (long long) bad_q, (long long) compared, st[tp::kStBand], kept ? (double) st[tp::kStBand] / kept : 0.0,
162                st[tp::kChkRescoredDiff], st[tp::kChkRescored], st[tp::kStFull], st[tp::kStFullTiles], st[tp::kChkKept],
163                st[tp::kChkKeptOut], (double) ratio);
164    if (ok && c.time && stride > 0) {   // one synthetic observation of each scorer (the bench worker measures the engine)
165        cudaEvent_t e0, e1, e2;
166        ck(cudaEventCreate(&e0)); ck(cudaEventCreate(&e1)); ck(cudaEventCreate(&e2));
167        constexpr int N = 5;
168        ck(cudaEventRecord(e0));
169        for (int r = 0; r < N; ++r) k::qsa_block_scores_tc(dp, dd, dq, dt, nq, max_blocks, s, ref, nullptr, active);
170        ck(cudaEventRecord(e1));
171        for (int r = 0; r < N; ++r)
172            k::qsa_block_scores_two_pass(dp, dd, dq, dt, nq, nq_cap, max_blocks, s, two, scratch, sbytes, nullptr, active);
173        ck(cudaEventRecord(e2));
174        ck(cudaEventSynchronize(e2));
175        float t3 = 0, t2 = 0;
176        ck(cudaEventElapsedTime(&t3, e0, e1)); ck(cudaEventElapsedTime(&t2, e1, e2));
177        std::printf("     time per call (synthetic, one run): 3xTF32 scorer %.3f ms, two-pass %.3f ms (keys once per chunk "
178                    "not included)\n", t3 / N, t2 / N);
179        k::qsa_two_pass_stats(st, true, nullptr);
180        cudaEventDestroy(e0); cudaEventDestroy(e1); cudaEventDestroy(e2);
181    }
182    ck(cudaFree(dp)); ck(cudaFree(dd)); ck(cudaFree(dq)); ck(cudaFree(dt)); ck(cudaFree(ref)); ck(cudaFree(two));
183    ck(cudaFree(ref_ids)); ck(cudaFree(two_ids)); ck(cudaFree(scratch));
184    return ok;
185}
186}  // namespace
187
188int main() {
189#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
190    // AMD: the two-pass scorer is CUDA-only (qsa_select.cu builds stubs under HIP), so the engine keeps today's scorer
191    std::puts("SKIP: the two-pass scorer is CUDA-only");
192    return 77;
193#endif
194#if defined(_WIN32)
195    if (std::getenv("STRATA_SELECT_TWO_PASS") == nullptr) _putenv_s("STRATA_SELECT_TWO_PASS", "1");
196#else
197    setenv("STRATA_SELECT_TWO_PASS", "1", 0);   // read once, at the first call
198#endif
199    int devices = 0;
200    if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) {
201        std::puts("SKIP: no CUDA device");
202        return 77;
203    }
204    if (!k::qsa_two_pass_on()) {
205        std::puts("FAIL: STRATA_SELECT_TWO_PASS is set to something other than 1");
206        return 1;
207    }
208    const Case cases[] = {
209        {2100, 64, kNormal, false},     {4096, 256, kNormal, false},   {9000, 37, kNormal, false},
210        {20000, 256, kNormal, false},   {20481, 256, kSmall, false},   {32768, 256, kIndexer, false},
211        {40000, 256, kWide, false},     {50000, 200, kNear, false},    {70000, 256, kDup, false},
212        {131072, 256, kIndexer, false}, {131075, 129, kNormal, false}, {262144, 256, kIndexer, true},
213        {262144, 256, kNormal, true},   {200003, 256, kSmall, false},  {65536, 256, kIndexer, true},
214    };
215    bool all = true;
216    for (const int64_t stride : {(int64_t) 0, (int64_t) 65538})
217        for (const Case& c : cases) all = run(c, stride) && all;
218    if (!all) {
219        std::puts("FAIL: the two-pass selection differs from the 3xTF32 scorer's");
220        return 1;
221    }
222    std::puts("PASS: two-pass ids identical to the 3xTF32 scorer's, scored-again blocks bitwise, kept blocks inside the bound");
223    return 0;
224}