okami.mom/strata

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

Niko1221Merge branch 'f-split-int' into f-split-fitfa6367a98

main
9.6 KiB189 linesraw
1// src/kernels/cuda/bf16_gemv.cu - the BF16 GEMV.  See the header for why it is not `s_gemv`.
2#include "strata/kernels/bf16_gemv.hpp"
3
4#include "strata/kernels/bf16_bits.hpp"
5
6#include <cuda_runtime.h>
7
8#include <cstdio>
9#include <cstdlib>
10
11namespace strata::kernels {
12namespace {
13
14constexpr int THREADS = 256;
15
16/// One thread per output row, walking it contiguously.  Kept as the naive reference the split version is
17/// checked against, and used directly for the shapes where the output width is already large.
18__global__ void bf16_gemv_naive_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
19                                       float* __restrict__ y, long long n_in, long long n_out) {
20    const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x;
21    if (o >= n_out) return;
22    const uint16_t* row = w + o * n_in;
23    float acc = 0.0f;
24    for (long long i = 0; i < n_in; ++i)
25        acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]);
26    y[o] = acc;
27}
28
29/// One WARP per output row, lanes striding the reduction axis.  For a fixed `i` consecutive lanes touch
30/// consecutive addresses in this layout, so the load is coalesced - the property that took `gr_read` from
31/// 262 ms/token to 8.9.
32__global__ void bf16_gemv_warp_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
33                                      float* __restrict__ y, long long n_in, long long n_out) {
34    const int warps_per_block = (int) (blockDim.x >> 5);
35    const long long o = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
36    if (o >= n_out) return;
37    const int lane = threadIdx.x & 31;
38    const uint16_t* row = w + o * n_in;
39    float acc = 0.0f;
40    for (long long i = lane; i < n_in; i += 32)
41        acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]);
42    for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off);
43    if (lane == 0) y[o] = acc;
44}
45
46/// TPR lanes cooperate on ONE row's reduction: `threads_per_row` threads each take a strided slice and the
47/// block reduces through shared memory.  Used when the output width is too small to fill the machine.
48__global__ void bf16_gemv_split_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
49                                       float* __restrict__ y, long long n_in, long long n_out, int tpr) {
50    extern __shared__ float scratch[];
51    const long long o = blockIdx.x;
52    if (o >= n_out) return;
53    const int t = threadIdx.x;                 // 0 .. tpr-1
54    const uint16_t* row = w + o * n_in;
55    float acc = 0.0f;
56    for (long long i = t; i < n_in; i += tpr)
57        acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]);
58    // block reduction; `tpr` is at most a few hundred, so a tree in shared is enough
59    scratch[t] = acc;
60    __syncthreads();
61    for (int off = tpr >> 1; off > 0; off >>= 1) {
62        if (t < off) scratch[t] += scratch[t + off];
63        __syncthreads();
64    }
65    if (t == 0) y[o] = scratch[0];
66}
67
68/// TWO weight matrices from one read of x - llama.cpp's `*_mul_mat_multi` shape.  One warp computes row `o`
69/// of `w1` and row `o` of `w2` with two independent accumulators over the SAME lane-strided loop, so each
70/// accumulator sees the addend sequence its standalone `bf16_gemv_warp_kernel` run gave it: bitwise equal
71/// (checked by `bf16_gemv_pair_parity`).  Rows past a matrix's `n_out` skip that accumulator only.
72__global__ void bf16_gemv_pair_warp_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w1,
73                                           float* __restrict__ y1, long long n_out1,
74                                           const uint16_t* __restrict__ w2, float* __restrict__ y2,
75                                           long long n_out2, long long n_in) {
76    const int warps_per_block = (int) (blockDim.x >> 5);
77    const long long o = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
78    const int lane = threadIdx.x & 31;
79    const long long n_out = n_out1 > n_out2 ? n_out1 : n_out2;
80    if (o >= n_out) return;
81    const int run1 = o < n_out1, run2 = o < n_out2;
82    const uint16_t* r1 = w1 + o * n_in;
83    const uint16_t* r2 = w2 + o * n_in;
84    float acc1 = 0.0f, acc2 = 0.0f;
85    for (long long i = lane; i < n_in; i += 32) {
86        const float xv = f32_from_bf16(x[i]);
87        if (run1) acc1 += xv * f32_from_bf16(r1[i]);
88        if (run2) acc2 += xv * f32_from_bf16(r2[i]);
89    }
90    if (run1) {
91        float a = acc1;
92        for (int off = 16; off > 0; off >>= 1) a += __shfl_down_sync(0xFFFFFFFFu, a, off);
93        if (lane == 0) y1[o] = a;
94    }
95    if (run2) {
96        float a = acc2;
97        for (int off = 16; off > 0; off >>= 1) a += __shfl_down_sync(0xFFFFFFFFu, a, off);
98        if (lane == 0) y2[o] = a;
99    }
100}
101
102inline void finish(void* stream, const char* what) {
103    const cudaError_t e = cudaGetLastError();
104    if (e != cudaSuccess) {
105        std::fprintf(stderr, "%s launch: %s\n", what, cudaGetErrorString(e));
106        std::exit(1);
107    }
108    if (stream != nullptr) return;
109    const cudaError_t s = cudaDeviceSynchronize();
110    if (s != cudaSuccess) {
111        std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(s));
112        std::exit(1);
113    }
114}
115
116}  // namespace
117
118void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream) {
119    if (n_in <= 0 || n_out <= 0) return;
120    // **THIS USED TO ALWAYS USE THE NAIVE KERNEL, AND THE NAIVE KERNEL IS UNCOALESCED.**
121    //
122    // `bf16_gemv_naive_kernel` gives one THREAD per output row and walks the row contiguously, so at a fixed
123    // `i` the 32 threads of a warp read `w[(o+k)*n_in + i]` - addresses `n_in * 2` bytes apart.  Every load in
124    // the kernel's inner loop costs 32 transactions instead of 1.  The comment above that kernel claims it is
125    // "used directly for the shapes where the output width is already large", but nothing ever made that
126    // choice: this function called it unconditionally, at every shape.
127    //
128    // What that costs, from the nsys per-kernel table: **4.66 ms/token across 24 calls, 194 us each** - the
129    // third largest kernel in the engine at the time, moving 1.19 GiB/token at ~210 GB/s where a plain read at
130    // this geometry measures 641 GB/s (`bench/micro/p32_floor.cu`).
131    //
132    // `bf16_gemv_warp_kernel` exists, is checked against this one by `bf16_gemv_parity`, and is coalesced -
133    // consecutive lanes touch consecutive addresses - which is the property `gr_read`'s comment records as
134    // having taken it from 262 ms/token to 8.9.  The threshold below is where warp-per-row has enough rows to
135    // fill the machine: 8 warps per block, so 64 rows is 8 blocks and 128 is 16, against 48 SMs.
136    if (n_out >= 64) {
137        const int warps = THREADS / 32;
138        const unsigned grid = (unsigned) ((n_out + warps - 1) / warps);
139        bf16_gemv_warp_kernel<<<grid, THREADS, 0, (cudaStream_t) stream>>>(x, w, y, n_in, n_out);
140        finish(stream, "bf16_gemv(warp)");
141        return;
142    }
143    // Below the threshold the warp kernel would leave most of the machine idle, and the naive one is at least
144    // not wasting warps.  It is still uncoalesced, so this is the branch to revisit if a small-output caller
145    // ever shows up hot in the profile.
146    const unsigned grid = (unsigned) ((n_out + THREADS - 1) / THREADS);
147    bf16_gemv_naive_kernel<<<grid, THREADS, 0, (cudaStream_t) stream>>>(x, w, y, n_in, n_out);
148    finish(stream, "bf16_gemv");
149}
150
151void bf16_gemv_pair(const uint16_t* x, const uint16_t* w1, float* y1, int64_t n_out1, const uint16_t* w2,
152                    float* y2, int64_t n_out2, int64_t n_in, void* stream) {
153    if (n_in <= 0 || (n_out1 <= 0 && n_out2 <= 0)) return;
154    // THE PAIR KERNEL IS THE WARP-PER-ROW ACCUMULATION on both sides, so it is bitwise what
155    // `bf16_gemv` (n_out >= 64) and `bf16_gemv_split` at tpr 32 produced.  Callers whose standalone path
156    // was the NAIVE kernel (a small `n_out` with the plain entry) must not use this.
157    const int warps = THREADS / 32;
158    const long long n_out = n_out1 > n_out2 ? n_out1 : n_out2;
159    const unsigned grid = (unsigned) ((n_out + warps - 1) / warps);
160    bf16_gemv_pair_warp_kernel<<<grid, THREADS, 0, (cudaStream_t) stream>>>(
161        x, w1, y1, n_out1, w2, y2, n_out2, n_in);
162    finish(stream, "bf16_gemv_pair");
163}
164
165void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out,
166                     int threads_per_row, void* stream) {
167    if (n_in <= 0 || n_out <= 0) return;
168    // WARP-PER-ROW when the caller asks for 32, because that path needs no shared memory and no barrier - and
169    // with 48 output rows it is the configuration that fills the machine.  A `tpr` that is not 32 and not a
170    // power of two is refused rather than quietly rounded, because the tree reduction below needs one.
171    if (threads_per_row == 32) {
172        const int warps = THREADS / 32;
173        const unsigned grid = (unsigned) ((n_out + warps - 1) / warps);
174        bf16_gemv_warp_kernel<<<grid, THREADS, 0, (cudaStream_t) stream>>>(x, w, y, n_in, n_out);
175        finish(stream, "bf16_gemv_split(warp)");
176        return;
177    }
178    if (threads_per_row <= 0 || (threads_per_row & (threads_per_row - 1)) != 0) {
179        std::fprintf(stderr, "bf16_gemv_split: threads_per_row %d must be a power of two (32 selects the "
180                             "warp-per-row path)\n", threads_per_row);
181        std::exit(1);
182    }
183    const unsigned grid = (unsigned) n_out;
184    bf16_gemv_split_kernel<<<grid, threads_per_row, (size_t) threads_per_row * sizeof(float),
185                             (cudaStream_t) stream>>>(x, w, y, n_in, n_out, threads_per_row);
186    finish(stream, "bf16_gemv_split");
187}
188
189}  // namespace strata::kernels