okami.mom/strata

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

Niko1221Strata: Qwen3.8-Flash-Next on a 12-24 GB NVIDIA GPU + 64 GB RAM, one-click install01529aaa8

main
7.5 KiB167 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#include "strata/kernels/router_top10.hpp"
13
14#include <cuda_runtime.h>
15
16#include <algorithm>
17#include <cmath>
18#include <cstdio>
19#include <cstdlib>
20#include <numeric>
21#include <random>
22#include <vector>
23
24namespace {
25
26void check(cudaError_t e, const char* what) {
27    if (e != cudaSuccess) {
28        std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
29        std::exit(1);
30    }
31}
32
33constexpr double RENORM_CLAMP = 6.103515625e-05;      // 2**-14
34
35// The host reference: softmax over all experts, stable descending argsort, gather, clamp, renormalise.
36void reference(const float* logits, int n_expert, int k, int* ids, float* w) {
37    double mx = logits[0];
38    for (int e = 1; e < n_expert; ++e) mx = std::max(mx, (double) logits[e]);
39    double sum = 0;
40    std::vector<double> p((size_t) n_expert);
41    for (int e = 0; e < n_expert; ++e) {
42        p[(size_t) e] = std::exp((double) logits[e] - mx);
43        sum += p[(size_t) e];
44    }
45    for (int e = 0; e < n_expert; ++e) p[(size_t) e] /= sum;
46
47    // stable descending: std::stable_sort with a strict greater-than keeps equal elements in index order
48    std::vector<int> idx((size_t) n_expert);
49    std::iota(idx.begin(), idx.end(), 0);
50    std::stable_sort(idx.begin(), idx.end(),
51                     [&](int a, int b) { return p[(size_t) a] > p[(size_t) b]; });
52    double s = 0;
53    for (int i = 0; i < k; ++i) {
54        ids[i] = idx[(size_t) i];
55        w[i] = (float) p[(size_t) idx[(size_t) i]];
56        s += p[(size_t) idx[(size_t) i]];
57    }
58    s = std::max(s, RENORM_CLAMP);
59    for (int i = 0; i < k; ++i) w[i] = (float) ((double) w[i] / s);
60}
61
62int run_case(const char* name, const std::vector<float>& logits, int n_tokens, int n_expert, int k,
63             double tol) {
64    std::vector<int> h_ids((size_t) n_tokens * k);
65    std::vector<float> h_w((size_t) n_tokens * k);
66    std::vector<int> r_ids((size_t) n_tokens * k);
67    std::vector<float> r_w((size_t) n_tokens * k);
68    for (int t = 0; t < n_tokens; ++t) {
69        reference(&logits[(size_t) t * n_expert], n_expert, k, &r_ids[(size_t) t * k], &r_w[(size_t) t * k]);
70    }
71
72    float* d_l = nullptr;
73    int* d_ids = nullptr;
74    float* d_w = nullptr;
75    check(cudaMalloc(&d_l, logits.size() * sizeof(float)), "malloc logits");
76    check(cudaMalloc(&d_ids, h_ids.size() * sizeof(int)), "malloc ids");
77    check(cudaMalloc(&d_w, h_w.size() * sizeof(float)), "malloc w");
78    check(cudaMemcpy(d_l, logits.data(), logits.size() * sizeof(float), cudaMemcpyHostToDevice), "copy");
79    strata::kernels::router_top10(d_l, n_tokens, n_expert, k, d_ids, d_w, nullptr);
80    check(cudaMemcpy(h_ids.data(), d_ids, h_ids.size() * sizeof(int), cudaMemcpyDeviceToHost), "back ids");
81    check(cudaMemcpy(h_w.data(), d_w, h_w.size() * sizeof(float), cudaMemcpyDeviceToHost), "back w");
82
83    long long id_bad = 0, w_bad = 0;
84    double worst = 0;
85    for (size_t i = 0; i < h_ids.size(); ++i) {
86        if (h_ids[i] != r_ids[i]) ++id_bad;
87        const double rel = std::fabs((double) h_w[i] - (double) r_w[i]) /
88                           (std::fabs((double) r_w[i]) > 1e-30 ? std::fabs((double) r_w[i]) : 1e-30);
89        worst = std::max(worst, rel);
90        if (!(rel <= tol)) ++w_bad;
91    }
92    // every token's weights must sum to 1 unless the clamp replaced the sum
93    double worst_sum = 0;
94    for (int t = 0; t < n_tokens; ++t) {
95        double s = 0;
96        for (int i = 0; i < k; ++i) s += (double) h_w[(size_t) t * k + i];
97        double raw = 0;
98        for (int i = 0; i < k; ++i) raw += (double) r_w[(size_t) t * k + i];
99        // both sides divide by the same clamped scale, so the ratios agree; check the kernel's own sum
100        worst_sum = std::max(worst_sum, std::fabs(s - 1.0));
101    }
102    std::printf("  %-26s ids %s (%lld bad)   weights worst rel %.3e (%lld over tol)   |sum-1| %.1e\n", name,
103                id_bad ? "*** WRONG ***" : "exact", id_bad, worst, w_bad, worst_sum);
104    cudaFree(d_l);
105    cudaFree(d_ids);
106    cudaFree(d_w);
107    return (int) (id_bad + w_bad);
108}
109
110}  // namespace
111
112int main(int argc, char** argv) {
113    bool selftest = false;
114    for (int i = 1; i < argc; ++i) {
115        if (std::string(argv[i]) == "--selftest") selftest = true;
116        else { std::fprintf(stderr, "usage: router_top10_parity [--selftest]\n"); return 2; }
117    }
118
119    const int NE = 512;          // the real n_expert
120    const int K = 10;            // the real top-k
121    const int NT = 64;
122    std::mt19937 rng(2024);
123    std::normal_distribution<float> gauss(0.0f, 1.0f);
124    int bad = 0;
125
126    // ---- random logits
127    std::vector<float> a((size_t) NT * NE);
128    for (auto& v : a) v = gauss(rng);
129    bad += run_case("random normal", a, NT, NE, K, 1e-5);
130
131    // ---- ALL-EQUAL logits: every expert ties, so the "smallest index wins" rule is the ONLY thing deciding
132    // the ids.  An unstable sort or a >= comparison in the maximum scan fails this and passes everything else.
133    std::vector<float> b((size_t) NT * NE, 0.5f);
134    bad += run_case("all equal (ties)", b, NT, NE, K, 1e-5);
135
136    // ---- a few exact ties among otherwise distinct values
137    std::vector<float> c((size_t) NT * NE);
138    for (int t = 0; t < NT; ++t) {
139        for (int e = 0; e < NE; ++e) c[(size_t) t * NE + e] = (e < 12) ? 2.0f : gauss(rng);
140    }
141    bad += run_case("12-way exact tie", c, NT, NE, K, 1e-5);
142
143    // ---- one dominant expert: the top-1 must be that expert and its weight must dominate
144    std::vector<float> d((size_t) NT * NE, 0.0f);
145    for (int t = 0; t < NT; ++t) d[(size_t) t * NE + (t % NE)] = 20.0f;
146    bad += run_case("dominant expert", d, NT, NE, K, 1e-5);
147
148    // ---- THE CLAMP CANNOT TRIGGER, and that is provable rather than untested.
149    // The sum of the top k of a probability vector over n outcomes is at least k/n (the minimum is the uniform
150    // distribution).  Here k/n = 10/512 = 0.01953125, which is 320x the 2**-14 = 6.1035e-05 clamp, so no input
151    // whatsoever can make this model's renormalisation clamp - not an extreme one, not an adversarial one.
152    // Asserting the bound is worth more than a test that cannot reach it.
153    const double min_possible = (double) K / (double) NE;
154    std::printf("  %-26s top-%d sum >= k/n = %.5f, clamp is %.3e -> margin %.0fx  %s\n", "clamp reachability",
155                K, min_possible, RENORM_CLAMP, min_possible / RENORM_CLAMP,
156                min_possible > RENORM_CLAMP ? "(CLAMP IS UNREACHABLE, asserted)" : "*** REACHABLE ***");
157    if (min_possible <= RENORM_CLAMP) {
158        std::fprintf(stderr, "the clamp CAN trigger, so it needs a test\n");
159        ++bad;
160    }
161
162    std::printf("\nrouter_top10: %d failures over 4 distributions x %d tokens x %d experts, top-%d\n", bad, NT, NE,
163                K);
164    if (bad) return 1;
165    if (selftest) std::printf("router_top10_parity OK\n");
166    return 0;
167}