okami.mom/strata

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

Niko1221Merge f-037-arc (5eaee81a4)86bed1c92

main
11.8 KiB252 linesraw
1// src/kernels/cuda/bf16_gemv.cu - the BF16 GEMV.  See the header for why it is not `s_gemv`.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include "strata/kprof.hpp"
5#include <dpct/dpct.hpp>
6#include "strata/sycl_queue.hpp"
7#include "strata/kernels/bf16_gemv.hpp"
8
9#include "strata/kernels/bf16_bits.hpp"
10
11#include <cstdio>
12#include <cstdlib>
13
14namespace strata::kernels {
15namespace {
16
17constexpr int THREADS = 256;
18
19/// One thread per output row, walking it contiguously.  Kept as the naive reference the split version is
20/// checked against, and used directly for the shapes where the output width is already large.
21__dpct_inline__ void bf16_gemv_naive_kernel(const uint16_t *__restrict__ x,
22                                            const uint16_t *__restrict__ w,
23                                            float *__restrict__ y,
24                                            long long n_in, long long n_out) {
25    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
26    const long long o =
27        (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
28        item_ct1.get_local_id(2);
29    if (o >= n_out) return;
30    const uint16_t* row = w + o * n_in;
31    float acc = 0.0f;
32#pragma unroll
33    for (long long i = 0; i < n_in; ++i)
34        acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]);
35    y[o] = acc;
36}
37
38/// One WARP per output row, lanes striding the reduction axis.  For a fixed `i` consecutive lanes touch
39/// consecutive addresses in this layout, so the load is coalesced - the property that took `gr_read` from
40/// 262 ms/token to 8.9.
41__dpct_inline__ void bf16_gemv_warp_kernel(const uint16_t *__restrict__ x,
42                                           const uint16_t *__restrict__ w,
43                                           float *__restrict__ y,
44                                           long long n_in, long long n_out) {
45    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
46    const int warps_per_block = (int)(item_ct1.get_local_range(2) >> 5);
47    const long long o = (long long)item_ct1.get_group(2) * warps_per_block +
48                        (item_ct1.get_local_id(2) >> 5);
49    if (o >= n_out) return;
50    const int lane = item_ct1.get_local_id(2) & 31;
51    const uint16_t* row = w + o * n_in;
52    float acc = 0.0f;
53#pragma unroll
54    for (long long i = lane; i < n_in; i += 32)
55        acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]);
56    /*
57DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
58masked sub_group function which may not be supported by all compilers or
59runtimes. You may need to adjust the code.
60*/
61#pragma unroll
62    for (int off = 16; off > 0; off >>= 1) acc +=
63        dpct::experimental::shift_sub_group_left(
64            0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
65            acc, off);
66    if (lane == 0) y[o] = acc;
67}
68
69/// TPR lanes cooperate on ONE row's reduction: `threads_per_row` threads each take a strided slice and the
70/// block reduces through shared memory.  Used when the output width is too small to fill the machine.
71__dpct_inline__ void bf16_gemv_split_kernel(const uint16_t *__restrict__ x,
72                                            const uint16_t *__restrict__ w,
73                                            float *__restrict__ y,
74                                            long long n_in, long long n_out,
75                                            int tpr, uint8_t *dpct_local) {
76    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
77    auto scratch = (float *)dpct_local;
78    const long long o = item_ct1.get_group(2);
79    if (o >= n_out) return;
80    const int t = item_ct1.get_local_id(2); // 0 .. tpr-1
81    const uint16_t* row = w + o * n_in;
82    float acc = 0.0f;
83#pragma unroll
84    for (long long i = t; i < n_in; i += tpr)
85        acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]);
86    // block reduction; `tpr` is at most a few hundred, so a tree in shared is enough
87    scratch[t] = acc;
88    item_ct1.barrier(sycl::access::fence_space::local_space);
89#pragma unroll
90    for (int off = tpr >> 1; off > 0; off >>= 1) {
91        if (t < off) scratch[t] += scratch[t + off];
92        /*
93        DPCT1118: SYCL group functions and algorithms must be encountered in
94        converged control flow. You may need to adjust the code.
95        */
96        item_ct1.barrier(sycl::access::fence_space::local_space);
97    }
98    if (t == 0) y[o] = scratch[0];
99}
100
101inline void finish(void *stream, const char *what) try {
102    /*
103    DPCT1010: SYCL uses exceptions to report errors and does not use the
104    error codes. The cudaGetLastError function call was replaced with 0. You
105    need to rewrite this code.
106    */
107    const dpct::err0 e = 0;
108
109    if (stream != nullptr) return;
110    const dpct::err0 s =
111        DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw());
112}
113catch (sycl::exception const &exc) {
114  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
115            << ", line:" << __LINE__ << std::endl;
116  std::exit(1);
117}
118
119}  // namespace
120
121void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream) {
122    if (n_in <= 0 || n_out <= 0) return;
123    // **THIS USED TO ALWAYS USE THE NAIVE KERNEL, AND THE NAIVE KERNEL IS UNCOALESCED.**
124    //
125    // `bf16_gemv_naive_kernel` gives one THREAD per output row and walks the row contiguously, so at a fixed
126    // `i` the 32 threads of a warp read `w[(o+k)*n_in + i]` - addresses `n_in * 2` bytes apart.  Every load in
127    // the kernel's inner loop costs 32 transactions instead of 1.  The comment above that kernel claims it is
128    // "used directly for the shapes where the output width is already large", but nothing ever made that
129    // choice: this function called it unconditionally, at every shape.
130    //
131    // What that costs, from the nsys per-kernel table: **4.66 ms/token across 24 calls, 194 us each** - the
132    // third largest kernel in the engine at the time, moving 1.19 GiB/token at ~210 GB/s where a plain read at
133    // this geometry measures 641 GB/s (`bench/micro/p32_floor.cu`).
134    //
135    // `bf16_gemv_warp_kernel` exists, is checked against this one by `bf16_gemv_parity`, and is coalesced -
136    // consecutive lanes touch consecutive addresses - which is the property `gr_read`'s comment records as
137    // having taken it from 262 ms/token to 8.9.  The threshold below is where warp-per-row has enough rows to
138    // fill the machine: 8 warps per block, so 64 rows is 8 blocks and 128 is 16, against 48 SMs.
139    if (n_out >= 64) {
140        const int warps = THREADS / 32;
141        const unsigned grid = (unsigned) ((n_out + warps - 1) / warps);
142        {
143            auto exp_props = sycl::ext::oneapi::experimental::properties{
144                sycl::ext::oneapi::experimental::use_root_sync};
145
146            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
147                ->template parallel_for<
148                    dpct_kernel_name<class bf16_gemv_warp_kernel_1fb910>>(
149                    sycl::nd_range<3>(sycl::range(1, 1, grid) *
150                                          sycl::range(1, 1, THREADS),
151                                      sycl::range(1, 1, THREADS)),
152                    exp_props,
153                    [=](sycl::nd_item<3> item_ct1)
154                        [[sycl::reqd_sub_group_size(32)]] {
155                            bf16_gemv_warp_kernel(x, w, y, n_in, n_out);
156                        });
157        }
158        finish(stream, "bf16_gemv(warp)");
159        return;
160    }
161    // Below the threshold the warp kernel would leave most of the machine idle, and the naive one is at least
162    // not wasting warps.  It is still uncoalesced, so this is the branch to revisit if a small-output caller
163    // ever shows up hot in the profile.
164    const unsigned grid = (unsigned) ((n_out + THREADS - 1) / THREADS);
165    {
166        auto exp_props = sycl::ext::oneapi::experimental::properties{
167            sycl::ext::oneapi::experimental::use_root_sync};
168
169        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
170            ->template parallel_for<
171                dpct_kernel_name<class bf16_gemv_naive_kernel_7678d1>>(
172                sycl::nd_range<3>(sycl::range(1, 1, grid) *
173                                      sycl::range(1, 1, THREADS),
174                                  sycl::range(1, 1, THREADS)),
175                exp_props, [=](sycl::nd_item<3> item_ct1) {
176                    bf16_gemv_naive_kernel(x, w, y, n_in, n_out);
177                });
178    }
179    finish(stream, "bf16_gemv");
180}
181
182void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out,
183                     int threads_per_row, void* stream) {
184    if (n_in <= 0 || n_out <= 0) return;
185    // WARP-PER-ROW when the caller asks for 32, because that path needs no shared memory and no barrier - and
186    // with 48 output rows it is the configuration that fills the machine.  A `tpr` that is not 32 and not a
187    // power of two is refused rather than quietly rounded, because the tree reduction below needs one.
188    if (threads_per_row == 32) {
189        const int warps = THREADS / 32;
190        const unsigned grid = (unsigned) ((n_out + warps - 1) / warps);
191        {
192            auto exp_props = sycl::ext::oneapi::experimental::properties{
193                sycl::ext::oneapi::experimental::use_root_sync};
194
195            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
196                ->template parallel_for<
197                    dpct_kernel_name<class bf16_gemv_warp_kernel_1f3015>>(
198                    sycl::nd_range<3>(sycl::range(1, 1, grid) *
199                                          sycl::range(1, 1, THREADS),
200                                      sycl::range(1, 1, THREADS)),
201                    exp_props,
202                    [=](sycl::nd_item<3> item_ct1)
203                        [[sycl::reqd_sub_group_size(32)]] {
204                            bf16_gemv_warp_kernel(x, w, y, n_in, n_out);
205                        });
206        }
207        finish(stream, "bf16_gemv_split(warp)");
208        return;
209    }
210    if (threads_per_row <= 0 || (threads_per_row & (threads_per_row - 1)) != 0) {
211        std::fprintf(stderr, "bf16_gemv_split: threads_per_row %d must be a power of two (32 selects the "
212                             "warp-per-row path)\n", threads_per_row);
213        std::exit(1);
214    }
215    const unsigned grid = (unsigned) n_out;
216    /*
217    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
218    limit. To get the device limit, query info::device::max_work_group_size.
219    Adjust the work-group size if needed.
220    */
221    {
222        auto exp_props = sycl::ext::oneapi::experimental::properties{
223            sycl::ext::oneapi::experimental::use_root_sync};
224
225        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
226            ->submit([&](sycl::handler &cgh) {
227                /*
228                DPCT1083: The size of local memory in the migrated code may
229                be different from the original code. Check that the allocated
230                memory size in the migrated code is correct.
231                */
232                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
233                    sycl::range((size_t)threads_per_row * sizeof(float)), cgh);
234
235                cgh.parallel_for<
236                    dpct_kernel_name<class bf16_gemv_split_kernel_adfacf>>(
237                    sycl::nd_range<3>(sycl::range(1, 1, grid) *
238                                          sycl::range(1, 1, threads_per_row),
239                                      sycl::range(1, 1, threads_per_row)),
240                    exp_props, [=](sycl::nd_item<3> item_ct1) {
241                        bf16_gemv_split_kernel(
242                            x, w, y, n_in, n_out, threads_per_row,
243                            dpct_local_acc_ct1
244                                .get_multi_ptr<sycl::access::decorated::no>()
245                                .get());
246                    });
247            });
248    }
249    finish(stream, "bf16_gemv_split");
250}
251
252}  // namespace strata::kernels