okami.mom/strata

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

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

main
18.9 KiB353 linesraw
1// src/kernels/qsa_rows_bench.cpp - QSAROWS (docs/QSAROWS.md): what the T rows of a verification window cost in a QSA
2// layer's decode kernels at a long context, row by row.  GPU, synthetic data at the real geometry (24 query heads x
3// 256, 2 KV heads, indexer 4 x 128, blocks of 4 cells, top-k 2048), INT8 pools, no model.
4//
5// The hypothesis under test: "the decode attention of the QSA layers works row by row, re-reading K/V for every row of
6// the window, so 8 layers x ~0.25 ms explain the ~2.5 ms a row the stage costs".  The kernels measured here are the
7// ones verify.cpp launches for a window of T rows at the usual long-context options (--max-context 262144, --kv int8):
8//
9//   scores   qsa_block_scores   (block_scores_multi_kernel: every pooled key read ONCE for the T queries)
10//   topk     qsa_block_topk     (one CTA per query; max_blocks 65538 -> block_topk_wide_kernel)
11//   attn     qsa_decode_attn_batch over each row's own selection, cap 2051 (33 chunks x 2 KV heads x T blocks)
12//   append   native_qsa_indexer_append_steps for the T raw indexer keys (one CTA, the steps in sequence)
13//   dense    qsa_decode_attn_batch over a 32768-cell window per row: the drafter's shape, which the hypothesis's
14//            "~240 us a query" comes from (the drafter runs it with ONE query per step: capture_round's record_rest)
15//
16// --rows: block_scores_rows_kernel (STRATA_QSA_ROWS=1, docs/QSAROWS.md) against the multi kernel, scores and ids bit for
17// bit, and its microseconds beside the reference's.
18//
19//   qsa_rows_bench [--device N] [--iters 100] [--ctx 131072] [--max-context 262144] [--rows] [--no-dense]
20//   exit 0 (77: no GPU; 1: a --rows parity failure)
21#include "strata/kernels/kv_q8.hpp"
22#include "strata/kernels/native_qsa_indexer.hpp"
23#include "strata/kernels/qsa.hpp"
24#include "strata/kernels/qsa_decode_attn.hpp"
25#include "strata/kernels/qsa_select.hpp"
26#include "strata/kernels/rope_scaling.hpp"
27
28#include <cuda_runtime.h>
29
30#include <algorithm>
31#include <cmath>
32#include <cstdint>
33#include <cstdio>
34#include <cstdlib>
35#include <cstring>
36#include <random>
37#include <set>
38#include <string>
39#include <vector>
40
41namespace k = strata::kernels;
42
43namespace {
44cudaStream_t st = nullptr;
45void ck(cudaError_t e, const char* what) {
46    if (e != cudaSuccess) {
47        std::fprintf(stderr, "qsa_rows_bench: %s: %s\n", what, cudaGetErrorString(e));
48        std::exit(2);
49    }
50}
51template <typename T> T* dalloc(size_t n) {
52    T* p = nullptr;
53    ck(cudaMalloc((void**) &p, n * sizeof(T) + 256), "cudaMalloc");
54    ck(cudaMemset(p, 0, n * sizeof(T) + 256), "cudaMemset");
55    return p;
56}
57template <typename T> T* upload(const std::vector<T>& h) {
58    T* d = dalloc<T>(h.size());
59    ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");
60    return d;
61}
62template <typename T> std::vector<T> download(const T* d, size_t n) {
63    std::vector<T> h(n);
64    ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "download");
65    return h;
66}
67uint16_t f16_scale_q8(uint32_t r) { return (uint16_t) ((9u << 10) | (r & 0x3FFu)); }
68
69struct Timer {
70    cudaEvent_t e0 = nullptr, e1 = nullptr;
71    Timer() { ck(cudaEventCreate(&e0), "event"); ck(cudaEventCreate(&e1), "event"); }
72    ~Timer() { cudaEventDestroy(e0); cudaEventDestroy(e1); }
73    // microseconds per call over `iters` back-to-back calls, warmed; the median of three such runs
74    template <typename F> double us(F&& f, int iters) {
75        double r[3];
76        for (int a = 0; a < 3; ++a) {
77            for (int i = 0; i < 4; ++i) f();
78            ck(cudaDeviceSynchronize(), "warm");
79            ck(cudaEventRecord(e0, st), "record");
80            for (int i = 0; i < iters; ++i) f();
81            ck(cudaEventRecord(e1, st), "record");
82            ck(cudaEventSynchronize(e1), "sync");
83            float ms = 0.0f;
84            ck(cudaEventElapsedTime(&ms, e0, e1), "elapsed");
85            r[a] = 1000.0 * ms / iters;
86        }
87        std::sort(r, r + 3);
88        return r[1];
89    }
90};
91
92constexpr int NH = 24, HD = 256, NKV = 2, IQ = 4, ID = 128;
93constexpr int MAXT = 4;
94
95struct Table {   // us[T] for T = 1..MAXT
96    double us[MAXT + 1] = {};
97    void print(const char* what) const {
98        std::printf("  %-44s", what);
99        for (int T = 1; T <= MAXT; ++T) std::printf(" T=%d %8.1f", T, us[T]);
100        std::printf("  | +%.1f us a row\n", (us[MAXT] - us[1]) / (MAXT - 1));
101    }
102};
103}  // namespace
104
105int main(int argc, char** argv) {
106    int device = 0, iters = 100;
107    int64_t ctx = 131072, max_ctx = 262144;
108    bool rows = false, dense = true;
109    for (int i = 1; i < argc; ++i) {
110        if (std::strcmp(argv[i], "--device") == 0 && i + 1 < argc) device = std::atoi(argv[++i]);
111        else if (std::strcmp(argv[i], "--iters") == 0 && i + 1 < argc) iters = std::atoi(argv[++i]);
112        else if (std::strcmp(argv[i], "--ctx") == 0 && i + 1 < argc) ctx = std::atoll(argv[++i]);
113        else if (std::strcmp(argv[i], "--max-context") == 0 && i + 1 < argc) max_ctx = std::atoll(argv[++i]);
114        else if (std::strcmp(argv[i], "--rows") == 0) rows = true;
115        else if (std::strcmp(argv[i], "--no-dense") == 0) dense = false;
116        else {
117            std::fprintf(stderr, "usage: qsa_rows_bench [--device N] [--iters 100] [--ctx 131072] [--max-context 262144] "
118                                 "[--rows] [--no-dense]\n");
119            return 2;
120        }
121    }
122    int devices = 0;
123    if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) {
124        std::puts("SKIP: no GPU");
125        return 77;
126    }
127    ck(cudaSetDevice(device), "cudaSetDevice");
128    ck(cudaStreamCreate(&st), "stream");
129    cudaDeviceProp prop{};
130    ck(cudaGetDeviceProperties(&prop, device), "cudaGetDeviceProperties");
131    const k::QsaShapes s = k::qsa_real_shapes();
132    const int64_t PS = s.page_size;
133    const int64_t max_cells = (max_ctx + PS - 1) / PS * PS;
134    const int64_t max_blocks = max_cells / s.idx_block + 2;                       // verify.cpp: max_blocks_
135    const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s);              // verify.cpp: cap_ (2051)
136    const int64_t cells = (ctx + MAXT + 64 + PS - 1) / PS * PS;                     // the pools' rows: resident cells
137    const int64_t pages = cells / PS, prows = pages * NKV * PS;
138    const int64_t dense_win = 32768, dense_cap = dense_win;                       // the drafter's --mtp-window
139    std::printf("qsa_rows_bench on device %d (%s, %d.%d), %d iterations: context %lld, capacity %lld cells (max_blocks "
140                "%lld), selection cap %lld, int8 pools over %lld cells%s\n",
141                device, prop.name, prop.major, prop.minor, iters, (long long) ctx, (long long) max_cells,
142                (long long) max_blocks, (long long) cap, (long long) cells,
143                std::getenv("STRATA_QSA_ROWS") ? ", STRATA_QSA_ROWS set" : "");
144    std::mt19937 rng(20261012u);
145    std::normal_distribution<float> nd(0.0f, 1.0f);
146
147    // ---- INT8 K/V pools, every page resident, identity page table
148    std::vector<int8_t> c8((size_t) (prows * HD));
149    for (auto& x : c8) x = (int8_t) ((int) (rng() % 255u) - 127);
150    int8_t* k8 = upload(c8);
151    for (auto& x : c8) x = (int8_t) ((int) (rng() % 255u) - 127);
152    int8_t* v8 = upload(c8);
153    c8.clear(); c8.shrink_to_fit();
154    std::vector<uint16_t> sc((size_t) (prows * (HD / k::KV_Q8_GROUP)));
155    for (auto& x : sc) x = f16_scale_q8(rng());
156    uint16_t* k8s = upload(sc);
157    for (auto& x : sc) x = f16_scale_q8(rng());
158    uint16_t* v8s = upload(sc);
159    std::vector<int32_t> tab((size_t) pages);
160    for (int64_t i = 0; i < pages; ++i) tab[(size_t) i] = (int32_t) i;
161    int32_t* table = upload(tab);
162    k::QsaAttnPools pools;
163    pools.page_table = table;
164    pools.k_q = k8; pools.v_q = v8; pools.k_scale = k8s; pools.v_scale = v8s;
165
166    // ---- the indexer's state: pooled keys (unit-ish rows), the spare, a tail, the block position
167    std::vector<float> hp((size_t) (max_blocks * ID));
168    for (auto& x : hp) x = nd(rng) * 0.09f;
169    float* pooled = upload(hp);
170    hp.clear(); hp.shrink_to_fit();
171    std::vector<float> hd((size_t) ID);
172    for (auto& x : hd) x = nd(rng) * 0.09f;
173    float* dead = upload(hd);
174    float* tail = dalloc<float>((size_t) (s.idx_block - 1) * ID);
175    int32_t* block_pos = dalloc<int32_t>(1);
176    std::vector<float> hg((size_t) ID, 1.0f);
177    float* gamma = upload(hg);
178    // the T rows' indexer queries: one query perturbed a little per row, so the selections overlap as a window's do
179    std::vector<float> hq0((size_t) (IQ * ID)), hqi((size_t) (MAXT * IQ * ID));
180    for (auto& x : hq0) x = nd(rng);
181    for (int t = 0; t < MAXT; ++t)
182        for (int i = 0; i < IQ * ID; ++i) hqi[(size_t) t * IQ * ID + i] = hq0[(size_t) i] + 0.15f * nd(rng);
183    float* q_idx = upload(hqi);
184    std::vector<float> hraw((size_t) (MAXT * ID));
185    for (auto& x : hraw) x = nd(rng);
186    float* raw = upload(hraw);
187    // the attention queries [MAXT, NH, HD]
188    std::vector<float> hq((size_t) (MAXT * NH * HD));
189    for (auto& x : hq) x = nd(rng);
190    float* q = upload(hq);
191    // step records for rows 0..MAXT-1 at cells ctx .. ctx + MAXT - 1 (verify: pos, n_kv, n_bid, width)
192    std::vector<int32_t> hst((size_t) (MAXT * k::kStepCount));
193    for (int t = 0; t < MAXT; ++t) {
194        const int64_t pos = ctx + t, n_kv = pos + 1;
195        hst[(size_t) t * k::kStepCount + k::kStepPos] = (int32_t) pos;
196        hst[(size_t) t * k::kStepCount + k::kStepNKv] = (int32_t) n_kv;
197        hst[(size_t) t * k::kStepCount + k::kStepNBid] = (int32_t) (n_kv / s.idx_block);
198        hst[(size_t) t * k::kStepCount + k::kStepWidth] = (int32_t) k::qsa_selection_width(n_kv, s);
199    }
200    int32_t* steps = upload(hst);
201    // the drafter's dense window: the same cells, width = the window
202    std::vector<int32_t> hsd(hst);
203    for (int t = 0; t < MAXT; ++t) hsd[(size_t) t * k::kStepCount + k::kStepWidth] = (int32_t) dense_win;
204    int32_t* steps_d = upload(hsd);
205    std::vector<int32_t> hwid((size_t) (MAXT * dense_cap));
206    for (int t = 0; t < MAXT; ++t)
207        for (int64_t j = 0; j < dense_win; ++j) hwid[(size_t) t * dense_cap + j] = (int32_t) (ctx + t + 1 - dense_win + j);
208    int32_t* ids_d = upload(hwid);
209    hwid.clear(); hwid.shrink_to_fit();
210
211    float* scores = dalloc<float>((size_t) (MAXT * max_blocks));
212    int32_t* ids = dalloc<int32_t>((size_t) (MAXT * cap));
213    const size_t scr_floats = (size_t) k::qsa_decode_attn_scratch_floats(cap, s);
214    float* scratch = dalloc<float>(scr_floats * MAXT);
215    float* attn = dalloc<float>((size_t) (MAXT * NH * HD));
216    const size_t scr_floats_d = (size_t) k::qsa_decode_attn_scratch_floats(dense_cap, s);
217    float* scratch_d = dalloc<float>(scr_floats_d * MAXT);
218    float* attn_d = dalloc<float>((size_t) (MAXT * NH * HD));
219    const k::QsaIndexerBuffers ib{tail, dead, pooled, block_pos};
220    const k::RopeScaling scaling;
221
222    // ---- the selections once (the attention's inputs), and how much the rows' selections overlap
223    k::qsa_block_scores(pooled, dead, q_idx, steps, MAXT, max_blocks, s, scores, st);
224    k::qsa_block_topk(scores, steps, MAXT, max_blocks, cap, s, ids, st);
225    ck(cudaDeviceSynchronize(), "selection");
226    {
227        const std::vector<int32_t> hid = download(ids, (size_t) (MAXT * cap));
228        std::printf("  selections: width %d a row;", hst[k::kStepWidth]);
229        for (int T = 2; T <= MAXT; ++T) {
230            std::set<int32_t> u;
231            for (int t = 0; t < T; ++t)
232                for (int j = 0; j < hst[(size_t) t * k::kStepCount + k::kStepWidth]; ++j) u.insert(hid[(size_t) t * cap + j]);
233            std::printf(" union of %d rows %zu cells (%.2fx one row)", T, u.size(), (double) u.size() / hst[k::kStepWidth]);
234        }
235        std::puts("");
236    }
237
238    Timer tm;
239    Table t_scores, t_topk, t_attn, t_append, t_layer, t_dense;
240    for (int T = 1; T <= MAXT; ++T) {
241        t_scores.us[T] = tm.us([&] { k::qsa_block_scores(pooled, dead, q_idx, steps, T, max_blocks, s, scores, st); }, iters);
242        t_topk.us[T] = tm.us([&] { k::qsa_block_topk(scores, steps, T, max_blocks, cap, s, ids, st); }, iters);
243        t_attn.us[T] = tm.us([&] { k::qsa_decode_attn_batch(q, pools, ids, steps, cap, s, scratch, attn, T, st); }, iters);
244        // the append writes the tail / pooled / block_pos the scores read; its own cells (ctx .. ctx + T - 1) land in
245        // the tail (ctx % 4 == 0) and, at T == 4, complete block ctx / 4: the same state every call
246        t_append.us[T] = tm.us([&] {
247            k::native_qsa_indexer_append_steps(raw, steps + k::kStepPos, (int) k::kStepCount, T, 0, gamma, 1e-6f, ib, s,
248                                               max_cells, scaling, st);
249        }, iters);
250        t_layer.us[T] = tm.us([&] {
251            k::native_qsa_indexer_append_steps(raw, steps + k::kStepPos, (int) k::kStepCount, T, 0, gamma, 1e-6f, ib, s,
252                                               max_cells, scaling, st);
253            k::qsa_block_scores(pooled, dead, q_idx, steps, T, max_blocks, s, scores, st);
254            k::qsa_block_topk(scores, steps, T, max_blocks, cap, s, ids, st);
255            k::qsa_decode_attn_batch(q, pools, ids, steps, cap, s, scratch, attn, T, st);
256        }, iters);
257        if (dense)
258            t_dense.us[T] = tm.us([&] {
259                k::qsa_decode_attn_batch(q, pools, ids_d, steps_d, dense_cap, s, scratch_d, attn_d, T, st);
260            }, iters);
261    }
262    std::puts("-- a QSA layer's decode kernels at the verification window's shape (us a call, median of 3 runs)");
263    t_scores.print("scores  qsa_block_scores (multi)");
264    t_topk.print("topk    qsa_block_topk");
265    t_attn.print("attn    qsa_decode_attn_batch cap 2051");
266    t_append.print("append  native_qsa_indexer_append_steps");
267    t_layer.print("layer   append + scores + topk + attn");
268    if (dense) {
269        std::puts("-- the drafter's dense window (32768 cells a row): the shape the hypothesis's ~240 us a query comes from");
270        t_dense.print("dense   qsa_decode_attn_batch cap 32768");
271    }
272    const double per_row = (t_layer.us[MAXT] - t_layer.us[1]) / (MAXT - 1);
273    std::printf("-- per row: %.1f us a QSA layer -> x4 layers (stage 0) %.2f ms, x8 layers (stage 1) %.2f ms\n", per_row,
274                4 * per_row / 1000.0, 8 * per_row / 1000.0);
275
276    bool ok = true;
277    if (rows) {
278        // QSAROWS: block_scores_rows_kernel (STRATA_QSA_ROWS=1) against block_scores_multi_kernel, bit for bit on the scores
279        // and on the ids the top-k draws from them, at every T; then the microseconds of the two
280        std::puts("-- STRATA_QSA_ROWS: qsa_block_scores_rows against qsa_block_scores (multi), scores and ids bit for bit");
281        float* scores_b = dalloc<float>((size_t) (MAXT * max_blocks));
282        int32_t* ids_b = dalloc<int32_t>((size_t) (MAXT * cap));
283        long long cases = 0, failed = 0;
284        Table t_rows;
285        for (int T = 1; T <= MAXT; ++T) {
286            ck(cudaMemset(scores, 0xFF, (size_t) MAXT * max_blocks * 4), "fill");
287            ck(cudaMemset(scores_b, 0xFF, (size_t) MAXT * max_blocks * 4), "fill");
288            ck(cudaMemset(ids, 0x7F, (size_t) MAXT * cap * 4), "fill");
289            ck(cudaMemset(ids_b, 0x7F, (size_t) MAXT * cap * 4), "fill");
290            k::qsa_block_scores(pooled, dead, q_idx, steps, T, max_blocks, s, scores, st);
291            if (!k::qsa_block_scores_rows(pooled, dead, q_idx, steps, T, max_blocks, s, scores_b, st)) {
292                std::printf("  FAIL T=%d: qsa_block_scores_rows refused the call\n", T);
293                ++cases; ++failed;
294                continue;
295            }
296            k::qsa_block_topk(scores, steps, T, max_blocks, cap, s, ids, st);
297            k::qsa_block_topk(scores_b, steps, T, max_blocks, cap, s, ids_b, st);
298            ck(cudaDeviceSynchronize(), "rows sync");
299            const std::vector<float> a = download(scores, (size_t) T * max_blocks), b = download(scores_b, (size_t) T * max_blocks);
300            const std::vector<int32_t> ia = download(ids, (size_t) T * cap), ib2 = download(ids_b, (size_t) T * cap);
301            ++cases;
302            const bool same_s = std::memcmp(a.data(), b.data(), a.size() * 4) == 0;
303            const bool same_i = std::memcmp(ia.data(), ib2.data(), ia.size() * 4) == 0;
304            if (!same_s || !same_i) {
305                ++failed;
306                size_t count = 0, first = a.size();
307                for (size_t i = 0; i < a.size(); ++i)
308                    if (std::memcmp(&a[i], &b[i], 4) != 0) { if (first == a.size()) first = i; ++count; }
309                std::printf("  FAIL T=%d: scores %s (%zu of %zu differ, first at query %zu block %zu), ids %s\n", T,
310                            same_s ? "same" : "DIFFER", count, a.size(), first / (size_t) max_blocks, first % (size_t) max_blocks,
311                            same_i ? "same" : "DIFFER");
312            }
313            t_rows.us[T] = tm.us([&] { k::qsa_block_scores_rows(pooled, dead, q_idx, steps, T, max_blocks, s, scores_b, st); },
314                                 iters);
315        }
316        // a short context too (n_bid small, the tail block with cells): rows at cells 100..103
317        {
318            std::vector<int32_t> hs2(hst);
319            for (int t = 0; t < MAXT; ++t) {
320                const int64_t pos = 100 + t, n_kv = pos + 1;
321                hs2[(size_t) t * k::kStepCount + k::kStepPos] = (int32_t) pos;
322                hs2[(size_t) t * k::kStepCount + k::kStepNKv] = (int32_t) n_kv;
323                hs2[(size_t) t * k::kStepCount + k::kStepNBid] = (int32_t) (n_kv / s.idx_block);
324                hs2[(size_t) t * k::kStepCount + k::kStepWidth] = (int32_t) k::qsa_selection_width(n_kv, s);
325            }
326            int32_t* steps2 = upload(hs2);
327            for (int T = 1; T <= MAXT; ++T) {
328                ck(cudaMemset(scores, 0xFF, (size_t) MAXT * max_blocks * 4), "fill");
329                ck(cudaMemset(scores_b, 0xFF, (size_t) MAXT * max_blocks * 4), "fill");
330                k::qsa_block_scores(pooled, dead, q_idx, steps2, T, max_blocks, s, scores, st);
331                k::qsa_block_scores_rows(pooled, dead, q_idx, steps2, T, max_blocks, s, scores_b, st);
332                ck(cudaDeviceSynchronize(), "rows sync");
333                const std::vector<float> a = download(scores, (size_t) T * max_blocks), b = download(scores_b, (size_t) T * max_blocks);
334                ++cases;
335                if (std::memcmp(a.data(), b.data(), a.size() * 4) != 0) { ++failed; std::printf("  FAIL short context T=%d\n", T); }
336            }
337            ck(cudaFree(steps2), "free");
338        }
339        std::printf("  parity: %lld cases, %lld differ -> %s\n", cases, failed, failed ? "FAIL" : "bit-identical");
340        ok = failed == 0;
341        t_scores.print("scores  qsa_block_scores (multi, reference)");
342        t_rows.print("scores  qsa_block_scores_rows");
343        ck(cudaFree(scores_b), "free");
344        ck(cudaFree(ids_b), "free");
345    }
346    for (void* p : {(void*) k8, (void*) v8, (void*) k8s, (void*) v8s, (void*) table, (void*) pooled, (void*) dead,
347                    (void*) tail, (void*) block_pos, (void*) gamma, (void*) q_idx, (void*) raw, (void*) q, (void*) steps,
348                    (void*) steps_d, (void*) ids_d, (void*) scores, (void*) ids, (void*) scratch, (void*) attn,
349                    (void*) scratch_d, (void*) attn_d})
350        ck(cudaFree(p), "free");
351    std::printf("qsa_rows_bench: %s\n", ok ? "done" : "FAIL");
352    return ok ? 0 : 1;
353}