okami.mom/strata

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

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

main
17.0 KiB367 linesraw
1// src/kernels/cuda/kv_q4.cu - see include/strata/kernels/kv_q4.hpp. Q4_0 KV with Walsh-Hadamard rotation
2// (from PR #21 by code-martin; KV-streaming integration and the deterministic group maximum added on merge).
3#define DPCT_PROFILING_ENABLED
4#include <sycl/sycl.hpp>
5#include "strata/kprof.hpp"
6#include <dpct/dpct.hpp>
7#include "strata/sycl_queue.hpp"
8#include "strata/kernels/kv_q4.hpp"
9#include "strata/kernels/f16_bits.hpp"
10#include "strata/kernels/kv_stream.hpp"
11
12#include <cstdio>
13#include <cstdlib>
14
15namespace strata::kernels {
16namespace {
17
18void check(const char* what) {
19    /*
20    DPCT1010: SYCL uses exceptions to report errors and does not use the
21    error codes. The cudaGetLastError function call was replaced with 0. You
22    need to rewrite this code.
23    */
24    const dpct::err0 e = 0;
25}
26
27// Fast Walsh-Hadamard Transform for N = 256: one warp per row, 8 values per lane in registers.
28// Orthonormal (scale 1/sqrt(256) = 1/16), so it is its own inverse.
29__dpct_inline__ void fwht256_kernel(const float *__restrict__ src,
30                                    float *__restrict__ dst, int64_t n_rows,
31                                    float scale) {
32    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
33    constexpr int warp_size = 32;
34    constexpr int N = 256;
35    constexpr int el_w = N / warp_size;   // 8
36
37    const int64_t r =
38        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(1) +
39        item_ct1.get_local_id(1);
40    if (r >= n_rows) return;
41
42    const float* row_src = src + r * N;
43    float* row_dst = dst + r * N;
44
45    float reg[el_w];
46    const int lane = item_ct1.get_local_id(2);
47
48#pragma unroll
49    for (int i = 0; i < el_w; ++i) reg[i] = row_src[i * warp_size + lane] * scale;
50
51    // the low 5 index bits live across lanes
52#pragma unroll
53    for (int h = 1; h < warp_size; h *= 2) {
54#pragma unroll
55        for (int j = 0; j < el_w; ++j) {
56            const float val = reg[j];
57            /*
58            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
59            feature masked sub_group function which may not be supported by all
60            compilers or runtimes. You may need to adjust the code.
61            */
62            const float val2 = dpct::experimental::permute_sub_group_by_xor(
63                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
64                val, h);
65            reg[j] = (lane & h) == 0 ? val + val2 : val2 - val;
66        }
67    }
68    // the high 3 bits across each lane's registers
69#pragma unroll
70    for (int h = warp_size; h < N; h *= 2) {
71        const int step = h / warp_size;
72#pragma unroll
73        for (int j = 0; j < el_w; j += 2 * step) {
74#pragma unroll
75            for (int k = 0; k < step; ++k) {
76                const float x = reg[j + k];
77                const float y = reg[j + k + step];
78                reg[j + k] = x + y;
79                reg[j + k + step] = x - y;
80            }
81        }
82    }
83#pragma unroll
84    for (int i = 0; i < el_w; ++i) row_dst[i * warp_size + lane] = reg[i];
85}
86
87// One 32-value group in one warp (lane = element), ggml's q4_0: d = (the value of largest |x|) / -8,
88// q = clamp(trunc(x / d + 8.5), 0, 15). Returns the scale bits; `byte` is lane t's packed byte for t < 16
89// (element t in the low nibble, t + 16 in the high one). Ties in |x| resolve to the larger value in EVERY lane,
90// so all lanes agree on d (a plain `a > amax` could leave lanes with opposite signs and one block two scales).
91__dpct_inline__ uint16_t q4_group(float x, int lane, uint8_t &byte) {
92    float amax = sycl::fabs(x), mval = x;
93#pragma unroll
94    for (int o = 16; o > 0; o >>= 1) {
95        /*
96        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
97        feature masked sub_group function which may not be supported by all
98        compilers or runtimes. You may need to adjust the code.
99        */
100        const float a = dpct::experimental::permute_sub_group_by_xor(
101            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
102            amax, o);
103        /*
104        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
105        feature masked sub_group function which may not be supported by all
106        compilers or runtimes. You may need to adjust the code.
107        */
108        const float v = dpct::experimental::permute_sub_group_by_xor(
109            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
110            mval, o);
111        if (a > amax || (a == amax && v > mval)) { amax = a; mval = v; }
112    }
113    const float d = mval / -8.0f;
114    const float id = d != 0.0f ? 1.0f / d : 0.0f;
115    int q = sycl::vec<float, 1>{(x * id + 8.5f)}
116                .convert<int, sycl::rounding_mode::rtz>()[0];
117    const uint8_t qc = (uint8_t) (q < 0 ? 0 : (q > 15 ? 15 : q));
118    /*
119    DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
120    masked sub_group function which may not be supported by all compilers or
121    runtimes. You may need to adjust the code.
122    */
123    const uint8_t qhi = dpct::experimental::shift_sub_group_left(
124        0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), qc,
125        16);
126    byte = (uint8_t) (qc | (qhi << 4));
127    (void) lane;
128    return f16_from_f32(d);
129}
130
131__dpct_inline__ void q4_store(uint8_t *pool, long long row, int b, int lane,
132                              uint16_t d, uint8_t byte) {
133    block_q4_0* blk = reinterpret_cast<block_q4_0*>(pool + row * (long long) sizeof(block_q4_0) * 8) + b;
134    if (lane == 0) blk->d = d;
135    if (lane < 16) blk->qs[lane] = byte;
136}
137
138// One block = one 32-value group of one KV head of K (plane 0) or V (plane 1) for token step_idx; 32 threads.
139__dpct_inline__ void
140kv_append_q4_kernel(uint8_t *__restrict__ k_q4, uint8_t *__restrict__ v_q4,
141                    const int32_t *__restrict__ table,
142                    const int32_t *__restrict__ step, int step_stride,
143                    int planes, const float *__restrict__ kcur,
144                    const float *__restrict__ vcur, int kv_heads, int head_dim,
145                    int page_size, KvHostPools host) {
146    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
147    const int step_idx = (int)(item_ct1.get_group(0) / (unsigned)planes);
148    const bool is_v = (item_ct1.get_group(0) % (unsigned)planes) == 1u;
149    /*
150    DPCT1098: The '*' expression is used instead of the __ldg call. These
151    two expressions do not provide the exact same functionality. Check the
152    generated code for potential precision and/or performance issues.
153    */
154    const long long pos =
155        (long long)*(step + (long long)step_idx * step_stride + kStepPos);
156    const int h = item_ct1.get_group(2), b = item_ct1.get_group(1),
157              t = item_ct1.get_local_id(2);
158    const long long step_off = (long long) step_idx * kv_heads * head_dim;
159    const float x = (is_v ? vcur : kcur)[step_off + h * head_dim + b * QK4_0 + t];
160    uint8_t byte;
161    const uint16_t d = q4_group(x, t, byte);
162    const long long page = (long long) table[pos / page_size];
163    if (page >= 0) q4_store(is_v ? v_q4 : k_q4, (page * kv_heads + h) * page_size + (pos % page_size), b, t, d, byte);
164    if (host.k_q4 != nullptr)
165        q4_store(is_v ? host.v_q4 : host.k_q4, ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size), b, t,
166                 d, byte);
167}
168
169// The prompt path: grid (T, kv_heads, groups), K then V; also into the staging pool (identity layout) when given.
170__dpct_inline__ void kv_append_q4_batch_kernel(
171    uint8_t *__restrict__ k_q4, uint8_t *__restrict__ v_q4,
172    const int32_t *__restrict__ table, int64_t pos0,
173    const float *__restrict__ K, const float *__restrict__ V, int kv_heads,
174    int head_dim, int page_size, int is_v_grid, KvHostPools host,
175    KvHostPools stage) {
176    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
177    const long long t = item_ct1.get_group(2);
178    const long long pos = pos0 + t;
179    const int h = item_ct1.get_group(1), b = item_ct1.get_group(0),
180              th = item_ct1.get_local_id(2);
181    const bool is_v = is_v_grid != 0;
182    const float x = (is_v ? V : K)[t * (kv_heads * head_dim) + h * head_dim + b * QK4_0 + th];
183    uint8_t byte;
184    const uint16_t d = q4_group(x, th, byte);
185    const long long page = (long long) table[pos / page_size];
186    const long long row_id = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size);
187    if (page >= 0) q4_store(is_v ? v_q4 : k_q4, (page * kv_heads + h) * page_size + (pos % page_size), b, th, d, byte);
188    if (host.k_q4 != nullptr) q4_store(is_v ? host.v_q4 : host.k_q4, row_id, b, th, d, byte);
189    if (stage.k_q4 != nullptr) q4_store(is_v ? stage.v_q4 : stage.k_q4, row_id, b, th, d, byte);
190}
191
192// Gather step[kStepWidth] cells into FP16 scratch (the non-fused attention paths)
193__dpct_inline__ void kv_gather_q4_kernel(
194    const uint8_t *__restrict__ k_q4, const uint8_t *__restrict__ v_q4,
195    const int32_t *__restrict__ table, const int32_t *__restrict__ ids,
196    const int32_t *__restrict__ step, int kv_heads, int head_dim, int page_size,
197    uint16_t *__restrict__ k_scratch, uint16_t *__restrict__ v_scratch) {
198    /*
199    DPCT1098: The '*' expression is used instead of the __ldg call. These
200    two expressions do not provide the exact same functionality. Check the
201    generated code for potential precision and/or performance issues.
202    */
203    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
204    const long long n_ids = (long long)*(step + kStepWidth);
205    const int blocks_per_head = head_dim / QK4_0;                        // 8
206    const int bytes_per_head = blocks_per_head * sizeof(block_q4_0);    // 144
207    const long long total_blocks = n_ids * kv_heads * blocks_per_head;
208
209    const long long blk_idx =
210        (long long)item_ct1.get_group(2) * item_ct1.get_local_range(1) +
211        item_ct1.get_local_id(1);
212    if (blk_idx >= total_blocks) return;
213
214    const int t = item_ct1.get_local_id(2);
215    const long long id = blk_idx / (kv_heads * blocks_per_head);
216    const int rem = (int) (blk_idx % (kv_heads * blocks_per_head));
217    const int h = rem / blocks_per_head;
218    const int b = rem % blocks_per_head;
219
220    const int cell = ids[id];
221    const long long page = (long long) table[cell / page_size];
222    const long long row = (page * kv_heads + h) * page_size + (cell % page_size);
223
224    const block_q4_0* k_blk = reinterpret_cast<const block_q4_0*>(k_q4 + row * bytes_per_head) + b;
225    const block_q4_0* v_blk = reinterpret_cast<const block_q4_0*>(v_q4 + row * bytes_per_head) + b;
226    const float kd = f32_from_f16(k_blk->d);
227    const float vd = f32_from_f16(v_blk->d);
228    const int j = t < 16 ? t : (t - 16);
229    const uint8_t k_byte = k_blk->qs[j];
230    const uint8_t v_byte = v_blk->qs[j];
231    const int kq = (t < 16) ? ((k_byte & 0x0F) - 8) : ((k_byte >> 4) - 8);
232    const int vq = (t < 16) ? ((v_byte & 0x0F) - 8) : ((v_byte >> 4) - 8);
233    const long long dst_offset = ((id * kv_heads + h) * head_dim) + (b * QK4_0 + t);
234    k_scratch[dst_offset] = f16_from_f32((float) kq * kd);
235    v_scratch[dst_offset] = f16_from_f32((float) vq * vd);
236}
237
238void need_256(const QsaShapes& s, const char* what) {
239    if (s.head_dim != 256) {
240        std::fprintf(stderr, "%s: head_dim must be 256 (the Hadamard transform's size)\n", what);
241        std::exit(1);
242    }
243}
244
245}  // namespace
246
247void fwht256_cuda(const float* src, float* dst, int64_t n_rows, void* stream) {
248    if (n_rows <= 0) return;
249    const int rows_per_block = 4;
250    const int64_t num_blocks = (n_rows + rows_per_block - 1) / rows_per_block;
251    {
252        auto exp_props = sycl::ext::oneapi::experimental::properties{
253            sycl::ext::oneapi::experimental::use_root_sync};
254
255        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
256            ->submit([&](sycl::handler &cgh) {
257                auto ct3 = 1.0f / 16.0f;
258
259                cgh.parallel_for<dpct_kernel_name<class fwht256_kernel_d551a1>>(
260                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)num_blocks) *
261                                          sycl::range(1, rows_per_block, 32),
262                                      sycl::range(1, rows_per_block, 32)),
263                    exp_props,
264                    [=](sycl::nd_item<3> item_ct1)
265                        [[sycl::reqd_sub_group_size(32)]] {
266                            fwht256_kernel(src, dst, n_rows, ct3);
267                        });
268            });
269    }
270    check("fwht256 launch");
271}
272
273void kv_append_q4_steps(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step,
274                        int step_stride, int n_steps, const float* kcur, const float* vcur, const QsaShapes& s,
275                        void* stream, const KvHostPools* host) {
276    if (n_steps <= 0) return;
277    need_256(s, "kv_append_q4");
278    const int planes = (v_q4 == nullptr || (v_q4 == k_q4 && vcur == kcur)) ? 1 : 2;
279    const dpct::dim3 grid((unsigned)s.n_head_kv, (unsigned)(s.head_dim / QK4_0),
280                          (unsigned)(n_steps * planes));
281    {
282        auto exp_props = sycl::ext::oneapi::experimental::properties{
283            sycl::ext::oneapi::experimental::use_root_sync};
284
285        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
286            ->submit([&](sycl::handler &cgh) {
287                KvHostPools host_host_KvHostPools_ct11 =
288                    host ? *host : KvHostPools{};
289
290                cgh.parallel_for<
291                    dpct_kernel_name<class kv_append_q4_kernel_f256b8>>(
292                    sycl::nd_range<3>(grid * sycl::range(1, 1, 32),
293                                      sycl::range(1, 1, 32)),
294                    exp_props,
295                    [=](sycl::nd_item<3> item_ct1)
296                        [[sycl::reqd_sub_group_size(32)]] {
297                            kv_append_q4_kernel(
298                                k_q4, v_q4, page_table, step, step_stride,
299                                planes, kcur, vcur, (int)s.n_head_kv,
300                                (int)s.head_dim, (int)s.page_size,
301                                host_host_KvHostPools_ct11);
302                        });
303            });
304    }
305    check("kv_append_q4 launch");
306}
307
308void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step,
309                       const float* kcur, const float* vcur, const QsaShapes& s, void* stream,
310                       const KvHostPools* host) {
311    kv_append_q4_steps(k_q4, v_q4, page_table, step, 0, 1, kcur, vcur, s, stream, host);
312}
313
314void kv_append_q4(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, int64_t pos0, int64_t T, const float* K,
315                  const float* V, const QsaShapes& s, void* stream, const KvHostPools* host, const KvHostPools* stage) {
316    if (T <= 0) return;
317    need_256(s, "kv_append_q4");
318    const dpct::dim3 grid((unsigned)T, (unsigned)s.n_head_kv,
319                          (unsigned)(s.head_dim / QK4_0));
320    dpct::queue_ptr cs = strata::q_of(stream);
321    const KvHostPools h = host ? *host : KvHostPools{}, st = stage ? *stage : KvHostPools{};
322    for (int is_v = 0; is_v < 2; ++is_v)
323    {
324        auto exp_props = sycl::ext::oneapi::experimental::properties{
325            sycl::ext::oneapi::experimental::use_root_sync};
326
327        strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<
328            dpct_kernel_name<class kv_append_q4_batch_kernel_11c37a>>(
329            sycl::nd_range<3>(grid * sycl::range(1, 1, 32),
330                              sycl::range(1, 1, 32)),
331            exp_props,
332            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
333                kv_append_q4_batch_kernel(k_q4, v_q4, page_table, pos0, K, V,
334                                          (int)s.n_head_kv, (int)s.head_dim,
335                                          (int)s.page_size, is_v, h, st);
336            });
337    }
338    check("kv_append_q4 batch launch");
339}
340
341void kv_gather_q4_step(const uint8_t* k_q4, const uint8_t* v_q4, const int32_t* page_table, const int32_t* ids,
342                       const int32_t* step, int64_t max_ids, const QsaShapes& s, uint16_t* k_scratch,
343                       uint16_t* v_scratch, void* stream) {
344    if (max_ids <= 0) return;
345    const int blocks_per_head = (int) (s.head_dim / QK4_0);
346    const int64_t total_blocks = max_ids * s.n_head_kv * blocks_per_head;
347    const int rows_per_block = 4;
348    const unsigned num_blocks = (unsigned) ((total_blocks + rows_per_block - 1) / rows_per_block);
349    {
350        auto exp_props = sycl::ext::oneapi::experimental::properties{
351            sycl::ext::oneapi::experimental::use_root_sync};
352
353        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
354            ->template parallel_for<dpct_kernel_name<class kv_gather_q4_kernel_300c16>>(
355                sycl::nd_range<3>(sycl::range(1, 1, num_blocks) *
356                                      sycl::range(1, rows_per_block, 32),
357                                  sycl::range(1, rows_per_block, 32)),
358                exp_props, [=](sycl::nd_item<3> item_ct1) {
359                    kv_gather_q4_kernel(k_q4, v_q4, page_table, ids, step,
360                                        (int)s.n_head_kv, (int)s.head_dim,
361                                        (int)s.page_size, k_scratch, v_scratch);
362                });
363    }
364    check("kv_gather_q4 launch");
365}
366
367}  // namespace strata::kernels