diff --git a/src/dsv41/ds4_iq.cu b/src/dsv41/ds4_iq.cu index cc486f3c..a8dab64e 100644 --- a/src/dsv41/ds4_iq.cu +++ b/src/dsv41/ds4_iq.cu @@ -506,11 +506,13 @@ template <> struct Fast { static constexpr int WORDS = 8192; }; #else template struct Fast { static constexpr int WORDS = 0; }; #endif -template constexpr int kTabWords = Fast::WORDS > 0 ? Fast::WORDS : (Ty::TAB > 0 ? Ty::TAB : 1); +// F: whether the fast form is wanted (the kernels of many rows a pass are bound by the dot products and their registers, and the +// larger codebook's shared memory costs them occupancy: they keep decode) +template constexpr int kTabWords = F && Fast::WORDS > 0 ? Fast::WORDS : (Ty::TAB > 0 ? Ty::TAB : 1); -template +template __device__ __forceinline__ void load_tab_fast(uint32_t* tab) { - if constexpr (Fast::WORDS == 0) { + if constexpr (!F || Fast::WORDS == 0) { load_tab(tab); } else if constexpr (T == kIQ1_M) { for (int j = threadIdx.x; j < 4096; j += blockDim.x) { @@ -520,9 +522,9 @@ __device__ __forceinline__ void load_tab_fast(uint32_t* tab) { } } } -template +template __device__ __forceinline__ void decode_fast_b(const uint8_t* __restrict__ b, int ib, const uint32_t* tab, Sub& s) { - if constexpr (Fast::WORDS == 0) { + if constexpr (!F || Fast::WORDS == 0) { decode_b(b, ib, tab, s); } else if constexpr (T == kIQ1_M) { // (56-byte blocks in 1120-byte rows at 256-aligned offsets: 8-byte aligned) const uint32_t qsw = *(const uint32_t*) (b + 4 * ib); @@ -941,50 +943,56 @@ __global__ void __launch_bounds__(kThreads) light_q8_kernel(const float* __restr // grid (n_ff / 8 or n_embd / 8, n_exp): a light expert's rows, a warp a row of the weights (gate and up, or down), every // row of the expert a pass -> h16 (the F16 swiglu) or y template -__global__ void __launch_bounds__(kThreads) light_kernel(const SetArgs a, const int8_t* __restrict__ xq, +__global__ void __launch_bounds__(kThreads, NE >= 8 ? 4 : 1) light_kernel(const SetArgs a, const int8_t* __restrict__ xq, const float* __restrict__ xd) { - __shared__ uint32_t tab[Ty::TAB > 0 ? Ty::TAB : 1]; + constexpr int kBPS = kQK == 32 ? 1 : 8, kStep = 32 / kBPS; // (as the token kernels: a lane keeps its sub-block position) + constexpr bool kF = NE <= 4; + __shared__ __align__(16) uint32_t tab[kTabWords]; const int e = blockIdx.y; const int lo = a.bounds[e] - a.row0, ne = a.bounds[e + 1] - a.bounds[e]; if (ne <= 0 || ne > NE) return; // (uniform: the tiles take an expert of more rows) - load_tab(tab); + load_tab_fast(tab); __syncthreads(); - const int K = GATE_UP ? a.n_embd : a.n_ff, N = GATE_UP ? a.n_ff : a.n_embd, nsb = K / 32; - const int row = blockIdx.x * kWarps + (threadIdx.x >> 5), lane = threadIdx.x & 31; - if (row >= N) return; + const int K = GATE_UP ? a.n_embd : a.n_ff, N = GATE_UP ? a.n_ff : a.n_embd, nsb = K / 32, nblk = nsb / kBPS; + const int lane = threadIdx.x & 31; + const int ib0 = kBPS == 8 ? lane & 7 : 0, blk0 = kBPS == 8 ? lane >> 3 : lane; const uint8_t* blob = a.wbase + (size_t) e * a.stride; const size_t rb = row_bytes_t(K); - const uint8_t* w0 = blob + a.tr[GATE_UP ? 0 : 2] + (size_t) row * rb; - const uint8_t* w1 = blob + a.tr[1] + (size_t) row * rb; const size_t q0 = (size_t) e * kLightRows; - float a0[NE], a1[NE]; + // (a persistent grid, as the token kernels': blockIdx.x strides over the tiles of kWarps rows) + for (int row = blockIdx.x * kWarps + (threadIdx.x >> 5); row < N; row += gridDim.x * kWarps) { + const uint8_t* w0 = blob + a.tr[GATE_UP ? 0 : 2] + (size_t) row * rb; + const uint8_t* w1 = blob + a.tr[1] + (size_t) row * rb; + float a0[NE], a1[NE]; #pragma unroll - for (int i = 0; i < NE; ++i) a0[i] = a1[i] = 0.0f; - for (int kb = lane; kb < nsb; kb += 32) { - Sub s0, s1; - decode(w0, kb, tab, s0); - if (GATE_UP) decode(w1, kb, tab, s1); + for (int i = 0; i < NE; ++i) a0[i] = a1[i] = 0.0f; + for (int blk = blk0; blk < nblk; blk += kStep) { + const int kb = blk * kBPS + ib0; + Sub s0, s1; + decode_fast_b(w0 + (size_t) blk * Ty::B, ib0, tab, s0); + if (GATE_UP) decode_fast_b(w1 + (size_t) blk * Ty::B, ib0, tab, s1); +#pragma unroll + for (int i = 0; i < NE; ++i) + if (i < ne) { + const int4* xp = (const int4*) (xq + (q0 + i) * K + (size_t) kb * 32); + const int4 xa = xp[0], xb = xp[1]; + const float dx = xd[(q0 + i) * nsb + kb]; + a0[i] = fmaf(dx, sub_dot(s0, xa, xb), a0[i]); + if (GATE_UP) a1[i] = fmaf(dx, sub_dot(s1, xa, xb), a1[i]); + } + } #pragma unroll for (int i = 0; i < NE; ++i) if (i < ne) { - const int4* xp = (const int4*) (xq + (q0 + i) * K + (size_t) kb * 32); - const int4 xa = xp[0], xb = xp[1]; - const float dx = xd[(q0 + i) * nsb + kb]; - a0[i] = fmaf(dx, sub_dot(s0, xa, xb), a0[i]); - if (GATE_UP) a1[i] = fmaf(dx, sub_dot(s1, xa, xb), a1[i]); + const float v0 = warp_sum(a0[i]); + const float v1 = GATE_UP ? warp_sum(a1[i]) : 0.0f; + if (lane == 0) { + const size_t lr = (size_t) (lo + i); + if (GATE_UP) a.h[lr * a.ldo + row] = __half_as_ushort(__float2half_rn(swiglu(v0, v1, a.limit))); + else a.y[lr * a.ldo + row] = v0; + } } } -#pragma unroll - for (int i = 0; i < NE; ++i) - if (i < ne) { - const float v0 = warp_sum(a0[i]); - const float v1 = GATE_UP ? warp_sum(a1[i]) : 0.0f; - if (lane == 0) { - const size_t lr = (size_t) (lo + i); - if (GATE_UP) a.h[lr * a.ldo + row] = __half_as_ushort(__float2half_rn(swiglu(v0, v1, a.limit))); - else a.y[lr * a.ldo + row] = v0; - } - } } bool tc_ok() { // as ds4_gguf.cu's: sm_70 and later, STRATA_DS4_NO_TC=1 keeps the F32 kernel @@ -1029,10 +1037,9 @@ bool tc_ok() { // as ds4_gguf.cu's: sm_70 and later, STRATA_DS4_NO_TC=1 keeps // CUDA: a persistent grid (the resident blocks of the device, split over the groups), each block looping over row tiles with // its codebook loaded once; HIP keeps the full grid (one tile a block) -template -int resident_ctas(K kernel) { +template +int resident_ctas() { // (a static a kernel: the occupancy differs by the codebook's shared memory) #if defined(STRATA_USE_HIP) - (void) kernel; return 1 << 30; #else static std::atomic cache[16]; @@ -1043,7 +1050,8 @@ int resident_ctas(K kernel) { if (v == 0) { int sms = 0, per = 0; cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); - cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per, kernel, kThreads, 0); + cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per, Kernel, kThreads, 0); + if (const char* e = std::getenv("DS4_IQ_MAX_SMS")) sms = std::min(sms, std::max(1, std::atoi(e))); // (benchmarking: a smaller card) if (const char* e = std::getenv("DS4_IQ_CTA_PER_SM")) per = std::min(per, std::max(1, std::atoi(e))); v = std::max(1, sms * std::max(per, 1)); cache[dev].store(v, std::memory_order_relaxed); @@ -1053,12 +1061,12 @@ int resident_ctas(K kernel) { } template void launch_gu(const Args& a, dim3 grid, cudaStream_t s) { - grid.x = (unsigned) std::max(1, std::min((int) grid.x, resident_ctas(gate_up_kernel) / (int) grid.y)); + grid.x = (unsigned) std::max(1, std::min((int) grid.x, resident_ctas>() / (int) grid.y)); gate_up_kernel<<>>(a); } template void launch_dn(const Args& a, dim3 grid, cudaStream_t s) { - grid.x = (unsigned) std::max(1, std::min((int) grid.x, resident_ctas(down_kernel) / (int) grid.y)); + grid.x = (unsigned) std::max(1, std::min((int) grid.x, resident_ctas>() / (int) grid.y)); down_kernel<<>>(a); } template @@ -1125,10 +1133,15 @@ bool light_on() { // STRATA_DS4_NO_LIGHT=1: every set through the GEMM tiles } template void launch_light(const SetArgs& a, const LightBuf& b, cudaStream_t s) { - const dim3 grid((unsigned) (((GU ? a.n_ff : a.n_embd) + kWarps - 1) / kWarps), (unsigned) a.n_exp); - if (a.max_rows <= 4) light_kernel<<>>(a, b.q, b.d); - else if (a.max_rows <= 8) light_kernel<<>>(a, b.q, b.d); - else light_kernel<<>>(a, b.q, b.d); + dim3 grid((unsigned) (((GU ? a.n_ff : a.n_embd) + kWarps - 1) / kWarps), (unsigned) a.n_exp); + if (a.max_rows <= 4) { // (persistent for a few rows: the codebook per block is then the cost; more rows are compute, the full grid balances) + grid.x = (unsigned) std::max(1, std::min((int) grid.x, resident_ctas>() / std::max(1, (int) grid.y))); + light_kernel<<>>(a, b.q, b.d); + } else if (a.max_rows <= 8) { + light_kernel<<>>(a, b.q, b.d); + } else { + light_kernel<<>>(a, b.q, b.d); + } } bool light_set(const SetArgs& a, bool gu, cudaStream_t s) { const int K = gu ? a.n_embd : a.n_ff; diff --git a/src/dsv41/ds4_main.cpp b/src/dsv41/ds4_main.cpp index dca4e18c..03e38401 100644 --- a/src/dsv41/ds4_main.cpp +++ b/src/dsv41/ds4_main.cpp @@ -22,6 +22,8 @@ #include #include #include +#include +#include #include #include #include @@ -773,6 +775,7 @@ int main(int argc, char** argv) { const std::string v = val("--dspark"); spec = v != "off"; o.dspark = v != "none"; // none: not even loaded + o.dspark_auto = v == "auto"; } else if (a == "--dspark-conf") o.dspark_conf = (float) std::atof(val("--dspark-conf").c_str()); else if (a == "--tp") o.tp = std::max(1, std::atoi(val("--tp").c_str())); else if (a == "--prefill-chunk") o.prefill_chunk = std::max(0, std::atoi(val("--prefill-chunk").c_str())); @@ -864,6 +867,12 @@ int main(int argc, char** argv) { } return 0; } + if (!ids_s.empty() && ids_s[0] == '@') { // --ids @file: the ids in a file (a command line is 32 KB on Windows) + std::ifstream idf(ids_s.substr(1)); + std::stringstream ss; + ss << idf.rdbuf(); + ids_s = ss.str(); + } const std::vector ids = parse_ids(ids_s); if (!images.empty()) { // --images: a GENI file's pictures, for the prompt's spans std::vector pics; diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 154a8af4..73a518bc 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -502,6 +502,19 @@ struct Dev { // the chunked prompt path's buffers on a device: a chunk of C tokens through a layer at once (the attention in slabs of // A queries, the indexer in slabs of AI), its GEMMs through FP16 reconstructions of the weights and cuBLAS +// DS4_PRED_DUMP: a fixed +-1 random projection of the router input (D -> 256), one block a token +__global__ void pred_proj_k(const float* x, int D, float* out) { + const int t = blockIdx.x, j = threadIdx.x; // 256 threads + const float* xr = x + (size_t) t * D; + float a = 0.0f; + for (int d = 0; d < D; ++d) { + unsigned h = (unsigned) d * 2654435761u ^ ((unsigned) j + 1u) * 40503u; + h ^= h >> 15; h *= 2246822519u; h ^= h >> 13; h *= 3266489917u; h ^= h >> 16; + a += (h & 1u) ? xr[d] : -xr[d]; + } + out[(size_t) t * 256 + j] = a * rsqrtf((float) D); +} + struct Chunk { int C = 0, A = 0, AI = 0; float *h = nullptr, *x = nullptr, *acc = nullptr, *qr = nullptr, *kvr = nullptr, *ckr = nullptr, *cgr = nullptr, @@ -1087,6 +1100,13 @@ struct Model::Impl { // attention, after the routing and the shared expert, after the experts' gate / up, after the wait for the CPU // lane, after the down pass and the post - read after the token's sync, each the time since the mark before it bool prof_on = std::getenv("DS4_PROF") != nullptr; + // DS4_PRED_DUMP=file (predictor data, the chunked prompt path): per layer and chunk u8 layer, u16 T, T x 384 fp16 router + // logits, T x 256 fp16 projection of the router input. DS4_XIN_DUMP=file (expert similarity inputs): u8 layer, u16 T, + // T x D fp32 router inputs, the first DS4_XIN_N (1024) tokens of each layer. + std::FILE* pred_f = std::getenv("DS4_PRED_DUMP") != nullptr ? std::fopen(std::getenv("DS4_PRED_DUMP"), "wb") : nullptr; + std::FILE* xin_f = std::getenv("DS4_XIN_DUMP") != nullptr ? std::fopen(std::getenv("DS4_XIN_DUMP"), "wb") : nullptr; + int xin_n = std::getenv("DS4_XIN_N") ? std::atoi(std::getenv("DS4_XIN_N")) : 1024; + std::array xin_got{}; std::FILE* trace_f = std::getenv("DS4_TRACE") != nullptr ? std::fopen(std::getenv("DS4_TRACE"), "wb") : nullptr; struct ProfMark { const Dev* d; @@ -1902,6 +1922,17 @@ struct Model::Impl { if (o.vision_only) return true; // layers: roles and the sources they read + if (o.dspark_auto && o.dspark && g.n_mtp > 0) { // (see Options::dspark_auto) + double exp_b = 0, room_b = 0; + for (const auto& kt : pk.t) + if (kt.first.rfind("layers.", 0) == 0 && kt.first.find(".ffn.experts.") != std::string::npos) exp_b += (double) kt.second.bytes; + for (const Dev& d : devs) room_b += std::max(0.0, (double) d.free0 - (double) ((size_t) o.reserve_mib << 20)); + if (exp_b > 1.5 * room_b) { + o.dspark = false; + std::fprintf(stderr, "ds4: DSpark not loaded: the routed experts (%.0f GB) are far more than the GPU holds (%.0f GB), where its verify " + "rounds read 3.3x a token's bytes and gain nothing (--dspark on loads it anyway)\n", exp_b / 1e9, room_b / 1e9); + } + } if (!o.dspark) g.n_mtp = 0; L.resize((size_t) (g.nl + g.n_mtp)); int last_src = -1; @@ -4296,6 +4327,9 @@ struct Model::Impl { return; } store = std::move(st); + // (the router lookahead's guesses are not read ahead with the store: measured 4.5 against 4.7 tok/s, 62% of the guesses are right and + // the SSD is the narrow part; DS4_AHEAD=1 turns them on) + if (std::getenv("DS4_AHEAD") == nullptr) ahead_mode = 0; for (Layer& l : L) if (l.il < g.nl && want_zc) l.zc.assign((size_t) l.n_exp, 0); std::fprintf(stderr, "ds4: RAM store: up to %zu slots of %.1f MB (%.1f GB), policy %d, %d reader threads, %s reads\n", @@ -6336,6 +6370,37 @@ struct Model::Impl { std::fwrite(gb.data(), 4, gb.size(), dump_r); std::fflush(dump_r); } + if (mi == 0 && !l.mtp && (pred_f != nullptr || xin_f != nullptr)) { + std::lock_guard lk(dump_mu); + if (pred_f != nullptr) { + float* dp = nullptr; + CK(cudaMalloc(&dp, (size_t) T * 256 * 4)); + pred_proj_k<<>>(c.x, (int) D, dp); + std::vector hp((size_t) T * 256), hl((size_t) T * l.n_exp); + CK(cudaMemcpyAsync(hp.data(), dp, hp.size() * 4, cudaMemcpyDeviceToHost, s)); + CK(cudaMemcpy2DAsync(hl.data(), (size_t) l.n_exp * 4, c.glog, 1024 * 4, (size_t) l.n_exp * 4, (size_t) T, + cudaMemcpyDeviceToHost, s)); + CK(cudaStreamSynchronize(s)); + CK(cudaFree(dp)); + std::vector o(hp.size() + hl.size()); + for (size_t i = 0; i < hl.size(); ++i) o[i] = strata::kernels::f16_from_f32(hl[i]); + for (size_t i = 0; i < hp.size(); ++i) o[hl.size() + i] = strata::kernels::f16_from_f32(hp[i]); + const uint8_t hd[3] = {(uint8_t) l.il, (uint8_t) (T & 255), (uint8_t) (T >> 8)}; + std::fwrite(hd, 1, 3, pred_f); + std::fwrite(o.data(), 2, o.size(), pred_f); + } + if (xin_f != nullptr && xin_got[(size_t) l.il] < xin_n) { // up to 32 evenly spaced tokens of the chunk + const int tk = std::min(std::min(T, 32), xin_n - xin_got[(size_t) l.il]); + const int stride = std::max(1, T / tk); + std::vector hx((size_t) T * D); + CK(cudaMemcpyAsync(hx.data(), c.x, hx.size() * 4, cudaMemcpyDeviceToHost, s)); + CK(cudaStreamSynchronize(s)); + const uint8_t hd[3] = {(uint8_t) l.il, (uint8_t) (tk & 255), (uint8_t) (tk >> 8)}; + std::fwrite(hd, 1, 3, xin_f); + for (int i = 0; i < tk; ++i) std::fwrite(hx.data() + (size_t) std::min(T - 1, i * stride) * D, 4, (size_t) D, xin_f); + xin_got[(size_t) l.il] += tk; + } + } if (mi == 0 && trace_f != nullptr && !l.mtp) { // DS4_TRACE: a chunk's picks, u8 (layer | 0x80), u16 T, T x k int16 ids std::vector ri((size_t) T * kPicks); CK(cudaMemcpy(ri.data(), c.ridx, ri.size() * 4, cudaMemcpyDeviceToHost)); diff --git a/src/dsv41/ds4_model.hpp b/src/dsv41/ds4_model.hpp index c291d13a..dc5925cf 100644 --- a/src/dsv41/ds4_model.hpp +++ b/src/dsv41/ds4_model.hpp @@ -37,6 +37,10 @@ struct Options { // most (never past the RAM the process can still get less 8 GB); 0: off, the OS page cache as before double ssd_cache_gb = -1.0; // < 0: auto (the RAM the process can get less a floor, at most 48 GB; off below 4 GB), 0: off int ssd_policy = 0; + // dspark_auto: the drafter is loaded only where the routed experts fit the GPUs (more than 1.5x what they have, the verify rounds + // read 3.3x the bytes of a token and measured no faster than plain decoding, and the drafter's 7 GB of experts take the VRAM the + // trunk's hottest would have had); --dspark on / off / none says it outright + bool dspark_auto = true; bool dspark = true; // load the DSpark drafter (the checkpoint's mtp.* blocks) for speculative decoding float dspark_conf = 0.5f; // a draft is verified while its confidence (sigmoid) is at least this // tensor parallelism: runs of tp GPUs of one kind (the same memory) take the same layers, each a share of the diff --git a/tests/dsv41/iq_expert_test.cpp b/tests/dsv41/iq_expert_test.cpp index 17faa7da..802e8abd 100644 --- a/tests/dsv41/iq_expert_test.cpp +++ b/tests/dsv41/iq_expert_test.cpp @@ -249,11 +249,72 @@ static void bench_big(int type, int mib) { for (auto p : plan) hipFree((void*) p); } +// the light sets (experts of <= 16 rows: DSpark verify windows, short prompts): n_exp experts of `rows` rows each, gate/up and down +static void bench_light(int type, int nexp, int rows) { + const int E = 5120, FF = 2304; + const size_t rb_g = iq::row_bytes(type, E), rb_d = iq::row_bytes(type, FF); + auto al = [](size_t n) { return (n + 255) / 256 * 256; }; + const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d); + std::mt19937_64 rng(7); + std::vector one(blob); + for (auto& b : one) b = (uint8_t) rng(); + uint8_t* w; CK(hipMalloc(&w, blob * nexp)); + for (int e = 0; e < nexp; ++e) CK(hipMemcpy(w + (size_t) e * blob, one.data(), blob, hipMemcpyHostToDevice)); + const int NR = nexp * rows, T = 8; + std::vector bounds(nexp + 1), idx(NR); + for (int e = 0; e <= nexp; ++e) bounds[e] = e * rows; + for (int i = 0; i < NR; ++i) idx[i] = i % T; + std::vector x((size_t) T * E); + std::normal_distribution nd(0.f, 1.f); + for (auto& v : x) v = nd(rng); + std::vector h((size_t) NR * FF, 0x3c00); + iq::SetArgs q{}; + q.wbase = w; q.stride = blob; for (int r = 0; r < 3; ++r) q.tr[r] = off[r]; + q.bounds = up(bounds); q.row0 = 0; q.max_rows = rows; q.n_exp = nexp; q.n_embd = E; q.n_ff = FF; q.limit = 7.0f; + q.tg = q.td = type; q.xf = up(x); q.idx = up(idx); q.ldx = E; + uint16_t* dh; CK(hipMalloc(&dh, (size_t) NR * FF * 2)); q.h = dh; q.ldo = FF; + q.xh = up(h); + float* dy; CK(hipMalloc(&dy, (size_t) NR * E * 4)); + hipEvent_t e0, e1; hipEventCreate(&e0); hipEventCreate(&e1); + double us[2] = {0, 0}; + for (int part = 0; part < 2; ++part) { + auto run = [&](int reps) { + hipEventRecord(e0); + for (int rep = 0; rep < reps; ++rep) { + if (part == 0) { q.h = dh; q.ldo = FF; iq::light_gate_up(q, 0); } + else { q.y = dy; q.ldo = E; q.ldx = FF; iq::light_down(q, 0); } + } + hipEventRecord(e1); hipEventSynchronize(e1); + float ms; hipEventElapsedTime(&ms, e0, e1); + return (double) ms; + }; + double ms = 0; int reps = 4; + while (ms < 200.0) { ms = run(reps); reps *= 2; } + const int n = std::max(2, (int) (reps / 2 * 40.0 / ms)); + double best = 1e30; + for (int wnd = 0; wnd < 5; ++wnd) best = std::min(best, run(n) * 1e3 / n); + us[part] = best; + } + const double bytes = (double) nexp * (off[2] + al((size_t) E * rb_d)); + std::printf("light %-7s %3d experts x %2d rows: gate/up %7.1f us down %7.1f us -> %6.0f GB/s of weights, %.2f Tw/s\n", iq::name(type), nexp, rows, + us[0], us[1], bytes / ((us[0] + us[1]) * 1e-6) / 1e9, (double) nexp * 3 * FF * E / ((us[0] + us[1]) * 1e-6) / 1e12); + hipFree(w); +} + int main(int argc, char** argv) { std::vector types = {16, 17, 22, 18, 21, 23, 29}; std::vector devs; for (int i = 1; i < argc; ++i) { - if (std::string(argv[i]) == "--bench-big") { // [types] [MiB] + if (std::string(argv[i]) == "--bench-light") { // [types] [n_exp] [rows list] + std::vector bt, rl = {1, 2, 4}; + int nexp = 24; + if (i + 1 < argc && argv[i + 1][0] != '-') { for (const char* p = argv[++i]; *p;) { bt.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } } + else bt = types; + if (i + 1 < argc && argv[i + 1][0] != '-') nexp = std::atoi(argv[++i]); + if (i + 1 < argc && argv[i + 1][0] != '-') { rl.clear(); for (const char* p = argv[++i]; *p;) { rl.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } } + for (int t : bt) for (int r : rl) bench_light(t, nexp, r); + return 0; + } else if (std::string(argv[i]) == "--bench-big") { // [types] [MiB] std::vector bt; int mib = 640; if (i + 1 < argc && argv[i + 1][0] != '-') { for (const char* p = argv[++i]; *p;) { bt.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } } else bt = types; diff --git a/tools/dsv41/win/h100sim.py b/tools/dsv41/win/h100sim.py new file mode 100644 index 00000000..e362375d --- /dev/null +++ b/tools/dsv41/win/h100sim.py @@ -0,0 +1,132 @@ +"""h100sim.py - replay the H100 routing corpus (1.78M tokens, code/agent/chat/multi/math/long, DS4_TRACE format, see +phaseA-tests/h100/trace_tools.py) through an LRU expert cache at this PC's sizes, with and without a profile warm start. + + h100sim.py [--tokens N] [--skip S] [--caps 30,40,44] [--sizes sizes.json] + +Prints the demand hit rate by bytes after a warm-up of `--warm` tokens, for: empty start LRU; LRU started with the profile's +hottest experts in (the engine's preload) and the same cold-start window's hit rate (first 2000 tokens), and a static top-N +(profile only, no adaptation).""" +import argparse +import collections +import io +import json +import struct +import sys + +import numpy as np + + +def decode(path, max_tokens, skip): + if path.endswith('.zst'): + import zstandard + raw = zstandard.ZstdDecompressor().stream_reader(open(path, 'rb')).read() + else: + raw = open(path, 'rb').read() + buf = np.frombuffer(raw, dtype=np.uint8) + pos, n = 0, len(buf) + per = {l: [] for l in range(40)} + got = [0] * 40 + while pos < n: + b0 = int(buf[pos]) + if b0 & 0x80: + l = b0 & 0x7F + T = int(buf[pos + 1]) | (int(buf[pos + 2]) << 8) + pos += 3 + else: + l = b0 + T = int(buf[pos + 1]) & 0x7F + pos += 2 + sz = T * 12 + if pos + sz > n: + break + per[l].append(buf[pos:pos + sz].view(np.int16).reshape(T, 6)) + pos += sz + if min(got) >= skip + max_tokens: + break + got[l] += T + arr = [] + for l in range(40): + a = np.concatenate(per[l])[skip:skip + max_tokens] + arr.append(a) + m = min(len(a) for a in arr) + return np.stack([a[:m] for a in arr], axis=1) # [tokens][layer][6] + + +def lru(acc_iter, size, cap, init=None, warm=0): + od = collections.OrderedDict() + used = 0 + if init: + for k in init: + od[k] = size[k[0]] + used += size[k[0]] + hb = tb = 0.0 + first_hb = first_tb = 0.0 + for i, (t, k) in enumerate(acc_iter): + sz = size[k[0]] + cnt = t >= warm + early = t < 2000 + if k in od: + od.move_to_end(k) + if cnt: + hb += sz + if early: + first_hb += sz + else: + od[k] = sz + used += sz + while used > cap: + _, s0 = od.popitem(last=False) + used -= s0 + if cnt: + tb += sz + if early: + first_tb += sz + return 100 * hb / max(tb, 1), 100 * first_hb / max(first_tb, 1) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('trace') + ap.add_argument('profile') + ap.add_argument('--tokens', type=int, default=40000) + ap.add_argument('--skip', type=int, default=0) + ap.add_argument('--warm', type=int, default=4000) + ap.add_argument('--caps', default='30,40') + ap.add_argument('--sizes', default=r'C:\ds-ista-work\sizes.json') + a = ap.parse_args() + d = json.load(open(a.sizes)) + size = {int(k): float(v) for k, v in d['exp_layer'].items()} + tr = decode(a.trace, a.tokens, a.skip) + prof = np.fromfile(a.profile, dtype=np.uint32).reshape(-1, 384)[:40] + print('trace', tr.shape, 'tokens', len(tr)) + + def acc(): + for t in range(len(tr)): + for l in range(40): + for e in tr[t, l]: + yield t, (l, int(e)) + dens = sorted(((prof[l, e] / size[l], l, e) for l in range(40) for e in range(384)), reverse=True) + for cg in [float(x) for x in a.caps.split(',')]: + cap = cg * 1e9 + r0, f0 = lru(acc(), size, cap, None, a.warm) + order, used = [], 0.0 + for _, l, e in dens: + if used + size[l] > cap: + break + order.append((l, e)) + used += size[l] + r1, f1 = lru(acc(), size, cap, list(reversed(order)), a.warm) # hottest last = most recent + # static: top-N of the profile, no adaptation + sel = set(order) + hb = tb = 0.0 + for t, k in acc(): + if t >= a.warm: + tb += size[k[0]] + if k in sel: + hb += size[k[0]] + print('cap %.0f GB: LRU from empty: steady hit %.1f%% (first 2000 tokens %.1f%%); LRU from the profile\'s hottest: steady %.1f%% (first 2000 tokens %.1f%%); static top-N alone %.1f%%' % ( + cg, r0, f0, r1, f1, 100 * hb / tb)) + + +if __name__ == '__main__': + main()