okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
248dbee5b
main
1// route_resident_parity - the warp-parallel STRATA_ROUTE_RESIDENT swap against a scalar reference of the same 2// semantics, bit for bit. 3// 4// route_resident_k is one warp per token: lane j scans experts j, j + 32, ... and the warp reduces the best 5// logit in a shuffle tree, where the form it replaced walked all 512 experts on a single thread. The two have 6// to land on the same expert and leave the same bits in ids and weights, because the option's whole 7// justification is that it moves misses across PCIe and not the model. This checks that on random cases built 8// for the corners: many equal logits (the tie rule is the smallest expert index), repeated ids, a partly 9// resident table, random rank windows, and margins from below to above the gap a swap needs. 10// 11// The reference below is the spec written out plainly - a serial walk with the same comparisons - and not a 12// copy of the kernel that the parallel form replaced. It runs on the device so that expf, and therefore the 13// softmax bits, are the same function in both. 14// 15// Run: route_resident_parity (ctest: route_resident_parity; GPU, synthetic, no model) 16#include "strata/kernels/native_router.hpp" 17 18#include <cuda_runtime.h> 19 20#include <cmath> 21#include <cstdlib> 22#include <cstdint> 23#include <cstdio> 24#include <cstring> 25#include <random> 26#include <vector> 27 28namespace { 29void ck(cudaError_t e, const char* what) { 30 if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(2); } 31} 32 33constexpr int kExperts = 512; 34constexpr int kTop = 10; 35constexpr int kMaxTok = 8; 36// The weights are a softmax ratio (ten expf calls, a sum, one division). The kernel is bit-identical to the 37// serial form it replaced - that was measured with both kernels side by side in one translation unit - but 38// this reference is a second compilation, and two compilations of that expression land within a handful of 39// ulp of each other (expf is an approximation, and the ratio amplifies it). 8 ulp is 1e-6 relative: an order 40// of magnitude below anything the engine can act on, and far above what a semantic difference would produce. 41constexpr int kWeightUlp = 8; 42 43// The spec. One thread per token, serial scan of all 512 experts, the comparisons the warp form reduces to: 44// a strictly greater logit wins, so the smallest expert index keeps a tie, and the already-picked test runs 45// against the ids as they are at that rank (a swap changes the set). 46__global__ void route_resident_ref_k(const float* __restrict__ logits, int32_t* __restrict__ ids, 47 float* __restrict__ weights, const int32_t* __restrict__ res, int n_tok, 48 float margin, int lo, int hi, unsigned long long* __restrict__ stats) { 49 const int t = blockIdx.x * blockDim.x + threadIdx.x; 50 if (t >= n_tok) return; 51 const float* l = logits + (size_t) t * kExperts; 52 int32_t* id = ids + (size_t) t * kTop; 53 int32_t my[kTop]; 54 for (int r = 0; r < kTop; ++r) my[r] = id[r]; 55 int swaps = 0, tail = 0, before = 0; 56 for (int r = 0; r < kTop; ++r) before += res[my[r]] < 0; 57 for (int r = lo; r <= hi && r < kTop; ++r) { 58 const int e = my[r]; 59 if (res[e] >= 0) continue; // resident already: nothing to swap 60 ++tail; 61 float bv = -INFINITY; 62 int bi = -1; 63 for (int f = 0; f < kExperts; ++f) { 64 if (res[f] < 0) continue; 65 bool used = false; 66 for (int q = 0; q < kTop; ++q) used |= my[q] == f; 67 if (used) continue; 68 if (l[f] > bv) { bv = l[f]; bi = f; } 69 } 70 if (bi >= 0 && l[e] - bv <= margin) { my[r] = bi; ++swaps; } 71 } 72 int after = 0; 73 for (int r = 0; r < kTop; ++r) after += res[my[r]] < 0; 74 if (swaps) { 75 float m = -INFINITY; 76 for (int r = 0; r < kTop; ++r) m = fmaxf(m, l[my[r]]); 77 float ex[kTop], sum = 0.0f; 78 for (int r = 0; r < kTop; ++r) { ex[r] = expf(l[my[r]] - m); sum += ex[r]; } 79 for (int r = 0; r < kTop; ++r) weights[(size_t) t * kTop + r] = ex[r] / sum; 80 } 81 for (int r = 0; r < kTop; ++r) id[r] = my[r]; 82 if (stats) { 83 atomicAdd(stats + 0, (unsigned long long) tail); 84 atomicAdd(stats + 1, (unsigned long long) swaps); 85 atomicAdd(stats + 2, (unsigned long long) before); 86 atomicAdd(stats + 3, (unsigned long long) after); 87 } 88} 89 90// The router's top-10 of a row, ties to the smallest index - what the kernel is handed as `ids`. 91void top10(const float* l, int32_t* out) { 92 for (int r = 0; r < kTop; ++r) { 93 float bv = -INFINITY; 94 int bi = -1; 95 for (int f = 0; f < kExperts; ++f) { 96 bool used = false; 97 for (int q = 0; q < r; ++q) used |= out[q] == f; 98 if (used) continue; 99 if (l[f] > bv) { bv = l[f]; bi = f; } 100 } 101 out[r] = bi; 102 } 103} 104} // namespace 105 106int main() { 107 const float margins[] = {-0.5f, 0.0f, 0.05f, 0.25f, 0.5f, 1.0f, 1.5f}; 108 const int n_margins = (int) (sizeof(margins) / sizeof(margins[0])); 109 const int cases = 240; 110 std::mt19937 rng(20261010u); 111 std::uniform_real_distribution<float> ud(-3.0f, 3.0f); 112 std::uniform_int_distribution<int> pick(0, 1); 113 std::uniform_int_distribution<int> coin(0, 99); 114 115 std::vector<float> logits((size_t) kMaxTok * kExperts), weights((size_t) kMaxTok * kTop); 116 std::vector<int32_t> ids((size_t) kMaxTok * kTop), res(kExperts); 117 std::vector<float> sentinel(weights.size()); 118 const uint32_t pattern = 0xA5A5A5A5u; 119 for (size_t i = 0; i < sentinel.size(); ++i) std::memcpy(&sentinel[i], &pattern, 4); 120 121 float* d_logits = nullptr; 122 float* d_w_ref = nullptr; 123 float* d_w_par = nullptr; 124 int32_t* d_ids_ref = nullptr; 125 int32_t* d_ids_par = nullptr; 126 int32_t* d_res = nullptr; 127 unsigned long long* d_stats = nullptr; 128 ck(cudaMalloc(&d_logits, logits.size() * 4), "logits"); 129 ck(cudaMalloc(&d_w_ref, weights.size() * 4), "w_ref"); 130 ck(cudaMalloc(&d_w_par, weights.size() * 4), "w_par"); 131 ck(cudaMalloc(&d_ids_ref, ids.size() * 4), "ids_ref"); 132 ck(cudaMalloc(&d_ids_par, ids.size() * 4), "ids_par"); 133 ck(cudaMalloc(&d_res, res.size() * 4), "res"); 134 ck(cudaMalloc(&d_stats, 4 * sizeof(unsigned long long)), "stats"); 135 cudaStream_t stream = nullptr; 136 ck(cudaStreamCreate(&stream), "stream"); 137 138 int bad = 0, swapped_cases = 0, stats_bad = 0, dumped = 0, worst_ulp = 0; 139 unsigned long long swaps_total = 0; 140 for (int c = 0; c < cases; ++c) { 141 const int n_tok = 1 + (c % kMaxTok); 142 const float margin = margins[c % n_margins]; 143 // The rank window: what the profile marks as tail. Sometimes the whole tail, sometimes a slice. 144 const int lo = pick(rng) ? 4 + (c % 4) : 0; 145 const int hi = pick(rng) ? kTop - 1 : lo + (c % (kTop - lo)); 146 const bool tie_heavy = pick(rng) != 0; // half the cases round the logits onto a coarse grid 147 const bool ids_from_router = pick(rng) != 0; // the other half get ids with repeats instead 148 const int resident_pct = 40 + coin(rng) % 45; // 40-84% of the table resident 149 150 for (int e = 0; e < kExperts; ++e) res[e] = (coin(rng) < resident_pct) ? (int32_t) (e % 7) : -1; 151 for (size_t i = 0; i < logits.size(); ++i) { 152 float v = ud(rng); 153 if (tie_heavy) v = std::round(v * 2.0f) * 0.5f; // many equal logits, so the tie rule gets used 154 logits[i] = v; 155 } 156 for (int t = 0; t < n_tok; ++t) { 157 int32_t* row = ids.data() + (size_t) t * kTop; 158 if (ids_from_router) { 159 top10(logits.data() + (size_t) t * kExperts, row); 160 } else { 161 for (int r = 0; r < kTop; ++r) row[r] = (int32_t) (rng() % kExperts); // repeats on purpose 162 } 163 } 164 165 ck(cudaMemcpy(d_logits, logits.data(), logits.size() * 4, cudaMemcpyHostToDevice), "up logits"); 166 ck(cudaMemcpy(d_res, res.data(), res.size() * 4, cudaMemcpyHostToDevice), "up res"); 167 168 // Reference, from the router's ids and a sentinel weight buffer, with its own counters. 169 ck(cudaMemcpy(d_ids_ref, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "up ids ref"); 170 ck(cudaMemcpy(d_w_ref, sentinel.data(), sentinel.size() * 4, cudaMemcpyHostToDevice), "up w ref"); 171 ck(cudaMemset(d_stats, 0, 4 * sizeof(unsigned long long)), "zero stats"); 172 route_resident_ref_k<<<(n_tok + 63) / 64, 64, 0, stream>>>(d_logits, d_ids_ref, d_w_ref, d_res, n_tok, 173 margin, lo, hi, d_stats); 174 ck(cudaStreamSynchronize(stream), "sync ref"); 175 unsigned long long st_ref[4] = {0, 0, 0, 0}; 176 ck(cudaMemcpy(st_ref, d_stats, sizeof(st_ref), cudaMemcpyDeviceToHost), "down stats ref"); 177 178 // The shipped kernel, same inputs, same sentinel. 179 ck(cudaMemcpy(d_ids_par, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "up ids par"); 180 ck(cudaMemcpy(d_w_par, sentinel.data(), sentinel.size() * 4, cudaMemcpyHostToDevice), "up w par"); 181 ck(cudaMemset(d_stats, 0, 4 * sizeof(unsigned long long)), "zero stats"); 182 strata::kernels::native_route_resident(d_logits, d_ids_par, d_w_par, d_res, n_tok, margin, lo, hi, 183 d_stats, (void*) stream); 184 ck(cudaStreamSynchronize(stream), "sync par"); 185 unsigned long long st_par[4] = {0, 0, 0, 0}; 186 ck(cudaMemcpy(st_par, d_stats, sizeof(st_par), cudaMemcpyDeviceToHost), "down stats par"); 187 188 std::vector<int32_t> i_ref(ids.size()), i_par(ids.size()); 189 std::vector<float> w_ref(weights.size()), w_par(weights.size()); 190 ck(cudaMemcpy(i_ref.data(), d_ids_ref, i_ref.size() * 4, cudaMemcpyDeviceToHost), "down ids ref"); 191 ck(cudaMemcpy(i_par.data(), d_ids_par, i_par.size() * 4, cudaMemcpyDeviceToHost), "down ids par"); 192 ck(cudaMemcpy(w_ref.data(), d_w_ref, w_ref.size() * 4, cudaMemcpyDeviceToHost), "down w ref"); 193 ck(cudaMemcpy(w_par.data(), d_w_par, w_par.size() * 4, cudaMemcpyDeviceToHost), "down w par"); 194 195 const bool ids_same = i_ref == i_par; 196 // Weights: the kernel is bit-identical to the serial form it replaced (measured with both kernels 197 // side by side in one translation unit); this reference is a second compilation, so its softmax can 198 // round a division differently. Compare within a few ulp and report the worst seen. 199 int w_ulp = 0; 200 for (size_t i = 0; i < w_ref.size(); ++i) { 201 uint32_t a = 0, b = 0; 202 std::memcpy(&a, &w_ref[i], 4); 203 std::memcpy(&b, &w_par[i], 4); 204 if (a != b) { 205 const uint32_t d = a > b ? a - b : b - a; 206 if ((int) d > w_ulp) w_ulp = (int) d; 207 } 208 } 209 if (w_ulp > worst_ulp) worst_ulp = w_ulp; 210 const bool w_same = w_ulp <= kWeightUlp; 211 const bool st_same = std::memcmp(st_ref, st_par, sizeof(st_ref)) == 0; 212 if (!ids_same || !w_same || !st_same) { 213 ++bad; 214 if (!st_same) ++stats_bad; 215 std::printf(" case %3d n_tok %d margin %.2f ranks [%d,%d] ties %d ids %s weights %s (%d ulp) stats %s\n", 216 c, n_tok, margin, lo, hi, (int) tie_heavy, ids_same ? "same" : "*** DIFFER ***", 217 w_same ? "same" : "*** DIFFER ***", w_ulp, st_same ? "same" : "*** DIFFER ***"); 218 if (std::getenv("STRATA_PARITY_DUMP") && dumped < 2) { 219 ++dumped; 220 for (int t = 0; t < n_tok; ++t) { 221 std::printf(" token %d ids in ", t); 222 for (int r = 0; r < kTop; ++r) std::printf(" %d", ids[(size_t) t * kTop + r]); 223 std::printf("\n ids ref "); 224 for (int r = 0; r < kTop; ++r) std::printf(" %d", i_ref[(size_t) t * kTop + r]); 225 std::printf("\n ids par "); 226 for (int r = 0; r < kTop; ++r) std::printf(" %d", i_par[(size_t) t * kTop + r]); 227 std::printf("\n logits "); 228 for (int r = 0; r < kTop; ++r) 229 std::printf(" %.9g", logits[(size_t) t * kExperts + i_ref[(size_t) t * kTop + r]]); 230 std::printf("\n w ref "); 231 for (int r = 0; r < kTop; ++r) 232 std::printf(" %08x", *(uint32_t*) &w_ref[(size_t) t * kTop + r]); 233 std::printf("\n w par "); 234 for (int r = 0; r < kTop; ++r) 235 std::printf(" %08x", *(uint32_t*) &w_par[(size_t) t * kTop + r]); 236 std::printf("\n"); 237 } 238 } 239 } 240 if (st_par[1]) { ++swapped_cases; swaps_total += st_par[1]; } 241 } 242 243 std::printf("route_resident_parity: %d cases, %d with swaps (%llu swaps), %d mismatches, weights within %d ulp\n", 244 cases, swapped_cases, swaps_total, bad, worst_ulp); 245 if (stats_bad) std::printf(" (%d of them in the counters)\n", stats_bad); 246 if (swapped_cases == 0) { 247 std::printf("route_resident_parity: no case swapped anything - the test proved nothing\n"); 248 ++bad; 249 } 250 std::printf(bad ? "route_resident_parity: %d FAILURES\n" : "route_resident_parity OK\n", bad); 251 cudaFree(d_logits); cudaFree(d_w_ref); cudaFree(d_w_par); 252 cudaFree(d_ids_ref); cudaFree(d_ids_par); cudaFree(d_res); cudaFree(d_stats); 253 cudaStreamDestroy(stream); 254 return bad ? 1 : 0; 255}