okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f2b41fd29
main
1// tests/cuda/prefill_iq4_w4a8_test.cu - the opt-in IQ4 W4A8 expert kernel (STRATA_IQ4_W4A8, moe_iq4_w4a8.cu) against 2// the MMQ path it replaces, bit for bit. 3// 4// prefill_iq4_w4a8_test 4,096-token layer-chunks (a few seconds) 5// prefill_iq4_w4a8_test --full 15,360-token layer-chunks (a 16K prompt chunk's step) 6// 7// One prompt layer-chunk of a Qwen3.8-Flash-Next IQ4 pack's routed-expert products: T tokens x 10 experts each over 512 8// experts, the experts with rows in id order, 16 per launch; gate/up [1280 x 2560] IQ4_XS on the chunk's whole q8_1 9// activation array (absolute bounds), down [2560 x 640] IQ4_NL on each group's own q8_1 rows (group-local bounds) - the 10// Product fields prefill.cpp passes. Synthetic weights of the right format (valid f16 block scales) and activations of 11// row-varying magnitude, all from a hash of the index. Three routings (uniform, log-normal sigma 1 and 2: many experts 12// with a few rows, a few with hundreds) and two weight layouts (group buffers; with -DSTRATA_MMQ_TAB=ON also the pointer 13// table, each expert in its own slot with a guard, as STRATA_MMQ_DIRECT reads them). Every output word of 14// mmq::Context::run and of run_iq4_w4a8 (MMQ where it declines a product) must be equal, and the kernel must have run 15// some products of both types. Exit 0: identical; 1: a difference; 77: no CUDA device, or a GPU the kernel does not 16// run on (it covers sm_80..sm_88; elsewhere it declines every product and MMQ runs as before). 17#include "strata/prefill/moe_iq4_w4a8.hpp" 18#include "strata/prefill/mmq_ids_margin.hpp" 19#include "strata/prefill/moe_mmq.hpp" 20 21#include "ggml.h" 22 23#include <cuda_runtime.h> 24 25#include <algorithm> 26#include <cmath> 27#include <cstdint> 28#include <cstdio> 29#include <cstdlib> 30#include <cstring> 31#include <random> 32#include <string> 33#include <vector> 34 35namespace mmq = strata::prefill::mmq; 36 37namespace { 38 39void ck(cudaError_t e, const char* what) { 40 if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(2); } 41} 42 43__host__ __device__ inline uint64_t mix(uint64_t x) { // splitmix64 44 x += 0x9E3779B97F4A7C15ull; 45 x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull; 46 x = (x ^ (x >> 27)) * 0x94D049BB133111EBull; 47 return x ^ (x >> 31); 48} 49 50// random bytes, then each block's leading f16 d set to a small positive value (IQ4_XS and IQ4_NL blocks lead with d) 51__global__ void fill_weights(uint8_t* w, size_t n, uint64_t seed, size_t block_bytes, int wide) { 52 for (size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (size_t) gridDim.x * blockDim.x) { 53 const uint64_t h = mix(seed ^ (i * 0x100000001B3ull)); 54 uint8_t b = (uint8_t) h; 55 const size_t o = i % block_bytes; 56 if (o == 0) b = (uint8_t) (h >> 8); // d low byte 57 if (o == 1) b = 0x20; // d high byte: f16 0x20xx ~ 0.0078..0.016 58 if (wide && o == 1) { // --wide: any sign, exponent -10..+3 (scale extremes; no inf/nan/denormal) 59 const uint32_t e = 5 + (uint32_t) ((h >> 20) % 14u); 60 b = (uint8_t) (((h >> 40) & 1 ? 0x80 : 0) | (e << 2) | ((h >> 12) & 3)); 61 } 62 w[i] = b; 63 } 64} 65 66// x[r][c] = N(0,1) * m(r), m(r) in 0.1..10 67__global__ void fill_act(float* x, int64_t rows, int64_t cols, uint64_t seed, int64_t row0) { 68 const int64_t n = rows * cols; 69 for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) { 70 const int64_t r = i / cols + row0, c = i % cols; 71 const uint64_t h = mix(seed ^ ((uint64_t) r * 0x9E3779B97F4A7C15ull) ^ ((uint64_t) c << 1)); 72 const float u1 = ((h >> 40) + 1) * (1.0f / 16777217.0f), u2 = ((h >> 16) & 0xFFFFFF) * (1.0f / 16777216.0f); 73 const float g = sqrtf(-2.0f * logf(u1)) * cospif(2.0f * u2); 74 const float m = 0.1f + 9.9f * (float) (mix(seed ^ 0xABCDEFull ^ (uint64_t) r) >> 40) * (1.0f / 16777216.0f); 75 x[i] = g * m; 76 } 77} 78 79std::vector<int> routing(int64_t TK, double sigma) { // sigma 0: uniform 80 constexpr int NE = 512; 81 std::vector<int> c(NE, 0); 82 if (sigma <= 0.0) { 83 for (int e = 0; e < NE; ++e) c[e] = (int) (TK / NE + (e < TK % NE ? 1 : 0)); 84 return c; 85 } 86 std::mt19937_64 rng(1234); 87 std::normal_distribution<double> nd(0.0, 1.0); 88 std::vector<double> w(NE); 89 double sum = 0; 90 for (auto& x : w) { x = std::exp(sigma * nd(rng)); sum += x; } 91 int64_t got = 0; 92 for (int e = 0; e < NE; ++e) { c[e] = (int) std::floor(TK * w[e] / sum); got += c[e]; } 93 for (int e = 0; got < TK; e = (e + 1) % NE) { ++c[e]; ++got; } 94 return c; 95} 96 97struct Result { 98 size_t words = 0, differ = 0, unwritten = 0; 99 int64_t new_gu = 0, new_dn = 0, mmq_gu = 0, mmq_dn = 0; 100 double ms_gu[2] = {0, 0}, ms_dn[2] = {0, 0}; // --bench: the layer-chunk's gate/up and down products, MMQ (0) and the kernel (1), best of 5 101}; 102 103// one layer-chunk: MMQ into (gu_a, dm_a), the kernel (MMQ where it declines) into (gu_b, dm_b), then compare 104Result run_case(int64_t T, double sigma, bool tab, int wide, bool bench) { 105 constexpr int K = 10, G = 16, NFF = 640, N = 2560, NW = 4; // NW weight sets, cycled over the groups 106 const int64_t TK = T * K; 107 const ggml_type gt = GGML_TYPE_IQ4_XS, dt = GGML_TYPE_IQ4_NL; 108 const size_t gub = mmq::matrix_bytes(gt, 2 * NFF, N), db = mmq::matrix_bytes(dt, N, NFF); 109 const std::vector<int> cnt = routing(TK, sigma); 110 std::vector<int> order; 111 for (int e = 0; e < (int) cnt.size(); ++e) 112 if (cnt[e] > 0) order.push_back(e); 113 const int ngroups = (int) ((order.size() + G - 1) / G); 114 std::vector<int32_t> bounds_abs(order.size() + 1, 0); 115 for (size_t i = 0; i < order.size(); ++i) bounds_abs[i + 1] = bounds_abs[i] + cnt[(size_t) order[i]]; 116 int maxc = 0; 117 for (int e : order) maxc = std::max(maxc, cnt[e]); 118 119 constexpr size_t TAIL = 4096; // MMQ reads past a group buffer's last expert: zeroed, as the prompt path's 120 std::vector<uint8_t*> wgu(NW), wd(NW); 121 for (int i = 0; i < NW; ++i) { 122 ck(cudaMalloc(&wgu[i], G * gub + TAIL), "wgu"); 123 ck(cudaMalloc(&wd[i], G * db + TAIL), "wd"); 124 fill_weights<<<1024, 256>>>(wgu[i], G * gub, 0x1000 + i, ggml_type_size(gt), wide); 125 fill_weights<<<1024, 256>>>(wd[i], G * db, 0x2000 + i, ggml_type_size(dt), wide); 126 ck(cudaMemset(wgu[i] + G * gub, 0, TAIL), "tail"); 127 ck(cudaMemset(wd[i] + G * db, 0, TAIL), "tail"); 128 } 129 float* x; 130 ck(cudaMalloc(&x, (size_t) TK * N * 4), "x"); 131 fill_act<<<4096, 256>>>(x, TK, N, 0x3000, 0); 132 void* xq; 133 ck(cudaMalloc(&xq, mmq::q8_bytes(TK, N)), "xq"); 134 mmq::quantize(x, nullptr, xq, gt, N, N, TK, nullptr); 135 ck(cudaDeviceSynchronize(), "quantize x"); 136 ck(cudaFree(x), "free x"); 137 std::vector<void*> hq(ngroups); 138 std::vector<int32_t*> dbounds(ngroups); 139 float* h; 140 ck(cudaMalloc(&h, (size_t) maxc * G * NFF * 4), "h"); 141 for (int g = 0; g < ngroups; ++g) { 142 const int j0 = g * G, n = std::min<int>(G, (int) order.size() - j0); 143 const int64_t r0 = bounds_abs[j0], nr = bounds_abs[j0 + n] - r0; 144 fill_act<<<2048, 256>>>(h, nr, NFF, 0x4000, r0); 145 ck(cudaMalloc(&hq[g], mmq::q8_bytes(nr, NFF)), "hq"); 146 mmq::quantize(h, nullptr, hq[g], dt, NFF, NFF, nr, nullptr); 147 std::vector<int32_t> lb(n + 1); 148 for (int i = 0; i <= n; ++i) lb[i] = bounds_abs[j0 + i] - (int32_t) r0; 149 ck(cudaMalloc(&dbounds[g], (n + 1) * 4), "dbounds"); 150 ck(cudaMemcpy(dbounds[g], lb.data(), (n + 1) * 4, cudaMemcpyHostToDevice), "dbounds"); 151 } 152 ck(cudaDeviceSynchronize(), "quantize h"); 153 ck(cudaFree(h), "free h"); 154 int32_t *bounds_dev, *ids; 155 ck(cudaMalloc(&bounds_dev, bounds_abs.size() * 4), "bounds"); 156 ck(cudaMemcpy(bounds_dev, bounds_abs.data(), bounds_abs.size() * 4, cudaMemcpyHostToDevice), "bounds"); 157 const size_t ids_rows = (size_t) mmq::mmq_ids_table_rows((uint64_t) TK, (uint64_t) TK); // (mul_mat_q reads the row table past its last row: mmq_ids_margin.hpp) 158 ck(cudaMalloc(&ids, ids_rows * 4), "ids"); 159 mmq::iota(ids, (int64_t) ids_rows, nullptr); 160 float *gu_a, *dm_a, *gu_b, *dm_b; 161 const size_t ngu = (size_t) TK * 2 * NFF, ndm = (size_t) TK * N; 162 ck(cudaMalloc(&gu_a, ngu * 4), "gu_a"); 163 ck(cudaMalloc(&dm_a, ndm * 4), "dm_a"); 164 ck(cudaMalloc(&gu_b, ngu * 4), "gu_b"); 165 ck(cudaMalloc(&dm_b, ndm * 4), "dm_b"); 166 167 // the pointer-table layout: every expert in its own slot [gate | up | down] + a guard the prep zeroes 168 const size_t blob = gub + db, slot = blob + mmq::kSlotGuard; 169 uint8_t* ring = nullptr; 170 std::vector<mmq::WeightTab> tgu(ngroups), tdn(ngroups); 171 std::vector<mmq::GuardTab> guards(ngroups); 172 if (tab) { 173 ck(cudaMalloc(&ring, order.size() * slot), "ring"); 174 for (int g = 0; g < ngroups; ++g) { 175 const int j0 = g * G, n = std::min<int>(G, (int) order.size() - j0); 176 for (int i = 0; i < n; ++i) { 177 uint8_t* b = ring + (size_t) (j0 + i) * slot; 178 ck(cudaMemcpy(b, wgu[g % NW] + (size_t) i * gub, gub, cudaMemcpyDeviceToDevice), "ring gu"); 179 ck(cudaMemcpy(b + gub, wd[g % NW] + (size_t) i * db, db, cudaMemcpyDeviceToDevice), "ring d"); 180 ck(cudaMemset(b + blob, 0x7F, mmq::kSlotGuard), "ring guard"); // garbage: the prep must zero it 181 tgu[g].p[i] = b; 182 tdn[g].p[i] = b + gub; 183 guards[g].p[i] = b + blob; 184 } 185 guards[g].n = n; 186 } 187 ck(cudaDeviceSynchronize(), "ring"); 188 } 189 std::vector<mmq::Product> pgu(ngroups), pdn(ngroups); 190 for (int g = 0; g < ngroups; ++g) { 191 const int j0 = g * G, n = std::min<int>(G, (int) order.size() - j0); 192 const int64_t r0 = bounds_abs[j0], nr = bounds_abs[j0 + n] - r0; 193 int64_t maxr = 0; 194 for (int i = 0; i < n; ++i) maxr = std::max<int64_t>(maxr, cnt[(size_t) order[(size_t) (j0 + i)]]); 195 mmq::Product& a = pgu[g]; 196 a.w = wgu[g % NW]; a.type = gt; a.w_rows = 2 * NFF; a.w_cols = N; a.expert_bytes = gub; a.n = n; 197 a.xq = xq; a.bounds = bounds_dev + j0; a.ids = ids; a.total_rows = TK; a.max_rows = maxr; a.ld_dst = 2 * NFF; 198 if (tab) a.tab = &tgu[g]; 199 mmq::Product& b = pdn[g]; 200 b.w = wd[g % NW]; b.type = dt; b.w_rows = N; b.w_cols = NFF; b.expert_bytes = db; b.n = n; 201 b.xq = hq[g]; b.bounds = dbounds[g]; b.ids = ids; b.total_rows = nr; b.max_rows = maxr; b.ld_dst = N; 202 if (tab) b.tab = &tdn[g]; 203 } 204 cudaStream_t s; 205 ck(cudaStreamCreate(&s), "stream"); 206 mmq::Context ctx; 207 Result res; 208 for (int arm = 0; arm < 2; ++arm) { // 0: MMQ, 1: the kernel where it covers a product 209 float* gu = arm ? gu_b : gu_a; 210 float* dm = arm ? dm_b : dm_a; 211 ck(cudaMemsetAsync(gu, 0xFF, ngu * 4, s), "memset gu"); 212 ck(cudaMemsetAsync(dm, 0xFF, ndm * 4, s), "memset dm"); 213 for (int g = 0; g < ngroups; ++g) { // gate/up then down per group, as the prompt path interleaves them 214 if (tab) mmq::prep_group(guards[g], mmq::kSlotGuard, nullptr, nullptr, 0, s); 215 mmq::Product a = pgu[g], b = pdn[g]; 216 a.dst = gu; 217 b.dst = dm + bounds_abs[(size_t) g * G] * N; 218 if (arm == 1 && mmq::run_iq4_w4a8(a, s)) ++res.new_gu; 219 else { ctx.run(a, s); if (arm == 1) ++res.mmq_gu; } 220 if (arm == 1 && mmq::run_iq4_w4a8(b, s)) ++res.new_dn; 221 else { ctx.run(b, s); if (arm == 1) ++res.mmq_dn; } 222 } 223 ck(cudaStreamSynchronize(s), "run"); 224 ck(cudaGetLastError(), "run (launch)"); 225 } 226 if (bench) { // time the two product sets of the chunk per arm (the kernel where it covers a product, MMQ elsewhere) 227 cudaEvent_t e0, e1; 228 cudaEventCreate(&e0); cudaEventCreate(&e1); 229 for (int arm = 0; arm < 2; ++arm) { 230 for (int which = 0; which < 2; ++which) { // 0: gate/up, 1: down 231 double best = 1e30; 232 for (int rep = 0; rep < 5; ++rep) { 233 cudaEventRecord(e0, s); 234 for (int g = 0; g < ngroups; ++g) { 235 if (tab) mmq::prep_group(guards[g], mmq::kSlotGuard, nullptr, nullptr, 0, s); 236 mmq::Product a = pgu[g], b = pdn[g]; 237 a.dst = arm ? gu_b : gu_a; 238 b.dst = (arm ? dm_b : dm_a) + bounds_abs[(size_t) g * G] * N; 239 mmq::Product& q = which ? b : a; 240 if (arm == 1 && mmq::run_iq4_w4a8(q, s)) continue; 241 ctx.run(q, s); 242 } 243 cudaEventRecord(e1, s); 244 cudaEventSynchronize(e1); 245 float ms = 0; 246 cudaEventElapsedTime(&ms, e0, e1); 247 best = std::min<double>(best, ms); 248 } 249 (which ? res.ms_dn : res.ms_gu)[arm] = best; 250 } 251 } 252 cudaEventDestroy(e0); cudaEventDestroy(e1); 253 } 254 std::vector<uint32_t> ha(ngu), hb(ngu); 255 for (int part = 0; part < 2; ++part) { 256 const size_t n = part ? ndm : ngu; 257 ha.resize(n); 258 hb.resize(n); 259 ck(cudaMemcpy(ha.data(), part ? dm_a : gu_a, n * 4, cudaMemcpyDeviceToHost), "d2h a"); 260 ck(cudaMemcpy(hb.data(), part ? dm_b : gu_b, n * 4, cudaMemcpyDeviceToHost), "d2h b"); 261 for (size_t i = 0; i < n; ++i) { 262 res.differ += ha[i] != hb[i]; 263 res.unwritten += (ha[i] == 0xFFFFFFFFu) + (hb[i] == 0xFFFFFFFFu); 264 } 265 res.words += n; 266 } 267 cudaStreamDestroy(s); 268 for (auto p : wgu) cudaFree(p); 269 for (auto p : wd) cudaFree(p); 270 for (auto p : hq) cudaFree(p); 271 for (auto p : dbounds) cudaFree(p); 272 cudaFree(xq); cudaFree(bounds_dev); cudaFree(ids); cudaFree(ring); 273 cudaFree(gu_a); cudaFree(dm_a); cudaFree(gu_b); cudaFree(dm_b); 274 return res; 275} 276 277} // namespace 278 279int main(int argc, char** argv) { 280 bool full = false, wide = false, bench = false; 281 int64_t tokens = 0; // --tokens N: the layer-chunk's tokens (a tail: 97, 2049, 8191 ...) 282 for (int i = 1; i < argc; ++i) { 283 if (std::strcmp(argv[i], "--full") == 0) full = true; 284 else if (std::strcmp(argv[i], "--wide") == 0) wide = true; 285 else if (std::strcmp(argv[i], "--bench") == 0) bench = true; 286 else if (std::strcmp(argv[i], "--tokens") == 0 && i + 1 < argc) tokens = std::atoll(argv[++i]); 287 } 288 int ndev = 0; 289 if (cudaGetDeviceCount(&ndev) != cudaSuccess || ndev == 0) { 290 std::printf("prefill_iq4_w4a8_test: no CUDA device - skipped\n"); 291 return 77; 292 } 293 cudaDeviceProp prop{}; 294 ck(cudaGetDeviceProperties(&prop, 0), "device properties"); 295 const int cc = prop.major * 10 + prop.minor; 296 if ((cc < 80 || cc >= 89) && cc != 120) { 297 std::printf("prefill_iq4_w4a8_test: %s is sm_%d; the kernel runs on sm_80..sm_88 and sm_120 only (MMQ elsewhere) - skipped\n", 298 prop.name, cc); 299 return 77; 300 } 301 const int64_t T = tokens > 0 ? tokens : full ? 15360 : 4096; 302 std::vector<bool> layouts{false}; 303 if (mmq::tab_fits(GGML_TYPE_IQ4_XS, 1280) && mmq::tab_fits(GGML_TYPE_IQ4_NL, 2560)) layouts.push_back(true); 304 else std::printf("(this build has no pointer-table MMQ: the group-buffer layout only)\n"); 305 bool ok = true; 306 int64_t tot_gu = 0, tot_dn = 0; 307 for (double sigma : {0.0, 1.0, 2.0}) { 308 for (bool tab : layouts) { 309 const Result r = run_case(T, sigma, tab, wide ? 1 : 0, bench); 310 const bool pass = r.differ == 0 && r.unwritten == 0; // (coverage is checked over the whole run below: a launch MMQ would split along K stays on MMQ) 311 tot_gu += r.new_gu; tot_dn += r.new_dn; 312 if (bench) std::printf(" bench: gate/up MMQ %.3f ms, kernel %.3f ms (%+.1f%%); down MMQ %.3f ms, kernel %.3f ms (%+.1f%%)\n", r.ms_gu[0], r.ms_gu[1], 100.0 * (r.ms_gu[0] / r.ms_gu[1] - 1), r.ms_dn[0], r.ms_dn[1], 100.0 * (r.ms_dn[0] / r.ms_dn[1] - 1)); 313 std::printf("%s: %lld tokens%s, routing %s, %s: %zu words, %zu differ, %zu unwritten; kernel %lld + %lld products, " 314 "MMQ %lld + %lld (gate/up + down)\n", pass ? "PASS" : "FAIL", (long long) T, wide ? " (wide scales)" : "", 315 sigma > 0 ? (sigma > 1.5 ? "log-normal 2" : "log-normal 1") : "uniform", 316 tab ? "pointer table" : "group buffers", r.words, r.differ, r.unwritten, (long long) r.new_gu, 317 (long long) r.new_dn, (long long) r.mmq_gu, (long long) r.mmq_dn); 318 ok = ok && pass; 319 } 320 } 321 if (tot_dn == 0) { std::printf("FAIL: the kernel ran no down product in any case\n"); ok = false; } 322 if (tot_gu == 0) std::printf("note: the kernel ran no gate/up product (MMQ would split every such launch along K here)\n"); 323 std::printf("prefill_iq4_w4a8_test: %s on %s (sm_%d)\n", ok ? "all identical" : "DIFFERENCES", prop.name, cc); 324 return ok ? 0 : 1; 325}