Boom5426's picture
WeightCode records and weights (redacted 2026-11-10, see REDACTIONS.json)
4c27541
Raw History Blame Contribute Delete
5.92 kB
"""Numpy reference forward pass of an encoder-only Transformer described by model_spec.json (arch tfm).
Requires numpy only. Call ``forward(params, x)``:
* ``params``: dict of float arrays keyed by parameter name, PyTorch layout (linear weight [out, in], embedding
weight [rows, d]).
* ``x``: int64 token ids of shape [N, SEQ_LEN] (any integer dtype is accepted), each in 0 .. VOCAB_SIZE - 1.
* returns float32 logits [N, SEQ_LEN, N_OUT]; the prediction at a position is the argmax over the last axis.
Computation (pre-LayerNorm; blocks ``b1`` .. ``bK`` read from the parameter names):
h = tok_emb.weight[x] + pos_emb.weight[t]
per block i: h = h + attention(ln1(h)); h = h + fc2(relu(fc1(ln2(h))))
logits = head(ln_f(h))
LayerNorm: (a - mean) / sqrt(var + LN_EPS) * weight + bias over the last axis, var the biased variance.
Attention: q, k, v = a @ W.T + b; N_HEADS heads, head j on columns j * head_dim .. (j + 1) * head_dim - 1;
softmax(q k^T / sqrt(head_dim)) over the keys, keys at positions whose token is PAD_ID excluded; heads concatenated,
then @ o.weight.T + o.bias. All arithmetic runs in float64 and the logits are cast once to float32. Rows are
processed in chunks of at most CHUNK, which bounds memory.
"""
from __future__ import annotations
import numpy as np
SEQ_LEN = 59
VOCAB_SIZE = 17
N_OUT = 7
N_HEADS = 4
PAD_ID = 0
LN_EPS = 1e-05
CHUNK = 512
def _tensor(params: dict, key: str) -> np.ndarray:
if key not in params:
raise KeyError(f"missing parameter {key!r}")
value = np.asarray(params[key])
if not np.issubdtype(value.dtype, np.floating):
raise TypeError(f"{key} must be a float array, got {value.dtype}")
return value.astype(np.float64)
def _blocks(params: dict) -> list[str]:
numbers = set()
for key in params:
head = str(key).split(".")[0]
if head in ("tok_emb", "pos_emb", "ln_f", "head"):
continue
if not (head.startswith("b") and head[1:].isdigit() and head[1] != "0"):
raise KeyError(f"unexpected parameter name {key!r}")
numbers.add(int(head[1:]))
ordered = sorted(numbers)
if not ordered or ordered != list(range(1, len(ordered) + 1)):
raise KeyError(f"blocks must be numbered b1..bK without gaps, got {ordered}")
return [f"b{number}" for number in ordered]
def _layernorm(a: np.ndarray, weight: np.ndarray, bias: np.ndarray) -> np.ndarray:
mean = a.mean(axis=-1, keepdims=True)
var = ((a - mean) ** 2).mean(axis=-1, keepdims=True)
return (a - mean) / np.sqrt(var + LN_EPS) * weight + bias
def _linear(a: np.ndarray, params: dict, name: str) -> np.ndarray:
weight, bias = _tensor(params, name + ".weight"), _tensor(params, name + ".bias")
if weight.ndim != 2 or weight.shape[1] != a.shape[-1] or bias.shape != (weight.shape[0],):
raise ValueError(f"{name} weight {weight.shape} / bias {bias.shape} do not fit input width {a.shape[-1]}")
return a @ weight.T + bias
def _attention(a: np.ndarray, params: dict, name: str, key_pad: np.ndarray) -> np.ndarray:
n, length, width = a.shape
if width % N_HEADS:
raise ValueError(f"width {width} is not divisible by N_HEADS {N_HEADS}")
head_dim = width // N_HEADS
def heads(t: np.ndarray) -> np.ndarray:
return t.reshape(n, length, N_HEADS, head_dim).transpose(0, 2, 1, 3)
q, k, v = (heads(_linear(a, params, f"{name}.{part}")) for part in "qkv")
scores = q @ k.transpose(0, 1, 3, 2) / np.sqrt(head_dim)
scores = np.where(key_pad[:, None, None, :], -np.inf, scores)
scores = scores - scores.max(axis=-1, keepdims=True)
weights = np.exp(scores)
weights = weights / weights.sum(axis=-1, keepdims=True)
mixed = (weights @ v).transpose(0, 2, 1, 3).reshape(n, length, width)
return _linear(mixed, params, f"{name}.o")
def _forward_chunk(params: dict, blocks: list[str], x: np.ndarray) -> np.ndarray:
tok, pos = _tensor(params, "tok_emb.weight"), _tensor(params, "pos_emb.weight")
if tok.ndim != 2 or tok.shape[0] != VOCAB_SIZE or pos.shape != (SEQ_LEN, tok.shape[1]):
raise ValueError(f"embeddings {tok.shape} / {pos.shape} do not fit vocab {VOCAB_SIZE} and length {SEQ_LEN}")
h = tok[x] + pos[None, :, :]
key_pad = x == PAD_ID
if np.any(key_pad.all(axis=1)):
raise ValueError("a row consists of PAD only")
for block in blocks:
a = _layernorm(h, _tensor(params, block + ".ln1.weight"), _tensor(params, block + ".ln1.bias"))
h = h + _attention(a, params, block + ".attn", key_pad)
a = _layernorm(h, _tensor(params, block + ".ln2.weight"), _tensor(params, block + ".ln2.bias"))
h = h + _linear(np.maximum(_linear(a, params, block + ".mlp.fc1"), 0.0), params, block + ".mlp.fc2")
a = _layernorm(h, _tensor(params, "ln_f.weight"), _tensor(params, "ln_f.bias"))
logits = _linear(a, params, "head")
if logits.shape[-1] != N_OUT:
raise ValueError(f"model produces {logits.shape[-1]} outputs per position, expected {N_OUT}")
return logits.astype(np.float32)
def forward(params: dict[str, np.ndarray], x: np.ndarray) -> np.ndarray:
"""Logits float32 [N, SEQ_LEN, N_OUT] for int token rows [N, SEQ_LEN]."""
x = np.asarray(x)
if not np.issubdtype(x.dtype, np.integer):
raise TypeError(f"token ids must be integers, got {x.dtype}")
if x.ndim != 2 or x.shape[1] != SEQ_LEN:
raise ValueError(f"token rows must have shape [N, {SEQ_LEN}], got {list(x.shape)}")
if x.size and (x.min() < 0 or x.max() >= VOCAB_SIZE):
raise ValueError(f"token ids must lie in 0 .. {VOCAB_SIZE - 1}")
x = x.astype(np.int64)
blocks = _blocks(params)
if x.shape[0] == 0:
return np.zeros((0, SEQ_LEN, N_OUT), dtype=np.float32)
chunks = [_forward_chunk(params, blocks, x[start : start + CHUNK]) for start in range(0, x.shape[0], CHUNK)]
return np.concatenate(chunks, axis=0)