Download tools/ref_forward.py from Ozomozyan/hkimi: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/Ozomozyan/hkimi/resolve/main/tools/ref_forward.py
- Command line
-
hf download hf://Ozomozyan/hkimi/tools/ref_forward.py
-
curl -L -o ref_forward.py https://huggingface.co/Ozomozyan/hkimi/resolve/main/tools/ref_forward.py
17.3 kB
| #!/usr/bin/env python3 | |
| """Reference forward pass in plain NumPy (float64), straight off a checkpoint directory. | |
| This is the oracle the C++ engine is tested against. It is written to be read, | |
| not to be fast, and deliberately takes a different route from the engine where | |
| it can (attention is expanded per head here, the engine works in latent form), | |
| so an agreement between the two means something. | |
| The math follows the released reference code: | |
| - modeling_kimi_linear.py of the Kimi-Linear / Kimi K3 release (via WARP's | |
| tools/kimi_ref.py, which was checked against it end to end) | |
| - fla.ops.kda.naive.naive_recurrent_kda for the KDA recurrence | |
| - the DeepSeek-V3.2-style indexer for K3.1's sparse attention (as implemented | |
| by vLLM and SGLang; Moonshot ships no modeling code for K3.1) | |
| python tools/ref_forward.py MODEL_DIR --tokens 1,2,3 --out logits.bin | |
| MODEL_DIR is a checkpoint (config.json and safetensors shards) or a store made | |
| by `hkimi convert`. Tensors are read lazily, so it also runs on real weights: | |
| - Kimi-Linear 48B, whole model, a few tokens (a few minutes, a few GB of RAM). | |
| On the store, the result must equal `hkimi sweep --dump-logits` closely | |
| (same weights, two implementations). On the original checkpoint it must | |
| be close to Hugging Face (tools/hf_logits.py): that one checks that this | |
| file understands the architecture. | |
| - Single layers of Kimi K3.1 Pro, from a few shards, on the hidden states | |
| that `hkimi layer-test --dump DIR` used: | |
| python tools/ref_forward.py MODEL_DIR --check-dump DIR | |
| which runs every layer found in DIR and compares it with the engine's output. One layer by | |
| hand: --layer 5 --hidden-in DIR/layer-5.in.bin --out ref5.bin, then tools/compare_logits.py. | |
| A real K3.1 layer takes a minute or two with 8 rows (each routed expert is decoded in NumPy). | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import numpy as np | |
| from hk_safetensors import Checkpoint, StoreFiles, mxfp4_dequant | |
| def sigmoid(x): | |
| return 1.0 / (1.0 + np.exp(-x)) | |
| def softplus(x): | |
| return np.logaddexp(0.0, x) | |
| def rms_norm(x, w, eps): | |
| return x / np.sqrt(np.mean(x * x, axis=-1, keepdims=True) + eps) * w | |
| def softmax(x, axis=-1): | |
| x = x - np.max(x, axis=axis, keepdims=True) | |
| e = np.exp(x) | |
| return e / np.sum(e, axis=axis, keepdims=True) | |
| class Ref: | |
| def __init__(self, model_dir): | |
| self.store = os.path.exists(os.path.join(model_dir, "manifest.json")) | |
| if self.store: | |
| self.ck = StoreFiles(model_dir) | |
| cfg = self.ck.config | |
| else: | |
| self.ck = Checkpoint(model_dir) | |
| cfg = json.load(open(os.path.join(model_dir, "config.json"))) | |
| self.nested = "text_config" in cfg | |
| self.c = cfg["text_config"] if self.nested else cfg | |
| self.p = "language_model." if self.nested else "" | |
| c = self.c | |
| self.eps = c["rms_norm_eps"] | |
| lac = c["linear_attn_config"] | |
| self.kda_set = set(lac["kda_layers"]) | |
| self.kh, self.kd, self.conv_k = lac["num_heads"], lac["head_dim"], lac["short_conv_kernel_size"] | |
| self.full_gate = lac.get("use_full_rank_gate", False) | |
| self.gate_lb = lac.get("gate_lower_bound") | |
| self.situ = c.get("hidden_act") == "situ" | |
| self.sb = c.get("activation_situ_beta") or 1.0 | |
| self.slb = c.get("activation_situ_linear_beta") | |
| self.ares = c.get("attn_res_block_size") | |
| self.latent = c.get("routed_expert_hidden_size") | |
| self.dsa = c.get("dsa_config") | |
| self.dsa_set = set(self.dsa["dsa_layers"]) if self.dsa else set() | |
| self.routes = [] # (layer, [per token: sorted expert ids]) for debugging | |
| def t(self, name): | |
| return self.ck.f64(self.p + name) | |
| def expert(self, L, e): | |
| if self.store: | |
| return self.ck.expert(L, e) # from the bit planes | |
| out = [] | |
| for tag in ("w1", "w3", "w2"): # gate, up, down | |
| base = f"{self.p}model.layers.{L}.block_sparse_moe.experts.{e}.{tag}" | |
| if self.ck.has(base + ".weight_packed"): | |
| packed, _ = self.ck.raw(base + ".weight_packed") | |
| scale, _ = self.ck.raw(base + ".weight_scale") | |
| out.append(mxfp4_dequant(packed, scale)) | |
| else: | |
| out.append(self.ck.f64(base + ".weight")) | |
| return out | |
| def act(self, g, u): | |
| if self.situ: | |
| a = self.sb * np.tanh(g / self.sb) * sigmoid(g) | |
| return a * (self.slb * np.tanh(u / self.slb) if self.slb else u) | |
| return g * sigmoid(g) * u | |
| # ---- Kimi Delta Attention ------------------------------------------------- | |
| def kda(self, L, x): | |
| a = f"model.layers.{L}.self_attn." | |
| T, H, D, K = x.shape[0], self.kh, self.kd, self.conv_k | |
| qkv = [] | |
| for n in "qkv": | |
| proj = x @ self.t(a + n + "_proj.weight").T # [T, H*D] | |
| w = self.t(a + n + "_conv1d.weight").reshape(H * D, K) # [C, K] | |
| seq = np.concatenate([np.zeros((K - 1, H * D)), proj], 0) # causal: zero history | |
| y = np.stack([(seq[t:t + K] * w.T).sum(0) for t in range(T)]) | |
| qkv.append((y * sigmoid(y)).reshape(T, H, D)) # SiLU | |
| q, k, v = qkv | |
| z = (x @ self.t(a + "f_a_proj.weight").T) @ self.t(a + "f_b_proj.weight").T | |
| z = z.reshape(T, H, D) + self.t(a + "dt_bias").reshape(H, D) | |
| A = np.exp(self.t(a + "A_log").reshape(-1)[:H]).reshape(H, 1) # one scale per head | |
| g = self.gate_lb * sigmoid(A * z) if self.gate_lb is not None else -A * softplus(z) | |
| beta = sigmoid(x @ self.t(a + "b_proj.weight").T) # [T, H] | |
| qn = q / np.maximum(np.linalg.norm(q, axis=-1, keepdims=True), 1e-12) * D ** -0.5 | |
| kn = k / np.maximum(np.linalg.norm(k, axis=-1, keepdims=True), 1e-12) | |
| S = np.zeros((H, D, D)) | |
| o = np.zeros((T, H, D)) | |
| for t in range(T): | |
| S = S * np.exp(g[t])[:, :, None] # decay rows (key axis) | |
| err = v[t] - np.einsum("hk,hkv->hv", kn[t], S) # v - S^T k | |
| S = S + np.einsum("hk,hv->hkv", beta[t][:, None] * kn[t], err) | |
| o[t] = np.einsum("hk,hkv->hv", qn[t], S) | |
| if self.full_gate: | |
| gate = x @ self.t(a + "g_proj.weight").T | |
| else: | |
| gate = (x @ self.t(a + "g_a_proj.weight").T) @ self.t(a + "g_b_proj.weight").T | |
| o = rms_norm(o, self.t(a + "o_norm.weight"), self.eps) * sigmoid(gate.reshape(T, H, D)) | |
| return o.reshape(T, H * D) @ self.t(a + "o_proj.weight").T | |
| # ---- full attention (MLA), expanded per head ------------------------------ | |
| def mla(self, L, x): | |
| a = f"model.layers.{L}.self_attn." | |
| c, T = self.c, x.shape[0] | |
| nh, n, r, vh, kr = c["num_attention_heads"], c["qk_nope_head_dim"], c["qk_rope_head_dim"], c["v_head_dim"], c["kv_lora_rank"] | |
| qd = n + r | |
| qa = None | |
| if c.get("q_lora_rank"): | |
| qa = rms_norm(x @ self.t(a + "q_a_proj.weight").T, self.t(a + "q_a_layernorm.weight"), self.eps) | |
| q = (qa @ self.t(a + "q_b_proj.weight").T).reshape(T, nh, qd) | |
| else: | |
| q = (x @ self.t(a + "q_proj.weight").T).reshape(T, nh, qd) | |
| ckv = x @ self.t(a + "kv_a_proj_with_mqa.weight").T | |
| kpass = rms_norm(ckv[:, :kr], self.t(a + "kv_a_layernorm.weight"), self.eps) | |
| krot = ckv[:, kr:] | |
| kb = (kpass @ self.t(a + "kv_b_proj.weight").T).reshape(T, nh, n + vh) | |
| knope, val = kb[:, :, :n], kb[:, :, n:] | |
| k = np.concatenate([knope, np.broadcast_to(krot[:, None, :], (T, nh, r))], -1) # NoPE: no rotation | |
| att = np.einsum("thd,shd->hts", q, k) * qd ** -0.5 | |
| mask = np.triu(np.full((T, T), -np.inf), 1) | |
| if (L + 1) in self.dsa_set and T > self.dsa["index_topk"]: | |
| mask = mask + self.dsa_mask(L, x, qa) | |
| att = softmax(att + mask[None], -1) | |
| o = np.einsum("hts,shd->thd", att, val).reshape(T, nh * vh) | |
| if c.get("mla_use_output_gate"): | |
| o = o * sigmoid(x @ self.t(a + "g_proj.weight").T) | |
| return o @ self.t(a + "o_proj.weight").T | |
| def dsa_mask(self, L, x, qa): | |
| """0 where a query may attend, -inf elsewhere: its index_topk best causal keys.""" | |
| a = f"model.layers.{L}.self_attn.indexer." | |
| T = x.shape[0] | |
| ih, idim, topk = self.dsa["index_num_heads"], self.dsa["index_head_dim"], self.dsa["index_topk"] | |
| key = x @ self.t(a + "wk.weight").T | |
| mu = key.mean(-1, keepdims=True) | |
| var = ((key - mu) ** 2).mean(-1, keepdims=True) | |
| key = (key - mu) / np.sqrt(var + self.eps) * self.t(a + "k_norm.weight") + self.t(a + "k_norm.bias") | |
| q = (qa @ self.t(a + "wq_b.weight").T).reshape(T, ih, idim) | |
| w = x @ self.t(a + "weights_proj.weight").T | |
| score = np.einsum("th,ths->ts", w, np.maximum(np.einsum("thd,sd->ths", q, key), 0.0)) | |
| mask = np.full((T, T), -np.inf) | |
| for t in range(T): | |
| vis = t + 1 | |
| if vis <= topk: | |
| mask[t, :vis] = 0.0 | |
| else: | |
| order = sorted(range(vis), key=lambda s: (-score[t, s], -s)) # ties: the more recent token | |
| mask[t, order[:topk]] = 0.0 | |
| return mask | |
| # ---- feed-forward ---------------------------------------------------------- | |
| def moe(self, L, x): | |
| m = f"model.layers.{L}.block_sparse_moe." | |
| c, T = self.c, x.shape[0] | |
| scores = sigmoid(x @ self.t(m + "gate.weight").T) | |
| choice = scores + self.t(m + "gate.e_score_correction_bias")[None] | |
| k = c["num_experts_per_token"] | |
| xin = x @ self.t(m + "routed_expert_down_proj.weight").T if self.latent else x | |
| y = np.zeros_like(xin) | |
| route, users = [], {} # users: expert -> [(token, weight)] | |
| for t in range(T): | |
| idx = sorted(sorted(range(scores.shape[1]), key=lambda e: (-choice[t, e], e))[:k]) | |
| route.append(idx) | |
| w = scores[t, idx] | |
| if c.get("moe_renormalize", True): | |
| w = w / (w.sum() + 1e-20) | |
| w = w * c["routed_scaling_factor"] | |
| for j, e in enumerate(idx): | |
| users.setdefault(e, []).append((t, w[j])) | |
| for e in sorted(users): # one expert in memory at a time: a real one is hundreds of MB as float64 | |
| G, U, Dn = self.expert(L, e) | |
| for t, w in users[e]: | |
| y[t] += w * (self.act(xin[t] @ G.T, xin[t] @ U.T) @ Dn.T) | |
| self.routes.append((L, route)) | |
| if self.latent: | |
| if c.get("latent_moe_use_norm"): | |
| y = rms_norm(y, self.t(m + "routed_expert_norm.weight"), self.eps) | |
| y = y @ self.t(m + "routed_expert_up_proj.weight").T | |
| sg, su, sd = (self.t(m + f"shared_experts.{n}_proj.weight") for n in ("gate", "up", "down")) | |
| return y + self.act(x @ sg.T, x @ su.T) @ sd.T | |
| def dense(self, L, x): | |
| m = f"model.layers.{L}.mlp." | |
| return self.act(x @ self.t(m + "gate_proj.weight").T, x @ self.t(m + "up_proj.weight").T) @ self.t(m + "down_proj.weight").T | |
| def attn_res(self, ps, blocks, norm_w, proj_w): | |
| v = np.stack(blocks + [ps], -2) # [T, nb+1, d] | |
| key = v / np.sqrt(np.mean(v * v, -1, keepdims=True) + self.eps) | |
| a = softmax((key * (norm_w * proj_w.reshape(-1))).sum(-1), -1) | |
| return (a[..., None] * v).sum(-2) | |
| def layer(self, L, x, blocks): | |
| """One layer on its input x [T, d]. blocks: the attention-residual history, extended when L starts a block.""" | |
| pre = f"model.layers.{L}." | |
| ps = None | |
| if self.ares: | |
| ps = x | |
| if blocks: | |
| x = self.attn_res(ps, blocks, self.t(pre + "self_attention_res_norm.weight"), self.t(pre + "self_attention_res_proj.weight")) | |
| if L % self.ares == 0: | |
| blocks.append(ps) | |
| ps = None | |
| h = rms_norm(x, self.t(pre + "input_layernorm.weight"), self.eps) | |
| att = self.kda(L, h) if (L + 1) in self.kda_set else self.mla(L, h) | |
| if self.ares: | |
| ps = att if ps is None else ps + att | |
| x = self.attn_res(ps, blocks, self.t(pre + "mlp_res_norm.weight"), self.t(pre + "mlp_res_proj.weight")) | |
| else: | |
| x = x + att | |
| h = rms_norm(x, self.t(pre + "post_attention_layernorm.weight"), self.eps) | |
| ffn = self.moe(L, h) if self.ck.has(self.p + pre + "block_sparse_moe.gate.weight") else self.dense(L, h) | |
| return (ps + ffn) if self.ares else (x + ffn) | |
| def forward(self, ids, hidden=None): | |
| c = self.c | |
| x = self.ck.f64(self.p + "model.embed_tokens.weight", rows=[int(i) for i in ids]) | |
| blocks = [] | |
| for L in range(c["num_hidden_layers"]): | |
| x = self.layer(L, x, blocks) | |
| if hidden is not None: | |
| hidden.append(x.copy()) | |
| if self.ares and blocks: | |
| x = self.attn_res(x, blocks, self.t("model.output_attn_res_norm.weight"), self.t("model.output_attn_res_proj.weight")) | |
| x = rms_norm(x, self.t("model.norm.weight"), self.eps) | |
| # The head a slice at a time: the real one is several GB as float64. | |
| vocab = c["vocab_size"] | |
| logits = np.empty((x.shape[0], vocab)) | |
| for r in range(0, vocab, 16384): | |
| logits[:, r:r + 16384] = x @ self.ck.f64(self.p + "lm_head.weight", rows=slice(r, r + 16384)).T | |
| return logits | |
| def layer_alone(self, L, x): | |
| """Layer L on hidden states x [T, d], the way `hkimi layer-test` runs it. | |
| With attention residuals a layer also reads the outputs of earlier blocks. They are not | |
| there when a layer runs alone, so both sides use the same stand-ins: scaled copies of x. | |
| """ | |
| blocks = [] | |
| if self.ares and L > 0: | |
| blocks = [x * (0.5 + 0.25 * b) for b in range((L + self.ares - 1) // self.ares)] | |
| return self.layer(L, x, blocks) | |
| def check_dump(ref, dump_dir, rtol=1e-3, out=print): | |
| """Compares every layer-N.in.bin / layer-N.out.bin pair written by `hkimi layer-test --dump` with this | |
| reference. Returns the number of layers that differ by more than rtol (relative, over the whole output).""" | |
| d = ref.c["hidden_size"] | |
| layers = sorted(int(m.group(1)) for m in (re.match(r"layer-(\d+)\.in\.bin$", n) for n in os.listdir(dump_dir)) if m) | |
| if not layers: | |
| out("no layer-N.in.bin files in %s (make them with: hkimi layer-test <store> --dump %s)" % (dump_dir, dump_dir)) | |
| return 1 | |
| bad = 0 | |
| for L in layers: | |
| x = np.fromfile(os.path.join(dump_dir, "layer-%d.in.bin" % L), dtype=np.float32).reshape(-1, d).astype(np.float64) | |
| y = np.fromfile(os.path.join(dump_dir, "layer-%d.out.bin" % L), dtype=np.float32).reshape(-1, d).astype(np.float64) | |
| r = ref.layer_alone(L, x) | |
| rel = float(np.linalg.norm(y - r) / max(np.linalg.norm(r), 1e-30)) | |
| ok = y.shape == r.shape and rel <= rtol | |
| bad += 0 if ok else 1 | |
| out("layer %3d: %d rows, engine against the NumPy reference: relative difference %.1e %s" % (L, x.shape[0], rel, "ok" if ok else "FAIL")) | |
| return bad | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("model_dir", help="a checkpoint directory or a store") | |
| ap.add_argument("--tokens", help="token ids: the whole model is run on them and the logits are written") | |
| ap.add_argument("--layer", type=int, help="run this layer alone, on --hidden-in") | |
| ap.add_argument("--hidden-in", help="float32 [T, hidden], e.g. layer-N.in.bin from `hkimi layer-test --dump`") | |
| ap.add_argument("--out", help="float32 file: logits [T, vocab], or with --layer the layer's output [T, hidden]") | |
| ap.add_argument("--check-dump", metavar="DIR", help="compare every layer dumped by `hkimi layer-test --dump DIR`") | |
| ap.add_argument("--rtol", type=float, default=1e-3, help="largest relative difference --check-dump accepts") | |
| a = ap.parse_args() | |
| ref = Ref(a.model_dir) | |
| if a.check_dump: | |
| sys.exit(1 if check_dump(ref, a.check_dump, a.rtol) else 0) | |
| if a.layer is not None: | |
| if not a.hidden_in: | |
| ap.error("--layer needs --hidden-in") | |
| x = np.fromfile(a.hidden_in, dtype=np.float32).reshape(-1, ref.c["hidden_size"]).astype(np.float64) | |
| y = ref.layer_alone(a.layer, x) | |
| if a.out: | |
| y.astype(np.float32).tofile(a.out) | |
| print(f"layer {a.layer}: {x.shape[0]} rows, input rms {np.sqrt(np.mean(x * x)):.4f}, output rms {np.sqrt(np.mean(y * y)):.4f}") | |
| else: | |
| if not a.tokens: | |
| ap.error("give --tokens, --check-dump DIR, or --layer with --hidden-in") | |
| ids = [int(t) for t in a.tokens.replace(",", " ").split()] | |
| logits = ref.forward(ids) | |
| if a.out: | |
| logits.astype(np.float32).tofile(a.out) | |
| for i, row in enumerate(logits): | |
| top = np.argsort(-row)[:3] | |
| print(f"pos {i:4d} tok {ids[i]:6d} -> top " + " ".join(f"{t}({row[t] - np.log(np.exp(row - row.max()).sum()) - row.max():.3f})" for t in top)) | |