---
title: "Memory Layers at Scale — paper by Berges et al. (2024)"
description: "Memory Layers at Scale tests whether trainable key–value lookups can improve factual recall and other language tasks at nearly fixed compute."
canonical: "https://research.elamur.ai/free/en/papers/berges-2024-memory-layers-scale/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/) · [Constitution](https://md.constitution.elamur.ai/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/berges-2024-memory-layers-scale/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2024](https://md.research.elamur.ai/free/en/papers/2024/) / Memory Layers at Scale

# Memory Layers at Scale

Paper · 2024 · Vincent-Pierre Berges, Barlas Oğuz, Daniel Haziza et al.

**Authors:** [Vincent-Pierre Berges](https://md.research.elamur.ai/free/en/authors/vincent-pierre-berges/), [Barlas Oğuz](https://md.research.elamur.ai/free/en/authors/barlas-oguz/), [Daniel Haziza](https://md.research.elamur.ai/free/en/authors/daniel-haziza/), [Wen-tau Yih](https://md.research.elamur.ai/free/en/authors/wen-tau-yih/), [Luke Zettlemoyer](https://md.research.elamur.ai/free/en/authors/luke-zettlemoyer/) and Ghosh, Gargi · **Year:** 2024 · **Venue:** arXiv (Cornell University) · **Licence:** [arXiv — non-exclusive license to distribute](http://arxiv.org/licenses/nonexclusive-distrib/1.0/)

[**1** citations OpenAlex, 2026-10-14](https://openalex.org/works?filter=cites:W4405432939) · Cited by **4** papers in our library of more than 163,000 papers whose bibliographies we read · [arXiv (Cornell University)](https://openalex.org/S4306400194) · [licence](http://arxiv.org/licenses/nonexclusive-distrib/1.0/)

- [PDF](https://arxiv.org/pdf/2412.09764)
- [arXiv 2412.09764](https://arxiv.org/abs/2412.09764)
- [OpenAlex](https://openalex.org/W4405432939)

Citations: OpenAlex, 2026-10-14.

## Summary

A language system needs to do different kinds of work to answer a question. It may have to follow the wording, connect the question to the right subject, and recall a fact such as the capital of a country. In a dense network, enlarging the weights that support this work also increases the arithmetic needed to use them. Memory Layers at Scale asks whether the network can get extra room for learned associations by looking up a small number of entries in a large table. The authors replace selected feed-forward blocks in a [transformer](https://md.research.elamur.ai/free/en/concepts/transformer/) with trainable memory. Each token supplies a query, the closest learned keys determine which entries to read, and the layer combines their values before passing the result onward.

The table grows without requiring the network to read all of its values for every token. The authors build searchable keys from pairs of shorter vectors and divide the value vectors across GPUs. Their improved design, Memory+, lets several layers query the same table and uses the current token representation to control how much of the retrieved information passes through. This arrangement gives the network several opportunities to use the memory while keeping the size of the shared table fixed. The authors’ experiments cover base networks with parameter counts ranging from 134 million to 8 billion, and the experiment with the largest memory uses 128 billion memory parameters.

The clearest gains come on short factual [question answering](https://md.research.elamur.ai/free/en/concepts/question-answering/). In comparisons using the same base architecture, Memory+ improves on the dense baseline and on the parameter-matched mixture-of-experts baseline, with only small differences in floating-point work. It also improves on a simpler memory layer and on the related PEER design in the reported comparisons. In the memory-size sweep, a 1.3b base with 128 billion memory parameters approaches a Llama2 7B reference on factual questions. The larger dense reference was trained on 2x more tokens with 10x more FLOPs. At the 8B base scale, the authors also report gains on coding and broader knowledge benchmarks.

The results distinguish arithmetic from the cost of moving data. A query can use only a small part of the table and still ask the hardware to fetch values from widely separated locations. The authors obtain a faster lookup by changing how those reads and their gradients are handled, and they identify production efficiency as an open engineering problem. Their evidence about factuality concerns short answers. It establishes that added capacity helps on the tested questions and leaves open how the network represents individual facts, how dependable its longer responses become, and whether sparsity changes what it retains over time.

## Deep dive: Memory Layers at Scale

Memory Layers at Scale tests whether trainable key–value lookups can improve factual recall and other language tasks at nearly fixed compute. · about 35 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### Giving stored associations room to grow

A system trained to predict text can later answer questions about information it encountered during training. The paper starts from earlier findings that this ability improves as systems grow. A recurring example is an association between an entity and a familiar attribute, such as a celebrity and a birthday. The surrounding text can express this association in different ways, but a successful answer must make the same underlying fact available when a relevant question is asked. The authors ask whether the architecture used to learn a large range of linguistic functions is also the most economical place to store these recurring associations. They situate the question in earlier work on [large language models](https://md.research.elamur.ai/free/en/concepts/large-language-models/), including [Language Models are Few-Shot Learners](https://md.research.elamur.ai/free/en/papers/brown-2020-language-models-few-shot-learners/).

A feed-forward network processes a token by applying learned transformations to its current representation. In a dense feed-forward block, each input ordinarily goes through the same weight matrices. Making those transformations larger can increase the functions they can represent, with an accompanying increase in the calculation per input. A sufficiently expressive feed-forward network can represent associations. The design question is whether every input needs access to so much of the same calculation when each will call for a small fraction of the information the system has learned.

The paper studies that question by changing where some parameters live. A table with a large collection of learned values can make a small subset available to each input. The size of the stored collection and the size of an individual read are then separate design choices. A larger collection may give training more places to put information, while a small read limits the arithmetic used to turn a query into an output. To realize that separation in practice, the system must also find the relevant subset efficiently. An architecture that reads few values but compares a query with every available key would still have a search cost that rises with the full table.

The authors keep dense processing in the architecture. A learned association needs an input representation suitable for retrieving it, and the resulting vector still has to contribute to a useful prediction. The paper's change concerns selected points in an existing network. At those points, a token can use its contextual representation to consult stored values. Other layers continue to provide transformations that act across the representation. This makes the effect of the intervention measurable. It also makes the amount and location of the remaining dense processing part of the design.

#### Earlier ways to separate parameters from arithmetic

Previous studies of [scaling laws](https://md.research.elamur.ai/free/en/concepts/scaling-laws/) describe how performance varies with the amount of training data, computation, and learned weights. The paper cites [Scaling Laws for Neural Language Models](https://md.research.elamur.ai/free/en/papers/kaplan-2020-scaling-laws-neural-language-models/) for the regular behavior observed across dense architectures with different depths and widths. Such studies typically emphasize how well a system predicts text, measured on training data or on held-out data. The probability of the correct text gives a score even when that text would lose to a competing prediction. A downstream benchmark may instead count success only when the final answer meets a threshold. The paper draws on earlier work to explain why a smoothly improving probability score and a sharply changing benchmark score can coexist.

Mixture-of-experts provides an established case in which parameter count and computation can grow at different rates. An expert is a feed-forward component with its own learned weights. A routing rule chooses which experts take part for a given input. Adding experts expands the pool of parameters and need not proportionally expand the path activated for each input. The paper describes this technique as easier to scale with existing hardware than sparse memory, in part because an activated expert still carries out the familiar dense operations. Its success motivates the question of whether a more direct retrieval operation can make better use of a comparable parameter budget on some tasks.

Trainable memory itself predates this paper. The authors trace it through memory networks, their end-to-end trainable extensions, and Neural Turing Machines, which used trainable memory as part of a larger system. Work on product keys addressed the difficulty of finding entries in a growing table. Rather than maintaining an independently searchable full vector for each entry, product-key lookup uses combinations of vectors from smaller sets. Memory Layers at Scale takes that approach as its starting point and asks what changes are needed to train and use much larger memories in a contemporary transformer.

The paper also describes PEER as a connection between product-key memory and expert routing. PEER uses an address to retrieve vectors that form a rank-one matrix. Combining several of these matrices gives a feed-forward transformation assembled for the current input. A conventional memory read uses its hits to assemble an output vector. PEER uses its hits to assemble part of an operation that will act on the input. Both use finely divided capacity, which makes PEER a closer comparison for the architecture than a baseline made up of large feed-forward experts.

#### The difference between a learned memory and a source of evidence

Question answering provides a direct way to test whether a network can use associations learned during pretraining. The paper relates this use of factual questions to earlier open-domain work, including [Reading Wikipedia to Answer Open-Domain Questions](https://md.research.elamur.ai/free/en/papers/chen-2017-reading-wikipedia-answer-open-domain/). The questions can cover subjects across a broad domain, and short answers make it possible to check the response against a reference. The paper distinguishes the ability to answer such questions from the wider issue of hallucination, in which a system produces unsupported or incorrect material. Earlier work surveyed the range of circumstances in which such failures arise. [Survey of Hallucination in Natural Language Generation](https://md.research.elamur.ai/free/en/papers/ji-2022-survey-hallucination-natural-language-generation/)

A different line of work supplies material at the time a question is asked. In [retrieval-augmented generation](https://md.research.elamur.ai/free/en/concepts/retrieval-augmented-generation/), a system searches for relevant material and uses it to help produce its response. The paper cites this as an established route to improving factuality, along with work on learning to find relevant passages. The memory used in this study lives in the network's trained weights. A key selects a vector learned through training, and that vector becomes part of the network's internal representation. The memory therefore addresses how the system acquires and uses information in its parameters. [Dense Passage Retrieval for Open-Domain Question Answering](https://md.research.elamur.ai/free/en/papers/karpukhin-2020-dense-passage-retrieval-open-domain/)

That distinction explains why the paper frames its central measurement around correct short answers. A memory read can be helpful even if none of its entries corresponds to a passage that a reader could inspect. The architecture is designed to discover associations through the language training objective. Its main test is whether expanding and changing that internal capacity improves what the network can predict or answer under comparable training conditions.

### The method, step by step

#### From a token to a memory read

The authors begin with a Llama-style transformer. Its attention blocks let a token's representation depend on other positions, so the representation reaching a feed-forward block already carries context. The authors substitute a memory operation for the feed-forward block at chosen depths. The memory operation reads separately for each token, following the position-by-position pattern of the feed-forward operation it replaces. A token can produce a different query in a different sentence because its representation has already changed with the context.

A memory entry has a key and a value. The key is a vector used to decide when the entry should be read. The value is the vector returned when the entry is used. A query is a vector derived from the token representation, and the layer compares it with the keys. The best-matching keys supply a short list of addresses. The layer gives values at those addresses weights derived from their scores, then adds the weighted values to form an output. Thus the table can contain different values for related contexts, and a token can use a combination of them.

Consider the paper's example of retrieving an association between a country and its capital. In this architecture, the words asking for the capital can help shape the token's contextual representation before a lookup. That query can score learned keys differently from a query about the same country in another context. The retrieved vectors can then help the rest of the network assign probability to the answer. This description gives the role of each operation. The architecture itself puts no label on an address identifying which country, relation, or fact it represents. The training signal comes from text prediction and can reward several cooperating addresses for a useful result.

The initial selection and the subsequent weighting perform different jobs. The selection step bounds the number of values that have to be read. The weighting step gives a stronger match more influence within that set while permitting several retrieved vectors to contribute. This resembles attention in the way it scores keys and combines values. Ordinary attention in the paper's comparison forms keys and values from activations. Memory uses keys and values held in the learned parameters, allowing the same collection of entries to serve many different inputs throughout training and evaluation. The paper connects the score-and-combine operation to [Neural Machine Translation by Jointly Learning to Align and Translate](https://md.research.elamur.ai/free/en/papers/bahdanau-2014-neural-machine-translation-jointly-learning/).

How Memory+ processes a token The steps in order.

#### The lookup in mathematical form

The paper first describes memory with a full matrix of keys. This gives a direct account of the computation before the authors introduce the more efficient search. The query and each key have a common width. An inner product between them gives a score, and the layer retains the addresses of the highest-scoring keys.

```
I = SelectTopkIndices(Kq)
```

Here `q` is the query vector, `K` is the matrix whose rows are key vectors, and `Kq` denotes matrix–vector multiplication, yielding one score per row. `SelectTopkIndices` returns the addresses associated with the `k` largest scores. The letter `k` denotes the number of entries to select, and `I` collects those addresses. The equals sign assigns the result of the operation on the right to the quantity on the left.

```
s = Softmax(Kᵢq)
```

Here `s` is the vector of weights associated with the selected entries. `Kᵢ` denotes the rows of `K` indexed by the collection `I`, with the subscript `ᵢ` standing for that collection. Multiplying those rows by the same query `q` gives the selected keys' scores. `Softmax` converts these scores to positive weights that sum to one. The normalization takes place over the selected entries, so increasing a selected entry's relative score increases its share of the weighted read.

```
y = sVᵢ
```

Here `V` is the table of value vectors and `Vᵢ` is the matrix of its rows at the addresses in `I`. The order of those rows agrees with the order of the weights in `s`. The product `sVᵢ` forms a weighted sum across the rows, and `y` is the resulting output vector. In this basic formulation, `N` is the number of key–value entries, `n` is the width of each key and value, and `k` of the `N` rows participate. Each of the selected matrices has `k` rows of width `n`, while the output has width `n`. The paper later varies the widths of keys and values independently.

These equations expose where sparsity occurs. Once the selected addresses are known, there is no need to retrieve values at other addresses for this token. During training, the value gradients for that token are directed to the entries used in the read. Other tokens can contribute to some of the same entries, and all their contributions must be accumulated. The search problem remains in the first equation. Written with a full matrix `K`, it looks as though finding the best addresses requires computing every score. The product-key representation changes how the scores can be found.

#### Finding the best addresses without building every key

The authors consider the difficulty of using a nearest-neighbor search system whose index is built for a fixed set of vectors. Here the keys themselves are learned. An index built for earlier keys could become out of date as training changes their positions. The chosen product-key design works directly with the current vectors. It also reduces the number of elementary scores that have to be computed. The paper discusses the indexing alternative in connection with [Billion-scale similarity search with GPUs](https://md.research.elamur.ai/free/en/papers/johnson-2017-billion-scale-similarity-search-gpus/).

A product key has a left half from one set and a right half from another. The effective full key is the concatenation of the two halves. Each pair of half-key indices identifies one address in the value table. In the paper's notation, `K₁` and `K₂` are the two half-key matrices, each with the square root of `N` rows and half of the full key width `n` in each row. Pairing their rows gives `N` possible full keys. The paper's implementation can use those keys as a virtual set because the full score separates into scores for the two halves.

To perform the lookup, the current query `q` is split into `q₁` and `q₂`, each with half the full query width. The first half is compared with rows in `K₁` and the second with rows in `K₂`. For each side, the procedure retains the best `k` matches. A pair's full score is the sum of its two half-scores. The paper expresses the choice of the highest-scoring pair as follows.

```
argmax over i₁ ∈ I₁, i₂ ∈ I₂ of (s₁[i₁] + s₂[i₂])
```

Here `I₁` and `I₂` contain the retained half-key indices from the respective searches. The variables `i₁` and `i₂` are particular indices drawn from those collections, as indicated by `∈`. The quantities `s₁` and `s₂` give the scores of the retained half-keys on their respective sides, and square brackets denote the score associated with the specified index. The plus sign adds the scores, and `argmax` asks which pair attains the highest sum. A memory read needs the top `k` full addresses, so it ranks the pair scores to select that set. Those scores then supply the softmax weights for the associated values.

The additive score is what makes the shortlists effective. If a half-key lies below the retained group on its side, then pairing the same opposite half with each higher-scoring alternative gives pairs scoring at least as well. The search can therefore find highest-scoring combinations using the best halves. It still has to evaluate combinations from the two shortlists. Its economy comes from working with those lists and the two smaller key matrices, while the larger table of value vectors is accessed only at the selected addresses.

A consequence of the representation is that addresses sharing a half-key also share part of their score. The corresponding values remain separate entries. Learning one half-key can therefore change the chances of retrieving several values, and the other half of the query helps distinguish among them. Table capacity counts the available values, while key width and the two half-key sets determine how the query can differentiate their addresses. This difference matters in the ablations that trade off key size, value width, and the number of available values.

#### Sharing a pool across several transformer depths

The simplest experimental variant, Memory, uses a memory block at the middle feed-forward position. Memory+ consults the same pool at several positions. In the main fixed-memory experiments, the authors use 3 memory layers arranged around the middle. The distance between selected positions is a stride of 4 for the 134m base and a stride of 8 for the other bases in that series. In this usage, a stride describes how far apart the memory replacements sit in the transformer stack.

Sharing gives the table a common set of parameters even though the query entering each replacement can come from a different depth. A later read can therefore reflect transformations that occurred after an earlier read. Both reads can affect how the common entries are trained. The table's footprint depends on the shared collection, so adding sites at which it is used need not replicate all of its values. At each new site, however, the architecture gives up the dense feed-forward block that would have occupied the position. The experiment thus changes the balance of lookup and dense transformation as well as the number of times a token can consult the pool.

This is also why the position of a memory block is meaningful. A block near the middle sees representations produced by the preceding layers and leaves later layers to use its output. When there are several memory blocks, the spacing affects how much intervening processing can take place. The architecture does not prescribe what type of information a particular depth must retrieve. It creates distinct opportunities to consult the pool, and the authors use empirical comparisons to select a layout.

#### Controlling how the retrieved vector enters the network

A plain memory layer produces the weighted read `y`. Memory+ gives the input a second role after that read. A learned projection of the input yields a vector, which passes through a nonlinear function. The resulting vector acts as a gate on the retrieved representation. It can modulate each coordinate separately. This allows the same retrieved mixture to enter the next stage differently for different inputs, even when the inputs picked similar addresses.

```
output = (y ⊙ silu(xᵀ W₁))ᵀ W₂
```

In this expression, `output` is the block's result and `y` is the weighted memory read. The vector `x` is the input to the block. The superscript `ᵀ` indicates a transpose, and writing quantities next to each other indicates matrix multiplication in the paper's projection notation. `W₁` is the learned input projection, whose transformed coordinates provide the gate after `silu` is applied. The symbol `⊙` means element-by-element multiplication of that gate with `y`. Parentheses mark the combined vector, and `W₂` is the learned projection used to produce the final output.

```
silu(x) = x sigmoid(x)
```

Here `silu` is the nonlinearity and `x` denotes an input to the function, interpreted coordinate by coordinate when the input is a vector. The sigmoid maps each coordinate to a value between zero and one. The juxtaposition on the right means that the coordinate is multiplied by its own sigmoid value. The paper calls its gated architectural variant *swilu* in the experiment and ablation discussions. The expression above shows how the block uses `silu` to modulate the retrieved vector.

The gate and the address scores act at different stages. Address scores determine which stored vectors are brought into the mixture and how strongly each contributes to it. The gate operates on the resulting mixture and can alter individual coordinates. Consequently, the token participates both in finding information and in deciding how the read enters the subsequent network. The authors also apply query–key normalization when needed. They introduce it to alleviate training instability encountered with large memories, especially when the base network is small. It acts on the quantities used to compute match scores. The paper gives the gated output equation and describes when it uses normalization, without supplying a separate normalization equation for this implementation.

#### Moving and updating values across GPUs

Efficient address selection still leaves a large array of learned values. Training has to store those values and the associated optimizer state, which holds information used in parameter updates. The authors distribute the table across a group of GPUs by dividing each value vector along its embedding dimension. Each participating device holds a slice of the coordinates for the table's values. An address consequently refers to pieces of the same vector on the different devices. The implementation illustrates how [GPU parallel computing](https://md.research.elamur.ai/free/en/topics/gpu-parallel-computing/) supports a sparse layer whose main demands come from storing and moving data.

The devices in a memory group exchange the selected indices. Each device can then look up its part of the requested vectors and aggregate the contributions for its own dimension slice. After this local work, each device receives the aggregated pieces for the tokens it is responsible for. The exchange is arranged so that a device need only assemble the required outputs for its own tokens. This avoids materializing the full group's complete output on every device. The group for this operation is independent of those used to split the network, sequence processing, or other parts of execution.

The operation that fetches a set of learned vectors and reduces them to an output is implemented as a weighted EmbeddingBag. The layer's weights on the selected addresses determine the contribution of each fetched row. Once the addresses are available, applying these weights requires relatively little arithmetic compared with moving the vectors. The authors develop CUDA kernels suited to this pattern. Their forward implementation focuses on improving access to the value data. The main benchmark for this part of the implementation measures how quickly the GPU memory can supply the requested bytes.

Training also needs the backward operation. A gradient is the signal describing how a change to a quantity would affect the training objective. Several tokens can read the same row, so the backward computation may need to add contributions to the same row of the value gradient. Concurrent updates require coordination. The authors compare direct atomic additions, a lock that protects an entire row, and a method that reverses the lookup mapping beforehand. Atomic additions make sums safe when updates coincide. Row locking spreads the cost of gaining access across the row's coordinates. Reversing the mapping groups the work by the value row and lets the backward computation find the tokens that contribute to it. That last option requires preprocessing, so its benefit depends on the shape and distribution of the reads.

#### How the systems are trained

For the scaling series, the authors use bases of 134m, 373m, 720m, and 1.3b parameters. They use the Llama2 [tokenizer](https://md.research.elamur.ai/free/en/concepts/tokenization/) with a vocabulary of 32k tokens and train to 1T tokens from a mixture similar to the one used for Llama2. A tokenizer determines how text is broken into the units seen during training. Vocabulary size counts the available units. Training token count measures how many units the system processes and is a separate quantity. The architectural and data reference for this series is [Llama 2](https://md.research.elamur.ai/free/en/papers/touvron-2023-llama-2-open-foundation-fine/).

At the 8B base size, the authors use the Llama3 configuration, a vocabulary of 128k tokens, and a better optimized data mixture similar to Llama3's. They look at performance during training as well as at a later checkpoint. This scale has its own matched dense comparisons. Comparisons between it and the smaller-base series also change the tokenizer and training mixture, so they cover a different setup as well as a different base size. [The Llama 3 Herd of Models](https://md.research.elamur.ai/free/en/papers/grattafiori-2024-llama-3-herd-models/)

The memory learns alongside the rest of the network. Training makes the keys, values, and projections useful for predicting text. The paper does not construct the pool by assigning question-and-answer pairs to addresses. A training token contributes to the values used along its selected path, while other tokens can update a different subset. This arrangement is central to the study's capacity claim. A large memory supplies many potential parameters for text prediction, and a single training case can use a small share of them. Whether those parameters ultimately help answer factual questions is measured after training.

### Experiments and results

#### Benchmarks and what their scores count

The evaluation separates short factual questions from tasks that ask for other capabilities. The factual benchmarks are [Natural Questions](https://md.research.elamur.ai/free/en/papers/kwiatkowski-2019-natural-questions-benchmark-question-answering/) and [TriviaQA](https://md.research.elamur.ai/free/en/papers/joshi-2017-triviaqa-large-scale-distantly-supervised/). The paper reports exact match for Natural Questions, also denoted NQ. Exact match credits an answer that matches a reference under the benchmark's scoring rule. TriviaQA, denoted TQA, uses F1, which gives credit according to the overlap between a predicted answer and the reference, accounting for both what the system included and what it recovered. These scores capture different notions of success, so the paper uses the appropriate metric for each dataset.

The evaluation also includes questions whose answers draw on multiple pieces of information. The paper uses [HotpotQA](https://md.research.elamur.ai/free/en/papers/yang-2018-hotpotqa-dataset-diverse-explainable-multi/) for this category and reports answer F1. A result on this benchmark indicates how well the complete system answers its questions. The score does not expose which information came from a memory read or trace how the answer was assembled. It complements the factual tests by placing learned information in a setting where questions ask for more than a simple association.

For scientific and general knowledge, the benchmarks are [MMLU](https://md.research.elamur.ai/free/en/papers/hendrycks-2020-measuring-massive-multitask-language-understanding/), HellaSwag, OBQA, and [PIQA](https://md.research.elamur.ai/free/en/papers/bisk-2019-piqa-reasoning-about-physical-commonsense/). Their reported metric is accuracy. The coding evaluations use [HumanEval](https://md.research.elamur.ai/free/en/papers/chen-2021-evaluating-large-language-models-trained/) and MBPP with pass@1, which measures success on the first attempted solution. The coding and broader knowledge results test whether the architectural change pays off beyond short factual recall. Each benchmark measures the behavior of the full trained system, including the remaining dense layers.

For architectural ablations, the authors examine the probability assigned to the correct answer. They describe this as negative log-likelihood, also denoted NLL, for which lower is better. The table captions describe the corresponding likelihood measurements for the training set and answers on NQ and TQA. A system can place more probability on a reference while still choosing a different answer, especially when it is small and its outright success rate is low. Likelihood can register that progress before accuracy sees a new correct decision. This is why the authors use it to compare architectural settings whose accuracy figures could be noisy.

#### Holding memory size fixed across base networks

The first scaling experiment holds the Memory configuration's value count fixed across the series of base sizes. Each half-key set contains `2¹⁰` keys, giving `2²⁰` values, which the paper describes as roughly 1 million memory entries. This convention controls the number of addresses while the base architecture grows. The base configuration still supplies the reference for comparing floating-point operations, or FLOPs. The paper treats the FLOP differences among alternatives at the same base size as negligible. That comparison concerns the amount of arithmetic, with hardware performance evaluated separately.

The dense baseline uses the corresponding base architecture without the extra sparse parameter pool. For mixture-of-experts, the authors choose the lowest expert count that puts the comparison system above Memory in parameter count. The choices are 16 experts for the 134m base, 8 for the 373m base, 6 for the 720m base, and 4 for the 1.3b base. The comparison also specifies how experts receive work. During training the baseline uses expert-choice routing, in which experts select inputs, while evaluation uses top-1 routing, which sends the input through its highest-ranked expert. Consequently, the result compares Memory against a specified training and evaluation route through the expert architecture.

The PEER baseline uses 768 half-keys and ends up with slightly more parameters than Memory. For a fixed number of addresses, PEER stores two value vectors per address to build its rank-one operations, which the authors describe as requiring twice the parameters. Choosing its number of half-keys is therefore a way to make the overall parameter budgets close. The comparison uses the same memory-layer configuration and hyper-parameters for PEER, as described in the setup. Neither sparse baseline has to land on exactly the same number of weights, because the experiment chooses among discrete expert counts or half-key counts.

Memory improves substantially over the dense networks at the same base scale. On question answering, the authors say it generally matches dense networks with twice the number of dense parameters. Memory+ usually improves further. The paper describes its question-answering performance as generally falling between that of dense systems using 2x-4x higher compute. These findings concern a family of comparisons across sizes and tasks. The introductory claim of an improvement of over 100% refers to factual question-answering accuracy in the authors' overall account. They give that figure as a relative gain, without identifying a specific dataset and split for that headline number.

PEER performs similarly to the simpler Memory design when parameter counts are close and trails Memory+ in the reported comparisons. The mixture-of-experts systems lag the memory variants, with the contrast especially apparent on factual questions. These are comparisons of complete architectural choices, including each baseline's routing or lookup and the authors' improvements to Memory+. They show that the way sparse parameters are accessed matters under this setup. Parameter matching brings the systems closer in storage capacity, and a common base configuration helps control arithmetic. Neither condition implies that the systems allocate useful capacity in the same way.

The fixed-size series also puts the dense-compute comparisons in perspective. A dense system can gain capacity by enlarging the network, whereas the augmented system uses the memory pool to add capacity to a smaller base. If the memory system comes close to a bigger dense reference on factual questions, that is evidence that these tasks benefit from having more accessible parameters even when the number of arithmetic operations grows little. The result on a particular benchmark depends on the depth and width of the base as well as on what can be recovered through the table.

#### Growing the memory while holding the base fixed

The next experiment changes the other side of the comparison. The authors keep the 1.3b base fixed and grow the memory. In the scaling figure, the point with no memory is the dense version of the same base. The series is trained to 1 trillion tokens. As memory capacity rises, the authors describe a predictable improvement in factual question answering. The plotted measurements pair exact match on Natural Questions with F1 on TriviaQA, and the figure also tracks task NLL. Together they allow a reader to consider discrete answer scores alongside the probability given to correct answers.

At the largest end of this sweep, the paper describes a memory with 64 million keys and 128 billion memory parameters. The 1.3b system at that size approaches the factual question-answering performance of a Llama2 7B reference. That reference saw 2 trillion training tokens, or 2x more tokens, and used 10x more FLOPs. These are numbers for the training budgets in that comparison. The result is about approaching the reference on the factual evaluation, instead of an estimate of equivalent performance over all the tasks the reference could perform.

The base-size study and the memory-size study answer different questions. The former asks whether a given extra pool is useful at several base sizes and how it fares against other allocations of parameters. The latter asks whether adding entries still pays off after the base architecture has been chosen. Evidence of continued improvement on the factual plots indicates that the memory has room to help beyond the fixed-size setting. Because the table's width and size describe stored parameters and the plotted scores describe predictions, the curves do not assign a value to individual additional entries. They measure the effect of expanding the system as a whole.

The Llama2 7B line gives a reference for how much performance the memory sweep recovers under a different training budget. The cleaner evidence for the benefit of memory growth is the trend within the fixed-base sweep itself. There the study uses the same base size and token budget while varying the memory. Using both views lets the paper make an architectural comparison and show how large its gains are relative to a familiar dense reference without treating those comparisons as interchangeable.

#### Testing the architecture with an 8B base

For the larger base experiment, the authors use Memory+ with `4096²` value entries. They describe this as 16 million values and 64B memory parameters. This setting puts the largest base and a large memory together, although the fixed-base sweep reaches a larger memory in absolute size. The authors report checkpoints at 200 billion and 1 trillion training tokens. This makes it possible to see whether an advantage that appears earlier in training persists after the dense comparison has processed more text.

At this scale the memory-augmented system improves on the dense baseline across the expanded evaluation, which includes scientific and general knowledge and coding as well as question answering. In the authors' account, the gains are more pronounced at 200B tokens. They interpret that pattern as a sign that memory can help the system learn facts sooner. The direct observation is a difference in benchmark performance at comparable points in training. The measurement does not track when individual facts entered the system or which entries contributed to acquiring them.

At 1 trillion training tokens, the paper says Memory+ approaches the performance of the Llama3.1 8B reference, which was trained on 15 trillion tokens. That comparison puts the benchmark performance in the context of the training budget of another system. The 8B result establishes that the architecture is useful in the authors' larger experimental setup, while the head-to-head comparison with a dense baseline in that setup is the more direct measure of adding memory. The Llama3.1 result is a reference point, and the token counts describe the amount of training. They do not by themselves identify the contribution of each difference between the systems.

The expanded evaluation matters because it checks what happens when some dense feed-forward processing is exchanged for learned lookup. Factual questions show the clearest connection to the authors' motivation. The reported gains on coding and broader knowledge show that the resulting architecture can also improve the measured behavior of the complete system in those domains. Since the study does not isolate the memory entries used by a particular solution, those gains remain evidence about the architecture's effect on task performance.

#### The speed of the sparse read

The paper reports a separate engineering benchmark for the operation that reads and combines value vectors. On the H100, the forward pass of the custom CUDA implementation reaches 3TB/s of memory bandwidth. The hardware's rated bandwidth is 3.35TB/s. The corresponding PyTorch implementation reaches less than 400GB/s in the paper's comparison. The chart places the achieved rate beside the hardware specification. The specification is a device reference, while the custom kernel's figure is a measured rate for the operation.

EmbeddingBag forward benchmark on H100, achieved and rated bandwidth The custom forward kernel approaches the device's rated memory bandwidth.

**The numbers**

| System or setting | TB/s |
| --- | --- |
| H100 rated bandwidth | 3.35 |
| Custom EmbeddingBag forward (this paper) | 3 |

For the backward pass, the direct atomic approach can be up to 5x faster than the PyTorch operator. The authors report that the reverse-index and row-lock approaches can be faster when embedding width exceeds 128 and the reads across embeddings are reasonably balanced. This qualification matters because requests concentrated on a limited set of rows impose different coordination costs. A method that groups contributions by row can benefit from some access patterns and pay extra setup costs in others. The paper gives the conditions under which its alternatives can improve on direct atomic accumulation.

Taken together, the custom kernels make the EmbeddingBag operation 6x faster end to end than the PyTorch operation in the authors' use cases. Here “end to end” refers to the embedding operation under comparison. The training run also performs the rest of the transformer computations, participates in communication, and updates the weights. The lookup benchmark shows that an implementation choice can make a large difference to the cost of accessing stored values, even though the mathematical read remains a weighted sum over the same selected rows.

### What the ablations show

#### How often to consult the same pool

An ablation changes a feature or setting to see how much it contributes to performance. The paper's placement study changes the number of feed-forward positions occupied by shared memory. Because the pool is shared, this comparison holds its storage capacity fixed as new sites are added. The number of dense feed-forward blocks changes along with the number of memory reads. That joint change is exactly the architectural choice under study. It limits how specifically the results can identify a cause, while making them directly relevant to choosing the layout.

The training likelihood and the likelihood measurements on Natural Questions and TriviaQA initially improve as more sites use the shared pool. The authors find the best balance around 3 memory layers. Replacing more feed-forward blocks eventually harms performance. More sites can help the same collection of values influence processing at different depths, but the decline shows that the ability to read from the table does not compensate indefinitely for the loss of dense feed-forward capacity. The result is evidence for complementarity in the tested architecture.

The authors also vary centering and spacing. Centered layouts with larger strides work better in their comparisons, motivating the positions used for Memory+. A plausible reading is that spreading the sites leaves room for the network to transform representations between successive lookups. The comparison establishes the practical layout preference more directly than it establishes how the phases of processing differ. In particular, the likelihood results offer no mapping from depth to the kind of association read there.

This experiment helps interpret the fixed-size results. Some of the benefit of Memory+ can come from giving the network additional points at which to consult the same learned capacity. Increasing the number of entries is another intervention with its own measured effect. The paper studies both. It does not have to attribute every gain of the final design to the sheer size of the table, since performance varies even when the pool itself is held fixed.

#### Which modifications helped the read

The authors compare input-conditioned linear gating with the *swilu* variant. Simple gating improves some cases, while the nonlinear variant improves the reported results consistently enough to become part of the final configuration. The selected variant already includes an input-controlled gate, so the final design uses its existing modulation without the additional simple gating option. The comparison shows that the way a retrieved representation is used can matter even with the same general lookup mechanism.

Another experiment changes how entries get included during training. A top-`k` search repeatedly gives high-scoring keys an opportunity to contribute, while lower-scoring keys miss those reads. To broaden participation, one variant adds randomly chosen entries to the top results. A different variant includes a fixed key–value pair as an anchor in the selected set. This fixed entry receives a place among the values that share the softmax weights. It provides a consistent option while the other addresses vary from token to token.

The authors see small improvements from these sampling changes in some comparisons. Both have a cost in training speed in their implementation, and the gains become inconsistent for larger systems. The main experiments exclude them. The result is specific to the tested interventions for broadening or anchoring the read. It leaves room for other ways of allocating training among entries and gives no direct measure of how much information each part of the pool acquires. By contrast, the gate changes how the output of any selected read is used and shows a more consistent gain in the reported tests.

The architecture comparisons and the likelihood ablations answer questions at different levels. Memory+ is a package that changes placement, introduces modulation, and uses the chosen key width. Its advantage over Memory is the effect of deploying that package. The separate variants help explain why some ingredients were selected, and the combination remains the unit evaluated against the larger dense and sparse baselines.

#### How wide keys and values need to be

A memory with a given parameter budget can trade the number of values against their width. Narrower vectors allow more entries at a fixed budget, while wider vectors provide more coordinates per entry. To test this choice, the authors add a projection after the memory operation so that the value width can differ from the base representation width. Their dimension ablation uses the 373m base, whose latent dimension is 1024. The measured outcomes are likelihood on the training set and likelihood on Natural Questions and TriviaQA answers.

The default value width, equal to the base representation width, works best among the tested settings. The comparison makes clear that purchasing more addresses by reducing the width of each value can have a cost. Each entry must contribute a vector compatible with what the surrounding network needs to use, and the projection can map dimensions without creating additional independently stored coordinates for an entry. The ablation concerns this fixed-budget trade. The experiment that simply enlarges the table without narrowing its values answers a separate question and finds continued benefits from more entries.

Key width governs the representation used for matching. The paper counts total key width across both half-keys. Widening the keys helps in the reported dimension comparison, suggesting that address selection also influences the usefulness of a given pool. With wider keys there are also more dense parameters, including those involved in producing the corresponding query representation. Enlarging that path indefinitely would undermine the compute-controlled comparison that motivates the study. The experiments use a key width of half the base representation width, with the selected value width matching the base.

The dimension results clarify why memory size alone does not capture the architecture. The keys govern access. The values determine what a read can return. The gate and the rest of the network determine how a read changes the prediction. The ablations provide evidence for decisions at each stage. Their likelihood measurements can favor a setting without demonstrating that a particular entry has become easier to interpret or that a particular category of facts has moved into the table.

### Limitations

#### Scope and open problems identified by the authors

The authors use short-form questions to show that learned memory helps factual performance. They leave long-form generation for future work. In a short question, the reference typically gives a compact target, and exact match or F1 can measure how well the answer agrees with it. A longer response can contain many factual claims as well as qualifications, and success on individual questions does not establish the reliability of that response. The authors describe reduced hallucination as a potential direction for further learning methods, beyond the behavior shown by the factual benchmarks.

The paper also distinguishes the ability to train a memory of this size from the ability to serve it efficiently in production. Sparse reads stress device memory and, when the table is distributed, require the devices to exchange information. Dense kernels benefit from mature hardware support and optimization. The custom EmbeddingBag results address an important part of the workload. The authors still identify substantial engineering work before this architecture is ready for efficient large-scale deployment. Their expectation that sparse memory could eventually rival dense feed-forward blocks in execution speed is a prospect, not a measured system-wide result.

The authors characterize their evidence about learning and factuality as high-level and empirical. They show benchmark gains from the architecture, test ways of arranging and controlling the memory, and demonstrate that the lookup can be engineered at scale. They propose that sparse updates might later support less forgetting and continual learning. The reported training protocol measures performance after processing different amounts of pretraining text. It does not present a sequence of controlled updates in which previously learned information is checked for retention. The paper leaves that mechanism and its possible benefits open.

#### Limits of the comparisons

The close comparisons match particular budgets. The study keeps the base configuration comparable when evaluating alternative allocations of sparse parameters and minimizes the difference in FLOPs. Expert counts and key counts are discrete, so the sparse systems have approximate parameter matches. PEER has somewhat more weights in the stated fixed-memory comparison, and the expert baseline's count is chosen to exceed Memory's. The result therefore supports the architecture against these configured baselines. It cannot determine the best performance obtainable by every alternative sparse design with its own independently tuned training and routing choices.

Floating-point operations measure arithmetic, while GPU memory capacity, bytes transferred, and communication influence elapsed time and resource use. The tables add both trainable values and optimizer state. Those are real costs even when each query reads few entries. The 6x speedup is for the authors' version of EmbeddingBag compared with PyTorch's implementation in their use cases. It cannot be used as a multiplier for the speed of the whole network, and the dense-compute comparisons alone cannot establish a similar advantage in energy consumption.

The larger external references also differ in their training. The Llama2 7B reference used both more tokens and more FLOPs than the fixed-base memory series. The Llama3.1 8B reference used a much larger training token budget than the paper's 8B Memory+ checkpoint. These comparisons show where the authors' systems stand relative to familiar dense references on measured tasks. The fixed-base memory sweep and the same-base dense comparisons provide the more direct tests of the architectural change. The article's quantitative comparisons use the reported settings and budgets, while the paper's prose gives several benchmark outcomes as comparative trends without enumerating their individual scores or splits.

#### What a correct answer reveals about a read

A higher score establishes that the changed network assigns more probability to correct answers or produces more of them under the benchmark rule. The result does not identify a stored record with a specific fact. Values can cooperate in a weighted read, the same value can participate in many contexts, and dense blocks also contribute to the final prediction. The paper motivates the design with simple associations, then measures the network that learns and uses them. Pinning a fact to a specific address would require evidence about individual reads and about what changes when those entries are altered.

The same distinction applies to the gains on coding and multi-hop question answering. A better answer or a passing program is an outcome of the complete network. It does not reveal which computational steps took place at which depth, whether a memory read supplied a necessary fact, or whether the architecture used the extra capacity in a less direct way. The gain signals that lookup and dense processing can work together on these tasks. The benchmarks leave their division of labor unresolved.

Finally, the tested ranges describe empirical scaling. The authors show that larger memories continue helping on their factual evaluations through the sizes examined. Key selection, value updates, and inter-device communication can present different costs as the setup grows. The ablations already show that some changes helpful at one scale are less consistent at larger sizes. The evidence supports the reported range and the choices tested within it. Further scaling, different training mixtures, and other kinds of factual evaluation would each extend that evidence in a different direction.

### What came after

The documented research record ends with Memory Layers at Scale. PEER and the earlier product-key networks belong to its technical background and comparisons. The subsequent directions articulated by the authors are to improve the production efficiency of sparse reads, test factual performance in longer responses, and investigate learning methods that use sparse updates to retain information over time. These are open research questions from the paper.

## Cite

Cite as Vincent-Pierre Berges, Barlas Oğuz, Daniel Haziza, Wen-tau Yih, Luke Zettlemoyer and Gargi Ghosh. 2024. Memory Layers at Scale. arXiv (Cornell University).

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.48550/arxiv.2412.09764](https://doi.org/10.48550/arxiv.2412.09764) · [arXiv 2412.09764](https://arxiv.org/abs/2412.09764)

```bibtex
@misc{berges2024memory,
  title = {{Memory Layers at Scale}},
  author = {Vincent-Pierre Berges, Barlas Oğuz, Daniel Haziza, Wen-tau Yih, Luke Zettlemoyer and Gargi Ghosh},
  year = {2024},
  doi = {10.48550/arxiv.2412.09764},
  eprint = {2412.09764},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.2412.09764}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
