okami.mom/strata

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

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

main
12.6 KiB229 linesraw
1// src/kernels/cuda/kv_q8.cu - see include/strata/kernels/kv_q8.hpp.
2#include "strata/kernels/kv_q8.hpp"
3#include "strata/kernels/f16_bits.hpp"
4
5#include <cuda_runtime.h>
6
7#include <cstdio>
8#include <cstdlib>
9
10namespace strata::kernels {
11namespace {
12
13void check(const char* what) {
14    const cudaError_t e = cudaGetLastError();
15    if (e != cudaSuccess) {
16        std::fprintf(stderr, "kv_q8: %s: %s\n", what, cudaGetErrorString(e));
17        std::exit(1);
18    }
19}
20
21void validate(const QsaShapes& s, const char* what) {
22    if (s.head_dim % KV_Q8_GROUP != 0 || s.n_head_kv <= 0 || s.page_size <= 0) {
23        std::fprintf(stderr, "kv_q8: %s: head_dim %lld must be a multiple of %d\n", what, (long long) s.head_dim,
24                     KV_Q8_GROUP);
25        std::exit(1);
26    }
27}
28
29// One block = one 64-value group of one KV head of K (blockIdx.z = 0) or V (1); 64 threads, one value each.
30// MULTI (S26 STRATA_LFUSE): blockIdx.z = 2 * token + (K / V); token j reads step + j * step_stride and its rows at
31// kcur / vcur + j * cur_stride - every token's code is the single launch's
32template <bool MULTI = false>
33__global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict__ v_q,
34                                    uint16_t* __restrict__ k_scale, uint16_t* __restrict__ v_scale,
35                                    const int32_t* __restrict__ table, const int32_t* __restrict__ step,
36                                    const float* __restrict__ kcur, const float* __restrict__ vcur, int kv_heads,
37                                    int head_dim, int page_size, KvHostPools host, int step_stride = 0,
38                                    int cur_stride = 0) {
39    if constexpr (MULTI) {
40        const int j = blockIdx.z >> 1;
41        step += (size_t) j * step_stride; kcur += (size_t) j * cur_stride; vcur += (size_t) j * cur_stride;
42    }
43    const long long pos = (long long) __ldg(step + kStepPos);
44    const int h = blockIdx.x, g = blockIdx.y, t = threadIdx.x;
45    const bool is_v = MULTI ? (blockIdx.z & 1) == 1 : blockIdx.z == 1;
46    const int groups = head_dim / KV_Q8_GROUP;
47    const float x = (is_v ? vcur : kcur)[h * head_dim + g * KV_Q8_GROUP + t];
48    // max |x| over the 64 values: two warps, then combine through shared memory in a fixed order
49    float a = fabsf(x);
50    for (int o = 16; o > 0; o >>= 1) a = fmaxf(a, __shfl_xor_sync(0xffffffffu, a, o));
51    __shared__ float warp_max[2];
52    if ((t & 31) == 0) warp_max[t >> 5] = a;
53    __syncthreads();
54    const float amax = fmaxf(warp_max[0], warp_max[1]);
55    const uint16_t sbits = f16_from_f32(amax / 127.0f);
56    const float sf = f32_from_f16(sbits);                          // quantize against the STORED scale
57    int q = 0;
58    if (sf > 0.0f) {
59        q = __float2int_rn(x / sf);
60        q = q < -127 ? -127 : (q > 127 ? 127 : q);
61    }
62    // KV streaming: the host copy (identity layout) always, the VRAM page only if the block is resident
63    const long long page = (long long) table[pos / page_size];
64    if (page >= 0) {
65        const long long row = (page * kv_heads + h) * page_size + (pos % page_size);
66        (is_v ? v_q : k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q;
67        if (t == 0) (is_v ? v_scale : k_scale)[row * groups + g] = sbits;
68    }
69    if (host.k_q != nullptr) {
70        const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size);
71        (is_v ? host.v_q : host.k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q;
72        if (t == 0) (is_v ? host.v_scale : host.k_scale)[row * groups + g] = sbits;
73    }
74}
75
76// One thread = 4 consecutive values of one cell and head (as the FP16 gather does with uint2).  This is the gather
77// the ready-made engine runs; the experimental build's 8-wide kernel is below it.
78__global__ void kv_gather_q8_kernel(const int8_t* __restrict__ k_q, const int8_t* __restrict__ v_q,
79                                    const uint16_t* __restrict__ k_scale, const uint16_t* __restrict__ v_scale,
80                                    const int32_t* __restrict__ table, const int32_t* __restrict__ ids,
81                                    const int32_t* __restrict__ step, int kv_heads, int head_dim, int page_size,
82                                    uint16_t* __restrict__ k_scratch, uint16_t* __restrict__ v_scratch) {
83    const long long n_ids = (long long) __ldg(step + kStepWidth);
84    const int per = head_dim / 4;
85    const long long total = n_ids * kv_heads * per;
86    const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x;
87    if (i >= total) return;
88    const long long id = i / (kv_heads * (long long) per);
89    const int rem = (int) (i % (kv_heads * (long long) per));
90    const int h = rem / per, q4 = rem - h * per;
91    const int cell = ids[id];
92    const long long page = (long long) table[cell / page_size];
93    const long long row = (page * kv_heads + h) * page_size + (cell % page_size);
94    const int d = q4 * 4;
95    const int groups = head_dim / KV_Q8_GROUP;
96    const float ks = f32_from_f16(k_scale[row * groups + d / KV_Q8_GROUP]);
97    const float vs = f32_from_f16(v_scale[row * groups + d / KV_Q8_GROUP]);
98    const char4 kc = reinterpret_cast<const char4*>(k_q + row * head_dim)[q4];
99    const char4 vc = reinterpret_cast<const char4*>(v_q + row * head_dim)[q4];
100    ushort4 ko, vo;
101    ko.x = f16_from_f32((float) kc.x * ks); ko.y = f16_from_f32((float) kc.y * ks);
102    ko.z = f16_from_f32((float) kc.z * ks); ko.w = f16_from_f32((float) kc.w * ks);
103    vo.x = f16_from_f32((float) vc.x * vs); vo.y = f16_from_f32((float) vc.y * vs);
104    vo.z = f16_from_f32((float) vc.z * vs); vo.w = f16_from_f32((float) vc.w * vs);
105    const long long dst = (id * kv_heads + h) * (long long) per + q4;
106    reinterpret_cast<ushort4*>(k_scratch)[dst] = ko;
107    reinterpret_cast<ushort4*>(v_scratch)[dst] = vo;
108}
109
110#if defined(STRATA_EXPERIMENTAL_SM60)
111// One thread = 8 consecutive values of one cell and head: an 8-byte `uint2` load of codes and a 16-byte `uint4`
112// store of the dequantized fp16.  The 8 values share one 64-value group, so one scale is loaded per thread and
113// the arithmetic stays `(float) code * scale -> f16_from_f32`, i.e. bitwise the same as the previous 4-wide
114// version (whose char4 loads became these uint2 loads).  `load8_q8` in qsa_decode_attn.cu reads 8 int8 the
115// same way; this is the gather's other half.  Only in the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON):
116// the ready-made engine keeps exactly the 4-wide kernel above, so its gather is bit for bit the release engine's.
117__device__ __forceinline__ uint32_t q8_pair_to_f16x2(const int8_t* c, float s) {
118    return (uint32_t) f16_from_f32((float) c[0] * s) | ((uint32_t) f16_from_f32((float) c[1] * s) << 16);
119}
120
121__global__ void kv_gather_q8_wide_kernel(const int8_t* __restrict__ k_q, const int8_t* __restrict__ v_q,
122                                         const uint16_t* __restrict__ k_scale, const uint16_t* __restrict__ v_scale,
123                                         const int32_t* __restrict__ table, const int32_t* __restrict__ ids,
124                                         const int32_t* __restrict__ step, int kv_heads, int head_dim, int page_size,
125                                         uint16_t* __restrict__ k_scratch, uint16_t* __restrict__ v_scratch) {
126    const long long n_ids = (long long) __ldg(step + kStepWidth);
127    const int per = head_dim / 8;
128    const long long total = n_ids * kv_heads * per;
129    const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x;
130    if (i >= total) return;
131    const long long id = i / (kv_heads * (long long) per);
132    const int rem = (int) (i % (kv_heads * (long long) per));
133    const int h = rem / per, q8 = rem - h * per;
134    const int cell = ids[id];
135    const long long page = (long long) table[cell / page_size];
136    const long long row = (page * kv_heads + h) * page_size + (cell % page_size);
137    const int d = q8 * 8;                    // 8 divides KV_Q8_GROUP, so all 8 values share the group's scale
138    const int groups = head_dim / KV_Q8_GROUP;
139    const float ks = f32_from_f16(k_scale[row * groups + d / KV_Q8_GROUP]);
140    const float vs = f32_from_f16(v_scale[row * groups + d / KV_Q8_GROUP]);
141    const uint2 kraw = *reinterpret_cast<const uint2*>(k_q + row * head_dim + d);   // one 8-byte load
142    const uint2 vraw = *reinterpret_cast<const uint2*>(v_q + row * head_dim + d);
143    const int8_t* kc = reinterpret_cast<const int8_t*>(&kraw);
144    const int8_t* vc = reinterpret_cast<const int8_t*>(&vraw);
145    uint4 ko, vo;
146    ko.x = q8_pair_to_f16x2(kc + 0, ks); ko.y = q8_pair_to_f16x2(kc + 2, ks);
147    ko.z = q8_pair_to_f16x2(kc + 4, ks); ko.w = q8_pair_to_f16x2(kc + 6, ks);
148    vo.x = q8_pair_to_f16x2(vc + 0, vs); vo.y = q8_pair_to_f16x2(vc + 2, vs);
149    vo.z = q8_pair_to_f16x2(vc + 4, vs); vo.w = q8_pair_to_f16x2(vc + 6, vs);
150    const long long dst = (id * kv_heads + h) * (long long) per + q8;
151    reinterpret_cast<uint4*>(k_scratch)[dst] = ko;
152    reinterpret_cast<uint4*>(v_scratch)[dst] = vo;
153}
154
155// The current device is below sm_75 (per device: a layer split can mix cards); STRATA_Q8_GATHER_WIDE=0 turns the
156// 8-wide gather off (A/B).  The wide kernel is bitwise identical, so this only decides speed.  Mirrors
157// qsa_decode_attn.cu's pre75_attn.
158bool pre75_q8_gather() {
159    static const bool off = [] {
160        const char* e = std::getenv("STRATA_Q8_GATHER_WIDE");
161        return e != nullptr && e[0] == '0';
162    }();
163    static int cc[64] = {};
164    int dev = 0;
165    if (off) return false;
166    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
167    if (cc[dev] == 0) {
168        int major = 0, minor = 0;
169        if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
170            cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) {
171            cudaGetLastError();
172            return false;
173        }
174        cc[dev] = 10 * major + minor;
175    }
176    return cc[dev] < 75;
177}
178#endif  // STRATA_EXPERIMENTAL_SM60
179
180}  // namespace
181
182void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table,
183                       const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream,
184                       const KvHostPools* host) {
185    validate(s, "kv_append_q8");
186    const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), 2);
187    kv_append_q8_kernel<<<grid, KV_Q8_GROUP, 0, (cudaStream_t) stream>>>(
188        k_q, v_q, k_scale, v_scale, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim,
189        (int) s.page_size, host ? *host : KvHostPools{});
190    check("kv_append_q8 launch");
191}
192
193void kv_append_q8_steps(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table,
194                        const int32_t* step, int step_stride, const float* kcur, const float* vcur, int cur_stride,
195                        int n_tok, const QsaShapes& s, void* stream, const KvHostPools* host) {
196    validate(s, "kv_append_q8 (steps)");
197    if (n_tok < 1) return;
198    const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), (unsigned) (2 * n_tok));
199    kv_append_q8_kernel<true><<<grid, KV_Q8_GROUP, 0, (cudaStream_t) stream>>>(
200        k_q, v_q, k_scale, v_scale, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim,
201        (int) s.page_size, host ? *host : KvHostPools{}, step_stride, cur_stride);
202    check("kv_append_q8 (steps) launch");
203}
204
205void kv_gather_q8_step(const int8_t* k_q, const int8_t* v_q, const uint16_t* k_scale, const uint16_t* v_scale,
206                       const int32_t* page_table, const int32_t* ids, const int32_t* step, int64_t max_ids,
207                       const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) {
208    validate(s, "kv_gather_q8");
209    if (max_ids <= 0) return;
210#if defined(STRATA_EXPERIMENTAL_SM60)
211    if (pre75_q8_gather()) {
212        const long long total = max_ids * s.n_head_kv * (s.head_dim / 8);
213        const unsigned blocks = (unsigned) ((total + 255) / 256);
214        kv_gather_q8_wide_kernel<<<blocks, 256, 0, (cudaStream_t) stream>>>(
215            k_q, v_q, k_scale, v_scale, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim,
216            (int) s.page_size, k_scratch, v_scratch);
217        check("kv_gather_q8 wide launch");
218        return;
219    }
220#endif
221    const long long total = max_ids * s.n_head_kv * (s.head_dim / 4);
222    const unsigned blocks = (unsigned) ((total + 255) / 256);
223    kv_gather_q8_kernel<<<blocks, 256, 0, (cudaStream_t) stream>>>(
224        k_q, v_q, k_scale, v_scale, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size,
225        k_scratch, v_scratch);
226    check("kv_gather_q8 launch");
227}
228
229}  // namespace strata::kernels