AI Logic

Architectures

Neural Attention Memory Models (NAMMs)

Updated:

Structure of NAMMs. The left shows the overall flow: each token's column of the attention matrix is turned into features with a short-time Fourier transform and an exponential moving average, recency features are concatenated, the memory model outputs scores, and tokens scoring below 0 are dropped from the KV cache; below it is training with CMA-ES. The right shows the inside of BAM (self-attention with a backward mask, residual and multiplicative combination, a linear layer) and the range visible under the backward mask.

Background and overview

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 KK and values VV 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=512n_{\text{up}} = 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.

  1. Take the attention matrix AA for the latest 512 queries. The column AiA_i for the ii-th token in the KV cache is a signal that lists, in time order, "how much each query attended to token ii."
  2. 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\omega_i^t of 17 frequency magnitudes for each segment t=1,…,nTt = 1, \dots, n_T (nT=512/16=32n_T = 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.
  3. Collapse the segment axis into one vector with an exponential moving average. The value ωi′\omega'_i from the previous run is also discounted and added, so the whole history since the token entered is reflected.
ωi=(∑t=1nTγ t−1 ωit)+γ nT ωi′\omega_i = \left(\sum_{t=1}^{n_T} \gamma^{\,t-1}\, \omega_i^t\right) + \gamma^{\,n_T}\, \omega'_i

Here γ=0.9916\gamma = 0.9916 is the discount factor.

  1. Concatenate to ωi\omega_i an 8-dimensional sinusoidal feature that encodes the token's "age" (the number of queries seen since it entered the cache).
  2. The memory model mϕm_\phi outputs a score sis_i for each token.
  3. Drop tokens with si<0s_i < 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\omega_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)o_i = \mathrm{attention}_{\hat{M}}\bigl(K_\Omega, V_\Omega, Q_\Omega\bigr), \qquad s_i = \mathrm{linear}(o_i)

M^\hat{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.

  1. Draw 32 candidate weight vectors from a normal distribution defined by a mean vector and a covariance matrix.
  2. 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.
  3. 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.

MethodLongBench (21 tasks)InfiniteBenchInfiniteBench cacheChouBunChouBun cache
Base model (keep all)28.86 (1.00)1.053274721.2112099
H2O28.37 (0.99)1.05819319.868292
L227.42 (1.00)1.63819318.938292
FastGen27.88 (0.95)1.422301618.938616
NAMMs29.33 (1.11)11.001319224.449895
  • 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 toBase modelH2OL2NAMMsNAMMs cache (relative to base)
Llama 3 70B (LongBench)35.2234.1733.5034.700.83
Llava Next Video 7B (long video understanding)43.8441.9741.4544.380.72
Decision Transformer (9 D4RL tasks)29.0428.7027.9131.730.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.

MethodWhat it reducesHow it decidesTraining the base modelEffect on performance
H2ONumber of tokens in the cacheSimple statistics of the attention matrixNot neededTends to drop as the cache shrinks
L2Number of tokens in the cacheL2 norm of the keysNot neededSame as above
FastGenNumber of tokens in the cacheInspects each head's attention pattern and switches among several rulesNot neededSame as above
NAMMsNumber of tokens in the cacheA learned network outputs scores from attention spectrogramsNot needed (only NAMMs are trained, with an evolution strategy)Improves on many tasks
MQA, GQANumber of keys and values per headFixed by the architectureNeeded (trained in that form)Not compared in this paper
KV cache quantizationBits per valueChanges the numeric representationDepends on the methodNot compared in this paper

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.

References

  1. Cetin, E., Sun, Q., Zhao, T., & Tang, Y. (2025). An Evolved Universal Transformer Memory. ICLR 2025. arXiv:2410.13166.
  2. Sakana AI. evo-memory (official implementation of NAMMs).
  3. Zhang, Z., Sheng, Y., Zhou, T., Chen, T., Zheng, L., Cai, R., Song, Z., Tian, Y., Ré, C., Barrett, C., et al. H2O: Heavy-Hitter Oracle for Efficient Generative Inference of Large Language Models. arXiv:2306.14048.
  4. Devoto, A., Zhao, Y., Scardapane, S., & Minervini, P. (2024). A Simple and Effective L2 Norm-Based Strategy for KV Cache Compression. arXiv:2406.11430.
  5. Ge, S., Zhang, Y., Liu, L., Zhang, M., Han, J., & Gao, J. (2024). Model Tells You What to Discard: Adaptive KV Cache Compression for LLMs (FastGen). ICLR 2024. arXiv:2310.01801.