okami.mom/strata

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

Niko1221Merge branch 'f-139b-old' into f-139-relbd34d0d87

main
7.2 KiB155 linesraw
1// src/prefill/gemm_bf16_parity.cu - Gemm::bf16 against cuBLAS's own BF16 product (GPU, synthetic, no model).
2//
3// Below sm_80 (no BF16 tensor cores) Gemm::bf16 converts the weight and the activations to FP16 and runs the FP16
4// tensor-core GEMM (Volta by default, Turing with STRATA_BF16_TC=1) or widens them to fp32 (Pascal); everywhere else
5// it is the cuBLAS BF16 call itself.  (On Pascal the cuBLAS BF16 reference itself may be refused: the test then fails
6// at the reference, which says so.)  This
7// checks the result against cublasGemmEx on the same BF16 inputs, within fp32-accumulation rounding, over the prompt
8// path's shapes: the hyper-connection down / up projections, the router and indexer rows, the PLE value matrix, a T
9// large enough to slice the activations, beta = 1 accumulation (the bf16x2 low parts) and an output row stride wider
10// than N.  --bench adds the time of each against the cuBLAS BF16 product.
11#include "strata/prefill/gemm.hpp"
12
13#include <cublas_v2.h>
14#include <cuda_runtime.h>
15
16#include <algorithm>
17#include <chrono>
18#include <cmath>
19#include <cstdint>
20#include <cstdio>
21#include <cstring>
22#include <random>
23#include <string>
24#include <vector>
25
26namespace {
27
28uint16_t to_bf16(float f) {   // round to nearest even
29    uint32_t u;
30    std::memcpy(&u, &f, 4);
31    u += 0x7fffu + ((u >> 16) & 1u);
32    return (uint16_t) (u >> 16);
33}
34
35bool ok_or(cudaError_t e, const char* what) {
36    if (e != cudaSuccess) std::printf("FAIL: %s: %s\n", what, cudaGetErrorString(e));
37    return e == cudaSuccess;
38}
39
40struct Shape {
41    int64_t T, N, K, ldy;
42    const char* what;
43};
44
45}  // namespace
46
47int main(int argc, char** argv) {
48    const bool bench = argc > 1 && std::string(argv[1]) == "--bench";
49    int dev = 0, maj = 0, min = 0;
50    cudaGetDevice(&dev);
51    cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev);
52    cudaDeviceGetAttribute(&min, cudaDevAttrComputeCapabilityMinor, dev);
53    std::printf("gemm_bf16_parity: compute capability %d.%d\n", maj, min);
54
55    cudaStream_t st = nullptr;
56    if (!ok_or(cudaStreamCreate(&st), "stream")) return 1;
57    strata::prefill::Gemm gemm;
58    std::string err;
59    if (!gemm.init(st, 0, err)) { std::printf("FAIL: %s\n", err.c_str()); return 1; }
60    cublasHandle_t h = nullptr;
61    if (cublasCreate(&h) != CUBLAS_STATUS_SUCCESS) { std::printf("FAIL: cublasCreate\n"); return 1; }
62    cublasSetStream(h, st);
63
64    const Shape shapes[] = {
65        {4096, 320, 10240, 0, "hc down (activations sliced)"},
66        {4096, 10240, 320, 0, "hc up"},
67        {777, 2560, 2560, 0, "PLE value"},
68        {512, 512, 2560, 0, "router / indexer q"},
69        {300, 4, 10240, 0, "hc inject"},
70        {2048, 1, 2560, 0, "single row"},
71        {333, 128, 2560, 136, "row stride wider than N"},
72    };
73    std::mt19937 rng(1234);
74    std::normal_distribution<float> nd(0.0f, 1.0f);
75    int failures = 0;
76    for (const Shape& s : shapes) {
77        const int64_t ldy = s.ldy > 0 ? s.ldy : s.N;
78        std::vector<uint16_t> x((size_t) (s.T * s.K)), xlo(x.size()), w((size_t) (s.N * s.K));
79        for (size_t i = 0; i < x.size(); ++i) {
80            const float v = 3.0f * nd(rng);          // activations: normalized, a few units
81            x[i] = to_bf16(v);
82            xlo[i] = to_bf16(1e-3f * nd(rng));       // a bf16x2 low part
83        }
84        for (auto& v : w) v = to_bf16(0.02f * nd(rng));
85        uint16_t *dx = nullptr, *dxlo = nullptr, *dw = nullptr;
86        float *dy = nullptr, *dr = nullptr;
87        const size_t ybytes = (size_t) (s.T * ldy) * 4;
88        bool ok = ok_or(cudaMalloc((void**) &dx, x.size() * 2), "x") && ok_or(cudaMalloc((void**) &dxlo, x.size() * 2), "xlo") &&
89                  ok_or(cudaMalloc((void**) &dw, w.size() * 2), "w") && ok_or(cudaMalloc((void**) &dy, ybytes), "y") &&
90                  ok_or(cudaMalloc((void**) &dr, ybytes), "ref");
91        if (!ok) return 1;
92        cudaMemcpy(dx, x.data(), x.size() * 2, cudaMemcpyHostToDevice);
93        cudaMemcpy(dxlo, xlo.data(), xlo.size() * 2, cudaMemcpyHostToDevice);
94        cudaMemcpy(dw, w.data(), w.size() * 2, cudaMemcpyHostToDevice);
95        cudaMemset(dy, 0, ybytes);
96        cudaMemset(dr, 0, ybytes);
97
98        // the product under test: X . W^T, then the low part added with beta = 1
99        gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy);
100        gemm.bf16(dxlo, dw, dy, s.T, s.N, s.K, ldy, 1.0f);
101        // the reference: cuBLAS on the BF16 inputs, the same two calls
102        const float one = 1.0f, zero = 0.0f;
103        auto ref = [&](const uint16_t* X, float beta) {
104            return cublasGemmEx(h, CUBLAS_OP_T, CUBLAS_OP_N, (int) s.N, (int) s.T, (int) s.K, &one, dw, CUDA_R_16BF,
105                                (int) s.K, X, CUDA_R_16BF, (int) s.K, &beta, dr, CUDA_R_32F, (int) ldy,
106                                CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT);
107        };
108        if (ref(dx, zero) != CUBLAS_STATUS_SUCCESS || ref(dxlo, one) != CUBLAS_STATUS_SUCCESS) {
109            std::printf("FAIL: reference cublasGemmEx\n");
110            return 1;
111        }
112        if (!ok_or(cudaStreamSynchronize(st), "sync")) return 1;
113        std::vector<float> y((size_t) (s.T * ldy)), r(y.size());
114        cudaMemcpy(y.data(), dy, ybytes, cudaMemcpyDeviceToHost);
115        cudaMemcpy(r.data(), dr, ybytes, cudaMemcpyDeviceToHost);
116        double worst = 0.0, mag = 1e-30;
117        int bad = 0;
118        for (int64_t t = 0; t < s.T; ++t)
119            for (int64_t c = 0; c < s.N; ++c) {
120                const float a = y[(size_t) (t * ldy + c)], b = r[(size_t) (t * ldy + c)];
121                if (!std::isfinite(a)) ++bad;
122                worst = std::max(worst, (double) std::fabs(a - b));
123                mag = std::max(mag, (double) std::fabs(b));
124            }
125        // the untouched columns of a wider row stride stay as they were
126        for (int64_t t = 0; t < s.T && ldy > s.N; ++t)
127            for (int64_t c = s.N; c < ldy; ++c)
128                if (y[(size_t) (t * ldy + c)] != 0.0f) ++bad;
129        const bool pass = bad == 0 && worst <= 1e-4 * mag;
130        if (!pass) ++failures;
131        std::printf("  %-32s T %5lld N %5lld K %5lld ldy %5lld: worst |diff| %.3e of max |ref| %.3e (rel %.2e) %s\n",
132                    s.what, (long long) s.T, (long long) s.N, (long long) s.K, (long long) ldy, worst, mag, worst / mag,
133                    pass ? "pass" : "FAIL");
134
135        if (bench) {
136            auto time = [&](auto&& f) {
137                for (int i = 0; i < 3; ++i) f();
138                cudaStreamSynchronize(st);
139                const auto t0 = std::chrono::steady_clock::now();
140                for (int i = 0; i < 20; ++i) f();
141                cudaStreamSynchronize(st);
142                return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count() / 20;
143            };
144            const double us_gemm = time([&] { gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy); });
145            const double us_ref = time([&] { ref(dx, zero); });
146            std::printf("      bench: Gemm::bf16 %9.1f us   cuBLAS BF16 %9.1f us   (%.2fx)\n", us_gemm, us_ref,
147                        us_ref / us_gemm);
148        }
149        cudaFree(dx); cudaFree(dxlo); cudaFree(dw); cudaFree(dy); cudaFree(dr);
150    }
151    cublasDestroy(h);
152    cudaStreamDestroy(st);
153    std::printf("gemm_bf16_parity: %d failures\n", failures);
154    return failures == 0 ? 0 : 1;
155}