okami.mom/strata

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

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
7.3 KiB165 linesraw
1// src/prefill/lm_kernels_parity.cu - the two kernels of the layer-major prompt path (STRATA_PREFILL_LAYER_MAJOR=1,
2// #3976 / #1670) against a host reference, on synthetic data of the model's width (N = 2560): no model, a few MiB.
3//   moe_shared_init   acc[t, :] = shared[t, :] * sigmoid(sg[t])      (the device sigmoid is __expf: within 1e-5 relative)
4//   moe_scatter_add   acc[u_tok[u], :] += sum_{j in [u_off[u], u_off[u+1])} u_w[j] * Dm[u_rows[j], :], in that j order,
5//                     one block per token and no atomics: the same bits as the host's fmaf chain, and the same bits on a
6//                     second launch (deterministic)
7// Exit 0 pass, 1 fail, 77 no CUDA device (ctest SKIP_RETURN_CODE).
8#include "strata/prefill/kernels.hpp"
9
10#include <cuda_runtime.h>
11
12#include <cmath>
13#include <cstdint>
14#include <cstdio>
15#include <cstring>
16#include <random>
17#include <vector>
18
19namespace {
20
21constexpr int N = 2560;
22
23bool ck(cudaError_t e, const char* what) {
24    if (e != cudaSuccess) std::printf("FAIL: %s: %s\n", what, cudaGetErrorString(e));
25    return e == cudaSuccess;
26}
27template <typename T> T* dalloc(size_t n) {
28    T* p = nullptr;
29    if (!ck(cudaMalloc(&p, n * sizeof(T)), "cudaMalloc")) std::exit(1);
30    return p;
31}
32template <typename T> void up(T* d, const std::vector<T>& h) {
33    if (!h.empty() && !ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload")) std::exit(1);
34}
35
36int fails = 0;
37
38void check_shared_init(int64_t T, std::mt19937& g) {
39    std::normal_distribution<float> nd(0.0f, 1.0f);
40    std::vector<float> shared((size_t) T * N), sg((size_t) T), ref((size_t) T * N), got((size_t) T * N);
41    for (auto& x : shared) x = nd(g);
42    for (auto& x : sg) x = nd(g) * 3.0f;
43    for (int64_t t = 0; t < T; ++t)
44        for (int d = 0; d < N; ++d)
45            ref[(size_t) t * N + d] = shared[(size_t) t * N + d] * (1.0f / (1.0f + std::exp(-sg[(size_t) t])));
46    float *d_sh = dalloc<float>(shared.size()), *d_sg = dalloc<float>(sg.size()), *d_acc = dalloc<float>(shared.size());
47    up(d_sh, shared);
48    up(d_sg, sg);
49    cudaMemset(d_acc, 0xff, shared.size() * 4);
50    strata::prefill::moe_shared_init(d_sh, d_sg, d_acc, T, nullptr);
51    ck(cudaDeviceSynchronize(), "sync");
52    ck(cudaMemcpy(got.data(), d_acc, got.size() * 4, cudaMemcpyDeviceToHost), "download");
53    double worst = 0;
54    for (size_t i = 0; i < got.size(); ++i) {
55        const double scale = std::fabs(ref[i]) + 1e-6;
56        worst = std::fmax(worst, std::fabs((double) got[i] - ref[i]) / scale);
57    }
58    const bool ok = worst < 1e-5;
59    std::printf("moe_shared_init T=%lld: worst relative error %.2e %s\n", (long long) T, worst, ok ? "ok" : "FAIL");
60    fails += ok ? 0 : 1;
61    cudaFree(d_sh);
62    cudaFree(d_sg);
63    cudaFree(d_acc);
64}
65
66// rows: how many expert rows the group has; tokens: how many super-chunk tokens exist; each row belongs to a token, a token
67// may own several rows of the group (an entry's rows are in token order, a token has up to 8 routed experts)
68void check_scatter(int64_t tokens, int64_t rows, int max_per_tok, uint32_t seed) {
69    std::mt19937 g(seed);
70    std::normal_distribution<float> nd(0.0f, 1.0f);
71    std::uniform_int_distribution<int> pick(0, (int) tokens - 1);
72    // assign rows to tokens, at most max_per_tok per token
73    std::vector<int> per((size_t) tokens, 0);
74    std::vector<int32_t> row_tok;
75    while ((int64_t) row_tok.size() < rows) {
76        const int t = pick(g);
77        if (per[(size_t) t] >= max_per_tok) continue;
78        ++per[(size_t) t];
79        row_tok.push_back(t);
80    }
81    // the CSR the engine builds: unique tokens in order of first appearance, each token's rows in row order
82    std::vector<int32_t> u_tok, u_off, u_rows(rows);
83    std::vector<int> slot((size_t) tokens, -1);
84    for (int32_t r = 0; r < (int32_t) rows; ++r) {
85        const int t = row_tok[(size_t) r];
86        if (slot[(size_t) t] < 0) { slot[(size_t) t] = (int) u_tok.size(); u_tok.push_back(t); u_off.push_back(0); }
87        ++u_off[(size_t) slot[(size_t) t]];
88    }
89    const int64_t nu = (int64_t) u_tok.size();
90    std::vector<int32_t> fillp((size_t) nu);
91    int32_t acc_n = 0;
92    for (int64_t i = 0; i < nu; ++i) { const int32_t c = u_off[(size_t) i]; u_off[(size_t) i] = acc_n; fillp[(size_t) i] = acc_n; acc_n += c; }
93    u_off.push_back((int32_t) rows);
94    std::vector<float> u_w(rows);
95    std::vector<float> w_row((size_t) rows);
96    for (auto& x : w_row) x = std::fabs(nd(g)) * 0.2f;
97    for (int32_t r = 0; r < (int32_t) rows; ++r) {
98        const int32_t p = fillp[(size_t) slot[(size_t) row_tok[(size_t) r]]]++;
99        u_rows[(size_t) p] = r;
100        u_w[(size_t) p] = w_row[(size_t) r];
101    }
102    std::vector<float> Dm((size_t) rows * N), acc0((size_t) tokens * N);
103    for (auto& x : Dm) x = nd(g);
104    for (auto& x : acc0) x = nd(g);
105    // host reference, the kernel's order: s = fma chain over the token's rows, then acc += s
106    std::vector<float> ref = acc0;
107    for (int64_t u = 0; u < nu; ++u)
108        for (int d = 0; d < N; ++d) {
109            float s = 0.0f;
110            for (int32_t j = u_off[(size_t) u]; j < u_off[(size_t) u + 1]; ++j)
111                s = std::fma(u_w[(size_t) j], Dm[(size_t) u_rows[(size_t) j] * N + d], s);
112            ref[(size_t) u_tok[(size_t) u] * N + d] += s;
113        }
114    float *d_Dm = dalloc<float>(Dm.size()), *d_acc = dalloc<float>(acc0.size()), *d_w = dalloc<float>(u_w.size());
115    int32_t *d_ut = dalloc<int32_t>(u_tok.size()), *d_uo = dalloc<int32_t>(u_off.size()), *d_ur = dalloc<int32_t>(u_rows.size());
116    up(d_Dm, Dm);
117    up(d_w, u_w);
118    up(d_ut, u_tok);
119    up(d_uo, u_off);
120    up(d_ur, u_rows);
121    std::vector<float> got1(acc0.size()), got2(acc0.size());
122    for (int run = 0; run < 2; ++run) {
123        up(d_acc, acc0);
124        strata::prefill::moe_scatter_add(d_Dm, d_ut, d_uo, d_ur, d_w, nu, d_acc, nullptr);
125        ck(cudaDeviceSynchronize(), "sync");
126        ck(cudaMemcpy((run ? got2 : got1).data(), d_acc, acc0.size() * 4, cudaMemcpyDeviceToHost), "download");
127    }
128    size_t diff = 0, diff_runs = 0;
129    for (size_t i = 0; i < ref.size(); ++i) {
130        diff += std::memcmp(&ref[i], &got1[i], 4) != 0;
131        diff_runs += std::memcmp(&got1[i], &got2[i], 4) != 0;
132    }
133    const bool ok = diff == 0 && diff_runs == 0;
134    std::printf("moe_scatter_add tokens=%lld rows=%lld (<= %d per token, %lld tokens in the group): %zu values differ from the host "
135                "chain, %zu differ between two launches %s\n", (long long) tokens, (long long) rows, max_per_tok, (long long) nu,
136                diff, diff_runs, ok ? "ok" : "FAIL");
137    fails += ok ? 0 : 1;
138    cudaFree(d_Dm);
139    cudaFree(d_acc);
140    cudaFree(d_w);
141    cudaFree(d_ut);
142    cudaFree(d_uo);
143    cudaFree(d_ur);
144}
145
146}  // namespace
147
148int main() {
149    int n = 0;
150    if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) {
151        std::printf("SKIP: no CUDA device\n");
152        return 77;
153    }
154    std::mt19937 g(7);
155    check_shared_init(1, g);
156    check_shared_init(512, g);
157    check_shared_init(2049, g);
158    check_scatter(512, 1, 8, 1);        // one row
159    check_scatter(512, 700, 8, 2);      // a group inside one sub-chunk
160    check_scatter(4096, 5000, 8, 3);    // several sub-chunks of a super-chunk
161    check_scatter(8192, 8192, 1, 4);    // every token once
162    check_scatter(300, 2400, 8, 5);     // every token at its limit
163    std::printf(fails == 0 ? "PASS\n" : "FAIL (%d)\n", fails);
164    return fails == 0 ? 0 : 1;
165}