okami.mom/strata

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

waveringanaedge0-strata: add the engine for Edge0 145B and Edge0 120Bfd19246dc

main
10.1 KiB184 linesraw
1// src/kernels/cuda/latent.cu - the latent MoE's engine-side kernels (new file).
2//
3// Bit-identical dot to iq_mmvq(8)'s vec_dot_q8_0_q8_1: per block
4//   acc += dx * dw * sum_k(xs[k] * ws[k])
5// where dx is the q8_1 block's f16 scale (struct {half ds[2]; int8 qs[32]}: the first half,
6// bytes 0..1; the values follow at bytes 4..35) and dw the q8_0 block's f16 scale
7// ({half d; int8 qs[32]}: bytes 0..1; values at 2..33).  The per-block 32-lane sum is
8// computed directly (same integer arithmetic as the dp4a lanes, no alignment assumptions).
9#include "strata/kernels/latent.hpp"
10#include "strata/kernels/dp4a.hpp"
11
12#include <cstdio>
13#include <cuda_fp16.h>
14#include <cuda_runtime.h>
15
16namespace strata::kernels {
17
18__global__ void latent_plan_rows_k(int32_t* tok, const int32_t* dst, const int32_t* counts, const int32_t* ids,
19                                   const int32_t* labels, int E, int base_token, int G, int K) {
20    const int nj = counts[1];   // all GPU entries (the VRAM share + the PCIe share)
21    for (int j = threadIdx.x; j < nj; j += blockDim.x) {
22        const int d = dst[j];
23        const int32_t e = ids[d];
24        const int g = (e >= 0 && e < E) ? labels[e] : 0;
25        tok[j] = (base_token + d / K) * G + g;
26    }
27}
28
29void latent_plan_rows(int32_t* tok, const int32_t* dst, const int32_t* counts, const int32_t* ids,
30                      const int32_t* labels_dev, int64_t E, int base_token, int G, int K, void* stream) {
31    latent_plan_rows_k<<<1, 64, 0, (cudaStream_t) stream>>>(tok, dst, counts, ids, labels_dev, (int) E, base_token, G, K);
32}
33
34// latent_u_k optimized: coalesced dp4a, one warp per output row.
35// Old version: one THREAD per row with scalar byte loads and no reuse -> ~25x read
36// amplification, ~0.84 ms/layer. New: lanes stride the ELL words of a row as int32
37// (built from 2-byte-aligned ushort pairs, q8_0 stores {half d; i8 qs[32]} at +2),
38// dp4a per word, warp-shuffle reduction. U[g] rows are read once per (route,row)
39// and shared across routes through L2 as before, but now at stream bandwidth.
40__device__ __forceinline__ int latent_ld4_i8(const uint8_t* p) {
41    const unsigned short a = *(const unsigned short*) p;
42    const unsigned short b = *(const unsigned short*) (p + 2);
43    return (int) ((unsigned) a | ((unsigned) b << 16));   // a = p0|p1<<8, b<<16 = p2<<16|p3<<24
44}
45
46
47// Q4DU: the weight block's dot with a q8_1 activation block, fmt 8 (Q8_0) or 4 (Q4_0).
48// The q8_1 block is always {f16 d; f16 s; int8 qs[32]} (36 B, values at +4); the weight block
49// is {f16 d; int8 qs[32]} (34 B) for fmt 8, {f16 d; uint8 nib[16]} (18 B) for fmt 4 with
50// element j in byte j's low nibble and element j+16 in its high one, value (code - 8) * d -
51// the same centred codes as iq_kernels.cu's vec_dot_q4_0_q8_1 (q4_0_centred).
52__device__ __forceinline__ float lat_blk_dot_q4(const uint8_t* wb, const uint8_t* xb, int j) {
53    // nibble words are built from byte loads: a Q4_0 block is only 2-byte aligned inside its
54    // row (18 B stride), a raw int dereference at +2 is misaligned and faults on sm_120.
55    const float dw = __half2float(*(const __half*) wb);
56    const float dx = __half2float(*(const __half*) xb);
57    // 4 bytes at wb+2+j: each byte's low nibble is element (j+k), its high nibble element (j+k+16).
58    int w0 = 0, w16 = 0, xw = 0, xw16 = 0;
59    #pragma unroll
60    for (int k = 0; k < 4; ++k) {
61        const int byte_ = (int) wb[2 + j + k];
62        w0 |= (((byte_ & 0xF) - 8) & 0xFF) << (8 * k);          // mask: a negative code's sign
63        w16 |= ((((byte_ >> 4) & 0xF) - 8) & 0xFF) << (8 * k);  // bits must not bleed into the
64        xw |= (int) (uint32_t) xb[4 + j + k] << (8 * k);        // neighbouring byte of the word
65        xw16 |= (int) (uint32_t) xb[4 + j + k + 16] << (8 * k); // (dp4a reads s8 itself)
66    }
67    return dx * dw * (float) (__dp4a(xw, w0, 0) + __dp4a(xw16, w16, 0));
68}
69
70__global__ void latent_u_k(const uint8_t* __restrict__ u_q8, const uint8_t* __restrict__ ylq,
71                           const int32_t* __restrict__ ids, const int32_t* __restrict__ labels, int E, int cap_entries,
72                           int ELL, int H, float* __restrict__ out, int fmt) {
73    const int r = blockIdx.x;
74    if (r >= cap_entries) return;
75    const int32_t e = ids[r];
76    const int g = (e >= 0 && e < E) ? labels[e] : 0;
77    const int nb = ELL / 32;            // value blocks per row
78    const int wrow = nb * (fmt == 4 ? 18 : 34);   // Q4DU: the weight row's bytes
79    const uint8_t* w = u_q8 + (size_t) g * (size_t) H * (size_t) wrow;
80    const uint8_t* x = ylq + (size_t) r * (size_t) (nb * 36);
81    float* o = out + (size_t) r * (size_t) H;
82    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
83    const int h = (int) (blockIdx.y * (blockDim.x >> 5)) + warp;
84    if (h >= H) return;
85    const uint8_t* wb = w + (size_t) h * (size_t) wrow;
86    float facc = 0.0f;
87    if (fmt == 4) {
88        for (int wi = lane; wi < nb * 4; wi += 32) {   // 4 int4 words per block (16 nibble bytes)
89            const int b = wi >> 2, j = (wi & 3) * 4;
90            facc += lat_blk_dot_q4(wb + (size_t) b * 18, x + (size_t) b * 36, j);
91        }
92    } else {
93    for (int wi = lane; wi < nb * 8; wi += 32) {
94        const int b = wi >> 3, j = (wi & 7) * 4;
95        const float dx = __half2float(*(const __half*) (x + (size_t) b * 36));
96        const float dw = __half2float(*(const __half*) (wb + (size_t) b * 34));
97        const int xw = *(const int*) (x + (size_t) b * 36 + 4 + j);
98        const int ww = latent_ld4_i8(wb + (size_t) b * 34 + 2 + j);
99        facc += dx * dw * (float) __dp4a(xw, ww, 0);
100    }
101    }
102    #pragma unroll
103    for (int off = 16; off > 0; off >>= 1) facc += __shfl_down_sync(0xffffffffu, facc, off);
104    if (lane == 0) o[h] = facc;
105}
106
107void latent_u_grouped(const uint8_t* u_q8, const uint8_t* ylq, const int32_t* ids, const int32_t* labels_dev,
108                      int64_t E, int64_t cap_entries, int ELL, int H, float* out, void* stream, int fmt) {
109    if (cap_entries <= 0) return;
110    if (u_q8 == nullptr || ylq == nullptr || ids == nullptr || labels_dev == nullptr || out == nullptr) {
111        std::fprintf(stderr, "latent_u_grouped NULL ptr: u=%p ylq=%p ids=%p labels=%p out=%p E=%lld cap=%lld ELL=%d H=%d\n",
112                     (const void*) u_q8, (const void*) ylq, (const void*) ids, (const void*) labels_dev,
113                     (const void*) out, (long long) E, (long long) cap_entries, ELL, H);
114        std::fflush(stderr);
115        std::abort();
116    }
117    const int warps_per_block = 8;   // 256 threads
118    const int rows_per_block = warps_per_block;
119    dim3 grid((unsigned) cap_entries, (unsigned) ((H + rows_per_block - 1) / rows_per_block));
120    latent_u_k<<<grid, warps_per_block * 32, 0, (cudaStream_t) stream>>>(u_q8, ylq, ids, labels_dev, (int) E,
121                                                                         (int) cap_entries, ELL, H, out, fmt);
122}
123
124// knife-0 (STRATA_LATENT_U_GPU): the CPU share's U computed on the GPU and written straight into parts_.
125// One block per routed row r (like latent_u_k), 8 warps.  A GPU row (r in dst[0..count)) copies hit_out;
126// a CPU row computes U[labels[ids[r]]] . hq[r] with the same dp4a dot as latent_u_k (bit-compatible to ~1e-7).
127__global__ void latent_u_matvec_k(const uint8_t* __restrict__ u_q8, const uint8_t* __restrict__ hq,
128                                  const int32_t* __restrict__ ids, const int32_t* __restrict__ labels,
129                                  const int32_t* __restrict__ dst, const int32_t* __restrict__ count,
130                                  int E, int n_entries, int ELL, int H, float* __restrict__ parts, int fmt) {
131    const int g = blockIdx.x;
132    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
133    const int hout = (int) (blockIdx.y * (blockDim.x >> 5)) + warp;
134    const int nb = ELL / 32, wrow = nb * (fmt == 4 ? 18 : 34);   // Q4DU
135    __shared__ int c_shared;
136    __shared__ uint8_t hq_s[2016];   // nb*36 = 56*36, ELL=1792 (latent) fixed
137    if (threadIdx.x == 0) c_shared = *count;
138    __syncthreads();
139    const int c = c_shared;
140    if (hout >= H) return;
141    const uint8_t* wb = u_q8 + (size_t) g * (size_t) H * (size_t) wrow + (size_t) hout * (size_t) wrow;
142    for (int r = 0; r < n_entries; ++r) {
143        const int32_t e = ids[r];
144        if (e < 0 || e >= E || labels[e] != g) continue;
145        bool gpu = false;
146        for (int i = 0; i < c; ++i) if (dst[i] == r) { gpu = true; break; }
147        if (gpu) continue;
148        const uint8_t* x = hq + (size_t) r * (size_t) (nb * 36);
149        for (int i = threadIdx.x; i < nb * 36; i += blockDim.x) hq_s[i] = x[i];   // once per block
150        __syncthreads();
151        float facc = 0.0f;
152        if (fmt == 4) {
153            for (int wi = lane; wi < nb * 4; wi += 32) {
154                const int b = wi >> 2, j = (wi & 3) * 4;
155                facc += lat_blk_dot_q4(wb + (size_t) b * 18, hq_s + (size_t) b * 36, j);
156            }
157        } else {
158        for (int wi = lane; wi < nb * 8; wi += 32) {
159            const int b = wi >> 3, j = (wi & 7) * 4;
160            const float dx = __half2float(*(const __half*) (hq_s + (size_t) b * 36));
161            const float dw = __half2float(__ldg((const __half*) (wb + (size_t) b * 34)));
162            const int xw = *(const int*) (hq_s + (size_t) b * 36 + 4 + j);
163            const int ww = latent_ld4_i8(wb + (size_t) b * 34 + 2 + j);
164            facc += dx * dw * (float) __dp4a(xw, ww, 0);
165        }
166        }
167        #pragma unroll
168        for (int off = 16; off > 0; off >>= 1) facc += __shfl_down_sync(0xffffffffu, facc, off);
169        if (lane == 0) parts[(size_t) r * (size_t) H + hout] = facc;
170        __syncthreads();
171    }
172}
173
174void latent_u_matvec(const uint8_t* u_q8, const uint8_t* hq, const int32_t* ids, const int32_t* labels_dev,
175                     const int32_t* dst, const int32_t* count, int64_t E, int64_t n_entries, int ELL, int H,
176                     int G, float* parts, void* stream, int fmt) {
177    if (n_entries <= 0 || G <= 0) return;
178    const int warps_per_block = 8;
179    dim3 grid((unsigned) G, (unsigned) ((H + warps_per_block - 1) / warps_per_block));
180    latent_u_matvec_k<<<grid, warps_per_block * 32, 0, (cudaStream_t) stream>>>(
181        u_q8, hq, ids, labels_dev, dst, count, (int) E, (int) n_entries, ELL, H, parts, fmt);
182}
183
184}  // namespace strata::kernels