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.
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.
| MoE | Engram | |
|---|---|---|
| Sparse unit | expert FFN | table row |
| Selected by | learned router on | fixed hash of the last 2–3 token IDs |
| Selection known | when the layer runs | before the model runs |
| Main cost | FLOPs and HBM | memory bandwidth; host RAM is acceptable |
| Good for | composition, reasoning | names, 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 , which feeds the gate, and the raw token IDs, which feed the hash.
Part A: from tokens to row numbers
For each position 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.
- 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. - Build the suffix n-grams. At position , take the 2-gram and the 3-gram , where is a canonical ID. A suffix n-gram ends at , 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.
- Hash. There are about 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).
- Read and concatenate. Read row of each table and join the rows end to end into the memory vector . This step does no multiplication at all.
Each hash head has its own table with a prime number of rows . 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.
At (“great”) the arithmetic is: , , . XOR gives the 2-gram mix 29524 and the 3-gram mix 30647. The rows are , , and , so
Different odd multipliers make the order of the tokens matter: (the, great) and (great, the) give different mix values. Each token reads 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 . That is row 0 in the table, the same row as (the, great). In the 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 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.
Part B: the gate decides how much memory enters
Two learned matrices of size turn the memory vector into a key and a value: and . The value is what the memory says. The key is what the memory is about, and the gate compares it with the context:
The hidden state 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, and . With a hidden state that agrees, , the normalized dot product is 3.999, and . With a hidden state that points the other way, , and , 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.
Two details from the source. First, the official code applies a signed square root before the sigmoid, , 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 parallel copies of the residual stream. Engram then computes 4 gates with 4 separate key matrices, but one shared table and one shared .
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 reads , , and :
Finally , 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 . The gradient passes through the gate, then through , and arrives at the 8 numbers of . The path through the gate is almost zero here, because and are almost parallel: the dot product is near its maximum , 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.
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 of the sparse parameters from MoE experts to Engram tables: and . 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.
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.
| Benchmark | MoE-27B | Engram-27B | Engram-40B |
|---|---|---|---|
| MMLU | 57.4 | 60.4 | 60.6 |
| BBH | 50.9 | 55.9 | 57.5 |
| HumanEval | 37.8 | 40.8 | 38.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 , 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.
This also explains the choice of layers 2 and 15. Layer 1 is too early: there is no time to prefetch, and 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 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.
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 , which carries it.