Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Engram,
explained.
Ask a model to find one fact buried in a million tokens and attention has to weigh all million to answer — and the longer the haystack, the more the needle gets drowned out. Engram gives the model a different faculty: a learned memory table, read by hashing the last few tokens (filled during pretraining and fixed at inference). Each lookup costs the same constant time, and it doesn't matter whether the context is a page or a library. Best of all, the model only reaches for it when it needs to.
Contents 14 sections
The delta The recall wall: attention dilutes A memory indexed by the last few tokens Conditional: a gate decides how much to trust the lookup Why long-context recall improves: 84 → 97 Why it matters How it works The math The evidence Since then Solve it yourself Questions Check yourself Where this sitsWhat changes against attention: retrieval instead of competition
The whole ladder below this rung treats long context as a cost problem. This rung names a quality problem that persists even when you can afford the compute, and it follows from what softmax does. Attention distributes a fixed total weight across every position, so as the context grows, the one passage that matters is competing against more and more irrelevant ones. Its share of the attention mass is diluted by their number — which is why recall of a specific buried fact degrades with length even in a model whose window nominally covers it.
The change is to add a path that is looked up rather than computed. Alongside attention and the feed-forward layers, the model gets a very large table of learned embeddings, indexed by hashes of the last few tokens. Each lookup costs the same whatever the length of the context, and a context-aware gate decides how much of what comes back to use. The memory is conditional in the way mixture-of-experts computation is conditional: a big store of parameters, of which each position touches only a sliver.
Stated in the units this ladder is argued on, the claim is about the recall metric rather than about throughput: on needle-in-a-haystack retrieval the reported move is from the mid-eighties to the high nineties. That is the same weakness rung 4 admits — a fixed state cannot hold arbitrary detail — attacked from the opposite side. Mamba compresses and hopes the summary kept the right thing; this gives the model a lookup for the local, static patterns it would otherwise have to rebuild in its early layers, and spends the freed capacity on everything else.
The recall wall: attention dilutes
Softmax attention answers a query by spreading a fixed budget of probability across every token it can see. That's fine for a short context. But the needle-in-a-haystack test — hide one crucial fact in a long document and ask for it — exposes the flaw: as the haystack grows, the needle's slice of the attention budget shrinks, and it can get washed out by thousands of irrelevant tokens.
Two costs in one: you pay O(n) to scan everything, and the answer quality drops with length. Engram attacks the second one head-on.
A memory indexed by the last few tokens
Engram adds a conditional memory: a very large table of learned embedding vectors that the model reads by hashing N-grams of the most recent tokens. At each position the last few token IDs — first normalized so that equivalent tokens share an ID — are hashed into slots of the table, using several independent hash functions per N-gram order so that two unrelated N-grams rarely collide in every one of them. The retrieved vectors are combined and passed on.
several heads per order
read slots
O(1) per position
The table is trained with the rest of the model during pre-training; nothing is written into it while the model runs. Because the address comes from token IDs alone, a lookup costs the same at position 10 as at position 100,000, and it is known before the layer that needs it executes — which is what lets the tables sit in host memory and be prefetched instead of occupying accelerator memory.
Conditional: a gate decides how much to trust the lookup
A hashed N-gram is a blunt key. The same three tokens mean different things in different sentences, and a collision can put an unrelated pattern in the same slot. So the retrieved memory is not added to the model blindly: the current hidden state acts as a query against it, and a context-aware gate scales the contribution down when the memory disagrees with what the model has already worked out from the context.
"Conditional memory" is the paper's name for this, by analogy with mixture-of-experts. MoE adds capacity that is computed sparsely — each token runs a few experts out of many. Engram adds capacity that is looked up sparsely — each position reads a few slots out of a huge table. The paper treats the split of a fixed parameter budget between the two as a design choice to measure, not to assume.
A lot of what early Transformer layers do is reconstruct local, static knowledge — names, idioms, multi-token entities. A lookup can supply that directly, which frees the layers and the attention budget for longer-range reasoning.
Why long-context recall improves: 84 → 97
The long-context gain is indirect, and it is worth being precise about it. The model does not store the needle in the table at inference time — the table is fixed after training. The argument is that once local pattern-reconstruction is offloaded to the lookup, attention has more of its capacity left for finding and using distant context. DeepSeek reports multi-query needle-in-a-haystack accuracy climbing from about 84.2 to 97 with Engram, alongside gains on knowledge, reasoning, code and math benchmarks at matched compute.
What a single retrieval benchmark cannot show is how much of that comes from the memory itself versus from the extra parameters it adds; that is the comparison to look for in independent replications.
Why it matters
Engram is part of a clear shift: stop forcing every piece of knowledge a model holds to be recomputed through stacks of matrix multiplies, and give the model a cheap way to look up what is static. It sits in a line of memory-layer ideas — product-key memories, hashed n-gram embeddings — but pairs the lookup with a context gate and studies it as a second sparsity axis next to mixture-of-experts.
The broader lesson is that "long context" is two problems wearing one name: the cost of a big window and the reliability of what the model does inside it. Sparse and linear attention attack the first; freeing capacity, as Engram does, is one way to attack the second. Compare it with in-context memory designs such as Titans, which write to a memory while the model runs, and with MemGPT, which manages memory outside the model entirely.
How DeepSeek Engram looks up hashed N-gram memory, step by step
Engram is the conditional-memory module described in DeepSeek's 2026 technical report. It gives a transformer a very large table of learned embeddings that is read by lookup instead of by computation. At each position the last few tokens are hashed into the table, and a gate driven by the model's own hidden state decides how much of what comes back to use. The table is learned in pretraining; nothing is written into it at inference time.
- Form the suffix N-grams. At position t, take the N-grams that end at t: the last two tokens, the last three, and so on up to a small maximum order. Per the report, token IDs are first normalized so that surface variants of the same word share entries.
- Hash each N-gram with several heads. A table with a row for every possible N-gram would be astronomically large, so each N-gram order has K independent hash functions, each mapping the N-gram to a row of its own embedding table. Two N-grams can collide in one head; colliding in all K heads is very unlikely.
- Look up and concatenate. The rows from every head and every order are concatenated into one memory vector et. The cost is a fixed number of row reads per token whatever the table's size: O(1) in the number of stored parameters, and deterministic.
- Gate it by context. The same N-gram means different things in different contexts, and a hashed row may be a collision. So et is projected to a key and a value, and a scalar gate, a sigmoid of the scaled dot product between the normalized hidden state and the normalized key, scales the value before it joins the residual stream. The hidden state is the query: when the retrieved memory does not fit the context, the gate closes.
- Place it at a few layers. Per the report, the module sits at a small number of layers rather than all of them, inside a model that also uses mixture-of-experts layers.
- Train it with the model. The tables are ordinary parameters, learned end to end by the language-modeling loss during pretraining. Each token updates only the few rows it read, so a huge table adds parameters without adding much computation.
- Serve it from host memory. The row indices depend only on the input token IDs, so every row a forward pass will need is known before it reaches the Engram layers. Those rows can be fetched from CPU memory while earlier layers run, so the table does not have to fit in GPU memory. The report states that the throughput cost of doing this is small.
Why it is called conditional memory
Mixture-of-experts is conditional computation: a huge pool of parameters, of which each token activates only a few experts. Engram is presented as a second axis of the same kind of sparsity, conditional memory: a huge table of which each token reads only a few rows, selected by its local N-gram context. The report treats the two as complementary and studies how to split a fixed parameter budget between them.
What it is not
Engram is not an associative store that writes facts during inference, and it is not retrieval over the document in the context window. Its keys are local token patterns, so it holds what pretraining learned about those patterns, such as names and fixed phrases, and hands it to every position in constant time, which spares the network from rebuilding that knowledge layer by layer.
Engram hashed lookup and context gate
et = concatn,k En,k[ zt,n,k ]
kt = WKet, vt = WVet, αt = σ( ĥt · k̂t / √d )
ut = αt vt, added to the residual stream
xt−n+1, …, xt— the suffix N-gram of order n ending at position t, as normalized token IDs.φn,k— hash head k for order n: a fixed, deterministic function of the token IDs alone.En,k[z]— row z of that head's embedding table, a trained parameter.et— the memory vector: every head's row, for every order, concatenated.ĥt, k̂t— the normalized hidden state at this layer and the normalized memory key; the hidden state is the query.αt— a scalar gate between 0 and 1: how much of the memory this context accepts.
At the extremes: α near 0 means the context rejects what was retrieved, the right outcome for a hash collision or a phrase used in an unusual sense; α near 1 means the memory is taken in full. With K = 1 a single collision corrupts the vector, while with several heads an N-gram is only fully confused with another if they collide in every head. A small table makes collisions common and leaves more work to the gate; a very large one is what pushes the tables into host memory.
What DeepSeek reported for Engram
All results below are as reported by DeepSeek in the Engram technical report, and none had been independently reproduced when it appeared. The comparisons hold total parameters and per-token compute fixed, so Engram is tested as a way to spend sparse parameters, not as free extra capacity.
| Comparison in the report | Reported outcome |
|---|---|
| Engram model against an MoE-only model with the same total parameters and FLOPs per token | lower loss, and gains across knowledge, reasoning, code and math benchmarks |
| Splitting a fixed sparse budget between experts and memory | loss lowest at an intermediate split, worse with all experts or mostly memory |
| Needle-in-a-haystack retrieval | from about 84 to about 97 |
| Tables held in host memory and prefetched | small throughput penalty |
The allocation result is the report's central argument. If memory and experts were interchangeable, the best split would sit at one end; a minimum in the middle says each does something the other does poorly, with experts for computation that depends on context and memory for static local patterns.
The long-context result needs its mechanism stated correctly. Engram's keys are local N-grams at the current position, so it cannot fetch a fact planted thousands of tokens earlier by its content. The report's explanation is indirect: by taking over the reconstruction of local, static patterns, the memory frees attention and early layers for global context, and the report presents layer-by-layer analyses suggesting the network behaves as if it were deeper.
The open questions are the ones that separate a mechanism from a benchmark result: whether the gains hold under independent replication and at other scales, how much of the needle-in-a-haystack gain survives on tasks whose answers are not copyable spans, and how collisions and gating behave in languages and domains that pretraining covered thinly.
Where this stands, and what would settle it
Very recent, so the honest summary is that the diagnosis is stronger than the verdict. The diagnosis — that softmax dilution is a distinct failure from compute cost, and that a benchmark measuring average next-token quality will not reveal it — is clearly right and clarifies why the five rungs below disagree: three of them were solving cost and two were solving capacity, and dilution is neither.
What a single retrieval benchmark cannot tell you is whether the memory helps when the useful fact is not a verbatim string. Needle-in-a-haystack tasks reward exact lookup, which is the regime an addressed memory is best at by construction; the harder and more valuable question is multi-hop reasoning over several buried facts, and aggregation over many passages, where what to look up is not given. A mechanism can move a haystack score a long way and leave that untouched.
What would settle it: independent evaluation on tasks whose answers are not copyable spans, and the serving numbers — a conditional memory's value depends entirely on how often the condition fires and what a miss costs, and that is an engineering measurement rather than a claim. Worth reading this rung primarily for the framing: context length and context usability are different quantities, and most reported context windows are measurements of the first.
O(1) recall that doesn't care how big the haystack is
This toy keeps only Engram's cost model: a dictionary stands in for the hashed N-gram table, so a lookup costs one operation however long the context is, while a linear scan pays n and grows with it. Build a store over a hundred-thousand-token haystack, look up a key, and watch the cost stay flat. Then gate it: only gated positions touch the memory at all. (The real table is learned during pre-training and indexed by recent tokens — it does not store facts written at run time.) Build a memory over a hundred-thousand-token haystack, drop in a needle, and watch the lookup find it at the same cost as if the haystack were empty. Then gate it: only the tokens that actually need a recall touch the memory at all.
Write the body of recall_plan. Everything else in the file is
already written; this is the function the paper is about. Press ▶ Run to check it against
the 7 assertions below — they start red.
- A keyed write is retrievable by its key
- A keyed lookup is O(1) — one operation, always
- A linear scan costs n and grows with context
- NIAH: the needle is found at the same O(1) cost regardless of haystack size
- Conditional gate: only tokens that need recall touch the memory
- Recall_plan charges one keyed op per gated position, and a scan at every position
- With no gate open, nothing touches the memory at all
Questions people ask about Engram
How does DeepSeek Engram work?
Engram adds a large learned memory that is read by lookup. At each position in the layers where it is used, the module takes the N-grams that end at the current token, such as the last two and last three tokens, and hashes each one with several independent hash functions into separate embedding tables. The retrieved rows are concatenated into a memory vector. A gate then compares the model's current hidden state with a key projected from that vector and scales the memory's value by a sigmoid of their similarity before adding it to the residual stream. The tables are trained with the rest of the model during pretraining, and the lookup costs the same whatever the tables' size.
What does conditional memory mean in DeepSeek's Engram?
It is the memory counterpart of conditional computation. A mixture-of-experts layer holds many experts but activates only a few per token, so total parameters grow without per-token compute growing in step. Engram does the same with memory: a very large embedding table of which each token reads only a few rows, chosen by its local N-gram context. The condition is the token pattern itself, not a separate decision about whether to look something up: at the layers where Engram sits, every position performs its lookup, and the context gate then decides how much of the result to use. The report presents conditional memory as a new, complementary axis of sparsity.
How does Engram compare with mixture-of-experts?
The report treats them as two ways to spend sparse parameters and compares them at equal total parameters and equal compute per token. Experts are routed by the hidden state and compute something new for each context; Engram rows are addressed by token IDs and supply stored knowledge about local patterns. When a fixed budget is split between the two, the report finds the loss is lowest at an intermediate split, not at either extreme, and that the Engram-augmented model beat the MoE-only model on knowledge, reasoning, code and math benchmarks. A practical difference is serving: expert choice is known only after routing, while Engram's rows are known from the input, so they can be prefetched.
Why would an N-gram memory improve long-context retrieval?
Not by storing the needle. Engram's keys are the few tokens before the current position, so it has no way to look up a fact from far back in the context by its content. DeepSeek's report states that needle-in-a-haystack accuracy rose from about 84 to about 97, and explains the gain indirectly: by handling the reconstruction of names, fixed phrases and other static local patterns through cheap lookups, Engram frees the attention layers and early layers for the global work of tracking context, and the report's layer-wise analyses suggest the model behaves as if it were deeper. That explanation is the report's own, and the result has not been independently confirmed.
Can Engram's memory tables be stored in CPU memory?
Yes, and the report presents this as a key advantage. Because the rows an Engram layer reads are determined by hashing the input token IDs, the system knows exactly which rows a forward pass will need before the computation reaches those layers. It can fetch them from host memory over the interconnect while the earlier layers are still running, hiding most of the transfer. That lets the tables grow far beyond GPU memory. The report states the throughput penalty of offloading is small. Mixture-of-experts weights cannot be prefetched the same way, because which experts a token needs depends on the hidden state computed just before routing.
Is Engram the same as Titans or retrieval-augmented generation?
No. Titans updates a neural memory by gradient descent while it reads, so its memory holds what this particular input contained. Retrieval-augmented generation searches an external document store at query time and puts passages into the context. Engram does neither: its tables are learned during pretraining and fixed at inference, nothing is written while it reads, and its addresses are local token patterns rather than a search over documents or the context. The closest relatives are hashed N-gram embeddings and embedding-table approaches to adding parameters cheaply, combined with a context gate. It complements attention and mixture-of-experts rather than replacing either.
4 questions to test what you just read
Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.
Suppose an Engram layer uses 2-grams and 3-grams with 8 hash heads each. How many table rows does one position read, and how does that change if every table is made ten times larger?
Show answer
2 orders × 8 heads = 16 rows per position. Making the tables ten times larger leaves it at 16: the cost is a fixed number of lookups, O(1) in table size. Only memory capacity grows, which is why the tables can be offloaded to host memory.
With hash tables of about one million rows each and 4 heads, what is the chance that two given N-grams collide in one head, and in all four?
Show answer
One head: about 1 in 10⁶. All four, if the heads hash independently: (10⁻⁶)⁴ = 10⁻²⁴. A collision in one head garbles a quarter of the memory vector; the other heads still carry the right rows, and the gate can discount the mixture.
If the scaled similarity between the hidden state and the memory key is −3 in one context and +2 in another, how much of the memory does each context take in?
Show answer
σ(−3) ≈ 0.047, so about 5% of the memory passes: the context rejects it. σ(2) ≈ 0.88, so most of it passes. This is how the same N-gram row can help in one sentence and be ignored in another.
Why can Engram rows be prefetched from CPU memory before a layer runs, while the experts a mixture-of-experts layer will need cannot?
Show answer
Engram's row indices are hashes of the input token IDs, known as soon as the input is. An MoE router picks experts from the hidden state, which exists only after the layers below it have run. Deterministic addressing is what turns a huge table into something that can live off the GPU.
Making the context long
Attention costs quadratic in sequence length. Six attempts to escape that, ending with two 2026 papers that give the model a memory instead.
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Paper Breakdowns
- Attention Is All You NeedThe paper that introduced the Transformer — the architecture underneath GPT, BERT, Claude, and Gemini. Self-attention, Query/Key/Value, multi-head attention, positional encoding, and the real BLEU results, explained in depth with analogies and animated visuals, not just equations.Read →
- BERTThe paper that made "pre-train once, fine-tune anywhere" the default for NLP. Bidirectional context, masked language modeling, next-sentence prediction, the [CLS]/[SEP] tokens, and the GLUE sweep — explained with analogies, not just equations.Read →
- Chain-of-Thought PromptingShow a model a few worked examples with their reasoning and it starts solving problems it used to fail. Why reasoning emerges only at scale, the GSM8K jump, zero-shot "Let's think step by step", and how CoT seeded modern reasoning models.Read →
- LoRAThe paper that made fine-tuning affordable. Freeze the giant pretrained model and train two tiny low-rank matrices instead — up to 10,000x fewer trainable parameters, no extra inference latency, and swappable per-task adapters. The road to QLoRA and PEFT.Read →
- Direct Preference OptimizationRLHF without the RL. Align a model to human preference pairs with one simple classification-style loss — no separate reward model, no unstable reinforcement learning. Why "your LM is secretly a reward model", and how DPO became the default alignment method.Read →
- ChinchillaThe compute-optimal scaling law that said models were too big. Parameters and training tokens should scale together — ~20 tokens per parameter — so a 70B model trained on 1.4T tokens beat the 280B giants. Why every model since trains on trillions of tokens.Read →