okami.mom/strata

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

Niko1221Merge main (87dfca0e7) into f-own-int: the 0.2.14 app branch, fixtures and CI fixes, the Qwen4-readiness tools, the shape-engine build scriptsffb3d9b31

main
12.3 KiB252 linesraw
1// src/kernels/router_top10_parity.cpp - P2.S2's parity test for the MoE router.
2//
3// The reference here is a HOST implementation of `ref/moe.py::router` written from the same specification the
4// kernel was written from - so this checks the kernel against the spec independently of the kernel, which is
5// the strongest thing available without running llama.cpp.  It is NOT a check against llama.cpp itself, and
6// that gap is stated rather than implied.
7//
8// WHAT THE TEST CAN AND CANNOT SEE.  It compares expert IDs exactly and weights to a tolerance, on several
9// logit distributions including ties (where the "smallest index wins" rule is the only thing that decides) and
10// near-ties (where a float difference decides).  It also asserts that the 2**-14 CLAMP CANNOT TRIGGER for this
11// model's geometry - see below - so the absence of a clamp test is a proven fact rather than an omission.
12#define DPCT_PROFILING_ENABLED
13#include <sycl/sycl.hpp>
14#include <dpct/dpct.hpp>
15#include "strata/kernels/router_top10.hpp"
16
17#include <algorithm>
18#include <cmath>
19#include <cstdio>
20#include <cstdlib>
21#include <numeric>
22#include <random>
23#include <vector>
24
25namespace {
26
27void check(dpct::err0 e, const char *what) {
28}
29
30constexpr double RENORM_CLAMP = 6.103515625e-05;      // 2**-14
31
32// The host reference: softmax over all experts, stable descending argsort, gather, clamp, renormalise.
33void reference(const float* logits, int n_expert, int k, int* ids, float* w) {
34    double mx = logits[0];
35    for (int e = 1; e < n_expert; ++e) mx = std::max(mx, (double) logits[e]);
36    double sum = 0;
37    std::vector<double> p((size_t) n_expert);
38    for (int e = 0; e < n_expert; ++e) {
39        p[(size_t) e] = std::exp((double) logits[e] - mx);
40        sum += p[(size_t) e];
41    }
42    for (int e = 0; e < n_expert; ++e) p[(size_t) e] /= sum;
43
44    // stable descending: std::stable_sort with a strict greater-than keeps equal elements in index order
45    std::vector<int> idx((size_t) n_expert);
46    std::iota(idx.begin(), idx.end(), 0);
47    std::stable_sort(idx.begin(), idx.end(),
48                     [&](int a, int b) { return p[(size_t) a] > p[(size_t) b]; });
49    double s = 0;
50    for (int i = 0; i < k; ++i) {
51        ids[i] = idx[(size_t) i];
52        w[i] = (float) p[(size_t) idx[(size_t) i]];
53        s += p[(size_t) idx[(size_t) i]];
54    }
55    s = std::max(s, RENORM_CLAMP);
56    for (int i = 0; i < k; ++i) w[i] = (float) ((double) w[i] / s);
57}
58
59int run_case(const char* name, const std::vector<float>& logits, int n_tokens, int n_expert, int k,
60             double tol) {
61    std::vector<int> h_ids((size_t) n_tokens * k);
62    std::vector<float> h_w((size_t) n_tokens * k);
63    std::vector<int> r_ids((size_t) n_tokens * k);
64    std::vector<float> r_w((size_t) n_tokens * k);
65    for (int t = 0; t < n_tokens; ++t) {
66        reference(&logits[(size_t) t * n_expert], n_expert, k, &r_ids[(size_t) t * k], &r_w[(size_t) t * k]);
67    }
68
69    float* d_l = nullptr;
70    int* d_ids = nullptr;
71    float* d_w = nullptr;
72    check(DPCT_CHECK_ERROR(d_l = sycl::malloc_device<float>(
73                               logits.size(), dpct::get_in_order_queue())),
74          "malloc logits");
75    check(DPCT_CHECK_ERROR(d_ids = sycl::malloc_device<int>(
76                               h_ids.size(), dpct::get_in_order_queue())),
77          "malloc ids");
78    check(DPCT_CHECK_ERROR(d_w = sycl::malloc_device<float>(
79                               h_w.size(), dpct::get_in_order_queue())),
80          "malloc w");
81    /*
82    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
83    in the original code the source host memory is pageable memory. If the
84    memory is not pageable, call wait() on event return by memcpy API to ensure
85    synchronization behavior.
86    */
87    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
88              d_l, logits.data(), logits.size() * sizeof(float)).wait()),
89          "copy");
90    strata::kernels::router_top10(d_l, n_tokens, n_expert, k, d_ids, d_w, nullptr);
91    check(DPCT_CHECK_ERROR(
92              (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
93                  .memcpy(h_ids.data(), d_ids, h_ids.size() * sizeof(int))
94                  .wait()),
95          "back ids");
96    check(DPCT_CHECK_ERROR(
97              (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
98                  .memcpy(h_w.data(), d_w, h_w.size() * sizeof(float))
99                  .wait()),
100          "back w");
101
102    long long id_bad = 0, w_bad = 0;
103    double worst = 0;
104    for (size_t i = 0; i < h_ids.size(); ++i) {
105        if (h_ids[i] != r_ids[i]) ++id_bad;
106        const double rel = std::fabs((double) h_w[i] - (double) r_w[i]) /
107                           (std::fabs((double) r_w[i]) > 1e-30 ? std::fabs((double) r_w[i]) : 1e-30);
108        worst = std::max(worst, rel);
109        if (!(rel <= tol)) ++w_bad;
110    }
111    // every token's weights must sum to 1 unless the clamp replaced the sum
112    double worst_sum = 0;
113    for (int t = 0; t < n_tokens; ++t) {
114        double s = 0;
115        for (int i = 0; i < k; ++i) s += (double) h_w[(size_t) t * k + i];
116        double raw = 0;
117        for (int i = 0; i < k; ++i) raw += (double) r_w[(size_t) t * k + i];
118        // both sides divide by the same clamped scale, so the ratios agree; check the kernel's own sum
119        worst_sum = std::max(worst_sum, std::fabs(s - 1.0));
120    }
121    std::printf("  %-26s ids %s (%lld bad)   weights worst rel %.3e (%lld over tol)   |sum-1| %.1e\n", name,
122                id_bad ? "*** WRONG ***" : "exact", id_bad, worst, w_bad, worst_sum);
123    sycl::free(d_l, dpct::get_in_order_queue());
124    sycl::free(d_ids, dpct::get_in_order_queue());
125    sycl::free(d_w, dpct::get_in_order_queue());
126    return (int) (id_bad + w_bad);
127}
128
129// The fp32 router (variant 3, the one a card without fp64 runs) against the double kernel (variant 0) on the SAME inputs: ids that differ
130// and the largest relative weight difference. Needs a device that runs double (a card with fp64, or an Arc under IGC_EnableDPEmulation=1
131// OverrideDefaultFP64Settings=1); without one it says so and is skipped (the reference check above then covers the fp32 path).
132int f32_vs_double(const char* name, const std::vector<float>& logits, int n_tokens, int n_expert, int k) {
133    auto& q = dpct::get_in_order_queue();
134    if (!q.get_device().has(sycl::aspect::fp64)) {
135        std::printf("  %-26s fp32 vs double: skipped (this device runs no double)\n", name);
136        return 0;
137    }
138    float* d_l = sycl::malloc_device<float>(logits.size(), q);
139    int* d_i[2] = {sycl::malloc_device<int>((size_t) n_tokens * k, q), sycl::malloc_device<int>((size_t) n_tokens * k, q)};
140    float* d_w[2] = {sycl::malloc_device<float>((size_t) n_tokens * k, q), sycl::malloc_device<float>((size_t) n_tokens * k, q)};
141    q.memcpy(d_l, logits.data(), logits.size() * sizeof(float)).wait();
142    std::vector<int> ids[2];
143    std::vector<float> w[2];
144    const int variants[2] = {0, 3};
145    for (int v = 0; v < 2; ++v) {
146        if (!strata::kernels::router_top10_variant(d_l, n_tokens, n_expert, k, d_i[v], d_w[v], nullptr, variants[v])) {
147            std::printf("  %-26s fp32 vs double: variant %d not available\n", name, variants[v]);
148            return 1;
149        }
150        q.wait();
151        ids[v].resize((size_t) n_tokens * k);
152        w[v].resize((size_t) n_tokens * k);
153        q.memcpy(ids[v].data(), d_i[v], ids[v].size() * sizeof(int)).wait();
154        q.memcpy(w[v].data(), d_w[v], w[v].size() * sizeof(float)).wait();
155    }
156    long long id_diff = 0;
157    double worst = 0, worst_abs = 0;
158    for (size_t i = 0; i < ids[0].size(); ++i) {
159        if (ids[0][i] != ids[1][i]) { ++id_diff; continue; }
160        const double a = w[0][i], b = w[1][i];
161        worst_abs = std::max(worst_abs, std::fabs(a - b));
162        worst = std::max(worst, std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30));
163    }
164    std::printf("  %-26s fp32 vs double: ids differ %lld of %zu   weights max rel %.3e  max abs %.3e\n", name, id_diff, ids[0].size(), worst, worst_abs);
165    sycl::free(d_l, q);
166    for (int v = 0; v < 2; ++v) { sycl::free(d_i[v], q); sycl::free(d_w[v], q); }
167    return id_diff ? 1 : 0;
168}
169
170}  // namespace
171
172int main(int argc, char** argv) {
173    bool selftest = false;
174    for (int i = 1; i < argc; ++i) {
175        if (std::string(argv[i]) == "--selftest") selftest = true;
176        else { std::fprintf(stderr, "usage: router_top10_parity [--selftest]\n"); return 2; }
177    }
178
179    const int NE = 512;          // the real n_expert
180    const int K = 10;            // the real top-k
181    const int NT = 64;
182    std::mt19937 rng(2024);
183    std::normal_distribution<float> gauss(0.0f, 1.0f);
184    int bad = 0;
185
186    // ---- random logits
187    std::vector<float> a((size_t) NT * NE);
188    for (auto& v : a) v = gauss(rng);
189    bad += run_case("random normal", a, NT, NE, K, 1e-5);
190
191    // ---- ALL-EQUAL logits: every expert ties, so the "smallest index wins" rule is the ONLY thing deciding
192    // the ids.  An unstable sort or a >= comparison in the maximum scan fails this and passes everything else.
193    std::vector<float> b((size_t) NT * NE, 0.5f);
194    bad += run_case("all equal (ties)", b, NT, NE, K, 1e-5);
195
196    // ---- a few exact ties among otherwise distinct values
197    std::vector<float> c((size_t) NT * NE);
198    for (int t = 0; t < NT; ++t) {
199        for (int e = 0; e < NE; ++e) c[(size_t) t * NE + e] = (e < 12) ? 2.0f : gauss(rng);
200    }
201    bad += run_case("12-way exact tie", c, NT, NE, K, 1e-5);
202
203    // ---- one dominant expert: the top-1 must be that expert and its weight must dominate
204    std::vector<float> d((size_t) NT * NE, 0.0f);
205    for (int t = 0; t < NT; ++t) d[(size_t) t * NE + (t % NE)] = 20.0f;
206    bad += run_case("dominant expert", d, NT, NE, K, 1e-5);
207
208    // ---- THE CLAMP CANNOT TRIGGER, and that is provable rather than untested.
209    // The sum of the top k of a probability vector over n outcomes is at least k/n (the minimum is the uniform
210    // distribution).  Here k/n = 10/512 = 0.01953125, which is 320x the 2**-14 = 6.1035e-05 clamp, so no input
211    // whatsoever can make this model's renormalisation clamp - not an extreme one, not an adversarial one.
212    // Asserting the bound is worth more than a test that cannot reach it.
213    const double min_possible = (double) K / (double) NE;
214    std::printf("  %-26s top-%d sum >= k/n = %.5f, clamp is %.3e -> margin %.0fx  %s\n", "clamp reachability",
215                K, min_possible, RENORM_CLAMP, min_possible / RENORM_CLAMP,
216                min_possible > RENORM_CLAMP ? "(CLAMP IS UNREACHABLE, asserted)" : "*** REACHABLE ***");
217    if (min_possible <= RENORM_CLAMP) {
218        std::fprintf(stderr, "the clamp CAN trigger, so it needs a test\n");
219        ++bad;
220    }
221
222    std::printf("\nrouter_top10: %d failures over 4 distributions x %d tokens x %d experts, top-%d\n", bad, NT, NE,
223                K);
224
225    // ---- the Qwen4 shapes (Q4-READY): 256 experts top-8 (q4_lite), 512 top-8, 256 top-10, and the fp32 router against the double one
226    // on the same inputs at each (variant 3 vs variant 0; skipped on a device that runs no double)
227    const int shapes[][2] = {{256, 8}, {512, 8}, {256, 10}, {512, 10}};
228    for (const auto& sh : shapes) {
229        const int ne = sh[0], kk = sh[1];
230        char label[64];
231        std::vector<float> r((size_t) NT * ne);
232        for (auto& v : r) v = gauss(rng);
233        std::snprintf(label, sizeof label, "random %dx top-%d", ne, kk);
234        bad += run_case(label, r, NT, ne, kk, 1e-5);
235        bad += f32_vs_double(label, r, NT, ne, kk);
236        std::vector<float> tie((size_t) NT * ne);
237        for (int t = 0; t < NT; ++t)
238            for (int e = 0; e < ne; ++e) tie[(size_t) t * ne + e] = (e < 12) ? 2.0f : gauss(rng);
239        std::snprintf(label, sizeof label, "12-way tie %dx top-%d", ne, kk);
240        bad += run_case(label, tie, NT, ne, kk, 1e-5);
241        bad += f32_vs_double(label, tie, NT, ne, kk);
242        std::vector<float> wide((size_t) NT * ne);
243        for (auto& v : wide) v = 6.0f * gauss(rng);          // a peaked router (large logit spread)
244        std::snprintf(label, sizeof label, "wide %dx top-%d", ne, kk);
245        bad += run_case(label, wide, NT, ne, kk, 1e-5);
246        bad += f32_vs_double(label, wide, NT, ne, kk);
247    }
248    std::printf("router_top10 (with the Qwen4 shapes): %d failures\n", bad);
249    if (bad) return 1;
250    if (selftest) std::printf("router_top10_parity OK\n");
251    return 0;
252}