hkimi / src /gpu /selftest.cpp
Ozomozyan's picture
hkimi 0.1.0
68888be verified
Raw History Blame Contribute Delete
27.9 kB
#include "gpu/selftest.h"
#include <cmath>
#include <cstring>
#include <functional>
#include "common/base.h"
#include "common/numeric.h"
#include "io/file_io.h"
namespace hk {
namespace {
struct Ctx {
Backend& bk;
Rng rng;
Ctx(Backend& b, uint64_t seed) : bk(b), rng(seed) {}
std::vector<float> randn(size_t n, float std = 1.0f) {
std::vector<float> v(n);
for (auto& x : v) x = (float)rng.normal() * std;
return v;
}
Tensor* tensor(int rows, int cols, float std = 1.0f) {
Tensor* t = bk.alloc(rows, cols);
std::vector<float> v = randn((size_t)rows * (size_t)cols, std);
if (rows > 0 && cols > 0) bk.upload(t, 0, rows, v.data());
return t;
}
Weight* dense(WFmt fmt, int rows, int cols, float std = 1.0f) {
std::vector<float> v = randn((size_t)rows * (size_t)cols, std);
std::vector<uint8_t> raw;
if (fmt == WFmt::F32) {
raw.resize(v.size() * 4);
memcpy(raw.data(), v.data(), raw.size());
} else {
raw.resize(v.size() * 2);
for (size_t i = 0; i < v.size(); ++i)
store_le16(raw.data() + 2 * i, fmt == WFmt::BF16 ? f32_to_bf16(v[i]) : f32_to_f16(v[i]));
}
WeightDesc d;
d.fmt = fmt;
d.rows = rows;
d.cols = cols;
WeightData data;
data.dense = raw.data();
return bk.load(d, data);
}
// random bit planes: nplanes planes, E8M0 or half-float scales
Weight* planes(int rows, int cols, int nplanes, ScaleKind sk, int group) {
PlanesDesc pd;
pd.rows = rows;
pd.cols = cols;
pd.nplanes = nplanes;
pd.group = group;
pd.scale = sk;
for (int i = 0; i < 8; ++i) pd.lut[i] = nplanes == 4 ? kE2M1[i] : 0.3f + 0.7f * (float)i;
std::vector<uint8_t> sc((size_t)pd.scale_bytes()), pl[4];
if (sk == ScaleKind::E8M0) {
for (auto& b : sc) b = (uint8_t)(120 + rng.below(6));
} else {
for (size_t i = 0; i + 1 < sc.size(); i += 2) store_le16(sc.data() + i, f32_to_f16(0.05f + 0.2f * (float)rng.uniform()));
}
WeightData data;
data.planes.scales = sc.data();
for (int p = 0; p < nplanes; ++p) {
pl[p].resize((size_t)pd.plane_bytes());
for (auto& b : pl[p]) b = (uint8_t)rng.below(256);
data.planes.planes[p] = pl[p].data();
}
WeightDesc d;
d.fmt = WFmt::PLANES;
d.rows = rows;
d.cols = cols;
d.planes = pd;
return bk.load(d, data);
}
std::vector<float> read(const Tensor* t) {
std::vector<float> v((size_t)t->rows * (size_t)t->cols);
if (!v.empty()) bk.download(t, 0, t->rows, v.data());
return v;
}
};
double rel_err(const std::vector<float>& a, const std::vector<float>& b) {
if (a.size() != b.size()) return 1e30;
double num = 0, den = 0;
for (size_t i = 0; i < a.size(); ++i) {
if (!std::isfinite(a[i]) || !std::isfinite(b[i])) return 1e30;
num += ((double)a[i] - b[i]) * ((double)a[i] - b[i]);
den += (double)a[i] * a[i];
}
return std::sqrt(num / std::max(den, 1e-30));
}
} // namespace
SelftestReport backend_selftest(Backend& ref, Backend& dut, uint64_t seed, bool quick) {
SelftestReport rep;
// each case builds the same inputs on both backends (same seed), runs fn and returns the outputs to compare
auto run = [&](const std::string& name, double tol, const std::function<std::vector<float>(Ctx&)>& fn) {
SelftestCase c;
c.name = name;
try {
Ctx a(ref, seed), b(dut, seed);
std::vector<float> ra = fn(a), rb = fn(b);
c.rel_err = rel_err(ra, rb);
c.ok = c.rel_err <= tol;
} catch (const std::exception& e) {
c.rel_err = 1e30;
c.ok = false;
c.name += std::string(" [") + e.what() + "]";
}
rep.passed += c.ok ? 1 : 0;
rep.cases.push_back(c);
};
// The tested backend against itself: fn computes the same rows twice, all at once and a
// few at a time, and the results must be the same bits (docs/exact.md). rel_err holds
// the share of values that differ.
auto run_same = [&](const std::string& name, const std::function<void(Ctx&, std::vector<float>&, std::vector<float>&)>& fn) {
SelftestCase c;
c.name = name;
c.bits = true;
try {
Ctx b(dut, seed);
std::vector<float> whole, parts;
fn(b, whole, parts);
size_t diff = whole.size() == parts.size() ? 0 : std::max(whole.size(), parts.size());
for (size_t i = 0; i < whole.size() && i < parts.size(); ++i) diff += memcmp(&whole[i], &parts[i], 4) != 0 ? 1 : 0;
c.rel_err = whole.empty() ? 1.0 : (double)diff / (double)whole.size();
c.ok = diff == 0 && !whole.empty();
} catch (const std::exception& e) {
c.rel_err = 1e30;
c.ok = false;
c.name += std::string(" [") + e.what() + "]";
}
rep.passed += c.ok ? 1 : 0;
rep.cases.push_back(c);
};
const int T = quick ? 3 : 7;
const double tol = 2e-4;
// 37 rows: two full tiles of the GPU kernel and a rest of five. Then the same rows in groups of
// 1, 2, 3, 5 and 9, which go through every other tile width.
for (int kind = 0; kind < 4; ++kind) {
static const char* const names[4] = {"F32", "BF16", "planes x4", "planes x2"};
run_same(std::string("linear ") + names[kind] + ": a row alone and among others, same bits",
[&, kind](Ctx& c, std::vector<float>& whole, std::vector<float>& parts) {
const int n = 37, rows = 96, cols = 160;
WeightRef w(&c.bk, kind == 0 ? c.dense(WFmt::F32, rows, cols, 0.1f)
: kind == 1 ? c.dense(WFmt::BF16, rows, cols, 0.1f)
: kind == 2 ? c.planes(rows, cols, 4, ScaleKind::E8M0, 32)
: c.planes(rows, cols, 2, ScaleKind::F16, 32));
std::vector<float> xv = c.randn((size_t)n * cols);
TensorRef x(&c.bk, n, cols), y(&c.bk, n, rows);
c.bk.upload(x, 0, n, xv.data());
c.bk.linear(w, x, y);
c.bk.linear(w, x, y, 0.5f, true);
whole = c.read(y);
static const int group[5] = {1, 2, 3, 5, 9};
for (int a = 0, g = 0; a < n; ++g) {
const int m = std::min(group[g % 5], n - a);
TensorRef xs(&c.bk, m, cols), ys(&c.bk, m, rows);
c.bk.upload(xs, 0, m, xv.data() + (size_t)a * cols);
c.bk.linear(w, xs, ys);
c.bk.linear(w, xs, ys, 0.5f, true);
std::vector<float> o = c.read(ys);
parts.insert(parts.end(), o.begin(), o.end());
a += m;
}
});
}
// An expert record loaded matrix by matrix, then as one block from a page-locked
// buffer (where the backend can): the three products must be the same bits.
run_same("load_block: an expert record in one piece and matrix by matrix, same bits",
[&](Ctx& c, std::vector<float>& whole, std::vector<float>& parts) {
const int rows[3] = {40, 40, 96}, cols[3] = {96, 96, 64}, n = 5;
WeightDesc d[3];
int64_t scale_all = 0, plane_all = 0;
for (int m = 0; m < 3; ++m) {
PlanesDesc& pd = d[m].planes;
pd.rows = rows[m];
pd.cols = cols[m];
pd.nplanes = 4;
pd.group = 32;
pd.scale = ScaleKind::E8M0;
for (int i = 0; i < 8; ++i) pd.lut[i] = kE2M1[i];
d[m].fmt = WFmt::PLANES;
d[m].rows = rows[m];
d[m].cols = cols[m];
scale_all += pd.scale_bytes();
plane_all += pd.plane_bytes();
}
const int64_t scale_part = align_up(scale_all), plane_part = align_up(plane_all);
AlignedBuf rec(scale_part + 4 * plane_part);
for (int64_t i = 0; i < rec.size(); ++i) rec.data()[i] = (uint8_t)c.rng.below(256);
for (int64_t i = 0; i < scale_all; ++i) rec.data()[i] = (uint8_t)(120 + c.rng.below(6));
WeightData data[3];
int64_t soff = 0, poff = 0;
for (int m = 0; m < 3; ++m) {
data[m].planes.scales = rec.data() + soff;
for (int p = 0; p < 4; ++p) data[m].planes.planes[p] = rec.data() + scale_part + p * plane_part + poff;
soff += d[m].planes.scale_bytes();
poff += d[m].planes.plane_bytes();
}
std::vector<std::vector<float>> xv(3);
for (int m = 0; m < 3; ++m) xv[(size_t)m] = c.randn((size_t)n * cols[m]);
auto products = [&](Weight* const* w, std::vector<float>& out) {
for (int m = 0; m < 3; ++m) {
TensorRef x(&c.bk, n, cols[m]), y(&c.bk, n, rows[m]);
c.bk.upload(x, 0, n, xv[(size_t)m].data());
c.bk.linear(w[m], x, y);
std::vector<float> o = c.read(y);
out.insert(out.end(), o.begin(), o.end());
}
};
{
WeightRef a(&c.bk, c.bk.load(d[0], data[0])), b(&c.bk, c.bk.load(d[1], data[1])), e(&c.bk, c.bk.load(d[2], data[2]));
Weight* w[3] = {a.get(), b.get(), e.get()};
products(w, whole);
}
const bool pinned = c.bk.pin(rec.data(), rec.size());
try {
Weight* w[3] = {nullptr, nullptr, nullptr};
c.bk.load_block(d, data, 3, rec.data(), rec.size(), w);
WeightRef a(&c.bk, w[0]), b(&c.bk, w[1]), e(&c.bk, w[2]);
products(w, parts);
// one of the three goes first, the others must still be whole
a.reset();
std::vector<float> again;
Weight* rest[3] = {nullptr, b.get(), e.get()};
for (int m = 1; m < 3; ++m) {
TensorRef x(&c.bk, n, cols[m]), y(&c.bk, n, rows[m]);
c.bk.upload(x, 0, n, xv[(size_t)m].data());
c.bk.linear(rest[m], x, y);
std::vector<float> o = c.read(y);
again.insert(again.end(), o.begin(), o.end());
}
const std::vector<float> tail(whole.begin() + (std::ptrdiff_t)((size_t)n * rows[0]), whole.end());
whole.insert(whole.end(), tail.begin(), tail.end());
parts.insert(parts.end(), again.begin(), again.end());
} catch (...) {
if (pinned) c.bk.unpin(rec.data());
throw;
}
if (pinned) c.bk.unpin(rec.data());
});
// Two matrices loaded the ordinary way and ahead of need (load_async), from a page-locked
// buffer where the backend can: same bits. After the wait nothing may read the source,
// so it is overwritten before the products are taken; and one of the two is given back
// while the other still travels.
run_same("load_async: weights loaded ahead of need and loaded when asked for, same bits",
[&](Ctx& c, std::vector<float>& whole, std::vector<float>& parts) {
const int rows = 70, cols = 96, n = 6;
const size_t one = (size_t)rows * (size_t)cols * 2;
AlignedBuf raw(align_up((int64_t)(3 * one)));
std::vector<float> v = c.randn((size_t)rows * (size_t)cols * 3, 0.1f);
for (size_t i = 0; i < v.size(); ++i) store_le16(raw.data() + 2 * i, f32_to_bf16(v[i]));
WeightDesc d;
d.fmt = WFmt::BF16;
d.rows = rows;
d.cols = cols;
WeightData at[3];
for (int m = 0; m < 3; ++m) at[m].dense = raw.data() + (size_t)m * one;
const std::vector<float> xv = c.randn((size_t)n * cols);
auto product = [&](const Weight* w, std::vector<float>& out) {
TensorRef x(&c.bk, n, cols), y(&c.bk, n, rows);
c.bk.upload(x, 0, n, xv.data());
c.bk.linear(w, x, y);
std::vector<float> o = c.read(y);
out.insert(out.end(), o.begin(), o.end());
};
{
WeightRef a(&c.bk, c.bk.load(d, at[0])), b(&c.bk, c.bk.load(d, at[1]));
product(a, whole);
product(b, whole);
}
const bool pinned = c.bk.pin(raw.data(), raw.size());
try {
WeightRef a(&c.bk, c.bk.load_async(d, at[0])), b(&c.bk, c.bk.load_async(d, at[1])), gone(&c.bk, c.bk.load_async(d, at[2]));
gone.reset(); // given back while the others may still be on their way
{
// something else is computed meanwhile, in memory that was just given back
WeightRef o(&c.bk, c.dense(WFmt::BF16, rows, cols, 0.1f));
std::vector<float> unused;
product(o, unused);
}
c.bk.wait_loads();
memset(raw.data(), 0xA5, (size_t)raw.size());
product(a, parts);
product(b, parts);
} catch (...) {
if (pinned) c.bk.unpin(raw.data());
throw;
}
if (pinned) c.bk.unpin(raw.data());
});
run_same("gemm: a row alone and among others, same bits", [&](Ctx& c, std::vector<float>& whole, std::vector<float>& parts) {
const int n = 9, k = 24, r = 5;
std::vector<float> av = c.randn((size_t)n * k);
Tensor* b = c.tensor(r, k);
TensorRef a(&c.bk, n, k), o(&c.bk, n, r);
c.bk.upload(a, 0, n, av.data());
c.bk.gemm(a, false, b, true, 1.0f, 0.0f, o);
whole = c.read(o);
for (int i = 0; i < n; ++i) {
TensorRef a1(&c.bk, 1, k), o1(&c.bk, 1, r);
c.bk.upload(a1, 0, 1, av.data() + (size_t)i * k);
c.bk.gemm(a1, false, b, true, 1.0f, 0.0f, o1);
std::vector<float> v = c.read(o1);
parts.insert(parts.end(), v.begin(), v.end());
}
c.bk.release(b);
});
run_same("kda_recur: all steps at once and one at a time, same bits", [&](Ctx& c, std::vector<float>& whole, std::vector<float>& parts) {
const int H = 2, D = 8, n = 6;
std::vector<float> q = c.randn((size_t)n * H * D), k = c.randn((size_t)n * H * D), v = c.randn((size_t)n * H * D),
g = c.randn((size_t)n * H * D, 0.5f), bl = c.randn((size_t)n * H);
for (auto& x : g) x = -std::fabs(x);
for (int pass = 0; pass < 2; ++pass) {
TensorRef S(&c.bk, H * D, D);
c.bk.fill(S, 0.0f);
std::vector<float>& out = pass == 0 ? whole : parts;
const int step = pass == 0 ? n : 1;
for (int a = 0; a < n; a += step) {
TensorRef tq(&c.bk, step, H * D), tk(&c.bk, step, H * D), tv(&c.bk, step, H * D), tg(&c.bk, step, H * D),
tb(&c.bk, step, H), o(&c.bk, step, H * D);
c.bk.upload(tq, 0, step, q.data() + (size_t)a * H * D);
c.bk.upload(tk, 0, step, k.data() + (size_t)a * H * D);
c.bk.upload(tv, 0, step, v.data() + (size_t)a * H * D);
c.bk.upload(tg, 0, step, g.data() + (size_t)a * H * D);
c.bk.upload(tb, 0, step, bl.data() + (size_t)a * H);
c.bk.kda_recur(tq, tk, tv, tg, tb, H, S, o);
std::vector<float> oo = c.read(o);
out.insert(out.end(), oo.begin(), oo.end());
}
std::vector<float> ss = c.read(S);
out.insert(out.end(), ss.begin(), ss.end());
}
});
run_same("mla_attend: a query alone, with only the keys it sees, and in a batch: same bits",
[&](Ctx& c, std::vector<float>& whole, std::vector<float>& parts) {
MlaShape sh;
sh.heads = 3;
sh.nope = 8;
sh.rope = 4;
sh.vdim = 6;
sh.kv_rank = 16;
const int S = 13, nq = 6, pos0 = S - nq, qd = sh.heads * (sh.nope + sh.rope);
WeightRef kvb(&c.bk, c.dense(WFmt::BF16, sh.heads * (sh.nope + sh.vdim), sh.kv_rank, 0.3f));
std::vector<float> qv = c.randn((size_t)nq * qd);
Tensor* C = c.tensor(S, sh.kv_rank);
Tensor* R = c.tensor(S, sh.rope);
TensorRef q(&c.bk, nq, qd), o(&c.bk, nq, sh.heads * sh.vdim);
c.bk.upload(q, 0, nq, qv.data());
c.bk.mla_attend(sh, q, kvb, C, R, S, pos0, nullptr, o);
whole = c.read(o);
for (int t = 0; t < nq; ++t) {
TensorRef q1(&c.bk, 1, qd), o1(&c.bk, 1, sh.heads * sh.vdim);
c.bk.upload(q1, 0, 1, qv.data() + (size_t)t * qd);
c.bk.mla_attend(sh, q1, kvb, C, R, pos0 + t + 1, pos0 + t, nullptr, o1);
std::vector<float> v = c.read(o1);
parts.insert(parts.end(), v.begin(), v.end());
}
for (Tensor* t : {C, R}) c.bk.release(t);
});
for (int rows_x : {1, T}) {
const std::string sfx = rows_x == 1 ? " (1 row)" : " (batch)";
run("linear F32" + sfx, tol, [&](Ctx& c) {
WeightRef w(&c.bk, c.dense(WFmt::F32, 96, 160, 0.1f));
Tensor* xt = c.tensor(rows_x, 160);
TensorRef y(&c.bk, rows_x, 96);
c.bk.linear(w, xt, y);
c.bk.linear(w, xt, y, 0.5f, true);
std::vector<float> out = c.read(y);
c.bk.release(xt);
return out;
});
run("linear BF16" + sfx, tol, [&](Ctx& c) {
WeightRef w(&c.bk, c.dense(WFmt::BF16, 130, 192, 0.1f));
Tensor* xt = c.tensor(rows_x, 192);
TensorRef y(&c.bk, rows_x, 130);
c.bk.linear(w, xt, y);
std::vector<float> out = c.read(y);
c.bk.release(xt);
return out;
});
run("linear F16" + sfx, tol, [&](Ctx& c) {
WeightRef w(&c.bk, c.dense(WFmt::F16, 40, 64, 0.1f));
Tensor* xt = c.tensor(rows_x, 64);
TensorRef y(&c.bk, rows_x, 40);
c.bk.linear(w, xt, y);
std::vector<float> out = c.read(y);
c.bk.release(xt);
return out;
});
for (int np = 1; np <= 4; ++np) {
run(strfmt("linear planes k=%d E8M0", np) + sfx, tol, [&, np](Ctx& c) {
WeightRef w(&c.bk, c.planes(70, 224, np, ScaleKind::E8M0, 32));
Tensor* xt = c.tensor(rows_x, 224);
TensorRef y(&c.bk, rows_x, 70);
c.bk.linear(w, xt, y);
std::vector<float> out = c.read(y);
c.bk.release(xt);
return out;
});
}
run("linear planes k=2 F16 g64" + sfx, tol, [&](Ctx& c) {
WeightRef w(&c.bk, c.planes(50, 256, 2, ScaleKind::F16, 64));
Tensor* xt = c.tensor(rows_x, 256);
TensorRef y(&c.bk, rows_x, 50);
c.bk.linear(w, xt, y, 2.0f, false);
std::vector<float> out = c.read(y);
c.bk.release(xt);
return out;
});
}
run("gather BF16 + planes", tol, [&](Ctx& c) {
WeightRef w(&c.bk, c.dense(WFmt::BF16, 50, 64));
WeightRef p(&c.bk, c.planes(50, 64, 3, ScaleKind::F16, 32));
const int32_t ids[4] = {7, 0, 49, 7};
TensorRef y(&c.bk, 4, 64), z(&c.bk, 4, 64);
c.bk.gather(w, ids, 4, y);
c.bk.gather(p, ids, 4, z);
std::vector<float> out = c.read(y), o2 = c.read(z);
out.insert(out.end(), o2.begin(), o2.end());
return out;
});
run("gemm (all transposes)", tol, [&](Ctx& c) {
Tensor* a = c.tensor(5, 9);
Tensor* b = c.tensor(9, 4);
Tensor* bt = c.tensor(4, 9);
Tensor* at = c.tensor(9, 5);
TensorRef o(&c.bk, 5, 4);
c.bk.gemm(a, false, b, false, 1.0f, 0.0f, o);
c.bk.gemm(a, false, bt, true, 0.5f, 1.0f, o);
c.bk.gemm(at, true, b, false, 2.0f, 1.0f, o);
c.bk.gemm(at, true, bt, true, 1.0f, 0.5f, o);
std::vector<float> out = c.read(o);
for (Tensor* t : {a, b, bt, at}) c.bk.release(t);
return out;
});
run("copy / fill / take / scatter", tol, [&](Ctx& c) {
Tensor* a = c.tensor(6, 10);
TensorRef b(&c.bk, 8, 12);
c.bk.fill(b, 0.25f);
c.bk.copy(b, 1, 2, a, 0, 3, 5, 6);
const int32_t rows[3] = {5, 0, 2};
const float coef[3] = {0.5f, -1.0f, 2.0f};
TensorRef t(&c.bk, 3, 10);
c.bk.take_rows(a, rows, 3, t);
c.bk.scatter_add_rows(a, rows, coef, 3, t);
std::vector<float> out = c.read(b), o2 = c.read(a);
out.insert(out.end(), o2.begin(), o2.end());
c.bk.release(a);
return out;
});
run("rmsnorm (whole row, groups, in place)", tol, [&](Ctx& c) {
WeightRef w(&c.bk, c.dense(WFmt::BF16, 1, 48)), wg(&c.bk, c.dense(WFmt::F32, 1, 16));
Tensor* x = c.tensor(T, 48);
TensorRef y(&c.bk, T, 48);
c.bk.rmsnorm(x, w, 1e-5f, 48, y);
c.bk.rmsnorm(x, wg, 1e-5f, 16, x);
std::vector<float> out = c.read(y), o2 = c.read(x);
out.insert(out.end(), o2.begin(), o2.end());
c.bk.release(x);
return out;
});
run("layernorm", tol, [&](Ctx& c) {
WeightRef w(&c.bk, c.dense(WFmt::BF16, 1, 24)), b(&c.bk, c.dense(WFmt::BF16, 1, 24));
Tensor* x = c.tensor(T, 24);
c.bk.layernorm(x, w, b, 1e-5f, x);
std::vector<float> out = c.read(x);
c.bk.release(x);
return out;
});
run("axpy / mul_sigmoid / glu", tol, [&](Ctx& c) {
Tensor* g = c.tensor(T, 40, 2.0f);
Tensor* u = c.tensor(T, 40, 2.0f);
TensorRef y(&c.bk, T, 40), z(&c.bk, T, 40);
Act silu, situ;
situ.kind = ActKind::SITU;
situ.beta = 4.0f;
situ.lbeta = 25.0f;
c.bk.glu(g, u, silu, y);
c.bk.glu(g, u, situ, z);
c.bk.axpy(y, z, -0.5f);
c.bk.mul_sigmoid(y, g);
std::vector<float> out = c.read(y);
c.bk.release(g);
c.bk.release(u);
return out;
});
run("kda_conv (state carried)", tol, [&](Ctx& c) {
WeightRef w(&c.bk, c.dense(WFmt::BF16, 32, 4, 0.5f));
Tensor* p1 = c.tensor(T, 32);
Tensor* p2 = c.tensor(1, 32);
TensorRef ring(&c.bk, 3, 32), y1(&c.bk, T, 32), y2(&c.bk, 1, 32);
c.bk.kda_conv(p1, w, ring, y1);
c.bk.kda_conv(p2, w, ring, y2);
std::vector<float> out = c.read(y1), o2 = c.read(y2), o3 = c.read(ring);
out.insert(out.end(), o2.begin(), o2.end());
out.insert(out.end(), o3.begin(), o3.end());
c.bk.release(p1);
c.bk.release(p2);
return out;
});
for (bool bounded : {false, true}) {
run(bounded ? "kda_gate (bounded, K3)" : "kda_gate (softplus, Kimi-Linear)", tol, [&, bounded](Ctx& c) {
WeightRef a(&c.bk, c.dense(WFmt::F32, 1, 8, 0.3f)), b(&c.bk, c.dense(WFmt::F32, 1, 4 * 8, 0.5f));
Tensor* z = c.tensor(T, 32);
TensorRef g(&c.bk, T, 32);
c.bk.kda_gate(z, a, b, 4, bounded, -5.0f, g);
std::vector<float> out = c.read(g);
c.bk.release(z);
return out;
});
}
run("kda_recur (state carried)", tol, [&](Ctx& c) {
const int H = 3, D = 16;
std::vector<float> out;
TensorRef S(&c.bk, H * D, D);
for (int pass = 0; pass < 2; ++pass) {
const int n = pass == 0 ? T : 1;
Tensor* q = c.tensor(n, H * D);
Tensor* k = c.tensor(n, H * D);
Tensor* v = c.tensor(n, H * D);
Tensor* g = c.tensor(n, H * D, 0.5f);
Tensor* bl = c.tensor(n, H);
// decay gates must be <= 0: reuse the gate formula's sign convention
std::vector<float> gv = c.read(g);
for (auto& x : gv) x = -std::fabs(x);
c.bk.upload(g, 0, n, gv.data());
TensorRef o(&c.bk, n, H * D);
c.bk.kda_recur(q, k, v, g, bl, H, S, o);
std::vector<float> oo = c.read(o);
out.insert(out.end(), oo.begin(), oo.end());
for (Tensor* t : {q, k, v, g, bl}) c.bk.release(t);
}
std::vector<float> ss = c.read(S);
out.insert(out.end(), ss.begin(), ss.end());
return out;
});
for (bool sparse : {false, true}) {
run(sparse ? "mla_attend (sparse selection)" : "mla_attend (dense)", tol, [&, sparse](Ctx& c) {
MlaShape sh;
sh.heads = 3;
sh.nope = 8;
sh.rope = 4;
sh.vdim = 6;
sh.kv_rank = 16;
const int S = 11, nq = 4, pos0 = S - nq;
WeightRef kvb(&c.bk, c.dense(WFmt::BF16, sh.heads * (sh.nope + sh.vdim), sh.kv_rank, 0.3f));
Tensor* q = c.tensor(nq, sh.heads * (sh.nope + sh.rope));
Tensor* C = c.tensor(S + 3, sh.kv_rank);
Tensor* R = c.tensor(S + 3, sh.rope);
std::vector<uint8_t> sel((size_t)nq * S, 1);
if (sparse)
for (int t = 0; t < nq; ++t)
for (int s = 0; s < S; ++s) sel[(size_t)t * S + s] = (uint8_t)(((s * 7 + t) % 3) != 0 || s == pos0 + t);
TensorRef o(&c.bk, nq, sh.heads * sh.vdim);
c.bk.mla_attend(sh, q, kvb, C, R, S, pos0, sparse ? sel.data() : nullptr, o);
std::vector<float> out = c.read(o);
for (Tensor* t : {q, C, R}) c.bk.release(t);
return out;
});
}
run("dsa_scores", tol, [&](Ctx& c) {
const int H = 2, D = 8, S = 9, nq = 3;
Tensor* qi = c.tensor(nq, H * D);
Tensor* wh = c.tensor(nq, H);
Tensor* keys = c.tensor(S + 2, D);
TensorRef sc(&c.bk, nq, S);
c.bk.dsa_scores(qi, wh, keys, S, H, sc);
std::vector<float> out = c.read(sc);
for (Tensor* t : {qi, wh, keys}) c.bk.release(t);
return out;
});
run("attn_res (aliased output)", tol, [&](Ctx& c) {
WeightRef wn(&c.bk, c.dense(WFmt::BF16, 1, 32)), wp(&c.bk, c.dense(WFmt::BF16, 1, 32));
Tensor* ps = c.tensor(T, 32);
Tensor* b0 = c.tensor(T, 32);
Tensor* b1 = c.tensor(T, 32);
Tensor* blocks[2] = {b0, b1};
TensorRef y(&c.bk, T, 32);
c.bk.attn_res(ps, blocks, 2, wn, wp, 1e-5f, y);
c.bk.attn_res(ps, blocks, 1, wn, wp, 1e-5f, ps);
std::vector<float> out = c.read(y), o2 = c.read(ps);
out.insert(out.end(), o2.begin(), o2.end());
for (Tensor* t : {ps, b0, b1}) c.bk.release(t);
return out;
});
return rep;
}
} // namespace hk