okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1690a4a38
main
1// src/kernels/cuda/kv_stream.cu - see include/strata/kernels/kv_stream.hpp. 2#include "strata/kernels/kv_stream.hpp" 3#include "strata/kernels/kv_q4.hpp" 4#include "strata/kernels/kv_q8.hpp" 5 6#include <cuda_runtime.h> 7 8#include <algorithm> 9#include <cstdio> 10#include <cstdlib> 11 12namespace strata::kernels { 13namespace { 14 15void check(const char* what) { 16 const cudaError_t e = cudaGetLastError(); 17 if (e != cudaSuccess) { 18 std::fprintf(stderr, "kv_stream: %s: %s\n", what, cudaGetErrorString(e)); 19 std::exit(1); 20 } 21} 22 23constexpr int RT = 1024; // the resolve block 24 25// The per-block byte runs of the (up to four) pool arrays: block b of array i is bytes [b * len, (b + 1) * len). 26struct Runs { 27 const uint8_t* src[4]; 28 uint8_t* dst[4]; 29 int len[4]; 30 int n; 31}; 32 33Runs runs_of(const QsaAttnPools& slots, const KvHostPools& host, int fmt, const QsaShapes& s) { 34 const int rows = (int) (s.n_head_kv * s.page_size); 35 Runs r{}; 36 if (fmt == kKvHybrid) { // K8V4: int8 K codes, their scales, rotated q4_0 V 37 const int codes = rows * (int) s.head_dim, scales = rows * (int) (s.head_dim / KV_Q8_GROUP) * 2; 38 const int v = rows * (int) kv_q4_bytes_per_head((int) s.head_dim); 39 r.src[0] = (const uint8_t*) host.k_q; r.dst[0] = (uint8_t*) slots.k_q; r.len[0] = codes; 40 r.src[1] = (const uint8_t*) host.k_scale; r.dst[1] = (uint8_t*) slots.k_scale; r.len[1] = scales; 41 r.src[2] = (const uint8_t*) host.v_q4; r.dst[2] = (uint8_t*) slots.v_q4; r.len[2] = v; 42 r.n = 3; 43 } else if (fmt == kKvQ4) { 44 const int bytes = rows * (int) kv_q4_bytes_per_head((int) s.head_dim); 45 r.src[0] = (const uint8_t*) host.k_q4; r.dst[0] = (uint8_t*) slots.k_q4; r.len[0] = bytes; 46 r.src[1] = (const uint8_t*) host.v_q4; r.dst[1] = (uint8_t*) slots.v_q4; r.len[1] = bytes; 47 r.n = 2; 48 } else if (fmt == kKvInt8) { 49 const int codes = rows * (int) s.head_dim, scales = rows * (int) (s.head_dim / KV_Q8_GROUP) * 2; 50 r.src[0] = (const uint8_t*) host.k_q; r.dst[0] = (uint8_t*) slots.k_q; r.len[0] = codes; 51 r.src[1] = (const uint8_t*) host.v_q; r.dst[1] = (uint8_t*) slots.v_q; r.len[1] = codes; 52 r.src[2] = (const uint8_t*) host.k_scale; r.dst[2] = (uint8_t*) slots.k_scale; r.len[2] = scales; 53 r.src[3] = (const uint8_t*) host.v_scale; r.dst[3] = (uint8_t*) slots.v_scale; r.len[3] = scales; 54 r.n = 4; 55 } else { 56 const int bytes = rows * (int) s.head_dim * 2; 57 r.src[0] = (const uint8_t*) host.k_pool; r.dst[0] = (uint8_t*) slots.k_pool; r.len[0] = bytes; 58 r.src[1] = (const uint8_t*) host.v_pool; r.dst[1] = (uint8_t*) slots.v_pool; r.len[1] = bytes; 59 r.n = 2; 60 } 61 return r; 62} 63 64// Block-wide exclusive prefix sum of one int per thread (RT threads); `total` is the sum over the block. 65__device__ int block_scan(int v, int* warp_sums, int& total) { 66 const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; 67 int x = v; 68 for (int o = 1; o < 32; o <<= 1) { 69 const int y = __shfl_up_sync(0xffffffffu, x, o); 70 if (lane >= o) x += y; 71 } 72 if (lane == 31) warp_sums[w] = x; 73 __syncthreads(); 74 if (w == 0) { 75 int t = warp_sums[lane]; 76 for (int o = 1; o < 32; o <<= 1) { 77 const int y = __shfl_up_sync(0xffffffffu, t, o); 78 if (lane >= o) t += y; 79 } 80 warp_sums[lane] = t; 81 } 82 __syncthreads(); 83 total = warp_sums[31]; 84 const int excl = x - v + (w > 0 ? warp_sums[w - 1] : 0); 85 __syncthreads(); 86 return excl; 87} 88 89__global__ void __launch_bounds__(RT) resolve_kernel(KvStreamMap m, const int32_t* __restrict__ ids, 90 const int32_t* __restrict__ steps, int n_q, int cap, int page_size) { 91 __shared__ int s_nmiss, s_lookups, s_cut; 92 __shared__ int warp_sums[32]; 93 const int epoch = m.ctl[0] + 1; 94 if (threadIdx.x == 0) { s_nmiss = 0; s_lookups = 0; } 95 __syncthreads(); 96 // 1. hits take this epoch and their reference bit; a missing block is claimed exactly once (-1 -> -2) 97 int lookups = 0; 98 for (int q = 0; q < n_q; ++q) { 99 const int width = steps[q * kStepCount + kStepWidth]; 100 const int32_t* qi = ids + (long long) q * cap; 101 for (int i = threadIdx.x; i < width; i += RT) { 102 const int b = qi[i] / page_size; 103 if (i > 0 && qi[i - 1] / page_size == b) continue; // ids are ascending: one lookup per block 104 ++lookups; 105 const int sl = m.page_table[b]; 106 if (sl >= 0) { 107 m.slot_stamp[sl] = epoch; 108 m.slot_ref[sl] = 1; 109 } else if (sl == -1 && atomicCAS(&m.page_table[b], -1, -2) == -1) { 110 m.miss_block[atomicAdd(&s_nmiss, 1)] = b; 111 } 112 } 113 } 114 if (lookups > 0) atomicAdd(&s_lookups, lookups); // (#783, stuchapin909) most threads see none: skip the shared atomic 115 __syncthreads(); 116 // 2. one victim per miss: a clock sweep from the hand. A slot this call uses (stamp == epoch) is never taken; 117 // a referenced one loses its bit as the hand passes it and is taken on the next pass. 118 const int need = s_nmiss, n = (int) m.n_slots; 119 int hand = m.ctl[1], got = 0; 120 for (int scanned = 0; got < need && scanned < 3 * n; scanned += RT) { 121 const int j = (int) (((long long) hand + threadIdx.x) % n); 122 const bool mine = m.slot_stamp[j] == epoch; 123 const bool cand = !mine && (m.slot_block[j] < 0 || m.slot_ref[j] == 0); 124 int total = 0; 125 const int rank = block_scan(cand ? 1 : 0, warp_sums, total); 126 const int want = need - got; 127 if (threadIdx.x == 0) s_cut = RT; 128 __syncthreads(); 129 if (cand && rank == want - 1) s_cut = threadIdx.x + 1; // the hand stops just past the last slot taken 130 __syncthreads(); 131 const int cut = s_cut; 132 if (cand && rank < want) { 133 m.miss_slot[got + rank] = j; 134 m.slot_stamp[j] = epoch; // taken: a sweep that wraps around must not take it twice 135 } else if (threadIdx.x < cut && !mine) { 136 m.slot_ref[j] = 0; 137 } 138 got += total < want ? total : want; 139 hand = (int) (((long long) hand + cut) % n); 140 __syncthreads(); 141 } 142 // 3. re-point the table; the copy kernel fills the slots 143 const int placed = got < need ? got : need; 144 for (int k = threadIdx.x; k < need; k += RT) { 145 const int b = m.miss_block[k]; 146 if (k >= placed) { m.page_table[b] = -1; continue; } // overflow: never happens with a legal n_slots 147 const int sl = m.miss_slot[k]; 148 const int old = m.slot_block[sl]; 149 if (old >= 0) m.page_table[old] = -1; 150 m.slot_block[sl] = b; 151 m.slot_stamp[sl] = epoch; 152 m.slot_ref[sl] = 1; 153 m.page_table[b] = sl; 154 } 155 if (threadIdx.x == 0) { 156 m.ctl[0] = epoch; 157 m.ctl[1] = hand; 158 m.ctl[2] = placed; 159 if (placed < need) m.ctl[3] = 1; 160 unsigned long long* c = reinterpret_cast<unsigned long long*>(m.ctl + 4); 161 c[0] += (unsigned long long) placed; 162 c[1] += (unsigned long long) s_lookups; 163 c[2] += 1ull; 164 } 165} 166 167// One block per missed block (grid-stride): copy its runs from the host copy into its slot, 16 B per thread. 168__global__ void copy_kernel(KvStreamMap m, Runs r) { 169 const int need = m.ctl[2]; 170 for (int k = blockIdx.x; k < need; k += gridDim.x) { 171 const long long b = m.miss_block[k], sl = m.miss_slot[k]; 172 for (int a = 0; a < r.n; ++a) { 173 const uint4* src = reinterpret_cast<const uint4*>(r.src[a] + b * r.len[a]); 174 uint4* dst = reinterpret_cast<uint4*>(r.dst[a] + sl * r.len[a]); 175 for (int i = threadIdx.x; i < r.len[a] / 16; i += blockDim.x) dst[i] = src[i]; 176 } 177 } 178} 179 180__global__ void reset_kernel(KvStreamMap m) { 181 const long long i0 = (long long) blockIdx.x * blockDim.x + threadIdx.x, st = (long long) gridDim.x * blockDim.x; 182 for (long long i = i0; i < m.n_blocks; i += st) m.page_table[i] = -1; 183 for (long long i = i0; i < m.n_slots; i += st) { 184 m.slot_block[i] = -1; 185 m.slot_stamp[i] = -1; 186 m.slot_ref[i] = 0; 187 } 188 if (i0 < kKvCtlInts) m.ctl[i0] = 0; 189} 190 191__global__ void ring_kernel(int32_t* table, long long n_blocks, long long n_slots) { 192 for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < n_blocks; 193 i += (long long) gridDim.x * blockDim.x) 194 table[i] = (int32_t) (i % n_slots); 195} 196 197} // namespace 198 199uint64_t kv_block_bytes(const QsaShapes& s, int fmt) { 200 const uint64_t rows = (uint64_t) (s.n_head_kv * s.page_size); 201 if (fmt == kKvHybrid) 202 return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / KV_Q8_GROUP) * 2 + 203 rows * kv_q4_bytes_per_head((int) s.head_dim); 204 if (fmt == kKvQ4) return rows * kv_q4_bytes_per_head((int) s.head_dim) * 2; 205 return fmt == kKvInt8 ? rows * (uint64_t) s.head_dim * 2 + rows * (uint64_t) (s.head_dim / KV_Q8_GROUP) * 2 * 2 206 : rows * (uint64_t) s.head_dim * 2 * 2; 207} 208 209void kv_stream_reset(const KvStreamMap& m, void* stream) { 210 reset_kernel<<<128, 256, 0, (cudaStream_t) stream>>>(m); 211 check("reset"); 212} 213 214void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const KvHostPools& host, int fmt, 215 const int32_t* ids, const int32_t* steps, int64_t n_q, int64_t cap, const QsaShapes& s, 216 void* stream) { 217 if (n_q <= 0) return; 218 if (s.n_head_kv * s.page_size * (s.head_dim / KV_Q8_GROUP) * 2 % 16 != 0) { 219 std::fprintf(stderr, "kv_stream: a block's scale run must be a multiple of 16 bytes\n"); 220 std::exit(1); 221 } 222 // one sweep step looks at RT consecutive slots `(hand + thread) % n_slots`; with fewer slots than RT two 223 // threads see the same slot and may both take it for two different misses. The engine never streams with fewer 224 // than qsa_kv_resident_min() / page_size = 5,120 slots, so this is a guard, not a limit. 225 if (m.n_slots < RT) { 226 std::fprintf(stderr, "kv_stream: %lld slots is fewer than the resolve block (%d): the clock sweep would take a " 227 "slot twice\n", (long long) m.n_slots, RT); 228 std::exit(1); 229 } 230 resolve_kernel<<<1, RT, 0, (cudaStream_t) stream>>>(m, ids, steps, (int) n_q, (int) cap, (int) s.page_size); 231 check("resolve"); 232 copy_kernel<<<96, 128, 0, (cudaStream_t) stream>>>(m, runs_of(slots, host, fmt, s)); 233 check("copy"); 234} 235 236void kv_ring_table(int32_t* page_table, int64_t n_blocks, int64_t n_slots, void* stream) { 237 ring_kernel<<<64, 256, 0, (cudaStream_t) stream>>>(page_table, n_blocks, n_slots); 238 check("ring table"); 239} 240 241void kv_ring_restore(const QsaAttnPools& slots, const KvHostPools& host, int fmt, int64_t b0, int64_t b1, 242 int64_t n_slots, const QsaShapes& s, void* stream) { 243 const Runs r = runs_of(slots, host, fmt, s); 244 for (int64_t b = b0; b < b1;) { 245 const int64_t sl = b % n_slots, run = std::min<int64_t>(b1 - b, n_slots - sl); // up to the ring's end 246 for (int a = 0; a < r.n; ++a) 247 if (cudaMemcpyAsync(r.dst[a] + sl * r.len[a], r.src[a] + b * r.len[a], (size_t) (run * r.len[a]), 248 cudaMemcpyDefault, (cudaStream_t) stream) != cudaSuccess) 249 check("ring restore"); 250 b += run; 251 } 252} 253 254void kv_stage_from_host(const QsaAttnPools& stage, const KvHostPools& host, int fmt, int64_t n_blocks, 255 const QsaShapes& s, void* stream) { 256 if (n_blocks <= 0) return; 257 const Runs r = runs_of(stage, host, fmt, s); 258 for (int a = 0; a < r.n; ++a) 259 if (cudaMemcpyAsync(r.dst[a], r.src[a], (size_t) (n_blocks * r.len[a]), cudaMemcpyDefault, 260 (cudaStream_t) stream) != cudaSuccess) 261 check("stage"); 262} 263 264void kv_unstage_to_host(const QsaAttnPools& stage, const KvHostPools& host, int fmt, int64_t b0, int64_t b1, 265 const QsaShapes& s, void* stream) { 266 if (b1 <= b0) return; 267 const Runs r = runs_of(stage, host, fmt, s); // src: the host copy, dst: the staging pool (identity layout both) 268 for (int a = 0; a < r.n; ++a) 269 if (cudaMemcpyAsync((void*) (r.src[a] + b0 * r.len[a]), r.dst[a] + b0 * r.len[a], (size_t) ((b1 - b0) * r.len[a]), 270 cudaMemcpyDefault, (cudaStream_t) stream) != cudaSuccess) 271 check("unstage"); 272} 273 274KvStreamCounters kv_stream_counters(const KvStreamMap& m) { 275 int32_t c[kKvCtlInts] = {}; 276 KvStreamCounters r; 277 if (m.ctl == nullptr || cudaMemcpy(c, m.ctl, sizeof(c), cudaMemcpyDeviceToHost) != cudaSuccess) return r; 278 const unsigned long long* u = reinterpret_cast<const unsigned long long*>(c + 4); 279 r.misses = u[0]; 280 r.lookups = u[1]; 281 r.calls = u[2]; 282 r.overflow = c[3] != 0; 283 return r; 284} 285 286} // namespace strata::kernels