← notes Architectures

Engram: look up fixed patterns instead of recomputing them

Engram hashes the last 2 and 3 tokens into rows of large learned tables, gates what it reads against the hidden state, and adds it to the residual stream. Memory becomes a second kind of sparsity next to MoE.

19 min read 7 interactive

Remember instead of recompute

Much of text is fixed patterns: “Alexander the Great”, “New York City”, for i in range(. When a model sees “Alexander the”, the next token “Great” is almost certain. The model does not need to think here. It only needs to remember.

A normal Transformer has no place to store such a pattern. It rebuilds the pattern in every forward pass: attention joins “Alexander” and “the”, and then the feed-forward layers recall the entity. This uses several of the first layers. Engram, from DeepSeek-AI’s paper Conditional Memory via Scalable Lookup (arXiv 2601.07372), gives the model a lookup table for these patterns. The pattern arrives at layer 2 in one step, and the layers above it are free for other work.

The paper calls this conditional memory: each token reads only a few rows of a very large table. Compare it with MoE, which is conditional computation.

MoEEngram
Sparse unitexpert FFNtable row
Selected bylearned router on hth_tfixed hash of the last 2–3 token IDs
Selection knownwhen the layer runsbefore the model runs
Main costFLOPs and HBMmemory bandwidth; host RAM is acceptable
Good forcomposition, reasoningnames, facts, idioms, code patterns

Engram is not in every layer. Engram-27B puts it in layers 2 and 15. In those layers Engram runs first and adds its output to the residual stream; then attention and MoE run as usual. The module has two inputs: the hidden state hth_t, which feeds the gate, and the raw token IDs, which feed the hash.

Part A: from tokens to row numbers

For each position tt the module does eight steps. Steps 1–4 work only with integers and give row numbers. They have no gradient and can run on the CPU in the data loader. Steps 5–8 are normal differentiable computation.

  1. Compress the token IDs. The tokenizer has many tokens that differ only by case, accents or a leading space. Engram normalizes each token’s text (NFKC, no accents, lower case, no outer spaces), and all tokens with the same normalized text share one canonical ID. " Great", "Great", " GREAT" and " great" all become 2294. The paper reports that this makes the effective vocabulary 23% smaller for a 128k tokenizer. The map is used only by Engram; the normal embedding and the output head still see the raw IDs.
  2. Build the suffix n-grams. At position tt, take the 2-gram (xt−1′,xt′)(x'_{t-1}, x'_t) and the 3-gram (xt−2′,xt−1′,xt′)(x'_{t-2}, x'_{t-1}, x'_t), where x′x' is a canonical ID. A suffix n-gram ends at tt, so it uses only the past. Positions before the start use a padding ID. The 2-gram “the great” is general (Catherine the Great, the Great Wall); the 3-gram “alexander the great” is specific.
  3. Hash. There are about 129 2803≈2×1015129\,280^3 \approx 2\times 10^{15} possible 3-grams, too many for one row each. The official code uses a multiply–XOR hash, then a modulo by a prime table size (formula below).
  4. Read and concatenate. Read row zt,n,kz_{t,n,k} of each table and join the rows end to end into the memory vector ete_t. This step does no multiplication at all.
mixt,n=(xt′m0)⊕(xt−1′m1)⊕⋯⊕(xt−n+1′mn−1),zt,n,k=mixt,n mod pn,k\text{mix}_{t,n} = (x'_t m_0) \oplus (x'_{t-1} m_1) \oplus \dots \oplus (x'_{t-n+1} m_{n-1}), \qquad z_{t,n,k} = \text{mix}_{t,n} \bmod p_{n,k}

Each hash head kk has its own table En,kE_{n,k} with a prime number of rows pn,kp_{n,k}. All heads of one order share the mix value; they differ only in the prime.

The source works one sentence through by hand with toy sizes: two hash heads per order with table sizes 11 and 13 (2-grams) and 17 and 19 (3-grams), 2 numbers per row, multipliers 13, 7 and 3, and padding ID 2. The real demo code uses 8 heads per order, about 646,400 rows per table, 64 numbers per row and random odd 64-bit multipliers.

animation

One position's path from tokens to the memory vector

Click a token to pick the position t, then press Play or Step. Type your own sentence, or change the case of a word.

The row numbers come from the token IDs alone, so they are fixed before the model runs. Change “Great” to “GREAT”: compression gives the same canonical ID, so the same rows. Toy sizes; row values are random, as at the start of training.

At t=2t = 2 (“great”) the arithmetic is: 2294×13=298222294 \times 13 = 29822, 262×7=1834262 \times 7 = 1834, 417×3=1251417 \times 3 = 1251. XOR gives the 2-gram mix 29524 and the 3-gram mix 30647. The rows are 29524 mod 11=029524 \bmod 11 = 0, 29524 mod 13=129524 \bmod 13 = 1, 30647 mod 17=1330647 \bmod 17 = 13 and 30647 mod 19=030647 \bmod 19 = 0, so

e2=(0.3, −0.4, −0.3, −0.1, −0.1, 0.1, 0.7, −0.6).e_2 = (0.3,\ -0.4,\ -0.3,\ -0.1,\ -0.1,\ 0.1,\ 0.7,\ -0.6).

Different odd multipliers make the order of the tokens matter: (the, great) and (great, the) give different mix values. Each token reads 2K2K rows; here 4 of the 60 rows in the toy tables.

Collisions, and why there are several heads

A collision occurs when two different n-grams get the same row number. They then share one row, which adds noise. The source gives an example. If gatsby has canonical ID 3011, the 2-gram (the, gatsby) has mix (3011×13)⊕(262×7)=40909(3011 \times 13) \oplus (262 \times 7) = 40909. That is row 0 in the p=11p = 11 table, the same row as (the, great). In the p=13p = 13 table it is row 11, a different row from (the, great).

Three things protect the model:

  • Several heads. The heads use different primes, so two n-grams that collide on one head almost never collide on all heads. With K=8K = 8 heads and tables of about 646,000 rows, the probability is extremely small.
  • Training. A shared row learns the average of the n-grams that use it, and the other heads learn the difference.
  • The gate. If the combined memory does not fit the context, the gate value becomes small (next section).

playground

Collisions against table size and number of heads

Type another canonical ID for X to find a collision with (the, great). Then move the sliders: more heads, a larger table, fewer n-grams.

simulated (multiply–XOR hash) independent-heads estimate
load N / p
row shared, head 0
no clean head (K)
pairs equal on all K
A head is clean for an n-gram when no other n-gram shares its row. One head is often shared at a high load, but the share of n-grams with no clean head drops fast as K grows. Simulated with seeded random 2-grams and the toy multipliers 13 and 7.

Part B: the gate decides how much memory enters

Two learned matrices of size d×∣et∣d \times |e_t| turn the memory vector into a key and a value: kt=WKetk_t = W_K e_t and vt=WVetv_t = W_V e_t. The value is what the memory says. The key is what the memory is about, and the gate compares it with the context:

αt=σ ⁣(RMSNorm(ht)⊤ RMSNorm(kt)d),v~t=αtvt\alpha_t = \sigma\!\left(\frac{\mathrm{RMSNorm}(h_t)^\top\, \mathrm{RMSNorm}(k_t)}{\sqrt d}\right), \qquad \tilde v_t = \alpha_t v_t

The hidden state hth_t has already read the full context through the layers below. If it agrees with the key, the gate opens. This handles both failure modes of a 3-token memory: a collision, and an n-gram whose meaning depends on the context (“the great” in a history text or in a novel title).

In the toy example, k2=(0.08,0.11,0.59,−0.63)k_2 = (0.08, 0.11, 0.59, -0.63) and v2=(0.18,−0.20,0.04,−0.48)v_2 = (0.18, -0.20, 0.04, -0.48). With a hidden state that agrees, h2=(0.2,0.2,1.2,−1.3)h_2 = (0.2, 0.2, 1.2, -1.3), the normalized dot product is 3.999, z=1.999z = 1.999 and α2=0.881\alpha_2 = 0.881. With a hidden state that points the other way, h2=(−0.2,−0.3,−1.2,1.2)h_2 = (-0.2, -0.3, -1.2, 1.2), z=−1.996z = -1.996 and α2=0.120\alpha_2 = 0.120, so the model almost ignores the memory.

playground

The gate depends only on the angle between h and k

Drag the h handle around the circle. Try Case A and Case B. Then set Norm to None and move the size of h.

Rule
Width d
Norm
value v (what the memory says) gated value αv (what enters h)
cos(h, k)
z
gate α
reachable α
After RMSNorm, z = √d · cos(h, k), so z stays in [−√d, √d] and the size of h has no effect. Without the norm, a large h opens the gate with no real agreement. At d = 1024 the paper's z can reach ±32; the code's signed square root narrows that to about ±5.7. Case A and B are the source's numbers.

Two details from the source. First, the official code applies a signed square root before the sigmoid, z←sign(z)∣z∣z \leftarrow \mathrm{sign}(z)\sqrt{|z|}, which makes the gate less extreme and training more stable. The paper’s equation does not show it, and the toy example follows the paper. Second, DeepSeek’s backbone uses mHC (manifold-constrained hyper-connections), which keeps M=4M = 4 parallel copies of the residual stream. Engram then computes 4 gates with 4 separate key matrices, but one shared table and one shared WVW_V.

After the gate, a short depthwise causal convolution mixes each channel with the same channel at earlier positions. The kernel has size 4 and dilation 3 (the maximum n-gram order), so position tt reads tt, t−3t-3, t−6t-6 and t−9t-9:

ut=RMSNorm(v~t),ct[c]=∑j=03w[c,j] ut−3j[c],yt=SiLU(ct)+v~tu_t = \mathrm{RMSNorm}(\tilde v_t), \qquad c_t[c] = \sum_{j=0}^{3} w[c, j]\, u_{t-3j}[c], \qquad y_t = \mathrm{SiLU}(c_t) + \tilde v_t

Finally ht←ht+yth_t \leftarrow h_t + y_t, and the layer’s attention and MoE run on the updated hidden state.

Training: only the touched rows learn

Engram trains together with the model, with the normal next-token loss. There is no separate stage that counts n-grams. The rows start as random numbers, and the gradient teaches them what to store. In each step the CPU data loader computes the hash for the next batch while the GPU works on the current one.

The gradient reaches a row only if the forward pass read it. In the toy example the layers above send back ∂L/∂y2=(0.5,−0.2,0.1,0.3)\partial L/\partial y_2 = (0.5, -0.2, 0.1, 0.3). The gradient passes through the gate, then through WV⊤W_V^\top, and arrives at the 8 numbers of e2e_2. The path through the gate is almost zero here, because h^2\hat h_2 and k^2\hat k_2 are almost parallel: the dot product is near its maximum dd, where the slope is zero. A finite-difference check of the full gradient gives the same numbers to 3 decimals.

animation

One backward step and one Adam step on the toy tables

Press Play to send the gradient back from the layer output to the tables. Switch the table learning rate.

Table learning rate
The gradient splits into the 4 rows that the forward pass read; the other 56 rows get none. This is a sparse update. On its first step Adam moves each entry by exactly the learning rate against the sign of its gradient. Exact numbers from the source (base learning rate 10⁻³).

The paper trains the tables with Adam, a learning rate 5 times the base rate, and no weight decay. The source gives the reasons:

  • 5× learning rate. Rare n-grams appear seldom, so their rows get few updates. A larger step lets them learn in fewer visits.
  • No weight decay. Weight decay makes all weights a little smaller at each step. A rare row would shrink towards zero between its visits and forget what it learned.
  • Zero-initialized convolution. At step 0 Engram adds only a gated value, so the backbone trains normally and Engram’s contribution grows slowly.

How much of the budget goes to memory

The paper fixes the total number of parameters and the FLOPs per token. Then it moves a fraction 1−ρ1 - \rho of the sparse parameters from MoE experts to Engram tables: PMoE=ρPsparseP_\text{MoE} = \rho P_\text{sparse} and PEngram=(1−ρ)PsparseP_\text{Engram} = (1-\rho) P_\text{sparse}. The validation loss traces a U shape. No memory is not the best; all memory is not the best either.

playground

The U-shaped allocation law

Move ρ from 100% (pure MoE) to the left.

MoE experts Engram tables

Only the two dots are measured: pure MoE at 1.7248 and the best split at 1.7109, with ρ ≈ 75–80%. The dashed curve shows the shape only. Too much memory leaves too little computation.

The main comparison in the paper is at equal parameters and equal FLOPs. Engram-27B has the same total size (26.7B) and the same active parameters per token (3.8B) as MoE-27B, but 55 routed experts instead of 72. The freed parameters become 5.7B of Engram tables. Engram-40B has 18.5B of Engram tables.

BenchmarkMoE-27BEngram-27BEngram-40B
MMLU57.460.460.6
BBH50.955.957.5
HumanEval37.840.838.4

The largest gain is on BBH, a reasoning benchmark, not only on knowledge tasks. Two tests in the paper explain why.

  • Switch Engram off at inference. Factual knowledge falls to 29–44% of its score, but reading comprehension keeps 81–93%. The tables hold static knowledge (facts, names, fixed phrases); the backbone does in-context reasoning.
  • Effective depth. A CKA comparison of internal representations finds that layer 5 of Engram-27B is most similar to layer 12 of MoE-27B. The Engram model is about 7 layers ahead, so more of its depth is free for reasoning.

Inference: the address is known before layer 1

For MoE, the router needs hth_t, so the model knows which experts to use only when the layer runs. For Engram, the row numbers depend only on token IDs, so they are known before the first layer runs. This allows two things:

  • Offload. Keep the large tables in cheap host DRAM, not in GPU memory (HBM).
  • Prefetch. Start to copy the needed rows to the GPU at once, while the GPU computes the layers below the Engram layer.

animation

Prefetch hides the copy behind the layers below

Press Play. Click a layer to add or remove Engram there (up to 4). Switch the address to Hidden h, and move the copy time.

Address from
layer with Engram (click a layer to toggle) copy of rows over PCIe GPU waits
forward time
GPU wait
layers below first Engram

With addresses from token IDs, every copy starts at time 0: the copy for layer 15 has 15 units of cover, layer 2 has 2, and layer 1 has only 1. With an address that needs h, the copy starts only when the layer runs, and the GPU waits. Time units are toy (one layer = 1 unit).

This also explains the choice of layers 2 and 15. Layer 1 is too early: there is no time to prefetch, and hth_t has read almost no context, so the gate cannot judge the memory. A layer that is too late loses the benefit, because the early layers must again rebuild the patterns. Layer 2 gives early knowledge and a hidden state that is good enough for the gate. Layer 15 gives a second injection with a long prefetch window.

During prefill (reading the prompt) the model hashes all positions at once and reads all rows with one batched gather. During decode (one new token at a time) it needs only the new token and the 2 before it, and reads 2×8=162 \times 8 = 16 rows per Engram layer. Engram needs no extra cache, unlike the KV cache of attention, because its window is only 3 tokens.

calculator

Bytes that one decode step reads

Change the batch, the number of heads and the row width.

Number format
rows / token / layer
bytes / token / layer
read per decode step
copy time at this bandwidth
With the demo configuration: 16 rows × 64 numbers × 2 bytes = 2,048 bytes per token per layer. Two layers and a batch of 256 read about 1 MB per step, about 16 µs over a 64 GB/s PCIe 5 link (the source's own estimate). The tables hold thousands of times more.

The paper measures the real cost: with a 100B-parameter Engram table in host DRAM, the throughput loss is only 2.8% on an 8B backbone. N-grams follow a Zipf distribution (a few items are very frequent; most are rare), so a memory hierarchy fits well: the frequent rows (“of the”, “in a”) can stay in HBM, medium-frequency rows in host DRAM, and the long tail on NVMe SSD.

What Engram is not

  • Not a classic n-gram language model. A classic n-gram model counts n-grams and predicts from the counts. Engram stores learned vectors, and it is one part of a neural model trained with gradients.
  • Not retrieval (RAG). RAG searches an external text database at run time. Engram’s tables are model parameters, and the lookup is a fixed hash, not a search.
  • Not a limit on context. Engram sees only 3 tokens, but attention still sees the full context, and the gate uses hth_t, which carries it.