okami.mom/strata

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

Niko1221Merge branch 'f-1402-y' into f-14025af104b51

main
9.8 KiB221 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#define DPCT_PROFILING_ENABLED
12#include <sycl/sycl.hpp>
13#include <dpct/dpct.hpp>
14#include "strata/prefill/gemm.hpp"
15#include <dpct/blas_utils.hpp>
16
17#include <algorithm>
18#include <chrono>
19#include <cmath>
20#include <cstdint>
21#include <cstdio>
22#include <cstring>
23#include <random>
24#include <string>
25#include <vector>
26#include <dpct/lib_common_utils.hpp>
27
28namespace {
29
30uint16_t to_bf16(float f) {   // round to nearest even
31    uint32_t u;
32    std::memcpy(&u, &f, 4);
33    u += 0x7fffu + ((u >> 16) & 1u);
34    return (uint16_t) (u >> 16);
35}
36
37bool ok_or(dpct::err0 e, const char *what) {
38    /*
39    DPCT1009: SYCL reports errors using exceptions and does not use error
40    codes. Please replace the "get_error_string_dummy(...)" with a real
41    error-handling function.
42    */
43
44    return e == 0;
45}
46
47struct Shape {
48    int64_t T, N, K, ldy;
49    const char* what;
50};
51
52}  // namespace
53
54int main(int argc, char **argv) try {
55    const bool bench = argc > 1 && std::string(argv[1]) == "--bench";
56    int dev = 0, maj = 0, min = 0;
57    dev = dpct::get_current_device_id();
58    maj = dpct::get_device(dev).get_major_version();
59    min = dpct::get_device(dev).get_minor_version();
60    std::printf("gemm_bf16_parity: compute capability %d.%d\n", maj, min);
61
62    dpct::queue_ptr st = &dpct::get_in_order_queue();
63    if (!ok_or(DPCT_CHECK_ERROR(
64                   st = dpct::get_current_device().create_queue(true)),
65               "stream")) return 1;
66    strata::prefill::Gemm gemm;
67    std::string err;
68    if (!gemm.init(st, 0, err)) { std::printf("FAIL: %s\n", err.c_str()); return 1; }
69    dpct::blas::descriptor_ptr h = nullptr;
70    if (DPCT_CHECK_ERROR(h = new dpct::blas::descriptor()) != 0) {
71        std::printf("FAIL: cublasCreate\n"); return 1;
72    }
73    h->set_queue(st);
74
75    const Shape shapes[] = {
76        {4096, 320, 10240, 0, "hc down (activations sliced)"},
77        {4096, 10240, 320, 0, "hc up"},
78        {777, 2560, 2560, 0, "PLE value"},
79        {512, 512, 2560, 0, "router / indexer q"},
80        {300, 4, 10240, 0, "hc inject"},
81        {2048, 1, 2560, 0, "single row"},
82        {333, 128, 2560, 136, "row stride wider than N"},
83    };
84    std::mt19937 rng(1234);
85    std::normal_distribution<float> nd(0.0f, 1.0f);
86    int failures = 0;
87    for (const Shape& s : shapes) {
88        const int64_t ldy = s.ldy > 0 ? s.ldy : s.N;
89        std::vector<uint16_t> x((size_t) (s.T * s.K)), xlo(x.size()), w((size_t) (s.N * s.K));
90        for (size_t i = 0; i < x.size(); ++i) {
91            const float v = 3.0f * nd(rng);          // activations: normalized, a few units
92            x[i] = to_bf16(v);
93            xlo[i] = to_bf16(1e-3f * nd(rng));       // a bf16x2 low part
94        }
95        for (auto& v : w) v = to_bf16(0.02f * nd(rng));
96        uint16_t *dx = nullptr, *dxlo = nullptr, *dw = nullptr;
97        float *dy = nullptr, *dr = nullptr;
98        const size_t ybytes = (size_t) (s.T * ldy) * 4;
99        bool ok =
100            ok_or(
101                DPCT_CHECK_ERROR(dx = (uint16_t *)sycl::malloc_device(
102                                     x.size() * 2, dpct::get_in_order_queue())),
103                "x") &&
104            ok_or(
105                DPCT_CHECK_ERROR(dxlo = (uint16_t *)sycl::malloc_device(
106                                     x.size() * 2, dpct::get_in_order_queue())),
107                "xlo") &&
108            ok_or(
109                DPCT_CHECK_ERROR(dw = (uint16_t *)sycl::malloc_device(
110                                     w.size() * 2, dpct::get_in_order_queue())),
111                "w") &&
112            ok_or(DPCT_CHECK_ERROR(dy = (float *)sycl::malloc_device(
113                                       ybytes, dpct::get_in_order_queue())),
114                  "y") &&
115            ok_or(DPCT_CHECK_ERROR(dr = (float *)sycl::malloc_device(
116                                       ybytes, dpct::get_in_order_queue())),
117                  "ref");
118        if (!ok) return 1;
119        /*
120        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
121        assuming in the original code the source host memory is pageable memory.
122        If the memory is not pageable, call wait() on event return by memcpy API
123        to ensure synchronization behavior.
124        */
125        dpct::get_in_order_queue().memcpy(dx, x.data(), x.size() * 2).wait();
126        /*
127        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
128        assuming in the original code the source host memory is pageable memory.
129        If the memory is not pageable, call wait() on event return by memcpy API
130        to ensure synchronization behavior.
131        */
132        dpct::get_in_order_queue().memcpy(dxlo, xlo.data(), xlo.size() * 2).wait();
133        /*
134        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
135        assuming in the original code the source host memory is pageable memory.
136        If the memory is not pageable, call wait() on event return by memcpy API
137        to ensure synchronization behavior.
138        */
139        dpct::get_in_order_queue().memcpy(dw, w.data(), w.size() * 2).wait();
140        dpct::get_in_order_queue().memset(dy, 0, ybytes).wait();
141        dpct::get_in_order_queue().memset(dr, 0, ybytes).wait();
142
143        // the product under test: X . W^T, then the low part added with beta = 1
144        gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy);
145        gemm.bf16(dxlo, dw, dy, s.T, s.N, s.K, ldy, 1.0f);
146        // the reference: cuBLAS on the BF16 inputs, the same two calls
147        const float one = 1.0f, zero = 0.0f;
148        auto ref = [&](const uint16_t* X, float beta) {
149            /*
150            DPCT1020: Migration of cublasGemmEx, if it is called from
151            __global__ or __device__ function, is not supported. You may need to
152            redesign the code to use the host-side dpct::blas::gemm instead,
153            which submits this call to the SYCL queue automatically.
154            */
155            return cublasGemmEx(
156                h, oneapi::mkl::transpose::trans,
157                oneapi::mkl::transpose::nontrans, (int)s.N, (int)s.T, (int)s.K,
158                &one, dw, dpct::library_data_t::real_bfloat16, (int)s.K, X,
159                dpct::library_data_t::real_bfloat16, (int)s.K, &beta, dr,
160                dpct::library_data_t::real_float, (int)ldy,
161                dpct::compute_type::f32, -1);
162        };
163        if (ref(dx, zero) != 0 || ref(dxlo, one) != 0) {
164            std::printf("FAIL: reference cublasGemmEx\n");
165            return 1;
166        }
167        if (!ok_or(DPCT_CHECK_ERROR(st->wait()), "sync")) return 1;
168        std::vector<float> y((size_t) (s.T * ldy)), r(y.size());
169        dpct::get_in_order_queue().memcpy(y.data(), dy, ybytes).wait();
170        dpct::get_in_order_queue().memcpy(r.data(), dr, ybytes).wait();
171        double worst = 0.0, mag = 1e-30;
172        int bad = 0;
173        for (int64_t t = 0; t < s.T; ++t)
174            for (int64_t c = 0; c < s.N; ++c) {
175                const float a = y[(size_t) (t * ldy + c)], b = r[(size_t) (t * ldy + c)];
176                if (!std::isfinite(a)) ++bad;
177                worst = std::max(worst, (double) std::fabs(a - b));
178                mag = std::max(mag, (double) std::fabs(b));
179            }
180        // the untouched columns of a wider row stride stay as they were
181        for (int64_t t = 0; t < s.T && ldy > s.N; ++t)
182            for (int64_t c = s.N; c < ldy; ++c)
183                if (y[(size_t) (t * ldy + c)] != 0.0f) ++bad;
184        const bool pass = bad == 0 && worst <= 1e-4 * mag;
185        if (!pass) ++failures;
186        std::printf("  %-32s T %5lld N %5lld K %5lld ldy %5lld: worst |diff| %.3e of max |ref| %.3e (rel %.2e) %s\n",
187                    s.what, (long long) s.T, (long long) s.N, (long long) s.K, (long long) ldy, worst, mag, worst / mag,
188                    pass ? "pass" : "FAIL");
189
190        if (bench) {
191            auto time = [&](auto&& f) {
192#pragma unroll
193                for (int i = 0; i < 3; ++i) f();
194                st->wait();
195                const auto t0 = std::chrono::steady_clock::now();
196#pragma unroll
197                for (int i = 0; i < 20; ++i) f();
198                st->wait();
199                return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count() / 20;
200            };
201            const double us_gemm = time([&] { gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy); });
202            const double us_ref = time([&] { ref(dx, zero); });
203            std::printf("      bench: Gemm::bf16 %9.1f us   cuBLAS BF16 %9.1f us   (%.2fx)\n", us_gemm, us_ref,
204                        us_ref / us_gemm);
205        }
206        sycl::free(dx, dpct::get_in_order_queue());
207            sycl::free(dxlo, dpct::get_in_order_queue());
208            sycl::free(dw, dpct::get_in_order_queue());
209            sycl::free(dy, dpct::get_in_order_queue());
210            sycl::free(dr, dpct::get_in_order_queue());
211    }
212    delete (h);
213    dpct::get_current_device().destroy_queue(st);
214    std::printf("gemm_bf16_parity: %d failures\n", failures);
215    return failures == 0 ? 0 : 1;
216}
217catch (sycl::exception const &exc) {
218  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
219            << ", line:" << __LINE__ << std::endl;
220  std::exit(1);
221}