okami.mom/strata

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

Niko1221Merge branch 'f-split-int' into f-split-vision7c5e84612

main
12.2 KiB213 linesraw
1#include <cstring>
2// src/kernels/qsa_select_bench.cpp - the prompt path's QSA selection (qsa_select.hpp) timed per stage, block scores
3// (the warp kernel and the fast one: tensor cores, or the FP32 tiled kernel on CUDA below sm_80) and top-k, for a batch of consecutive queries at a given context, and
4// the two scorers compared: score difference and how many selections differ (GPU, synthetic, no model).
5// Usage: qsa_select_bench [context=131072] [queries=256] [reps=10] [capacity_cells]
6// capacity_cells (the engine's --max-context): the score buffers and the top-k dispatch follow the CAPACITY
7// (max_blocks = capacity / 4 + 2), the work follows the context. Default: capacity = context (max_blocks = ctx / 4 + 1).
8#include "strata/kernels/qsa.hpp"
9#include "strata/kernels/qsa_select.hpp"
10
11#include <cuda_runtime.h>
12
13#include <algorithm>
14#include <cmath>
15#include <cstdio>
16#include <cstdlib>
17#include <cstring>
18#include <random>
19#include <vector>
20
21namespace k = strata::kernels;
22
23namespace {
24void ck(cudaError_t e, const char* w) {
25    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
26}
27template <typename T> T* up(const std::vector<T>& h) {
28    T* d = nullptr;
29    ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc");
30    ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");
31    return d;
32}
33}  // namespace
34
35int main(int argc, char** argv) {
36    const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 131072;
37    const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 256;
38    const int reps = argc > 3 ? std::atoi(argv[3]) : 10;
39    const k::QsaShapes s = k::qsa_real_shapes();
40    const int64_t capacity = argc > 4 ? std::atoll(argv[4]) : 0;
41    const int64_t max_blocks = capacity > 0 ? capacity / 4 + 2 : ctx / 4 + 1, cap = k::qsa_selection_width(k::kTopkMaxCells, s);
42    std::mt19937 rng(7);
43    std::normal_distribution<float> nd(0.f, 1.f);
44    // keys with a shared direction plus noise, so the scores have a spread like a real indexer's
45    std::vector<float> dir(128), pooled((size_t) (max_blocks * 128)), dead(128), q((size_t) (nq * 512));
46    for (auto& x : dir) x = nd(rng);
47    for (int64_t b = 0; b < max_blocks; ++b) {
48        const float a = nd(rng);
49        for (int d = 0; d < 128; ++d) pooled[(size_t) (b * 128 + d)] = 0.5f * a * dir[d] + nd(rng);
50    }
51    for (auto& x : dead) x = nd(rng);
52    for (int64_t i = 0; i < nq; ++i)
53        for (int d = 0; d < 512; ++d) q[(size_t) (i * 512 + d)] = 0.2f * dir[d % 128] + 0.1f * nd(rng);
54    std::vector<int32_t> steps((size_t) (nq * k::kStepCount));
55    for (int64_t i = 0; i < nq; ++i) {   // qsa_step_fill's arithmetic (kept here so the bench links only qsa_select)
56        int32_t* st = steps.data() + i * k::kStepCount;
57        const int64_t pos = ctx - nq + i;
58        st[k::kStepPos] = (int32_t) pos;
59        st[k::kStepNKv] = (int32_t) (pos + 1);
60        st[k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block);
61        st[k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s);
62    }
63    const float* d_pooled = up(pooled);
64    const float* d_dead = up(dead);
65    const float* d_q = up(q);
66    const int32_t* d_steps = up(steps);
67    float *sc_old = nullptr, *sc_new = nullptr;
68    int32_t *ids_old = nullptr, *ids_new = nullptr;
69    ck(cudaMalloc(&sc_old, (size_t) (nq * max_blocks) * 4), "malloc");
70    ck(cudaMalloc(&sc_new, (size_t) (nq * max_blocks) * 4), "malloc");
71    ck(cudaMalloc(&ids_old, (size_t) (nq * cap) * 4), "malloc");
72    ck(cudaMalloc(&ids_new, (size_t) (nq * cap) * 4), "malloc");
73    const int64_t active = steps[(size_t) ((nq - 1) * k::kStepCount + k::kStepNBid)] + 1;
74    if (std::getenv("QSA_BENCH_DECODE")) {   // a decode window's call: no block count (block_scores_multi_kernel)
75        auto run_dec = [&] { k::qsa_block_scores(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_old, nullptr, -1); };
76        run_dec();
77        ck(cudaDeviceSynchronize(), "sync");
78        cudaEvent_t a0, a1;
79        cudaEventCreate(&a0); cudaEventCreate(&a1);
80        cudaEventRecord(a0);
81        for (int r = 0; r < reps; ++r) run_dec();
82        cudaEventRecord(a1); cudaEventSynchronize(a1);
83        float ms = 0; cudaEventElapsedTime(&ms, a0, a1);
84        std::vector<float> h((size_t) (nq * max_blocks));
85        ck(cudaMemcpy(h.data(), sc_old, h.size() * 4, cudaMemcpyDeviceToHost), "down");
86        unsigned long long x = 1469598103934665603ull;
87        for (int64_t i = 0; i < nq; ++i) {
88            const int64_t nbid = steps[(size_t) (i * k::kStepCount + k::kStepNBid)];
89            for (int64_t j = 0; j <= nbid; ++j) { uint32_t u; std::memcpy(&u, &h[(size_t) (i * max_blocks + j)], 4); x = (x ^ u) * 1099511628211ull; }
90        }
91        const double gb = (double) active * 512.0 / 1e9;
92        std::printf("decode scores ctx %lld, %lld queries: %.1f us (%.0f GB/s of pooled keys), hash %016llx\n", (long long) ctx,
93                    (long long) nq, 1e3 * ms / reps, gb / (ms / reps / 1e3), x);
94        return 0;
95    }
96    auto run_old = [&] { k::qsa_block_scores(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_old, nullptr, active); };
97    // a device without the tensor-core scorer (HIP other than gfx12): time the warp scorer and the top-k only
98    const bool have_tc = k::qsa_block_scores_tc(d_pooled, d_dead, d_q, d_steps, 1, max_blocks, s, sc_new, nullptr, active);
99    auto run_new = [&] {
100        if (!k::qsa_block_scores_tc(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_new, nullptr, active)) {
101            std::fprintf(stderr, "tc scorer refused\n");
102            std::exit(2);
103        }
104    };
105    run_old();
106    if (have_tc) run_new();
107    else ck(cudaMemcpy(sc_new, sc_old, (size_t) (nq * max_blocks) * 4, cudaMemcpyDeviceToDevice), "copy");
108    k::qsa_block_topk_ref(sc_old, d_steps, nq, max_blocks, cap, s, ids_old, nullptr);
109    k::qsa_block_topk(sc_new, d_steps, nq, max_blocks, cap, s, ids_new, nullptr, active);
110    int32_t* ids_reg = nullptr;   // the register top-k on the OLD scores: must equal the reference exactly
111    ck(cudaMalloc(&ids_reg, (size_t) (nq * cap) * 4), "malloc");
112    k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr, active);
113    ck(cudaDeviceSynchronize(), "warm");
114    // compare
115    std::vector<float> a((size_t) (nq * max_blocks)), b(a.size());
116    std::vector<int32_t> ia((size_t) (nq * cap)), ib(ia.size());
117    ck(cudaMemcpy(a.data(), sc_old, a.size() * 4, cudaMemcpyDeviceToHost), "down");
118    ck(cudaMemcpy(b.data(), sc_new, b.size() * 4, cudaMemcpyDeviceToHost), "down");
119    if (std::getenv("QSA_BENCH_HASH")) {   // the fast scorer's bytes (compare STRATA_SELECT_SIMT=1 and =2)
120        unsigned long long h = 1469598103934665603ull;
121        for (int64_t i = 0; i < nq; ++i) {
122            const int64_t nbid = steps[(size_t) (i * k::kStepCount + k::kStepNBid)];
123            for (int64_t j = 0; j < nbid; ++j) {
124                uint32_t u;
125                std::memcpy(&u, &b[(size_t) (i * max_blocks + j)], 4);
126                h = (h ^ u) * 1099511628211ull;
127            }
128        }
129        std::printf("fast scores hash %016llx\n", h);
130    }
131    ck(cudaMemcpy(ia.data(), ids_old, ia.size() * 4, cudaMemcpyDeviceToHost), "down");
132    ck(cudaMemcpy(ib.data(), ids_new, ib.size() * 4, cudaMemcpyDeviceToHost), "down");
133    std::vector<int32_t> ir(ia.size());
134    ck(cudaMemcpy(ir.data(), ids_reg, ir.size() * 4, cudaMemcpyDeviceToHost), "down");
135    int64_t reg_same = 0;
136    for (int64_t i = 0; i < nq; ++i) {
137        const int64_t w = steps[(size_t) (i * k::kStepCount + k::kStepWidth)];
138        reg_same += std::equal(ia.begin() + i * cap, ia.begin() + i * cap + w, ir.begin() + i * cap);
139    }
140    double max_rel = 0, sum_rel = 0, n_rel = 0;
141    int64_t same_sel = 0, cells_diff = 0, cells_all = 0;
142    for (int64_t i = 0; i < nq; ++i) {
143        const int32_t* st = steps.data() + i * k::kStepCount;
144        for (int64_t j = 0; j <= st[k::kStepNBid]; ++j) {
145            const double x = a[(size_t) (i * max_blocks + j)], y = b[(size_t) (i * max_blocks + j)];
146            const double r = std::fabs(x - y) / std::max(1e-6, std::fabs(x));
147            max_rel = std::max(max_rel, r);
148            sum_rel += r;
149            n_rel += 1;
150        }
151        const int64_t w = st[k::kStepWidth];
152        std::vector<int32_t> x(ia.begin() + i * cap, ia.begin() + i * cap + w), y(ib.begin() + i * cap, ib.begin() + i * cap + w);
153        same_sel += x == y;
154        std::vector<int32_t> d;
155        std::set_symmetric_difference(x.begin(), x.end(), y.begin(), y.end(), std::back_inserter(d));
156        cells_diff += (int64_t) d.size() / 2;
157        cells_all += w;
158    }
159    // accuracy against an FP64 host reference on a sample (blocks below n_bid; the tail block is the warp kernel's own
160    // arithmetic in both scorers). Gate, as the prompt-attention harness's: the scorer under test is no worse than 4x
161    // the warp kernel's error, floored at 1e-5 of the score scale.  The floor is the fast scorer's own: measured against the FP64
162    // reference it sits at 1.0e-6 of the scale (RTX 5070 sm_120, ctx 32K: 0.99e-6, which a 1e-6 floor failed by rounding; 131K: 0.97e-6)
163    // against the warp kernel's 7e-8, i.e. FP32-accumulated TF32-split products; 1e-5 keeps ten times that margin and is still
164    // two orders below a plain single-TF32 product (~1e-3), which is the error this gate exists to catch.
165    double err_old = 0, err_new = 0, scale = 0;
166    {
167        std::mt19937 srng(11);
168        const int64_t nqs = std::min<int64_t>(nq, 32);
169        for (int64_t qs = 0; qs < nqs; ++qs) {
170            const int64_t i = qs * nq / nqs;
171            const int64_t nbid = steps[(size_t) (i * k::kStepCount + k::kStepNBid)];
172            if (nbid <= 0) continue;
173            for (int sidx = 0; sidx < 1024; ++sidx) {
174                const int64_t j = sidx < 64 ? std::min<int64_t>(nbid - 1, sidx) : (int64_t) (srng() % (uint64_t) nbid);
175                double ref = 0;
176                for (int h = 0; h < 4; ++h) {
177                    double d = 0;
178                    for (int c = 0; c < 128; ++c) d += (double) q[(size_t) (i * 512 + h * 128 + c)] * (double) pooled[(size_t) (j * 128 + c)];
179                    ref += d > 0 ? d : 0;
180                }
181                scale = std::max(scale, std::fabs(ref));
182                err_old = std::max(err_old, std::fabs(ref - (double) a[(size_t) (i * max_blocks + j)]));
183                err_new = std::max(err_new, std::fabs(ref - (double) b[(size_t) (i * max_blocks + j)]));
184            }
185        }
186    }
187    const bool acc_ok = !have_tc || err_new <= std::max(4.0 * err_old, 1e-5 * scale);
188    // time
189    cudaEvent_t e0, e1;
190    cudaEventCreate(&e0); cudaEventCreate(&e1);
191    auto timed = [&](auto f) {
192        cudaEventRecord(e0);
193        for (int r = 0; r < reps; ++r) f();
194        cudaEventRecord(e1);
195        ck(cudaEventSynchronize(e1), "time");
196        float ms = 0;
197        cudaEventElapsedTime(&ms, e0, e1);
198        return ms / reps;
199    };
200    const float t_old = timed(run_old), t_new = have_tc ? timed(run_new) : t_old;
201    const float t_tk = timed([&] { k::qsa_block_topk_ref(sc_old, d_steps, nq, max_blocks, cap, s, ids_old, nullptr); });
202    const float t_tk2 = timed([&] { k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr, active); });
203    std::printf("top-k %.3f -> %.3f ms (%.1fx), register top-k identical to the reference %lld/%lld\n", t_tk, t_tk2,
204                t_tk / t_tk2, (long long) reg_same, (long long) nq);
205    std::printf("%s accuracy vs FP64 (score scale %.3g): warp kernel max err %.3g, fast scorer max err %.3g (%.2g of scale)\n",
206                !have_tc ? "SKIP" : acc_ok ? "PASS" : "FAIL", scale, err_old, err_new, scale > 0 ? err_new / scale : 0.0);
207    if (!have_tc) std::printf("fast scorer not available on this device: warp scorer %.3f ms, top-k %.3f ms (%.0f%% of the two)\n", t_old, t_tk2, 100.0 * t_tk2 / (t_old + t_tk2));
208    std::printf("ctx %lld, %lld queries x %lld blocks: scores %.3f -> %.3f ms (%.1fx), top-k %.3f ms; score rel diff "
209                "mean %.2g max %.2g; selections identical %lld/%lld, cells differing %.4f%%\n", (long long) ctx,
210                (long long) nq, (long long) active, t_old, t_new, t_old / t_new, t_tk, sum_rel / std::max(1.0, n_rel),
211                max_rel, (long long) same_sel, (long long) nq, cells_all ? 100.0 * (double) cells_diff / (double) cells_all : 0.0);
212    return acc_ok && reg_same == nq ? 0 : 1;
213}