Skip to content
INDIE / MACHINE
CODELESSON 5 OF 68 MIN

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.

STEP 1 / 8QUIZ 0 / 2
01 /

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⁵³.

PYTORCH / NUMPYengram_demo_v1.py
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)
HYPERFIELDlib/courses/engram-hash.ts
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;
}
02 /

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.

PYTORCHEngram.forward
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 output
HYPERFIELDlib/courses/tiny-engram.ts
export 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 };
}
03 /

Op by op

STEPPYTORCHHYPERFIELDNOTE
Hashnp.bitwise_xor(mix, t * m)mix ^= tok * mBigInt keeps int64 exact
Head offsetsinput_ids + self.offsetsr + offsets[i % heads]Done on the host here
Lookupself.embedding(ids)table.indexSelect(0, rows)nn.Embedding is a row gather
Concat heads.flatten(start_dim=-2).reshape([b, s, -1])
Signed sqrtg.abs().clamp_min(1e-6).sqrt() * g.sign()g.abs().maximum(1e-6).sqrt().mul(g.sign())clamp_min = maximum with a number
Causal convnn.Conv1d(..., groups=C, padding=(k-1)*d)[..., :T]cat(zeros, x) + k shifted indexSelectsOne gather per tap
SiLUnn.SiLU()x.mul(x.sigmoid())
04 / CHECK YOURSELF

Quick check

Why does the TypeScript hash use BigInt?

05 /

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.

INTERACTIVE / LIVE ENGRAM (HYPERFIELD, IN THIS PAGE)
The function from the code step, running in your browser: width 8, orders 2 and 3, two heads each with 31-43 rows, fixed weights. Words are normalized before they get an id, so “The” and “the” are the same token. ↺ marks an n-gram the sentence already read: the same rows, the same memory. The gate still differs, because it also looks at the hidden state.
06 /

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:

node tests/courses-engram-parity.mjs
CHECKRESULT
Hash rows, 2 layers × 2 × 12 tokens × 4 headsIdentical to numpy
Max absolute output error4.8e-7
ReferencePyTorch 2.14.1+cpu, numpy 2.5.4, fp32
Hyperfield0.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).

07 /

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.

HYPERFIELD 0.2.0hf.nn.Engram
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 host
08 / CHECK YOURSELF

Quick check

Where does the hash run in Hyperfield's layer?

LESSON 5 COMPLETE

Up next: Training and serving Engram