okami.mom/strata

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

Niko1221Trial2 merge f-0291-pr-amd (82eaeb422): verify.cpp head keeps both: pr-nv2's chunked head (h0/HT, up to 8 columns a launch) and pr-amd's fused q8_1 image (q8_head, image at the chunk's own xq_ offset)62db0bf10

main
12.6 KiB282 linesraw
1// src/kernels/verify_parity.cpp - batched / split verify-window kernels against the kernels they replace, BITWISE.
2//
3// A verify window's token t must come out bit for bit as it would in a window of any other size (the drafts are
4// accepted exactly when greedy decode would have produced them), so every kernel here is checked against the
5// one it stands in for, on random inputs that include -0.0, denormals, NaN, -inf and large values.  The tests
6// follow eddoursul's fork (MIT; verify_parity.cpp), ported to this tree's kernels.
7#include "strata/kernels/elementwise.hpp"
8#include "strata/kernels/f16_bits.hpp"
9#include "strata/kernels/quantize_act.hpp"
10#include "strata/kernels/sampler.hpp"
11#include "strata/kernels/verify_kernels.hpp"
12
13#include <cuda_runtime.h>
14
15#include <algorithm>
16#include <cmath>
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20#include <random>
21#include <string>
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
33template <typename T> T* dev(size_t n) {
34    T* p = nullptr;
35    check(cudaMalloc(&p, n * sizeof(T)), "cudaMalloc");
36    return p;
37}
38template <typename T> void up(T* d, const std::vector<T>& h) {
39    check(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");
40}
41template <typename T> std::vector<T> down(const T* d, size_t n) {
42    std::vector<T> h(n);
43    check(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "download");
44    return h;
45}
46
47// argmax_rows against sample_tokens' greedy pick and row_top_prob_split against row_top_prob, bitwise: rows of both
48// vocabularies with ties at the maximum (the lowest index wins), NaN, -inf, a row with no value above -inf, and
49// launches repeated on one scratch (each must leave its counters at zero)
50int test_argmax(std::mt19937& rng, cudaStream_t s) {
51    using namespace strata::kernels;
52    int bad = 0;
53    std::normal_distribution<float> nd(0.0f, 4.0f);
54    uint8_t* sa = dev<uint8_t>(argmax_rows_scratch_bytes(8));   // one scratch for every row count, as in the engine
55    uint8_t* st = dev<uint8_t>(row_top_prob_scratch_bytes(8));
56    check(cudaMemset(sa, 0, argmax_rows_scratch_bytes(8)), "memset");
57    check(cudaMemset(st, 0, row_top_prob_scratch_bytes(8)), "memset");
58    for (const int n : {248320, 40525, 4097, 33}) {
59        for (const int rows : {4, 8, 1, 3, 8, 2}) {
60            std::vector<float> h((size_t) rows * n);
61            for (float& v : h) v = nd(rng);
62            for (int r = 0; r < rows; ++r) {
63                float* row = h.data() + (size_t) r * n;
64                const int a = (int) (rng() % n), b = (int) (rng() % n);
65                row[a] = row[b] = 40.0f;                       // a tie at the maximum
66                row[(int) (rng() % n)] = std::nanf("");        // never picked
67                row[(int) (rng() % n)] = -INFINITY;
68                if (r == 2)                                    // no value above -inf: 0
69                    for (int i = 0; i < n; ++i) row[i] = i % 7 ? -INFINITY : std::nanf("");
70            }
71            float* d_l = dev<float>(h.size());
72            up(d_l, h);
73            int* d_ref = dev<int>(rows);
74            int32_t* d_out = dev<int32_t>(rows);
75            float* d_p1 = dev<float>(rows);
76            float* d_p2 = dev<float>(rows);
77            SamplerParams sp;
78            sp.greedy = true;
79            sp.temperature = 0.0f;
80            sample_tokens(d_l, rows, n, nullptr, 0, sp, d_ref, s);
81            row_top_prob(d_l, rows, n, d_ref, d_p1, s);
82            for (int rep = 0; rep < 3; ++rep) {
83                argmax_rows(d_l, rows, n, sa, d_out, s);
84                row_top_prob_split(d_l, rows, n, d_out, d_p2, st, s);
85                check(cudaStreamSynchronize(s), "argmax");
86                const std::vector<int> ref = down(d_ref, rows);
87                const std::vector<int32_t> out = down(d_out, rows);
88                const std::vector<float> p1 = down(d_p1, rows), p2 = down(d_p2, rows);
89                for (int r = 0; r < rows; ++r)
90                    if (ref[r] != out[r] || std::memcmp(&p1[r], &p2[r], 4) != 0) {
91                        if (bad < 5)
92                            std::printf("  argmax n %d rows %d row %d: %d / %d, p %.9g / %.9g\n", n, rows, r, ref[r],
93                                        out[r], p1[r], p2[r]);
94                        ++bad;
95                    }
96            }
97            (void) cudaFree(d_l); (void) cudaFree(d_ref); (void) cudaFree(d_out); (void) cudaFree(d_p1); (void) cudaFree(d_p2);
98        }
99    }
100    (void) cudaFree(sa);
101    (void) cudaFree(st);
102    std::printf("argmax_rows, row_top_prob_split: %s\n",
103                bad ? "MISMATCH" : "bitwise equal to the one-block kernels (ties, NaN, -inf, 1-8 rows on one scratch)");
104    return bad;
105}
106
107int test_mapped_multi(std::mt19937& rng, cudaStream_t s) {
108    using namespace strata::kernels;
109    int bad = 0;
110    // 7-copy round layout + non-multiple-of-4 large copy (1025 words) + 4B-aligned non-16B-aligned large copy (1028 words)
111    const int64_t words[7] = {5, 40, 1025, 1028, 51200, 4, 16};
112    const int64_t off[7]   = {0,  0,    0,    1,     0, 0,  0};   // entry 3 is +1 word (+4 B) offset -> 4B-aligned, not 16B
113    int32_t* h_src[7] = {};
114    int32_t* d_src[7] = {};
115    int32_t* d_ref[7] = {};
116    int32_t* d_out[7] = {};
117    MappedCopy mc[7] = {};
118    for (int i = 0; i < 7; ++i) {
119        const size_t alloc_w = (size_t) (words[i] + off[i]);
120        check(cudaHostAlloc((void**) &h_src[i], alloc_w * 4, cudaHostAllocMapped), "cudaHostAlloc");
121        check(cudaHostGetDevicePointer((void**) &d_src[i], h_src[i], 0), "cudaHostGetDevicePointer");
122        for (size_t j = 0; j < alloc_w; ++j) h_src[i][j] = (int32_t) rng();
123        d_ref[i] = dev<int32_t>(alloc_w);
124        d_out[i] = dev<int32_t>(alloc_w);
125        check(cudaMemset(d_ref[i], 0, alloc_w * 4), "memset");
126        if (words[i] > 1024 && (words[i] & 3) == 0 && off[i] == 0)
127            copy_from_mapped((float*) (d_ref[i] + off[i]), (const float*) (d_src[i] + off[i]), words[i], s);
128        else
129            copy_i32_from_mapped(d_ref[i] + off[i], d_src[i] + off[i], words[i], s);
130        mc[i] = {d_out[i] + off[i], d_src[i] + off[i], words[i]};
131    }
132    const char* prev = std::getenv("STRATA_MTP_MULTI_COPY");
133    const std::string saved = prev ? prev : "";
134    for (const char* mode : {"1", "0"}) {
135#if defined(_WIN32)
136        _putenv_s("STRATA_MTP_MULTI_COPY", mode);
137#else
138        setenv("STRATA_MTP_MULTI_COPY", mode, 1);
139#endif
140        for (int i = 0; i < 7; ++i) check(cudaMemsetAsync(d_out[i], 0x5a, (size_t) (words[i] + off[i]) * 4, s), "poison");
141        copy_from_mapped_multi(mc, 7, s);
142        check(cudaStreamSynchronize(s), "mapped_multi");
143        for (int i = 0; i < 7; ++i) {
144            const std::vector<int32_t> r = down(d_ref[i] + off[i], (size_t) words[i]);
145            const std::vector<int32_t> o = down(d_out[i] + off[i], (size_t) words[i]);
146            if (r != o) ++bad;
147        }
148    }
149#if defined(_WIN32)
150    _putenv_s("STRATA_MTP_MULTI_COPY", prev ? saved.c_str() : "");
151#else
152    if (prev) setenv("STRATA_MTP_MULTI_COPY", saved.c_str(), 1);
153    else unsetenv("STRATA_MTP_MULTI_COPY");
154#endif
155    for (int i = 0; i < 7; ++i) {
156        (void) cudaFreeHost(h_src[i]);
157        (void) cudaFree(d_ref[i]);
158        (void) cudaFree(d_out[i]);
159    }
160    std::printf("copy_from_mapped_multi: %s\n",
161                bad ? "MISMATCH" : "bitwise equal to individual mapped copies (multi=1 and fallback=0, aligned + 1025w + 4B-aligned)");
162    return bad;
163}
164
165int test_quantize_q8_0_scaled(std::mt19937& rng, cudaStream_t s) {
166    using namespace strata::kernels;
167    int bad = 0;
168    std::normal_distribution<float> nd(0.0f, 3.0f);
169    for (const int64_t n : {2560, 10240, 25600}) {
170        const int64_t nb = n / 32;
171        std::vector<float> hx((size_t) n);
172        for (int64_t i = 0; i < n; ++i) hx[(size_t) i] = nd(rng);
173        for (int64_t j = 0; j < 32 && j < n; ++j) hx[(size_t) j] = 0.0f;   // all-zero block
174        if (nb > 2) {
175            hx[64] = 127.0f;
176            for (int j = 1; j < 32; ++j) hx[64 + j] = (float) j - 0.5f;    // exact .5 half-away ties
177        }
178        float* d_x = dev<float>((size_t) n);
179        uint8_t* d_b = dev<uint8_t>((size_t) nb * 34);
180        float* d_s = dev<float>((size_t) nb);
181        up(d_x, hx);
182        quantize_q8_0_scaled(d_x, d_b, d_s, n, s);
183        check(cudaStreamSynchronize(s), "q8_0_scaled");
184        const std::vector<uint8_t> gb = down(d_b, (size_t) nb * 34);
185        const std::vector<float> gs = down(d_s, (size_t) nb);
186        for (int64_t b = 0; b < nb; ++b) {
187            const float* xb = hx.data() + b * 32;
188            float amax = 0.0f;
189            for (int i = 0; i < 32; ++i) amax = std::fmax(amax, std::fabs(xb[i]));
190            const float sc = amax > 0.f ? amax / 127.f : 0.f;
191            const float inv = sc > 0.f ? 1.f / sc : 0.f;
192            if (std::memcmp(&gs[(size_t) b], &sc, 4) != 0) ++bad;
193            const uint16_t d16 = f16_from_f32(sc);
194            const uint8_t* ob = gb.data() + b * 34;
195            if (ob[0] != (uint8_t) (d16 & 0xFF) || ob[1] != (uint8_t) (d16 >> 8)) ++bad;
196            for (int i = 0; i < 32; ++i) {
197                const float t = xb[i] * inv;
198                const float r = t + (t >= 0.f ? 0.5f : -0.5f);
199                int v = (int) r;
200                v = v < -127 ? -127 : (v > 127 ? 127 : v);
201                if (ob[2 + i] != (uint8_t) (int8_t) v) ++bad;
202            }
203        }
204        (void) cudaFree(d_x);
205        (void) cudaFree(d_b);
206        (void) cudaFree(d_s);
207    }
208    std::printf("quantize_q8_0_scaled: %s\n", bad ? "MISMATCH" : "bitwise equal to CPU act_quant_q8_1 reference (zero, .5 ties, normal)");
209    return bad;
210}
211
212void bench_head_ops(cudaStream_t s) {
213    using namespace strata::kernels;
214    uint8_t* sa = dev<uint8_t>(argmax_rows_scratch_bytes(8));
215    uint8_t* st = dev<uint8_t>(row_top_prob_scratch_bytes(8));
216    check(cudaMemset(sa, 0, argmax_rows_scratch_bytes(8)), "memset");
217    check(cudaMemset(st, 0, row_top_prob_scratch_bytes(8)), "memset");
218    cudaEvent_t e0, e1;
219    check(cudaEventCreate(&e0), "ev");
220    check(cudaEventCreate(&e1), "ev");
221    constexpr int ITERS = 200;
222    auto time_fn = [&](auto&& fn) {
223        for (int i = 0; i < 20; ++i) fn();
224        check(cudaStreamSynchronize(s), "warm");
225        check(cudaEventRecord(e0, s), "e0");
226        for (int i = 0; i < ITERS; ++i) fn();
227        check(cudaEventRecord(e1, s), "e1");
228        check(cudaEventSynchronize(e1), "sync");
229        float ms = 0.0f;
230        check(cudaEventElapsedTime(&ms, e0, e1), "elapsed");
231        return ms * 1000.0 / ITERS;
232    };
233    for (const int n : {106299, 248320}) {
234        for (const int rows : {1, 4, 5}) {
235            if (n == 106299 && rows > 1) continue;
236            std::vector<float> h((size_t) rows * n, 0.1f);
237            for (int r = 0; r < rows; ++r) h[(size_t) r * n + (r * 1337 + 42) % n] = 10.0f;
238            float* d_l = dev<float>(h.size());
239            up(d_l, h);
240            int32_t* d_out = dev<int32_t>(rows);
241            float* d_p = dev<float>(rows);
242            SamplerParams sp;
243            sp.greedy = true;
244            sp.temperature = 0.0f;
245            const double us_g1 = time_fn([&] { sample_tokens(d_l, rows, n, nullptr, 0, sp, d_out, s); });
246            const double us_gm = time_fn([&] { argmax_rows(d_l, rows, n, sa, d_out, s); });
247            const double us_p1 = time_fn([&] { row_top_prob(d_l, rows, n, d_out, d_p, s); });
248            const double us_pm = time_fn([&] { row_top_prob_split(d_l, rows, n, d_out, d_p, st, s); });
249            std::printf("  V=%6d rows=%d: greedy 1-blk %6.2f us -> argmax_rows %6.2f us (x%.2f) | top_prob 1-blk %6.2f us -> split %6.2f us (x%.2f)\n",
250                        n, rows, us_g1, us_gm, us_g1 / us_gm, us_p1, us_pm, us_p1 / us_pm);
251            (void) cudaFree(d_l); (void) cudaFree(d_out); (void) cudaFree(d_p);
252        }
253    }
254    (void) cudaEventDestroy(e0);
255    (void) cudaEventDestroy(e1);
256    (void) cudaFree(sa);
257    (void) cudaFree(st);
258}
259
260}  // namespace
261
262int main(int argc, char** argv) {
263    bool do_bench = false;
264    for (int i = 1; i < argc; ++i) {
265        if (std::string(argv[i]) == "--bench") do_bench = true;
266        else if (std::string(argv[i]) != "--selftest") {
267            std::fprintf(stderr, "usage: verify_parity [--selftest] [--bench]\n");
268            return 2;
269        }
270    }
271    std::mt19937 rng(20260925);
272    cudaStream_t s = nullptr;
273    check(cudaStreamCreate(&s), "stream");
274    int bad = 0;
275    bad += test_argmax(rng, s);
276    bad += test_mapped_multi(rng, s);
277    bad += test_quantize_q8_0_scaled(rng, s);
278    if (do_bench && bad == 0) bench_head_ops(s);
279    (void) cudaStreamDestroy(s);
280    std::printf("verify_parity: %s\n", bad ? "FAIL" : "PASS");
281    return bad ? 1 : 0;
282}