okami.mom/strata

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

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

main
9.2 KiB198 linesraw
1// bench/qsa_prompt_attn_sm70_bench.cpp - the Volta (sm_70) prompt attention against the FP32 kernel it replaces.
2//
3// Same synthetic pools and prompt-shaped selections as src/kernels/qsa_prompt_attn_parity.cpp (GPU, no model), but
4// timing is the point: for each KV format (int8, fp16) and a sweep of query counts it times
5// `qsa_decode_attn_batch` (the FP32 fallback, in batches of 32 as prefill.cpp calls it) against
6// `qsa_prompt_attn_batch` with CUDA events, and reports the output difference.  Run it on one card:
7//   flock /tmp/opencode/gpu.lock -c 'CUDA_VISIBLE_DEVICES=0 ./qsa_prompt_attn_sm70_bench [ctx=32768] [nq=2048] [reps=10]'
8#include "strata/kernels/qsa.hpp"
9#include "strata/kernels/qsa_decode_attn.hpp"
10#include "strata/kernels/qsa_prompt_attn.hpp"
11
12#include <cuda_fp16.h>
13#include <cuda_runtime.h>
14
15#include <algorithm>
16#include <cmath>
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20#include <functional>
21#include <random>
22#include <vector>
23
24namespace k = strata::kernels;
25
26namespace {
27void ck(cudaError_t e, const char* w) {
28    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
29}
30template <typename T> T* up(const std::vector<T>& h) {
31    T* d = nullptr;
32    ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc");
33    ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");
34    return d;
35}
36uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast<uint16_t*>(&h); }
37
38// one synthetic prompt: the widest selection the shape has (2,051 cells at 32K), a recent window plus older cells
39// that drift slowly from query to query, as qsa_prompt_attn_parity builds them.  fmt 1 int8 KV, 0 fp16 KV,
40// 2 hybrid K8V4 (int8 K, q4_0 V - the Q2_0 engine's pools)
41void build(int fmt, int64_t ctx, int64_t nq, std::vector<int8_t>& kq, std::vector<int8_t>& vq, std::vector<uint16_t>& ks,
42           std::vector<uint16_t>& vs, std::vector<uint16_t>& kh, std::vector<uint16_t>& vh, std::vector<uint8_t>& vq4,
43           std::vector<int32_t>& table, std::vector<int32_t>& ids, std::vector<int32_t>& steps, std::vector<float>& q,
44           int64_t& cap) {
45    const k::QsaShapes s = k::qsa_real_shapes();
46    const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size;
47    const int64_t pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS;
48    std::mt19937 rng(1234 + fmt);
49    std::normal_distribution<float> nd(0.f, 1.f);
50    std::uniform_int_distribution<int> code(-127, 127);
51    std::uniform_real_distribution<float> sc(0.005f, 0.03f);
52    if (fmt == 1 || fmt == 2) {
53        kq.resize(rows * HD); ks.resize(rows * 4);
54        for (auto& x : kq) x = (int8_t) code(rng);
55        for (auto& x : ks) x = f2h(sc(rng));
56        if (fmt == 1) {
57            vq.resize(rows * HD); vs.resize(rows * 4);
58            for (auto& x : vq) x = (int8_t) code(rng);
59            for (auto& x : vs) x = f2h(sc(rng));
60        } else {
61            vq4.resize((size_t) (rows * (HD / 32) * 18));   // q4_0 blocks: a finite fp16 scale + random nibbles
62            for (size_t i = 0; i < vq4.size(); i += 18) {
63                const uint16_t d = f2h(sc(rng));
64                vq4[i] = (uint8_t) d; vq4[i + 1] = (uint8_t) (d >> 8);
65                for (int j = 2; j < 18; ++j) vq4[i + j] = (uint8_t) rng();
66            }
67        }
68    } else {
69        kh.resize(rows * HD); vh.resize(rows * HD);
70        for (auto& x : kh) x = f2h(nd(rng) * 1.5f);
71        for (auto& x : vh) x = f2h(nd(rng));
72    }
73    table.resize(pages);
74    for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i;
75    std::shuffle(table.begin(), table.end(), rng);
76    cap = k::qsa_selection_width(ctx, s);
77    ids.assign((size_t) (nq * cap), 0);
78    steps.assign((size_t) (nq * k::kStepCount), 0);
79    q.assign((size_t) (nq * NH * HD), 0.f);
80    for (auto& x : q) x = nd(rng) * 2.0f;
81    std::vector<int32_t> old_cells;
82    for (int64_t i = 0; i < nq; ++i) {
83        const int64_t pos = ctx - nq + i, nkv = pos + 1;
84        const int64_t w = k::qsa_selection_width(nkv, s);
85        int32_t* sel = ids.data() + i * cap;
86        steps[i * k::kStepCount + k::kStepWidth] = (int32_t) w;
87        if (w == nkv) {
88            for (int64_t c = 0; c < w; ++c) sel[c] = (int32_t) c;
89            continue;
90        }
91        const int64_t recent = 512, older = w - recent;
92        if ((int64_t) old_cells.size() != older) {
93            std::vector<int32_t> all((size_t) (nkv - recent));
94            for (int64_t c = 0; c < nkv - recent; ++c) all[c] = (int32_t) c;
95            std::shuffle(all.begin(), all.end(), rng);
96            old_cells.assign(all.begin(), all.begin() + older);
97        } else {
98            std::uniform_int_distribution<int64_t> pick(0, older - 1), any(0, nkv - recent - 1);
99            for (int r = 0; r < older / 32; ++r) {
100                const int32_t c = (int32_t) any(rng);
101                if (std::find(old_cells.begin(), old_cells.end(), c) == old_cells.end()) old_cells[pick(rng)] = c;
102            }
103        }
104        std::vector<int32_t> v(old_cells);
105        for (int64_t c = nkv - recent; c < nkv; ++c) v.push_back((int32_t) c);
106        std::sort(v.begin(), v.end());
107        std::copy(v.begin(), v.end(), sel);
108    }
109}
110
111float time_ms(const std::function<void()>& f, int reps) {
112    cudaEvent_t e0, e1;
113    ck(cudaEventCreate(&e0), "event");
114    ck(cudaEventCreate(&e1), "event");
115    f();
116    ck(cudaDeviceSynchronize(), "warm");
117    ck(cudaEventRecord(e0), "event");
118    for (int r = 0; r < reps; ++r) f();
119    ck(cudaEventRecord(e1), "event");
120    ck(cudaEventSynchronize(e1), "time");
121    float ms = 0;
122    ck(cudaEventElapsedTime(&ms, e0, e1), "time");
123    cudaEventDestroy(e0);
124    cudaEventDestroy(e1);
125    return ms / reps;
126}
127
128void run(int fmt, int64_t ctx, int64_t nq, int reps) {
129    const k::QsaShapes s = k::qsa_real_shapes();
130    const int64_t HD = s.head_dim, NH = s.n_head;
131    std::vector<int8_t> kq, vq;
132    std::vector<uint16_t> ks, vs, kh, vh;
133    std::vector<uint8_t> vq4;
134    std::vector<int32_t> table, ids, steps;
135    std::vector<float> q;
136    int64_t cap = 0;
137    build(fmt, ctx, nq, kq, vq, ks, vs, kh, vh, vq4, table, ids, steps, q, cap);
138    k::QsaAttnPools pl;
139    if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); }
140    else if (fmt == 2) { pl.k_q = up(kq); pl.k_scale = up(ks); pl.v_q4 = up(vq4); }
141    else { pl.k_pool = up(kh); pl.v_pool = up(vh); }
142    pl.page_table = up(table);
143    const int32_t* d_ids = up(ids);
144    const int32_t* d_steps = up(steps);
145    const float* d_q = up(q);
146    float *d_old = nullptr, *d_new = nullptr, *scratch = nullptr;
147    const int64_t batch = 32;
148    ck(cudaMalloc(&d_old, nq * NH * HD * 4), "malloc");
149    ck(cudaMalloc(&d_new, nq * NH * HD * 4), "malloc");
150    ck(cudaMalloc(&scratch, batch * k::qsa_decode_attn_scratch_floats(cap, s) * 4), "malloc");
151    std::printf("# %s KV, ctx %lld, selection %lld cells, %lld queries of %lld heads x %lld dims\n",
152                fmt == 1 ? "int8" : fmt == 2 ? "int8+q4 V (K8V4)" : "fp16", (long long) ctx, (long long) cap,
153                (long long) nq, (long long) NH, (long long) HD);
154    const int64_t counts[] = {16, 64, 256, 1024, 2048, 4096};
155    for (int64_t nqi : counts) {
156        if (nqi > nq) continue;
157        auto old_run = [&]() {
158            for (int64_t t0 = 0; t0 < nqi; t0 += batch)
159                k::qsa_decode_attn_batch(d_q + t0 * NH * HD, pl, d_ids + t0 * cap, d_steps + t0 * k::kStepCount, cap,
160                                         s, scratch, d_old + t0 * NH * HD, std::min(batch, nqi - t0), nullptr);
161        };
162        auto new_run = [&]() {
163            if (!k::qsa_prompt_attn_batch(d_q, pl, d_ids, d_steps, cap, s, d_new, nqi, nullptr)) {
164                std::fprintf(stderr, "qsa_prompt_attn_batch refused the pools\n");
165                std::exit(2);
166            }
167        };
168        old_run(); new_run();
169        ck(cudaDeviceSynchronize(), "run");
170        std::vector<float> o((size_t) (nqi * NH * HD)), nw(o.size());
171        ck(cudaMemcpy(o.data(), d_old, o.size() * 4, cudaMemcpyDeviceToHost), "down");
172        ck(cudaMemcpy(nw.data(), d_new, nw.size() * 4, cudaMemcpyDeviceToHost), "down");
173        double diff = 0, scale = 0;
174        for (size_t i = 0; i < o.size(); ++i) {
175            diff = std::max(diff, (double) std::fabs(o[i] - nw[i]));
176            scale = std::max(scale, (double) std::fabs(o[i]));
177        }
178        const float ms_old = time_ms(old_run, reps), ms_new = time_ms(new_run, reps);
179        std::printf("q %5lld: fp32 %8.3f ms   volta %8.3f ms   %5.2fx   max|old-new| %.3g (%.2g of scale)\n",
180                    (long long) nqi, ms_old, ms_new, ms_old / ms_new, diff, scale > 0 ? diff / scale : 0.0);
181    }
182    cudaFree((void*) d_ids); cudaFree((void*) d_steps); cudaFree((void*) d_q); cudaFree(d_old); cudaFree(d_new);
183    cudaFree(scratch);
184    cudaFree((void*) pl.k_q); cudaFree((void*) pl.v_q); cudaFree((void*) pl.k_scale); cudaFree((void*) pl.v_scale);
185    cudaFree((void*) pl.v_q4);
186    cudaFree((void*) pl.k_pool); cudaFree((void*) pl.v_pool); cudaFree((void*) pl.page_table);
187}
188}  // namespace
189
190int main(int argc, char** argv) {
191    const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 32768;
192    const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 2048;
193    const int reps = argc > 3 ? std::atoi(argv[3]) : 10;
194    run(1, ctx, nq, reps);
195    run(2, ctx, nq, reps);
196    run(0, ctx, nq, reps);
197    return 0;
198}