hkimi / src /model /layers.cpp
Ozomozyan's picture
hkimi 0.1.0
68888be verified
Raw History Blame Contribute Delete
13.9 kB
#include "model/layers.h"
#include <algorithm>
#include <cmath>
#include <numeric>
#include "common/base.h"
#include "common/numeric.h"
namespace hk {
void apply_lin(Backend& bk, const Lin& l, const Tensor* X, Tensor* Y, LinHook* hook) {
bk.linear(l.w, X, Y);
if (hook && l.name) hook->on_linear(*l.name, X, Y);
}
void KdaState::init(Backend& bk, const ModelConfig& c) {
const int HD = c.kda_heads * c.kda_dim;
S = TensorRef(&bk, HD, c.kda_dim);
for (int i = 0; i < 3; ++i) ring[i] = TensorRef(&bk, c.conv_k - 1, HD);
}
void MlaState::reserve(Backend& bk, const ModelConfig& c, bool dsa, int need) {
if (need <= cap) return;
int ncap = std::max(need, std::max(64, cap * 2));
TensorRef nc(&bk, ncap, c.kv_lora), nr(&bk, ncap, c.rope), nk;
if (dsa) nk = TensorRef(&bk, ncap, c.idx_dim);
if (len > 0) {
bk.copy(nc, 0, 0, C, 0, 0, len, c.kv_lora);
bk.copy(nr, 0, 0, R, 0, 0, len, c.rope);
if (dsa) bk.copy(nk, 0, 0, keys, 0, 0, len, c.idx_dim);
}
C = std::move(nc);
R = std::move(nr);
keys = std::move(nk);
cap = ncap;
}
void KdaTail::truncate(int n, int HD, int H) {
HK_CHECK(n >= 0 && n <= rows, "internal: a KDA tail of %d positions cannot be cut to %d", rows, n);
rows = n;
for (std::vector<float>* v : {&pq, &pk, &pv, &g}) v->resize((size_t)n * (size_t)HD);
bl.resize((size_t)n * (size_t)H);
}
namespace {
// rows of a device tensor, appended to a host vector
void keep_rows(Backend& bk, const Tensor* t, std::vector<float>& dst) {
const size_t at = dst.size();
dst.resize(at + (size_t)t->rows * (size_t)t->cols);
if (t->rows > 0) bk.download(t, 0, t->rows, dst.data() + at);
}
} // namespace
void kda_forward(Backend& bk, const ModelConfig& c, const KdaW& w, const Tensor* h, KdaState& st, Tensor* out, LinHook* hook,
KdaTail* keep) {
const int T = h->rows, H = c.kda_heads, HD = H * c.kda_dim;
// q, k, v: projection, short causal convolution over time, SiLU
TensorRef p(&bk, T, HD), q(&bk, T, HD), k(&bk, T, HD), v(&bk, T, HD);
apply_lin(bk, w.q, h, p, hook);
if (keep) keep_rows(bk, p, keep->pq);
bk.kda_conv(p, w.qc, st.ring[0], q);
apply_lin(bk, w.k, h, p, hook);
if (keep) keep_rows(bk, p, keep->pk);
bk.kda_conv(p, w.kc, st.ring[1], k);
apply_lin(bk, w.v, h, p, hook);
if (keep) keep_rows(bk, p, keep->pv);
bk.kda_conv(p, w.vc, st.ring[2], v);
// per-channel decay gate through a low-rank bottleneck
TensorRef fa(&bk, T, w.f_a.w->desc.rows), z(&bk, T, HD), g(&bk, T, HD);
apply_lin(bk, w.f_a, h, fa, hook);
apply_lin(bk, w.f_b, fa, z, hook);
bk.kda_gate(z, w.A_log, w.dt_bias, H, c.kda_bounded, c.kda_lower_bound, g);
// per-head write strength (the sigmoid is applied inside the recurrence)
TensorRef bl(&bk, T, H);
apply_lin(bk, w.b, h, bl, hook);
if (keep) {
keep_rows(bk, g, keep->g);
keep_rows(bk, bl, keep->bl);
keep->rows += T;
}
TensorRef o(&bk, T, HD);
bk.kda_recur(q, k, v, g, bl, H, st.S, o);
// output: per-head RMSNorm, sigmoid gate, projection
TensorRef gate(&bk, T, HD);
if (w.g) {
apply_lin(bk, w.g, h, gate, hook);
} else {
TensorRef ga(&bk, T, w.g_a.w->desc.rows);
apply_lin(bk, w.g_a, h, ga, hook);
apply_lin(bk, w.g_b, ga, gate, hook);
}
bk.rmsnorm(o, w.o_norm, c.rms_eps, c.kda_dim, o);
bk.mul_sigmoid(o, gate);
apply_lin(bk, w.o, o, out, hook);
}
void kda_replay(Backend& bk, const ModelConfig& c, const KdaW& w, const KdaTail& tail, int rows, KdaState& st) {
if (rows <= 0) return;
const int H = c.kda_heads, HD = H * c.kda_dim;
HK_CHECK(rows <= tail.rows && tail.pq.size() >= (size_t)rows * (size_t)HD && tail.bl.size() >= (size_t)rows * (size_t)H,
"internal: a KDA tail of %d positions cannot be replayed over %d", tail.rows, rows);
TensorRef p(&bk, rows, HD), q(&bk, rows, HD), k(&bk, rows, HD), v(&bk, rows, HD), g(&bk, rows, HD), bl(&bk, rows, H),
o(&bk, rows, HD);
bk.upload(p, 0, rows, tail.pq.data());
bk.kda_conv(p, w.qc, st.ring[0], q);
bk.upload(p, 0, rows, tail.pk.data());
bk.kda_conv(p, w.kc, st.ring[1], k);
bk.upload(p, 0, rows, tail.pv.data());
bk.kda_conv(p, w.vc, st.ring[2], v);
bk.upload(g, 0, rows, tail.g.data());
bk.upload(bl, 0, rows, tail.bl.data());
bk.kda_recur(q, k, v, g, bl, H, st.S, o); // o, what these positions read from the memory, is not needed again
}
void dsa_select(const float* scores, int T, int S, int pos0, int topk, std::vector<uint8_t>& sel) {
sel.assign((size_t)T * (size_t)S, 0);
std::vector<int> order;
for (int t = 0; t < T; ++t) {
const int visible = pos0 + t + 1; // keys 0..pos0+t
uint8_t* m = sel.data() + (size_t)t * (size_t)S;
if (visible <= topk) { // short context: every visible key, i.e. dense attention
std::fill(m, m + visible, (uint8_t)1);
continue;
}
const float* sc = scores + (size_t)t * (size_t)S;
order.resize((size_t)visible);
std::iota(order.begin(), order.end(), 0);
// highest score first; ties go to the more recent token
std::nth_element(order.begin(), order.begin() + topk, order.end(),
[&](int a, int b) { return sc[a] != sc[b] ? sc[a] > sc[b] : a > b; });
for (int i = 0; i < topk; ++i) m[order[(size_t)i]] = 1;
}
}
void mla_forward(Backend& bk, const ModelConfig& c, const MlaW& w, bool dsa, const Tensor* h, MlaState& st, Tensor* out,
LinHook* hook) {
const int T = h->rows, H = c.heads, qd = c.qdim();
const int pos0 = st.len;
st.reserve(bk, c, dsa, pos0 + T);
// queries, optionally through the low-rank q_a / q_b factorization
TensorRef q(&bk, T, H * qd), qa;
if (c.q_lora > 0) {
qa = TensorRef(&bk, T, c.q_lora);
apply_lin(bk, w.q_a, h, qa, hook);
bk.rmsnorm(qa, w.q_a_norm, c.rms_eps, c.q_lora, qa);
apply_lin(bk, w.q_b, qa, q, hook);
} else {
apply_lin(bk, w.q, h, q, hook);
}
// Compressed key/value latent: the first kv_lora columns are normalized and cached,
// the last `rope` columns are the positional slice shared by all heads (NoPE: no rotation).
TensorRef ckv(&bk, T, c.kv_lora + c.rope), lat(&bk, T, c.kv_lora);
apply_lin(bk, w.kv_a, h, ckv, hook);
bk.copy(lat, 0, 0, ckv, 0, 0, T, c.kv_lora);
bk.rmsnorm(lat, w.kv_a_norm, c.rms_eps, c.kv_lora, lat);
bk.copy(st.C, pos0, 0, lat, 0, 0, T, c.kv_lora);
bk.copy(st.R, pos0, 0, ckv, 0, c.kv_lora, T, c.rope);
st.len = pos0 + T;
const int S = st.len;
std::vector<uint8_t> sel;
const uint8_t* selp = nullptr;
if (dsa) {
// indexer key of each new token (LayerNorm, with bias), cached like the latents
TensorRef key(&bk, T, c.idx_dim);
apply_lin(bk, w.idx_k, h, key, hook);
bk.layernorm(key, w.idx_norm_w, w.idx_norm_b, c.rms_eps, key);
bk.copy(st.keys, pos0, 0, key, 0, 0, T, c.idx_dim);
if (S > c.idx_topk) {
// Only now is attention sparse: each query keeps its idx_topk best keys. The constant
// factors of the reference (heads^-0.5 * dim^-0.5) do not change the ranking.
TensorRef qi(&bk, T, c.idx_heads * c.idx_dim), wh(&bk, T, c.idx_heads), sc(&bk, T, S);
apply_lin(bk, w.idx_q, qa, qi, hook);
apply_lin(bk, w.idx_w, h, wh, hook);
bk.dsa_scores(qi, wh, st.keys, S, c.idx_heads, sc);
std::vector<float> host((size_t)T * (size_t)S);
bk.download(sc, 0, T, host.data());
dsa_select(host.data(), T, S, pos0, c.idx_topk, sel);
selp = sel.data();
}
}
TensorRef o(&bk, T, H * c.vdim);
MlaShape sh;
sh.heads = H;
sh.nope = c.nope;
sh.rope = c.rope;
sh.vdim = c.vdim;
sh.kv_rank = c.kv_lora;
bk.mla_attend(sh, q, w.kv_b, st.C, st.R, S, pos0, selp, o);
if (w.g) {
TensorRef gate(&bk, T, H * c.vdim);
apply_lin(bk, w.g, h, gate, hook);
bk.mul_sigmoid(o, gate);
}
apply_lin(bk, w.o, o, out, hook);
}
void moe_route(const ModelConfig& c, const float* logits, const float* bias, int T, Routing& out) {
const int E = c.n_experts, k = c.top_k;
out.T = T;
out.k = k;
out.idx.resize((size_t)T * (size_t)k);
out.w.resize((size_t)T * (size_t)k);
std::vector<float> score((size_t)E), choice((size_t)E);
std::vector<int> order((size_t)E);
for (int t = 0; t < T; ++t) {
const float* lg = logits + (size_t)t * (size_t)E;
for (int e = 0; e < E; ++e) {
score[(size_t)e] = sigmoidf(lg[e]);
// the correction bias only decides which experts are picked, not their weights
choice[(size_t)e] = score[(size_t)e] + bias[e];
}
std::iota(order.begin(), order.end(), 0);
std::partial_sort(order.begin(), order.begin() + k, order.end(), [&](int a, int b) {
return choice[(size_t)a] != choice[(size_t)b] ? choice[(size_t)a] > choice[(size_t)b] : a < b;
});
std::sort(order.begin(), order.begin() + k);
double sum = 0;
for (int j = 0; j < k; ++j) sum += score[(size_t)order[(size_t)j]];
for (int j = 0; j < k; ++j) {
float wj = score[(size_t)order[(size_t)j]];
if (c.moe_renorm) wj = (float)(wj / (sum + 1e-20));
out.idx[(size_t)t * k + j] = order[(size_t)j];
out.w[(size_t)t * k + j] = wj * c.routed_scale;
}
}
}
void ffn_forward(Backend& bk, const Act& act, const Lin& gate, const Lin& up, const Lin& down, const Tensor* h, Tensor* out,
LinHook* hook) {
const int T = h->rows, n = gate.w->desc.rows;
TensorRef g(&bk, T, n), u(&bk, T, n);
apply_lin(bk, gate, h, g, hook);
apply_lin(bk, up, h, u, hook);
bk.glu(g, u, act, g);
apply_lin(bk, down, g, out, hook);
}
void expert_forward(Backend& bk, const Act& act, const Weight* gate, const Weight* up, const Weight* down, const Tensor* Xc,
Tensor* Yc) {
const int n = Xc->rows, inter = gate->desc.rows;
TensorRef g(&bk, n, inter), u(&bk, n, inter);
bk.linear(gate, Xc, g);
bk.linear(up, Xc, u);
bk.glu(g, u, act, g);
bk.linear(down, g, Yc);
}
void layer_pre(Backend& bk, const ModelConfig& c, const LayerW& w, Tensor* x, std::vector<Tensor*>& blocks, KdaState* kda,
MlaState* mla, PreOut& out, LinHook* hook, KdaTail* keep) {
const int T = x->rows, d = c.hidden, L = w.layer;
const float eps = c.rms_eps;
TensorRef ps, mixed;
const Tensor* att_in = x;
if (c.ares_block) {
// Running sum of this block so far. At a block's first layer it is the previous
// block's output (or the embedding) and becomes a stored block itself.
ps = TensorRef(&bk, T, d);
bk.copy(ps, 0, 0, x, 0, 0, T, d);
if (!blocks.empty()) {
mixed = TensorRef(&bk, T, d);
bk.attn_res(ps, blocks.data(), (int)blocks.size(), w.ar_attn_norm, w.ar_attn_proj, eps, mixed);
att_in = mixed;
}
if (L % c.ares_block == 0) blocks.push_back(ps.detach());
}
TensorRef h(&bk, T, d), att(&bk, T, d);
bk.rmsnorm(att_in, w.in_norm, eps, d, h);
if (w.kda) {
HK_CHECK(kda != nullptr, "layer %d is KDA but no KDA state was given", L);
kda_forward(bk, c, w.kdaw, h, *kda, att, hook, keep);
} else {
HK_CHECK(mla != nullptr, "layer %d is full attention but no cache was given", L);
mla_forward(bk, c, w.mlaw, c.is_dsa(L), h, *mla, att, hook);
}
TensorRef xmid(&bk, T, d);
if (c.ares_block) {
if (!ps) ps = std::move(att);
else bk.axpy(ps, att, 1.0f);
bk.attn_res(ps, blocks.data(), (int)blocks.size(), w.ar_mlp_norm, w.ar_mlp_proj, eps, xmid);
} else {
bk.copy(xmid, 0, 0, x, 0, 0, T, d);
bk.axpy(xmid, att, 1.0f);
}
out.h2 = TensorRef(&bk, T, d);
bk.rmsnorm(xmid, w.post_norm, eps, d, out.h2);
out.res = c.ares_block ? std::move(ps) : std::move(xmid);
if (w.moe) {
out.logits = TensorRef(&bk, T, c.n_experts);
apply_lin(bk, w.moew.gate, out.h2, out.logits, hook);
if (c.latent > 0) {
out.xlat = TensorRef(&bk, T, c.latent);
apply_lin(bk, w.moew.down, out.h2, out.xlat, hook);
}
out.done = false;
} else {
TensorRef f(&bk, T, d);
ffn_forward(bk, act_of(c), w.mlp_gate, w.mlp_up, w.mlp_down, out.h2, f, hook);
bk.copy(x, 0, 0, out.res, 0, 0, T, d);
bk.axpy(x, f, 1.0f);
out.done = true;
}
}
void layer_post(Backend& bk, const ModelConfig& c, const LayerW& w, const Tensor* h2, const Tensor* res, Tensor* ylat,
Tensor* x, LinHook* hook) {
const int T = h2->rows, d = c.hidden;
TensorRef y(&bk, T, d);
if (c.latent > 0) {
if (c.latent_norm) bk.rmsnorm(ylat, w.moew.latent_norm, c.rms_eps, c.latent, ylat);
apply_lin(bk, w.moew.up, ylat, y, hook);
} else {
bk.copy(y, 0, 0, ylat, 0, 0, T, d);
}
if (c.n_shared > 0) {
// shared experts always run, on the full-width hidden state
TensorRef s(&bk, T, d);
ffn_forward(bk, act_of(c), w.moew.sh_gate, w.moew.sh_up, w.moew.sh_down, h2, s, hook);
bk.axpy(y, s, 1.0f);
}
bk.copy(x, 0, 0, res, 0, 0, T, d);
bk.axpy(x, y, 1.0f);
}
void head_norm(Backend& bk, const ModelConfig& c, const HeadW& w, Tensor* x, std::vector<Tensor*>& blocks, Tensor* out) {
if (c.ares_block && !blocks.empty())
bk.attn_res(x, blocks.data(), (int)blocks.size(), w.ar_norm, w.ar_proj, c.rms_eps, x);
bk.rmsnorm(x, w.norm, c.rms_eps, c.hidden, out);
}
} // namespace hk