Skip to content
INDIE / MACHINE
CODELESSON 5 OF 68 MIN

Coding it: PyTorch to Hyperfield

The N-Grammer forward pass in PyTorch and in Hyperfield (TypeScript, WebGPU/CPU) side by side, an op-by-op mapping, and a live layer that matches PyTorch.

STEP 1 / 7QUIZ 0 / 2
01 /

Two libraries, one layer

Hyperfield is a TypeScript ML library with a PyTorch-style API that runs on WebGPU or a CPU backend (npm hyperfield@0.1.0). On the left is the real layer from the Yumon PyTorch trainer; on the right is the parameter setup the tiny course layer uses, built from plain tensors so you can see every piece.

PYTORCHyumon-pet python-train/dec_model.py
class Ngram(nn.Module):
    def __init__(self, cfg: NgramConfig, width: int, layer: int):
        super().__init__()
        self.k, self.h = cfg.num_clusters, cfg.heads
        self.dh = width // self.h
        g = torch.Generator().manual_seed(cfg.seed + layer)
        self.centroids = nn.Parameter(torch.randn(self.h, self.k, self.dh, generator=g))
        self.bigrams = nn.Embedding(self.h * (self.k + 1) * self.k, self.dh)
        nn.init.normal_(self.bigrams.weight, 0.0, 0.02)
        self.norm = RMSNorm(self.dh)
        self.out = linear(width, width)
        nn.init.zeros_(self.out.weight)
        self.loss_weight = cfg.loss_weight
HYPERFIELDlib/courses/tiny-ngrammer.ts
export function demoWeights({ width = 8, heads = 2, k = 4, outScale = 0.5 } = {}): NgramWeights {
  const dh = width / heads;
  const fill = (n: number, seed: number, scale = 1) => Float32Array.from({ length: n }, (_, i) => wave(i, seed) * scale);
  return {
    heads,
    k,
    centroids: hf.tensor(fill(heads * k * dh, 1), [heads, k, dh]),
    bigrams: hf.tensor(fill(heads * (k + 1) * k * dh, 2, 0.02), [heads * (k + 1) * k, dh]),
    out: hf.tensor(fill(width * width, 3, outScale), [width, width]),
  };
}
02 /

The forward pass in both

Same five steps in both. Read them line against line - the numbered comments in the Hyperfield version follow the PyTorch order.

PYTORCHNgram.forward
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
    b, s, w = x.shape
    with torch.autocast(x.device.type, enabled=False):
        h = x.detach().float().view(b, s, self.h, self.dh)
        h = h * torch.rsqrt(h.pow(2).mean(-1, keepdim=True) + 1e-6)
        h = h.permute(2, 0, 1, 3).reshape(self.h, b * s, self.dh)
        c = self.centroids.float()
        dist = c.detach().pow(2).sum(-1).unsqueeze(1) - 2 * h @ c.detach().transpose(1, 2)
        ids = dist.argmin(-1)  # [heads, rows]
        q = torch.gather(c, 1, ids.unsqueeze(-1).expand(-1, -1, self.dh))
        loss = (q - h).pow(2).mean() * self.loss_weight
        ids = ids.transpose(0, 1).reshape(b, s, self.h)
        prev = torch.cat([torch.full_like(ids[:, :1], self.k), ids[:, :-1]], dim=1)
        off = torch.arange(self.h, device=x.device) * ((self.k + 1) * self.k)
        emb = self.norm(self.bigrams(prev * self.k + ids + off)).reshape(b, s, w)
    return x + self.out(emb.to(x.dtype)), loss
