okami.mom/strata

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

Niko1221Merge f-141-quick: CPU prefill share, file tier batched reads, tokenizer cache, server hardening, small fixes073e2fe28

main
11.8 KiB234 linesraw
1// src/kernels/qsa_select_bench.cpp - the prompt path's QSA selection (qsa_select.hpp) timed per stage, block scores
2// (the warp kernel and the tensor-core one) and top-k, for a batch of consecutive queries at a given context, and
3// the two scorers compared: score difference and how many selections differ (GPU, synthetic, no model).
4// Usage: qsa_select_bench [context=131072] [queries=256] [reps=10] [capacity_cells]
5// capacity_cells (the engine's --max-context): the score buffers and the top-k dispatch follow the CAPACITY
6// (max_blocks = capacity / 4 + 2), the work follows the context. Default: capacity = context (max_blocks = ctx / 4 + 1).
7#define DPCT_PROFILING_ENABLED
8#include <sycl/sycl.hpp>
9#include <dpct/dpct.hpp>
10#include "strata/kernels/qsa.hpp"
11#include "strata/kernels/qsa_select.hpp"
12
13#include <algorithm>
14#include <cmath>
15#include <cstdio>
16#include <cstdlib>
17#include <random>
18#include <vector>
19
20namespace k = strata::kernels;
21
22namespace {
23void ck(dpct::err0 e, const char *w) {
24    /*
25    DPCT1009: SYCL reports errors using exceptions and does not use error
26    codes. Please replace the "get_error_string_dummy(...)" with a real
27    error-handling function.
28    */
29}
30template <typename T> T* up(const std::vector<T>& h) {
31    T* d = nullptr;
32    ck(DPCT_CHECK_ERROR(
33           d = (T *)sycl::malloc_device(h.size() * sizeof(T) + 64,
34                                        dpct::get_in_order_queue())),
35       "malloc");
36    /*
37    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
38    the original code the source host memory is pageable memory. If the memory
39    is not pageable, call wait() on event return by memcpy API to ensure
40    synchronization behavior.
41    */
42    ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
43           d, h.data(), h.size() * sizeof(T)).wait()),
44       "upload");
45    return d;
46}
47}  // namespace
48
49int main(int argc, char** argv) {
50    const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 131072;
51    const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 256;
52    const int reps = argc > 3 ? std::atoi(argv[3]) : 10;
53    const k::QsaShapes s = k::qsa_real_shapes();
54    const int64_t capacity = argc > 4 ? std::atoll(argv[4]) : 0;
55    const int64_t max_blocks = capacity > 0 ? capacity / 4 + 2 : ctx / 4 + 1, cap = k::qsa_selection_width(k::kTopkMaxCells, s);
56    std::mt19937 rng(7);
57    std::normal_distribution<float> nd(0.f, 1.f);
58    // keys with a shared direction plus noise, so the scores have a spread like a real indexer's
59    std::vector<float> dir(128), pooled((size_t) (max_blocks * 128)), dead(128), q((size_t) (nq * 512));
60    for (auto& x : dir) x = nd(rng);
61    for (int64_t b = 0; b < max_blocks; ++b) {
62        const float a = nd(rng);
63        for (int d = 0; d < 128; ++d) pooled[(size_t) (b * 128 + d)] = 0.5f * a * dir[d] + nd(rng);
64    }
65    for (auto& x : dead) x = nd(rng);
66    for (int64_t i = 0; i < nq; ++i)
67        for (int d = 0; d < 512; ++d) q[(size_t) (i * 512 + d)] = 0.2f * dir[d % 128] + 0.1f * nd(rng);
68    std::vector<int32_t> steps((size_t) (nq * k::kStepCount));
69    for (int64_t i = 0; i < nq; ++i) {   // qsa_step_fill's arithmetic (kept here so the bench links only qsa_select)
70        int32_t* st = steps.data() + i * k::kStepCount;
71        const int64_t pos = ctx - nq + i;
72        st[k::kStepPos] = (int32_t) pos;
73        st[k::kStepNKv] = (int32_t) (pos + 1);
74        st[k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block);
75        st[k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s);
76    }
77    const float* d_pooled = up(pooled);
78    const float* d_dead = up(dead);
79    const float* d_q = up(q);
80    const int32_t* d_steps = up(steps);
81    float *sc_old = nullptr, *sc_new = nullptr;
82    int32_t *ids_old = nullptr, *ids_new = nullptr;
83    ck(DPCT_CHECK_ERROR(
84           sc_old = (float *)sycl::malloc_device((size_t)(nq * max_blocks) * 4,
85                                                 dpct::get_in_order_queue())),
86       "malloc");
87    ck(DPCT_CHECK_ERROR(
88           sc_new = (float *)sycl::malloc_device((size_t)(nq * max_blocks) * 4,
89                                                 dpct::get_in_order_queue())),
90       "malloc");
91    ck(DPCT_CHECK_ERROR(
92           ids_old = (int32_t *)sycl::malloc_device(
93               (size_t)(nq * cap) * 4, dpct::get_in_order_queue())),
94       "malloc");
95    ck(DPCT_CHECK_ERROR(
96           ids_new = (int32_t *)sycl::malloc_device(
97               (size_t)(nq * cap) * 4, dpct::get_in_order_queue())),
98       "malloc");
99    const int64_t active = steps[(size_t) ((nq - 1) * k::kStepCount + k::kStepNBid)] + 1;
100    auto run_old = [&] { k::qsa_block_scores(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_old, nullptr, active); };
101    // a device without the tensor-core scorer (HIP other than gfx12): time the warp scorer and the top-k only
102    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);
103    auto run_new = [&] {
104        if (!k::qsa_block_scores_tc(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_new, nullptr, active)) {
105            std::fprintf(stderr, "tc scorer refused\n");
106            std::exit(2);
107        }
108    };
109    run_old();
110    if (have_tc) run_new();
111    else ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
112                sc_new, sc_old, (size_t)(nq * max_blocks) * 4).wait()),
113            "copy");
114    k::qsa_block_topk_ref(sc_old, d_steps, nq, max_blocks, cap, s, ids_old, nullptr);
115    k::qsa_block_topk(sc_new, d_steps, nq, max_blocks, cap, s, ids_new, nullptr, active);
116    int32_t* ids_reg = nullptr;   // the register top-k on the OLD scores: must equal the reference exactly
117    ck(DPCT_CHECK_ERROR(
118           ids_reg = (int32_t *)sycl::malloc_device(
119               (size_t)(nq * cap) * 4, dpct::get_in_order_queue())),
120       "malloc");
121    k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr, active);
122    ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
123       "warm");
124    // compare
125    std::vector<float> a((size_t) (nq * max_blocks)), b(a.size());
126    std::vector<int32_t> ia((size_t) (nq * cap)), ib(ia.size());
127    ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
128                            .memcpy(a.data(), sc_old, a.size() * 4)
129                            .wait()),
130       "down");
131    ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
132                            .memcpy(b.data(), sc_new, b.size() * 4)
133                            .wait()),
134       "down");
135    ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
136                            .memcpy(ia.data(), ids_old, ia.size() * 4)
137                            .wait()),
138       "down");
139    ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
140                            .memcpy(ib.data(), ids_new, ib.size() * 4)
141                            .wait()),
142       "down");
143    std::vector<int32_t> ir(ia.size());
144    ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
145                            .memcpy(ir.data(), ids_reg, ir.size() * 4)
146                            .wait()),
147       "down");
148    int64_t reg_same = 0;
149    for (int64_t i = 0; i < nq; ++i) {
150        const int64_t w = steps[(size_t) (i * k::kStepCount + k::kStepWidth)];
151        reg_same += std::equal(ia.begin() + i * cap, ia.begin() + i * cap + w, ir.begin() + i * cap);
152    }
153    double max_rel = 0, sum_rel = 0, n_rel = 0;
154    int64_t same_sel = 0, cells_diff = 0, cells_all = 0;
155    for (int64_t i = 0; i < nq; ++i) {
156        const int32_t* st = steps.data() + i * k::kStepCount;
157        for (int64_t j = 0; j <= st[k::kStepNBid]; ++j) {
158            const double x = a[(size_t) (i * max_blocks + j)], y = b[(size_t) (i * max_blocks + j)];
159            const double r = std::fabs(x - y) / std::max(1e-6, std::fabs(x));
160            max_rel = std::max(max_rel, r);
161            sum_rel += r;
162            n_rel += 1;
163        }
164        const int64_t w = st[k::kStepWidth];
165        std::vector<int32_t> x(ia.begin() + i * cap, ia.begin() + i * cap + w), y(ib.begin() + i * cap, ib.begin() + i * cap + w);
166        same_sel += x == y;
167        std::vector<int32_t> d;
168        std::set_symmetric_difference(x.begin(), x.end(), y.begin(), y.end(), std::back_inserter(d));
169        cells_diff += (int64_t) d.size() / 2;
170        cells_all += w;
171    }
172    // accuracy against an FP64 host reference on a sample (blocks below n_bid; the tail block is the warp kernel's own
173    // arithmetic in both scorers). Gate, as the prompt-attention harness's: the scorer under test is no worse than 4x
174    // the warp kernel's error, floored at 1e-5 of the score scale.
175    double err_old = 0, err_new = 0, scale = 0;
176    {
177        std::mt19937 srng(11);
178        const int64_t nqs = std::min<int64_t>(nq, 32);
179        for (int64_t qs = 0; qs < nqs; ++qs) {
180            const int64_t i = qs * nq / nqs;
181            const int64_t nbid = steps[(size_t) (i * k::kStepCount + k::kStepNBid)];
182            if (nbid <= 0) continue;
183            for (int sidx = 0; sidx < 1024; ++sidx) {
184                const int64_t j = sidx < 64 ? std::min<int64_t>(nbid - 1, sidx) : (int64_t) (srng() % (uint64_t) nbid);
185                double ref = 0;
186                for (int h = 0; h < 4; ++h) {
187                    double d = 0;
188                    for (int c = 0; c < 128; ++c) d += (double) q[(size_t) (i * 512 + h * 128 + c)] * (double) pooled[(size_t) (j * 128 + c)];
189                    ref += d > 0 ? d : 0;
190                }
191                scale = std::max(scale, std::fabs(ref));
192                err_old = std::max(err_old, std::fabs(ref - (double) a[(size_t) (i * max_blocks + j)]));
193                err_new = std::max(err_new, std::fabs(ref - (double) b[(size_t) (i * max_blocks + j)]));
194            }
195        }
196    }
197    const bool acc_ok = !have_tc || err_new <= std::max(4.0 * err_old, 1e-5 * scale);
198    // time
199    dpct::event_ptr e0, e1;
200    e0 = new sycl::event(); e1 = new sycl::event();
201    auto timed = [&](auto f) {
202        try {
203    dpct::sync_barrier(e0);
204        for (int r = 0; r < reps; ++r) f();
205        dpct::sync_barrier(e1);
206        ck(DPCT_CHECK_ERROR(e1->wait_and_throw()), "time");
207        float ms = 0;
208        ms = (e1->get_profiling_info<
209                  sycl::info::event_profiling::command_end>() -
210              e0->get_profiling_info<
211                  sycl::info::event_profiling::command_start>()) /
212             1000000.0f;
213        return ms / reps;
214    }
215    catch (sycl::exception const &exc) {
216      std::cerr << exc.what() << "Exception caught at file:" << __FILE__
217                << ", line:" << __LINE__ << std::endl;
218      std::exit(1);
219    }
220    };
221    const float t_old = timed(run_old), t_new = have_tc ? timed(run_new) : t_old;
222    const float t_tk = timed([&] { k::qsa_block_topk_ref(sc_old, d_steps, nq, max_blocks, cap, s, ids_old, nullptr); });
223    const float t_tk2 = timed([&] { k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr, active); });
224    std::printf("top-k %.3f -> %.3f ms (%.1fx), register top-k identical to the reference %lld/%lld\n", t_tk, t_tk2,
225                t_tk / t_tk2, (long long) reg_same, (long long) nq);
226    std::printf("%s accuracy vs FP64 (score scale %.3g): warp kernel max err %.3g, tensor-core max err %.3g (%.2g of scale)\n",
227                !have_tc ? "SKIP" : acc_ok ? "PASS" : "FAIL", scale, err_old, err_new, scale > 0 ? err_new / scale : 0.0);
228    if (!have_tc) std::printf("tensor-core 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));
229    std::printf("ctx %lld, %lld queries x %lld blocks: scores %.3f -> %.3f ms (%.1fx), top-k %.3f ms; score rel diff "
230                "mean %.2g max %.2g; selections identical %lld/%lld, cells differing %.4f%%\n", (long long) ctx,
231                (long long) nq, (long long) active, t_old, t_new, t_old / t_new, t_tk, sum_rel / std::max(1.0, n_rel),
232                max_rel, (long long) same_sel, (long long) nq, cells_all ? 100.0 * (double) cells_diff / (double) cells_all : 0.0);
233    return acc_ok && reg_same == nq ? 0 : 1;
234}