okami.mom/strata

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

Niko1221Merge f-sm75-iq-b19: in a build without MMQ, Turing cards (RTX 20 series) read i-quant prompts on Strata's fused expert kernels3b0ca805f

main
8.4 KiB173 linesraw
1// src/kernels/pf_wmma_parity.cpp - gemm_iq_f16_grouped (the Volta prompt experts, STRATA_PF_WMMA) against a double
2// reference over the same FP16 weights (iq_dequant_f16, the FP16 path's dequantization) and FP16 activations.
3//
4//     build/pf_wmma_parity            (needs a CUDA GPU with FP16 tensor cores: sm_70+; synthetic blobs, no model)
5//
6// Every gate/up format the prompt path gives it (IQ2_XXS, IQ2_S, IQ1_M, and this pack's IQ4_NL / IQ3_S / IQ4_XS: 1280
7// rows of 2560) and the down products (Q2_0, and IQ4_NL: 2560 rows of 640); a group of experts with 0, 1, 63, 64, 65,
8// 200 and 300 rows (one past the 256-row chunk); the rows placed past a nonzero first bound.  The sums are FP32 on
9// tensor cores in another order than the reference, so the check is a tolerance: max |got - ref| <= 2e-3 * (max |ref|
10// of the matrix) + 1e-6.
11#include "strata/kernels/iq_kernels.hpp"
12
13#include <cuda_fp16.h>
14#include <cuda_runtime.h>
15
16#include <algorithm>
17#include <cmath>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21#include <random>
22#include <vector>
23
24namespace k = strata::kernels;
25
26namespace {
27
28void ck(cudaError_t e, const char* what) {
29    if (e != cudaSuccess) {
30        std::fprintf(stderr, "CUDA error in %s: %s\n", what, cudaGetErrorString(e));
31        std::exit(2);
32    }
33}
34
35const char* name_of(int t) {
36    switch (t) {
37        case 16: return "IQ2_XXS";
38        case 17: return "IQ2_XS";
39        case 18: return "IQ3_XXS";
40        case 20: return "IQ4_NL";
41        case 21: return "IQ3_S";
42        case 22: return "IQ2_S";
43        case 23: return "IQ4_XS";
44        case 29: return "IQ1_M";
45        case 42: return "Q2_0";
46        case 12: return "Q4_K";
47        case 13: return "Q5_K";
48        case 14: return "Q6_K";
49        case 7: return "Q5_1";
50        case 8: return "Q8_0";
51        default: return "?";
52    }
53}
54int block_values(int t) { return t == 20 || t == 7 || t == 8 ? 32 : t == 42 ? 64 : 256; }
55
56// `rows` rows of `n` values of format t: random bytes, then a finite fp16 scale in every block
57std::vector<uint8_t> random_rows(int t, int64_t rows, int64_t n, std::mt19937& rng) {
58    const size_t rb = k::iq_row_bytes(t, n), bs = k::iq_row_bytes(t, block_values(t));
59    std::vector<uint8_t> w((size_t) rows * rb);
60    std::uniform_int_distribution<int> byte(0, 255), ex(2, 8), man(0, 1023), sgn(0, 1);
61    for (auto& b : w) b = (uint8_t) byte(rng);
62    for (size_t o = 0; o < w.size(); o += bs) {
63        if (t == 29) {
64            // IQ1_M: the fp16 scale is the top nibbles of its four scale words (bytes 48..55), the sign and the
65            // exponent's top bits in the last: 0x1 / 0x2 there (0x9 / 0xA negative) keeps it in 2^-11 .. 2^-3
66            const uint8_t nib = (uint8_t) ((sgn(rng) ? 0x8 : 0x0) | (1 + (byte(rng) & 1)));
67            w[o + 55] = (uint8_t) ((w[o + 55] & 0x0F) | (nib << 4));
68        } else {   // the other formats start their block with the fp16 scale: 2^-13 .. 2^-6
69            // (Q4_K / Q5_K: 2^-14 .. 2^-11, their 6-bit sub-scales multiply it by up to 63)
70            const int e = (t == 12 || t == 13) ? 1 + ex(rng) % 4 : ex(rng);
71            const uint16_t h = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (e << 10) | man(rng));
72            std::memcpy(&w[o], &h, 2);
73            if (t == 12 || t == 13 || t == 7) {   // Q4_K / Q5_K: dmin, Q5_1: m - the second fp16, as small
74                const int em = (t == 7) ? ex(rng) : 1 + ex(rng) % 4;
75                const uint16_t m = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (em << 10) | man(rng));
76                std::memcpy(&w[o + 2], &m, 2);
77            }
78        }
79    }
80    return w;
81}
82
83
84int run(int ty, int n_out, int K, std::mt19937& rng) {
85    const std::vector<int> rows = {0, 1, 63, 64, 65, 200, 300};
86    const int E = (int) rows.size(), base = 5;
87    std::vector<int32_t> bounds(E + 1);
88    bounds[0] = base;
89    for (int e = 0; e < E; ++e) bounds[e + 1] = bounds[e] + rows[e];
90    const int total = bounds[E];
91    const size_t eb = k::iq_row_bytes(ty, K) * (size_t) n_out;
92    std::vector<uint8_t> w;
93    for (int e = 0; e < E; ++e) { auto r = random_rows(ty, n_out, K, rng); w.insert(w.end(), r.begin(), r.end()); }
94    std::normal_distribution<float> nd(0.f, 1.f);
95    std::vector<__half> x((size_t) total * K);
96    for (auto& v : x) v = __float2half(nd(rng));
97    uint8_t* dw; __half* dx; int32_t* db; float* dy; uint16_t* dq;
98    ck(cudaMalloc(&dw, w.size() + 4096), "w");
99    ck(cudaMemcpy(dw, w.data(), w.size(), cudaMemcpyHostToDevice), "w");
100    ck(cudaMalloc(&dx, x.size() * 2), "x");
101    ck(cudaMemcpy(dx, x.data(), x.size() * 2, cudaMemcpyHostToDevice), "x");
102    ck(cudaMalloc(&db, bounds.size() * 4), "b");
103    ck(cudaMemcpy(db, bounds.data(), bounds.size() * 4, cudaMemcpyHostToDevice), "b");
104    ck(cudaMalloc(&dy, (size_t) total * n_out * 4), "y");
105    ck(cudaMemset(dy, 0xff, (size_t) total * n_out * 4), "y");
106    ck(cudaMalloc(&dq, (size_t) E * n_out * K * 2), "dq");
107    const int maxr = *std::max_element(rows.begin(), rows.end());
108    {   // the kernel's shared memory (iq_kernels.cu: WG_BN 128 weight columns of wk + 8 halves, WG_BM 64 rows of WG_XK 128 + 8 halves; wk 128 for Q2_0 and the IQ4_NL down, else 256): a card whose
109        // opt-in limit is lower (Turing: 64 KB) has no launch of it - skipped with that reason, not a failure
110        const int wk = (ty == 42 || (ty == 20 && K % 256 != 0)) ? 128 : 256;
111        const size_t need = (size_t) 128 * (wk + 8) * 2 + (size_t) 64 * (128 + 8) * 2;
112        int cur = 0, optin = 0;
113        cudaGetDevice(&cur);
114        cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, cur);
115        if (need > (size_t) optin) {
116            std::printf("%-8s %5d x %4d: skipped, its tile needs %zu B of shared memory and this card allows %d B per block\n", name_of(ty), n_out, K, need, optin);
117            cudaFree(dw); cudaFree(dx); cudaFree(db); cudaFree(dy); cudaFree(dq);
118            return 0;
119        }
120    }
121    if (!k::gemm_iq_f16_grouped(ty, dw, eb, n_out, K, dx, K, db, E, maxr, dy, n_out, nullptr)) {
122        std::printf("%-8s %5d x %4d: not launched\n", name_of(ty), n_out, K);
123        return 1;
124    }
125    for (int e = 0; e < E; ++e) k::iq_dequant_f16(ty, dw + e * eb, (int64_t) n_out * K, dq + (size_t) e * n_out * K, nullptr);
126    ck(cudaDeviceSynchronize(), "run");
127    std::vector<float> y((size_t) total * n_out);
128    std::vector<uint16_t> q((size_t) E * n_out * K);
129    ck(cudaMemcpy(y.data(), dy, y.size() * 4, cudaMemcpyDeviceToHost), "y");
130    ck(cudaMemcpy(q.data(), dq, q.size() * 2, cudaMemcpyDeviceToHost), "dq");
131    double worst = 0, scale = 0;
132    for (int e = 0; e < E; ++e)
133        for (int r = bounds[e]; r < bounds[e + 1]; ++r)
134            for (int n = 0; n < n_out; ++n) {
135                double s = 0;
136                const uint16_t* wr = &q[((size_t) e * n_out + n) * K];
137                for (int kk = 0; kk < K; ++kk) {
138                    __half h; std::memcpy(&h, &wr[kk], 2);
139                    s += (double) __half2float(h) * (double) __half2float(x[(size_t) r * K + kk]);
140                }
141                scale = std::max(scale, std::fabs(s));
142                worst = std::max(worst, std::fabs(s - (double) y[(size_t) r * n_out + n]));
143            }
144    const bool ok = worst <= 2e-3 * scale + 1e-6;
145    std::printf("%-8s %5d x %4d, %d rows in %d experts: max |err| %.3g of max |ref| %.3g  %s\n", name_of(ty), n_out, K,
146                total - base, E, worst, scale, ok ? "ok" : "FAIL");
147    cudaFree(dw); cudaFree(dx); cudaFree(db); cudaFree(dy); cudaFree(dq);
148    return ok ? 0 : 1;
149}
150
151}  // namespace
152
153int main() {
154    // every sm_70+ card in one process, in turn: a layer split launches the tiles on its second card after the first
155    int n_dev = 0, ran = 0, fails = 0;
156    cudaGetDeviceCount(&n_dev);
157    for (int dev = 0; dev < n_dev; ++dev) {
158        int major = 0;
159        cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
160        if (major < 7) continue;
161        cudaSetDevice(dev);
162        std::printf("device %d\n", dev);
163        ++ran;
164        std::mt19937 rng(70);
165        for (int ty : {16, 22, 29}) fails += run(ty, 1280, 2560, rng);
166        fails += run(42, 2560, 640, rng);
167        for (int ty : {20, 21, 23}) fails += run(ty, 1280, 2560, rng);   // this pack's gate/up formats, generic WK=256 path
168        fails += run(20, 2560, 640, rng);                                // the IQ4_NL down, the new WK=128 lane
169    }
170    if (!ran) { std::printf("pf_wmma_parity: needs sm_70+, skipped\n"); return 77; }
171    std::printf("pf_wmma_parity: %d failures on %d devices\n", fails, ran);
172    return fails ? 1 : 0;
173}