okami.mom/strata

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

Niko1221Int3 merge f-0291-df2-spark (15165e170)6360274c8

main
7.6 KiB164 linesraw
1// src/core/dflash2_q4_parity.cpp - the drafter's Q4_0 GEMM (kernels/dflash2.hpp df2_gemm with Df2Mat::q4, after df2_q4_tile) against a CPU reference.
2//
3//     dflash2_q4_parity
4//
5// Random float matrices are quantized to ggml Q4_0 blocks on the CPU (the reference of tools/dflash2_pack.py quant_q4_0), tiled on the device, and multiplied by
6// random planar-int8 activations (df2_quant_rows).  The reference reads the same blocks and the same activation codes back and sums per block in integers,
7// so the only difference to the kernel is the float order of the sum over blocks.  Shapes: the drafter's (n_in 2560, 4096, 7680, 12800), one, two and three
8// matrices to a launch, 1..8 columns.  Exit 0 when every output is within 2e-5 of the largest value (relative), 1 otherwise.
9#include "strata/kernels/dflash2.hpp"
10
11#include <cuda_runtime.h>
12
13#include <algorithm>
14#include <cmath>
15#include <cstdint>
16#include <cstdio>
17#include <cstdlib>
18#include <cstring>
19#include <random>
20#include <vector>
21
22namespace {
23
24uint16_t f2h(float f) {   // IEEE half, round to nearest even (the d of a block is stored this way)
25    uint32_t x;
26    std::memcpy(&x, &f, 4);
27    const uint32_t sign = (x >> 16) & 0x8000u;
28    int32_t e = (int32_t) ((x >> 23) & 0xff) - 127 + 15;
29    uint32_t m = x & 0x7fffffu;
30    if (e <= 0) {
31        if (e < -10) return (uint16_t) sign;
32        m |= 0x800000u;
33        const int sh = 14 - e;
34        uint32_t r = m >> sh;
35        const uint32_t rem = m & ((1u << sh) - 1), half = 1u << (sh - 1);
36        if (rem > half || (rem == half && (r & 1))) ++r;
37        return (uint16_t) (sign | r);
38    }
39    if (e >= 31) return (uint16_t) (sign | 0x7c00u);
40    uint32_t r = ((uint32_t) e << 10) | (m >> 13);
41    const uint32_t rem = m & 0x1fffu;
42    if (rem > 0x1000u || (rem == 0x1000u && (r & 1))) ++r;
43    return (uint16_t) (sign | r);
44}
45
46float h2f(uint16_t h) {
47    const uint32_t sign = (uint32_t) (h & 0x8000u) << 16;
48    const uint32_t e = (h >> 10) & 0x1f, m = h & 0x3ff;
49    uint32_t x;
50    if (e == 0) {
51        if (m == 0) x = sign;
52        else {
53            int s = 0;
54            uint32_t mm = m;
55            while (!(mm & 0x400)) { mm <<= 1; ++s; }
56            x = sign | ((uint32_t) (127 - 15 - s + 1) << 23) | ((mm & 0x3ff) << 13);
57        }
58    } else if (e == 31) x = sign | 0x7f800000u | (m << 13);
59    else x = sign | ((e - 15 + 127) << 23) | (m << 13);
60    float f;
61    std::memcpy(&f, &x, 4);
62    return f;
63}
64
65// ggml quantize_row_q4_0_ref: 18 bytes a block
66void quant_q4_0(const float* x, int n, uint8_t* out) {
67    for (int b = 0; b < n / 32; ++b) {
68        float amax = 0, mx = 0;
69        for (int i = 0; i < 32; ++i)
70            if (std::fabs(x[b * 32 + i]) > amax) { amax = std::fabs(x[b * 32 + i]); mx = x[b * 32 + i]; }
71        const float d = mx / -8.0f, id = d != 0.0f ? 1.0f / d : 0.0f;
72        const uint16_t dh = f2h(d);
73        out[b * 18] = (uint8_t) (dh & 0xff);
74        out[b * 18 + 1] = (uint8_t) (dh >> 8);
75        for (int i = 0; i < 16; ++i) {
76            const int q0 = std::min(15, (int) (x[b * 32 + i] * id + 8.5f)), q1 = std::min(15, (int) (x[b * 32 + 16 + i] * id + 8.5f));
77            out[b * 18 + 2 + i] = (uint8_t) (q0 | (q1 << 4));
78        }
79    }
80}
81
82struct Case { int n_in; std::vector<int> n_out; };
83
84}  // namespace
85
86int main() {
87    std::mt19937 rng(20261031);
88    std::normal_distribution<float> nd(0.0f, 0.1f);
89    const Case cases[] = {{2560, {64}}, {2560, {64, 32}}, {2560, {4096, 1024, 1024}}, {4096, {2560}}, {7680, {2560}}, {12800, {2560}}, {2560, {7680, 7680}}, {2560, {16}}};
90    int bad = 0, total = 0;
91    for (const Case& cs : cases) {
92        const int n_in = cs.n_in, nb = n_in / 32, nm = (int) cs.n_out.size();
93        std::vector<std::vector<uint8_t>> blocks(nm);
94        std::vector<uint8_t*> dev_w(nm);
95        std::vector<float*> dev_y(nm);
96        for (int m = 0; m < nm; ++m) {
97            const int n_out = cs.n_out[m];
98            std::vector<float> w((size_t) n_out * n_in);
99            for (float& v : w) v = nd(rng);
100            blocks[m].resize((size_t) n_out * nb * 18);
101            for (int r = 0; r < n_out; ++r) quant_q4_0(&w[(size_t) r * n_in], n_in, &blocks[m][(size_t) r * nb * 18]);
102            uint8_t* tmp;
103            cudaMalloc((void**) &tmp, blocks[m].size());
104            cudaMemcpy(tmp, blocks[m].data(), blocks[m].size(), cudaMemcpyHostToDevice);
105            cudaMalloc((void**) &dev_w[m], blocks[m].size());
106            strata::kernels::df2_q4_tile(tmp, dev_w[m], dev_w[m] + (size_t) n_out * n_in / 2, n_in, (int64_t) n_out * nb, nullptr);
107            cudaDeviceSynchronize();
108            cudaFree(tmp);
109            cudaMalloc((void**) &dev_y[m], (size_t) 8 * n_out * 4);
110        }
111        std::vector<float> x((size_t) 8 * n_in);
112        for (float& v : x) v = nd(rng) * 4.0f;
113        float* dx;
114        int8_t* dxq;
115        float* dxd;
116        cudaMalloc((void**) &dx, x.size() * 4);
117        cudaMalloc((void**) &dxq, (size_t) 8 * n_in + 4096);
118        cudaMalloc((void**) &dxd, (size_t) 8 * nb * 4 + 64);
119        cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice);
120        strata::kernels::df2_quant_rows(dx, n_in, 8, dxq, dxd, nullptr);
121        cudaDeviceSynchronize();
122        std::vector<int8_t> xq((size_t) 8 * n_in);
123        std::vector<float> xd((size_t) 8 * nb);
124        cudaMemcpy(xq.data(), dxq, xq.size(), cudaMemcpyDeviceToHost);
125        cudaMemcpy(xd.data(), dxd, xd.size() * 4, cudaMemcpyDeviceToHost);
126        for (int ncols : {1, 2, 3, 5, 8}) {
127            strata::kernels::Df2Mat mats[3];
128            for (int m = 0; m < nm; ++m) mats[m] = strata::kernels::Df2Mat{dev_w[m], dev_y[m], cs.n_out[m], true};
129            strata::kernels::df2_gemm(mats, nm, dxq, dxd, n_in, ncols, nullptr);
130            cudaDeviceSynchronize();
131            double worst = 0, big = 0;
132            for (int m = 0; m < nm; ++m) {
133                const int n_out = cs.n_out[m];
134                std::vector<float> y((size_t) 8 * n_out);
135                cudaMemcpy(y.data(), dev_y[m], y.size() * 4, cudaMemcpyDeviceToHost);
136                for (int c = 0; c < ncols; ++c)
137                    for (int r = 0; r < n_out; ++r) {
138                        double ref = 0;
139                        for (int b = 0; b < nb; ++b) {
140                            const uint8_t* blk = &blocks[m][((size_t) r * nb + b) * 18];
141                            const uint16_t dh = (uint16_t) blk[0] | ((uint16_t) blk[1] << 8);
142                            long isum = 0;
143                            for (int i = 0; i < 16; ++i) {
144                                isum += (long) ((blk[2 + i] & 15) - 8) * xq[(size_t) c * n_in + b * 32 + i];
145                                isum += (long) ((blk[2 + i] >> 4) - 8) * xq[(size_t) c * n_in + b * 32 + 16 + i];
146                            }
147                            ref += (double) h2f(dh) * (double) xd[(size_t) c * nb + b] * (double) isum;
148                        }
149                        const double got = y[(size_t) c * n_out + r];
150                        worst = std::max(worst, std::fabs(got - ref));
151                        big = std::max(big, std::fabs(ref));
152                    }
153            }
154            const bool ok = worst <= 2e-5 * std::max(big, 1e-9);
155            ++total;
156            if (!ok) ++bad;
157            std::printf("n_in %5d mats %d rows %5d cols %d: max |kernel - cpu| %.3g of %.3g (%.2g)  %s\n", n_in, nm, cs.n_out[0], ncols, worst, big, worst / std::max(big, 1e-9), ok ? "ok" : "MISMATCH");
158        }
159        for (int m = 0; m < nm; ++m) { cudaFree(dev_w[m]); cudaFree(dev_y[m]); }
160        cudaFree(dx); cudaFree(dxq); cudaFree(dxd);
161    }
162    std::printf("%s: %d of %d cases match the CPU reference\n", bad == 0 ? "PASS" : "FAIL", total - bad, total);
163    return bad == 0 ? 0 : 1;
164}