Skip to content
INDIE / MACHINE
CONCEPTLESSON 2 OF 66 MIN

The N-Grammer layer at a glance

Where an N-Grammer layer sits in a transformer, the six steps of its forward pass, and what is learned versus computed.

STEP 1 / 5QUIZ 0 / 2
01 /

Where it sits

In the original paper (Roy et al., 2022) the layer augments the token embeddings at the bottom of the network. The Yumon decoder does the same: its config says "ngram": { "layers": [0], "num_clusters": 256, "heads": 16 }, meaning one layer in front of block 0, 256 centroids, 16 heads.

It takes the residual stream x of shape [batch, seq, width] and returns a tensor of the same shape, so you can drop it in front of any block without touching anything else.

ARCHITECTURE DIAGRAM
Rendering diagram...
02 /

Step through one pass

Click through the six stages for three tokens. Watch each vector turn into two small integers, then into two table rows.

INTERACTIVE / ONE PASS THROUGH THE LAYER
STAGEthecatsat
1. Residual inx ∈ ℝ⁸x ∈ ℝ⁸x ∈ ℝ⁸
2. Split + normalizeℝ⁴ℝ⁴ℝ⁴ℝ⁴ℝ⁴ℝ⁴
3. Snap to a centroid130230
4. Look one back∅∅1302
5. Bigram row#17#39#4#34#3#28
6. Look up, add backx + Δx + Δx + Δ

Residual in. One vector per token, shape [batch, seq, width]. Here width = 8.

Real values from a tiny layer (width 8, 2 heads, 4 centroids) - the same numbers PyTorch produces for these weights. ∅ is the “no previous token” id.
03 / CHECK YOURSELF

Quick check

x has shape [2, 10, 256]. What shape does the N-Grammer layer return?

04 /

This version vs the paper

There are a few N-Grammer variants. This course follows the one in the Yumon decoder (yumon-pet's dec_model.py), which deliberately differs from the paper and from lucidrains/n-grammer-pytorch:

PAPER / LUCIDRAINSTHIS COURSE (YUMON)
Bigram tableHashed into a fixed-size n-gram vocabularyExact: one row per (prev, id) pair, (K+1)·K rows per head
Combine with xConcatenateProject back to width w and add
Centroid updatesEMA k-meansCentroids are parameters trained by an auxiliary loss
05 / CHECK YOURSELF

Quick check

Which of these is NOT a learned parameter of the layer?

LESSON 2 COMPLETE

Up next: Snapping to centroids: product quantization