okami.mom/strata

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

Niko1221Merge branch 'f-139b-arc' into f-139-relad33b8074

main
9.5 KiB191 linesraw
1// src/kernels/bf16_gemv_parity.cpp - P2.S5's test for the BF16 GEMV.
2//
3// THREE THINGS ARE CHECKED, and the third is the one the engine's correctness rests on:
4//
5//   1. both kernels against a host reference that reads the SAME bf16 bits - so what is under test is the
6//      reduction, not the conversion, and the tolerance is set by summation order and nothing else;
7//   2. the naive and the split kernel agree with each other, because the naive one is the reference the
8//      split one exists to be checked against and a disagreement there means one of them is wrong;
9//   3. **THE ACTIVATION CONTRACT IS OBSERVABLE.**  A BF16 weight sees a BF16 activation; feeding it fp16 or
10//      f32 instead is a 2^-9 = 1.95e-03 relative change, which is above any 1e-3 tolerance.  An fp16
11//      activation is the rival reading, computed and required to differ, because it is what the engine did
12//      before `docs/activation-contract.md` settled the question and it produces perfectly plausible output.
13#define DPCT_PROFILING_ENABLED
14#include <sycl/sycl.hpp>
15#include <dpct/dpct.hpp>
16#include "strata/kernels/bf16_bits.hpp"
17#include "strata/kernels/bf16_gemv.hpp"
18#include "strata/kernels/f16_bits.hpp"
19
20#include <cmath>
21#include <cstdio>
22#include <cstdlib>
23#include <random>
24#include <string>
25#include <vector>
26
27namespace {
28
29using strata::kernels::bf16_from_f32;
30using strata::kernels::f32_from_bf16;
31
32void check(dpct::err0 e, const char *what) {
33}
34
35double rel_l1(const std::vector<float>& a, const std::vector<float>& b) {
36    double d = 0, m = 0;
37    for (size_t i = 0; i < a.size(); ++i) {
38        d += std::fabs((double) a[i] - (double) b[i]);
39        m += std::fabs((double) a[i]);
40    }
41    return d / (m > 1e-30 ? m : 1e-30);
42}
43
44/// The host reference, in DOUBLE, over the same bf16 bits.
45void reference(const std::vector<uint16_t>& x, const std::vector<uint16_t>& w, long long n_in, long long n_out,
46               std::vector<float>& y) {
47    y.assign((size_t) n_out, 0.0f);
48    for (long long o = 0; o < n_out; ++o) {
49        double acc = 0;
50        for (long long i = 0; i < n_in; ++i)
51            acc += (double) f32_from_bf16(x[(size_t) i]) * (double) f32_from_bf16(w[(size_t) (o * n_in + i)]);
52        y[(size_t) o] = (float) acc;
53    }
54}
55
56}  // namespace
57
58int main(int argc, char** argv) {
59    bool selftest = false;
60    for (int i = 1; i < argc; ++i) {
61        if (std::string(argv[i]) == "--selftest") selftest = true;
62        else { std::fprintf(stderr, "usage: bf16_gemv_parity [--selftest]\n"); return 2; }
63    }
64    int bad = 0;
65
66    // THE REAL SHAPES, because a kernel that only works on a square toy is not a kernel this engine can use.
67    // `ssm_alpha` is [2560, 48] - a wide reduction and 48 outputs - and `indexer.k_proj` is [2560, 128].
68    struct Shape { long long n_in, n_out; const char* what; };
69    const Shape shapes[] = {
70        {2560, 48, "ssm_alpha.weight  [2560, 48]"},
71        {2560, 128, "indexer.k_proj   [2560, 128]"},
72        {2560, 512, "indexer.q_proj   [2560, 512]"},
73        {2560, 2560, "ple_value        [2560, 2560]"},
74    };
75
76    for (const Shape& s : shapes) {
77        std::mt19937 rng(4242);
78        std::normal_distribution<float> g(0.0f, 1.0f);
79        std::vector<float> fx((size_t) s.n_in), fw((size_t) (s.n_in * s.n_out));
80        for (auto& v : fx) v = g(rng);
81        // a realistic weight scale: these are projections, not embeddings
82        for (auto& v : fw) v = g(rng) * 0.05f;
83
84        // THE ACTIVATION IS ROUNDED TO BF16 FIRST, which is the contract, and the WEIGHT is already bf16 in
85        // the pack - the loaded bytes ARE the high 16 bits of an f32.
86        std::vector<uint16_t> x((size_t) s.n_in), w((size_t) (s.n_in * s.n_out));
87        for (size_t i = 0; i < fx.size(); ++i) x[i] = bf16_from_f32(fx[i]);
88        for (size_t i = 0; i < fw.size(); ++i) w[i] = bf16_from_f32(fw[i]);
89
90        std::vector<float> want;
91        reference(x, w, s.n_in, s.n_out, want);
92
93        uint16_t *d_x = nullptr, *d_w = nullptr;
94        float *d_y = nullptr;
95        check(DPCT_CHECK_ERROR(d_x = (uint16_t *)sycl::malloc_device(
96                                   x.size() * 2, dpct::get_in_order_queue())),
97              "x");
98        check(DPCT_CHECK_ERROR(d_w = (uint16_t *)sycl::malloc_device(
99                                   w.size() * 2, dpct::get_in_order_queue())),
100              "w");
101        check(DPCT_CHECK_ERROR(
102                  d_y = (float *)sycl::malloc_device(
103                      (size_t)s.n_out * 4, dpct::get_in_order_queue())),
104              "y");
105        /*
106        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
107        assuming in the original code the source host memory is pageable memory.
108        If the memory is not pageable, call wait() on event return by memcpy API
109        to ensure synchronization behavior.
110        */
111        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_x, x.data(),
112                                                                 x.size() * 2).wait()),
113              "cx");
114        /*
115        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
116        assuming in the original code the source host memory is pageable memory.
117        If the memory is not pageable, call wait() on event return by memcpy API
118        to ensure synchronization behavior.
119        */
120        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_w, w.data(),
121                                                                 w.size() * 2).wait()),
122              "cw");
123
124        std::vector<float> naive((size_t) s.n_out), warp((size_t) s.n_out), split((size_t) s.n_out);
125        strata::kernels::bf16_gemv(d_x, d_w, d_y, s.n_in, s.n_out, nullptr);
126        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
127                                   .memcpy(naive.data(), d_y, naive.size() * 4)
128                                   .wait()),
129              "cy1");
130        strata::kernels::bf16_gemv_split(d_x, d_w, d_y, s.n_in, s.n_out, 32, nullptr);
131        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
132                                   .memcpy(warp.data(), d_y, warp.size() * 4)
133                                   .wait()),
134              "cy2");
135        strata::kernels::bf16_gemv_split(d_x, d_w, d_y, s.n_in, s.n_out, 256, nullptr);
136        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
137                                   .memcpy(split.data(), d_y, split.size() * 4)
138                                   .wait()),
139              "cy3");
140
141        const double rn = rel_l1(want, naive), rw = rel_l1(want, warp), rs = rel_l1(want, split);
142        std::printf("  %-34s naive %.2e  warp %.2e  split256 %.2e\n", s.what, rn, rw, rs);
143        // The products are EXACT - both sides are bf16-valued, so f32 represents each product exactly - and
144        // the only difference is the order the 2560 terms are added.  A tight bound is therefore meaningful.
145        if (!(rn <= 1e-5 && rw <= 1e-5 && rs <= 1e-5)) { std::printf("    *** over 1e-5 ***\n"); ++bad; }
146
147        // ---- 3. THE ACTIVATION CONTRACT.  The rival: an fp16 activation instead of bf16, which is what the
148        // engine did before the contract was settled.  It must be observable, or check 1 above would pass
149        // against either and the contract would be untested.
150        {
151            std::vector<float> fp16_as_f32((size_t) s.n_in);
152            std::vector<uint16_t> x16((size_t) s.n_in);
153            for (size_t i = 0; i < fx.size(); ++i) {
154                x16[i] = strata::kernels::f16_from_f32(fx[i]);
155                fp16_as_f32[i] = strata::kernels::f32_from_f16(x16[i]);
156            }
157            // Round the fp16 value to bf16 - i.e. give the kernel a bf16 activation whose VALUES came through
158            // fp16.  That is the whole difference between the two contracts at this call site.
159            for (size_t i = 0; i < fp16_as_f32.size(); ++i) x[i] = bf16_from_f32(fp16_as_f32[i]);
160            /*
161            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
162            assuming in the original code the source host memory is pageable
163            memory. If the memory is not pageable, call wait() on event return
164            by memcpy API to ensure synchronization behavior.
165            */
166            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
167                      d_x, x.data(), x.size() * 2).wait()),
168                  "cx2");
169            std::vector<float> rival((size_t) s.n_out);
170            strata::kernels::bf16_gemv(d_x, d_w, d_y, s.n_in, s.n_out, nullptr);
171            check(DPCT_CHECK_ERROR(
172                      (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
173                          .memcpy(rival.data(), d_y, rival.size() * 4)
174                          .wait()),
175                  "cy4");
176            const double r = rel_l1(want, rival);
177            const bool visible = r > 1e-4;
178            std::printf("      %-30s %s (%.4f%% apart)\n", "bf16 vs fp16 activation",
179                        visible ? "yes" : "*** NO ***", r * 100);
180            if (!visible) ++bad;
181        }
182        sycl::free(d_x, dpct::get_in_order_queue());
183            sycl::free(d_w, dpct::get_in_order_queue());
184            sycl::free(d_y, dpct::get_in_order_queue());
185    }
186
187    std::printf("\nbf16_gemv: %d failures\n", bad);
188    if (bad) return 1;
189    if (selftest) std::printf("bf16_gemv_parity OK\n");
190    return 0;
191}