okami.mom/strata

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

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

main
6.6 KiB142 linesraw
1// src/kernels/cuda/s2_gemv_q8.cu - the S2 GEMV that consumes Q8_0 ACTIVATIONS, as ggml does.
2//
3// THE GAP THIS CLOSES (round 186).  `ggml_mul_mat` converts src1 - the ACTIVATION - to the weight's
4// `vec_dot_type` before the dot product, and for Q2_0 that is Q8_0.  The CUDA kernels built in rounds 166-177
5// take FP16 activations instead, while the CPU expert path (`bench/micro/cpu_s2.cpp`) already quantizes to int8
6// and uses `vpdpbusd`.  Left that way the two paths compute different numbers for different experts of the SAME
7// token, and the measured size of the difference is the activation contract itself: 0.9498% relative, against
8// P2.S2's 1e-3 tolerance for FP16 paths.
9//
10// This is the CORRECTNESS version, not the fast one.  It dequantizes each activation (`xq * dx`) inside the
11// loop and does the same float arithmetic as `s2_gemv_quads`; the speed win available here is `__dp4a`, which
12// turns four int8 MACs into one instruction, and that belongs to Phase 3 once the numerics are settled.  The
13// phase's rule is the simplest correct kernel first, and a dp4a version whose numerics are wrong would be
14// indistinguishable from a fast one.
15//
16// Layout: activations are (n_in/32) ggml Q8_0 blocks, 34 bytes each - `fp16 d` then `int8 qs[32]` - produced by
17// `strata::kernels::quantize_q8_0`.  A quad of four elements lies inside one 32-element block, so the block
18// scale is constant across it and is loaded once.
19#define DPCT_PROFILING_ENABLED
20#include <sycl/sycl.hpp>
21#include "strata/kprof.hpp"
22#include <dpct/dpct.hpp>
23#include "strata/sycl_queue.hpp"
24#include "strata/kernels/s2_gemv_q8.hpp"
25
26#include <cstdio>
27#include <cstdlib>
28
29namespace strata::kernels {
30namespace {
31
32constexpr int QK_S2 = 64;
33constexpr int QK8_0 = 32;
34
35__dpct_inline__ void s2_gemv_q8_kernel(const uint8_t *__restrict__ act,
36                                       const uint8_t *__restrict__ codes,
37                                       const float *__restrict__ scales,
38                                       float *__restrict__ y, long long n_in,
39                                       long long n_out, int threads_per_row,
40                                       uint8_t *dpct_local) {
41    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
42    auto partial = (float *)dpct_local;
43    const long long o = item_ct1.get_group(2);
44    if (o >= n_out) return;
45    const int tid = item_ct1.get_local_id(2);
46
47    const long long n_quads = n_in / 4;
48    const uint8_t* c = codes + o * n_quads;             // one code byte per quad
49    const float* s = scales + o * (n_in / QK_S2);
50
51    float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f;
52    for (long long q = tid; q < n_quads; q += threads_per_row) {
53        const uint8_t byte = c[q];
54        const float d = s[q >> 4];                      // (q*4) >> 6, the S2 group index as a shift
55        // the activation quad: four int8 in one 32-element block, so one block scale
56        const long long ablk = (q * 4) / QK8_0;
57        const uint8_t* blk = act + ablk * 34;
58        const uint16_t dbits = (uint16_t) (blk[0] | (blk[1] << 8));
59        const float dx =
60            sycl::vec<sycl::half, 1>(
61                sycl::bit_cast<sycl::half, unsigned short>(dbits))
62                .convert<float, sycl::rounding_mode::automatic>()[0];
63        const int8_t* xq = reinterpret_cast<const int8_t*>(blk + 2);
64        const int off = (int) ((q * 4) % QK8_0);
65
66        const float w0 = (float) ((int) (byte & 3) - 1) * d;
67        const float w1 = (float) ((int) ((byte >> 2) & 3) - 1) * d;
68        const float w2 = (float) ((int) ((byte >> 4) & 3) - 1) * d;
69        const float w3 = (float) ((int) ((byte >> 6) & 3) - 1) * d;
70        a0 += w0 * ((float) xq[off + 0] * dx);
71        a1 += w1 * ((float) xq[off + 1] * dx);
72        a2 += w2 * ((float) xq[off + 2] * dx);
73        a3 += w3 * ((float) xq[off + 3] * dx);
74    }
75    partial[tid] = (a0 + a1) + (a2 + a3);
76    item_ct1.barrier(sycl::access::fence_space::local_space);
77#pragma unroll
78    for (int step = threads_per_row / 2; step > 0; step >>= 1) {
79        if (tid < step) partial[tid] += partial[tid + step];
80        /*
81        DPCT1118: SYCL group functions and algorithms must be encountered in
82        converged control flow. You may need to adjust the code.
83        */
84        item_ct1.barrier(sycl::access::fence_space::local_space);
85    }
86    if (tid == 0) y[o] = partial[0];
87}
88
89}  // namespace
90
91void s2_gemv_q8(const uint8_t* act, const uint8_t* codes, const float* scales, float* y, int64_t n_in,
92                int64_t n_out, int threads_per_row, void* stream) {
93    if (n_in <= 0 || n_out <= 0) return;
94    if (n_in % QK8_0 != 0 || n_in % QK_S2 != 0) {
95        std::fprintf(stderr, "s2_gemv_q8: n_in %lld must be a multiple of %d\n", (long long) n_in, QK_S2);
96        std::exit(1);
97    }
98    /*
99    DPCT1083: The size of local memory in the migrated code may be different
100    from the original code. Check that the allocated memory size in the migrated
101    code is correct.
102    */
103    const size_t smem = (size_t)threads_per_row * sizeof(float);
104    /*
105    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
106    limit. To get the device limit, query info::device::max_work_group_size.
107    Adjust the work-group size if needed.
108    */
109    {
110        auto exp_props = sycl::ext::oneapi::experimental::properties{
111            sycl::ext::oneapi::experimental::use_root_sync};
112
113        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
114            ->submit([&](sycl::handler &cgh) {
115                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
116                    sycl::range(smem), cgh);
117
118                cgh.parallel_for<
119                    dpct_kernel_name<class s2_gemv_q8_kernel_b9a814>>(
120                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_out) *
121                                          sycl::range(1, 1, threads_per_row),
122                                      sycl::range(1, 1, threads_per_row)),
123                    exp_props, [=](sycl::nd_item<3> item_ct1) {
124                        s2_gemv_q8_kernel(
125                            act, codes, scales, y, n_in, n_out, threads_per_row,
126                            dpct_local_acc_ct1
127                                .get_multi_ptr<sycl::access::decorated::no>()
128                                .get());
129                    });
130            });
131    }
132    /*
133    DPCT1010: SYCL uses exceptions to report errors and does not use the
134    error codes. The cudaGetLastError function call was replaced with 0. You
135    need to rewrite this code.
136    */
137    const dpct::err0 e = 0;
138
139    if (stream == nullptr) dpct::get_current_device().queues_wait_and_throw();
140}
141
142}  // namespace strata::kernels