okami.mom/strata

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

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

main
19.7 KiB378 linesraw
1// src/kernels/qsa_prompt_attn_parity.cpp - perf-review D-1: the tensor-core prompt attention (qsa_prompt_attn.hpp)
2// against the FP32 kernel it replaces (`qsa_decode_attn_batch`) and an FP64 host reference (GPU, synthetic, no model).
3//
4// Int8, FP16 and Q4_0 pools with random codes, scales and queries; selections shaped like the prompt path's (the 2,051
5// widest, a recent window plus older cells that drift slowly from one query to the next, so neighbours share most
6// of them as they do in a real prompt; short contexts take every cell). Checks:
7//   1. against FP64, the new kernel's error is no larger than a small multiple of the old kernel's (both FP32 math);
8//   2. the new and old outputs agree to a relative 1e-4 of the output scale;
9// then times both over a prompt chunk (the old one in batches of 32, as prefill.cpp calls it).
10// HIP builds (S6): the same checks for the RDNA4 matrix-core kernel (STRATA_HIP_WMMA), skipped (77) off gfx12.
11// Usage: qsa_prompt_attn_parity [context=32768] [queries=2048] [reps=5]
12#include "strata/kernels/qsa.hpp"
13#include "strata/kernels/qsa_decode_attn.hpp"
14#include "strata/kernels/qsa_prompt_attn.hpp"
15#include "strata/kernels/kv_q4.hpp"
16
17#include <cuda_fp16.h>
18#include <cuda_runtime.h>
19
20#include <algorithm>
21#include <cmath>
22#include <cstdio>
23#include <cstdlib>
24#include <cstring>
25#include <random>
26#include <vector>
27
28namespace k = strata::kernels;
29
30namespace {
31void ck(cudaError_t e, const char* w) {
32    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
33}
34template <typename T> T* up(const std::vector<T>& h) {
35    T* d = nullptr;
36    ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc");
37    ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");
38    return d;
39}
40float h2f(uint16_t b) { __half h; *reinterpret_cast<uint16_t*>(&h) = b; return __half2float(h); }
41uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast<uint16_t*>(&h); }
42
43int run(int fmt, int64_t ctx, int64_t nq, int reps) {   // fmt 1 int8, 0 fp16, 2 q4_0
44#if !defined(__HIPCC__) && !defined(STRATA_USE_HIP)
45    if (fmt == 2) {   // mode 4 (Q4_0 KV) runs on sm_80 and newer only: below that the dispatcher keeps the old kernel
46        int dev = 0, major = 0;
47        ck(cudaGetDevice(&dev), "device");
48        ck(cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev), "cc");
49        if (major < 8) {
50            std::printf("SKIP q4_0 ctx %lld: the tensor-core kernel takes Q4_0 KV on sm_80+ only (this device: sm_%d)\n",
51                        (long long) ctx, major);
52            return 0;
53        }
54    }
55#endif
56    const k::QsaShapes s = k::qsa_real_shapes();
57    const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size;
58    const int64_t pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS;
59    std::mt19937 rng(1234 + fmt);
60    std::normal_distribution<float> nd(0.f, 1.f);
61    std::uniform_int_distribution<int> code(-127, 127);
62    std::uniform_real_distribution<float> sc(0.005f, 0.03f);
63    // pools; page table a shuffled permutation (the readers must follow it)
64    std::vector<int8_t> kq, vq;
65    std::vector<uint16_t> ks, vs, kh, vh;
66    std::vector<uint8_t> k4, v4;   // q4_0: 8 blocks of {fp16 d, 16 code bytes} per row (kv_q4.hpp)
67    constexpr int64_t B4 = 18, ROW4 = 8 * B4;
68    if (fmt == 2) {
69        std::uniform_int_distribution<int> byte(0, 255);
70        // the scales as a q4_0 pool holds them: signed (ggml's d = max / -8) and spread over two decades, so a chunk's
71        // cells mix signs and magnitudes (a positive-only bound on them overflowed FP16 on real K/V)
72        std::uniform_real_distribution<float> lg(std::log(0.01f), std::log(1.0f));
73        auto sc4 = [&](std::mt19937& r) { return std::exp(lg(r)) * (byte(r) & 1 ? -1.0f : 1.0f); };
74        k4.resize(rows * ROW4); v4.resize(rows * ROW4);
75        for (auto* pool : {&k4, &v4})
76            for (int64_t b = 0; b < rows * 8; ++b) {
77                const uint16_t d = f2h(sc4(rng));
78                std::memcpy(pool->data() + b * B4, &d, 2);
79                for (int j = 0; j < 16; ++j) (*pool)[b * B4 + 2 + j] = (uint8_t) byte(rng);
80            }
81    } else if (fmt == 1) {
82        kq.resize(rows * HD); vq.resize(rows * HD); ks.resize(rows * 4); vs.resize(rows * 4);
83        for (auto& x : kq) x = (int8_t) code(rng);
84        for (auto& x : vq) x = (int8_t) code(rng);
85        for (auto& x : ks) x = f2h(sc(rng));
86        for (auto& x : vs) x = f2h(sc(rng));
87    } else {
88        kh.resize(rows * HD); vh.resize(rows * HD);
89        for (auto& x : kh) x = f2h(nd(rng) * 1.5f);
90        for (auto& x : vh) x = f2h(nd(rng));
91    }
92    std::vector<int32_t> table(pages);
93    for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i;
94    std::shuffle(table.begin(), table.end(), rng);
95    // queries at positions ctx - nq .. ctx - 1
96    const int64_t cap = k::qsa_selection_width(ctx, s);
97    std::vector<int32_t> ids((size_t) (nq * cap), 0), steps((size_t) (nq * k::kStepCount), 0);
98    std::vector<float> q((size_t) (nq * NH * HD));
99    for (auto& x : q) x = nd(rng) * 2.0f;
100    std::vector<int32_t> old_cells;
101    for (int64_t i = 0; i < nq; ++i) {
102        const int64_t pos = ctx - nq + i, nkv = pos + 1;
103        const int64_t w = k::qsa_selection_width(nkv, s);
104        int32_t* sel = ids.data() + i * cap;
105        steps[i * k::kStepCount + k::kStepWidth] = (int32_t) w;
106        if (w == nkv) {
107            for (int64_t c = 0; c < w; ++c) sel[c] = (int32_t) c;
108            continue;
109        }
110        const int64_t recent = 512, older = w - recent;
111        if ((int64_t) old_cells.size() != older) {   // the older cells: a set that drifts ~3% per query
112            std::vector<int32_t> all((size_t) (nkv - recent));
113            for (int64_t c = 0; c < nkv - recent; ++c) all[c] = (int32_t) c;
114            std::shuffle(all.begin(), all.end(), rng);
115            old_cells.assign(all.begin(), all.begin() + older);
116        } else {
117            std::uniform_int_distribution<int64_t> pick(0, older - 1), any(0, nkv - recent - 1);
118            for (int r = 0; r < older / 32; ++r) {
119                const int32_t c = (int32_t) any(rng);
120                if (std::find(old_cells.begin(), old_cells.end(), c) == old_cells.end()) old_cells[pick(rng)] = c;
121            }
122        }
123        std::vector<int32_t> v(old_cells);
124        for (int64_t c = nkv - recent; c < nkv; ++c) v.push_back((int32_t) c);
125        std::sort(v.begin(), v.end());
126        std::copy(v.begin(), v.end(), sel);
127    }
128    // QA_SAME=1 (S23 probe): every query reads the same first-w cells - the best case of any K/V sharing between queries
129    // (all loads hit the caches); QA_SAME=2: query i reads a window of w cells at i / 4 * 64 (neighbours share ~90%)
130    if (const char* sm = std::getenv("QA_SAME")) {
131        const int mode = std::atoi(sm);
132        for (int64_t i = 0; i < nq; ++i) {
133            const int64_t w = steps[i * k::kStepCount + k::kStepWidth], nkv = ctx - nq + i + 1;
134            if (w == nkv) continue;
135            if (mode == 3 || mode == 4) {   // 3: w random cells per query (no overlap beyond chance); 4: a 4-query group shares
136                // one random set of w - 512 cells (the union of 4 queries = 1x), the last 512 cells recent
137                std::mt19937 r3((unsigned) (mode == 3 ? i : i / 4) * 2654435761u + 7);
138                std::vector<int32_t> all((size_t) (nkv - 512));
139                for (int64_t c = 0; c < nkv - 512; ++c) all[c] = (int32_t) c;
140                std::shuffle(all.begin(), all.end(), r3);
141                std::vector<int32_t> v(all.begin(), all.begin() + (w - 512));
142                for (int64_t c = nkv - 512; c < nkv; ++c) v.push_back((int32_t) c);
143                std::sort(v.begin(), v.end());
144                std::copy(v.begin(), v.end(), ids.data() + i * cap);
145                continue;
146            }
147            const int64_t base = mode == 1 ? 0 : std::min<int64_t>(i / 4 * 64, nkv - w);
148            for (int64_t c = 0; c < w; ++c) ids[i * cap + c] = (int32_t) (base + c);
149        }
150    }
151    // QA_DUMP=<file> QA_LAYER=n (S23 probe): the engine's own selections (STRATA_QSA_DUMP records {layer, pos0, T, cap} +
152    // T*cap cells): the last record of that layer, whose T must be nq and pos0 + T ctx
153    if (const char* df = std::getenv("QA_DUMP")) {
154        const int want = std::getenv("QA_LAYER") ? std::atoi(std::getenv("QA_LAYER")) : 3;
155        std::FILE* f = std::fopen(df, "rb");
156        if (!f) { std::fprintf(stderr, "QA_DUMP: cannot open\n"); std::exit(2); }
157        int32_t h[4];
158        long at = -1;
159        while (std::fread(h, 4, 4, f) == 4) {
160            const long data = std::ftell(f);
161            if (h[0] == want && h[2] == nq && h[1] + h[2] == ctx && h[3] == cap) at = data;
162            std::fseek(f, (long) h[2] * h[3] * 4, SEEK_CUR);
163        }
164        if (at < 0) { std::fprintf(stderr, "QA_DUMP: no record for layer %d, T %lld, ctx %lld\n", want, (long long) nq, (long long) ctx); std::exit(2); }
165        std::fseek(f, at, SEEK_SET);
166        if (std::fread(ids.data(), 4, ids.size(), f) != ids.size()) std::exit(2);
167        std::fclose(f);
168        for (int grp : {2, 4, 8, 16}) {   // the union of `grp` neighbouring queries' cells against grp x the width
169            double su = 0, sw = 0;
170            for (int64_t i0 = 0; i0 + grp <= nq; i0 += grp * 16) {
171                std::vector<int32_t> u;
172                for (int g2 = 0; g2 < grp; ++g2) {
173                    const int64_t w = steps[(i0 + g2) * k::kStepCount + k::kStepWidth];
174                    u.insert(u.end(), ids.begin() + (i0 + g2) * cap, ids.begin() + (i0 + g2) * cap + w);
175                    sw += (double) w;
176                }
177                std::sort(u.begin(), u.end());
178                su += (double) (std::unique(u.begin(), u.end()) - u.begin());
179            }
180            std::printf("QA_DUMP overlap: %d-query groups read %.2fx the cells of one query (%.1f%% of %d x)\n", grp,
181                        su * grp / sw, 100.0 * su / sw, grp);
182        }
183    }
184    k::QsaAttnPools pl;
185    if (fmt == 2) { pl.k_q4 = up(k4); pl.v_q4 = up(v4); }
186    else if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); }
187    else { pl.k_pool = up(kh); pl.v_pool = up(vh); }
188    // a q4_0 value: block d / 32 of the row, element j = d % 32 in the low nibble of byte j (j < 16), else the high
189    // nibble of byte j - 16, minus 8, times the block's scale
190    auto q4v = [&](const std::vector<uint8_t>& pool, int64_t row, int64_t d) {
191        const uint8_t* blk = pool.data() + row * ROW4 + (d / 32) * B4;
192        uint16_t sc;
193        std::memcpy(&sc, blk, 2);
194        const int j = (int) (d % 32);
195        const int code = j < 16 ? (blk[2 + j] & 0x0F) : (blk[2 + j - 16] >> 4);
196        return (double) (code - 8) * h2f(sc);
197    };
198    pl.page_table = up(table);
199    const int32_t* d_ids = up(ids);
200    const int32_t* d_steps = up(steps);
201    const float* d_q = up(q);
202    float *d_old = nullptr, *d_new = nullptr, *scratch = nullptr;
203    const int64_t batch = 32;
204    ck(cudaMalloc(&d_old, nq * NH * HD * 4), "malloc");
205    ck(cudaMalloc(&d_new, nq * NH * HD * 4), "malloc");
206    ck(cudaMalloc(&scratch, batch * k::qsa_decode_attn_scratch_floats(cap, s) * 4), "malloc");
207    auto old_run = [&]() {
208        for (int64_t t0 = 0; t0 < nq; t0 += batch)
209            k::qsa_decode_attn_batch(d_q + t0 * NH * HD, pl, d_ids + t0 * cap, d_steps + t0 * k::kStepCount, cap, s,
210                                     scratch, d_old + t0 * NH * HD, std::min(batch, nq - t0), nullptr);
211    };
212    // int8 KV: v2 here, and the opt-in INT8-MMA kernel (STRATA_PROMPT_ATTN_IMMA) checked and timed below beside it
213    if (fmt == 1) k::qsa_prompt_attn_set_imma(0);
214    auto new_run = [&]() {
215        if (!k::qsa_prompt_attn_batch(d_q, pl, d_ids, d_steps, cap, s, d_new, nq, nullptr)) {
216            std::fprintf(stderr, "qsa_prompt_attn_batch refused the pools\n");
217            std::exit(2);
218        }
219    };
220    float* d_im = nullptr;
221    ck(cudaMalloc(&d_im, nq * NH * HD * 4), "malloc");
222    auto imma_run = [&]() {
223        k::qsa_prompt_attn_set_imma(1);
224        const bool ok = k::qsa_prompt_attn_batch(d_q, pl, d_ids, d_steps, cap, s, d_im, nq, nullptr);
225        k::qsa_prompt_attn_set_imma(0);
226        if (!ok) { std::fprintf(stderr, "qsa_prompt_attn_batch refused the pools (imma)\n"); std::exit(2); }
227    };
228    old_run();
229    new_run();
230    if (fmt == 1) imma_run();
231    ck(cudaDeviceSynchronize(), "run");
232    std::vector<float> o((size_t) (nq * NH * HD)), nw(o.size()), im(fmt == 1 ? o.size() : 0);
233    if (fmt == 1) ck(cudaMemcpy(im.data(), d_im, im.size() * 4, cudaMemcpyDeviceToHost), "down");
234    ck(cudaMemcpy(o.data(), d_old, o.size() * 4, cudaMemcpyDeviceToHost), "down");
235    ck(cudaMemcpy(nw.data(), d_new, nw.size() * 4, cudaMemcpyDeviceToHost), "down");
236    {   // a hash of the new kernel's output bits (bitwise A/B of two builds / switches)
237        uint64_t hh = 1469598103934665603ull;
238        for (float x : nw) { uint32_t u; std::memcpy(&u, &x, 4); hh = (hh ^ u) * 1099511628211ull; }
239        std::printf("NEWHASH %016llx\n", (unsigned long long) hh);
240    }
241    // 1. FP64 reference on a sample of queries
242    double err_old = 0, err_new = 0, err_im = 0, ref_scale = 0;
243    for (int64_t i = 0; i < nq; i += std::max<int64_t>(1, nq / 16)) {
244        const int64_t w = steps[i * k::kStepCount + k::kStepWidth];
245        const int32_t* sel = ids.data() + i * cap;
246        for (int64_t h = 0; h < NH; ++h) {
247            const int64_t kvh = h / (NH / NKV);
248            std::vector<double> sco((size_t) w);
249            double mx = -1e300;
250            for (int64_t c = 0; c < w; ++c) {
251                const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS;
252                double a = 0;
253                for (int64_t d = 0; d < HD; ++d) {
254                    const double kv = fmt == 2 ? q4v(k4, row, d)
255                                      : fmt == 1 ? (double) kq[row * HD + d] * h2f(ks[row * 4 + d / 64]) : h2f(kh[row * HD + d]);
256                    a += (double) q[(i * NH + h) * HD + d] * kv;
257                }
258                sco[c] = a / 16.0;
259                mx = std::max(mx, sco[c]);
260            }
261            double l = 0;
262            for (auto& x : sco) { x = std::exp(x - mx); l += x; }
263            for (int64_t d = 0; d < HD; ++d) {
264                double a = 0;
265                for (int64_t c = 0; c < w; ++c) {
266                    const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS;
267                    const double vv = fmt == 2 ? q4v(v4, row, d)
268                                      : fmt == 1 ? (double) vq[row * HD + d] * h2f(vs[row * 4 + d / 64]) : h2f(vh[row * HD + d]);
269                    a += sco[c] * vv;
270                }
271                const double r = a / l;
272                const size_t at = (size_t) ((i * NH + h) * HD + d);
273                ref_scale = std::max(ref_scale, std::fabs(r));
274                err_old = std::max(err_old, std::fabs(o[at] - r));
275                err_new = std::max(err_new, std::fabs(nw[at] - r));
276                if (fmt == 1) err_im = std::max(err_im, std::fabs(im[at] - r));
277            }
278        }
279    }
280    // 2. new vs old everywhere
281    double diff = 0, scale = 0;
282    for (size_t i = 0; i < o.size(); ++i) {
283        diff = std::max(diff, (double) std::fabs(o[i] - nw[i]));
284        scale = std::max(scale, (double) std::fabs(o[i]));
285    }
286    // 3. speed
287    cudaEvent_t e0, e1;
288    cudaEventCreate(&e0);
289    cudaEventCreate(&e1);
290    float ms_old = 0, ms_new = 0;
291    cudaEventRecord(e0);
292    for (int r = 0; r < reps; ++r) old_run();
293    cudaEventRecord(e1);
294    ck(cudaEventSynchronize(e1), "time");
295    cudaEventElapsedTime(&ms_old, e0, e1);
296    cudaEventRecord(e0);
297    for (int r = 0; r < reps; ++r) new_run();
298    cudaEventRecord(e1);
299    ck(cudaEventSynchronize(e1), "time");
300    cudaEventElapsedTime(&ms_new, e0, e1);
301    bool ok_im = true;
302    if (fmt == 1) {   // the INT8-MMA kernel: the same bounds as v2's, against FP64 and against v2
303        double d_iv = 0;
304        for (size_t i = 0; i < o.size(); ++i) d_iv = std::max(d_iv, (double) std::fabs(im[i] - nw[i]));
305        float ms_im = 0, ms_v2 = 0;
306        for (int round = 0; round < 2; ++round) {   // alternating, v2 then imma, twice; the second round counts
307            cudaEventRecord(e0);
308            for (int r = 0; r < reps; ++r) new_run();
309            cudaEventRecord(e1);
310            ck(cudaEventSynchronize(e1), "time");
311            cudaEventElapsedTime(&ms_v2, e0, e1);
312            cudaEventRecord(e0);
313            for (int r = 0; r < reps; ++r) imma_run();
314            cudaEventRecord(e1);
315            ck(cudaEventSynchronize(e1), "time");
316            cudaEventElapsedTime(&ms_im, e0, e1);
317        }
318        ok_im = err_im <= std::max(4.0 * err_old, 1e-6 * ref_scale) && d_iv <= 1e-4 * scale;
319        std::printf("%s int8 IMMA ctx %lld, %lld queries: vs FP64 %.3g (v2 %.3g, FP32 %.3g); IMMA vs v2 %.3g (%.2g of scale); "
320                    "v2 %.3f -> IMMA %.3f ms per chunk (%.2fx)\n", ok_im ? "PASS" : "FAIL", (long long) ctx, (long long) nq,
321                    err_im, err_new, err_old, d_iv, d_iv / scale, ms_v2 / reps, ms_im / reps, ms_v2 / ms_im);
322    }
323    k::qsa_prompt_attn_set_imma(-1);
324    cudaFree(d_im);
325    const bool ok1 = err_new <= std::max(4.0 * err_old, 1e-6 * ref_scale) && ok_im;
326    const bool ok2 = diff <= 1e-4 * scale;
327    uint64_t sum = 1469598103934665603ull;   // the new kernel's output bits: two builds of it compare by this
328    for (float f : nw) {
329        uint32_t b;
330        std::memcpy(&b, &f, 4);
331        sum = (sum ^ b) * 1099511628211ull;
332    }
333    std::printf("%s %s ctx %lld, %lld queries: vs FP64 old %.3g new %.3g (output scale %.3g); new vs old %.3g (%.2g of "
334                "scale); %.3f -> %.3f ms per chunk (%.2fx); new output checksum %016llx\n",
335                ok1 && ok2 ? "PASS" : "FAIL", fmt == 2 ? "q4_0" : fmt == 1 ? "int8" : "fp16", (long long) ctx, (long long) nq, err_old,
336                err_new, ref_scale, diff, diff / scale, ms_old / reps, ms_new / reps, ms_old / ms_new, (unsigned long long) sum);
337    cudaFree((void*) d_ids); cudaFree((void*) d_steps); cudaFree((void*) d_q); cudaFree(d_old); cudaFree(d_new);
338    cudaFree(scratch);
339    cudaFree((void*) pl.k_q); cudaFree((void*) pl.v_q); cudaFree((void*) pl.k_scale); cudaFree((void*) pl.v_scale);
340    cudaFree((void*) pl.k_pool); cudaFree((void*) pl.v_pool); cudaFree((void*) pl.page_table);
341    cudaFree((void*) pl.k_q4); cudaFree((void*) pl.v_q4);
342    return ok1 && ok2 ? 0 : 1;
343}
344}  // namespace
345
346int main(int argc, char** argv) {
347#if defined(__HIP_PLATFORM_AMD__)
348    // S6: on AMD the kernel under test is the RDNA4 matrix-core one (opt-in in the engine); other cards skip
349    {
350        int dev = 0;
351        hipDeviceProp_t prop{};
352        if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return 2;
353        if (std::strncmp(prop.gcnArchName, "gfx12", 5) != 0 && std::strncmp(prop.gcnArchName, "gfx11", 5) != 0) {
354            std::printf("SKIP: %s is not gfx11 / gfx12 (the matrix-core prompt attention)\n", prop.gcnArchName);
355            return 77;
356        }
357#if defined(_WIN32)
358        _putenv_s("STRATA_HIP_WMMA", "1");
359#else
360        setenv("STRATA_HIP_WMMA", "1", 1);
361#endif
362    }
363#endif
364    const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 32768;
365    const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 2048;
366    const int reps = argc > 3 ? std::atoi(argv[3]) : 5;
367    int fails = 0;
368    fails += run(1, ctx, nq, reps);
369#if !defined(__HIP_PLATFORM_AMD__)
370    fails += run(0, ctx, nq, reps);   // FP16 KV: the RDNA4 kernel takes int8 KV only
371    fails += run(2, ctx, nq, reps);   // Q4_0 KV (mode 4)
372    fails += run(2, 1500, std::min<int64_t>(nq, 1500), reps);
373#endif
374    fails += run(1, 1500, std::min<int64_t>(nq, 1500), reps);   // short context: the selection is every cell
375    fails += run(1, 2100, std::min<int64_t>(nq, 256), reps);    // the identity-to-sparse edge
376    std::printf("FAILURES: %d\n", fails);
377    return fails;
378}