okami.mom/strata

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

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

main
9.6 KiB205 linesraw
1// src/kernels/s2_gemv_parity.cpp - P2.S2's parity test for the S2 GEMV.
2//
3// The reference is the same CHAIN as the decode test: `strata::dequantize_q2_0` is a scalar transcription that
4// `bench/micro/dequant_xcheck` checks against **ggml's own** dequantizer, so comparing the GPU GEMV against a
5// dot product built on that scalar decode compares against ggml through one proven hop.
6//
7// WHY A TOLERANCE AND NOT BIT EQUALITY.  The decode test is bit-exact because S2's decode is exact
8// integer-to-float arithmetic.  A dot product is not: the compiler is free to contract `a*b + acc` into an
9// FMA, which changes the result in the last bits, and nvcc does.  So this asserts a RELATIVE error, measures
10// what it actually is, and prints the number - the phase spec allows 1e-3 for FP16 paths, and if the measured
11// error were near that the tolerance would be hiding something rather than bounding rounding.
12#define DPCT_PROFILING_ENABLED
13#include <sycl/sycl.hpp>
14#include <dpct/dpct.hpp>
15#include "strata/artifact/dequant.hpp"
16#include "strata/kernels/s2_gemv.hpp"
17
18#include <cmath>
19#include <cstdint>
20#include <cstdio>
21#include <cstring>
22#include <random>
23#include <vector>
24
25namespace {
26
27constexpr int QK = 64;
28
29void check(dpct::err0 e, const char *what) {
30}
31
32// FP16 patterns, and they are deliberately NOT all powers of two.
33//
34// The first version of this table was {1.0, 0.5, 0.25, ...} - every value a power of two.  The test then
35// reported a worst relative error of EXACTLY zero, which is not a property of the kernel: (code-1) is in
36// {-1,0,1,2} and a power-of-two times an fp16 is exact, so every product was exact and no rounding could
37// occur in either implementation.  A test whose arithmetic cannot round cannot exercise its own tolerance, and
38// it would have hidden an accumulation-order or contraction bug for ever.
39//
40// The added patterns have full 11-bit mantissas, so products round and the two implementations'
41// rounding/contraction behaviour actually matters.
42const uint16_t kScales[] = {
43    0x3C00, 0x3800, 0x3400, 0x3000, 0x2C00, 0x2800, 0x2000,          // 1, 0.5, 0.25, ... powers of two
44    0xBC00, 0xB800, 0xB400, 0xB000, 0xAC00, 0x1800, 0x1400,
45    0x3E00, 0x3555, 0x3C01, 0x4248, 0x4123, 0x2AAA, 0x4A2B,          // 1.75, 0.333.., 1.0009765625, ...
46    0xBE00, 0xB555, 0xC248, 0x2AAB, 0x4A2C, 0x2AAB};
47
48}  // namespace
49
50int main(int argc, char** argv) {
51    long long n_in = 2560;          // the real n_embd, so the row length is the engine's
52    long long n_out = 640;          // the real expert intermediate width
53    double tol = 1e-5;
54    bool selftest = false;
55    for (int i = 1; i < argc; ++i) {
56        if (std::strcmp(argv[i], "--selftest") == 0) selftest = true;
57        else if (std::strcmp(argv[i], "--n-in") == 0 && i + 1 < argc) n_in = std::atoll(argv[++i]);
58        else if (std::strcmp(argv[i], "--n-out") == 0 && i + 1 < argc) n_out = std::atoll(argv[++i]);
59        else if (std::strcmp(argv[i], "--tol") == 0 && i + 1 < argc) tol = std::atof(argv[++i]);
60        else {
61            std::fprintf(stderr, "usage: s2_gemv_parity [--selftest] [--n-in N] [--n-out N] [--tol T]\n");
62            return 2;
63        }
64    }
65    if (n_in % QK != 0) { std::fprintf(stderr, "--n-in must be a multiple of %d\n", QK); return 2; }
66    const long long nb = n_in / QK;
67
68    std::mt19937 rng(999);
69    const int n_scales = (int) (sizeof(kScales) / sizeof(kScales[0]));
70
71    // FP16 activations.  Patterns are drawn from the same finite/exact table as the decode test, because a
72    // random 16-bit pattern can be NaN and a NaN makes the comparison fail for the wrong reason.
73    std::vector<uint16_t> x((size_t) n_in);
74    for (long long i = 0; i < n_in; ++i) x[(size_t) i] = kScales[rng() % n_scales];
75
76    // S2 weight planes for an [n_in, n_out] matrix: row o occupies a contiguous run of nb blocks.
77    std::vector<uint8_t> codes((size_t) n_out * nb * 16);
78    std::vector<float> scales((size_t) n_out * nb);
79    for (size_t i = 0; i < codes.size(); ++i) codes[i] = (uint8_t) (rng() & 0xFF);
80    for (size_t i = 0; i < scales.size(); ++i) {
81        scales[i] = strata::fp16_to_fp32(kScales[rng() % n_scales]);
82    }
83
84    // CPU reference: rebuild each row's RAW Q2_0 blocks from the planes, decode with the scalar path that
85    // dequant_xcheck proved equal to ggml, and accumulate in the same order the kernel does.
86    std::vector<float> ref((size_t) n_out, 0.0f);
87    std::vector<uint8_t> raw(18);
88    std::vector<float> dec(QK);
89    for (long long o = 0; o < n_out; ++o) {
90        float acc = 0.0f;
91        for (long long b = 0; b < nb; ++b) {
92            const float d = scales[(size_t) (o * nb + b)];
93            // write `d` back as the fp16 pattern the plane came from: the plane stores a WIDENED fp16, so
94            // re-narrowing is exact and the scalar decoder sees the same value the kernel does
95            const uint16_t d_bits = (uint16_t) [&] {
96                for (uint16_t c : kScales) {
97                    if (strata::fp16_to_fp32(c) == d) return c;
98                }
99                return (uint16_t) 0x3C00;
100            }();
101            raw[0] = (uint8_t) (d_bits & 0xFF);
102            raw[1] = (uint8_t) (d_bits >> 8);
103            std::memcpy(&raw[2], &codes[(size_t) ((o * nb + b) * 16)], 16);
104            strata::dequantize_q2_0(raw.data(), dec.data());
105            for (int j = 0; j < QK; ++j) {
106                acc += dec[(size_t) j] * strata::fp16_to_fp32(x[(size_t) (b * QK + j)]);
107            }
108        }
109        ref[(size_t) o] = acc;
110    }
111
112    uint16_t* d_x = nullptr;
113    uint8_t* d_codes = nullptr;
114    float *d_scales = nullptr, *d_y = nullptr;
115    check(DPCT_CHECK_ERROR(d_x = sycl::malloc_device<uint16_t>(
116                               x.size(), dpct::get_in_order_queue())),
117          "cudaMalloc x");
118    check(DPCT_CHECK_ERROR(d_codes = (uint8_t *)sycl::malloc_device(
119                               codes.size(), dpct::get_in_order_queue())),
120          "cudaMalloc codes");
121    check(DPCT_CHECK_ERROR(d_scales = sycl::malloc_device<float>(
122                               scales.size(), dpct::get_in_order_queue())),
123          "cudaMalloc scales");
124    check(DPCT_CHECK_ERROR(d_y = sycl::malloc_device<float>(
125                               (size_t)n_out, dpct::get_in_order_queue())),
126          "cudaMalloc y");
127    /*
128    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
129    the original code the source host memory is pageable memory. If the memory
130    is not pageable, call wait() on event return by memcpy API to ensure
131    synchronization behavior.
132    */
133    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
134              d_x, x.data(), x.size() * sizeof(uint16_t)).wait()),
135          "copy x");
136    /*
137    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
138    the original code the source host memory is pageable memory. If the memory
139    is not pageable, call wait() on event return by memcpy API to ensure
140    synchronization behavior.
141    */
142    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
143              d_codes, codes.data(), codes.size()).wait()),
144          "copy codes");
145    /*
146    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
147    the original code the source host memory is pageable memory. If the memory
148    is not pageable, call wait() on event return by memcpy API to ensure
149    synchronization behavior.
150    */
151    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
152              d_scales, scales.data(), scales.size() * sizeof(float)).wait()),
153          "copy scales");
154
155    strata::kernels::s2_gemv(d_x, d_codes, d_scales, d_y, n_in, n_out);
156
157    std::vector<float> got((size_t) n_out);
158    check(DPCT_CHECK_ERROR(
159              (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
160                  .memcpy(got.data(), d_y, got.size() * sizeof(float))
161                  .wait()),
162          "copy back");
163
164    long long bad = 0, first_bad = -1;
165    double worst = 0.0;
166    for (long long o = 0; o < n_out; ++o) {
167        const double a = ref[(size_t) o], b = got[(size_t) o];
168        const double denom = std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30;
169        const double rel = std::fabs(a - b) / denom;
170        if (!(rel <= worst)) worst = rel;
171        if (!(rel <= tol)) {
172            if (first_bad < 0) first_bad = o;
173            ++bad;
174        }
175    }
176
177    // NON-VACUITY: a zero matrix and a zero activation vector agree at zero.  The reference must actually vary
178    // and its magnitudes must be non-trivial, or the comparison cannot distinguish anything.
179    double lo = ref[0], hi = ref[0];
180    for (float v : ref) {
181        lo = std::fmin(lo, v);
182        hi = std::fmax(hi, v);
183    }
184    const double spread = hi - lo;
185    std::printf("s2_gemv: n_in %lld, n_out %lld, %lld rows over tolerance, worst rel %.3e (tol %.1e)\n", n_in,
186                n_out, bad, worst, tol);
187    std::printf("  reference spread [%.4g, %.4g]\n", lo, hi);
188    if (spread <= 0.0) {
189        std::fprintf(stderr, "VACUOUS: the reference is constant, so agreement proves nothing\n");
190        return 1;
191    }
192    if (bad) {
193        std::printf("  first bad row %lld: ref %.9g got %.9g\n", first_bad, (double) ref[(size_t) first_bad],
194                    (double) got[(size_t) first_bad]);
195        return 1;
196    }
197    std::printf("  agrees with the scalar decode that dequant_xcheck proved equal to ggml\n");
198    if (selftest) std::printf("s2_gemv_parity OK\n");
199
200    sycl::free(d_x, dpct::get_in_order_queue());
201    sycl::free(d_codes, dpct::get_in_order_queue());
202    sycl::free(d_scales, dpct::get_in_order_queue());
203    sycl::free(d_y, dpct::get_in_order_queue());
204    return 0;
205}