okami.mom/strata

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

Niko1221Merge branch 'f-hf-nv' into f-140241016e322

main
8.9 KiB191 linesraw
1// src/kernels/native_multi_parity.cpp - the multi-token router and the k = 10 combine, bitwise against their
2// single-token contracts (#783 PR-c: route_multi, combine_k10_vec4).
3//
4//   * native_router_top10_multi (one warp per token, 8 tokens per CTA) against native_router_top10 token by token,
5//     for n = 1..19 (a partial last CTA, and more than one CTA), on plain logits, on logits with exact ties and on
6//     logits with NaN (the router maps NaN to -FLT_MAX): ids and weights are compared with memcmp;
7//   * native_moe_combine / native_moe_combine_multi (k = 10 with a shared row takes the float4 kernel; a misaligned
8//     output, k = 9 and a null shared row take the scalar one) against a host replay of the documented contract:
9//     the first product rounds to F32, the next ones accumulate with FMA in expert order, the shared row is added
10//     once: memcmp.
11#include "strata/kernels/native_moe.hpp"
12#include "strata/kernels/native_router.hpp"
13#include "strata/kernels/router_top10.hpp"
14
15#include <cuda_runtime.h>
16
17#include <algorithm>
18#include <cmath>
19#include <cstdint>
20#include <cstdio>
21#include <cstdlib>
22#include <cstring>
23#include <random>
24#include <string>
25#include <vector>
26
27namespace {
28
29void check(cudaError_t e, const char* what) {
30    if (e != cudaSuccess) {
31        std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
32        std::exit(1);
33    }
34}
35
36template <typename T>
37T* up(const std::vector<T>& h) {
38    void* p = nullptr;
39    check(cudaMalloc(&p, h.size() * sizeof(T) + 64), "malloc");
40    check(cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "h2d");
41    return (T*) p;
42}
43template <typename T>
44std::vector<T> down(const T* d, size_t n) {
45    std::vector<T> h(n);
46    check(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "d2h");
47    return h;
48}
49
50}  // namespace
51
52int main(int argc, char**) {
53    (void) argc;
54    using namespace strata::kernels;
55    std::mt19937 rng(783);
56    std::normal_distribution<float> gauss(0.0f, 1.0f);
57    int bad = 0;
58    cudaStream_t st = nullptr;
59    check(cudaStreamCreate(&st), "stream");
60
61    // ---- the multi-token router
62    for (int mode = 0; mode < 3; ++mode) {
63        const char* names[] = {"random logits", "exact ties", "NaN logits"};
64        int mode_bad = 0, cases = 0;
65        for (int n = 1; n <= 19; ++n) {
66            std::vector<float> lg((size_t) n * 512);
67            for (auto& v : lg) v = gauss(rng) * 2.0f;
68            if (mode == 1)
69                for (size_t i = 0; i < lg.size(); ++i) lg[i] = (float) (int) (lg[i] * 2.0f) * 0.5f;   // coarse: many exact ties
70            if (mode == 2)
71                for (int t = 0; t < n; ++t) lg[(size_t) t * 512 + (size_t) (rng() % 512)] = std::nanf("");
72            float* d_l = up(lg);
73            int32_t *d_i, *d_ir;
74            float *d_w, *d_wr;
75            check(cudaMalloc(&d_i, (size_t) n * 10 * 4), "i");
76            check(cudaMalloc(&d_ir, (size_t) n * 10 * 4), "ir");
77            check(cudaMalloc(&d_w, (size_t) n * 10 * 4), "w");
78            check(cudaMalloc(&d_wr, (size_t) n * 10 * 4), "wr");
79            native_router_top10_multi(d_l, d_i, d_w, n, st);
80            for (int t = 0; t < n; ++t) native_router_top10(d_l + (size_t) t * 512, d_ir + t * 10, d_wr + t * 10, st);
81            check(cudaDeviceSynchronize(), "sync");
82            const auto i1 = down(d_i, (size_t) n * 10), i2 = down(d_ir, (size_t) n * 10);
83            const auto w1 = down(d_w, (size_t) n * 10), w2 = down(d_wr, (size_t) n * 10);
84            ++cases;
85            if (std::memcmp(i1.data(), i2.data(), i1.size() * 4) != 0 || std::memcmp(w1.data(), w2.data(), w1.size() * 4) != 0) {
86                std::printf("    *** native_router_top10_multi n=%d (%s) differs from native_router_top10 ***\n", n, names[mode]);
87                ++mode_bad;
88            }
89            cudaFree(d_l); cudaFree(d_i); cudaFree(d_ir); cudaFree(d_w); cudaFree(d_wr);
90        }
91        std::printf("  %-52s %s (%d cases)\n", (std::string("router multi == single, ") + names[mode]).c_str(),
92                    mode_bad ? "*** NO ***" : "bitwise", cases);
93        bad += mode_bad;
94    }
95
96    // ---- #1357: a model that does not have 512 experts takes the generic router (the native one reads 512 floats a
97    // row, so mtp.cpp's per-token call is guarded by n_expert == 512 like its siblings): router_top10 on 256-wide
98    // rows picks the host reference's ids in order, with its renormalised softmax weights
99    {
100        const int n = 3, NE = 256, K = 10;
101        std::vector<float> lg((size_t) n * NE);
102        for (auto& v : lg) v = gauss(rng) * 2.0f;
103        float* d_l = up(lg);
104        int32_t* d_i = nullptr;
105        float* d_w = nullptr;
106        check(cudaMalloc(&d_i, (size_t) n * K * 4), "i");
107        check(cudaMalloc(&d_w, (size_t) n * K * 4), "w");
108        router_top10(d_l, n, NE, K, d_i, d_w, st);
109        check(cudaDeviceSynchronize(), "sync");
110        const auto gi = down(d_i, (size_t) n * K);
111        const auto gw = down(d_w, (size_t) n * K);
112        int rbad = 0;
113        for (int t = 0; t < n; ++t) {
114            std::vector<int> ord(NE);
115            for (int i = 0; i < NE; ++i) ord[i] = i;
116            const float* row = lg.data() + (size_t) t * NE;
117            std::sort(ord.begin(), ord.end(), [&](int a, int b) { return row[a] != row[b] ? row[a] > row[b] : a < b; });
118            double sum = 0;
119            for (int j = 0; j < K; ++j) sum += std::exp((double) row[ord[j]] - row[ord[0]]);
120            for (int j = 0; j < K; ++j) {
121                const double want = std::exp((double) row[ord[j]] - row[ord[0]]) / sum;
122                if (gi[(size_t) t * K + j] != ord[j] || std::fabs(gw[(size_t) t * K + j] - want) > 1e-5) ++rbad;
123            }
124        }
125        std::printf("  %-52s %s\n", "router_top10 on 256 experts (non-512 fallback)", rbad ? "*** NO ***" : "matches the host reference");
126        bad += rbad;
127        cudaFree(d_l); cudaFree(d_i); cudaFree(d_w);
128    }
129
130    // ---- the combine
131    struct Cfg { const char* name; int k; bool shared; int out_off; };
132    const Cfg cfgs[] = {{"k=10 + shared (float4 kernel)", 10, true, 0}, {"k=10 + shared, output misaligned", 10, true, 1},
133                        {"k=10 without shared", 10, false, 0}, {"k=9 + shared", 9, true, 0}};
134    const int N = 2048;
135    for (const Cfg& c : cfgs) {
136        int cfg_bad = 0, cases = 0;
137        for (int n = 1; n <= 8; ++n) {
138            std::vector<float> parts((size_t) n * c.k * N), w((size_t) n * c.k), sh((size_t) n * N);
139            for (auto& v : parts) v = gauss(rng);
140            for (auto& v : w) v = (float) (rng() % 1000) / 1000.0f;
141            for (auto& v : sh) v = gauss(rng);
142            float* d_p = up(parts);
143            float* d_w = up(w);
144            float* d_s = up(sh);
145            float* d_o = nullptr;
146            check(cudaMalloc(&d_o, (size_t) n * N * 4 + 64), "o");
147            float* out = d_o + c.out_off;
148            if (c.out_off) {
149                // a misaligned output cannot take a multi launch of rows with the 4-float stride contract either way:
150                // the rows are still n*N floats from `out`
151            }
152            native_moe_combine_multi(d_p, d_w, c.shared ? d_s : nullptr, out, N, c.k, n, st);
153            check(cudaDeviceSynchronize(), "sync");
154            const auto got = down(out, (size_t) n * N);
155            std::vector<float> want((size_t) n * N);
156            for (int t = 0; t < n; ++t)
157                for (int col = 0; col < N; ++col) {
158                    float s = parts[((size_t) t * c.k) * N + col] * w[(size_t) t * c.k];
159                    for (int e = 1; e < c.k; ++e)
160                        s = std::fmaf(parts[((size_t) t * c.k + e) * N + col], w[(size_t) t * c.k + e], s);
161                    if (c.shared) s += sh[(size_t) t * N + col];
162                    want[(size_t) t * N + col] = s;
163                }
164            ++cases;
165            if (std::memcmp(got.data(), want.data(), got.size() * 4) != 0) {
166                std::printf("    *** native_moe_combine_multi n=%d (%s) differs from the contract's host replay ***\n", n, c.name);
167                ++cfg_bad;
168            }
169            // the single-token call is the same arithmetic
170            if (n == 1) {
171                check(cudaMemset(d_o, 0, (size_t) N * 4 + 64), "z");
172                native_moe_combine(d_p, d_w, c.shared ? d_s : nullptr, out, N, c.k, st);
173                check(cudaDeviceSynchronize(), "sync");
174                const auto g1 = down(out, (size_t) N);
175                ++cases;
176                if (std::memcmp(g1.data(), want.data(), g1.size() * 4) != 0) {
177                    std::printf("    *** native_moe_combine (%s) differs from the contract's host replay ***\n", c.name);
178                    ++cfg_bad;
179                }
180            }
181            cudaFree(d_p); cudaFree(d_w); cudaFree(d_s); cudaFree(d_o);
182        }
183        std::printf("  %-52s %s (%d cases)\n", (std::string("combine ") + c.name).c_str(), cfg_bad ? "*** NO ***" : "bitwise", cases);
184        bad += cfg_bad;
185    }
186
187    std::printf("\nnative_multi: %d failures\n", bad);
188    if (bad) return 1;
189    std::printf("native_multi_parity OK\n");
190    return 0;
191}