24 Memory Management for Large Language Models
Modern large language models are, at their core, memory systems. A model with 70 billion parameters encodes a vast compressed representation of human knowledge in its weights, yet the act of using that knowledge, generating a single new token, requires attending to every token that has come before. The key–value (KV) cache that stores past attention states can, for long contexts, consume more GPU memory than the model weights themselves. This chapter studies the mathematics of memory in large language models: from the hardware memory hierarchy that constrains every forward pass, through algorithmic techniques that tame the KV cache, to architectural innovations that equip Transformers with external, retrieval-based, and hash-indexed memory systems.
The fundamental tension is between what a model knows (encoded in its parameters) and what it can access (limited by the context window and available hardware memory). Scaling laws tell us that larger models and longer contexts improve capability, but both axes of scaling run headlong into memory walls: the former into GPU VRAM limits, the latter into the quadratic (training) and linear (inference) growth of attention memory.
Key Idea.
Memory Heterogeneity Thesis. Different types of knowledge require different memory mechanisms, each with its own access pattern, latency, and capacity. Parametric memory (model weights) stores slow-changing world knowledge; contextual memory (the KV cache) stores the evolving state of the current conversation; external memory (retrieval corpora, memory tables) provides unbounded storage at the cost of higher access latency. Effective LLM systems must manage all three simultaneously.
[colback=keyamberbg, colframe=keyamber, title=Central Question] How can we organise memory, across hardware levels and architectural levels, to enable LLMs to reason over arbitrarily long contexts without proportional cost growth?
Historical Note.
The idea that computation requires a hierarchy of memory dates to von Neumann's 1945 “First Draft of a Report on the EDVAC,” which described a stored-program architecture with fast registers, intermediate storage, and slow external memory. Eighty years later, the same hierarchy (registers, SRAM, HBM, DRAM, SSD) governs the design of every large language model deployment.
Neural memory systems emerged with Hopfield networks (1982) and were revitalised by Graves et al.'s Neural Turing Machine [1] and Weston et al.'s Memory Networks [2] in 2014–2015. These architectures demonstrated that neural networks could learn to read from and write to external memory banks via differentiable addressing. The modern KV cache crisis, where a single long-context inference can require hundreds of gigabytes of memory, has brought memory management back to the centre of LLM research.
Before diving into the technical development, we provide a roadmap of the chapter. Attention as Memory Access reframes the attention mechanism (Definition 12) as a differentiable memory access operation and quantifies the KV cache growth problem (Definition 16). Extending the Context Window studies methods for extending the effective context window via position-encoding manipulation. Sparse and Structured Attention Patterns introduces sparse and structured attention patterns that reduce the memory footprint. Memory-Augmented Architectures covers memory-augmented architectures, from Neural Turing Machines through the Engram architecture to retrieval-augmented generation. Hierarchical Memory Architectures builds these into hierarchical memory systems, State-Space Models and Recurrent Memory replaces the cache with a fixed recurrent state, and Connections and Synthesis draws the whole landscape onto a single capacity-latency frontier.
We assume familiarity with the Transformer architecture as developed in The Transformer, including scaled dot-product attention (Definition 12), multi-head attention (Definition 13), and rotary position embeddings (Definition 15). Readers seeking background on recurrence-based sequence models may consult Recurrent Foundations for Iterative Computation.
Attention as Memory Access
The attention mechanism, when viewed through the lens of memory systems, is a differentiable associative memory. In this section we make that analogy precise, quantify the memory cost of the KV cache, and identify the bandwidth bottleneck that dominates autoregressive generation.
Self-Attention as Differentiable Memory Read
Consider a standard self-attention layer (Definition 12). At generation step , the model has produced tokens and the KV cache (Definition 16) stores key and value vectors for all prior positions: (KV Cache Matrices) To generate token , the model computes a query from the embedding of and reads from the cache: (ATTN AS READ)
Remark 1 (Attention as Associative Memory).
(ATTN AS READ) is precisely a content-based memory read operation:
Memory bank: stores value vectors (the “data” to be retrieved).
Address keys: stores key vectors (the “index” for lookup).
Query: specifies what information is needed.
Read head: The softmax-weighted combination is a soft lookup: every memory slot contributes, weighted by relevance.
This is analogous to the content-based addressing in Neural Turing Machines [1], but with the memory bank growing by one entry per time step.
Multi-head attention (Definition 13) can be viewed as parallel read heads, each with its own query–key subspace. Grouped query attention (Definition 17) shares key–value banks across groups of read heads, reducing the memory bank size at the cost of some independence between heads.
Insight.
The KV cache is not merely an implementation optimisation; it is the model's working memory. Every token the model has seen is stored as a (key, value) pair, and every new token accesses that memory via a soft content-addressed read. The “context window” is simply the size of this working memory.
The KV Cache Growth Problem
We now quantify the memory cost precisely.
Definition 1 (Memory Complexity of Attention).
For a Transformer with layers, attention heads per layer, head dimension , and sequence length , the KV cache requires (KV Memory) stored in the model's working precision. In half-precision (fp16 or bf16), this corresponds to bytes bytes.
The factor of 2 in (KV Memory) accounts for both the key and value matrices. For reference, see the concrete memory budgets computed in Remark 11.
Example 1 (KV Cache of a 70B Model).
Consider a model with layers, heads, , and sequence length tokens. In fp16: The model weights themselves (70B parameters in fp16) occupy ;GB. At 128K context, the KV cache is more than twice the size of the model weights (a ratio of ). Both figures here are decimal: bytes. The binary value ;GiB is the same quantity, and mixing the two units is the most common way to lose a factor of in this arithmetic.
Proposition 1 (Compute–Memory Crossover).
During autoregressive generation, producing a single new token at position requires:
KV cache read: bytes of memory access (reading all keys and values across all layers).
Attention computation: FLOPs (computing the dot products for all and the weighted sum over values).
Define the arithmetic intensity . For the attention operation during decoding, (one FLOP per byte read). The system is compute-bound when and memory-bound otherwise. Since modern accelerators have (for an H100 SXM in fp16 or bf16, FLOP per byte, and in TF32), the attention decoding step is almost always memory-bound.
Proof.
Each attention head in each layer requires reading key vectors of dimension (totalling values in fp16, i.e., bytes) and value vectors ( bytes), for a total of bytes per head per layer. Across layers and heads: bytes.
The corresponding computation is dot products of dimension (costing FLOPs per head, using the convention that a multiply-add is 2 FLOPs) plus a further FLOPs for the weighted sum, which is also multiply-adds. That gives FLOPs per head per layer and FLOPs in total, matching the byte count exactly.
The arithmetic intensity is therefore Since for all current accelerators, we have , and the operation is memory-bandwidth–bound.
The Memory Bandwidth Wall
Definition 2 (Memory Bandwidth Bottleneck).
During autoregressive generation, each new token requires reading the entire KV cache from HBM\@. The maximum token generation throughput is therefore bounded by (Bandwidth Bound) where is the memory footprint of model parameters (which must also be read for the FFN layers).
Example 2 (Throughput on an H100).
An NVIDIA H100 SXM provides TB/s. For the 70B model at 128K context from Example 1: This is per sequence. Batching multiple sequences helps amortise the parameter reads but exacerbates the KV cache memory pressure.
Caution.
The quadratic cost of attention ( in FLOPs and memory) is often cited as the primary bottleneck. However, during autoregressive generation, which is the dominant workload for deployed LLMs, each step computes attention for a single new query against cached keys, costing FLOPs but requiring memory reads. The linear KV cache growth and the resulting bandwidth bottleneck are the more pressing constraints in practice. Flash Attention (Algorithm 3, Proposition 2) addresses the IO cost during training (prefill), but the decode-time bandwidth wall persists.
The rest of this chapter is devoted to techniques for pushing past this memory wall: extending the context window without proportional memory growth (Extending the Context Window), reducing the number of positions that attend to each other (Sparse and Structured Attention Patterns), augmenting the Transformer with external memory (Memory-Augmented Architectures), organising those stores into a hierarchy (Hierarchical Memory Architectures), and replacing the cache altogether with a fixed-size recurrent state (State-Space Models and Recurrent Memory).
Extending the Context Window
A model trained on sequences of length must, at deployment, often handle sequences of length . Naïve extrapolation fails: the model encounters position encodings outside its training distribution. This section presents three progressively more sophisticated methods for extending the context window, all of which manipulate the frequency schedule of rotary position embeddings (Definition 15).
Position Interpolation
Definition 3 (Position Interpolation).
Let a model be trained with maximum sequence length using RoPE (Definition 15). Position Interpolation (PI) [3] rescales position indices during inference to fit within the training range: (PI Rescale) The rescaled positions are no longer integers, but the RoPE rotation is well defined for all .
The intuition is simple: instead of extrapolating to unseen positions , we interpolate between the positions seen during training. The price is reduced positional resolution: positions that were distinguishable at training time may become aliased.
Proposition 2 (PI Angle Bound).
Under Position Interpolation, the maximum rotation angle for RoPE frequency band over the admissible positions is so every angle stays strictly inside the range seen during training.
Proof.
By definition of PI ((PI Rescale)), . The rotation angle for frequency band is . The maximum over is achieved at : Since during training the maximum angle was , all interpolated angles lie within the training range.
Remark 2.
PI preserves the relative-position property of RoPE (Proposition 1): the dot product between the query at position and the key at position depends only on (rescaled). However, the rescaled relative distances become , which compresses the position spectrum and may degrade local position discrimination.
NTK-Aware Scaling
Position Interpolation applies the same compression ratio to all frequency bands. But high-frequency bands encode local position information (nearby tokens), while low-frequency bands encode global position information (distant tokens). Compressing high frequencies degrades local discrimination unnecessarily.
Definition 4 (NTK-Aware Scaling).
Instead of uniformly interpolating all frequencies, NTK-Aware Scaling adjusts the RoPE base frequency: (NTK BASE) where is the extension ratio and is the head dimension. The individual frequency bands become
The key property of NTK-Aware Scaling is that the compression factor varies across frequency bands:
For (highest frequency): the scaling factor is , meaning no compression at all.
For (lowest frequency): the scaling factor approaches , giving maximum compression, similar to PI\@.
This preserves local positional precision while extending global reach.
Remark 3.
The name “NTK-Aware” comes from an analogy with neural tangent kernel (NTK) theory: the base-frequency adjustment ensures that the effective learning rate for each frequency band remains balanced, in the same way that NTK parameterisation balances gradient norms across layers.
YaRN: Yet Another RoPE ExtensioN
Definition 5 (YaRN).
YaRN [4] combines NTK-aware scaling with an attention temperature correction. The modified attention computation is (YARN ATTN) where the temperature is given by the empirical fit (YARN TEMP) so that the logits are multiplied by . Note the square: the quantity is , not the logit multiplier itself. The coefficient is fitted empirically to the LLaMA family in the original work rather than derived. The temperature compensates for the entropy increase caused by position interpolation: when positions are compressed, the attention logits decrease in magnitude, leading to a more uniform (higher entropy) attention distribution. The factor sharpens the distribution to restore the original attention pattern.
Remark 4.
YaRN additionally partitions the frequency bands into three groups:
No interpolation (highest frequencies, ): leave unchanged.
NTK interpolation (middle frequencies, ): apply the NTK-aware scaling from Definition 4.
Linear interpolation (lowest frequencies, ): apply PI-style uniform compression.
The boundaries and are determined by a wavelength threshold relative to .
Insight.
All context extension methods manipulate the same mathematical object, the RoPE frequency schedule , but with different trade-offs between local precision and global reach. PI compresses uniformly (simple but lossy at short range), NTK-Aware scaling compresses adaptively (preserving local info), and YaRN adds temperature correction to counteract entropy distortion. The progression illustrates a general principle: when extrapolating a learned representation, it is better to preserve the components the model relies on most (high-frequency, local structure) and compress those it is more robust to (low-frequency, global structure).
Example 3 (LLaMA-2 Context Extension).
Consider extending LLaMA-2 from to tokens. The extension ratio is . LLaMA-2 uses and head dimension .
PI scaling. All position indices are scaled by . Position maps to , within the training range. The minimum distinguishable position gap is positions.
NTK base frequency. From (NTK BASE): The lowest-frequency band () sees a compression factor close to , while the highest-frequency band () is virtually unchanged.
YaRN temperature. From (YARN TEMP): All attention logits are multiplied by , sharpening the softmax distribution to compensate for the reduced magnitude of interpolated position encodings. Applying instead would correct only about half the entropy increase, since that quantity is .
Exercise 1.
Show that under Position Interpolation with extension ratio , the minimum relative position difference that produces a distinct attention pattern is times larger than during training. Specifically, if two positions with were distinguishable during training, then under PI the minimum distinguishable gap is . Hint: Consider the dot product as a function of and compare the rescaled version.
Exercise 2.
Sparse and Structured Attention Patterns
Full attention requires every token to attend to every other token, yielding memory and computation during training (and KV cache reads per step during generation). Sparse attention restricts the set of (query, key) pairs that interact, reducing cost while preserving the ability to propagate information across the full sequence.
Formalising Sparse Attention
Definition 6 (Sparse Attention Pattern).
An attention pattern is a relation specifying which (query, key) pairs interact. For each query position , define the receptive field . The sparse attention under pattern is (Sparse ATTN) where the softmax is restricted to the receptive field . The per-token memory and computation cost is instead of .
Remark 5.
Full (dense) attention corresponds to (causal) or (bidirectional). Any sparse pattern sacrifices some information flow in exchange for efficiency.
The Sliding Window
Definition 7 (Sliding Window Attention).
The sliding window pattern with window size is (Sliding Window) Each token attends to at most positions (itself and the preceding tokens). The memory cost of the KV cache is reduced from to per layer, since keys and values outside the window can be evicted.
Proposition 3 (Sliding Window Information Propagation).
In a Transformer with layers of sliding window attention with window size , information from position can reach position (with ) if and only if . The effective receptive field is tokens.
Proof.
In a single layer, position receives information from positions . After two layers, position receives information from positions up to (since each position in its first-layer receptive field itself has a window of size ). By induction, after layers, the receptive field extends back to position .
Example 4 (Mistral 7B).
Mistral 7B uses sliding window attention with and layers. The effective receptive field is tokens, enabling the model to process very long contexts while keeping the per-layer KV cache at instead of .
Global Tokens and the BigBird Pattern
A pure sliding window cannot propagate information globally in a single layer. Adding a small set of global tokens, positions that attend to (and are attended by) all other positions, restores global connectivity.
Definition 8 (BigBird Attention Pattern).
The BigBird pattern [5] is the union of three sub-patterns: (Bigbird) where:
is a sliding window of size . BigBird is presented here in the bidirectional (encoder) setting, so this window spans positions, unlike the causal of Definition 7, which spans .
for a set of global token positions. Every position attends to global tokens and vice versa.
contains randomly chosen pairs per query position, providing stochastic long-range connections.
The per-token memory cost is .
The Longformer [22] uses a similar pattern (sliding window + global tokens, without the random component).
Theorem 1 (Information Propagation in BigBird).
For the BigBird attention pattern with at least global token and window size , the attention graph has diameter at most : any two positions are joined by a path of length at most 2, so two layers suffice for any . Without global tokens, the sliding window alone gives a diameter of , and covering a separation of in two layers would require .
Proof.
We construct an explicit path in the attention graph.
Case 1: or . Then directly, giving a path of length 1.
Case 2: Neither nor is a global token. Choose any . The path is :
: Since is a global token, , so attends to .
: Since is global, , so attends to .
This gives a path of length 2 via the global token.
Cases 1 and 2 are exhaustive, and each yields a path of length at most 2, so the diameter is at most 2 whenever .
If the global tokens are removed, or if their capacity is exhausted so that they cannot be relied on, the only remaining edges are the window edges. A position can then move at most places per hop, so crossing a separation of takes hops and the window-only diameter is . In particular two layers reach only , so two-layer coverage of the whole sequence needs .
Remark 6.
It is worth separating the two bounds, because they differ by a large factor in practice. At and the window-only diameter is , while a single global token brings the diameter to . The lesson is that connectivity in these patterns is bought by the hubs, not by the window; the window buys locality.
Remark 7.
Zaheer et al. [5] proved a stronger result: BigBird with random attention is a universal approximator of sequence-to-sequence functions, matching the expressiveness of full attention under mild assumptions on the number of global and random connections.
Ring Attention for Distributed Long Context
Sparse attention reduces per-device memory, but for very long sequences even the reduced KV cache may not fit on a single device. Ring Attention [23] distributes the full sequence across multiple devices while computing exact (dense) attention.
Proposition 4 (Ring Attention).
Partition a sequence of length evenly across devices, so device holds tokens with their query, key, and value projections. In each of rounds:
Each device computes local attention between its queries and the currently-held keys/values (a block of tokens).
Keys and values are passed to the next device in a ring topology.
After rounds, each device has computed attention against all keys. The per-device memory is for keys/values, and the total communication per device per head per layer is (RING COMM) The factor accounts for both keys and values.
Proof.
Each device sends its local KV block (of size tokens, each with -dimensional key and value, totalling elements) to the next device. This happens times (after rounds, the original block returns and no further send is needed). Total elements sent per device: In fp16, this is at most bytes per device per head per layer, confirming communication.
Computation overlaps with communication: while device sends its KV block to device , it computes attention on the block it just received. With sufficient bandwidth, the communication is fully hidden, and the wall-clock time is dominated by the sequential attention computations of size .
Remark 8.
Ring Attention is exact: it computes the same result as full dense attention. It is purely a systems-level optimisation that distributes the memory burden. Combining Ring Attention with sparse patterns (e.g., using a sliding window within each block and global tokens across blocks) further reduces both communication and computation.
Key Idea.
Sparse attention trades global information reach for efficiency. The fundamental design question is: which tokens truly need to attend to which? Global tokens ensure connectivity; sliding windows preserve local structure; random connections provide stochastic shortcuts. The optimal pattern depends on the task: local patterns suffice for language modelling where nearby context is most predictive, while tasks requiring long-range reasoning (e.g., document QA, code understanding) may require denser global connectivity.
Exercise 3.
For the BigBird pattern with global tokens, window size , and random connections per query:
Show that the per-token memory cost is .
Show that the total attention FLOPs for a sequence of length is .
Determine the condition on , , and under which the BigBird pattern achieves sub-quadratic total cost in .
Exercise 4.
In Ring Attention with devices, the computation of each local attention block takes time and the communication of each KV block takes time , where is the inter-device bandwidth. Show that the communication is fully hidden (i.e., ) when , i.e., when each device holds sufficiently many tokens.
Memory-Augmented Architectures
The KV cache is the Transformer's working memory: it stores contextual information that persists within a single forward pass. But it is ephemeral (cleared between sequences), bounded (limited by GPU memory), and expensive (every entry is read at every step). Memory-augmented architectures add a persistent, structured external memory that the model can read from (and sometimes write to) using learned addressing mechanisms. This section traces the evolution from Neural Turing Machines through modern architectures like Engram and retrieval-augmented generation.
Neural Turing Machines and Differentiable Neural Computers
Definition 9 (External Memory).
An external memory is a matrix , where is the number of memory slots and is the slot dimension. A controller network interacts with the memory through read and write heads.
Read operation. A read head produces a weight vector (a probability distribution over slots) and returns (Memory READ) where is the -th row of the memory matrix at time .
Content-based addressing. The read weights can be computed via content-based addressing: (Content Addressing) where is a query key emitted by the controller, is a sharpness parameter, and denotes cosine similarity.
Write operation. A write head produces an erase vector and an add vector : (Memory Write) where is the write weight distribution.
Historical Note.
Graves et al. [1] introduced the Neural Turing Machine (NTM), which augmented a recurrent neural network controller with a differentiable external memory and read/write heads using both content-based and location-based addressing. The Differentiable Neural Computer (DNC) [6] improved upon the NTM with dynamic memory allocation, temporal link matrices for tracking the order of writes, and a usage-based free mechanism.
Concurrently, Weston et al. [2] introduced Memory Networks with a simpler architecture: a large memory bank of (key, value) pairs addressed purely by content, without a write mechanism. End-to-end Memory Networks made the addressing differentiable, enabling training with backpropagation.
These architectures demonstrated that neural networks could learn to use external memory for algorithmic tasks (copying, sorting, graph traversal), but they faced challenges at scale: the fixed memory size limited capacity, content-based addressing became noisy for large , and the recurrent controller made training slow.
Remark 9.
Comparing (Content Addressing) with standard attention ((ATTN AS READ)) reveals a striking parallel:
| NTM Read | Attention | |
| Memory bank | ||
| Address keys | (reused) | |
| Query | (controller) | (projected) |
| Similarity | cosine | dot product / |
| Sharpness | (learned) | (fixed) |
N-gram Hash Memory: The Engram Architecture
While NTMs use a small, fully differentiable memory, modern LLMs need memory systems that can scale to billions of entries. The Engram architecture [24] takes a radically different approach: instead of learning the addressing mechanism end-to-end, it uses a fixed hash function to index into a massive lookup table, trading addressing flexibility for scalability.
Definition 10 (N-gram Hash Function).
For a sequence of token IDs , the -gram hash at position is computed via a polynomial rolling hash: (Ngram HASH) where is a prime number and is the hash table size. This maps each -gram of token IDs to an integer in .
Remark 10.
The polynomial rolling hash spreads possible -grams over buckets, giving an expected bucket load of entries per bucket, while the probability that two specified distinct -grams land in the same bucket is . The two quantities answer different questions and only the second is a probability: at , and the load is per bucket while the pairwise probability is . For the buckets are mostly empty and collisions are rare. For large , collisions are inevitable and can be viewed as a form of implicit dimensionality reduction: similar -grams may share a memory slot, forcing the memory to store generalisable patterns rather than memorising every sequence.
Definition 11 (Engram Module).
Given a token sequence and the hidden state from a Transformer layer, the Engram module computes:
N-gram hashing: For each -gram order , compute the hash using (Ngram HASH), which already reduces modulo .
Table lookup: Retrieve the memory vector (Engram Lookup) where is a learnable embedding table for -gram order .
Aggregation: Combine across -gram orders: (Engram Aggregate) where are learned (and optionally input-dependent) mixing weights.
Gated fusion: Merge the memory vector with the hidden state: (Engram GATE) where is a learned gate, , , and is the sigmoid function.
The gate allows the model to dynamically control how much memory influence each hidden dimension receives. When , the Engram module is effectively bypassed, recovering standard Transformer behaviour.
Proposition 5 (Engram Complexity).
The Engram module has the following complexity properties:
Time: per position, independent of context length and table size . The gating term dominates at realistic sizes (, ).
Memory (parameters): for the embedding tables, plus for the gating parameters.
Offloadability: The embedding tables can be stored on CPU DRAM or SSD\@. Each forward pass requires fetching only vectors of dimension (one per -gram order), with less than 3% latency overhead when prefetching is used.
Proof.
(1) Computing each hash ((Ngram HASH)) takes operations. Summing over , the total hashing cost is , but since is a small constant (typically ), this is . Each table lookup is (direct indexing). The aggregation ((Engram Aggregate)) and gating ((Engram GATE)) are and respectively. Total per-position cost: , independent of both and .
(2) Each of the embedding tables has rows of dimension , giving parameters.
(3) During inference, only the rows indexed by the current -gram hashes are accessed. These rows (totalling elements) can be prefetched from CPU/SSD while the Transformer layers compute, hiding the latency.
Theorem 2 (U-Shaped Scaling Law).
Consider a fixed total parameter budget , with fraction allocated to Transformer computation (weights of attention and FFN layers) and fraction allocated to Engram memory tables. Under Chinchilla-style power-law assumptions, the loss contributions from computation and memory are (LOSS COMP) with and . The total loss (Total LOSS) is U-shaped in with a unique interior minimum .
Proof.
We show that is strictly convex on with boundary behaviour as or , guaranteeing a unique interior minimum.
Step 1: Boundary behaviour. As , . As , . Thus at both endpoints.
Step 2: First-order condition. Taking the derivative: (DLdalpha) Setting : (FOC) The left-hand side is a strictly decreasing function of on (from to a finite positive value), and the right-hand side is a strictly increasing function (from a finite positive value to ). By the intermediate value theorem, there is a unique crossing .
Step 3: Second-order condition. for all , confirming strict convexity and that is a global minimum.
Remark 11.
When the two exponents coincide, , (FOC) can be solved in closed form: independent of the total budget , which suggests that in that regime the optimal compute-memory split is a property of the task rather than of the scale. For no such elementary solution exists: (FOC) then carries different exponents on and , and the root must be found numerically. The difference is not negligible, as Exercise 6 shows: at , , , the true root is , so treating the formula as general would misallocate the budget by several per cent.
Insight.
Engram decouples knowledge storage from reasoning computation. Factual knowledge (world facts, code patterns, syntactic -gram statistics) changes rarely and can live in a massive memory table offloaded to CPU\@. This frees GPU-resident Transformer layers to focus on reasoning and context understanding. The U-shaped scaling law (Theorem 2) formalises the intuition that neither pure computation (all Transformer) nor pure memory (all lookup) is optimal: the best models balance both.
Remark 12 (Connection to Mixture-of-Experts).
Mixture-of-Experts (MoE) [7] provides conditional computation: only a subset of FFN experts are activated per token. Engram provides conditional memory: only the relevant -gram entries are fetched per token. Together, they span the two axes of model scaling:
| Compute | Memory | |
| Dense | Standard FFN | Full KV cache |
| Conditional | MoE (sparse experts) | Engram (hash lookup) |
Exercise 5.
Suppose the vocabulary size is , the hash table size is , and we use bigrams ().
How many distinct bigrams are possible?
What is the expected number of bigrams per bucket, and separately, what is the probability that two specified distinct bigrams map to the same hash? Explain why only the second of these is a probability, and check that your first answer exceeds 1.
Argue that collisions can be beneficial: bigrams with similar continuations should ideally share memory entries.
Exercise 6.
Retrieval-Augmented Generation as External Memory
While NTMs and Engram operate at the vector level (individual memory vectors integrated into the hidden state), retrieval-augmented generation (RAG) operates at the sequence level: entire documents are retrieved and prepended to the context.
Definition 12 (Retrieval-Augmented Generation).
RAG [8] formalises external memory as a two-stage process over a document corpus :
Retrieve: Given query , select the top- most relevant documents: (RAG Retrieve) where is typically the inner product in an embedding space produced by a bi-encoder.
Generate: Produce the output by marginalising over retrieved documents: (RAG Generate) where and is the LLM's output distribution conditioned on the concatenation of the query and the retrieved document.
Remark 13 (RAG vs. Engram: Sequence-Level vs. Token-Level Memory).
RAG and Engram address complementary aspects of external memory:
RAG retrieves at the sequence level: full documents are appended to the context window. This increases the effective context length (and thus the KV cache size), but allows the attention mechanism to reason jointly over the query and the retrieved evidence.
Engram retrieves at the token level: per-position memory vectors are integrated into the hidden state via gating. This increases the effective parameter count (knowledge capacity) without increasing the context length.
RAG requires a retrieval index and is limited by the context window size; Engram requires hash tables and is limited by the table size. They can be combined: RAG provides relevant documents for reasoning, while Engram provides fine-grained -gram knowledge that would be too numerous to retrieve as documents.
Remark 14 (Connection to Diffusion Language Models).
RAG can also be applied to non-autoregressive generation. In diffusion language models (sec:diffusion_language), the retrieval step can condition the denoising process on retrieved documents, providing an external memory for iterative refinement.
Exercise 7.
Compare the memory cost of extending context via RAG versus native long context. Suppose a model processes a query of length and retrieves documents each of length .
What is the KV cache size for the RAG approach (query + retrieved documents)?
If the same information were stored as native context (a single sequence of length ), what would the KV cache size be?
Under what conditions (on and ) does RAG provide a memory advantage over native long context? Hint: Consider whether the model needs to attend across different retrieved documents.
Hierarchical Memory Architectures
Every modern computer organises its storage into a hierarchy (registers, L1/L2/L3 caches, DRAM, SSD, network) trading off capacity against access latency. The same principle governs biological memory: millisecond-scale sensory buffers, second-scale working memory, and hour-to-year-scale long-term stores. Recent work applies this insight directly to LLMs, constructing hierarchical memory systems that enable arbitrarily long context at bounded computational cost.
The Cognitive Memory Hierarchy
Historical Note.
Atkinson and Shiffrin (1968) proposed the multi-store model of human memory [9], distinguishing sensory, short-term, and long-term stores. Baddeley (1974) refined this into a working memory model with a central executive, a phonological loop, and a visuo-spatial sketchpad [10]. Tulving (1972) further decomposed long-term memory into episodic (events) and semantic (facts) [11]. Modern hierarchical memory architectures for LLMs draw explicit inspiration from these cognitive science models, mapping each store to a concrete neural mechanism.
The cognitive hierarchy suggests five tiers:
Sensory buffer. Raw perceptual input, retained for milliseconds. In an LLM, this corresponds to the current input tokens in the immediate attention window.
Working memory. A capacity-limited workspace (Miller's “” items [12]). In an LLM, the KV cache of the most recent segment plays this role.
Episodic memory. Autobiographical events indexed by time and context. Compressed representations of past segments, as in the Hierarchical Memory Transformer.
Semantic memory. Abstracted facts and concepts, detached from specific episodes. The model weights themselves, or external knowledge bases accessed via RAG (Definition 12).
Procedural memory. Skills and action patterns, often implicit. Learned strategies encoded in the model's policy, or in the top-level domain tier of H-MEM.
We now examine three concrete architectures that implement different subsets of this hierarchy.
HMT: Hierarchical Memory Transformer
Definition 13 (HMT Memory Levels).
(He et al., 2024 [13].) Given a sequence segmented into blocks of size , the Hierarchical Memory Transformer (HMT) maintains three memory tiers:
Sensory memory: the raw tokens of the current segment , comprising tokens.
Short-term memory (): compressed tokens distilled from the previous segment .
Long-term memory (): compressed tokens aggregating information from all earlier segments .
At each step the effective context is the concatenation so that the attention cost per segment is regardless of total sequence length.
The key operation connecting tiers is memory compression: converting a variable-length token sequence into a fixed number of summary tokens.
Definition 14 (Memory Compression Operator).
A memory compression operator maps token representations to memory tokens via learned cross-attention: where are learnable query vectors (independent of the input), and are the key and value projections of the input tokens.
Remark 15.
The compression operator is a form of Perceiver-style cross-attention [14]. The learnable queries act as “memory slots” that attend to the input, selecting and mixing the most relevant information. Unlike pooling, the queries can specialise: one slot may capture positional structure while another captures semantic content.
Proposition 6 (HMT Memory Efficiency).
For a sequence of total length processed in segments of size , HMT achieves an effective compression ratio of Adding only – additional parameters as a plug-and-play wrapper around a frozen base model, HMT achieves language modelling quality comparable to long-context models with – more parameters, while using – less inference memory.
Proof.
By induction on segments. At segment , the model processes new tokens with an attention context of size , while having observed total tokens. The ratio grows linearly with , establishing the compression ratio. The parameter overhead comes solely from the learnable queries at each layer, totalling additional parameters, a fraction of the base model size.
H-MEM: Index-Based Hierarchical Routing
Definition 15 (H-MEM).
(Sun & Zeng, 2025 [15].) H-MEM organises the memory of an LLM agent into four nested levels, which the authors describe as analogous to a section, subsection, subsubsection and its content:
(Episode). The stored content itself: individual interaction episodes. Capacity , access time .
(Memory Trace). Groups of related episodes sharing a common thread. Capacity .
(Category). Groups of related traces. Capacity .
(Domain). The top-level partition of the memory store. Capacity .
The cognitive taxonomy of The Cognitive Memory Hierarchy is a useful analogy for why a hierarchy helps, but it is not this architecture's own decomposition: H-MEM's levels are organisational, not functional, and retrieval descends from the broadest partition to the individual episode.
Each level maintains a set of index nodes , where is an embedding summarising the content reachable via node . The index nodes form a tree with branching factor : each level- node has children at level .
Retrieval in H-MEM is a top-down, beam-search-like traversal of the index tree.
Definition 16 (Recursive Top- Traversal).
Given a query vector , retrieval proceeds top-down through the hierarchy: where is the parent node reached at the previous level, is its set of children, is the cosine similarity between the query and index node , and selects the highest-scoring children. Restricting the top- to rather than to all level- nodes is what makes the traversal a descent rather than a flat scan, and is what Proposition 7 depends on. The search begins at the root, .
Proposition 7 (H-MEM Retrieval Complexity).
With levels, branching factor , and uniform top- selection at each level, retrieval requires similarity computations, versus for exhaustive flat search.
Proof.
At each level , we expand the selected nodes, each with children at level . Computing the similarity score for all children costs inner products. Repeating across levels gives . In contrast, a flat search over all leaf nodes requires comparisons. Since for typical values (, , gives ), the hierarchical traversal yields an exponential speedup.
Hierarchical FFN Memory Banks
While HMT and H-MEM operate at the sequence level, a complementary approach embeds hierarchical memory directly into the feedforward layers of the Transformer.
Definition 17 (FFN Memory Bank).
(Pouransari et al., 2025 [16].) An external memory bank of key-value pairs, with . For a hidden state , the memory-augmented FFN output is: where is the key matrix. In practice, approximate nearest-neighbour search (e.g., product quantisation) makes the top- retrieval sub-linear.
The key empirical finding is that a small anchor model augmented with a large memory bank can match substantially larger models.
Proposition 8 (Anchor-Memory Efficiency).
Suppose the knowledge required by a language model follows a Zipf distribution with exponent over “knowledge units.” Let denote the capacity of the anchor model (encoding frequent knowledge) and the memory bank size (encoding rare knowledge). The fraction of tokens requiring a memory access scales as which decreases as the anchor grows, and does not depend on so long as the bank covers the tail. The decay is slow: for typical natural-language distributions , so the exponent is only , and this is exactly why the bank has to be large. At those values a 160M anchor model with 18M parameters fetched from a 4.6B-parameter memory bank matches a -larger standard model in perplexity.
Insight.
HMT, H-MEM, and FFN memory banks all implement the same foundational principle: recent or frequent information resides in fast, small memory; old or rare information resides in slow, large memory. This is precisely the CPU cache hierarchy (L1/L2/L3/DRAM) applied to neural architectures. The “access frequency” analogue shifts from memory addresses to semantic relevance, but the mathematical structure of capacity–latency trade-offs is identical.
Example 5 (Sizing an HMT System).
Consider a 7B-parameter LLM with , layers, deployed for a conversational agent needing 100K-token context. With segment size , , :
Number of segments: .
Effective context per segment: tokens.
Compression ratio: .
Added parameters: M, roughly of the base model.
KV cache savings. With heads of dimension , one token costs bytes, that is ,KiB. Standard attention holds all tokens, requiring ,GB (,GiB) in fp16, while HMT holds only tokens, requiring ,GB (,GiB). The ratio is , matching the compression ratio above.
Note that the parameter overhead here sits below the – range quoted in Proposition 6, which reflects larger values and per-layer memory modules than this minimal configuration uses.
State-Space Models and Recurrent Memory
The architectures of Hierarchical Memory Architectures compress past context into a small set of “summary tokens” accessed via cross-attention. State-space models (SSMs) take this idea to its logical extreme: the entire history is compressed into a single fixed-dimensional state vector, updated recurrently at each time step. This eliminates the quadratic attention cost entirely, but raises a fundamental question: how much of the past can a finite-dimensional state actually remember?
Linear State-Space Models
Definition 18 (Linear State-Space Model).
(Gu et al., 2022 [17].) A continuous-time linear state-space model is a dynamical system (SSM Continuous State) where is the hidden state, is the input, is the output, and , , , are learnable parameters. Discretised via zero-order hold with step size : (SSM Discretise A) The resulting discrete-time recurrence is (SSM Discrete State)
The remarkable property of linear SSMs is that the same model admits two equivalent computational modes: a recurrent mode for efficient inference and a convolutional mode for parallelised training.
Proposition 9 (Convolution-Recurrence Duality).
Proof.
Initialise . Unrolling the recurrence : where the sum runs from because feeds into at the same index, so the current input is included and is applied times to the input at step . Substituting into (with for clarity): where . The convolution can be evaluated for all simultaneously via the FFT in .
Remark 16.
The kernel decays exponentially when all eigenvalues of have modulus strictly less than . The S4 model [17] addresses this by initialising with a special HiPPO (High-order Polynomial Projection Operator) structure [18] that optimally approximates a sliding-window history polynomial, ensuring slow spectral decay and long-range memory. This connects directly to the dynamical systems analysis of Connection to Dynamical Systems.
From S4 to Mamba: Content-Based Selection
Linear SSMs have a critical limitation: since , , are fixed (input-independent), the model treats every token identically; it cannot selectively attend to relevant inputs or ignore irrelevant ones. Mamba resolves this by making the SSM parameters input-dependent.
Definition 19 (Selective State Spaces (Mamba)).
(Gu & Dao, 2023 [19].) Mamba modifies the standard SSM by making the discretisation parameters functions of the input: (Mamba Selection) where , , and are learned linear projections. The discretised matrices become step-dependent: , . The recurrence becomes (Mamba Recurrence) This selection mechanism breaks the convolution structure (since now varies per step) but enables content-based memory routing: the model can selectively write to or read from its state based on the input content.
Remark 17.
By making input-dependent, Mamba effectively learns when to write to its state and when to maintain it:
Large : , so the state is reset and the new input is written strongly.
Small : , so the state is preserved and the input is largely ignored.
This is directly analogous to the forget and input gates of LSTMs [20], but operates in continuous time and is parameterised more parsimoniously. The connection to the dynamical systems perspective of Connection to Dynamical Systems is immediate: Mamba implements a time-varying linear dynamical system whose stability properties change adaptively with the input.
Example 6 (Mamba Gating Behaviour).
Consider a sentiment analysis task. When processing the token “not,” outputs a large value, causing the state to reset and begin accumulating the negated sentiment. When processing filler words like “the” or “a,” outputs a small value, preserving the current state. This selective gating allows Mamba to match attention-based models on tasks requiring content-dependent routing, while maintaining per-step cost.
The Attention-Recurrence Trade-off
Proposition 10 (SSM Memory Capacity Bound).
The SSM state can store at most bits of information about the past, where is the representation precision. For a sequence of length where each token carries bits of task-relevant information, faithful memory requires In contrast, attention with a full KV cache stores parameters, enabling exact recall of any past token.
Proof.
The state is a vector of real numbers, each represented to precision . Each coordinate stores at most bits, giving a total capacity of bits. By the data processing inequality, no function of can recover more information about the input sequence than itself contains. For tokens at bits each, perfect recall requires bits, yielding the stated lower bound on .
Caution.
SSMs sacrifice precise token-level recall for fixed memory cost. For tasks requiring exact retrieval (e.g., “What was the 5th word in the 3rd paragraph?”), attention-based models substantially outperform SSMs. Hybrid architectures like Jamba [21] address this by interleaving Mamba layers (cheap, providing broad context coverage) with attention layers (expensive, providing precise token recall). The resulting model enjoys the efficiency of SSMs for the majority of layers while retaining the recall capability of attention where needed.
Proposition 11 (Hybrid SSM-Attention Efficiency).
A hybrid model with Mamba layers and attention layers, processing a sequence of length :
Memory: (state for SSM layers, KV cache for attention layers).
Computation: per forward pass.
Setting , the memory scales as per layer. Jamba uses , one attention layer per eight, which by the same expression gives an smaller KV cache than an all-attention model of comparable size: ,GB against Mixtral's ,GB at 256K context, and against ,GB for LLaMA-2 70B. Retrieval quality on needle-in-a-haystack style tasks is retained at that ratio.
Connections and Synthesis
Having surveyed the landscape of memory mechanisms, from grouped-query attention and sliding windows (def:gqa,def:sparse-pattern,def:sliding-window) through external memory systems (def:external-memory,def:engram), hierarchical architectures (def:hmt,def:hmem,def:ffn-memory), and state-space models (def:ssm,def:mamba), we now seek a unifying mathematical framework.
The Memory System Framework
Definition 20 (Memory System).
A memory system is a tuple where:
Each memory tier specifies a capacity (in tokens or bytes), access latency , and access pattern .
The routing function assigns each query to one or more memory tiers.
We require the hierarchy condition: and (faster tiers are smaller).
Theorem 3 (Memory-Computation Trade-off).
Consider a memory system holding distinct items, where item is accessed with probability and the items are indexed so that . An assignment is a map obeying the capacities, for every , and its expected access latency is Assume , so at least one feasible assignment exists. Then the greedy assignment minimises : place the most frequently accessed items in tier 1, the next in tier 2, and so on, filling each tier to capacity before spilling into the next.
Proof.
Let be any optimal assignment and suppose it is not greedy. Then there are items and with but , that is, a more frequently accessed item sitting in a slower tier than a less frequently accessed one. Exchanging their tiers keeps the assignment feasible, since it permutes two items between two tiers and changes no tier's occupancy, and it changes the objective by strictly decreasing and contradicting optimality. Hence no such inverted pair exists, which is precisely the statement that orders items by against tiers ordered by . Any two assignments with that property differ only by permutations within a tier, which leave unchanged, so the greedy assignment is optimal. This is the rearrangement inequality, and the argument uses only ; the capacity ordering plays no part.
Remark 18.
The picture, fill the fast tier and spill, resembles water-filling, but the mathematics is different. Information-theoretic water-filling solves a concave allocation problem in which marginal returns equalise across channels; here the objective is linear and the solution is the greedy rearrangement above. It is also worth noting what goes wrong without the capacity constraints written as occupancy bounds: a relaxed program that only requires with has its optimum at a single coordinate, the tier minimising , and never spills at all. Nor is that ratio monotone in : HBM at and SSD at give ratios and , decreasing, even though both latency and capacity increase.
Unification Table
Table 1 places every memory mechanism studied in this chapter into the framework of Definition 20.
| Method | State Space | Capacity | Latency | Access |
| KV Cache | , GPU HBM | Content | ||
| MQA/GQA (Definition 17) | , GPU HBM | Content | ||
| Sparse Attn (Definition 6) | , GPU | Pattern | ||
| SSM / Mamba (Definition 19) | , GPU | State | ||
| Engram (Definition 11) | , CPU/SSD | hash | N-gram hash | |
| HMT (Definition 13) | , GPU | Cross-attn | ||
| H-MEM (Definition 15) | Tree-indexed | Top- descent | ||
| FFN Bank (Definition 17) | , disk | Top- sim. | ||
| RAG (Definition 12) | Doc. corpus | Unbounded | High | Retrieval |
The Memory Heterogeneity Principle
Key Idea.
The Memory Heterogeneity Principle. No single memory mechanism is optimal for all types of knowledge. Efficient LLM systems combine fast, small memories for recent and frequent access (KV cache, SSM state) with slow, large memories for rare and historical access (Engram, RAG, FFN memory banks). The optimal allocation between tiers is governed by Theorem 3 and follows the same water-filling principle as CPU cache design and information-theoretic channel allocation.
Connections to Reasoning and Diffusion
Memory and reasoning as dual operations.
The recurrence-based reasoning framework of Recurrent Foundations for Iterative Computation iterates an operator on a state , producing a sequence that converges (under the conditions of Theorem 1) to a fixed point encoding the answer. Memory provides the data that operates on: attention retrieves relevant tokens, Engram fetches stored knowledge, and SSM state carries compressed history. In this view:
Reasoning adds depth: more iterations of extract more complex relationships.
Memory adds breadth: more data supplied to enables it to draw on more evidence.
The Engram U-shaped scaling law (Theorem 2) quantifies this duality: allocating too many parameters to memory (breadth) starves the reasoning module (depth), and vice versa. The optimal split is determined by the relative exponents of the compute and memory scaling laws.
Memory in diffusion language models.
Diffusion LMs (sec:diffusion_language) do not use autoregressive KV caches: they process all positions in parallel at each denoising step, recomputing full bidirectional attention. This means the memory cost per denoising step is , dominated by the attention computation rather than a growing cache. The memory challenge for diffusion LMs is therefore different:
Recomputation cost: each of denoising steps requires a full forward pass with attention.
No cache reuse: unlike autoregressive models, where prefill computation is amortised over generation steps, diffusion LMs must recompute from scratch at each step.
Opportunity: sparse attention patterns (Definition 6) and SSM-based denoising backbones can reduce the per-step cost, potentially making diffusion LMs more memory-efficient than autoregressive models for long sequences.
Remark 19.
The synthesis above reveals a surprising convergence: techniques originally developed for autoregressive memory management (sparse attention, state compression, hierarchical caching) find direct application in diffusion models, recurrent reasoning systems, and retrieval-augmented generation. The unifying thread is Theorem 3: every system must navigate the same capacity–latency frontier, regardless of the generative paradigm.
Historical Timeline
The study of memory in computing and in neural networks has a rich history spanning eight decades. fig:memory-timeline traces the key milestones from the foundational von Neumann architecture through modern hierarchical memory systems. Blue entries denote architectural innovations, green entries denote attention and efficiency methods, orange entries denote memory systems, and purple entries denote scaling and context extension techniques.
Exercises
Exercise 8 (KV Cache Arithmetic).
Consider LLaMA-3-405B with layers, attention heads, per-head dimension , and GQA with groups (Definition 17).
Compute the KV cache size in GB (fp16, 2 bytes per element) at context lengths , , and . Recall from Definition 17 that the query heads are divided into groups, each sharing a single key-value head, so the model has key-value heads in total (and the cache shrinks by the factor ). Hint: each layer stores elements.
The model weights occupy approximately 810,GB in fp16. Compare the KV cache size to the model weight size at each context length.
At what context length does the KV cache exceed the model weights? Express your answer in terms of , and , and note that does not appear.
Exercise 9 (Position Interpolation).
Consider RoPE (Definition 15) with base frequency and head dimension .
Compute the rotation frequency for (highest frequency) and (lowest frequency).
Compute the rotation angle at position for both frequencies from part (a). Express in radians and in number of full rotations.
Apply Position Interpolation (Definition 3) to extend the context from to (scaling factor ). Recompute the rotation angles at with the interpolated positions and verify that they fall within the range seen during training at .
Exercise 10 (YaRN Temperature).
When applying NTK-aware scaling (Definition 4) with factor , the attention logits for a query-key pair separated by distance scale differently across frequency bands.
Starting from , show that the highest-frequency component () is left unchanged, while the lowest-frequency component () is compressed by the full factor .
Argue that the attention entropy increases as the interpolated logit magnitudes contract, and explain why a multiplicative temperature on the logits is the natural correction.
Show that a logit multiplier of the form can restore the pre-interpolation entropy to first order, and note that YaRN fits empirically for the LLaMA family rather than deriving it. Verify for that , so the logits are multiplied by .
Exercise 11 (BigBird Connectivity).
Consider BigBird (Definition 8) with global tokens, sliding window of width , and sequence length .
Ignoring the global tokens, so that only window edges may be used, prove that information propagates between any two positions in at most hops.
For , , , compute that bound.
Now restore the global tokens and apply Theorem 1. How many hops are needed? Compare with your answer to (b) and explain, in one sentence, which structural feature of the pattern accounts for the whole difference.
For a Transformer with layers, each layer enables one hop. State the condition on for full connectivity, first with and then with .
Exercise 12 (Ring Attention Communication).
Consider Ring Attention (Proposition 4) with devices, sequence length tokens, , and fp16 precision.
Each device holds tokens. In each of the communication rounds, each device sends its KV block (of size elements) to the next device. Compute the total bytes communicated per layer across all rounds and all devices.
On NVLink with 900,GB/s bidirectional bandwidth, estimate the wall-clock communication time per layer. Assume communication is fully overlapped with computation where possible.
Estimate the Flash Attention computation time for tokens on an A100 GPU (312 TFLOPS fp16). Is the system compute-bound or communication-bound?
Exercise 13 (Engram Hash Collisions).
Engram (Definition 11) uses a hash table of size with 2-gram keys drawn from a vocabulary of size .
Assuming a uniform hash function, compute the expected number of entries per bucket when all possible 2-grams are inserted.
What is the probability that two distinct 2-grams and collide (i.e., map to the same bucket)?
For , require that the probability of at least one collision occurring among all inserted 2-grams is below . Using the birthday approximation with , what is the minimum table size ? Is this practical? Contrast it with the far weaker requirement that a single specified pair collide with probability below .
In practice, not all 2-grams appear. If only distinct 2-grams occur in the training corpus, how does the collision analysis change? Relate to the birthday paradox.
Exercise 14 (U-Shaped Scaling Optimisation).
The Engram scaling law (Theorem 2) gives the loss as where is the fraction of compute allocated to the neural model and to the memory module. Use , , , , .
Differentiate with respect to and set to zero. Show that the optimal split satisfies or derive an equivalent implicit equation.
Solve numerically for . Verify that is a minimum (not a maximum) by checking the second derivative.
How does change as increases from to ? Plot and interpret the trend: does a larger budget favour more memory or more compute?
Exercise 15 (HMT Compression Analysis).
A document of tokens is processed by HMT with segment size , , and .
How many segments are needed to process the full document?
What is the compression ratio ?
Each compression step (Definition 14) retains a fraction of the information, with . After 20 segments, what fraction of the original information from segment 1 remains in long-term memory?
At what number of segments does the retained information drop below ? Below ? What are the implications for very long documents?
Exercise 16 (H-MEM Retrieval Analysis).
An H-MEM system has levels, branching factor , and uniform top- selection at each level.
What is the total memory capacity (number of leaf entries)?
How many similarity computations are required per query?
What is the speedup over flat (exhaustive) search?
If each similarity computation takes 100,ns, what is the retrieval latency? Compare to a flat search over entries.
Exercise 17 (SSM Memory Capacity).
Consider a Mamba model with state dimension and fp16 precision ( for the significand).
Using Proposition 10, compute the maximum number of bits storable in the state.
For a 128K-token sequence where each token carries bits of task-relevant information, what fraction of the total information can the state represent?
Design a hybrid architecture: Mamba for of layers, attention for of layers (each with full KV cache). For a model with layers and , compute the total memory at K tokens. What are the savings compared to full attention?
Exercise 18 (Convolution-Recurrence Duality).
Starting from the discrete SSM recurrence with :
Prove by induction that with . Check the case against the recurrence before generalising.
What condition on the eigenvalues of ensures that the convolution kernel decays exponentially?
Relate the eigenvalue condition to the vanishing gradient problem in RNNs. Why does the HiPPO initialisation help?
Show that if is diagonal with entries , the kernel can be evaluated in time without matrix powers.
Exercise 19 (Memory Bandwidth Analysis).
Consider an A100 GPU with 2,TB/s HBM bandwidth (Definition 2) and a KV cache of 10,GB.
During autoregressive generation, each token requires reading the entire KV cache. What is the maximum generation rate (tokens/second), ignoring computation time?
The model has attention heads. With GQA (Definition 17) using groups, so that there are key-value heads shared among the query heads, the cache shrinks by the factor , to ,GB. What is the new generation rate?
Suppose we offload of the KV cache to CPU memory, accessible via PCIe 5.0 at 64,GB/s. The remaining stays in HBM. What is the effective bandwidth, assuming uniform access? What is the generation rate?
At what offloading fraction does the system become communication-bound (CPU bandwidth limits throughput)?
Exercise 20 (RAG as a Memory System).
Map Retrieval-Augmented Generation (Definition 12) into the memory system framework of Definition 20.
Identify the memory tiers. What is the “fast tier” and what is the “slow tier”? What are their capacities and latencies?
What is the routing function ? How does it decide which queries go to the retrieval tier?
Compare RAG's memory system to Engram's (Definition 11). What are the key differences in routing, latency, and integration depth?
Under what conditions does Theorem 3 predict that RAG outperforms a larger model without retrieval?
Exercise 21 (Engram vs. Mixture of Experts).
Compare two approaches to scaling knowledge capacity:
Engram: a hash table with entries, each of dimension , totalling parameters. Lookup is via hashing.
Mixture of Experts (MoE): experts, each an FFN with parameters, totalling parameters. Top- routing costs for the gating computation.
Express the total parameter count and per-token FLOP cost for each approach.
Under what relationship between , , and does Engram store more parameters per FLOP of lookup cost?
MoE experts can compute with their parameters (via the FFN), while Engram entries are passively retrieved. Discuss the qualitative implications: when is passive retrieval sufficient, and when is active computation necessary?
Propose a hybrid “Engram-of-Experts” architecture that uses hash-based routing to select experts. What are the potential benefits and challenges?
Exercise 22 (Open Problem: Optimal Memory Architecture).
Given a total parameter budget , a target context length , and a task distribution :
Formalise the problem of finding the optimal memory architecture as an optimisation problem. Your decision variables should include: the number of tiers , the capacity and access mechanism of each tier, and the routing function . Your objective should minimise the expected loss on .
Why is this optimisation problem computationally hard? Identify at least three sources of difficulty (combinatorial structure, non-convexity, distribution dependence, etc.).
Using the insight from the U-shaped scaling law (Theorem 2), propose a practical heuristic: (i) estimate the scaling exponents and from small-scale experiments, (ii) compute the optimal split , and (iii) allocate tiers greedily along the Pareto frontier of fig:memory-landscape. Under what assumptions is this heuristic near-optimal?
References
-
Neural Turing Machines
BibTeX
@article{graves2014neural, title={Neural Turing Machines}, author={Graves, Alex and Wayne, Greg and Danihelka, Ivo}, journal={arXiv preprint arXiv:1410.5401}, year={2014} }Journal article
-
Memory Networks
BibTeX
@inproceedings{weston2015memory, title={Memory Networks}, author={Weston, Jason and Chopra, Sumit and Bordes, Antoine}, booktitle={International Conference on Learning Representations}, year={2015} }Conference paper
-
Extending Context Window of Large Language Models via Positional Interpolation
BibTeX
@article{chen2023extending, title={Extending Context Window of Large Language Models via Positional Interpolation}, author={Chen, Shouyuan and Wong, Sherman and Chen, Liangjian and Tian, Yuandong}, journal={arXiv preprint arXiv:2306.15595}, year={2023} }Journal article
-
YaRN: Efficient Context Window Extension of Large Language Models
BibTeX
@article{peng2024yarn, title={{YaRN}: Efficient Context Window Extension of Large Language Models}, author={Peng, Bowen and Quesnelle, Jeffrey and Fan, Honglu and Shippole, Enrico}, journal={arXiv preprint arXiv:2309.00071}, year={2024} }Journal article
-
BigBird: Transformers for Longer Sequences
BibTeX
@inproceedings{zaheer2020bigbird, title={{BigBird}: Transformers for Longer Sequences}, author={Zaheer, Manzil and Guruganesh, Guru and Dubey, Kumar Avinava and Ainslie, Joshua and Alberti, Chris and Ontanon, Santiago and others}, booktitle={Advances in Neural Information Processing Systems}, volume={33}, year={2020} }Conference paper
-
Hybrid Computing Using a Neural Network with Dynamic External Memory
BibTeX
@article{graves2016hybrid, title={Hybrid Computing Using a Neural Network with Dynamic External Memory}, author={Graves, Alex and Wayne, Greg and Reynolds, Malcolm and Harley, Tim and Danihelka, Ivo and Grabska-Barwi{\'n}ska, Agnieszka and others}, journal={Nature}, volume={538}, number={7626}, pages={471--476}, year={2016} }Journal article
-
Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer
BibTeX
@inproceedings{shazeer2017outrageously, title={Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer}, author={Shazeer, Noam and Mirhoseini, Azalia and Maziarz, Krzysztof and Davis, Andy and Le, Quoc and Hinton, Geoffrey and Dean, Jeff}, booktitle={International Conference on Learning Representations}, year={2017} }Conference paper
-
Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks
BibTeX
@article{lewis2020retrieval, title={Retrieval-Augmented Generation for Knowledge-Intensive {NLP} Tasks}, author={Lewis, Patrick and Perez, Ethan and Piktus, Aleksandra and Petroni, Fabio and Karpukhin, Vladimir and Goyal, Naman and others}, journal={Advances in Neural Information Processing Systems}, volume={33}, year={2020} }Journal article
-
Human Memory: A Proposed System and Its Control Processes
BibTeX
@article{atkinson1968human, title={Human Memory: A Proposed System and Its Control Processes}, author={Atkinson, Richard C. and Shiffrin, Richard M.}, journal={Psychology of Learning and Motivation}, volume={2}, pages={89--195}, year={1968} }Journal article
-
Working Memory
BibTeX
@article{baddeley1974working, title={Working Memory}, author={Baddeley, Alan D. and Hitch, Graham}, journal={Psychology of Learning and Motivation}, volume={8}, pages={47--89}, year={1974} }Journal article
-
Episodic and Semantic Memory
BibTeX
@article{tulving1972episodic, title={Episodic and Semantic Memory}, author={Tulving, Endel}, journal={Organization of Memory}, pages={381--403}, year={1972}, publisher={Academic Press} }Journal article
-
The Magical Number Seven, Plus or Minus Two: Some Limits on Our Capacity for Processing Information
BibTeX
@article{miller1956magical, title={The Magical Number Seven, Plus or Minus Two: Some Limits on Our Capacity for Processing Information}, author={Miller, George A.}, journal={Psychological Review}, volume={63}, number={2}, pages={81--97}, year={1956} }Journal article
-
HMT: Hierarchical Memory Transformer for Efficient Long Context Language Processing
BibTeX
@inproceedings{he2024hmt, title={{HMT}: Hierarchical Memory Transformer for Efficient Long Context Language Processing}, author={He, Zifan and others}, booktitle={Proceedings of NAACL}, note={arXiv:2405.06067}, year={2025} }Conference paper
-
Perceiver: General Perception with Iterative Attention
BibTeX
@inproceedings{jaegle2021perceiver, title={Perceiver: General Perception with Iterative Attention}, author={Jaegle, Andrew and Gimeno, Felix and Brock, Andrew and Zisserman, Andrew and Vinyals, Oriol and Carreira, Jo{\~a}o}, booktitle={International Conference on Machine Learning}, pages={4651--4664}, year={2021} }Conference paper
-
Hierarchical Memory for High-Efficiency Long-Term Reasoning in LLM Agents
BibTeX
@article{sun2025hmem, title={Hierarchical Memory for High-Efficiency Long-Term Reasoning in {LLM} Agents}, author={Sun, Haoran and Zeng, Shaoning}, journal={arXiv preprint arXiv:2507.22925}, year={2025} }Journal article
-
Pretraining with Hierarchical Memories: Separating Long-Tail and Common Knowledge
BibTeX
@article{pouransari2025hierarchical, title={Pretraining with Hierarchical Memories: Separating Long-Tail and Common Knowledge}, author={Pouransari, Hadi and others}, journal={arXiv preprint arXiv:2510.02375}, year={2025} }Journal article
-
Efficiently Modeling Long Sequences with Structured State Spaces
BibTeX
@article{gu2022efficiently, title={Efficiently Modeling Long Sequences with Structured State Spaces}, author={Gu, Albert and Goel, Karan and R{\'e}, Christopher}, journal={International Conference on Learning Representations}, year={2022} }Journal article
-
HiPPO: Recurrent Memory with Optimal Polynomial Projections
BibTeX
@article{gu2020hippo, title={{HiPPO}: Recurrent Memory with Optimal Polynomial Projections}, author={Gu, Albert and Dao, Tri and Ermon, Stefano and Rudra, Atri and R{\'e}, Christopher}, journal={Advances in Neural Information Processing Systems}, volume={33}, year={2020} }Journal article
-
Mamba: Linear-Time Sequence Modeling with Selective State Spaces
BibTeX
@article{gu2023mamba, title={Mamba: Linear-Time Sequence Modeling with Selective State Spaces}, author={Gu, Albert and Dao, Tri}, journal={arXiv preprint arXiv:2312.00752}, year={2023} }Journal article
-
Long Short-Term Memory
BibTeX
@article{hochreiter1997long, title={Long Short-Term Memory}, author={Hochreiter, Sepp and Schmidhuber, J{\"u}rgen}, journal={Neural Computation}, volume={9}, number={8}, pages={1735--1780}, year={1997} }Journal article
-
Jamba: A Hybrid Transformer-Mamba Language Model
BibTeX
@article{lieber2024jamba, title={Jamba: A Hybrid Transformer-Mamba Language Model}, author={Lieber, Opher and Lenz, Barak and Bata, Horace and Cohen, Gal and Osin, Jhonathan and others}, journal={arXiv preprint arXiv:2403.19887}, year={2024} }Journal article
-
Longformer: The Long-Document Transformer
BibTeX
@article{beltagy2020longformer, title={Longformer: The Long-Document Transformer}, author={Beltagy, Iz and Peters, Matthew E. and Cohan, Arman}, journal={arXiv preprint arXiv:2004.05150}, year={2020} }Journal article
-
Ring Attention with Blockwise Transformers for Near-Infinite Context
BibTeX
@inproceedings{liu2023ring, title={Ring Attention with Blockwise Transformers for Near-Infinite Context}, author={Liu, Hao and Zaharia, Matei and Abbeel, Pieter}, booktitle={International Conference on Learning Representations}, note={arXiv:2310.01889, October 2023}, year={2024} }Conference paper
-
Conditional Memory via Scalable Lookup: A New Axis of Sparsity for Large Language Models
BibTeX
@article{cheng2026engram, title={Conditional Memory via Scalable Lookup: A New Axis of Sparsity for Large Language Models}, author={Cheng, Xin and others}, journal={arXiv preprint arXiv:2601.07372}, year={2026} }Journal article