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.5 KiB199 linesraw
1// src/kernels/latent_module_verify.cpp - one layer through strata::latent::run_layer.
2//
3//     latent_layer_pack_verify <layerL_test.bin> <latent_a_pack> <latent_dense_q8.bin> <layer>
4//
5// A comes from FileExpertSource (latent_a_pack/experts.bin), D/U from LatentDense
6// (mmap), and the test bundle supplies only x/routing/reference.  This is the
7// production storage path, without touching verify.cpp.
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#include "strata/core/expert_source.hpp"
15#include "strata/core/latent_dense.hpp"
16#include "strata/kernels/cpu/expert_layout.hpp"
17#include "strata/latent/latent_moe.hpp"
18
19#include <cuda_runtime.h>
20
21#include <cmath>
22#include <cstdint>
23#include <cstdio>
24#include <cstdlib>
25#include <cstring>
26#include <fstream>
27#include <string>
28#include <vector>
29
30namespace k = strata::kernels;
31
32namespace {
33void ck(cudaError_t e, const char* what) {
34    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); }
35}
36
37template<typename T>
38std::vector<T> read_n(std::ifstream& f, size_t n, const char* what) {
39    std::vector<T> v(n);
40    if (!f.read((char*) v.data(), (std::streamsize) (n * sizeof(T)))) {
41        std::fprintf(stderr, "short read: %s\n", what);
42        std::exit(1);
43    }
44    return v;
45}
46
47double rel_l2(const std::vector<float>& got, const std::vector<float>& ref) {
48    double num = 0, den = 0;
49    for (size_t i = 0; i < got.size(); ++i) {
50        const double d = (double) got[i] - (double) ref[i];
51        num += d * d;
52        den += (double) ref[i] * (double) ref[i];
53    }
54    return std::sqrt(num / (den + 1e-30));
55}
56
57float max_abs(const std::vector<float>& got, const std::vector<float>& ref) {
58    float m = 0;
59    for (size_t i = 0; i < got.size(); ++i) m = std::fmax(m, std::fabs(got[i] - ref[i]));
60    return m;
61}
62
63void report(const char* name, const std::vector<float>& got, const std::vector<float>& ref) {
64    std::printf("  %-4s relL2 %.4f%%  max_abs %.6g\n", name, 100 * rel_l2(got, ref), max_abs(got, ref));
65}
66}  // namespace
67
68int main(int argc, char** argv) {
69    if (argc < 5) { std::fprintf(stderr, "usage: %s test.bin latent_a_pack dense_q8.bin layer\n", argv[0]); return 2; }
70    const int layer = std::atoi(argv[4]);
71    std::ifstream f(argv[1], std::ios::binary);
72    if (!f) { std::fprintf(stderr, "cannot open %s\n", argv[1]); return 2; }
73    char magic[4];
74    f.read(magic, 4);
75    if (std::memcmp(magic, "LAT0", 4) != 0) { std::fprintf(stderr, "bad magic\n"); return 2; }
76    int32_t hdr[7];
77    if (!f.read((char*) hdr, sizeof hdr)) return 2;
78    const int T = hdr[0], K = hdr[1], G = hdr[2], E = hdr[3], H = hdr[4], ELL = hdr[5], I = hdr[6];
79    std::printf("T=%d K=%d G=%d E=%d H=%d ELL=%d I=%d\n", T, K, G, E, H, ELL, I);
80    if (T * K > 128) { std::fprintf(stderr, "cap too large for this test\n"); return 2; }
81
82    const auto x = read_n<float>(f, (size_t) T * H, "x");
83    const auto topk = read_n<int32_t>(f, (size_t) T * K, "topk");
84    const auto w = read_n<float>(f, (size_t) T * K, "w");
85    const auto labels = read_n<int32_t>(f, (size_t) E, "labels");
86    // The test bundle's D/U Q8 is skipped; the real dense pack replaces it.  Q4DU: the
87    // bundle's D/U width follows the FORMAT ENV (the same pack family the operator passes).
88    {
89        const char* fe = std::getenv("STRATA_LATENT_DENSE_FMT");
90        const int fmtb = (fe && fe[0] == '4' && fe[1] == 0) ? 4 : 8;
91        const size_t drow = (size_t) H / 32 * (fmtb == 4 ? 18 : 34);
92        const size_t urow = (size_t) ELL / 32 * (fmtb == 4 ? 18 : 34);
93        f.seekg((std::streamoff) ((size_t) G * ELL * drow + (size_t) G * H * urow), std::ios::cur);
94    }
95    const auto ref_xl = read_n<float>(f, (size_t) T * G * ELL, "ref_xl");
96    const auto ref_yl = read_n<float>(f, (size_t) T * K * ELL, "ref_yl");
97    const auto ref_y = read_n<float>(f, (size_t) T * K * H, "ref_y");
98    const auto ref_out = read_n<float>(f, (size_t) T * H, "ref_out");
99
100    std::string err;
101    if (!strata::kernels::cpu::expert_layout_load(argv[2], 48, 512, err)) {
102        std::fprintf(stderr, "layout: %s\n", err.c_str()); return 2;
103    }
104    strata::core::FileExpertSource src;
105    if (!src.open(argv[2], 48, 512, err)) { std::fprintf(stderr, "source: %s\n", err.c_str()); return 2; }
106    strata::core::LatentDense dense;
107    if (!dense.open(argv[3], 48, G, H, ELL, err)) { std::fprintf(stderr, "dense: %s\n", err.c_str()); return 2; }
108    const int fmt = dense.fmt();   // Q4DU: the bundle's D/U skip and Inputs.fmt follow the pack
109    (void) fmt;
110
111    const k::NativeExpertLayout L = k::native_expert_layout(40, 40, ELL, I);
112    if (!k::native_expert_supported(40, 40, ELL, I)) { std::fprintf(stderr, "native layout unsupported\n"); return 2; }
113    const size_t asz = (size_t) E * L.bytes;
114
115    const int32_t cap = T * K;
116    // route plan grouped by expert: entries are the route indices, activations are token*G+group
117    std::vector<int32_t> start(E + 1, 0), dst(cap), tok(cap), pos(E);
118    std::vector<int32_t> counts(E, 0);
119    for (int32_t r = 0; r < cap; ++r) counts[topk[r]]++;
120    for (int e = 0; e < E; ++e) start[e + 1] = start[e] + counts[e];
121    pos = start;
122    for (int32_t r = 0; r < cap; ++r) {
123        const int e = topk[r];
124        const int p = pos[e]++;
125        dst[p] = r;
126        tok[p] = (r / K) * G + labels[e];
127    }
128
129    void *dxq = nullptr, *dxlq = nullptr, *dscr = nullptr;
130    float *dx = nullptr, *dD = nullptr, *dU = nullptr, *dXl = nullptr, *dYl = nullptr, *dY = nullptr;
131    float *dUIn = nullptr, *dUOut = nullptr;
132    void* dUq = nullptr;
133    uint8_t* dA = nullptr;
134    unsigned long long* dPtr = nullptr;
135    int32_t *dStart = nullptr, *dN = nullptr, *dDst = nullptr, *dTok = nullptr;
136
137    ck(cudaMalloc(&dx, (size_t) T * H * 4), "x");
138    ck(cudaMalloc(&dxq, (size_t) T * (H / 32) * 36), "xq");
139    ck(cudaMalloc(&dD, dense.d_bytes()), "D");
140    ck(cudaMalloc(&dU, dense.u_bytes()), "U");
141    ck(cudaMalloc(&dXl, (size_t) T * G * ELL * 4), "xl");
142    ck(cudaMalloc(&dxlq, (size_t) T * G * (ELL / 32) * 36), "xlq");
143    ck(cudaMalloc(&dA, asz), "A");
144    ck(cudaMalloc(&dPtr, (size_t) E * 8), "ptr");
145    ck(cudaMalloc(&dStart, (size_t) (E + 1) * 4), "start");
146    ck(cudaMalloc(&dN, 4), "n");
147    ck(cudaMalloc(&dDst, (size_t) cap * 4), "dst");
148    ck(cudaMalloc(&dTok, (size_t) cap * 4), "tok");
149    ck(cudaMalloc(&dYl, (size_t) cap * ELL * 4), "yl");
150    ck(cudaMalloc(&dY, (size_t) cap * H * 4), "y");
151    ck(cudaMalloc(&dUIn, (size_t) cap * ELL * 4), "uin");
152    ck(cudaMalloc(&dUOut, (size_t) cap * H * 4), "uout");
153    ck(cudaMalloc(&dUq, (size_t) cap * (ELL / 32) * 36), "uq");
154    ck(cudaMalloc(&dscr, k::native_expert_scratch_bytes(cap, I)), "scratch");
155
156    ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
157    ck(cudaMemcpy(dD, dense.d(layer), dense.d_bytes(), cudaMemcpyHostToDevice), "D");
158    ck(cudaMemcpy(dU, dense.u(layer), dense.u_bytes(), cudaMemcpyHostToDevice), "U");
159    for (int e = 0; e < E; ++e) {
160        const uint8_t* p = src.blob(layer, e);
161        if (!p) { std::fprintf(stderr, "source blob null layer %d expert %d\n", layer, e); return 2; }
162        ck(cudaMemcpy(dA + (size_t) e * L.bytes, p, L.bytes, cudaMemcpyHostToDevice), "A blob");
163    }
164    std::vector<unsigned long long> ptr(E);
165    for (int e = 0; e < E; ++e) ptr[e] = (unsigned long long) (dA + (size_t) e * L.bytes);
166    const int32_t n_groups = E;
167    ck(cudaMemcpy(dPtr, ptr.data(), ptr.size() * 8, cudaMemcpyHostToDevice), "ptr");
168    ck(cudaMemcpy(dStart, start.data(), start.size() * 4, cudaMemcpyHostToDevice), "start");
169    ck(cudaMemcpy(dN, &n_groups, 4, cudaMemcpyHostToDevice), "n");
170    ck(cudaMemcpy(dDst, dst.data(), dst.size() * 4, cudaMemcpyHostToDevice), "dst");
171    ck(cudaMemcpy(dTok, tok.data(), tok.size() * 4, cudaMemcpyHostToDevice), "tok");
172
173    const strata::latent::Geometry g{(int64_t) H, (int64_t) ELL, (int64_t) I, G, E, K};
174    const strata::latent::Inputs in{(const uint8_t*) dD, (const uint8_t*) dU, dx, topk.data(), labels.data(), nullptr, w.data(), T, fmt};   // Q4DU: the pack's fmt
175    const strata::latent::DevicePlan dp{dPtr, dStart, dN, dDst, dTok, cap, E};
176    const strata::latent::Buffers b{dxq, dxlq, dUq, dscr, dXl, dYl, dUIn, dUOut, dY};
177    if (!strata::latent::run_layer(g, in, dp, b, nullptr)) { std::fprintf(stderr, "run_layer failed\n"); return 2; }
178    ck(cudaDeviceSynchronize(), "run");
179
180    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);
181    ck(cudaMemcpy(xl.data(), dXl, xl.size() * 4, cudaMemcpyDeviceToHost), "xl");
182    ck(cudaMemcpy(yl.data(), dYl, yl.size() * 4, cudaMemcpyDeviceToHost), "yl");
183    ck(cudaMemcpy(y.data(), dY, y.size() * 4, cudaMemcpyDeviceToHost), "y");
184    strata::latent::combine(g, w.data(), y.data(), out.data(), T);
185
186    std::printf("latent module layer %d:\n", layer);
187    report("xl", xl, ref_xl);
188    report("yl", yl, ref_yl);
189    report("y", y, ref_y);
190    report("out", out, ref_out);
191    const double eo = rel_l2(out, ref_out);
192    std::printf("RESULT: %s (combine relL2 %.3f%%)\n", eo < 0.03 ? "ok" : "TOO FAR", 100 * eo);
193
194    for (void* p : {(void*) dx, dxq, (void*) dD, (void*) dU, (void*) dXl, dxlq, (void*) dA, (void*) dPtr,
195                    (void*) dStart, (void*) dN, (void*) dDst, (void*) dTok, (void*) dYl, (void*) dY,
196                    (void*) dUIn, (void*) dUOut, dUq, dscr})
197        cudaFree(p);
198    return eo < 0.03 ? 0 : 1;
199}