okami.mom/strata

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

waveringanaedge0-strata: add the engine for Edge0 145B and Edge0 120Bfd19246dc

main
9.6 KiB207 linesraw
1// src/kernels/latent_layer0_verify.cpp - layer0 latent-MoE pipeline on the real checkpoint.
2//
3//     latent_layer0_verify <latent_layer0_test.bin> <experts_layer0_native.bin>
4//
5// The A pack must be in the native block_nvfp4 nibble layout (d[4]+qs[32],
6// sub-block low/high split), not a verbatim copy of the checkpoint's even/odd
7// q bytes; make_native_pack.py does that permutation.
8//
9// D (Q8_0) -> q8_1 -> A (native NVFP4 grouped experts) -> U (Q8_0) -> combine,
10// against the Python float32 reference written in the test bundle.  This is the
11// first module of the latent adaptation: kernels + routing + two-stage output,
12// without the Strata verify/cache integration yet.
13#include "strata/kernels/iq_kernels.hpp"
14
15#include <cuda_runtime.h>
16
17#include <cmath>
18#include <cstdint>
19#include <cstdio>
20#include <cstdlib>
21#include <cstring>
22#include <fstream>
23#include <string>
24#include <vector>
25
26namespace k = strata::kernels;
27
28namespace {
29void ck(cudaError_t e, const char* what) {
30    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); }
31}
32
33template<typename T>
34std::vector<T> read_n(std::ifstream& f, size_t n, const char* what) {
35    std::vector<T> v(n);
36    if (!f.read((char*) v.data(), (std::streamsize) (n * sizeof(T)))) {
37        std::fprintf(stderr, "short read: %s\n", what);
38        std::exit(1);
39    }
40    return v;
41}
42
43double rel_l2(const std::vector<float>& got, const std::vector<float>& ref) {
44    double num = 0, den = 0;
45    for (size_t i = 0; i < got.size(); ++i) {
46        const double d = (double) got[i] - (double) ref[i];
47        num += d * d;
48        den += (double) ref[i] * (double) ref[i];
49    }
50    return std::sqrt(num / (den + 1e-30));
51}
52
53float max_abs(const std::vector<float>& got, const std::vector<float>& ref) {
54    float m = 0;
55    for (size_t i = 0; i < got.size(); ++i) m = std::fmax(m, std::fabs(got[i] - ref[i]));
56    return m;
57}
58
59void report(const char* name, const std::vector<float>& got, const std::vector<float>& ref) {
60    std::printf("  %-4s relL2 %.4f%%  max_abs %.6g\n", name, 100 * rel_l2(got, ref), max_abs(got, ref));
61}
62}  // namespace
63
64int main(int argc, char** argv) {
65    if (argc < 3) { std::fprintf(stderr, "usage: %s test.bin experts_layer0.bin\n", argv[0]); return 2; }
66    std::ifstream f(argv[1], std::ios::binary);
67    if (!f) { std::fprintf(stderr, "cannot open %s\n", argv[1]); return 2; }
68    char magic[4];
69    f.read(magic, 4);
70    if (std::memcmp(magic, "LAT0", 4) != 0) { std::fprintf(stderr, "bad magic\n"); return 2; }
71    int32_t hdr[7];
72    if (!f.read((char*) hdr, sizeof hdr)) return 2;
73    const int T = hdr[0], K = hdr[1], G = hdr[2], E = hdr[3], H = hdr[4], ELL = hdr[5], I = hdr[6];
74    std::printf("T=%d K=%d G=%d E=%d H=%d ELL=%d I=%d\n", T, K, G, E, H, ELL, I);
75    if (T * K > 128) { std::fprintf(stderr, "cap too large for this test\n"); return 2; }
76
77    const auto x = read_n<float>(f, (size_t) T * H, "x");
78    const auto topk = read_n<int32_t>(f, (size_t) T * K, "topk");
79    const auto w = read_n<float>(f, (size_t) T * K, "w");
80    const auto labels = read_n<int32_t>(f, (size_t) E, "labels");
81    const size_t drow = (size_t) H / 32 * 34, urow = (size_t) ELL / 32 * 34;
82    const auto dq8 = read_n<uint8_t>(f, (size_t) G * ELL * drow, "Dq8");
83    const auto uq8 = read_n<uint8_t>(f, (size_t) G * H * urow, "Uq8");
84    const auto ref_xl = read_n<float>(f, (size_t) T * G * ELL, "ref_xl");
85    const auto ref_yl = read_n<float>(f, (size_t) T * K * ELL, "ref_yl");
86    const auto ref_y = read_n<float>(f, (size_t) T * K * H, "ref_y");
87    const auto ref_out = read_n<float>(f, (size_t) T * H, "ref_out");
88
89    const k::NativeExpertLayout L = k::native_expert_layout(40, 40, ELL, I);
90    if (!k::native_expert_supported(40, 40, ELL, I)) { std::fprintf(stderr, "native layout unsupported\n"); return 2; }
91    std::ifstream af(argv[2], std::ios::binary | std::ios::ate);
92    if (!af) { std::fprintf(stderr, "cannot open %s\n", argv[2]); return 2; }
93    const size_t asz = (size_t) af.tellg();
94    if (asz != (size_t) E * L.bytes) {
95        std::fprintf(stderr, "A pack size %zu != %zu\n", asz, (size_t) E * L.bytes);
96        return 2;
97    }
98    af.seekg(0);
99    auto ablob = read_n<uint8_t>(af, asz, "A blobs");
100
101    const int32_t cap = T * K;
102    // route plan grouped by expert: entries are the route indices, activations are token*G+group
103    std::vector<int32_t> start(E + 1, 0), dst(cap), tok(cap), pos(E);
104    std::vector<int32_t> counts(E, 0);
105    for (int32_t r = 0; r < cap; ++r) counts[topk[r]]++;
106    for (int e = 0; e < E; ++e) start[e + 1] = start[e] + counts[e];
107    pos = start;
108    for (int32_t r = 0; r < cap; ++r) {
109        const int e = topk[r];
110        const int p = pos[e]++;
111        dst[p] = r;
112        tok[p] = (r / K) * G + labels[e];
113    }
114
115    void *dxq = nullptr, *dxlq = nullptr, *dscr = nullptr;
116    float *dx = nullptr, *dD = nullptr, *dU = nullptr, *dXl = nullptr, *dYl = nullptr, *dY = nullptr;
117    float *dUIn = nullptr, *dUOut = nullptr;
118    void* dUq = nullptr;
119    uint8_t* dA = nullptr;
120    unsigned long long* dPtr = nullptr;
121    int32_t *dStart = nullptr, *dN = nullptr, *dDst = nullptr, *dTok = nullptr;
122
123    ck(cudaMalloc(&dx, (size_t) T * H * 4), "x");
124    ck(cudaMalloc(&dxq, (size_t) T * (H / 32) * 36), "xq");
125    ck(cudaMalloc(&dD, (size_t) G * ELL * drow), "D");
126    ck(cudaMalloc(&dU, (size_t) G * H * urow), "U");
127    ck(cudaMalloc(&dXl, (size_t) T * G * ELL * 4), "xl");
128    ck(cudaMalloc(&dxlq, (size_t) T * G * (ELL / 32) * 36), "xlq");
129    ck(cudaMalloc(&dA, asz), "A");
130    ck(cudaMalloc(&dPtr, (size_t) E * 8), "ptr");
131    ck(cudaMalloc(&dStart, (size_t) (E + 1) * 4), "start");
132    ck(cudaMalloc(&dN, 4), "n");
133    ck(cudaMalloc(&dDst, (size_t) cap * 4), "dst");
134    ck(cudaMalloc(&dTok, (size_t) cap * 4), "tok");
135    ck(cudaMalloc(&dYl, (size_t) cap * ELL * 4), "yl");
136    ck(cudaMalloc(&dY, (size_t) cap * H * 4), "y");
137    ck(cudaMalloc(&dUIn, (size_t) cap * ELL * 4), "uin");
138    ck(cudaMalloc(&dUOut, (size_t) cap * H * 4), "uout");
139    ck(cudaMalloc(&dUq, (size_t) cap * (ELL / 32) * 36), "uq");
140    ck(cudaMalloc(&dscr, k::native_expert_scratch_bytes(cap, I)), "scratch");
141
142    ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
143    ck(cudaMemcpy(dD, dq8.data(), dq8.size(), cudaMemcpyHostToDevice), "D");
144    ck(cudaMemcpy(dU, uq8.data(), uq8.size(), cudaMemcpyHostToDevice), "U");
145    ck(cudaMemcpy(dA, ablob.data(), ablob.size(), cudaMemcpyHostToDevice), "A");
146    std::vector<unsigned long long> ptr(E);
147    for (int e = 0; e < E; ++e) ptr[e] = (unsigned long long) (dA + (size_t) e * L.bytes);
148    const int32_t n_groups = E;
149    ck(cudaMemcpy(dPtr, ptr.data(), ptr.size() * 8, cudaMemcpyHostToDevice), "ptr");
150    ck(cudaMemcpy(dStart, start.data(), start.size() * 4, cudaMemcpyHostToDevice), "start");
151    ck(cudaMemcpy(dN, &n_groups, 4, cudaMemcpyHostToDevice), "n");
152    ck(cudaMemcpy(dDst, dst.data(), dst.size() * 4, cudaMemcpyHostToDevice), "dst");
153    ck(cudaMemcpy(dTok, tok.data(), tok.size() * 4, cudaMemcpyHostToDevice), "tok");
154
155    // D: [T,H] x [G*ELL,H]^T -> [T,G*ELL]
156    k::quantize_q8_1_rows(dx, T, H, dxq, nullptr);
157    ck(cudaDeviceSynchronize(), "D quantize");
158    k::iq_mmvq(8, dD, dxq, dXl, H, G * ELL, T, nullptr);
159    ck(cudaDeviceSynchronize(), "D");
160    k::quantize_q8_1_rows(dXl, T * G, ELL, dxlq, nullptr);
161    ck(cudaDeviceSynchronize(), "xl quantize");
162
163    // A: every expert is a group; entries are grouped by expert, activation row = token*G+group.
164    k::native_expert_grouped(L, dPtr, dStart, dN, dDst, dTok, E, cap, dxlq, dscr, dYl, nullptr, E);
165    ck(cudaDeviceSynchronize(), "A");
166    // U: per group, gather the route rows, Q8 GEMM, scatter back.
167    for (int g = 0; g < G; ++g) {
168        std::vector<int32_t> routes;
169        for (int r = 0; r < cap; ++r) if (labels[topk[r]] == g) routes.push_back(r);
170        const int n = (int) routes.size();
171        if (!n) continue;
172        for (int i = 0; i < n; ++i)
173            ck(cudaMemcpy(dUIn + (size_t) i * ELL, dYl + (size_t) routes[i] * ELL, (size_t) ELL * 4,
174                          cudaMemcpyDeviceToDevice), "gather");
175        k::quantize_q8_1_rows(dUIn, n, ELL, dUq, nullptr);
176        ck(cudaDeviceSynchronize(), "U quantize");
177        k::iq_mmvq(8, (const uint8_t*) dU + (size_t) g * H * urow, dUq, dUOut, ELL, H, n, nullptr);
178        ck(cudaDeviceSynchronize(), "U");
179        for (int i = 0; i < n; ++i)
180            ck(cudaMemcpy(dY + (size_t) routes[i] * H, dUOut + (size_t) i * H, (size_t) H * 4,
181                          cudaMemcpyDeviceToDevice), "scatter");
182    }
183    ck(cudaDeviceSynchronize(), "run");
184
185    std::vector<float> xl((size_t) T * G * ELL), yl((size_t) cap * ELL), y((size_t) cap * H), out((size_t) T * H, 0.f);
186    ck(cudaMemcpy(xl.data(), dXl, xl.size() * 4, cudaMemcpyDeviceToHost), "xl");
187    ck(cudaMemcpy(yl.data(), dYl, yl.size() * 4, cudaMemcpyDeviceToHost), "yl");
188    ck(cudaMemcpy(y.data(), dY, y.size() * 4, cudaMemcpyDeviceToHost), "y");
189    for (int t = 0; t < T; ++t)
190        for (int j = 0; j < K; ++j)
191            for (int h = 0; h < H; ++h)
192                out[(size_t) t * H + h] += w[(size_t) t * K + j] * y[(size_t) (t * K + j) * H + h];
193
194    std::printf("latent layer0 (D Q8 -> A NVFP4 -> U Q8):\n");
195    report("xl", xl, ref_xl);
196    report("yl", yl, ref_yl);
197    report("y", y, ref_y);
198    report("out", out, ref_out);
199    const double eo = rel_l2(out, ref_out);
200    std::printf("RESULT: %s (combine relL2 %.3f%%)\n", eo < 0.03 ? "ok" : "TOO FAR", 100 * eo);
201
202    for (void* p : {(void*) dx, dxq, (void*) dD, (void*) dU, (void*) dXl, dxlq, (void*) dA, (void*) dPtr,
203                    (void*) dStart, (void*) dN, (void*) dDst, (void*) dTok, (void*) dYl, (void*) dY,
204                    (void*) dUIn, (void*) dUOut, dUq, dscr})
205        cudaFree(p);
206    return eo < 0.03 ? 0 : 1;
207}