Trinity / tools /k3ref.py
STAR-future's picture
Trinity: public release (history squashed)
f80e81a
Raw History Blame
14.3 kB
"""Reference forward pass of the Kimi K3.1 text decoder (and LittleBoy), in plain PyTorch, one layer at a time.
Written from the vLLM implementation (vllm/models/kimi_k3/nvidia: model.py, kda.py, mla.py, ops/attn_res.py,
ops/third_party/kda/fused_recurrent.py, layers/activation.py SituAndMul) so that the 2 TB checkpoint can be run
layer by layer on a single GPU, streaming one shard at a time. It is a correctness reference, not a fast kernel:
- KDA layers: per-token gated delta rule, fp32 state, l2-normalised q/k, sigmoid-bounded log-decay gate;
- MLA layers: NoPE multi-head latent attention with a sigmoid output gate. They are DSA layers in the checkpoint,
but for sequences of at most index_topk (2048) tokens the indexer keeps every key, so dense causal attention is
exact there. `forward_layer` refuses longer sequences;
- block attention residuals (attn_res, block size 12) carried as (delta, prefix, blocks);
- latent MoE: sigmoid router + selection bias, renormalised top-16, routed experts in a 3584-d latent space,
RMSNorm on the routed sum, up-projection, plus 2 shared experts; SITU activation (beta 4, linear beta 25).
`mask_new=True` excludes experts >= 896 from selection, which reproduces the base model exactly on LittleBoy weights.
"""
from __future__ import annotations
import math
import torch
import torch.nn.functional as F
E0 = 896
E2M1 = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0])
class Cfg:
def __init__(self, tc: dict):
self.hidden = tc["hidden_size"]
self.eps = tc["rms_norm_eps"]
self.n_layers = tc["num_hidden_layers"]
self.block = tc["attn_res_block_size"]
self.situ_beta = tc["activation_situ_beta"]
self.situ_lin = tc["activation_situ_linear_beta"]
la = tc["linear_attn_config"]
self.kda_layers = {i - 1 for i in la["kda_layers"]} # config lists are 1-based
self.kda_heads, self.kda_dim = la["num_heads"], la["head_dim"]
self.gate_lb = la["gate_lower_bound"]
self.conv = la["short_conv_kernel_size"]
self.heads = tc["num_attention_heads"]
self.nope, self.rope, self.vdim = tc["qk_nope_head_dim"], tc["qk_rope_head_dim"], tc["v_head_dim"]
self.kv_rank = tc["kv_lora_rank"]
self.topk = tc["num_experts_per_token"]
self.first_dense = tc["first_k_dense_replace"]
self.index_topk = tc["dsa_config"]["index_topk"]
self.n_blocks = math.ceil(self.n_layers / self.block)
def rms(x: torch.Tensor, w: torch.Tensor | None, eps: float) -> torch.Tensor:
xf = x.float()
y = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps)
return (y * w.float() if w is not None else y).to(x.dtype)
def situ_mul(gate: torch.Tensor, up: torch.Tensor, beta: float, lin: float) -> torch.Tensor:
g, u = gate.float(), up.float()
g = beta * torch.tanh(g / beta) * torch.sigmoid(g)
u = lin * torch.tanh(u / lin)
return (g * u).to(gate.dtype)
def lin(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
return x @ w.t()
def dequant(packed: torch.Tensor, scale: torch.Tensor, dtype=torch.bfloat16) -> torch.Tensor:
"""MXFP4 (two E2M1 nibbles per byte, low first; one E8M0 scale per 32 values) -> dense."""
lut = E2M1.to(packed.device)
vals = torch.stack([lut[(packed & 0x0F).long()], lut[(packed >> 4).long()]], dim=-1).reshape(packed.shape[0], -1)
s = torch.exp2(scale.float() - 127.0).repeat_interleave(32, dim=1)
return (vals * s).to(dtype)
def attn_res(prefix, delta, blocks, norm_w, qk_w, out_w, n_blocks, write_idx, eps):
"""vllm ops/attn_res.py. prefix [N,D] is updated in place (bf16 rounding, as the kernel does)."""
if delta is not None:
prefix.copy_((prefix.float() + delta.float()).to(prefix.dtype))
if write_idx >= 0:
blocks[:, write_idx].copy_(prefix)
if n_blocks == 0:
mixed = prefix.float()
else:
src = torch.cat([blocks[:, :n_blocks], prefix[:, None]], dim=1).float() # [N, S, D]
w = (norm_w.float() * qk_w.float())
logits = (src * w).sum(-1) * torch.rsqrt(src.pow(2).mean(-1) + eps) # [N, S]
mixed = (torch.softmax(logits, dim=-1)[..., None] * src).sum(1)
if out_w is not None:
return (mixed * torch.rsqrt(mixed.pow(2).mean(-1, keepdim=True) + eps) * out_w.float()).to(prefix.dtype)
return mixed.to(prefix.dtype)
def causal_conv_silu(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
"""x [B,T,C], w [C,1,K] (fp32): depthwise causal conv, then SiLU."""
B, T, C = x.shape
K = w.shape[-1]
y = F.conv1d(F.pad(x.float().transpose(1, 2), (K - 1, 0)), w.float(), groups=C)
return F.silu(y).transpose(1, 2).to(x.dtype)
def kda(x: torch.Tensor, W: dict, c: Cfg) -> torch.Tensor:
B, T, D = x.shape
H, K = c.kda_heads, c.kda_dim
q = causal_conv_silu(lin(x, W["q_proj"]), W["q_conv1d"]).view(B, T, H, K).float()
k = causal_conv_silu(lin(x, W["k_proj"]), W["k_conv1d"]).view(B, T, H, K).float()
v = causal_conv_silu(lin(x, W["v_proj"]), W["v_conv1d"]).view(B, T, H, K).float()
g1 = lin(lin(x, W["f_a_proj"]), W["f_b_proj"]).view(B, T, H, K).float()
beta = torch.sigmoid(lin(x, W["b_proj"]).float()) # [B,T,H]
g2 = lin(x, W["g_proj"]).view(B, T, H, K)
q = q / torch.sqrt((q * q).sum(-1, keepdim=True) + 1e-6) * K ** -0.5
k = k / torch.sqrt((k * k).sum(-1, keepdim=True) + 1e-6)
a = torch.exp(W["A_log"].float()[:H]).view(1, 1, H, 1)
gate = c.gate_lb * torch.sigmoid(a * (g1 + W["dt_bias"].float().view(1, 1, H, K))) # log decay, in (lb, 0)
decay = torch.exp(gate)
S = torch.zeros(B, H, K, K, device=x.device, dtype=torch.float32) # [B,H,V,K]
out = torch.empty(B, T, H, K, device=x.device, dtype=torch.float32)
for t in range(T):
S.mul_(decay[:, t, :, None, :])
kt = k[:, t]
vt = (v[:, t] - torch.einsum("bhvk,bhk->bhv", S, kt)) * beta[:, t, :, None]
S.add_(vt[..., None] * kt[:, :, None, :])
out[:, t] = torch.einsum("bhvk,bhk->bhv", S, q[:, t])
o = out * torch.rsqrt(out.pow(2).mean(-1, keepdim=True) + 1e-5) * W["o_norm"].float()
o = (o * torch.sigmoid(g2.float())).to(x.dtype).reshape(B, T, H * K)
return lin(o, W["o_proj"])
def mla(x: torch.Tensor, W: dict, c: Cfg) -> torch.Tensor:
B, T, D = x.shape
H, dn, dr, dv = c.heads, c.nope, c.rope, c.vdim
if T > c.index_topk:
raise ValueError(f"dense MLA equals DSA only up to {c.index_topk} tokens, got {T}")
q = lin(rms(lin(x, W["q_a_proj"]), W["q_a_layernorm"], c.eps), W["q_b_proj"]).view(B, T, H, dn + dr)
kv = lin(x, W["kv_a_proj_with_mqa"])
kv_c, k_pe = kv.split([c.kv_rank, dr], dim=-1)
kvb = lin(rms(kv_c, W["kv_a_layernorm"], c.eps), W["kv_b_proj"]).view(B, T, H, dn + dv)
k_nope, v = kvb.split([dn, dv], dim=-1)
k = torch.cat([k_nope, k_pe[:, :, None, :].expand(B, T, H, dr)], dim=-1) # NoPE: no rotation
vp = F.pad(v, (0, dn + dr - dv)) # equal head dims let SDPA use a memory-efficient kernel
qt, kt, vt = q.transpose(1, 2), k.transpose(1, 2), vp.transpose(1, 2)
o = torch.empty(B, H, T, dv, device=x.device, dtype=x.dtype)
hg = 96 if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8 else 16
for b in range(B): # bounded memory where only the math kernel exists (bf16 on sm75)
for h0 in range(0, H, hg):
o[b:b + 1, h0:h0 + hg] = F.scaled_dot_product_attention(
qt[b:b + 1, h0:h0 + hg], kt[b:b + 1, h0:h0 + hg], vt[b:b + 1, h0:h0 + hg], is_causal=True,
scale=(dn + dr) ** -0.5)[..., :dv]
o = o.transpose(1, 2).reshape(B, T, H * dv)
o = o * torch.sigmoid(lin(x, W["g_proj"]))
return lin(o, W["o_proj"])
def dense_mlp(x, W, c, pre="mlp."):
return lin(situ_mul(lin(x, W[pre + "gate_proj"]), lin(x, W[pre + "up_proj"]), c.situ_beta, c.situ_lin),
W[pre + "down_proj"])
def moe(x: torch.Tensor, W: dict, c: Cfg, mask_new=False, stats: dict | None = None,
parts: dict | None = None) -> torch.Tensor:
"""mask_new: bool for all rows, or a bool tensor [N] (rows whose new experts are masked: the base model).
parts, if given, receives 'acc' (the routed latent sum before routed_expert_norm, fp32) and 'idx'."""
shp = x.shape
x = x.reshape(-1, shp[-1])
n_exp = W["gate"].shape[0]
scores = torch.sigmoid(x.float() @ W["gate"].float().t()) # [N, E]
sel_key = scores + W["e_score_correction_bias"].float()
if n_exp > E0:
if isinstance(mask_new, torch.Tensor):
sel_key[mask_new, E0:] = -float("inf")
elif mask_new:
sel_key[:, E0:] = -float("inf")
idx = sel_key.topk(c.topk, dim=-1).indices # [N, k]
wts = scores.gather(1, idx)
wts = wts / wts.sum(-1, keepdim=True)
xl = lin(x, W["routed_expert_down_proj"]) # [N, 3584]
acc = torch.zeros(x.shape[0], xl.shape[1], device=x.device, dtype=torch.float32)
flat_e, flat_w = idx.reshape(-1), wts.reshape(-1)
tok = torch.arange(x.shape[0], device=x.device).repeat_interleave(c.topk)
order = torch.argsort(flat_e)
flat_e, flat_w, tok = flat_e[order], flat_w[order], tok[order]
counts = torch.bincount(flat_e, minlength=n_exp).tolist()
start = 0
for e, n in enumerate(counts):
if n == 0:
continue
t, w = tok[start:start + n], flat_w[start:start + n]
start += n
ex = W["experts"](e) # (w1, w2, w3) dense
h = situ_mul(lin(xl[t], ex[0]), lin(xl[t], ex[2]), c.situ_beta, c.situ_lin)
acc.index_add_(0, t, lin(h, ex[1]).float() * w[:, None])
if stats is not None:
stats["new_share"] = stats.get("new_share", []) + [float((idx >= E0).float().mean())]
if parts is not None:
parts["acc"], parts["idx"] = acc, idx
return moe_tail(acc, x, W, c).reshape(shp)
def moe_tail(acc: torch.Tensor, x: torch.Tensor, W: dict, c: Cfg) -> torch.Tensor:
"""Routed latent sum -> norm -> up-projection, plus the shared experts on the MoE input. All BF16 weights."""
routed = lin(rms(acc.to(x.dtype), W["routed_expert_norm"], c.eps), W["routed_expert_up_proj"])
return routed + dense_mlp(x, W, c, pre="shared_experts.")
def attn_phase(L: int, W: dict, c: Cfg, state: dict) -> torch.Tensor:
"""Pre-attention mix, attention, post-attention mix; returns the MLP/MoE input [B*T, D] (prefix updated)."""
B, T = state["shape"]
D = c.hidden
prefix, blocks = state["prefix"], state["blocks"]
delta = None if state["delta"] is None else state["delta"].reshape(B * T, D)
write = L % c.block == 0
nb = math.ceil(L / c.block)
h = attn_res(prefix, delta, blocks, W["self_attention_res_norm"], W["self_attention_res_proj"][0],
W["input_layernorm"], nb, L // c.block if write else -1, c.eps)
a = (kda if L in c.kda_layers else mla)(h.view(B, T, D), W, c).reshape(B * T, D)
if write:
prefix.copy_(a)
a = None
return attn_res(prefix, a, blocks, W["mlp_res_norm"], W["mlp_res_proj"][0], W["post_attention_layernorm"],
nb + int(write), -1, c.eps)
def forward_layer(L: int, W: dict, c: Cfg, state: dict, mask_new: bool = False, stats: dict | None = None) -> dict:
"""state: {'delta': [B,T,D] or None, 'prefix': [B*T,D], 'blocks': [B*T,nb,D], 'shape': (B,T)}."""
B, T = state["shape"]
h = attn_phase(L, W, c, state).view(B, T, c.hidden)
out = dense_mlp(h, W, c) if L < c.first_dense else moe(h, W, c, mask_new=mask_new, stats=stats)
state["delta"] = out
return state
def final_mix_terms(blocks: torch.Tensor, Wf: dict, c: Cfg) -> tuple:
"""The block part of the output attn_res, which does not depend on the last layer's MLP output:
m = max block logit, A = sum exp(l_s - m) v_s, Z = sum exp(l_s - m) (fp32)."""
src = blocks[:, : c.n_blocks].float()
w = Wf["output_attn_res_norm"].float() * Wf["output_attn_res_proj"][0].float()
logits = (src * w).sum(-1) * torch.rsqrt(src.pow(2).mean(-1) + c.eps) # [N, nb]
m = logits.max(-1).values
e = torch.exp(logits - m[:, None])
return (e[..., None] * src).sum(1), e.sum(-1), m
def final_from_terms(prefix: torch.Tensor, delta: torch.Tensor, A, Z, m, Wf: dict, c: Cfg) -> torch.Tensor:
"""Equal to final_hidden(): output attn_res with the prefix updated by the last delta, then the final RMSNorm."""
p = (prefix.float() + delta.float()).to(prefix.dtype).float() # bf16 rounding as in attn_res
w = Wf["output_attn_res_norm"].float() * Wf["output_attn_res_proj"][0].float()
lp = (p * w).sum(-1) * torch.rsqrt(p.pow(2).mean(-1) + c.eps)
mm = torch.maximum(m, lp)
a, b = torch.exp(m - mm), torch.exp(lp - mm)
mixed = (A * a[:, None] + p * b[:, None]) / (Z * a + b)[:, None]
return rms(mixed.to(prefix.dtype), Wf["norm"], c.eps)
def init_state(emb: torch.Tensor, c: Cfg) -> dict:
B, T, D = emb.shape
return {"delta": None, "prefix": emb.reshape(B * T, D).clone(),
"blocks": emb.new_zeros(B * T, c.n_blocks, D), "shape": (B, T)}
def final_hidden(state: dict, Wf: dict, c: Cfg) -> torch.Tensor:
B, T = state["shape"]
h = attn_res(state["prefix"], state["delta"].reshape(B * T, c.hidden), state["blocks"],
Wf["output_attn_res_norm"], Wf["output_attn_res_proj"][0], None, c.n_blocks, -1, c.eps)
return rms(h, Wf["norm"], c.eps).view(B, T, c.hidden)
def token_nll(hidden: torch.Tensor, lm_head: torch.Tensor, targets: torch.Tensor, chunk: int = 2048) -> torch.Tensor:
"""Per-token negative log-likelihood, vocabulary in chunks of rows to bound memory."""
h = hidden.reshape(-1, hidden.shape[-1])
t = targets.reshape(-1)
out = torch.empty(h.shape[0], device=h.device, dtype=torch.float32)
for i in range(0, h.shape[0], chunk):
logits = (h[i:i + chunk] @ lm_head.t()).float()
out[i:i + chunk] = F.cross_entropy(logits, t[i:i + chunk], reduction="none")
return out.view(targets.shape)