okami.mom/strata

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

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

main
13.3 KiB274 linesraw
1// src/kernels/batch_rows_parity.cpp - the batch window's one-launch-for-all-rows kernels (#2234, STRATA_BATCH_ATTN_ROWS /
2// STRATA_BATCH_GDN_GROUPS) against the per-row launches they replace, bitwise (GPU, synthetic, no model).
3//
4//   1. qsa_block_scores_rows   == qsa_block_scores, one call per row, each row with its OWN indexer keys;
5//   2. qsa_decode_attn_batch_rows == qsa_decode_attn_batch, one call per row, each row over its OWN K/V pools
6//      (int8 codes + scales, and fp16);
7//   3. gdn_step_norm_groups    == gdn_step_norm_multi, one call per slot group, in the window (all outputs, the state
8//      untouched) and in the 1-row commit (the state written after `keep` tokens).
9// Every case compares with memcmp, not a tolerance. Usage: batch_rows_parity
10#include "strata/kernels/qsa.hpp"
11#include "strata/kernels/qsa_decode_attn.hpp"
12#include "strata/kernels/qsa_select.hpp"
13#include "strata/kernels/verify_kernels.hpp"
14
15#include <cuda_fp16.h>
16#include <cuda_runtime.h>
17
18#include <algorithm>
19#include <cstdint>
20#include <cstdio>
21#include <cstdlib>
22#include <cstring>
23#include <random>
24#include <vector>
25
26namespace k = strata::kernels;
27
28namespace {
29void ck(cudaError_t e, const char* w) {
30    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
31}
32template <typename T> T* up(const std::vector<T>& h) {
33    T* d = nullptr;
34    ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc");
35    ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");
36    return d;
37}
38template <typename T> std::vector<T> down(const T* d, size_t n) {
39    std::vector<T> h(n);
40    ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "download");
41    return h;
42}
43uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast<uint16_t*>(&h); }
44
45int bad = 0;
46void report(const char* what, bool same) {
47    std::printf("  %-64s %s\n", what, same ? "bitwise" : "*** DIFFERS ***");
48    if (!same) ++bad;
49}
50
51// ---- 1. the block scores ----
52void scores_case(int rows) {
53    const k::QsaShapes s = k::qsa_real_shapes();
54    const int64_t max_blocks = 3000;
55    std::mt19937 rng(11 + rows);
56    std::normal_distribution<float> nd(0.f, 1.f);
57    k::QsaScoreRows sr;
58    sr.n = rows;
59    std::vector<const float*> pooled(rows), dead(rows);
60    std::vector<float> q((size_t) rows * s.idx_n_head * s.idx_dim);
61    for (auto& x : q) x = nd(rng);
62    std::vector<int32_t> steps((size_t) rows * k::kStepCount);
63    for (int r = 0; r < rows; ++r) {
64        std::vector<float> p((size_t) max_blocks * s.idx_dim), d((size_t) s.idx_dim);
65        for (auto& x : p) x = nd(rng);
66        for (auto& x : d) x = nd(rng);
67        pooled[r] = up(p);
68        dead[r] = up(d);
69        sr.pooled[r] = pooled[r];
70        sr.dead[r] = dead[r];
71        const int64_t pos = 700 + 997 * r + (r % 3) * 5;   // different lengths, and an incomplete block at the tail
72        steps[(size_t) r * k::kStepCount + k::kStepPos] = (int32_t) pos;
73        steps[(size_t) r * k::kStepCount + k::kStepNKv] = (int32_t) (pos + 1);
74        steps[(size_t) r * k::kStepCount + k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block);
75        steps[(size_t) r * k::kStepCount + k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s);
76    }
77    const float* d_q = up(q);
78    const int32_t* d_steps = up(steps);
79    float *d_rows = nullptr, *d_ref = nullptr;
80    const size_t n = (size_t) rows * max_blocks;
81    ck(cudaMalloc(&d_rows, n * 4), "malloc");
82    ck(cudaMalloc(&d_ref, n * 4), "malloc");
83    ck(cudaMemset(d_rows, 0, n * 4), "memset");
84    ck(cudaMemset(d_ref, 0, n * 4), "memset");
85    k::qsa_block_scores_rows(sr, d_q, d_steps, rows, max_blocks, s, d_rows, nullptr);
86    for (int r = 0; r < rows; ++r)
87        k::qsa_block_scores(pooled[r], dead[r], d_q + (size_t) r * s.idx_n_head * s.idx_dim, d_steps + (size_t) r * k::kStepCount, 1,
88                            max_blocks, s, d_ref + (size_t) r * max_blocks, nullptr);
89    ck(cudaDeviceSynchronize(), "sync");
90    const std::vector<float> a = down(d_rows, n), b = down(d_ref, n);
91    char name[96];
92    std::snprintf(name, sizeof name, "qsa_block_scores_rows, %d rows (own keys each)", rows);
93    report(name, std::memcmp(a.data(), b.data(), n * 4) == 0);
94    // the window selects with one top-k launch over all rows (row-independent) where the per-row path ran one per row
95    const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s);
96    int32_t *i_rows = nullptr, *i_ref = nullptr;
97    ck(cudaMalloc(&i_rows, (size_t) rows * cap * 4), "malloc");
98    ck(cudaMalloc(&i_ref, (size_t) rows * cap * 4), "malloc");
99    ck(cudaMemset(i_rows, 0, (size_t) rows * cap * 4), "memset");
100    ck(cudaMemset(i_ref, 0, (size_t) rows * cap * 4), "memset");
101    k::qsa_block_topk(d_ref, d_steps, rows, max_blocks, cap, s, i_rows, nullptr);
102    for (int r = 0; r < rows; ++r)
103        k::qsa_block_topk(d_ref + (size_t) r * max_blocks, d_steps + (size_t) r * k::kStepCount, 1, max_blocks, cap, s,
104                          i_ref + (size_t) r * cap, nullptr);
105    ck(cudaDeviceSynchronize(), "sync");
106    const std::vector<int32_t> ta = down(i_rows, (size_t) rows * cap), tb = down(i_ref, (size_t) rows * cap);
107    bool tsame = true;
108    for (int r = 0; r < rows; ++r) {
109        const int64_t w = steps[(size_t) r * k::kStepCount + k::kStepWidth];
110        tsame = tsame && std::memcmp(ta.data() + (size_t) r * cap, tb.data() + (size_t) r * cap, (size_t) w * 4) == 0;
111    }
112    std::snprintf(name, sizeof name, "qsa_block_topk over %d rows == one call per row", rows);
113    report(name, tsame);
114}
115
116// ---- 2. the decode attention ----
117void attn_case(int rows, bool int8) {
118    const k::QsaShapes s = k::qsa_real_shapes();
119    const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size;
120    const int64_t ctx_max = 5000, pages = (ctx_max + PS - 1) / PS, prow = pages * NKV * PS;
121    const int64_t cap = k::qsa_selection_width(ctx_max, s);
122    std::mt19937 rng(23 + rows + int8);
123    std::normal_distribution<float> nd(0.f, 1.f);
124    std::uniform_int_distribution<int> code(-127, 127);
125    std::uniform_real_distribution<float> sc(0.005f, 0.03f);
126    k::QsaAttnPoolsRows pr;
127    pr.n = rows;
128    std::vector<float> q((size_t) rows * NH * HD);
129    for (auto& x : q) x = nd(rng) * 2.0f;
130    std::vector<int32_t> ids((size_t) rows * cap, 0), steps((size_t) rows * k::kStepCount, 0);
131    for (int r = 0; r < rows; ++r) {
132        k::QsaAttnPools& pl = pr.p[r];
133        if (int8) {
134            std::vector<int8_t> kq((size_t) prow * HD), vq((size_t) prow * HD);
135            std::vector<uint16_t> ks((size_t) prow * (HD / 64)), vs(ks.size());
136            for (auto& x : kq) x = (int8_t) code(rng);
137            for (auto& x : vq) x = (int8_t) code(rng);
138            for (auto& x : ks) x = f2h(sc(rng));
139            for (auto& x : vs) x = f2h(sc(rng));
140            pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs);
141        } else {
142            std::vector<uint16_t> kh((size_t) prow * HD), vh(kh.size());
143            for (auto& x : kh) x = f2h(nd(rng) * 1.5f);
144            for (auto& x : vh) x = f2h(nd(rng));
145            pl.k_pool = up(kh); pl.v_pool = up(vh);
146        }
147        std::vector<int32_t> table(pages);
148        for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i;
149        std::shuffle(table.begin(), table.end(), rng);   // each row's pool has its own page order
150        pl.page_table = up(table);
151        const int64_t nkv = 900 + 641 * r + (r % 2) * 3;
152        const int64_t w = k::qsa_selection_width(nkv, s);
153        std::vector<int32_t> all((size_t) nkv);
154        for (int64_t c = 0; c < nkv; ++c) all[c] = (int32_t) c;
155        std::shuffle(all.begin(), all.end(), rng);
156        std::sort(all.begin(), all.begin() + w);
157        std::copy(all.begin(), all.begin() + w, ids.begin() + (size_t) r * cap);
158        steps[(size_t) r * k::kStepCount + k::kStepPos] = (int32_t) (nkv - 1);
159        steps[(size_t) r * k::kStepCount + k::kStepNKv] = (int32_t) nkv;
160        steps[(size_t) r * k::kStepCount + k::kStepNBid] = (int32_t) (nkv / s.idx_block);
161        steps[(size_t) r * k::kStepCount + k::kStepWidth] = (int32_t) w;
162    }
163    const float* d_q = up(q);
164    const int32_t* d_ids = up(ids);
165    const int32_t* d_steps = up(steps);
166    const int64_t scr = (int64_t) k::qsa_decode_attn_scratch_floats(cap, s);
167    float *scratch = nullptr, *d_rows = nullptr, *d_ref = nullptr;
168    ck(cudaMalloc(&scratch, (size_t) rows * scr * 4), "malloc");
169    const size_t n = (size_t) rows * NH * HD;
170    ck(cudaMalloc(&d_rows, n * 4), "malloc");
171    ck(cudaMalloc(&d_ref, n * 4), "malloc");
172    ck(cudaMemset(d_rows, 0, n * 4), "memset");
173    ck(cudaMemset(d_ref, 0, n * 4), "memset");
174    k::qsa_decode_attn_batch_rows(d_q, pr, d_ids, d_steps, cap, s, scratch, d_rows, rows, nullptr);
175    for (int r = 0; r < rows; ++r)
176        k::qsa_decode_attn_batch(d_q + (size_t) r * NH * HD, pr.p[r], d_ids + (size_t) r * cap, d_steps + (size_t) r * k::kStepCount, cap,
177                                 s, scratch + (size_t) r * scr, d_ref + (size_t) r * NH * HD, 1, nullptr);
178    ck(cudaDeviceSynchronize(), "sync");
179    const std::vector<float> a = down(d_rows, n), b = down(d_ref, n);
180    char name[96];
181    std::snprintf(name, sizeof name, "qsa_decode_attn_batch_rows, %d rows, %s pools (own pools each)", rows, int8 ? "int8" : "fp16");
182    report(name, std::memcmp(a.data(), b.data(), n * 4) == 0);
183}
184
185// ---- 3. the GDN recurrence ----
186void gdn_case(const std::vector<int>& ntok, bool commit) {
187    const int S = 128, h_k = 16, h_v = 48;   // the artifact's geometry
188    const int qk = S * h_k, C = 2 * qk + S * h_v, vd = S * h_v;
189    const float eps = 1e-6f;
190    int T = 0;
191    for (int n : ntok) T += n;
192    const int G = (int) ntok.size();
193    std::mt19937 rng(31 + T * 7 + G + commit);
194    std::normal_distribution<float> nd(0.f, 1.f);
195    std::vector<float> h((size_t) T * C), gate((size_t) T * h_v), beta((size_t) T * h_v), z((size_t) T * vd), gamma(S);
196    for (auto& v : h) v = nd(rng) * 0.1f;
197    for (auto& v : gate) v = -(0.5f + 3.0f * (float) (rng() % 100) / 100.0f);
198    for (auto& v : beta) v = (float) (rng() % 100) / 100.0f;
199    for (auto& v : z) v = nd(rng);
200    for (auto& v : gamma) v = 1.0f + 0.1f * nd(rng);
201    const size_t st_n = (size_t) S * h_v * S;
202    std::vector<std::vector<float>> st0(G);
203    std::vector<float*> st_g(G), st_r(G);
204    std::vector<int32_t*> keep(G);
205    k::GdnGroups gg;
206    gg.n = G;
207    int first = 0;
208    for (int i = 0; i < G; ++i) {
209        st0[i].resize(st_n);
210        for (auto& v : st0[i]) v = nd(rng) * 0.1f;
211        st_g[i] = up(st0[i]);
212        st_r[i] = up(st0[i]);
213        const int32_t kp = commit ? ntok[i] : 0;   // a commit group keeps all of its rows here
214        keep[i] = up(std::vector<int32_t>{kp});
215        gg.state[i] = st_g[i];
216        gg.keep[i] = commit ? keep[i] : nullptr;
217        gg.first[i] = first;
218        gg.ntok[i] = ntok[i];
219        first += ntok[i];
220    }
221    const float* d_h = up(h);
222    const float* d_gate = up(gate);
223    const float* d_beta = up(beta);
224    const float* d_z = up(z);
225    const float* d_gm = up(gamma);
226    float *d_y = nullptr, *d_yr = nullptr;
227    ck(cudaMalloc(&d_y, (size_t) T * vd * 4), "malloc");
228    ck(cudaMalloc(&d_yr, (size_t) T * vd * 4), "malloc");
229    ck(cudaMemset(d_y, 0, (size_t) T * vd * 4), "memset");
230    ck(cudaMemset(d_yr, 0, (size_t) T * vd * 4), "memset");
231    k::gdn_step_norm_groups(gg, d_h, C, d_gate, d_beta, d_z, d_gm, eps, d_y, h_k, h_v, commit, nullptr);
232    for (int i = 0; i < G; ++i) {
233        const int f = gg.first[i];
234        // the engine's per-slot call: a window group runs its rows with all outputs; a commit group (1 row) keeps them
235        k::gdn_step_norm_multi(st_r[i], d_h + (size_t) f * C, C, d_gate + (size_t) f * h_v, d_beta + (size_t) f * h_v,
236                               d_z + (size_t) f * vd, d_gm, eps, d_yr + (size_t) f * vd, h_k, h_v, ntok[i],
237                               commit ? keep[i] : nullptr, nullptr, 0);
238    }
239    ck(cudaDeviceSynchronize(), "sync");
240    bool same = true;
241    for (int i = 0; i < G; ++i) {
242        const std::vector<float> a = down(st_g[i], st_n), b = down(st_r[i], st_n);
243        same = same && std::memcmp(a.data(), b.data(), st_n * 4) == 0;
244        if (!commit) same = same && std::memcmp(a.data(), st0[i].data(), st_n * 4) == 0;   // a window leaves the state alone
245    }
246    if (!commit) {
247        const std::vector<float> a = down(d_y, (size_t) T * vd), b = down(d_yr, (size_t) T * vd);
248        same = same && std::memcmp(a.data(), b.data(), a.size() * 4) == 0;
249    }
250    char name[96], rows[64] = "";
251    for (int i = 0; i < G && i < 8; ++i) std::snprintf(rows + std::strlen(rows), sizeof rows - std::strlen(rows), "%s%d", i ? "," : "", ntok[i]);
252    std::snprintf(name, sizeof name, "gdn_step_norm_groups %s, groups of %s rows", commit ? "commit" : "window", rows);
253    report(name, same);
254}
255}  // namespace
256
257int main() {
258    std::printf("batch rows parity (#2234 kernels against the per-row launches)\n");
259    for (int r : {1, 2, 4, 8}) scores_case(r);
260    for (int r : {1, 3, 8}) {
261        attn_case(r, true);
262        attn_case(r, false);
263    }
264    gdn_case({1}, false);
265    gdn_case({1, 1, 1, 1}, false);
266    gdn_case({2, 2, 2, 2}, false);
267    gdn_case({1, 3, 2, 1, 1}, false);
268    gdn_case({1, 1, 1, 1, 1, 1, 1, 1}, false);
269    gdn_case({1}, true);
270    gdn_case({1, 1, 1, 1}, true);
271    gdn_case({1, 1, 1, 1, 1, 1, 1, 1}, true);
272    std::printf("%s\n", bad ? "batch_rows_parity: FAILED" : "batch_rows_parity: ok");
273    return bad ? 1 : 0;
274}