okami.mom/strata

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

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

main
12.6 KiB230 linesraw
1// src/kernels/latent_u_check.cpp - parity: latent_u_grouped (GPU) vs the engine's per-route U.
2//
3// Part 1 (existing): latent_u_grouped vs iq_mmvq(8) per-route reference, worst relL2.
4// Part 2 (new, knife-0): the SAME Q8_1 activation feeds BOTH the CPU kernel (lat_q8_0_q8_1_rows,
5// the current mode-7 path) and the GPU kernel (latent_u_grouped, the new path).  Both use the same
6// U weight (latent_dense_q8.bin, layer 0), so the delta is accumulation-order only.  Multi-seed +
7// multi-group: reports max/mean/p99 of the per-row delta and per-route relL2 (the quality-gate basis).
8#include "strata/core/latent_dense.hpp"
9#include "strata/kernels/iq_kernels.hpp"
10#include "strata/kernels/latent.hpp"
11#include "strata/kernels/cpu/kq_avx2.hpp"
12#include "strata/kernels/f16_bits.hpp"
13
14#include <cuda_runtime.h>
15
16#include <algorithm>
17#include <cinttypes>
18#include <cmath>
19#include <cstdio>
20#include <cstdlib>
21#include <cstring>
22#include <string>
23#include <vector>
24
25// scalar replica of expert_source.cpp:4861 lat_quant_q8_1 (per 32: d(f16), s(f16), qs[32])
26static void lat_quant_q8_1_scalar(const float* x, int n, uint8_t* o) {
27    const int nb = n / 32;
28    for (int b = 0; b < nb; ++b) {
29        const float* xb = x + b * 32;
30        uint8_t* ob = o + b * 36;
31        float amax = 0.0f, sum = 0.0f;
32        for (int j = 0; j < 32; ++j) { const float v = xb[j]; amax = std::fmax(amax, std::fabs(v)); sum += v; }
33        const float d32 = amax / 127.0f;
34        const float d = std::fabs(d32) > 65504.0f ? std::copysign(65504.0f, d32) : d32;
35        const uint16_t dh = strata::kernels::f16_from_f32(d);
36        const uint16_t sh = strata::kernels::f16_from_f32(sum);
37        ob[0] = (uint8_t)(dh & 0xFFu); ob[1] = (uint8_t)(dh >> 8);
38        ob[2] = (uint8_t)(sh & 0xFFu); ob[3] = (uint8_t)(sh >> 8);
39        int8_t* q = (int8_t*)(ob + 4);
40        for (int j = 0; j < 32; ++j) {
41            float v = amax == 0.0f ? 0.0f : std::roundf(xb[j] / d);
42            v = v > 127.0f ? 127.0f : (v < -127.0f ? -127.0f : v);
43            q[j] = (int8_t) v;
44        }
45    }
46}
47
48int main() {
49    const int G = 8, E = 512, cap = 10, ELL = 1792, H = 2560;
50    size_t urow = (size_t) (ELL / 32) * 34;   // Q4DU: overwritten from the pack below
51    const size_t xlq_row = (size_t) (ELL / 32) * 36;
52    
53    const char* dense_path = std::getenv("STRATA_LATENT_DENSE");
54    const char* labels_path = std::getenv("STRATA_LATENT_LABELS");
55    if (dense_path == nullptr || dense_path[0] == 0 || labels_path == nullptr || labels_path[0] == 0) {
56        std::fprintf(stderr, "usage: STRATA_LATENT_DENSE=<latent_dense_q8.bin> STRATA_LATENT_LABELS=<labels.bin> latent_u_check\n");
57        return 2;
58    }
59    strata::core::LatentDense dense;
60    std::string err;
61    if (!dense.open(dense_path, 48, G, H, ELL, err)) { std::fprintf(stderr, "dense: %s\n", err.c_str()); return 2; }
62    urow = dense.u_row_bytes();   // Q4DU: 34 (Q8_0) or 18 (Q4_0) per block, from the pack
63    const int fmt = dense.fmt();
64    std::fprintf(stderr, "latent_u_check: fmt=%d urow=%zu\n", fmt, urow);
65    if (dense.u_bytes() != (size_t) G * H * urow) { std::fprintf(stderr, "u_bytes %zu != %zu\n", dense.u_bytes(), (size_t) G * H * urow); return 2; }
66    std::vector<int32_t> labels((size_t) 48 * E);
67    {
68        std::FILE* f = std::fopen(labels_path, "rb");
69        if (f == nullptr) { std::perror("labels"); return 2; }
70        const size_t got = std::fread(labels.data(), 4, labels.size(), f);
71        std::fclose(f);
72        if (got != labels.size()) { std::fprintf(stderr, "labels short\n"); return 2; }
73    }
74
75    // device allocs (shared by both parts)
76    float *out_k = nullptr, *out_ref = nullptr, *yl_d = nullptr;
77    uint8_t *u_d = nullptr, *ylq = nullptr, *uq = nullptr, *hq_d = nullptr;
78    int32_t *ids_d = nullptr, *labels_d = nullptr;
79    float *out_cpu = nullptr, *out_gpu = nullptr;
80    const auto chk = [&](const char* what, cudaError_t e) {
81        if (e == cudaSuccess) return true;
82        std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
83        return false;
84    };
85    // Q4DU-fix: HARD-FAIL semantics.  A kernel launch or stream error (e.g. an illegal address
86    // left in the stream by a wrong row width) must abort with a clear message - never keep
87    // computing and print a misleading relL2 (the "false green" failure mode).
88    const auto gpu_check = [&](const char* what) {
89        const cudaError_t e = cudaGetLastError();
90        if (e != cudaSuccess) {
91            std::fprintf(stderr, "latent_u_check: FATAL %s: %s\n", what, cudaGetErrorString(e));
92            std::exit(1);
93        }
94    };
95    // Q4DU-fix: the outputs must not be all-zero or NaN (a dead stream produces zeros).
96    const auto out_guard = [&](const char* what, const float* v, size_t n) {
97        bool all_zero = true;
98        for (size_t i = 0; i < n; ++i) {
99            if (!std::isfinite(v[i])) { std::fprintf(stderr, "latent_u_check: FATAL %s: NaN/Inf at %zu\n", what, i); std::exit(1); }
100            if (v[i] != 0.0f) all_zero = false;
101        }
102        if (all_zero) { std::fprintf(stderr, "latent_u_check: FATAL %s: all-zero output (dead stream?)\n", what); std::exit(1); }
103    };
104    bool ok = chk("malloc u", cudaMalloc((void**) &u_d, (size_t) G * H * urow)) &&
105              chk("malloc yl", cudaMalloc((void**) &yl_d, (size_t) cap * ELL * 4)) &&
106              chk("malloc ylq", cudaMalloc((void**) &ylq, (size_t) cap * xlq_row)) &&
107              chk("malloc uq", cudaMalloc((void**) &uq, xlq_row)) &&
108              chk("malloc hq", cudaMalloc((void**) &hq_d, (size_t) cap * xlq_row)) &&
109              chk("malloc out_k", cudaMalloc((void**) &out_k, (size_t) cap * H * 4)) &&
110              chk("malloc out_ref", cudaMalloc((void**) &out_ref, (size_t) cap * H * 4)) &&
111              chk("malloc out_gpu", cudaMalloc((void**) &out_gpu, (size_t) cap * H * 4)) &&
112              chk("malloc ids", cudaMalloc((void**) &ids_d, (size_t) cap * 4)) &&
113              chk("malloc labels", cudaMalloc((void**) &labels_d, (size_t) 48 * E * 4));
114    if (!ok) return 2;
115    cudaMemcpy(u_d, dense.u(0), (size_t) G * H * urow, cudaMemcpyHostToDevice);
116    cudaMemcpy(labels_d, labels.data(), (size_t) 48 * E * 4, cudaMemcpyHostToDevice);
117
118    cudaStream_t cs = nullptr;
119    cudaStreamCreate(&cs);
120
121    const uint8_t* u_host = dense.u(0);
122
123    // ---- Part 1 (existing): GPU latent_u_grouped vs iq_mmvq(8) reference ----
124    {
125        std::vector<float> h_yl((size_t) cap * ELL);
126        std::vector<int32_t> h_ids(cap);
127        uint32_t s = 1;
128        auto rnd = [&s]() { s = s * 1664525u + 1013904223u; return s; };
129        for (float& v : h_yl) v = ((int) (rnd() % 2001) - 1000) / 1000.0f;
130        for (int r = 0; r < cap; ++r) h_ids[(size_t) r] = (int) (rnd() % 512);
131
132        cudaMemcpy(yl_d, h_yl.data(), (size_t) cap * ELL * 4, cudaMemcpyHostToDevice);
133        cudaMemcpy(ids_d, h_ids.data(), (size_t) cap * 4, cudaMemcpyHostToDevice);
134
135        strata::kernels::quantize_q8_1_rows(yl_d, cap, ELL, ylq, cs);
136        strata::kernels::latent_u_grouped(u_d, ylq, ids_d, labels_d, E, cap, ELL, H, out_k, cs, fmt);   // Q4DU
137        gpu_check("part1 grouped launch");
138        for (int r = 0; r < cap; ++r) {
139            const int g = labels[(size_t) h_ids[(size_t) r]];
140            cudaMemcpyAsync(uq, ylq + (size_t) r * xlq_row, xlq_row, cudaMemcpyDeviceToDevice, cs);
141            strata::kernels::iq_mmvq(strata::kernels::lat_dense_fmt_to_type(fmt), u_d + (size_t) g * (size_t) H * urow, uq, out_ref + (size_t) r * H, ELL, H, 1, cs);   // Q4DU
142        }
143        const cudaError_t se1 = cudaStreamSynchronize(cs);
144        if (se1 != cudaSuccess) { std::fprintf(stderr, "latent_u_check: FATAL part1 sync: %s\n", cudaGetErrorString(se1)); std::exit(1); }
145        std::vector<float> h_k((size_t) cap * H), h_r((size_t) cap * H);
146        cudaMemcpy(h_k.data(), out_k, (size_t) cap * H * 4, cudaMemcpyDeviceToHost);
147        cudaMemcpy(h_r.data(), out_ref, (size_t) cap * H * 4, cudaMemcpyDeviceToHost);
148        out_guard("part1 grouped output", h_k.data(), h_k.size());
149        out_guard("part1 mmvq reference", h_r.data(), h_r.size());
150        double worst = 0;
151        for (int r = 0; r < cap; ++r) {
152            double num = 0, den = 0;
153            for (int h = 0; h < H; ++h) {
154                const double d = (double) h_k[(size_t) r * H + h] - h_r[(size_t) r * H + h];
155                num += d * d; den += (double) h_r[(size_t) r * H + h] * h_r[(size_t) r * H + h];
156            }
157            worst = std::max(worst, std::sqrt(num / std::max(den, 1e-30)));
158        }
159        std::fprintf(stderr, "part1 GPU-vs-iq_mmvq worst relL2 = %g\n", worst);
160    }
161
162    // ---- Part 2 (new, knife-0): CPU lat_q8_0_q8_1_rows vs GPU latent_u_grouped, same hq, multi-seed ----
163    {
164        const int n_seeds = 3;
165        std::vector<double> row_delta;      // |cpu - gpu| per output row
166        std::vector<double> route_rel;      // per-route relL2
167        for (int seed = 0; seed < n_seeds; ++seed) {
168            std::vector<float> h_yl((size_t) cap * ELL);
169            std::vector<int32_t> h_ids(cap);
170            uint32_t s = (uint32_t) (0x9e3779b9u ^ ((uint32_t) seed * 0x1000003u));
171            auto rnd = [&s]() { s = s * 1664525u + 1013904223u; return s; };
172            for (float& v : h_yl) v = ((int) (rnd() % 2001) - 1000) / 1000.0f;
173            for (int r = 0; r < cap; ++r) h_ids[(size_t) r] = (int) (rnd() % 512);
174
175            // CPU hq quantization (the engine's lat_quant_q8_1 scalar replica)
176            std::vector<uint8_t> h_hq((size_t) cap * xlq_row);
177            for (int r = 0; r < cap; ++r)
178                lat_quant_q8_1_scalar(h_yl.data() + (size_t) r * ELL, ELL, h_hq.data() + (size_t) r * xlq_row);
179
180            // CPU path: per route, the group g = labels[ids[r]], U[g] . hq[r]
181            std::vector<float> h_cpu((size_t) cap * H);
182            for (int r = 0; r < cap; ++r) {
183                const int g = labels[(size_t) h_ids[(size_t) r]];
184                const void* act_arr[1] = { h_hq.data() + (size_t) r * xlq_row };
185                float* out_arr[1] = { h_cpu.data() + (size_t) r * H };
186                if (fmt == 4)
187                    strata::kernels::cpu::lat_q4_0_q8_1_rows(u_host + (size_t) g * (size_t) H * urow, urow, ELL,
188                                                             act_arr, 1, out_arr, 0, H);
189                else
190                    strata::kernels::cpu::lat_q8_0_q8_1_rows(u_host + (size_t) g * (size_t) H * urow, urow, ELL,
191                                                             act_arr, 1, out_arr, 0, H);
192            }
193
194            // GPU path: upload the SAME hq, latent_u_grouped
195            cudaMemcpy(hq_d, h_hq.data(), (size_t) cap * xlq_row, cudaMemcpyHostToDevice);
196            cudaMemcpy(ids_d, h_ids.data(), (size_t) cap * 4, cudaMemcpyHostToDevice);
197            strata::kernels::latent_u_grouped(u_d, hq_d, ids_d, labels_d, E, cap, ELL, H, out_gpu, cs, fmt);
198            gpu_check("part2 grouped launch");
199            const cudaError_t se2 = cudaStreamSynchronize(cs);
200            if (se2 != cudaSuccess) { std::fprintf(stderr, "latent_u_check: FATAL part2 sync: %s\n", cudaGetErrorString(se2)); std::exit(1); }
201            std::vector<float> h_gpu((size_t) cap * H);
202            cudaMemcpy(h_gpu.data(), out_gpu, (size_t) cap * H * 4, cudaMemcpyDeviceToHost);
203            out_guard("part2 gpu output", h_gpu.data(), h_gpu.size());
204            out_guard("part2 cpu output", h_cpu.data(), h_cpu.size());
205            for (int r = 0; r < cap; ++r) {
206                double num = 0, den = 0;
207                for (int h = 0; h < H; ++h) {
208                    const double d = (double) h_cpu[(size_t) r * H + h] - h_gpu[(size_t) r * H + h];
209                    row_delta.push_back(std::fabs(d));
210                    num += d * d; den += (double) h_gpu[(size_t) r * H + h] * h_gpu[(size_t) r * H + h];
211                }
212                route_rel.push_back(std::sqrt(num / std::max(den, 1e-30)));
213            }
214        }
215
216        std::sort(row_delta.begin(), row_delta.end());
217        std::sort(route_rel.begin(), route_rel.end());
218        const size_t nrow = row_delta.size(), nrel = route_rel.size();
219        double dsum = 0; for (double v : row_delta) dsum += v;
220        double rsum = 0; for (double v : route_rel) rsum += v;
221        std::fprintf(stderr, "part2 CPU-vs-GPU (seeds=%d, rows=%zu):\n", n_seeds, nrow);
222        std::fprintf(stderr, "  abs delta max %.3e mean %.3e p99 %.3e\n",
223                     row_delta.back(), dsum / (double) nrow, row_delta[(size_t) (0.99 * (nrow - 1))]);
224        std::fprintf(stderr, "  relL2   max %.3e mean %.3e p99 %.3e\n",
225                     route_rel.back(), rsum / (double) nrel, route_rel[(size_t) (0.99 * (nrel - 1))]);
226        const bool pass = route_rel.back() < 1e-4;
227        std::fprintf(stderr, "%s\n", pass ? "RESULT: ok" : "RESULT: FAIL");
228        return pass ? 0 : 1;
229    }
230}