okami.mom/strata

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

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

main
11.3 KiB236 linesraw
1// src/kernels/s2_gemv_q8_parity.cpp - the Q8_0-activation GEMV, and the size of the gap it closes.
2//
3// THREE CHECKS:
4//   1. The quantized-activation GEMV matches a host reference that quantizes the activation exactly as
5//      `ref/quant.py::q8_0` does and then dots it against the same weights.
6//   2. **The gap is REAL and MEASURABLE in this project's own kernels**: the same weights driven by an FP16
7//      activation and by a Q8_0 activation must DIFFER, by roughly the activation contract's ~1%.  Without this
8//      the first check would pass on a kernel that quietly used fp16 anyway, and the round-186 gap would look
9//      fixed without being fixed.
10//   3. The measured size of that difference is reported, so the number in the state file is one this test
11//      produces rather than one quoted from elsewhere.
12#define DPCT_PROFILING_ENABLED
13#include <sycl/sycl.hpp>
14#include <dpct/dpct.hpp>
15#include "strata/kernels/quantize_act.hpp"
16#include "strata/kernels/s_gemv.hpp"
17#include "strata/kernels/s2_gemv_q8.hpp"
18
19#include <cmath>
20#include <cstdio>
21#include <cstdlib>
22#include <cstring>
23#include <random>
24#include <vector>
25
26namespace {
27
28void check(dpct::err0 e, const char *what) {
29}
30
31}  // namespace
32
33int main(int argc, char** argv) {
34    bool selftest = false;
35    for (int i = 1; i < argc; ++i) {
36        if (std::string(argv[i]) == "--selftest") selftest = true;
37        else { std::fprintf(stderr, "usage: s2_gemv_q8_parity [--selftest]\n"); return 2; }
38    }
39
40    const long long n_in = 2560, n_out = 64;
41    const int tpr = 32;
42    std::mt19937 rng(31);
43    std::normal_distribution<float> gauss(0.0f, 1.0f);
44
45    std::vector<float> x((size_t) n_in);
46    for (auto& v : x) v = gauss(rng);
47    std::vector<uint8_t> codes((size_t) n_out * n_in / 4);
48    for (auto& v : codes) v = (uint8_t) (rng() & 0xFF);
49    std::vector<float> scales((size_t) n_out * (n_in / 64));
50    for (auto& v : scales) v = 0.001f + 0.0001f * (float) (rng() % 100);
51
52    // ---- device buffers
53    float* d_x = nullptr;
54    uint8_t* d_act = nullptr;
55    uint8_t* d_codes = nullptr;
56    float *d_scales = nullptr, *d_y_fp16 = nullptr, *d_y_q8 = nullptr;
57    check(DPCT_CHECK_ERROR(d_x = sycl::malloc_device<float>(
58                               (size_t)n_in, dpct::get_in_order_queue())),
59          "m x");
60    check(DPCT_CHECK_ERROR(
61              d_act = (uint8_t *)sycl::malloc_device(
62                  (size_t)(n_in / 32) * 34, dpct::get_in_order_queue())),
63          "m act");
64    check(DPCT_CHECK_ERROR(d_codes = (uint8_t *)sycl::malloc_device(
65                               codes.size(), dpct::get_in_order_queue())),
66          "m codes");
67    check(DPCT_CHECK_ERROR(d_scales = sycl::malloc_device<float>(
68                               scales.size(), dpct::get_in_order_queue())),
69          "m scales");
70    check(DPCT_CHECK_ERROR(d_y_fp16 = sycl::malloc_device<float>(
71                               (size_t)n_out, dpct::get_in_order_queue())),
72          "m y1");
73    check(DPCT_CHECK_ERROR(d_y_q8 = sycl::malloc_device<float>(
74                               (size_t)n_out, dpct::get_in_order_queue())),
75          "m y2");
76    /*
77    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
78    in the original code the source host memory is pageable memory. If the
79    memory is not pageable, call wait() on event return by memcpy API to ensure
80    synchronization behavior.
81    */
82    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
83              d_x, x.data(), x.size() * sizeof(float)).wait()),
84          "c x");
85    /*
86    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
87    in the original code the source host memory is pageable memory. If the
88    memory is not pageable, call wait() on event return by memcpy API to ensure
89    synchronization behavior.
90    */
91    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
92              d_codes, codes.data(), codes.size()).wait()),
93          "c codes");
94    /*
95    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
96    in the original code the source host memory is pageable memory. If the
97    memory is not pageable, call wait() on event return by memcpy API to ensure
98    synchronization behavior.
99    */
100    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
101              d_scales, scales.data(), scales.size() * sizeof(float)).wait()),
102          "c scales");
103
104    strata::kernels::quantize_q8_0(d_x, d_act, n_in, nullptr);
105
106    // ---- host reference: quantize the activation with the project's own rule, then dot
107    std::vector<uint8_t> h_act((size_t) (n_in / 32) * 34);
108    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
109                               .memcpy(h_act.data(), d_act, h_act.size())
110                               .wait()),
111          "c act back");
112    auto act_val = [&](long long i) {
113        const uint8_t* blk = &h_act[(size_t) (i / 32) * 34];
114        const uint16_t dbits = (uint16_t) (blk[0] | (blk[1] << 8));
115        // fp16 -> f32 without a CUDA header: 0x3C00 = 1.0, and the block scales here are normal
116        float d;
117        const uint32_t sign = (uint32_t) (dbits & 0x8000) << 16;
118        uint32_t ex = (dbits >> 10) & 0x1F, man = dbits & 0x3FF;
119        uint32_t out;
120        if (ex == 0) { out = sign; }
121        else { out = sign | ((ex - 15 + 127) << 23) | (man << 13); }
122        std::memcpy(&d, &out, 4);
123        return (float) ((int8_t) blk[2 + (i % 32)]) * d;
124    };
125    std::vector<float> ref((size_t) n_out, 0.0f);
126    for (long long o = 0; o < n_out; ++o) {
127        float acc = 0.0f;
128        for (long long g = 0; g < n_in / 64; ++g) {
129            const float d = scales[(size_t) (o * (n_in / 64) + g)];
130            for (int j = 0; j < 64; ++j) {
131                const long long i = g * 64 + j;
132                const uint8_t byte = codes[(size_t) (o * (n_in / 4) + i / 4)];
133                const int code = (byte >> ((i % 4) * 2)) & 3;
134                acc += (float) (code - 1) * d * act_val(i);
135            }
136        }
137        ref[(size_t) o] = acc;
138    }
139    strata::kernels::s2_gemv_q8(d_act, d_codes, d_scales, d_y_q8, n_in, n_out, tpr, nullptr);
140    std::vector<float> got((size_t) n_out);
141    check(DPCT_CHECK_ERROR(
142              (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
143                  .memcpy(got.data(), d_y_q8, got.size() * sizeof(float))
144                  .wait()),
145          "c y2");
146
147    int bad = 0;
148    double worst = 0.0, sum_abs = 0.0;
149    for (long long o = 0; o < n_out; ++o) {
150        const double a = ref[(size_t) o], b = got[(size_t) o];
151        sum_abs += std::fabs(a);
152        // relative to the row magnitude is not needed here - these rows are not cancelling - but the metric is
153        // stated because round 169 and round 189 both showed the wrong denominator reads as a wrong kernel
154        const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30);
155        if (!(rel <= worst)) worst = rel;
156        // 1e-4, not 1e-5: the measured worst is 1.479e-05, which is FMA contraction over 2560 terms rather
157        // than a structural error, and a threshold that passes 62 of 64 by luck is not a threshold.  The phase
158        // allows 1e-3 for FP16 paths, so this is ten times tighter than the spec and ten times looser than the
159        // measurement.
160        if (!(rel <= 1e-4)) ++bad;
161    }
162    std::printf("  %-38s %s (%d of %lld over 1e-4, worst rel %.3e, mean |ref| %.3f)\n",
163                "q8-activation GEMV vs host reference", bad ? "*** WRONG ***" : "matches", bad, n_out, worst,
164                sum_abs / (double) n_out);
165
166    // ---- CHECK 2: the gap is real.  The SAME weights driven by an fp16 activation must differ.
167    // The fp16 path wants fp16 activations, and `x` is f32, so it is converted exactly (the values are normal
168    // and small), which keeps the comparison about the ACTIVATION FORMAT and nothing else.
169    // A REAL fp32 -> fp16 conversion.  The first version wrote `0x3C00 + (int)(x*64)`, which adds to the raw
170    // BITS and therefore changes the EXPONENT - x = 2.0 became 0x3C80 = 1.25 - so the two paths were driven by
171    // unrelated activations and the comparison reported 2770%.  The number was a symptom of the fixture, and
172    // the fixture is what the check exists to be able to trust.
173    auto f32_to_f16 = [](float f) -> uint16_t {
174        uint32_t b;
175        std::memcpy(&b, &f, 4);
176        const uint32_t sign = (b >> 16) & 0x8000u;
177        int exp = (int) ((b >> 23) & 0xFF) - 127 + 15;
178        uint32_t man = b & 0x7FFFFFu;
179        if (exp >= 31) return (uint16_t) (sign | 0x7C00u | (man ? 0x200u : 0u));
180        if (exp <= 0) {
181            if (exp < -10) return (uint16_t) sign;
182            man |= 0x800000u;
183            const uint32_t sh = (uint32_t) (14 - exp);
184            uint32_t h = (man >> sh) & 0x3FFu;
185            const uint32_t rem = man & ((1u << sh) - 1u);
186            if (rem > (1u << (sh - 1)) || (rem == (1u << (sh - 1)) && (h & 1u))) ++h;
187            return (uint16_t) (sign | h);
188        }
189        uint16_t h = (uint16_t) (sign | ((uint32_t) exp << 10) | (man >> 13));
190        const uint32_t rem = man & 0x1FFFu;
191        if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h;
192        return h;
193    };
194    std::vector<uint16_t> hx((size_t) n_in);
195    for (long long i = 0; i < n_in; ++i) hx[(size_t) i] = f32_to_f16(x[(size_t) i]);
196    uint16_t* d_hx = nullptr;
197    check(DPCT_CHECK_ERROR(d_hx = sycl::malloc_device<uint16_t>(
198                               hx.size(), dpct::get_in_order_queue())),
199          "m hx");
200    /*
201    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
202    in the original code the source host memory is pageable memory. If the
203    memory is not pageable, call wait() on event return by memcpy API to ensure
204    synchronization behavior.
205    */
206    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
207              d_hx, hx.data(), hx.size() * sizeof(uint16_t)).wait()),
208          "c hx");
209    strata::kernels::SForm form{2, -1, 64, strata::kernels::Codebook::Affine, false};
210    strata::kernels::s_gemv_split(d_hx, d_codes, d_scales, nullptr, d_y_fp16, n_in, n_out, form, tpr);
211    std::vector<float> y16((size_t) n_out);
212    check(DPCT_CHECK_ERROR(
213              (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
214                  .memcpy(y16.data(), d_y_fp16, y16.size() * sizeof(float))
215                  .wait()),
216          "c y1");
217
218    double diff = 0.0;
219    for (long long o = 0; o < n_out; ++o) {
220        diff += std::fabs((double) y16[(size_t) o] - (double) got[(size_t) o]);
221    }
222    const double rel_gap = diff / (sum_abs > 1e-30 ? sum_abs : 1e-30);
223    std::printf("  %-38s %.4f%% of the reference magnitude\n", "fp16-activation vs q8-activation", rel_gap * 100);
224    if (rel_gap < 1e-4) {
225        std::fprintf(stderr,
226                     "the two activation paths agree to %.2e, so this test CANNOT see the difference it exists "
227                     "to measure - either the q8 path silently used fp16, or the fixture is degenerate\n",
228                     rel_gap);
229        ++bad;
230    }
231
232    std::printf("\ns2_gemv_q8: %d failures\n", bad);
233    if (bad) return 1;
234    if (selftest) std::printf("s2_gemv_q8_parity OK\n");
235    return 0;
236}