okami.mom/strata

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

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

main
12.1 KiB256 linesraw
1// src/kernels/cuda/kv_q8.cu - see include/strata/kernels/kv_q8.hpp.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include "strata/kprof.hpp"
5#include <dpct/dpct.hpp>
6#include "strata/sycl_queue.hpp"
7#include "strata/kernels/kv_q8.hpp"
8#include "strata/kernels/f16_bits.hpp"
9
10#include <cstdio>
11#include <cstdlib>
12
13namespace strata::kernels {
14namespace {
15
16void check(const char* what) {
17    /*
18    DPCT1010: SYCL uses exceptions to report errors and does not use the
19    error codes. The cudaGetLastError function call was replaced with 0. You
20    need to rewrite this code.
21    */
22    const dpct::err0 e = 0;
23}
24
25void validate(const QsaShapes& s, const char* what) {
26    if (s.head_dim % KV_Q8_GROUP != 0 || s.n_head_kv <= 0 || s.page_size <= 0) {
27        std::fprintf(stderr, "kv_q8: %s: head_dim %lld must be a multiple of %d\n", what, (long long) s.head_dim,
28                     KV_Q8_GROUP);
29        std::exit(1);
30    }
31}
32
33// One block = one 64-value group of one KV head of K (blockIdx.z = 0) or V (1); 64 threads, one value each.
34// MULTI (S26 STRATA_LFUSE): blockIdx.z = 2 * token + (K / V); token j reads step + j * step_stride and its rows at
35// kcur / vcur + j * cur_stride - every token's code is the single launch's
36template <bool MULTI = false>
37__dpct_inline__ void kv_append_q8_kernel(
38    int8_t *__restrict__ k_q, int8_t *__restrict__ v_q,
39    uint16_t *__restrict__ k_scale, uint16_t *__restrict__ v_scale,
40    const int32_t *__restrict__ table, const int32_t *__restrict__ step,
41    const float *__restrict__ kcur, const float *__restrict__ vcur,
42    int kv_heads, int head_dim, int page_size, KvHostPools host,
43    int step_stride = 0, int cur_stride = 0) {
44    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
45    if constexpr (MULTI) {
46        const int j = item_ct1.get_group(0) >> 1;
47        step += (size_t) j * step_stride; kcur += (size_t) j * cur_stride; vcur += (size_t) j * cur_stride;
48    }
49    /*
50    DPCT1098: The '*' expression is used instead of the __ldg call. These
51    two expressions do not provide the exact same functionality. Check the
52    generated code for potential precision and/or performance issues.
53    */
54    const long long pos = (long long)*(step + kStepPos);
55    const int h = item_ct1.get_group(2), g = item_ct1.get_group(1),
56              t = item_ct1.get_local_id(2);
57    const bool is_v =
58        MULTI ? (item_ct1.get_group(0) & 1) == 1 : item_ct1.get_group(0) == 1;
59    const int groups = head_dim / KV_Q8_GROUP;
60    const float x = (is_v ? vcur : kcur)[h * head_dim + g * KV_Q8_GROUP + t];
61    // max |x| over the 64 values: two warps, then combine through shared memory in a fixed order
62    float a = sycl::fabs(x);
63    /*
64DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
65masked sub_group function which may not be supported by all compilers or
66runtimes. You may need to adjust the code.
67*/
68#pragma unroll
69    for (int o = 16; o > 0; o >>= 1) a = sycl::fmax(
70        a, dpct::experimental::permute_sub_group_by_xor(
71               0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
72               a, o));
73    auto &warp_max =
74        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2]>(
75            sycl::ext::oneapi::this_work_item::get_work_group<3>());
76    if ((t & 31) == 0) warp_max[t >> 5] = a;
77    /*
78    DPCT1065: Consider replacing sycl::nd_item::barrier() with
79    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
80    performance if there is no access to global memory.
81    */
82    item_ct1.barrier();
83    const float amax = sycl::fmax(warp_max[0], warp_max[1]);
84    const uint16_t sbits = f16_from_f32(amax / 127.0f);
85    const float sf = f32_from_f16(sbits);                          // quantize against the STORED scale
86    int q = 0;
87    if (sf > 0.0f) {
88        q = sycl::vec<float, 1>{(x / sf)}
89                .convert<int, sycl::rounding_mode::rte>()[0];
90        q = q < -127 ? -127 : (q > 127 ? 127 : q);
91    }
92    // KV streaming: the host copy (identity layout) always, the VRAM page only if the block is resident
93    const long long page = (long long) table[pos / page_size];
94    if (page >= 0) {
95        const long long row = (page * kv_heads + h) * page_size + (pos % page_size);
96        (is_v ? v_q : k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q;
97        if (t == 0) (is_v ? v_scale : k_scale)[row * groups + g] = sbits;
98    }
99    if (host.k_q != nullptr) {
100        const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size);
101        (is_v ? host.v_q : host.k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q;
102        if (t == 0) (is_v ? host.v_scale : host.k_scale)[row * groups + g] = sbits;
103    }
104}
105
106// One thread = 4 consecutive values of one cell and head (as the FP16 gather does with uint2).
107__dpct_inline__ void kv_gather_q8_kernel(
108    const int8_t *__restrict__ k_q, const int8_t *__restrict__ v_q,
109    const uint16_t *__restrict__ k_scale, const uint16_t *__restrict__ v_scale,
110    const int32_t *__restrict__ table, const int32_t *__restrict__ ids,
111    const int32_t *__restrict__ step, int kv_heads, int head_dim, int page_size,
112    uint16_t *__restrict__ k_scratch, uint16_t *__restrict__ v_scratch) {
113    /*
114    DPCT1098: The '*' expression is used instead of the __ldg call. These
115    two expressions do not provide the exact same functionality. Check the
116    generated code for potential precision and/or performance issues.
117    */
118    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
119    const long long n_ids = (long long)*(step + kStepWidth);
120    const int per = head_dim / 4;
121    const long long total = n_ids * kv_heads * per;
122    const long long i =
123        item_ct1.get_group(2) * (long long)item_ct1.get_local_range(2) +
124        item_ct1.get_local_id(2);
125    if (i >= total) return;
126    const long long id = i / (kv_heads * (long long) per);
127    const int rem = (int) (i % (kv_heads * (long long) per));
128    const int h = rem / per, q4 = rem - h * per;
129    const int cell = ids[id];
130    const long long page = (long long) table[cell / page_size];
131    const long long row = (page * kv_heads + h) * page_size + (cell % page_size);
132    const int d = q4 * 4;
133    const int groups = head_dim / KV_Q8_GROUP;
134    const float ks = f32_from_f16(k_scale[row * groups + d / KV_Q8_GROUP]);
135    const float vs = f32_from_f16(v_scale[row * groups + d / KV_Q8_GROUP]);
136    const sycl::char4 kc =
137        reinterpret_cast<const sycl::char4 *>(k_q + row * head_dim)[q4];
138    const sycl::char4 vc =
139        reinterpret_cast<const sycl::char4 *>(v_q + row * head_dim)[q4];
140    sycl::ushort4 ko, vo;
141    ko.x() = f16_from_f32((float)kc.x() * ks);
142        ko.y() = f16_from_f32((float)kc.y() * ks);
143    ko.z() = f16_from_f32((float)kc.z() * ks);
144        ko.w() = f16_from_f32((float)kc.w() * ks);
145    vo.x() = f16_from_f32((float)vc.x() * vs);
146        vo.y() = f16_from_f32((float)vc.y() * vs);
147    vo.z() = f16_from_f32((float)vc.z() * vs);
148        vo.w() = f16_from_f32((float)vc.w() * vs);
149    const long long dst = (id * kv_heads + h) * (long long) per + q4;
150    reinterpret_cast<sycl::ushort4 *>(k_scratch)[dst] = ko;
151    reinterpret_cast<sycl::ushort4 *>(v_scratch)[dst] = vo;
152}
153
154}  // namespace
155
156void 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,
157                       const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream,
158                       const KvHostPools* host) {
159    validate(s, "kv_append_q8");
160    const dpct::dim3 grid((unsigned)s.n_head_kv,
161                          (unsigned)(s.head_dim / KV_Q8_GROUP), 2);
162    {
163        auto exp_props = sycl::ext::oneapi::experimental::properties{
164            sycl::ext::oneapi::experimental::use_root_sync};
165
166        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
167            ->submit([&](sycl::handler &cgh) {
168                KvHostPools host_host_KvHostPools_ct11 =
169                    host ? *host : KvHostPools{};
170
171                /*
172                DPCT1050: The template argument of the dpct_kernel_name
173                could not be deduced. You need to update this code.
174                */
175                cgh.parallel_for<dpct_kernel_name<
176                    class kv_append_q8_kernel_b60fdc,
177                    dpct_kernel_scalar<false>>>(
178                    sycl::nd_range<3>(grid * sycl::range(1, 1, KV_Q8_GROUP),
179                                      sycl::range(1, 1, KV_Q8_GROUP)),
180                    exp_props,
181                    [=](sycl::nd_item<3> item_ct1)
182                        [[sycl::reqd_sub_group_size(32)]] {
183                            kv_append_q8_kernel(
184                                k_q, v_q, k_scale, v_scale, page_table, step,
185                                kcur, vcur, (int)s.n_head_kv, (int)s.head_dim,
186                                (int)s.page_size, host_host_KvHostPools_ct11, 0,
187                                0);
188                        });
189            });
190    }
191    check("kv_append_q8 launch");
192}
193
194void 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,
195                        const int32_t* step, int step_stride, const float* kcur, const float* vcur, int cur_stride,
196                        int n_tok, const QsaShapes& s, void* stream, const KvHostPools* host) {
197    validate(s, "kv_append_q8 (steps)");
198    if (n_tok < 1) return;
199    const dpct::dim3 grid((unsigned)s.n_head_kv,
200                          (unsigned)(s.head_dim / KV_Q8_GROUP),
201                          (unsigned)(2 * n_tok));
202    {
203        auto exp_props = sycl::ext::oneapi::experimental::properties{
204            sycl::ext::oneapi::experimental::use_root_sync};
205
206        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
207            ->submit([&](sycl::handler &cgh) {
208                KvHostPools host_host_KvHostPools_ct11 =
209                    host ? *host : KvHostPools{};
210
211                cgh.parallel_for<
212                    dpct_kernel_name<class kv_append_q8_kernel_b60fdc,
213                                     dpct_kernel_scalar<true>>>(
214                    sycl::nd_range<3>(grid * sycl::range(1, 1, KV_Q8_GROUP),
215                                      sycl::range(1, 1, KV_Q8_GROUP)),
216                    exp_props,
217                    [=](sycl::nd_item<3> item_ct1)
218                        [[sycl::reqd_sub_group_size(32)]] {
219                            kv_append_q8_kernel<true>(
220                                k_q, v_q, k_scale, v_scale, page_table, step,
221                                kcur, vcur, (int)s.n_head_kv, (int)s.head_dim,
222                                (int)s.page_size, host_host_KvHostPools_ct11,
223                                step_stride, cur_stride);
224                        });
225            });
226    }
227    check("kv_append_q8 (steps) launch");
228}
229
230void kv_gather_q8_step(const int8_t* k_q, const int8_t* v_q, const uint16_t* k_scale, const uint16_t* v_scale,
231                       const int32_t* page_table, const int32_t* ids, const int32_t* step, int64_t max_ids,
232                       const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) {
233    validate(s, "kv_gather_q8");
234    if (max_ids <= 0) return;
235    const long long total = max_ids * s.n_head_kv * (s.head_dim / 4);
236    const unsigned blocks = (unsigned) ((total + 255) / 256);
237    {
238        auto exp_props = sycl::ext::oneapi::experimental::properties{
239            sycl::ext::oneapi::experimental::use_root_sync};
240
241        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
242            ->template parallel_for<dpct_kernel_name<class kv_gather_q8_kernel_84cbb3>>(
243                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
244                                      sycl::range(1, 1, 256),
245                                  sycl::range(1, 1, 256)),
246                exp_props, [=](sycl::nd_item<3> item_ct1) {
247                    kv_gather_q8_kernel(k_q, v_q, k_scale, v_scale, page_table,
248                                        ids, step, (int)s.n_head_kv,
249                                        (int)s.head_dim, (int)s.page_size,
250                                        k_scratch, v_scratch);
251                });
252    }
253    check("kv_gather_q8 launch");
254}
255
256}  // namespace strata::kernels