Files
Strata/engine/tests/ling32/ling32_moe_sy_test.cpp

890 lines
51 KiB
C++

// tests/ling32/ling32_moe_sy_test.cpp - the SYCL routed-expert / router / SwiGLU / combine kernels (src/ling32/sycl/ling32_sy_k_moe.cpp, ling32_sy_k_router.cpp) against their CPU definitions.
// Usage: ling32_moe_sy_test DATA_DIR (DATA_DIR = engine/tests/ling32/data: pack_s{4,5,6,8}.bin, real S_K superblocks; S2_K / S3_K slabs are random superblocks)
// What is compared, and how:
// * float activations: the CPU model below does the arithmetic of the kernel (lane l of a warp owns 8 weights of each superblock, fmaf chain, xor butterfly) = ling32_cpu_expert.cpp; bit for bit, and
// (sanity) the relative error against a double reference stays below 2e-5.
// * Q8 activations: the integer dot products are exact; the CPU model repeats the float arithmetic of the kernel (lane order, fma contraction) bit for bit; and the error against
// dot_sk_q8_1_row (sequential group order) stays below 2e-5 of sum|w x|, like ling32_kernel_test.
// * moe_act: float output against the CPU swiglu / S_xd / FWHT-128 (exp is the device's: a relative tolerance), the Q8 output = CPU quantiser of the kernel's own float output, bit for bit.
// * null slab entries write nothing; moe_tc_* (grouped by expert) equal moe_gu / moe_dn with float activations bit for bit; ALF-LB routing, swiglu, gemv2_swiglu_s8, moe_combine(_norm).
#if defined(_WIN32)
#include <stdlib.h>
#define setenv(k, v, o) _putenv_s((k), (v)) // MSVC runtime: no setenv
#endif
#include "ling32_kernels.hpp"
#include "strata/ling32/ling32_sk.hpp"
#include "strata/quant/sk_codecs.hpp"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <random>
#include <string>
#include <vector>
using namespace strata::ling32;
using namespace strata::ling32::gpu;
using strata::quant::sk::BlockQ8_1_G64;
using strata::quant::sk::SkCode;
namespace {
int g_fail = 0;
void check(bool ok, const std::string& what) {
std::printf(" %-130s %s\n", what.c_str(), ok ? "ok" : "FAIL");
if (!ok) ++g_fail;
}
template <class T> T* dev(const std::vector<T>& h) {
T* d = nullptr;
cudaMalloc(reinterpret_cast<void**>(&d), std::max<size_t>(h.size() * sizeof(T), 4));
cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice);
return d;
}
template <class T> T* dev_alloc(size_t n) {
T* d = nullptr;
cudaMalloc(reinterpret_cast<void**>(&d), std::max<size_t>(n * sizeof(T), 4));
return d;
}
template <class T> std::vector<T> host(const T* d, size_t n) {
std::vector<T> h(n);
cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost);
return h;
}
bool slurp(const std::string& p, std::vector<uint8_t>& out) {
std::ifstream f(p, std::ios::binary);
if (!f) return false;
out.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
return true;
}
std::mt19937 g_rng(20260);
float nrm() { static std::normal_distribution<float> nd(0.0f, 1.0f); return nd(g_rng); }
int rint_(int n) { return static_cast<int>(g_rng() % static_cast<unsigned>(n)); }
constexpr int sbb(int code) { return code == 2 ? 70 : code == 3 ? 102 : code == 4 ? 134 : code == 5 ? 166 : code == 6 ? 198 : 262; }
constexpr float khalf(int code) { return code == 2 ? 1.5f : code == 3 ? 3.5f : code == 4 ? 7.5f : code == 5 ? 15.5f : code == 6 ? 31.5f : 0.0f; }
// the q value of weight idx (0..255) of a superblock payload: unsigned (q - kHalf is the weight) for S2..S6, int8 for S8
int qraw(int code, const uint8_t* pl, int idx) {
if (code == 8) return static_cast<int8_t>(pl[idx]);
if (code == 2 || code == 3) {
int v = (pl[idx >> 2] >> (2 * (idx & 3))) & 3;
if (code == 3) v |= ((pl[64 + (idx >> 3)] >> (idx & 7)) & 1) << 2;
return v;
}
const int byte = pl[idx >> 1];
int v = (idx & 1) ? (byte >> 4) : (byte & 15);
if (code == 5) v |= ((pl[128 + (idx >> 3)] >> (idx & 7)) & 1) << 4;
else if (code == 6) v |= ((pl[128 + (idx >> 2)] >> (2 * (idx & 3))) & 3) << 4;
return v;
}
float qval(int code, const uint8_t* pl, int idx) { return code == 8 ? static_cast<float>(qraw(code, pl, idx)) : static_cast<float>(qraw(code, pl, idx)) - khalf(code); }
// a * b + c as one fused multiply-add (bit of g_fmask set) or as a rounded product and a sum: which one the SYCL compiler emits is a property of its contraction setting
int g_fmask = 3, g_dbg = 0;
inline float mad(float a, float b, float c, int bit) {
if (g_fmask & bit) return std::fmaf(a, b, c);
volatile float p = a * b;
return p + c;
}
// CPU model of one output row, float activations (ling32_cpu_expert.cpp): fma chains per lane, then the butterfly
float cpu_row_f(int code, const uint8_t* rowp, int K, const float* x) {
float lane[32] = {};
const int nsb = K / 256;
for (int sb = 0; sb < nsb; ++sb) {
const uint8_t* blk = rowp + static_cast<size_t>(sb) * sbb(code);
const float D = f16_bits_to_f32(static_cast<uint16_t>(blk[0] | (blk[1] << 8)));
for (int l = 0; l < 32; ++l) {
const int g = l >> 3, idx0 = g * 64 + (l & 7) * 8;
float s = 0.0f;
for (int j = 0; j < 8; ++j) s = mad(qval(code, blk + 6, idx0 + j), x[sb * 256 + idx0 + j], s, 1);
const float eff = D * (static_cast<float>(blk[2 + g]) / 255.0f);
lane[l] = mad(eff, s, lane[l], 2);
}
}
for (int o = 16; o >= 1; o >>= 1)
for (int l = 0; l < o; ++l) lane[l] = lane[l] + lane[l + o];
return lane[0];
}
// same, Q8 activations (xq: K/64 blocks): the kernel's float expression with the contraction clang makes of it
float cpu_row_q(int code, const uint8_t* rowp, int K, const Q8Blk* xq) {
float lane[32] = {};
const int nsb = K / 256;
for (int sb = 0; sb < nsb; ++sb) {
const uint8_t* blk = rowp + static_cast<size_t>(sb) * sbb(code);
const float D = f16_bits_to_f32(static_cast<uint16_t>(blk[0] | (blk[1] << 8)));
for (int l = 0; l < 32; ++l) {
const int g = l >> 3, idx0 = g * 64 + (l & 7) * 8;
const Q8Blk& xb = xq[sb * 4 + g];
int isum = 0;
for (int j = 0; j < 8; ++j) isum += qraw(code, blk + 6, idx0 + j) * xb.qs[(l & 7) * 8 + j];
const float eff = D * (static_cast<float>(blk[2 + g]) / 255.0f);
if (code == 8) lane[l] = mad(eff * xb.d, static_cast<float>(isum), lane[l], 2);
else lane[l] = mad(eff, mad(xb.d, static_cast<float>(isum), -((khalf(code) * xb.s) * 0.125f), 1), lane[l], 2);
}
}
for (int o = 16; o >= 1; o >>= 1)
for (int l = 0; l < o; ++l) lane[l] = lane[l] + lane[l + o];
return lane[0];
}
double row_ref_d(int code, const uint8_t* rowp, int K, const float* x, double* mag) {
double r = 0, m = 0;
for (int i = 0; i < K; ++i) {
const uint8_t* blk = rowp + static_cast<size_t>(i / 256) * sbb(code);
const double D = f16_bits_to_f32(static_cast<uint16_t>(blk[0] | (blk[1] << 8)));
const double eff = static_cast<float>(D) * (static_cast<float>(blk[2 + ((i & 255) >> 6)]) / 255.0f);
const double p = eff * qval(code, blk + 6, i & 255) * x[i];
r += p;
m += std::fabs(p);
}
*mag = m;
return r;
}
BlockQ8_1_G64 to_g64(const Q8Blk& q) { BlockQ8_1_G64 b; std::memcpy(b.qs, q.qs, 64); b.d = q.d; b.s = q.s; return b; }
Q8Blk from_g64(const BlockQ8_1_G64& b) { Q8Blk q; std::memcpy(q.qs, b.qs, 64); q.d = b.d; q.s = b.s; return q; }
std::vector<Q8Blk> quant_cpu(const float* x, int n) { // n % 64 == 0
std::vector<BlockQ8_1_G64> t(n / 64);
strata::quant::sk::quantize_q8_1_g64(x, t.data(), n);
std::vector<Q8Blk> r(t.size());
for (size_t i = 0; i < t.size(); ++i) r[i] = from_g64(t[i]);
return r;
}
// ---------------------------------------------------------------------------------------------- slabs
struct Slabs {
std::vector<uint8_t> buf;
std::vector<ExpertDesc> desc; // [layer_base + e]
int layer_base = 0, E = 0, D = 0, I = 0;
size_t stride = 0;
};
std::vector<uint8_t> g_pack[9]; // real superblocks of the codec vectors (codes 4, 5, 6, 8)
void fill_sb(int code, uint8_t* dst) {
if (!g_pack[code].empty() && !std::getenv("L32MOE_RANDSB")) {
const size_t n = g_pack[code].size() / sbb(code);
std::memcpy(dst, g_pack[code].data() + (g_rng() % n) * sbb(code), sbb(code));
return;
}
for (int i = 0; i < sbb(code); ++i) dst[i] = static_cast<uint8_t>(g_rng() & 0xFF); // S2_K / S3_K: random payload, a sane scale
const uint16_t h = static_cast<uint16_t>(0x2800 + g_rng() % 0x0C00);
dst[0] = h & 0xFF; dst[1] = h >> 8;
for (int g = 0; g < 4; ++g) dst[2 + g] = static_cast<uint8_t>(1 + g_rng() % 255);
}
Slabs make_slabs(int E, int D, int I, int layer_base, const std::vector<int>& codes) {
Slabs s;
s.E = E; s.D = D; s.I = I; s.layer_base = layer_base;
const size_t max_body = size_t(2) * I + size_t(2) * I * (D / 256) * 262 + size_t(D) * (I / 256) * 262;
s.stride = (max_body + 16383) / 16384 * 16384;
s.buf.assign(s.stride * E, 0);
s.desc.assign(size_t(layer_base) + E, ExpertDesc{});
for (int e = 0; e < E; ++e) {
const int gc = codes[rint_(int(codes.size()))], dc = codes[rint_(int(codes.size()))];
uint8_t* b = s.buf.data() + s.stride * e;
for (int i = 0; i < I; ++i) { // S_xd: fp16, 0.5 .. 2
const uint16_t h = f32_to_f16_bits(0.5f + 1.5f * (g_rng() % 1000) / 1000.0f);
b[2 * i] = h & 0xFF; b[2 * i + 1] = h >> 8;
}
const size_t gu_sb = size_t(2) * I * (D / 256), dn_sb = size_t(D) * (I / 256);
const size_t dn_off = size_t(2) * I + gu_sb * sbb(gc);
for (size_t i = 0; i < gu_sb; ++i) fill_sb(gc, b + size_t(2) * I + i * sbb(gc));
for (size_t i = 0; i < dn_sb; ++i) fill_sb(dc, b + dn_off + i * sbb(dc));
s.desc[size_t(layer_base) + e] = ExpertDesc{s.stride * e, gc, dc, int(dn_off), int(dn_off + dn_sb * sbb(dc))};
}
return s;
}
const uint8_t* slab_of(const Slabs& s, int e) { return s.buf.data() + s.stride * e; }
std::vector<float> make_act(size_t n) { // each 64-group scaled by 10^-U(0, 3): activations span decades
std::vector<float> x(n);
float grp = 1.0f;
for (size_t i = 0; i < n; ++i) {
if (i % 64 == 0) grp = std::pow(10.0f, -3.0f * std::uniform_real_distribution<float>(0.f, 1.f)(g_rng));
x[i] = std::getenv("L32MOE_XNORM") ? nrm() : nrm() * grp;
}
return x;
}
// ---------------------------------------------------------------------------------------------- the routed experts
void run_experts(const Slabs& S, int N, int top_k, bool null_some, bool use_table, const char* tag) {
const int D = S.D, I = S.I, P = N * top_k, E = S.E;
if (!use_table && null_some) return; // a null entry needs the table
std::vector<int> idx(P);
for (int p = 0; p < P; ++p) idx[p] = rint_(E);
std::vector<const uint8_t*> table(size_t(S.layer_base) + E, nullptr);
uint8_t* dsec = dev(S.buf);
ExpertDesc* ddesc = dev(S.desc);
std::vector<char> is_null(E, 0);
for (int e = 0; e < E; ++e) {
is_null[e] = (null_some && (e % 3 == 1)) ? 1 : 0;
table[size_t(S.layer_base) + e] = is_null[e] ? nullptr : dsec + S.stride * e;
}
const uint8_t* const* dtable = use_table ? reinterpret_cast<const uint8_t* const*>(dev(table)) : nullptr;
int* didx = dev(idx);
const std::vector<float> x = make_act(size_t(N) * D);
float* dx = dev(x);
const std::vector<Q8Blk> xq = quant_cpu(x.data(), N * D);
Q8Blk* dxq = dev(xq);
const float sentinel = 12345.0f;
std::vector<float> fill(size_t(P) * 2 * I, sentinel);
float* gu_f = dev(fill);
float* gu_q = dev(fill);
moe_gu(dsec, ddesc, S.layer_base, didx, N, top_k, E, D, I, dx, false, gu_f, 0, dtable);
moe_gu(dsec, ddesc, S.layer_base, didx, N, top_k, E, D, I, dxq, true, gu_q, 0, dtable);
cudaDeviceSynchronize();
const auto hf = host(gu_f, fill.size()), hq = host(gu_q, fill.size());
if (std::getenv("L32MOE_DBG") && !null_some) { // the trunk GEMV on the same rows of pair 0, for comparison with moe_gu and the CPU model
const ExpertDesc& d0 = S.desc[size_t(S.layer_base) + idx[0]];
float* tg = dev_alloc<float>(2 * I);
gemv_sk(dsec + S.stride * idx[0] + 2 * I, d0.gu_code, 2 * I, D, dx, false, 1, tg, 2 * I, false, 0);
cudaDeviceSynchronize();
const auto tgh = host(tg, 2 * I);
int dt = 0, dm = 0;
for (int r = 0; r < 2 * I; ++r) {
const float cf = cpu_row_f(d0.gu_code, slab_of(S, idx[0]) + 2 * I + size_t(r) * (D / 256) * sbb(d0.gu_code), D, x.data());
dt += std::memcmp(&cf, &tgh[r], 4) != 0;
dm += std::memcmp(&tgh[r], &hf[r], 4) != 0;
}
std::printf(" dbg pair 0 (code %d): trunk gemv_sk differs from the CPU model in %d of %d rows, from moe_gu in %d\n", d0.gu_code, dt, 2 * I, dm);
cudaFree(tg);
}
size_t bad_f = 0, bad_q = 0, written = 0, wrong_null = 0;
double e_f = 0, e_lib = 0;
for (int p = 0; p < P; ++p) {
const int e = idx[p];
const ExpertDesc& d = S.desc[size_t(S.layer_base) + e];
const uint8_t* slab = slab_of(S, e);
for (int r = 0; r < 2 * I; ++r) {
const size_t at = size_t(p) * 2 * I + r;
if (is_null[e]) { wrong_null += (hf[at] != sentinel) + (hq[at] != sentinel); continue; }
const uint8_t* rowp = slab + 2 * I + size_t(r) * (D / 256) * sbb(d.gu_code);
const float cf = cpu_row_f(d.gu_code, rowp, D, x.data() + size_t(p / top_k) * D);
const float cq = cpu_row_q(d.gu_code, rowp, D, xq.data() + size_t(p / top_k) * (D / 64));
bad_f += std::memcmp(&cf, &hf[at], 4) != 0;
bad_q += std::memcmp(&cq, &hq[at], 4) != 0;
if (std::getenv("L32MOE_DBG") && g_dbg < 12 && std::memcmp(&cf, &hf[at], 4) != 0) {
double mag;
const double ref = row_ref_d(d.gu_code, rowp, D, x.data() + size_t(p / top_k) * D, &mag);
std::printf(" dbg gu code %d row %d: gpu %.9g cpu %.9g double %.9g\n", d.gu_code, r, hf[at], cf, ref);
++g_dbg;
}
++written;
if (r % 17 == 0) {
double mag;
const double ref = row_ref_d(d.gu_code, rowp, D, x.data() + size_t(p / top_k) * D, &mag);
e_f = std::fmax(e_f, std::fabs(hf[at] - ref) / (mag + 1e-30));
std::vector<BlockQ8_1_G64> g(D / 64);
for (int i = 0; i < D / 64; ++i) g[i] = to_g64(xq[size_t(p / top_k) * (D / 64) + i]);
if (d.gu_code >= 4) e_lib = std::fmax(e_lib, std::fabs(hq[at] - strata::quant::sk::dot_sk_q8_1_row(rowp, static_cast<SkCode>(d.gu_code), g.data(), D)) / (mag + 1e-30));
}
}
}
const std::string t = std::string(tag) + " N=" + std::to_string(N) + " top_k=" + std::to_string(top_k) + " D=" + std::to_string(D) + " I=" + std::to_string(I) + (null_some ? " (null entries)" : "") + (use_table ? " [table]" : " [sec4+off]");
check(bad_f == 0 && wrong_null == 0, "moe_gu float acts: " + t + ": " + std::to_string(written) + " rows, " + std::to_string(bad_f) + " differ from the CPU model, " + std::to_string(wrong_null) + " null-entry writes; vs double " + std::to_string(e_f));
check(bad_q == 0 && e_lib < 2e-5, "moe_gu Q8 acts: " + t + ": " + std::to_string(bad_q) + " differ from the CPU model; vs dot_sk_q8_1_row " + std::to_string(e_lib));
// ---- moe_act on those gu rows (float and Q8 output) and moe_dn on its output
const float lim = (N % 2) ? 7.0f : 0.0f;
const bool post = (N % 3) != 0;
std::vector<float> gu_in(size_t(P) * 2 * I);
for (auto& v : gu_in) v = nrm() * 2.5f;
float* dgu = dev(gu_in);
std::vector<float> actfill(size_t(P) * I, sentinel);
float* act_f = dev(actfill);
std::vector<Q8Blk> qfill(size_t(P) * (I / 64));
for (auto& b : qfill) { std::memset(b.qs, 0x55, 64); b.d = sentinel; b.s = sentinel; }
Q8Blk* act_q = dev(qfill);
moe_act(dsec, ddesc, S.layer_base, didx, dgu, N, top_k, I, lim, post, act_f, false, 0, dtable);
moe_act(dsec, ddesc, S.layer_base, didx, dgu, N, top_k, I, lim, post, act_q, true, 0, dtable);
cudaDeviceSynchronize();
const auto af = host(act_f, actfill.size());
const auto aq = host(act_q, qfill.size());
double e_act = 0;
size_t qbad = 0, nwrong = 0;
for (int p = 0; p < P; ++p) {
const int e = idx[p];
const uint8_t* slab = slab_of(S, e);
if (is_null[e]) {
for (int i = 0; i < I; ++i) nwrong += af[size_t(p) * I + i] != sentinel;
for (int bq = 0; bq < I / 64; ++bq) nwrong += aq[size_t(p) * (I / 64) + bq].d != sentinel;
continue;
}
std::vector<float> v(I);
for (int i = 0; i < I; ++i) {
const float g = gu_in[size_t(p) * 2 * I + i], u = gu_in[size_t(p) * 2 * I + I + i];
auto silu = [](float a) { return a / (1.0f + std::exp(-a)); };
float r;
if (lim > 0.0f) {
const float gg = post ? std::fmin(silu(g), lim) : silu(std::fmin(g, lim));
r = gg * std::fmax(-lim, std::fmin(u, lim));
} else r = silu(g) * u;
const uint16_t h = static_cast<uint16_t>(slab[2 * i] | (slab[2 * i + 1] << 8));
v[i] = r / f16_bits_to_f32(h);
}
fwht128_f32(v.data(), v.data(), I);
double rms = 0;
for (float a : v) rms += double(a) * a;
rms = std::sqrt(rms / I) + 1e-30;
for (int i = 0; i < I; ++i) e_act = std::fmax(e_act, std::fabs(af[size_t(p) * I + i] - v[i]) / rms);
// the Q8 output = the CPU quantiser applied to the kernel's own float output
const std::vector<Q8Blk> ref = quant_cpu(af.data() + size_t(p) * I, I);
for (int bq = 0; bq < I / 64; ++bq) {
const Q8Blk& g = aq[size_t(p) * (I / 64) + bq];
qbad += std::memcmp(g.qs, ref[bq].qs, 64) != 0 || g.d != ref[bq].d || std::fabs(g.s - ref[bq].s) > 1e-6f * (1 + std::fabs(ref[bq].s));
}
}
check(e_act < 2e-5 && nwrong == 0 && qbad == 0, "moe_act float vs CPU (rel to rms) " + std::to_string(e_act) + ", Q8 blocks differing from the CPU quantiser of the float output: " + std::to_string(qbad) + ", null-entry writes " + std::to_string(nwrong) + " [lim " + std::to_string(lim) + (post ? " post_silu" : " pre") + "]");
// ---- moe_dn: float and Q8 activations, one activation row per pair (I wide)
const std::vector<float> a2 = make_act(size_t(P) * I);
const std::vector<Q8Blk> a2q = quant_cpu(a2.data(), P * I);
float* da2 = dev(a2);
Q8Blk* da2q = dev(a2q);
std::vector<float> yfill(size_t(P) * D, sentinel);
float* ye_f = dev(yfill);
float* ye_q = dev(yfill);
moe_dn(dsec, ddesc, S.layer_base, didx, N, top_k, E, D, I, da2, false, ye_f, 0, dtable);
moe_dn(dsec, ddesc, S.layer_base, didx, N, top_k, E, D, I, da2q, true, ye_q, 0, dtable);
cudaDeviceSynchronize();
const auto yf = host(ye_f, yfill.size()), yq = host(ye_q, yfill.size());
size_t dbad_f = 0, dbad_q = 0, dwrong = 0, drows = 0;
double d_lib = 0, d_dbl = 0;
for (int p = 0; p < P; ++p) {
const int e = idx[p];
const ExpertDesc& d = S.desc[size_t(S.layer_base) + e];
const uint8_t* slab = slab_of(S, e);
for (int r = 0; r < D; ++r) {
const size_t at = size_t(p) * D + r;
if (is_null[e]) { dwrong += (yf[at] != sentinel) + (yq[at] != sentinel); continue; }
const uint8_t* rowp = slab + d.dn_off + size_t(r) * (I / 256) * sbb(d.dn_code);
const float cf = cpu_row_f(d.dn_code, rowp, I, a2.data() + size_t(p) * I);
const float cq = cpu_row_q(d.dn_code, rowp, I, a2q.data() + size_t(p) * (I / 64));
dbad_f += std::memcmp(&cf, &yf[at], 4) != 0;
dbad_q += std::memcmp(&cq, &yq[at], 4) != 0;
++drows;
if (r % 29 == 0) {
double mag;
const double ref = row_ref_d(d.dn_code, rowp, I, a2.data() + size_t(p) * I, &mag);
d_dbl = std::fmax(d_dbl, std::fabs(yf[at] - ref) / (mag + 1e-30));
std::vector<BlockQ8_1_G64> g(I / 64);
for (int i = 0; i < I / 64; ++i) g[i] = to_g64(a2q[size_t(p) * (I / 64) + i]);
if (d.dn_code >= 4) d_lib = std::fmax(d_lib, std::fabs(yq[at] - strata::quant::sk::dot_sk_q8_1_row(rowp, static_cast<SkCode>(d.dn_code), g.data(), I)) / (mag + 1e-30));
}
}
}
check(dbad_f == 0 && dwrong == 0 && d_dbl < 2e-5, "moe_dn float acts: " + t + ": " + std::to_string(drows) + " rows, " + std::to_string(dbad_f) + " differ from the CPU model, null-entry writes " + std::to_string(dwrong) + "; vs double " + std::to_string(d_dbl));
check(dbad_q == 0 && d_lib < 2e-5, "moe_dn Q8 acts: " + t + ": " + std::to_string(dbad_q) + " differ from the CPU model; vs dot_sk_q8_1_row " + std::to_string(d_lib));
// ---- grouped by expert (float activations only): equal to moe_gu / moe_dn bit for bit
if (use_table || !null_some) {
MoeTcWork w;
const bool ok = moe_tc_alloc(w, P, E);
std::vector<float> g_fill(size_t(P) * 2 * I, sentinel);
float* tgu = dev(g_fill);
float* tye = dev(yfill);
float* gu_ref = dev(g_fill);
float* ye_ref = dev(yfill);
moe_tc_route(w, didx, P, 0);
moe_tc_gu(w, dsec, ddesc, S.layer_base, dtable, P, top_k, D, I, dx, tgu, 0);
moe_tc_dn(w, dsec, ddesc, S.layer_base, dtable, P, top_k, D, I, da2, tye, 0);
moe_gu(dsec, ddesc, S.layer_base, didx, N, top_k, E, D, I, dx, false, gu_ref, 0, dtable);
moe_dn(dsec, ddesc, S.layer_base, didx, N, top_k, E, D, I, da2, false, ye_ref, 0, dtable);
cudaDeviceSynchronize();
const auto a = host(tgu, g_fill.size()), b = host(gu_ref, g_fill.size()), c = host(tye, yfill.size()), d = host(ye_ref, yfill.size());
const bool same = std::memcmp(a.data(), b.data(), a.size() * 4) == 0 && std::memcmp(c.data(), d.data(), c.size() * 4) == 0;
auto rel_err = [&](const std::vector<float>& u, const std::vector<float>& v) { // max |u - v| of the written entries, relative to their rms
double e = 0, r = 0;
size_t n = 0;
for (size_t i = 0; i < u.size(); ++i) {
if (v[i] == sentinel && u[i] == sentinel) continue;
e = std::fmax(e, std::fabs(double(u[i]) - v[i]));
r += double(v[i]) * v[i];
++n;
}
return e / std::sqrt(r / std::max<size_t>(n, 1) + 1e-30);
};
const double e_tg = rel_err(a, b), e_td = rel_err(c, d);
check(ok && (same || (e_tg < 2e-5 && e_td < 2e-5)), std::string("moe_tc_route/gu/dn (grouped by expert) vs moe_gu / moe_dn: ") + (same ? "bit for bit" : "max error " + std::to_string(e_tg) + " / " + std::to_string(e_td) + " of the rms (XMX tiles)") + ": " + t);
moe_tc_free(w);
cudaFree(tgu); cudaFree(tye); cudaFree(gu_ref); cudaFree(ye_ref);
}
for (void* p : std::initializer_list<void*>{dsec, ddesc, didx, dx, dxq, gu_f, gu_q, dgu, act_f, act_q, da2, da2q, ye_f, ye_q}) cudaFree(p);
if (dtable) cudaFree(const_cast<uint8_t**>(reinterpret_cast<const uint8_t* const*>(dtable)));
}
// ---------------------------------------------------------------------------------------------- ALF-LB router
struct RouteRef {
std::vector<int> idx;
std::vector<float> w;
};
RouteRef route_cpu(const float* logits, const float* add_bias, const float* sel_bias, int E, int n_group, int topk_group, int top_n, float scale, int N) {
RouteRef r;
r.idx.resize(size_t(N) * top_n);
r.w.assign(size_t(N) * top_n, 0.0f);
const int per = E / n_group;
for (int t = 0; t < N; ++t) {
std::vector<float> sig(E), sc(E);
for (int e = 0; e < E; ++e) {
const float z = logits[size_t(t) * E + e] + (add_bias ? add_bias[e] : 0.0f);
sig[e] = 1.0f / (1.0f + std::exp(-z));
sc[e] = sig[e] + sel_bias[e];
}
std::vector<float> gs(n_group);
for (int g = 0; g < n_group; ++g) {
float m1 = -3.4e38f, m2 = -3.4e38f;
for (int i = 0; i < per; ++i) {
const float v = sc[g * per + i];
if (v > m1) { m2 = m1; m1 = v; } else if (v > m2) m2 = v;
}
gs[g] = m1 + m2;
}
std::vector<int> keep(n_group, 0);
for (int k = 0; k < topk_group; ++k) {
int best = -1;
for (int g = 0; g < n_group; ++g)
if (!keep[g] && (best < 0 || gs[g] > gs[best])) best = g;
keep[best] = 1;
}
std::vector<int> cand;
for (int e = 0; e < E; ++e)
if (keep[e / per]) cand.push_back(e);
std::sort(cand.begin(), cand.end(), [&](int a, int b) { return sc[a] > sc[b] || (sc[a] == sc[b] && a < b); });
float tot = 0.0f;
for (int i = 0; i < top_n; ++i) { r.idx[size_t(t) * top_n + i] = cand[i]; tot += sig[cand[i]]; }
for (int i = 0; i < top_n; ++i) r.w[size_t(t) * top_n + i] = sig[cand[i]] * (scale / (tot + 1e-20f));
}
return r;
}
void run_router(int E, int n_group, int topk_group, int top_n, int N, bool weights, bool add_b, bool ties) {
std::vector<float> lg(size_t(N) * E), ab(E), sb(E);
for (auto& v : lg) v = ties ? float(rint_(33) - 16) * 0.25f : nrm() * 2.0f; // ties: logits on a 0.25 grid, many equal scores
for (auto& v : ab) v = nrm() * 0.3f;
for (auto& v : sb) v = ties ? 0.0f : nrm() * 0.05f;
if (ties)
for (int e = 0; e < E; e += 5) sb[e] = 0.015625f * float(rint_(5));
float *dl = dev(lg), *dab = dev(ab), *dsb = dev(sb);
const float scale = 2.5f;
int* oi = dev_alloc<int>(size_t(N) * top_n);
float* ow = dev_alloc<float>(size_t(N) * top_n);
cudaMemset(ow, 0, size_t(N) * top_n * 4);
alflb_route(dl, add_b ? dab : nullptr, dsb, E, n_group, topk_group, top_n, scale, weights, oi, ow, N, 0);
cudaDeviceSynchronize();
const auto gi = host(oi, size_t(N) * top_n);
const auto gw = host(ow, size_t(N) * top_n);
const RouteRef ref = route_cpu(lg.data(), add_b ? ab.data() : nullptr, sb.data(), E, n_group, topk_group, top_n, scale, N);
size_t bad_i = 0;
double e_w = 0;
for (size_t i = 0; i < gi.size(); ++i) {
bad_i += gi[i] != ref.idx[i];
if (weights) e_w = std::fmax(e_w, std::fabs(gw[i] - ref.w[i]) / (std::fabs(ref.w[i]) + 1e-30));
}
// the reference kernel (one warp per token) and the parallel one agree
g_alflb_ref = 1;
int* oi2 = dev_alloc<int>(size_t(N) * top_n);
alflb_route(dl, add_b ? dab : nullptr, dsb, E, n_group, topk_group, top_n, scale, weights, oi2, ow, N, 0);
g_alflb_ref = 0;
cudaDeviceSynchronize();
const auto gi2 = host(oi2, size_t(N) * top_n);
const bool same = gi2 == gi;
check(bad_i == 0 && e_w < 1e-5 && same, "alflb_route E=" + std::to_string(E) + " groups " + std::to_string(n_group) + "/" + std::to_string(topk_group) + " top_n=" + std::to_string(top_n) + " N=" + std::to_string(N) +
(weights ? " weights" : " no weights") + (add_b ? " +add_bias" : "") + (ties ? " ties" : "") + ": " + std::to_string(bad_i) + " ids differ from the CPU, weights rel " + std::to_string(e_w) +
", ref kernel == par kernel: " + (same ? "yes" : "NO"));
cudaFree(dl); cudaFree(dab); cudaFree(dsb); cudaFree(oi); cudaFree(ow); cudaFree(oi2);
}
// ---------------------------------------------------------------------------------------------- swiglu / shared expert / combine
// ---------------------------------------------------------------------------------------------- route + grouped experts at the real batch sizes
// moe_tc_route counts and permutes the pairs by expert with work-group atomics in shared memory; this checks it (and the grouped kernels behind it) at the sizes of real prefill chunks: P = N * 8 pairs
// over E = 512 experts with uneven routing (a hot expert with 100+ pairs, a few experts without any, the last expert used), against a host histogram / permutation check and against the per-pair kernels.
struct BigRoute {
Slabs S;
uint8_t* dsec = nullptr;
ExpertDesc* ddesc = nullptr;
};
void run_big_route(BigRoute& B, int N, int top_k, int hot_pct, const char* tag) {
const Slabs& S = B.S;
const int D = S.D, I = S.I, P = N * top_k, E = S.E;
std::vector<int> idx(P), hist(E, 0);
for (int p = 0; p < P; ++p) {
const int r = rint_(100);
int e = rint_(E);
if (r < hot_pct) e = 3; // one hot expert
else if (r < hot_pct + 2) e = E - 1; // the last expert
else if (e >= 40 && e < 60) e += 20; // experts 40 .. 59 stay unused
idx[p] = e;
++hist[e];
}
int* didx = dev(idx);
const std::vector<float> x = make_act(size_t(N) * D), a2 = make_act(size_t(P) * I);
float *dx = dev(x), *da2 = dev(a2);
MoeTcWork w;
const bool ok = moe_tc_alloc(w, P, E);
moe_tc_route(w, didx, P, 0);
cudaDeviceSynchronize();
// the route tables
const auto perm = host(w.perm, P), est = host(w.exp_start, E), ecnt = host(w.exp_cnt, E), tile_e = host(w.tile_e, w.max_tiles), tile_j = host(w.tile_j, w.max_tiles);
const int ntiles = host(w.ntiles, 1)[0];
bool tabs = ok;
std::vector<char> seen(P, 0);
int start_expect = 0, mx = 0;
for (int e = 0; e < E && tabs; ++e) {
tabs = ecnt[e] == hist[e] && est[e] == start_expect;
start_expect += hist[e];
mx = std::max(mx, hist[e]);
for (int i = 0; tabs && i < ecnt[e]; ++i) {
const int p = perm[est[e] + i];
tabs = p >= 0 && p < P && !seen[p] && idx[p] == e;
if (tabs) seen[p] = 1;
}
}
for (int p = 0; tabs && p < P; ++p) tabs = seen[p] != 0;
// tile list: every expert with pairs has tiles j = 0 .. ceil(cnt / tn) - 1 for one tile width tn (16 or 32), in expert order
int tn_found = 0;
for (int tn : {16, 32}) {
int expect = 0;
for (int e = 0; e < E; ++e) expect += (hist[e] + tn - 1) / tn;
if (expect != ntiles) continue;
bool good = true;
int t = 0;
for (int e = 0; e < E && good; ++e)
for (int j = 0; j < (hist[e] + tn - 1) / tn && good; ++j, ++t) good = t < w.max_tiles && tile_e[t] == e && tile_j[t] == j;
if (good) { tn_found = tn; break; }
}
check(tabs && tn_found != 0, std::string("moe_tc_route ") + tag + " P=" + std::to_string(P) + " E=" + std::to_string(E) + ": counts, starts and the permutation by expert exact (largest expert " + std::to_string(mx) + " pairs), " +
std::to_string(ntiles) + " tiles of " + std::to_string(tn_found) + " pairs");
// the grouped GEMMs against the per-pair kernels
const float sentinel = 12345.0f;
std::vector<float> gfill(size_t(P) * 2 * I, sentinel), yfill(size_t(P) * D, sentinel);
float *tgu = dev(gfill), *tye = dev(yfill), *gref = dev(gfill), *yref = dev(yfill);
moe_tc_gu(w, B.dsec, B.ddesc, S.layer_base, nullptr, P, top_k, D, I, dx, tgu, 0);
moe_tc_dn(w, B.dsec, B.ddesc, S.layer_base, nullptr, P, top_k, D, I, da2, tye, 0);
moe_gu(B.dsec, B.ddesc, S.layer_base, didx, N, top_k, E, D, I, dx, false, gref, 0, nullptr);
moe_dn(B.dsec, B.ddesc, S.layer_base, didx, N, top_k, E, D, I, da2, false, yref, 0, nullptr);
cudaDeviceSynchronize();
const auto a = host(tgu, gfill.size()), b = host(gref, gfill.size()), c = host(tye, yfill.size()), d = host(yref, yfill.size());
auto rel = [&](const std::vector<float>& u, const std::vector<float>& v) {
double e = 0, r = 0;
size_t unwritten = 0;
for (size_t i = 0; i < u.size(); ++i) {
unwritten += u[i] == sentinel;
e = std::fmax(e, std::fabs(double(u[i]) - v[i]));
r += double(v[i]) * v[i];
}
return std::make_pair(e / std::sqrt(r / u.size() + 1e-30), unwritten);
};
const auto rg = rel(a, b), rd = rel(c, d);
const bool same = std::memcmp(a.data(), b.data(), a.size() * 4) == 0 && std::memcmp(c.data(), d.data(), c.size() * 4) == 0;
check(rg.second == 0 && rd.second == 0 && (same || (rg.first < 4e-5 && rd.first < 4e-5)), // the max over millions of outputs: 2.0e-5 at every size (the CUDA model test allows 5e-5)
std::string("grouped gate/up + down ") + tag + " P=" + std::to_string(P) + " vs the per-pair kernels: " + (same ? "bit for bit" : "max error " + std::to_string(rg.first) + " / " + std::to_string(rd.first) + " of the rms") + ", unwritten pairs " +
std::to_string(rg.second + rd.second));
moe_tc_free(w);
for (void* q : std::initializer_list<void*>{didx, dx, da2, tgu, tye, gref, yref}) cudaFree(q);
}
void run_swiglu_and_combine() {
{ // swiglu with strides
const int N = 5, I = 700, gs = 1400, us = 1000, os = 800;
std::vector<float> g(size_t(N) * gs), u(size_t(N) * us);
for (auto& v : g) v = nrm() * 3.0f;
for (auto& v : u) v = nrm() * 3.0f;
float *dg = dev(g), *du = dev(u), *dout = dev_alloc<float>(size_t(N) * os);
for (float lim : {0.0f, 7.0f})
for (int post = 0; post < 2; ++post) {
cudaMemset(dout, 0, size_t(N) * os * 4);
swiglu(dg, gs, du, us, lim, post != 0, dout, os, N, I, 0);
cudaDeviceSynchronize();
const auto o = host(dout, size_t(N) * os);
double e = 0;
for (int t = 0; t < N; ++t)
for (int i = 0; i < I; ++i) {
const float a = g[size_t(t) * gs + i], b = u[size_t(t) * us + i];
auto silu = [](float x) { return x / (1.0f + std::exp(-x)); };
float r;
if (lim > 0.0f) r = (post ? std::fmin(silu(a), lim) : silu(std::fmin(a, lim))) * std::fmax(-lim, std::fmin(b, lim));
else r = silu(a) * b;
e = std::fmax(e, std::fabs(o[size_t(t) * os + i] - r) / (std::fabs(r) + 1e-3));
}
check(e < 2e-6, std::string("swiglu N=5 I=700 lim=") + std::to_string(lim) + (post ? " post_silu" : " pre") + ": max rel error " + std::to_string(e));
}
cudaFree(dg); cudaFree(du); cudaFree(dout);
}
{ // gemv2_swiglu_s8: both S8_K matrices in one pass
const int rows = 70, K = 768;
const int nsb = K / 256;
std::vector<uint8_t> Wg(size_t(rows) * nsb * 262), Wu(size_t(rows) * nsb * 262);
for (size_t i = 0; i < size_t(rows) * nsb; ++i) { fill_sb(8, Wg.data() + i * 262); fill_sb(8, Wu.data() + i * 262); }
uint8_t *dWg = dev(Wg), *dWu = dev(Wu);
for (int N : {1, 3, 4, 7, 8, 16}) {
const std::vector<float> x = make_act(size_t(N) * K);
float* dx = dev(x);
const int os = rows + 3;
for (float lim : {0.0f, 7.0f}) {
float* dout = dev_alloc<float>(size_t(N) * os);
cudaMemset(dout, 0, size_t(N) * os * 4);
gemv2_swiglu_s8(dWg, dWu, rows, K, dx, N, lim, true, dout, os, 0);
cudaDeviceSynchronize();
const auto o = host(dout, size_t(N) * os);
double e = 0;
for (int t = 0; t < N; ++t)
for (int r = 0; r < rows; ++r) {
const float a = cpu_row_f(8, Wg.data() + size_t(r) * nsb * 262, K, x.data() + size_t(t) * K);
const float b = cpu_row_f(8, Wu.data() + size_t(r) * nsb * 262, K, x.data() + size_t(t) * K);
auto silu = [](float v) { return v / (1.0f + std::exp(-v)); };
const float ref = lim > 0 ? std::fmin(silu(a), lim) * std::fmax(-lim, std::fmin(b, lim)) : silu(a) * b;
e = std::fmax(e, std::fabs(o[size_t(t) * os + r] - ref) / (std::fabs(ref) + 0.05)); // the outputs are sums of terms of both signs: the error is relative to the typical output size
}
check(e < 1e-5, "gemv2_swiglu_s8 [70 x 768] N=" + std::to_string(N) + " lim=" + std::to_string(lim) + ": max rel error vs the CPU model " + std::to_string(e));
cudaFree(dout);
}
cudaFree(dx);
}
cudaFree(dWg); cudaFree(dWu);
}
{ // moe_combine and moe_combine_norm
for (int N : {1, 3, 16}) {
const int top_k = 8, D = 2560;
std::vector<float> x(size_t(N) * D), ye(size_t(N) * top_k * D), w(size_t(N) * top_k), ysh(size_t(N) * D), gamma(D);
for (auto& v : x) v = nrm();
for (auto& v : ye) v = nrm() * 0.5f;
for (auto& v : w) v = 0.05f + 0.2f * (g_rng() % 1000) / 1000.0f;
for (auto& v : ysh) v = nrm() * 0.3f;
for (auto& v : gamma) v = 1.0f + 0.1f * nrm();
float *dye = dev(ye), *dw = dev(w), *dysh = dev(ysh), *dg = dev(gamma);
for (int with_sh = 0; with_sh < 2; ++with_sh) {
float* dx1 = dev(x);
float* dx2 = dev(x);
float* dh = dev_alloc<float>(x.size());
float* dh2 = dev_alloc<float>(x.size());
moe_combine(dx1, dye, dw, N, top_k, D, 0, with_sh ? dysh : nullptr);
moe_combine_norm(dx2, dye, dw, N, top_k, D, 0, with_sh ? dysh : nullptr, dg, 1e-6f, dh);
rmsnorm(dx1, dg, 1e-6f, dh2, N, D, 0);
cudaDeviceSynchronize();
const auto o1 = host(dx1, x.size()), o2 = host(dx2, x.size()), h1 = host(dh, x.size()), h2 = host(dh2, x.size());
double e = 0;
for (int t = 0; t < N; ++t)
for (int d = 0; d < D; ++d) {
float s = 0.0f;
for (int k = 0; k < top_k; ++k) s = std::fmaf(w[t * top_k + k], ye[(size_t(t) * top_k + k) * D + d], s);
const size_t at = size_t(t) * D + d;
const float ref = (with_sh ? x[at] + ysh[at] : x[at]) + s;
e = std::fmax(e, std::fabs(o1[at] - ref) / (std::fabs(ref) + 1e-3));
}
check(e < 1e-6, "moe_combine N=" + std::to_string(N) + (with_sh ? " + shared" : "") + ": max rel error vs the CPU " + std::to_string(e));
check(std::memcmp(o1.data(), o2.data(), o1.size() * 4) == 0 && std::memcmp(h1.data(), h2.data(), h1.size() * 4) == 0,
"moe_combine_norm N=" + std::to_string(N) + (with_sh ? " + shared" : "") + ": x and h bit-identical to moe_combine + rmsnorm");
cudaFree(dx1); cudaFree(dx2); cudaFree(dh); cudaFree(dh2);
}
cudaFree(dye); cudaFree(dw); cudaFree(dysh); cudaFree(dg);
}
}
}
} // namespace
// ---------------------------------------------------------------------------------------------- the trunk GEMM (gemm_sk_tc: XMX tiles where the device has them) against the float GEMV
std::vector<uint8_t> make_matrix(int code, int rows, int K) {
std::vector<uint8_t> W(size_t(rows) * (K / 256) * sbb(code));
for (size_t i = 0; i < size_t(rows) * (K / 256); ++i) fill_sb(code, W.data() + i * sbb(code));
return W;
}
void run_trunk(int code, int rows, int K, int N, bool accumulate) {
const std::vector<uint8_t> W = make_matrix(code, rows, K);
const std::vector<float> x = make_act(size_t(N) * K);
std::vector<float> o0(size_t(N) * rows);
for (auto& v : o0) v = nrm();
uint8_t* dW = dev(W);
float *dx = dev(x), *dref = dev(o0), *dout = dev(o0);
gemv_sk(dW, code, rows, K, dx, false, N, dref, rows, accumulate, 0);
gemm_sk_tc(dW, code, rows, K, dx, N, dout, rows, accumulate, 0);
cudaDeviceSynchronize();
const auto a = host(dref, o0.size()), b = host(dout, o0.size());
double e = 0, r = 0;
for (size_t i = 0; i < a.size(); ++i) { e = std::fmax(e, std::fabs(double(a[i]) - b[i])); r += double(a[i]) * a[i]; }
const double rel = e / std::sqrt(r / a.size() + 1e-30);
const bool same = std::memcmp(a.data(), b.data(), a.size() * 4) == 0;
check(rel < 2e-5, "trunk GEMM S" + std::to_string(code) + " [" + std::to_string(rows) + " x " + std::to_string(K) + "] N=" + std::to_string(N) + (accumulate ? " accumulate" : "") + " vs the float GEMV: " +
(same ? "bit for bit" : "max error " + std::to_string(rel) + " of the rms"));
cudaFree(dW); cudaFree(dx); cudaFree(dref); cudaFree(dout);
}
// L32MOE_BENCH=trunk: the prefill GEMMs of the trunk at the real shapes (S8_K), scalar float GEMV vs gemm_sk_tc
void bench_trunk() {
struct Shape { const char* name; int rows, K; };
const Shape shapes[] = {{"KDA qkvfg [20480 x 2560]", 20480, 2560}, {"KDA/MLA o [2560 x 4096]", 2560, 4096}, {"MLA q [6144 x 2560]", 6144, 2560}, {"[2560 x 768]", 2560, 768},
{"dense / shared up-gate [6144 x 2560]", 6144, 2560}, {"dense down [2560 x 6144]", 2560, 6144}};
for (const Shape& sh : shapes) {
const std::vector<uint8_t> W = make_matrix(8, sh.rows, sh.K);
uint8_t* dW = dev(W);
for (int N : {32, 128, 512, 2048}) {
const std::vector<float> x = make_act(size_t(N) * sh.K);
float *dx = dev(x), *dout = dev_alloc<float>(size_t(N) * sh.rows);
auto time_ms = [&](auto&& fn) {
fn();
cudaDeviceSynchronize();
const auto t0 = std::chrono::steady_clock::now();
const int reps = N >= 512 ? 3 : 8;
for (int i = 0; i < reps; ++i) fn();
cudaDeviceSynchronize();
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / reps;
};
const double t_sc = time_ms([&] { gemv_sk(dW, 8, sh.rows, sh.K, dx, false, N, dout, sh.rows, false, 0); });
const double t_xm = time_ms([&] { gemm_sk_tc(dW, 8, sh.rows, sh.K, dx, N, dout, sh.rows, false, 0); });
const double fl = 2.0 * N * sh.rows * sh.K;
std::printf(" S8 %-38s N=%4d: scalar GEMV %8.3f ms = %6.2f TFLOP/s, gemm_sk_tc %8.3f ms = %6.2f TFLOP/s (%.2fx)\n", sh.name, N, t_sc, fl / (t_sc * 1e9), t_xm, fl / (t_xm * 1e9), t_sc / t_xm);
cudaFree(dx); cudaFree(dout);
}
cudaFree(dW);
}
}
// L32MOE_BENCH=decode: the decode path (1 and 4 tokens, top_k 8): moe_gu / moe_act / moe_dn with float and Q8 activations, rotating expert sets (weights from DRAM), GB/s of weights read.
void bench_decode() {
const int D = 2560, I = 768, E = 64, top_k = 8, nsets = 8;
for (int code : {5, 4, 6, 8}) {
const Slabs S = make_slabs(E, D, I, 0, {code});
uint8_t* dsec = dev(S.buf);
ExpertDesc* ddesc = dev(S.desc);
const double gu_bytes = double(2) * I * (D / 256) * sbb(code), dn_bytes = double(D) * (I / 256) * sbb(code);
for (int N : {1, 2, 4}) {
const int P = N * top_k;
std::vector<int> idx(size_t(nsets) * P);
for (int s = 0; s < nsets; ++s)
for (int p = 0; p < P; ++p) idx[size_t(s) * P + p] = (s * 8 + p) % E; /* distinct experts within a set, the sets cover all 64 */
int* didx = dev(idx);
const std::vector<float> x = make_act(size_t(N) * D), a2 = make_act(size_t(P) * I);
float *dx = dev(x), *da2 = dev(a2), *gu = dev_alloc<float>(size_t(P) * 2 * I), *ye = dev_alloc<float>(size_t(P) * D);
Q8Blk *dxq = dev(quant_cpu(x.data(), N * D)), *da2q = dev(quant_cpu(a2.data(), P * I));
auto time_ms = [&](auto&& fn) {
for (int s = 0; s < nsets; ++s) fn(s);
cudaDeviceSynchronize();
const auto t0 = std::chrono::steady_clock::now();
const int reps = 4;
for (int i = 0; i < reps * nsets; ++i) fn(i % nsets);
cudaDeviceSynchronize();
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / (reps * nsets);
};
const double t_gu = time_ms([&](int s) { moe_gu(dsec, ddesc, 0, didx + size_t(s) * P, N, top_k, E, D, I, dx, false, gu, 0, nullptr); });
const double t_dn = time_ms([&](int s) { moe_dn(dsec, ddesc, 0, didx + size_t(s) * P, N, top_k, E, D, I, da2, false, ye, 0, nullptr); });
const double t_guq = time_ms([&](int s) { moe_gu(dsec, ddesc, 0, didx + size_t(s) * P, N, top_k, E, D, I, dxq, true, gu, 0, nullptr); });
const double t_dnq = time_ms([&](int s) { moe_dn(dsec, ddesc, 0, didx + size_t(s) * P, N, top_k, E, D, I, da2q, true, ye, 0, nullptr); });
std::printf(" S%d N=%d (P=%2d): gate/up float %7.3f ms = %6.1f GB/s, down float %7.3f ms = %6.1f GB/s | Q8 acts: gate/up %7.3f ms = %6.1f GB/s, down %7.3f ms = %6.1f GB/s\n", code, N, P, t_gu, P * gu_bytes / (t_gu * 1e6), t_dn,
P * dn_bytes / (t_dn * 1e6), t_guq, P * gu_bytes / (t_guq * 1e6), t_dnq, P * dn_bytes / (t_dnq * 1e6));
for (void* p : std::initializer_list<void*>{didx, dx, da2, gu, ye, dxq, da2q}) cudaFree(p);
}
cudaFree(dsec); cudaFree(ddesc);
}
}
// L32MOE_BENCH=1: timing of the batch paths at the real shape (not part of the pass / fail run). Slabs of one code, pairs spread evenly over E experts.
void bench_batches() {
const int D = 2560, I = 768, E = 64, top_k = 8;
const double flop_pair = 2.0 * 3.0 * D * I; // gate + up + down
for (int code : {5, 8}) {
const Slabs S = make_slabs(E, D, I, 0, {code});
uint8_t* dsec = dev(S.buf);
ExpertDesc* ddesc = dev(S.desc);
for (int per : {4, 16, 64}) { // pairs per expert
const int P = per * E, N = P / top_k;
std::vector<int> idx(P);
for (int p = 0; p < P; ++p) idx[p] = p % E;
int* didx = dev(idx);
const std::vector<float> x = make_act(size_t(N) * D), a2 = make_act(size_t(P) * I);
float *dx = dev(x), *da2 = dev(a2), *gu = dev_alloc<float>(size_t(P) * 2 * I), *ye = dev_alloc<float>(size_t(P) * D);
MoeTcWork w;
moe_tc_alloc(w, P, E);
auto time_ms = [&](auto&& fn) {
fn();
cudaDeviceSynchronize();
const auto t0 = std::chrono::steady_clock::now();
const int reps = 5;
for (int i = 0; i < reps; ++i) fn();
cudaDeviceSynchronize();
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / reps;
};
const double t_pair = time_ms([&] { moe_gu(dsec, ddesc, 0, didx, N, top_k, E, D, I, dx, false, gu, 0, nullptr); moe_dn(dsec, ddesc, 0, didx, N, top_k, E, D, I, da2, false, ye, 0, nullptr); });
const double t_grp = time_ms([&] { moe_tc_route(w, didx, P, 0); moe_tc_gu(w, dsec, ddesc, 0, nullptr, P, top_k, D, I, dx, gu, 0); moe_tc_dn(w, dsec, ddesc, 0, nullptr, P, top_k, D, I, da2, ye, 0); });
const double wbytes = double(E) * (S.stride > 0 ? double(S.desc[0].body_bytes) : 0.0);
std::printf(" S%d slabs, %3d pairs/expert (P=%d): per-pair kernels %8.2f ms, grouped %8.2f ms = %6.2f TFLOP/s, %6.1f GB/s of weights\n", code, per, P, t_pair, t_grp,
flop_pair * P / (t_grp * 1e9), wbytes / (t_grp * 1e6));
moe_tc_free(w);
for (void* p : std::initializer_list<void*>{didx, dx, da2, gu, ye}) cudaFree(p);
}
cudaFree(dsec); cudaFree(ddesc);
}
}
// the route + grouped-experts cases at the real batch sizes; only_chunk: just the 16384-pair case (L32MOE_ONLY_CHUNK=1, to run the largest case alone)
static void run_big_section(bool only_chunk) {
std::printf("[route + grouped experts at the real batch sizes: P = 1024 .. 16384 pairs, E = 512 experts, a hot expert with 100+ pairs, unused experts]\n");
BigRoute B;
B.S = make_slabs(512, 512, 256, 0, {4, 5, 6, 8});
B.dsec = dev(B.S.buf);
B.ddesc = dev(B.S.desc);
if (!only_chunk) {
run_big_route(B, 128, 8, 25, "hot 25 percent");
run_big_route(B, 512, 8, 12, "hot 12 percent");
run_big_route(B, 512, 8, 0, "uniform");
run_big_route(B, 64, 8, 60, "hot 60 percent");
}
run_big_route(B, 2048, 8, 5, "chunk of 2048 tokens");
cudaFree(B.dsec);
cudaFree(B.ddesc);
}
int main(int argc, char** argv) {
if (!std::getenv("L32MOE_BENCH")) setenv("STRATA_L32_TRUNK_XMX_TILES", "0", 0); // the small trunk shapes of the test must reach the XMX kernel (the default needs 128 tiles)
if (argc < 2) { std::printf("usage: ling32_moe_sy_test DATA_DIR\n"); return 2; }
if (const char* e = std::getenv("L32MOE_FMA")) g_fmask = std::atoi(e);
int ndev = 0;
cudaGetDeviceCount(&ndev);
if (ndev < 1) { std::printf("no device\n"); return 2; }
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, 0);
std::printf("device 0: %s\n", prop.name);
if (const char* bm = std::getenv("L32MOE_BENCH")) { if (std::strcmp(bm, "decode") == 0) bench_decode(); else if (std::strcmp(bm, "trunk") == 0) bench_trunk(); else bench_batches(); return 0; }
for (int code : {4, 5, 6, 8})
if (!slurp(std::string(argv[1]) + "/pack_s" + std::to_string(code) + ".bin", g_pack[code])) { std::printf("pack_s%d.bin missing\n", code); return 2; }
if (std::getenv("L32MOE_ONLY_CHUNK")) { run_big_section(true); std::printf("%s (%d failed)\n", g_fail ? "FAIL" : "PASS", g_fail); return g_fail ? 1 : 0; }
std::printf("[routed experts: moe_gu / moe_act / moe_dn / moe_tc_*, small shape D=512 I=256, mixed S4/S5/S6/S8 slabs, N = 1..16 pairs]\n");
{
const Slabs S = make_slabs(12, 512, 256, 7, {4, 5, 6, 8});
for (int N = 1; N <= 16; ++N) run_experts(S, N, 1, false, false, "slabs");
for (int N : {1, 2, 5, 16}) run_experts(S, N, 8, false, true, "slabs");
for (int N : {1, 3, 16}) run_experts(S, N, 4, true, true, "slabs");
run_experts(S, 48, 8, false, true, "slabs, 32-pair tiles"); // 32 pairs per expert: the XMX kernel takes 32-pair tiles
run_experts(S, 40, 8, true, true, "slabs, 32-pair tiles");
}
std::printf("[routed experts: the MTP layer's S2_K / S3_K slabs (random superblocks) next to S4 / S8]\n");
{
const Slabs S = make_slabs(8, 512, 256, 3, {2, 3, 4, 8});
for (int N : {1, 4, 9, 16}) run_experts(S, N, 1, false, true, "S2/S3 slabs");
}
std::printf("[routed experts: the Ling-3.2-Air shape D=2560 I=768]\n");
{
const Slabs S = make_slabs(10, 2560, 768, 0, {4, 5, 6, 8});
run_experts(S, 1, 8, false, false, "real shape");
run_experts(S, 2, 8, true, true, "real shape");
}
std::printf("[ALF-LB router: ground-truth sort, ties to the lower id]\n");
for (int N : {1, 4, 16}) {
run_router(512, 8, 4, 8, N, true, false, false);
run_router(512, 8, 4, 8, N, true, false, true);
run_router(512, 8, 3, 8, N, true, true, true);
run_router(512, 8, 4, 40, N, false, true, false); // the lookahead ranking: a longer list, no weights
}
run_router(64, 4, 2, 8, 3, true, false, true); // other shape: reference kernel
run_router(512, 8, 1, 8, 2, true, false, true);
std::printf("[swiglu, shared expert (gemv2_swiglu_s8), combine]\n");
run_swiglu_and_combine();
std::printf("[trunk GEMM: gemm_sk_tc (XMX tiles where the device has them) against the float GEMV, row counts that are no multiple of the 128-row tile, token counts around the tile widths]\n");
for (int code : {8, 5, 4, 6, 2, 3})
for (int N : {1, 31, 33, 40, 100, 129}) run_trunk(code, code == 8 ? 200 : 392, code == 8 ? 768 : 512, N, N % 2 == 0);
run_big_section(false);
std::printf("%s (%d failed)\n", g_fail ? "FAIL" : "PASS", g_fail);
return g_fail ? 1 : 0;
}