NAMMs (Neural Attention Memory Models) are small networks that decide which tokens to drop from the "KV cache" of a pretrained Transformer. They were proposed in 2024 by Cetin et al. of Sakana AI in the paper "An Evolved Universal Transformer Memory" (ICLR 2025).
When a language model generates text one token at a time, it stores the keys K and values V of all previous tokens and matches them against the query of the new token. This storage is called the KV cache. The KV cache is like the model's "working memory": the longer the input, the larger it grows, and the more memory and computation it needs.
Earlier methods shrank the KV cache with hand-designed rules, such as dropping "tokens that receive little attention" or "tokens whose keys have a large norm." However, these traded away some performance for efficiency.
NAMMs learn the dropping rule itself. They have three key features:
They look only at attention values: The features describe how much, and with what periodicity, each token has been attended to by past queries. They do not depend on the weights of the base model.
They keep different tokens per layer and head: The same network is applied separately to the KV cache of every layer and every head.
They are trained with an evolution strategy: "Drop or keep" is not differentiable, so the gradient-free CMA-ES searches for weights that improve task scores.
In the paper, NAMMs trained on top of Llama 3 8B shrank the KV cache while scoring higher on long-context tasks than the original model that keeps all tokens. Moreover, NAMMs trained only on language were still effective when transferred as-is (without additional training) to a model that handles video and to the reinforcement learning model Decision Transformer.
Mechanism and computation steps
Every time the base model processes nup=512 tokens, NAMMs perform the following computation in each layer and each head (left of the figure at the top of the article). Long inputs are fed in chunks of 512 tokens.
Take the attention matrix A for the latest 512 queries. The column Ai for the i-th token in the KV cache is a signal that lists, in time order, "how much each query attended to token i."
Apply a short-time Fourier transform (STFT) to this signal. A discrete Fourier transform is taken with a Hann window of length 32 shifted by 16 each time, producing a vector ωit of 17 frequency magnitudes for each segment t=1,…,nT (nT=512/16=32). This compresses not only the "strength" of attention but also "with what periodicity it was attended to" into features of a fixed size.
Collapse the segment axis into one vector with an exponential moving average. The value ωi′ from the previous run is also discounted and added, so the whole history since the token entered is reflected.
ωi=(t=1∑nTγt−1ωit)+γnTωi′
Here γ=0.9916 is the discount factor.
Concatenate to ωi an 8-dimensional sinusoidal feature that encodes the token's "age" (the number of queries seen since it entered the cache).
The memory model mϕ outputs a score si for each token.
Drop tokens with si<0 from the KV cache. Only the remaining tokens are attended to from then on.
The memory model uses a design called BAM (Backward Attention Memory) (right of the figure at the top of the article). It applies single-head self-attention with queries, keys, and values built from the features ωi of all tokens in the cache, and finally turns the result into scores with a linear layer.
oi=attentionM^(KΩ,VΩ,QΩ),si=linear(oi)
M^ is a backward mask: each token sees only itself and tokens newer than itself. This is the opposite direction of the mask in GPT and similar models (which see only tokens older than themselves). The attention output has twice the feature dimension and is merged back into the input through a residual and multiplicative combination before going to the linear layer. Layer normalization is not used. The weights are shared across all layers, and the whole model has only about 4,000 parameters.
Training uses the evolution strategy CMA-ES.
Draw 32 candidate weight vectors from a normal distribution defined by a mean vector and a covariance matrix.
Attach each candidate's NAMMs to the base model, have it solve long-context tasks, and score it. The score is normalized by the score of the base model that keeps all tokens.
Move the mean and covariance toward the better-scoring candidates.
Tasks are added one at a time (incremental evolution). In the paper, training ran for 300 generations on English passage retrieval (PassageRetrieval-en), 250 more after adding Chinese reading comprehension (DuReader), and 120 more after adding story question answering (NarrativeQA). The respective metrics are exact-match accuracy, ROUGE-L, and F1 score.
NAMMs can be compared to a secretary who tidies up the documents on a desk. The secretary does not read the documents; they decide what to put away based only on "whether a document has been looked at recently" and "at what intervals it gets revisited." Because the secretary never reads the content, the same secretary can work whether the documents are text or video.
Why it works
The paper explains why NAMMs can improve performance, not just efficiency, as follows.
Dropping unneeded information lets the model focus on what remains: Long inputs contain many parts unrelated to the task, as well as duplicates. Just as prompt engineering by people changes scores, tidying the context the model sees leaves room for higher scores. Because NAMMs directly maximize task scores, they can learn to drop tokens "for the sake of the score" rather than "for the sake of efficiency."
They can give each layer and head a different context: In the analysis, early to middle layers kept many tokens relevant to the whole input, such as the task preamble and key words, for a long time, while later layers dropped them and focused on fine-grained local information. In coding tasks, whitespace, comments, and boilerplate code blocks were often dropped.
Using only attention values as features makes them transferable to other models: The features do not depend on the base model's weights or embeddings. They can therefore be used, without retraining, on language models of different sizes, video models, and reinforcement learning models.
The backward mask can spot duplicates: When the same sentence appears twice, the older tokens can see the newer ones and recognize that "the same thing appears later," so only the older copy is dropped. The newer copy's score is not affected by the older one, so the information is never lost entirely.
Evolution strategies can learn non-differentiable operations: Whether to drop a token is a 0-or-1 choice through which no gradient flows. CMA-ES searches for weights by looking only at scores, which avoids this problem. Backpropagation is not needed either; training just repeats inference with NAMMs attached.
In the analysis, the longer a task's inputs, the smaller the fraction of tokens kept relative to input length (correlation coefficient −0.84). The paper interprets this as NAMMs naturally learning, without any set limit, a strategy of forgetting duplicates and distracting information at a faster pace in longer contexts.
Experimental results
On Llama 3 8B (with its context extended from 8192 to 32768 tokens), NAMMs were compared with the base model that keeps all tokens and with the hand-designed rules H2O, L2, and FastGen. Values in parentheses are relative to the base model set to 1. For LongBench, the value in parentheses is the average over the 21 tasks of each task's score relative to the base model, so L2 comes out at 1.00 even though its average score is lower.
Method
LongBench (21 tasks)
InfiniteBench
InfiniteBench cache
ChouBun
ChouBun cache
Base model (keep all)
28.86 (1.00)
1.05
32747
21.21
12099
H2O
28.37 (0.99)
1.05
8193
19.86
8292
L2
27.42 (1.00)
1.63
8193
18.93
8292
FastGen
27.88 (0.95)
1.42
23016
18.93
8616
NAMMs
29.33 (1.11)
11.00
13192
24.44
9895
LongBench: Even on the tasks not used for training alone, NAMMs reached 1.07 times the base model.
InfiniteBench (average input of nearly 200,000 tokens): The base model scored close to 0 on most tasks, but NAMMs raised the overall score to 11.00 with a cache about 40% the size of the base model's.
ChouBun (a Japanese long-context benchmark built by the paper; no Japanese was used in training): The overall score rose by about 15%.
The results of transferring NAMMs trained only on language to other models without retraining are as follows.
Transferred to
Base model
H2O
L2
NAMMs
NAMMs cache (relative to base)
Llama 3 70B (LongBench)
35.22
34.17
33.50
34.70
0.83
Llava Next Video 7B (long video understanding)
43.84
41.97
41.45
44.38
0.72
Decision Transformer (9 D4RL tasks)
29.04
28.70
27.91
31.73
0.81
In the video model, NAMMs dropped almost exclusively redundant video frame tokens rather than the text of the final question. With Decision Transformer, scores improved on 8 of the 9 tasks. The paper suggests that forgetting past failed actions may have kept the model from imitating them.
Practical considerations
NAMMs do not always improve performance. When transferred to Llama 3 70B, the overall score fell slightly below the base model (35.22 → 34.70). It is better than H2O or L2, but scores drop on some tasks. On LongBench as well, one of the multi-document question answering tasks (2-4) fell to 0.80 of the base model.
The cache size cannot be specified directly. Tokens with a score below 0 are simply dropped, so how much remains depends on the input and the task. When transferring to the video model, the paper shifts the score threshold by 5 to match the cache size of the other methods.
The values of the attention matrix are required. Each layer and head gains the extra work of extracting the attention weights of the latest 512 queries and applying the STFT.
Training needs a lot of inference. No gradients are needed, but each generation repeats inference on long inputs for 32 candidates. The paper keeps the cost down and improves generalization by using only part of the prompts for each task and adding tasks incrementally.
How far NAMMs trained on language carry over to other domains has been verified only within the paper's three transfer targets (a large language model, video, and reinforcement learning).
Comparison with other methods
The following table compares, from the same viewpoints, methods that reduce the burden of the KV cache in long contexts.
Method
What it reduces
How it decides
Training the base model
Effect on performance
H2O
Number of tokens in the cache
Simple statistics of the attention matrix
Not needed
Tends to drop as the cache shrinks
L2
Number of tokens in the cache
L2 norm of the keys
Not needed
Same as above
FastGen
Number of tokens in the cache
Inspects each head's attention pattern and switches among several rules
Not needed
Same as above
NAMMs
Number of tokens in the cache
A learned network outputs scores from attention spectrograms
Not needed (only NAMMs are trained, with an evolution strategy)
Because NAMMs reduce the number of tokens, they reduce something different from MQA, GQA, or quantization, and the paper states that they can be combined. PagedAttention, which makes memory allocation more efficient, also addresses a different problem from NAMMs, which choose tokens to drop.
Rough guidelines for choosing:
Improving scores as well as efficiency on long-context tasks: NAMMs are a candidate. An official implementation is publicly available.
Setting a strict upper limit on the cache: H2O or L2, which let the limit be specified, may be easier to work with.
Training a model from scratch: Build in architectural measures such as MQA or GQA from the start, and add token selection like NAMMs on top as needed.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
"""
A small example of one run of NAMMs (Algorithms 1 and 2 and Eqs. (3)(4) of the paper).
For one layer and one head of the base model, build features from the attention matrix, score them with BAM, and drop tokens with s_i < 0.
The details of the residual and multiplicative combination are simplified to follow the paper's description (the output has twice the dimension and is merged back).
"""
N_UP, N_W, S_W, GAMMA, POS_DIM = 512, 32, 16, 0.9916, 8
N_FREQ = N_W // 2 + 1 # 17 frequencies
def attention_spectrogram(A):
# A: [512 queries, n cache tokens]. Apply the STFT per column (per token) and take frequency magnitudes
cols = A.T # [n, 512]
spec = torch.stft(cols, n_fft=N_W, hop_length=S_W, window=torch.hann_window(N_W),
center=False, return_complex=True).abs() # [n, 17, number of segments]
return spec
def ema_reduce(spec, prev):
# Eq. (4): collapse the segment axis with an EMA, and add the discounted previous value prev
n_t = spec.shape[-1]
w = GAMMA ** torch.arange(n_t, dtype=spec.dtype) # γ^{t-1}
return (spec * w).sum(-1) + (GAMMA ** n_t) * prev # [n, 17]
def oldness_features(age):
# 8-dim sinusoidal features of age (number of queries seen since entering the cache)
i = torch.arange(POS_DIM // 2, dtype=torch.float32)
freq = 1.0 / (10000 ** (2 * i / POS_DIM))
ang = age.float().unsqueeze(-1) * freq
return torch.cat([torch.sin(ang), torch.cos(ang)], dim=-1)
class BAM(nn.Module):
"""Self-attention with a backward mask (1 head, no layer norm) -> residual and multiplicative combination -> linear layer"""
def __init__(self, d_in=N_FREQ + POS_DIM, d_hidden=16):
super().__init__()
self.q = nn.Linear(d_in, d_hidden)
self.k = nn.Linear(d_in, d_hidden)
self.v = nn.Linear(d_in, 2 * d_in) # Output has twice the feature dimension
self.out = nn.Linear(d_in, 1)
self.d_hidden = d_hidden
def forward(self, x): # x: [n, d_in] (ordered oldest first)
n = x.shape[0]
att = self.q(x) @ self.k(x).T / self.d_hidden ** 0.5
older = torch.tril(torch.ones(n, n, dtype=torch.bool), diagonal=-1)
att = att.masked_fill(older, float("-inf")) # Do not look at older tokens (only self and newer tokens)
o = torch.softmax(att, dim=-1) @ self.v(x) # [n, 2 * d_in]
add, mul = o.chunk(2, dim=-1)
h = x + add + x * mul # Residual and multiplicative combination
return self.out(h).squeeze(-1) # Score s_i
@torch.no_grad()
def namm_step(A, k_cache, v_cache, prev_feat, age, bam):
# A: [512, n], k_cache / v_cache: [n, d_head], prev_feat: [n, 17], age: [n]
feat = ema_reduce(attention_spectrogram(A), prev_feat)
x = torch.cat([feat, oldness_features(age)], dim=-1)
# The paper normalizes features to unit variance on training data (omitted here)
keep = bam(x) >= 0 # Drop tokens with s_i < 0
return k_cache[keep], v_cache[keep], feat[keep], age[keep]
bam = BAM()
print(sum(p.numel() for p in bam.parameters())) # A small network of a few thousand parameters
n, d_head = 1000, 128
A = torch.softmax(torch.randn(N_UP, n), dim=-1)
k, v = torch.randn(n, d_head), torch.randn(n, d_head)
k, v, feat, age = namm_step(A, k, v, torch.zeros(n, N_FREQ), torch.arange(n, 0, -1), bam)
print(k.shape) # Only the remaining tokens are left
# Training uses gradient-free CMA-ES (pip install cma). evaluate returns the normalized score of the base model with NAMMs attached
# import cma
# x0 = torch.nn.utils.parameters_to_vector(bam.parameters()).numpy()
# es = cma.CMAEvolutionStrategy(x0, 0.65, {"popsize": 32})
# while not es.stop():
# cands = es.ask()
# es.tell(cands, [-evaluate(c) for c in cands]) # cma minimizes, so flip the sign
FAQ
Q. Do NAMMs change the weights of the base language model?
A.
No. NAMMs only select KV cache tokens from outside the base model, and the only thing trained is the roughly 4,000 parameters of NAMMs themselves. They can therefore be added to a pretrained model afterward or transferred to other models.
Q. Why are they trained with an evolution strategy instead of gradient descent?
A.
Because the choice to "keep or drop" a token is a 0-or-1 operation through which no gradient flows. CMA-ES has candidate weights solve tasks and updates the weights based only on the scores, so it can directly maximize non-differentiable choices as well as non-differentiable metrics such as exact-match accuracy and ROUGE-L.
Q. The name contains "Universal Transformer." Is it related to the Universal Transformer?
A.
The paper's title is "An Evolved Universal Transformer Memory," but it is unrelated to the layer-repeating Universal Transformer. Here, "universal" means that because NAMMs look only at attention values, they can be used with any Transformer, whether for language, video, or reinforcement learning.