okami.mom/strata

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

Niko1221Merge branch 'f-1402-y' into f-14025af104b51

main
9.2 KiB198 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#define DPCT_PROFILING_ENABLED
12#include <sycl/sycl.hpp>
13#include <dpct/dpct.hpp>
14#include "strata/kernels/native_moe.hpp"
15#include "strata/kernels/native_router.hpp"
16
17#include <cmath>
18#include <cstdint>
19#include <cstdio>
20#include <cstdlib>
21#include <cstring>
22#include <random>
23#include <string>
24#include <vector>
25
26namespace {
27
28void check(dpct::err0 e, const char *what) {
29}
30
31template <typename T>
32T* up(const std::vector<T>& h) {
33    void* p = nullptr;
34    check(DPCT_CHECK_ERROR(
35              p = (void *)sycl::malloc_device(h.size() * sizeof(T) + 64,
36                                              dpct::get_in_order_queue())),
37          "malloc");
38    /*
39    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
40    in the original code the source host memory is pageable memory. If the
41    memory is not pageable, call wait() on event return by memcpy API to ensure
42    synchronization behavior.
43    */
44    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
45              p, h.data(), h.size() * sizeof(T)).wait()),
46          "h2d");
47    return (T*) p;
48}
49template <typename T>
50std::vector<T> down(const T* d, size_t n) {
51    std::vector<T> h(n);
52    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
53                               .memcpy(h.data(), d, n * sizeof(T))
54                               .wait()),
55          "d2h");
56    return h;
57}
58
59}  // namespace
60
61int main(int argc, char**) {
62    (void) argc;
63    using namespace strata::kernels;
64    std::mt19937 rng(783);
65    std::normal_distribution<float> gauss(0.0f, 1.0f);
66    int bad = 0;
67    dpct::queue_ptr st = &dpct::get_in_order_queue();
68    check(DPCT_CHECK_ERROR(st = dpct::get_current_device().create_queue(true)),
69          "stream");
70
71    // ---- the multi-token router
72    for (int mode = 0; mode < 3; ++mode) {
73        const char* names[] = {"random logits", "exact ties", "NaN logits"};
74        int mode_bad = 0, cases = 0;
75        for (int n = 1; n <= 19; ++n) {
76            std::vector<float> lg((size_t) n * 512);
77            for (auto& v : lg) v = gauss(rng) * 2.0f;
78            if (mode == 1)
79                for (size_t i = 0; i < lg.size(); ++i) lg[i] = (float) (int) (lg[i] * 2.0f) * 0.5f;   // coarse: many exact ties
80            if (mode == 2)
81                for (int t = 0; t < n; ++t) lg[(size_t) t * 512 + (size_t) (rng() % 512)] = std::nanf("");
82            float* d_l = up(lg);
83            int32_t *d_i, *d_ir;
84            float *d_w, *d_wr;
85            check(DPCT_CHECK_ERROR(
86                      d_i = (int32_t *)sycl::malloc_device(
87                          (size_t)n * 10 * 4, dpct::get_in_order_queue())),
88                  "i");
89            check(DPCT_CHECK_ERROR(
90                      d_ir = (int32_t *)sycl::malloc_device(
91                          (size_t)n * 10 * 4, dpct::get_in_order_queue())),
92                  "ir");
93            check(DPCT_CHECK_ERROR(
94                      d_w = (float *)sycl::malloc_device(
95                          (size_t)n * 10 * 4, dpct::get_in_order_queue())),
96                  "w");
97            check(DPCT_CHECK_ERROR(
98                      d_wr = (float *)sycl::malloc_device(
99                          (size_t)n * 10 * 4, dpct::get_in_order_queue())),
100                  "wr");
101            native_router_top10_multi(d_l, d_i, d_w, n, st);
102            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);
103            check(DPCT_CHECK_ERROR(
104                      dpct::get_current_device().queues_wait_and_throw()),
105                  "sync");
106            const auto i1 = down(d_i, (size_t) n * 10), i2 = down(d_ir, (size_t) n * 10);
107            const auto w1 = down(d_w, (size_t) n * 10), w2 = down(d_wr, (size_t) n * 10);
108            ++cases;
109            if (std::memcmp(i1.data(), i2.data(), i1.size() * 4) != 0 || std::memcmp(w1.data(), w2.data(), w1.size() * 4) != 0) {
110                std::printf("    *** native_router_top10_multi n=%d (%s) differs from native_router_top10 ***\n", n, names[mode]);
111                ++mode_bad;
112            }
113            sycl::free(d_l, dpct::get_in_order_queue());
114                sycl::free(d_i, dpct::get_in_order_queue());
115                sycl::free(d_ir, dpct::get_in_order_queue());
116                sycl::free(d_w, dpct::get_in_order_queue());
117                sycl::free(d_wr, dpct::get_in_order_queue());
118        }
119        std::printf("  %-52s %s (%d cases)\n", (std::string("router multi == single, ") + names[mode]).c_str(),
120                    mode_bad ? "*** NO ***" : "bitwise", cases);
121        bad += mode_bad;
122    }
123
124    // ---- the combine
125    struct Cfg { const char* name; int k; bool shared; int out_off; };
126    const Cfg cfgs[] = {{"k=10 + shared (float4 kernel)", 10, true, 0}, {"k=10 + shared, output misaligned", 10, true, 1},
127                        {"k=10 without shared", 10, false, 0}, {"k=9 + shared", 9, true, 0}};
128    const int N = 2048;
129    for (const Cfg& c : cfgs) {
130        int cfg_bad = 0, cases = 0;
131        for (int n = 1; n <= 8; ++n) {
132            std::vector<float> parts((size_t) n * c.k * N), w((size_t) n * c.k), sh((size_t) n * N);
133            for (auto& v : parts) v = gauss(rng);
134            for (auto& v : w) v = (float) (rng() % 1000) / 1000.0f;
135            for (auto& v : sh) v = gauss(rng);
136            float* d_p = up(parts);
137            float* d_w = up(w);
138            float* d_s = up(sh);
139            float* d_o = nullptr;
140            check(DPCT_CHECK_ERROR(
141                      d_o = (float *)sycl::malloc_device(
142                          (size_t)n * N * 4 + 64, dpct::get_in_order_queue())),
143                  "o");
144            float* out = d_o + c.out_off;
145            if (c.out_off) {
146                // a misaligned output cannot take a multi launch of rows with the 4-float stride contract either way:
147                // the rows are still n*N floats from `out`
148            }
149            native_moe_combine_multi(d_p, d_w, c.shared ? d_s : nullptr, out, N, c.k, n, st);
150            check(DPCT_CHECK_ERROR(
151                      dpct::get_current_device().queues_wait_and_throw()),
152                  "sync");
153            const auto got = down(out, (size_t) n * N);
154            std::vector<float> want((size_t) n * N);
155            for (int t = 0; t < n; ++t)
156                for (int col = 0; col < N; ++col) {
157                    float s = parts[((size_t) t * c.k) * N + col] * w[(size_t) t * c.k];
158                    for (int e = 1; e < c.k; ++e)
159                        s = std::fmaf(parts[((size_t) t * c.k + e) * N + col], w[(size_t) t * c.k + e], s);
160                    if (c.shared) s += sh[(size_t) t * N + col];
161                    want[(size_t) t * N + col] = s;
162                }
163            ++cases;
164            if (std::memcmp(got.data(), want.data(), got.size() * 4) != 0) {
165                std::printf("    *** native_moe_combine_multi n=%d (%s) differs from the contract's host replay ***\n", n, c.name);
166                ++cfg_bad;
167            }
168            // the single-token call is the same arithmetic
169            if (n == 1) {
170                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
171                                           .memset(d_o, 0, (size_t)N * 4 + 64)
172                                           .wait()),
173                      "z");
174                native_moe_combine(d_p, d_w, c.shared ? d_s : nullptr, out, N, c.k, st);
175                check(DPCT_CHECK_ERROR(
176                          dpct::get_current_device().queues_wait_and_throw()),
177                      "sync");
178                const auto g1 = down(out, (size_t) N);
179                ++cases;
180                if (std::memcmp(g1.data(), want.data(), g1.size() * 4) != 0) {
181                    std::printf("    *** native_moe_combine (%s) differs from the contract's host replay ***\n", c.name);
182                    ++cfg_bad;
183                }
184            }
185            sycl::free(d_p, dpct::get_in_order_queue());
186                sycl::free(d_w, dpct::get_in_order_queue());
187                sycl::free(d_s, dpct::get_in_order_queue());
188                sycl::free(d_o, dpct::get_in_order_queue());
189        }
190        std::printf("  %-52s %s (%d cases)\n", (std::string("combine ") + c.name).c_str(), cfg_bad ? "*** NO ***" : "bitwise", cases);
191        bad += cfg_bad;
192    }
193
194    std::printf("\nnative_multi: %d failures\n", bad);
195    if (bad) return 1;
196    std::printf("native_multi_parity OK\n");
197    return 0;
198}