okami.mom/strata

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

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

main
11.4 KiB251 linesraw
1// src/kernels/cuda/s2_gemv_fast.cu - two levers on the hottest kernel, BOTH MEASURED NEGATIVE OR NEUTRAL.
2//
3// *** THIS FILE IS NAMED "fast" AND IS NOT FASTER.  DO NOT ADOPT IT AS THE FAST PATH. ***
4// It is kept because the negative result is worth more than the file costs: it closes two plausible
5// optimisations and it is the experiment that established the measurement floor.
6//
7// L5 got the S2 GEMV from 10.5 to 86.2 G weights/s by amortising the loads, and left the instruction-count
8// argument confirmed but unfinished.  Two further reductions were obvious, so both were built and measured:
9//
10// LEVER 1 - STAGE `x` IN SHARED MEMORY.  `x` is n_in halves (5 KB at n_embd 2560) and every output row reads
11// all of it, so the generic kernel issues n_out * n_in activation loads per GEMV.  Staging it once per block
12// measured WORSE in every single paired comparison (59-76 G w/s staged against 64-87 G w/s unstaged, across
13// four sweep passes and three thread counts).  The __syncthreads and the copy cost more than the L1/L2 hits
14// they replace - the same 5 KB is already resident and already broadcast.
15//
16// LEVER 2 - A CONSTANT-MEMORY CODE TABLE.  Turn the per-element shifts, masks and int-to-float convert into
17// one broadcast `float4` load per four elements.  Measured NEUTRAL: the two orderings swap between passes
18// with no consistent winner.
19//
20// WHY THE NEGATIVE RESULT IS THE REAL FINDING: run-to-run variance on this machine is now ~20% within a
21// single configuration (quads tpr=32 measured 64.3 to 79.5 G w/s across four passes), because `verify` holds
22// ~97% of six CPU cores.  **The noise floor now EXCEEDS the effect sizes being chased**, so further
23// micro-optimisation of this kernel cannot be evaluated here and should wait for a quiet machine rather than
24// produce more numbers that cannot be distinguished from noise.
25//
26// Both changes alter the summation order or the expression, so this kernel is checked against the naive
27// reference like every other one - being faster is never a reason to be trusted, and being neutral is not
28// either.
29#define DPCT_PROFILING_ENABLED
30#include <sycl/sycl.hpp>
31#include "strata/kprof.hpp"
32#include <dpct/dpct.hpp>
33#include "strata/kernels/s_gemv.hpp"
34
35#include <cstdio>
36#include <cstdlib>
37
38namespace strata::kernels {
39namespace {
40
41constexpr int QK_S2 = 64;
42constexpr int MAX_SHARED_HALVES = 4096;      // 8 KB of shared for x; n_embd 2560 fits with room
43
44// byte -> the four code values with the -1 bias already applied, in element order (bits 0,2,4,6).
45inline dpct::constant_memory<float, 2>& c_codes = *new dpct::constant_memory<float, 2>(256, 4);   // never freed: exit-order safe
46
47bool g_lut_ready[64] = {};   // per device: __constant__ memory is per device (a layer split runs on two)
48
49void ensure_lut() try {
50    int dev = 0;
51    dev = dpct::get_current_device_id();
52    if (dev < 0 || dev >= 64) dev = 0;
53    if (g_lut_ready[dev]) return;
54    float host[256][4];
55    for (int b = 0; b < 256; ++b) {
56        for (int k = 0; k < 4; ++k) {
57            host[b][k] = (float) (((b >> (2 * k)) & 3) - 1);
58        }
59    }
60    const dpct::err0 e =
61        DPCT_CHECK_ERROR(dpct::get_in_order_queue()
62                             .memcpy(c_codes.get_ptr(), host, sizeof(host))
63                             .wait());
64
65    g_lut_ready[dev] = true;
66}
67catch (sycl::exception const &exc) {
68  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
69            << ", line:" << __LINE__ << std::endl;
70  std::exit(1);
71}
72
73// One block per output row.  `staged` says whether x was copied to shared, so the SAME kernel covers both
74// configurations and the bench can measure them against each other with nothing else changed.
75template <bool STAGE_X>
76/*
77DPCT1110: The total declared local variable size in device function
78s2_gemv_fast_kernel exceeds 128 bytes and may cause high register pressure.
79Consult with your hardware vendor to find the total register size available and
80adjust the code, or use smaller sub-group size to avoid high register pressure.
81*/
82__dpct_inline__ void s2_gemv_fast_kernel(
83    const uint16_t *__restrict__ x, const uint8_t *__restrict__ codes,
84    const float *__restrict__ scales, float *__restrict__ y, long long n_in,
85    long long n_out, int threads_per_row, uint8_t *dpct_local,
86    dpct::accessor<float, dpct::constant, 2> c_codes) {
87    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
88    auto smem = (float *)dpct_local;
89    sycl::half *sx = reinterpret_cast<sycl::half *>(
90        smem); // [threads_per_row, ...] partials live after
91    float* partial = smem + (STAGE_X ? (MAX_SHARED_HALVES / 2) : 0);
92
93    const long long o = item_ct1.get_group(2);
94    if (o >= n_out) return;
95    const int tid = item_ct1.get_local_id(2);
96
97    if (STAGE_X) {
98        const sycl::half *xh = reinterpret_cast<const sycl::half *>(x);
99#pragma unroll
100        for (long long i = tid; i < n_in; i += threads_per_row) sx[i] = xh[i];
101        /*
102        DPCT1118: SYCL group functions and algorithms must be encountered in
103        converged control flow. You may need to adjust the code.
104        */
105        item_ct1.barrier(sycl::access::fence_space::local_space);
106    }
107
108    const long long n_quads = n_in / 4;
109    const uint8_t* c = codes + o * n_quads;
110    const float* s = scales + o * (n_in / QK_S2);
111
112    float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f;
113    for (long long q = tid; q < n_quads; q += threads_per_row) {
114        const uint8_t byte = c[q];                          // ONE load for four codes
115        const float d = s[q >> 4];                          // (q*4) >> 6
116        const sycl::float4 cv = *reinterpret_cast<const sycl::float4 *>(
117            &c_codes[byte][0]); // one broadcast load
118        if (STAGE_X) {
119            const sycl::half2 h01 =
120                *reinterpret_cast<const sycl::half2 *>(&sx[q * 4]);
121            const sycl::half2 h23 =
122                *reinterpret_cast<const sycl::half2 *>(&sx[q * 4 + 2]);
123            a0 += cv.x() * d * h01[0];
124            a1 += cv.y() * d * h01[1];
125            a2 += cv.z() * d * h23[0];
126            a3 += cv.w() * d * h23[1];
127        } else {
128            const sycl::uint2 xw2 =
129                *reinterpret_cast<const sycl::uint2 *>(x + q * 4);
130            const sycl::half2 h01 =
131                *reinterpret_cast<const sycl::half2 *>(&xw2.x());
132            const sycl::half2 h23 =
133                *reinterpret_cast<const sycl::half2 *>(&xw2.y());
134            a0 += cv.x() * d * h01[0];
135            a1 += cv.y() * d * h01[1];
136            a2 += cv.z() * d * h23[0];
137            a3 += cv.w() * d * h23[1];
138        }
139    }
140    partial[tid] = (a0 + a1) + (a2 + a3);
141    item_ct1.barrier(sycl::access::fence_space::local_space);
142#pragma unroll
143    for (int step = threads_per_row / 2; step > 0; step >>= 1) {
144        if (tid < step) partial[tid] += partial[tid + step];
145        /*
146        DPCT1118: SYCL group functions and algorithms must be encountered in
147        converged control flow. You may need to adjust the code.
148        */
149        item_ct1.barrier(sycl::access::fence_space::local_space);
150    }
151    if (tid == 0) y[o] = partial[0];
152}
153
154}  // namespace
155
156void s2_gemv_fast(const uint16_t *x, const uint8_t *codes, const float *scales,
157                  float *y, int64_t n_in, int64_t n_out, int threads_per_row,
158                  bool stage_x) try {
159    if (n_in <= 0 || n_out <= 0) return;
160    if (n_in % 4 != 0 || n_in % QK_S2 != 0) {
161        std::fprintf(stderr, "s2_gemv_fast: n_in %lld must be a multiple of %d\n", (long long) n_in, QK_S2);
162        std::exit(1);
163    }
164    ensure_lut();
165    if (stage_x && n_in > MAX_SHARED_HALVES) {
166        std::fprintf(stderr, "s2_gemv_fast: n_in %lld exceeds the %d-half shared staging limit\n",
167                     (long long) n_in, MAX_SHARED_HALVES);
168        std::exit(1);
169    }
170    /*
171    DPCT1083: The size of local memory in the migrated code may be different
172    from the original code. Check that the allocated memory size in the migrated
173    code is correct.
174    */
175    const size_t smem = (stage_x ? MAX_SHARED_HALVES * sizeof(sycl::half) : 0) +
176                        (size_t)threads_per_row * sizeof(float);
177    if (stage_x) {
178        /*
179        DPCT1049: The work-group size passed to the SYCL kernel may exceed
180        the limit. To get the device limit, query
181        info::device::max_work_group_size. Adjust the work-group size if needed.
182        */
183        c_codes.init();
184
185        auto exp_props = sycl::ext::oneapi::experimental::properties{
186            sycl::ext::oneapi::experimental::use_root_sync};
187        dpct::has_capability_or_fail(dpct::get_in_order_queue().get_device(),
188                                     {sycl::aspect::fp16});
189
190        strata::kprof::kp(&dpct::get_in_order_queue(), __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
191            sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
192                sycl::range(smem), cgh);
193            auto c_codes_acc_ct1 = c_codes.get_access(cgh);
194
195            cgh.parallel_for<dpct_kernel_name<class s2_gemv_fast_kernel_3b9618,
196                                              dpct_kernel_scalar<true>>>(
197                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_out) *
198                                      sycl::range(1, 1, threads_per_row),
199                                  sycl::range(1, 1, threads_per_row)),
200                exp_props, [=](sycl::nd_item<3> item_ct1) {
201                    s2_gemv_fast_kernel<true>(
202                        x, codes, scales, y, n_in, n_out, threads_per_row,
203                        dpct_local_acc_ct1
204                            .get_multi_ptr<sycl::access::decorated::no>()
205                            .get(),
206                        c_codes_acc_ct1);
207                });
208        });
209    } else {
210        /*
211        DPCT1049: The work-group size passed to the SYCL kernel may exceed
212        the limit. To get the device limit, query
213        info::device::max_work_group_size. Adjust the work-group size if needed.
214        */
215        c_codes.init();
216
217        auto exp_props = sycl::ext::oneapi::experimental::properties{
218            sycl::ext::oneapi::experimental::use_root_sync};
219        dpct::has_capability_or_fail(dpct::get_in_order_queue().get_device(),
220                                     {sycl::aspect::fp16});
221
222        strata::kprof::kp(&dpct::get_in_order_queue(), __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
223            sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
224                sycl::range(smem), cgh);
225            auto c_codes_acc_ct1 = c_codes.get_access(cgh);
226
227            cgh.parallel_for<dpct_kernel_name<class s2_gemv_fast_kernel_61f77f,
228                                              dpct_kernel_scalar<false>>>(
229                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_out) *
230                                      sycl::range(1, 1, threads_per_row),
231                                  sycl::range(1, 1, threads_per_row)),
232                exp_props, [=](sycl::nd_item<3> item_ct1) {
233                    s2_gemv_fast_kernel<false>(
234                        x, codes, scales, y, n_in, n_out, threads_per_row,
235                        dpct_local_acc_ct1
236                            .get_multi_ptr<sycl::access::decorated::no>()
237                            .get(),
238                        c_codes_acc_ct1);
239                });
240        });
241    }
242    const dpct::err0 e =
243        DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw());
244}
245catch (sycl::exception const &exc) {
246  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
247            << ", line:" << __LINE__ << std::endl;
248  std::exit(1);
249}
250
251}  // namespace strata::kernels