okami.mom/strata

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

Niko1221Layer split v1 (step 4): the second stage on its own GPU4572b8f22

main
7.1 KiB153 linesraw
1// src/kernels/cuda/s2_gemv_fast.cu - two levers on the hottest kernel, BOTH MEASURED NEGATIVE OR NEUTRAL.
2//
3// *** THIS FILE IS NAMED "fast" AND IS NOT FASTER.  DO NOT ADOPT IT AS THE FAST PATH. ***
4// It is kept because the negative result is worth more than the file costs: it closes two plausible
5// optimisations and it is the experiment that established the measurement floor.
6//
7// L5 got the S2 GEMV from 10.5 to 86.2 G weights/s by amortising the loads, and left the instruction-count
8// argument confirmed but unfinished.  Two further reductions were obvious, so both were built and measured:
9//
10// LEVER 1 - STAGE `x` IN SHARED MEMORY.  `x` is n_in halves (5 KB at n_embd 2560) and every output row reads
11// all of it, so the generic kernel issues n_out * n_in activation loads per GEMV.  Staging it once per block
12// measured WORSE in every single paired comparison (59-76 G w/s staged against 64-87 G w/s unstaged, across
13// four sweep passes and three thread counts).  The __syncthreads and the copy cost more than the L1/L2 hits
14// they replace - the same 5 KB is already resident and already broadcast.
15//
16// LEVER 2 - A CONSTANT-MEMORY CODE TABLE.  Turn the per-element shifts, masks and int-to-float convert into
17// one broadcast `float4` load per four elements.  Measured NEUTRAL: the two orderings swap between passes
18// with no consistent winner.
19//
20// WHY THE NEGATIVE RESULT IS THE REAL FINDING: run-to-run variance on this machine is now ~20% within a
21// single configuration (quads tpr=32 measured 64.3 to 79.5 G w/s across four passes), because `verify` holds
22// ~97% of six CPU cores.  **The noise floor now EXCEEDS the effect sizes being chased**, so further
23// micro-optimisation of this kernel cannot be evaluated here and should wait for a quiet machine rather than
24// produce more numbers that cannot be distinguished from noise.
25//
26// Both changes alter the summation order or the expression, so this kernel is checked against the naive
27// reference like every other one - being faster is never a reason to be trusted, and being neutral is not
28// either.
29#include "strata/kernels/s_gemv.hpp"
30
31#include <cuda_fp16.h>
32#include <cuda_runtime.h>
33
34#include <cstdio>
35#include <cstdlib>
36
37namespace strata::kernels {
38namespace {
39
40constexpr int QK_S2 = 64;
41constexpr int MAX_SHARED_HALVES = 4096;      // 8 KB of shared for x; n_embd 2560 fits with room
42
43// byte -> the four code values with the -1 bias already applied, in element order (bits 0,2,4,6).
44__constant__ float c_codes[256][4];
45
46bool g_lut_ready[64] = {};   // per device: __constant__ memory is per device (a layer split runs on two)
47
48void ensure_lut() {
49    int dev = 0;
50    cudaGetDevice(&dev);
51    if (dev < 0 || dev >= 64) dev = 0;
52    if (g_lut_ready[dev]) return;
53    float host[256][4];
54    for (int b = 0; b < 256; ++b) {
55        for (int k = 0; k < 4; ++k) {
56            host[b][k] = (float) (((b >> (2 * k)) & 3) - 1);
57        }
58    }
59    const cudaError_t e = cudaMemcpyToSymbol(c_codes, host, sizeof(host));
60    if (e != cudaSuccess) {
61        std::fprintf(stderr, "s2_gemv_fast: cudaMemcpyToSymbol failed: %s\n", cudaGetErrorString(e));
62        std::exit(1);
63    }
64    g_lut_ready[dev] = true;
65}
66
67// One block per output row.  `staged` says whether x was copied to shared, so the SAME kernel covers both
68// configurations and the bench can measure them against each other with nothing else changed.
69template <bool STAGE_X>
70__global__ void s2_gemv_fast_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes,
71                                    const float* __restrict__ scales, float* __restrict__ y, long long n_in,
72                                    long long n_out, int threads_per_row) {
73    extern __shared__ float smem[];
74    __half* sx = reinterpret_cast<__half*>(smem);           // [threads_per_row, ...] partials live after
75    float* partial = smem + (STAGE_X ? (MAX_SHARED_HALVES / 2) : 0);
76
77    const long long o = blockIdx.x;
78    if (o >= n_out) return;
79    const int tid = threadIdx.x;
80
81    if (STAGE_X) {
82        const __half* xh = reinterpret_cast<const __half*>(x);
83        for (long long i = tid; i < n_in; i += threads_per_row) sx[i] = xh[i];
84        __syncthreads();
85    }
86
87    const long long n_quads = n_in / 4;
88    const uint8_t* c = codes + o * n_quads;
89    const float* s = scales + o * (n_in / QK_S2);
90
91    float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f;
92    for (long long q = tid; q < n_quads; q += threads_per_row) {
93        const uint8_t byte = c[q];                          // ONE load for four codes
94        const float d = s[q >> 4];                          // (q*4) >> 6
95        const float4 cv = *reinterpret_cast<const float4*>(&c_codes[byte][0]);   // one broadcast load
96        if (STAGE_X) {
97            const __half2 h01 = *reinterpret_cast<const __half2*>(&sx[q * 4]);
98            const __half2 h23 = *reinterpret_cast<const __half2*>(&sx[q * 4 + 2]);
99            a0 += cv.x * d * __low2float(h01);
100            a1 += cv.y * d * __high2float(h01);
101            a2 += cv.z * d * __low2float(h23);
102            a3 += cv.w * d * __high2float(h23);
103        } else {
104            const uint2 xw2 = *reinterpret_cast<const uint2*>(x + q * 4);
105            const __half2 h01 = *reinterpret_cast<const __half2*>(&xw2.x);
106            const __half2 h23 = *reinterpret_cast<const __half2*>(&xw2.y);
107            a0 += cv.x * d * __low2float(h01);
108            a1 += cv.y * d * __high2float(h01);
109            a2 += cv.z * d * __low2float(h23);
110            a3 += cv.w * d * __high2float(h23);
111        }
112    }
113    partial[tid] = (a0 + a1) + (a2 + a3);
114    __syncthreads();
115    for (int step = threads_per_row / 2; step > 0; step >>= 1) {
116        if (tid < step) partial[tid] += partial[tid + step];
117        __syncthreads();
118    }
119    if (tid == 0) y[o] = partial[0];
120}
121
122}  // namespace
123
124void s2_gemv_fast(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in,
125                  int64_t n_out, int threads_per_row, bool stage_x) {
126    if (n_in <= 0 || n_out <= 0) return;
127    if (n_in % 4 != 0 || n_in % QK_S2 != 0) {
128        std::fprintf(stderr, "s2_gemv_fast: n_in %lld must be a multiple of %d\n", (long long) n_in, QK_S2);
129        std::exit(1);
130    }
131    ensure_lut();
132    if (stage_x && n_in > MAX_SHARED_HALVES) {
133        std::fprintf(stderr, "s2_gemv_fast: n_in %lld exceeds the %d-half shared staging limit\n",
134                     (long long) n_in, MAX_SHARED_HALVES);
135        std::exit(1);
136    }
137    const size_t smem = (stage_x ? MAX_SHARED_HALVES * sizeof(__half) : 0) +
138                        (size_t) threads_per_row * sizeof(float);
139    if (stage_x) {
140        s2_gemv_fast_kernel<true><<<(unsigned) n_out, threads_per_row, smem>>>(x, codes, scales, y, n_in, n_out,
141                                                                             threads_per_row);
142    } else {
143        s2_gemv_fast_kernel<false><<<(unsigned) n_out, threads_per_row, smem>>>(x, codes, scales, y, n_in, n_out,
144                                                                              threads_per_row);
145    }
146    const cudaError_t e = cudaDeviceSynchronize();
147    if (e != cudaSuccess) {
148        std::fprintf(stderr, "s2_gemv_fast: %s\n", cudaGetErrorString(e));
149        std::exit(1);
150    }
151}
152
153}  // namespace strata::kernels