okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
01529aaa8
main
1// src/kernels/cuda/s2_gemv.cu - P2.S2: the S2 GEMV, one thread per output row. 2// 3// Naive per the phase rule: dequantize on the fly, FP32 accumulation inside the row, no shared memory, no 4// vector loads, no __ldg hints. Phase 3 changes this file; the parity test is what says whether a change is 5// still right. 6#include "strata/kernels/s2_gemv.hpp" 7 8#include <cuda_fp16.h> 9#include <cuda_runtime.h> 10 11#include <cstdio> 12#include <cstdlib> 13 14namespace strata::kernels { 15namespace { 16 17constexpr int QK = 64; 18 19__global__ void s2_gemv_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes, 20 const float* __restrict__ scales, float* __restrict__ y, long long n_in, 21 long long n_out) { 22 const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x; 23 if (o >= n_out) return; 24 25 const long long nb = n_in / QK; 26 const uint8_t* c = codes + o * nb * (QK / 4); 27 const float* s = scales + o * nb; 28 29 float acc = 0.0f; 30 for (long long b = 0; b < nb; ++b) { 31 const float d = s[b]; 32 const uint8_t* cb = c + b * (QK / 4); 33 const uint16_t* xb = x + b * QK; 34 for (int j = 0; j < QK; ++j) { 35 // (code - 1) in the INTEGER domain, then the group scale, then the activation; the CPU reference 36 // below is written in the same order so the two differ only by floating-point contraction. 37 const int code = (cb[j >> 2] >> ((j & 3) * 2)) & 0x03; 38 acc += (float) (code - 1) * d * __half2float(__ushort_as_half(xb[j])); 39 } 40 } 41 y[o] = acc; 42} 43 44} // namespace 45 46void s2_gemv(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in, 47 int64_t n_out) { 48 if (n_in <= 0 || n_out <= 0) return; 49 if (n_in % QK != 0) { 50 std::fprintf(stderr, "s2_gemv: n_in %lld is not a multiple of %d\n", (long long) n_in, QK); 51 std::exit(1); 52 } 53 const int threads = 128; 54 const long long blocks = (n_out + threads - 1) / threads; 55 s2_gemv_kernel<<<(unsigned) blocks, threads>>>(x, codes, scales, y, n_in, n_out); 56 const cudaError_t e = cudaDeviceSynchronize(); 57 if (e != cudaSuccess) { 58 std::fprintf(stderr, "s2_gemv: %s\n", cudaGetErrorString(e)); 59 std::exit(1); 60 } 61} 62 63} // namespace strata::kernels