Coding it: PyTorch to Hyperfield
DeepSeek's demo Engram next to a Hyperfield (TypeScript) version, op by op, with a live layer that matches PyTorch.
The hash in both
On the left, the hash from DeepSeek's engram_demo_v1.py. On the right, the one this course runs. numpy's int64 products fit exactly in a JavaScript BigInt; a plain number would lose bits above 2⁵³.
def _get_ngram_hashes(self, input_ids: np.ndarray, layer_id: int) -> np.ndarray:
x = np.asarray(input_ids, dtype=np.int64)
B, T = x.shape
multipliers = self.layer_multipliers[layer_id]
def shift_k(k: int) -> np.ndarray:
if k == 0: return x
shifted = np.pad(x, ((0, 0), (k, 0)),
mode='constant', constant_values=self.pad_id)[:, :T]
return shifted
base_shifts = [shift_k(k) for k in range(self.max_ngram_size)]
all_hashes = []
for n in range(2, self.max_ngram_size + 1):
n_gram_index = n - 2
tokens = base_shifts[:n]
mix = (tokens[0] * multipliers[0])
for k in range(1, n):
mix = np.bitwise_xor(mix, tokens[k] * multipliers[k])
num_heads_for_this_ngram = self.n_head_per_ngram
head_vocab_sizes = self.vocab_size_across_layers[layer_id][n_gram_index]
for j in range(num_heads_for_this_ngram):
mod = int(head_vocab_sizes[j])
head_hash = mix % mod
all_hashes.append(head_hash.astype(np.int64, copy=False))
return np.stack(all_hashes, axis=2)export function engramHash(ids: ArrayLike<number>, batch: number, seq: number, { maxNgram, primes, multipliers, padId }: HashConfig): Int32Array {
const heads = primes.flat().length;
const out = new Int32Array(batch * seq * heads);
for (let b = 0; b < batch; b++) {
const tok = (t: number) => BigInt(t >= 0 ? ids[b * seq + t] : padId);
for (let t = 0; t < seq; t++) {
let mix = tok(t) * multipliers[0];
let o = (b * seq + t) * heads;
for (let n = 2; n <= maxNgram; n++) {
mix ^= tok(t - (n - 1)) * multipliers[n - 1];
for (const p of primes[n - 2]) out[o++] = Number(mix % BigInt(p));
}
}
}
return out;
}The layer in both
The demo runs four hyper-connection streams; the course layer has one, which turns the per-stream loops into single expressions. The numbered comments follow the demo's order.
def forward(self,hidden_states,input_ids):
"""
hidden_states: [B, L, HC_MULT, D]
input_ids: [B, L]
"""
hash_input_ids = torch.from_numpy(self.hash_mapping.hash(input_ids)[self.layer_id])
embeddings = self.multi_head_embedding(hash_input_ids).flatten(start_dim=-2)
gates = []
for hc_idx in range(backbone_config.hc_mult):
key = self.key_projs[hc_idx](embeddings)
normed_key = self.norm1[hc_idx](key)
query = hidden_states[:,:,hc_idx,:]
normed_query = self.norm2[hc_idx](query)
gate = (normed_key * normed_query).sum(dim=-1) / math.sqrt(backbone_config.hidden_size)
gate = gate.abs().clamp_min(1e-6).sqrt() * gate.sign()
gate = gate.sigmoid().unsqueeze(-1)
gates.append(gate)
gates = torch.stack(gates,dim=2)
value = gates * self.value_proj(embeddings).unsqueeze(2)
output = value + self.short_conv(value)
return outputexport function engramLayer(x: Tensor, ids: ArrayLike<number>, w: EngramWeights): EngramTrace {
const [b, s, d] = x.shape;
// 1. Hash every 2..N-gram ending at each position into one row per head.
const rows = engramHash(ids, b, s, w);
const sizes = w.primes.flat();
const offsets = sizes.map((_, i) => sizes.slice(0, i).reduce((a, p) => a + p, 0));
const global = Float32Array.from(rows, (r, i) => r + offsets[i % sizes.length]);
// 2. Read the rows and concatenate them: the memory vector e.
const memory = w.table.indexSelect(0, hf.tensor(global, [global.length])).reshape([b, s, -1]);
// 3. Gate: compare a key from the memory with the hidden state, both RMS-normalized.
const key = rmsNorm(hf.linear(memory, w.keyW, w.keyB), w.norm1, 2 ** -23);
const query = rmsNorm(x, w.norm2, 2 ** -23);
const dot = key.mul(query).sum(-1).div(Math.sqrt(d));
const gate = dot.abs().maximum(1e-6).sqrt().mul(dot.sign()).sigmoid(); // sigmoid(signed sqrt)
// 4. Value: the gated projection of the memory.
const value = gate.unsqueeze(-1).mul(hf.linear(memory, w.valueW, w.valueB));
// 5. Short causal conv over RMSNorm(value): tap j reads position t - (k-1-j) * dilation.
const k = w.conv.shape[2];
const dil = w.maxNgram;
const pad = (k - 1) * dil;
const normed = hf.cat([hf.zeros([b, pad, d]), rmsNorm(value, w.convNorm, 1e-5)], 1);
const taps = w.conv.reshape([d, k]);
let conv = hf.zeros([b, s, d]);
for (let j = 0; j < k; j++) {
const shifted = normed.indexSelect(1, hf.arange(j * dil, j * dil + s));
conv = conv.add(shifted.mul(taps.indexSelect(1, hf.tensor([j])).reshape([d])));
}
const y = value.add(conv.mul(conv.sigmoid())); // value + SiLU(conv)
return { rows, gate, value, y };
}Op by op
| STEP | PYTORCH | HYPERFIELD | NOTE |
|---|---|---|---|
| Hash | np.bitwise_xor(mix, t * m) | mix ^= tok * m | BigInt keeps int64 exact |
| Head offsets | input_ids + self.offsets | r + offsets[i % heads] | Done on the host here |
| Lookup | self.embedding(ids) | table.indexSelect(0, rows) | nn.Embedding is a row gather |
| Concat heads | .flatten(start_dim=-2) | .reshape([b, s, -1]) | |
| Signed sqrt | g.abs().clamp_min(1e-6).sqrt() * g.sign() | g.abs().maximum(1e-6).sqrt().mul(g.sign()) | clamp_min = maximum with a number |
| Causal conv | nn.Conv1d(..., groups=C, padding=(k-1)*d)[..., :T] | cat(zeros, x) + k shifted indexSelects | One gather per tap |
| SiLU | nn.SiLU() | x.mul(x.sigmoid()) |
Quick check
Why does the TypeScript hash use BigInt?
Run it in your browser
This table is computed by engramLayer from the previous step, live, with Hyperfield in this page. “The cat sat on the” appears twice with different capitals: after compression it reads the same rows both times.
Does it match PyTorch?
The parity test builds DeepSeek's demo classes in PyTorch (shrunk to width 8 and tables of 37-67 rows, random weights), runs them, and loads the same weights into engramLayer:
| CHECK | RESULT |
|---|---|
| Hash rows, 2 layers × 2 × 12 tokens × 4 heads | Identical to numpy |
| Max absolute output error | 4.8e-7 |
| Reference | PyTorch 2.14.1+cpu, numpy 2.5.4, fp32 |
| Hyperfield | 0.1.0, CPU backend, Node 24.11 |
Hyperfield 0.2.0's hf.nn.Engram is checked the same way with two hyper-connection streams, including every gradient (max error 2.6e-6).
The packaged layer
Hyperfield 0.2.0 ships the full layer: streams, tokenizer compression, KV-cache state for generation, and the demo's parameter names, so a state dict saved from the demo loads without renaming.
import * as hf from "hyperfield"; // 0.2.0
const { lookup, size } = hf.text.compressVocab(tokenizer);
const engram = new hf.nn.Engram({
layerId: 1, layerIds: [1, 15], hiddenSize: 1024, hcMult: 4,
maxNgram: 3, headsPerNgram: 8, embedPerNgram: 512,
tableSizes: [size * 5, size * 5], vocabSize: size, lookup,
});
engram.loadStateDict(stateDict); // the demo's parameter names
h = engram.call({ hidden: h, ids }).add(h); // ids: raw token ids, on the hostQuick check
Where does the hash run in Hyperfield's layer?