HYPERFIELDngramLayer
export function ngramLayer(x: Tensor, { heads, k, centroids, bigrams, out }: NgramWeights): NgramTrace {
  const [b, s, width] = x.shape;
  const dh = width / heads;

  // 1. Split the residual into heads and RMS-normalize each slice.
  const h = rmsNorm(x.reshape([b, s, heads, dh]))
    .reshape([b * s, heads, dh])
    .transpose(0, 1); // [heads, rows, dh]

  // 2. Nearest centroid. |h - c|² = |h|² - 2 h·c + |c|², and |h|² is the same for every c.
  const dist = centroids.square().sum(-1).unsqueeze(1).sub(h.matmul(centroids.transpose(1, 2)).mul(2));
  const ids = dist.neg().argmax(-1).transpose(0, 1).reshape([b, s, heads]); // argmin

  // 3. Previous id: shift right by one, with k (the "no previous" row) at position 0.
  const start = hf.full([b, 1, heads], k);
  const prev = s === 1 ? start : hf.cat([start, ids.indexSelect(1, hf.arange(s - 1))], 1);

  // 4. One exact bigram row per head: head h owns rows [h (k+1) k, (h+1) (k+1) k).
  const rows = prev.mul(k).add(ids).add(hf.arange(heads).mul((k + 1) * k));

  // 5. Look up, normalize, project back to full width and add to the residual.
  const emb = rmsNorm(bigrams.indexSelect(0, rows.reshape([b * s * heads])).reshape([b, s, heads, dh]));
  const y = x.add(hf.linear(emb.reshape([b, s, width]), out));
  return { ids, prev, rows, y };
}
03 /

Op by op

STEPPYTORCHHYPERFIELDNOTE
Split headsx.view(b, s, H, dh)x.reshape([b, s, H, dh])Shapes are arrays in Hyperfield
RMS normh.pow(2).mean(-1, keepdim=True)h.square().mean(-1, true)keepdim is positional
Heads firstpermute(2, 0, 1, 3).reshape(...)reshape([b*s, H, dh]).transpose(0, 1)Same [heads, rows, dh] result
Distancesh @ c.transpose(1, 2)h.matmul(c.transpose(1, 2))Batched over heads
Nearestdist.argmin(-1)dist.neg().argmax(-1)argmin(d) = argmax(−d)
Shift righttorch.cat([torch.full_like(...), ids[:, :-1]], 1)hf.cat([hf.full(...), ids.indexSelect(1, hf.arange(s - 1))], 1)No slicing syntax; gather the first s−1 positions
Table lookupself.bigrams(rows)bigrams.indexSelect(0, rows)nn.Embedding is a row gather
Projectionself.out(emb)hf.linear(emb, out)Both compute emb @ outᵀ
No gradientx.detach()(inference only)Hyperfield has .detach() and hf.noGrad() for training
04 / CHECK YOURSELF

Quick check

The Hyperfield version has no argmin. How does it find the nearest centroid?

05 /

Run it in your browser

This table is computed by ngramLayer from the previous step, live, with Hyperfield in this page. Type your own words. A repeated phrase like “the cat” reads the same rows each time it appears.

INTERACTIVE / LIVE N-GRAMMER (HYPERFIELD, IN THIS PAGE)
This is the exact function from the code step above, running in your browser: width 8, 2 heads, K = 4, fixed weights. A word's vector comes from its letters, so a repeated word gets the same ids. Rows marked ↺ were already read earlier in the sentence - the same bigram, the same memory.
06 /

Does it match PyTorch?

The course repo has a parity test. It runs ngramLayer on Hyperfield's CPU backend, writes the weights and input to JSON, and loads them into the real Ngram module from yumon-pet's dec_model.py:

node tests/courses-parity.mjs
CHECKRESULT
Cluster ids, 10 tokens × 2 headsIdentical
Max absolute output error2.38e-7
ReferencePyTorch 2.14.1+cpu, fp32
Hyperfield0.1.0, CPU backend, Node 24.11

The full Yumon model in Hyperfield (27.2M parameters, the same N-Grammer layer at K = 256 and 16 heads) matches PyTorch logits to 2.5e-5 on WebGPU, per the Hyperfield README.

07 / CHECK YOURSELF

Quick check

PyTorch's nn.Linear(w, w) stores weight W of shape [out, in]. What does hf.linear(x, W) compute?

LESSON 5 COMPLETE

Up next: Training it: centroid loss and zero init