okami.mom/strata

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

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

main
6.7 KiB139 linesraw
1// src/kernels/cuda/s2_gemv_quads.cu - S2 with the code load amortised over four elements.
2//
3// THE HYPOTHESIS THIS TESTS.  L4 measured 66 G weights/s = 0.55 weights/cycle/SM, and at an estimated ~13
4// instructions per weight that is ~7.2 instructions/cycle/SM against an SM's 4/cycle issue ceiling.  Compute
5// (0.4% of FP32 peak) and bandwidth (2%) are excluded by measurement and the dependency chain was excluded by
6// experiment in L4, so instruction ISSUE is what remains.  If that is right, cutting instructions per weight
7// must move the rate; if the rate does not move, the hypothesis is wrong and that is worth knowing too.
8//
9// WHERE THE INSTRUCTIONS GO.  For S2 four consecutive elements share ONE byte (element i at byte i/4, bits
10// (i%4)*2), and four halves of x are eight contiguous bytes.  The generic kernel walks with a thread stride
11// and loads one byte and one half PER ELEMENT; a thread that takes a contiguous quad instead loads one byte
12// and one 64-bit word for all four.  Memory instructions per element drop from 2 to 0.5, and the address
13// arithmetic is computed once rather than four times.
14//
15// S2 IS SPECIALISED DELIBERATELY: it is 31.64 GiB of the 38 GiB pack, so it is the kernel that matters.  The
16// generic `s_gemv_split` still serves S4 and S8.
17#define DPCT_PROFILING_ENABLED
18#include <sycl/sycl.hpp>
19#include "strata/kprof.hpp"
20#include <dpct/dpct.hpp>
21#include "strata/kernels/s_gemv.hpp"
22
23#include <cstdio>
24#include <cstdlib>
25
26namespace strata::kernels {
27namespace {
28
29// QK = 64 elements per group; a quad of 4 elements is 1/16 of a group, so
30//     group = (quad * 4) >> 6 = quad >> 4
31constexpr int QK_S2 = 64;
32constexpr int CODES_PER_BYTE_S2 = 4;
33
34__dpct_inline__ void s2_gemv_quads_kernel(const uint16_t *__restrict__ x,
35                                          const uint8_t *__restrict__ codes,
36                                          const float *__restrict__ scales,
37                                          float *__restrict__ y, long long n_in,
38                                          long long n_out, int threads_per_row,
39                                          uint8_t *dpct_local) {
40    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
41    auto partial = (float *)dpct_local;
42    const long long o = item_ct1.get_group(2);
43    if (o >= n_out) return;
44    const int tid = item_ct1.get_local_id(2);
45
46    const long long n_quads = n_in / 4;
47    const uint8_t* c = codes + o * n_quads;             // exactly one code byte per quad
48    const float* s = scales + o * (n_in / QK_S2);
49
50    float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f;
51    for (long long q = tid; q < n_quads; q += threads_per_row) {
52        const uint8_t byte = c[q];                      // ONE load for four codes
53        const float d = s[q >> 4];                      // (q*4) >> 6, the group index as a shift
54        // ONE 64-bit load for four halves.  `x` is 256-byte aligned and four halves are eight bytes, so
55        // this is an aligned uint2 - if it were not, the misaligned access would fault rather than be slow.
56        const sycl::uint2 xw =
57            *reinterpret_cast<const sycl::uint2 *>(x + q * 4);
58        const sycl::half2 h01 = *reinterpret_cast<const sycl::half2 *>(&xw.x());
59        const sycl::half2 h23 = *reinterpret_cast<const sycl::half2 *>(&xw.y());
60        // the four codes, each carrying the -1 bias in the INTEGER domain; the scale is applied once per
61        // element here rather than once per group, which is the same expression the generic kernel uses
62        const float w0 = (float) ((int) (byte & 3) - 1) * d;
63        const float w1 = (float) ((int) ((byte >> 2) & 3) - 1) * d;
64        const float w2 = (float) ((int) ((byte >> 4) & 3) - 1) * d;
65        const float w3 = (float) ((int) ((byte >> 6) & 3) - 1) * d;
66        a0 += w0 * h01[0];
67        a1 += w1 * h01[1];
68        a2 += w2 * h23[0];
69        a3 += w3 * h23[1];
70    }
71    partial[tid] = (a0 + a1) + (a2 + a3);
72    item_ct1.barrier(sycl::access::fence_space::local_space);
73#pragma unroll
74    for (int step = threads_per_row / 2; step > 0; step >>= 1) {
75        if (tid < step) partial[tid] += partial[tid + step];
76        /*
77        DPCT1118: SYCL group functions and algorithms must be encountered in
78        converged control flow. You may need to adjust the code.
79        */
80        item_ct1.barrier(sycl::access::fence_space::local_space);
81    }
82    if (tid == 0) y[o] = partial[0];
83}
84
85}  // namespace
86
87void s2_gemv_quads(const uint16_t *x, const uint8_t *codes, const float *scales,
88                   float *y, int64_t n_in, int64_t n_out,
89                   int threads_per_row) try {
90    if (n_in <= 0 || n_out <= 0) return;
91    if (n_in % 4 != 0) {
92        std::fprintf(stderr, "s2_gemv_quads: n_in %lld is not a multiple of 4\n", (long long) n_in);
93        std::exit(1);
94    }
95    /*
96    DPCT1083: The size of local memory in the migrated code may be different
97    from the original code. Check that the allocated memory size in the migrated
98    code is correct.
99    */
100    const size_t smem = (size_t)threads_per_row * sizeof(float);
101    /*
102    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
103    limit. To get the device limit, query info::device::max_work_group_size.
104    Adjust the work-group size if needed.
105    */
106    {
107        auto exp_props = sycl::ext::oneapi::experimental::properties{
108            sycl::ext::oneapi::experimental::use_root_sync};
109        dpct::has_capability_or_fail(dpct::get_in_order_queue().get_device(),
110                                     {sycl::aspect::fp16});
111
112        strata::kprof::kp(&dpct::get_in_order_queue(), __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
113            sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
114                sycl::range(smem), cgh);
115
116            cgh.parallel_for<
117                dpct_kernel_name<class s2_gemv_quads_kernel_5797f4>>(
118                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_out) *
119                                      sycl::range(1, 1, threads_per_row),
120                                  sycl::range(1, 1, threads_per_row)),
121                exp_props, [=](sycl::nd_item<3> item_ct1) {
122                    s2_gemv_quads_kernel(
123                        x, codes, scales, y, n_in, n_out, threads_per_row,
124                        dpct_local_acc_ct1
125                            .get_multi_ptr<sycl::access::decorated::no>()
126                            .get());
127                });
128        });
129    }
130    const dpct::err0 e =
131        DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw());
132}
133catch (sycl::exception const &exc) {
134  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
135            << ", line:" << __LINE__ << std::endl;
136  std::exit(1);
137}
138
139}  // namespace strata::kernels