Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

~8 min readGoogle · 2025

Titans,
explained.

Every model you've used has two speeds of memory: the context window (perfect recall, brutally expensive, forgets everything when full) and the weights (vast knowledge, frozen at training time). Titans asks the question in between: what if part of the model could keep learning while it reads — writing the surprising parts of your document into its own weights, at test time, on the fly?

The delta

What changes against Mamba: the memory keeps learning after training

Rung 4's state is a compressed summary written by fixed weights. This rung asks a different question: what if the long-term memory is itself a small network whose weights are updated during inference, so that reading a long input literally trains the module that will later be asked to recall it? The memory stops being a buffer the model writes into and becomes a model the input fits.

The interesting part is what decides whether something is written, because a memory that stores everything is a transcript again. The rule is surprise: how much the memory module would have to change to account for this input is exactly how much it did not already predict it, and that quantity — the gradient of the memory's own loss — is used as the write signal. Unsurprising input barely moves the weights; a genuinely new fact moves them a lot. Two further controls keep that usable at length: a momentum term, so a surprising passage keeps influencing the update for a while rather than only at the instant it appeared, and explicit forgetting, so finite capacity is reclaimed instead of saturating.

Stated in the units the ladder compares on: the long-term memory is consulted at a cost that does not scale with how much has been stored, so this is a third answer to rung 4's capacity problem — not a bigger fixed state and not exact attention, but a learned map. The architecture is presented with several ways to wire it in relative to the attention that remains — as extra context, as a gate, or as its own layer — and the reported evaluations run to contexts in the millions of tokens.

01

Two memories, and the gap between them

Attention is a phenomenal short-term memory: every token can look at every other token, losslessly. The price is quadratic cost and a hard window — outside it, the past simply doesn't exist. Recurrent architectures like Mamba take the opposite trade: compress all history into a fixed-size state. Linear cost, unlimited length — but compression is lossy, and details fade.

Model weights are the third store: a vast long-term memory of everything seen in training — and completely frozen at inference. Nothing you show a deployed model changes them. So the field's dilemma: perfect-but-bounded recall, or unbounded-but-lossy compression, with no memory that grows during use. Titans aims squarely at that gap.

02

A memory that learns while it reads

Titans adds a neural long-term memory: a small MLP whose whole job is to store associations — and whose weights are updated during inference. As the sequence streams in, each chunk can trigger a gradient step on the memory module. Reading is training, for that one small component; the backbone stays frozen.

Inference step, with a memory that writes
Incoming tokens
→
Surprise check
prediction error
→
Gradient write
memory weights update
→
Attention + memory
answer from both

Retrieval is just a forward pass: query the memory MLP and it reproduces what it stored. Because the memory is weights — not a token buffer — its capacity doesn't consume the context window, and reading a 2M-token document doesn't mean attending over 2M tokens. The distant past lives in the memory; attention handles the recent window it's actually good at.

The key idea

Stop choosing between "keep every token" and "compress everything." Keep a learner in the loop: a module that trains on your input as it arrives, so the past is stored the way models store everything durable — in weights.

03

What gets written? Whatever surprises it

A memory that writes everything equally would drown in routine text. Titans borrows a page from human memory: we remember what violates expectations. Its write strength is driven by a surprise metric — the gradient of the memory's prediction error on the incoming input. Content the memory already anticipates yields small gradients: barely stored. Content that breaks its expectations yields large gradients: written hard.

"…the meeting is at 3pm on Thursday…" low surprise → faint write
"…the launch code is TANGO-7-ECHO…" high surprise → strong write

The elegance is that the signal is free — it's the same gradient the update already computes. Surprise decides what to remember; the gradient step decides how. One mechanism, both jobs.

04

Momentum and forgetting — memory as an optimizer

Raw surprise has failure modes: a single shocking token shouldn't erase context (surprise spikes then vanishes), and a finite memory that never forgets eventually overwrites itself into mush. Titans handles both with tools straight out of optimization.

Momentum smooths the write signal: past surprise carries into the present, so an important passage keeps getting written even when individual tokens stop being shocking. A learned forgetting gate (weight decay on the memory) fades stale associations to make room — adaptive, data-dependent forgetting rather than a fixed horizon. The memory module is, in effect, a tiny optimizer with momentum and decay, running inside inference.

Line it up and it's literally SGD-with-momentum, run over the token stream — the surprise is the gradient of the memory's loss, and the write steps against it (gradient descent):

Momentum β carries a surprise forward; the forget gate decays what isn't refreshed. The runnable version below writes a secret code hard, a routine line faintly, and watches memory fade under silence.

05

Three ways to wire the memory in

The paper tests three placements of the memory relative to attention:

VariantHow memory meets attention
Memory as Context (MAC)Retrieved memories are prepended as extra tokens; attention reads current window + recalled past together. Best overall.
Memory as Gate (MAG)Memory and attention run in parallel branches, blended by a learned gate.
Memory as Layer (MAL)Memory is a layer the sequence passes through before attention.

Alongside both sits a small set of persistent memory tokens — learnable, input-independent parameters holding task knowledge. Three stores, three timescales: persistent (trained, fixed), long-term (written at test time), short-term (attention over the window).

07

Why it matters

Titans reopened a question the field had parked: maybe long context isn't a window problem but a memory problem. Instead of racing to attend over ever-more tokens, let part of the model learn its input. That framing — test-time learning as an architectural primitive — has rippled into follow-up architectures, memory research, and the agent world's obsession with what to remember across long horizons.

It also completes a neat symmetry with the reasoning era: test-time compute spends more thinking per query; Titans spends learning per query. Both push intelligence out of the frozen-training paradigm and into the moment of use — which is likely where the next architectural decade gets decided.

Read next

Titans answers the same scaling pain as Mamba (fixed-state compression) and FlashAttention (making the window cheaper) — three different bets on the memory bottleneck.

How it works

How Titans learns to memorize at test time, step by step

Titans, from Ali Behrouz, Peilin Zhong and Vahab Mirrokni at Google Research, adds a neural long-term memory to an attention-based model. The memory is a small MLP whose weights are updated by gradient descent while the model reads, on an online associative-memory loss.

Memory as Context (MAC), one segment long-term memory M MLP written at test time S ← ηS − θ∇ℓ M ← (1 − α)M + S new segment query q persistent recalled h segment t M*(q) attention over [persistent, h, segment] output o = y ⊗ M*(y) write y: surprise gradient step on M
Memory as context (MAC): recall from the long-term memory, attend over recall plus segment, then write the result back with the surprise update.
  1. Project each token to a key and a value. kt = xtWK and vt = xtWV. Following recent linear recurrent models, the projections are followed by a short depthwise convolution, and keys and queries are ℓ2-normalized.
  2. Measure surprise. The memory M is asked to map the key to the value, with loss ‖M(kt) − vt‖². The gradient of that loss with respect to M's weights is the momentary surprise: large when the memory could not predict this association, small when it could.
  3. Accumulate surprise with momentum. St = ηtSt−1 − θt∇ℓ. Past surprise decays at rate ηt instead of vanishing, so a surprising passage keeps being written for a while after the token that triggered it.
  4. Forget, then write. Mt = (1 − αt)Mt−1 + St. The forgetting gate αt acts as weight decay on the memory and frees capacity. All three controls, ηt, θt and αt, are computed from the input rather than fixed.
  5. Read without writing. Retrieval is a plain forward pass with a query, yt = M*(qt) with qt = xtWQ. No weights change on a read.
  6. Make it trainable in parallel. Updating weights token by token is sequential, so the sequence is split into chunks. Within a chunk every gradient is taken with respect to the memory's weights at the start of the chunk, a mini-batch form of the update that can be written as matrix multiplications, and the momentum term is combined across the chunk with a parallel scan.
  7. Add persistent memory. A set of learnable, input-independent tokens is prepended to the sequence to hold task knowledge. With attention as short-term memory and the neural module as long-term memory, that makes three stores.
  8. Wire it in one of three ways. In memory as context (MAC), each segment's tokens query the memory, the recalled vectors are concatenated with the persistent tokens and the segment, attention runs over that window, and the attention output is written into the memory and used to gate the final output. In memory as gate (MAG), sliding-window attention and the memory run as parallel branches combined by a gate. In memory as a layer (MAL), the memory is a layer applied before sliding-window attention. The memory alone, without attention, is also tested as a recurrent model.

Where it sits among test-time learners

Weights used as fast-changing memory go back to fast-weight programmers, and linear attention can be read as one. DeltaNet's delta rule is the special case of this update with a linear memory, no momentum and no forgetting. Test-time training (TTT) layers (Sun et al., 2024) also train an inner model by gradient descent on a self-supervised loss during the forward pass. Titans adds the momentum term, data-dependent forgetting and a deeper MLP memory, and combines the result with attention.

Training setup

The language models were trained on FineWeb-Edu at roughly 340M, 400M and 760M parameters, on 15 to 30 billion tokens, against Transformer++ and recurrent baselines including Mamba, Mamba-2, DeltaNet, Gated DeltaNet and TTT.

The math

The Titans memory loss, surprise and update rule

ℓ(Mt−1; xt) = ‖Mt−1(kt) − vt‖₂², kt = xtWK, vt = xtWV
St = ηt St−1 − θt ∇ℓ(Mt−1; xt)
Mt = (1 − αt) Mt−1 + St, yt = Mt*(qt)
  • M — the memory: the weights of a small MLP, one or more layers deep.
  • ℓ — the associative-memory loss: how badly the memory maps this token's key to its value.
  • ∇ℓ — momentary surprise, the gradient with respect to the memory's weights.
  • St — accumulated surprise, a momentum buffer; ηt sets how fast past surprise decays.
  • θt — how strongly this token's surprise is written, effectively a learning rate.
  • αt — the forgetting gate, a weight decay between 0 and 1.
  • M*(q) — a read: a forward pass with no update.

At the extremes: αt = 1 wipes the memory, and αt = 0 never forgets. ηt = 0 removes momentum, leaving one plain gradient step per token, the form TTT layers use. θt = 0 turns writing off. With a linear memory, a matrix, and η = α = 0, the gradient is 2(M kt − vt)kt^⊤ and the update becomes the delta rule of DeltaNet.

The evidence

What Behrouz, Zhong and Mirrokni ran, and what Titans showed

The paper compares its three variants, and the memory module alone, against Transformer++ and a field of modern recurrent models at matched sizes, then tests long-context recall separately.

BenchmarkCompared withReported outcome
Language modeling and commonsense reasoning, about 340M to 760M parametersTransformer++, Mamba, Mamba-2, DeltaNet, Gated DeltaNet, TTTTitans variants lowest perplexity and best average accuracy
Single needle-in-a-haystack, 2K to 16K tokensTTT, Mamba-2, DeltaNethighest retrieval accuracy, smallest drop as length grows
BABILong, reasoning over facts spread through very long textGPT-4 and GPT-4o-mini, Llama 3.1-8B with retrieval, Mamba, recurrent memory transformersTitans (MAC) best, with far fewer parameters
Context length—effective beyond 2M tokens, per the paper
Time-series forecasting and DNA modelingspecialized baselinescompetitive or better

The ablations test each part of the update. Replacing the deep memory with a linear one, removing the convolution, removing momentum, removing the forgetting term and removing the persistent tokens each made results worse. Deeper memory modules improved perplexity but lowered training throughput, a trade-off the paper reports directly.

Two cautions. The language-model comparisons stop below a billion parameters, a scale at which new sequence primitives have often looked better than they later did. And the long-context results lean on synthetic and semi-synthetic benchmarks such as needle-in-a-haystack and BABILong, which reward exactly the kind of fact storage the memory is built for. Beating far larger general-purpose models such as GPT-4 on BABILong shows that the mechanism suits the benchmark; it does not by itself show a general advantage.

Since then

Where this stands, and what would settle it

This is recent work, and the right register for it is what it would take to believe rather than what it has proved. The mechanism's appeal is real: a surprise-gated write is a principled answer to what a fixed-capacity memory should keep, and it is the same intuition that makes prioritised replay work, applied to storage instead of sampling.

The questions it raises are mostly about serving rather than quality, and they are substantial. A module whose weights change while processing a request is stateful in a way current inference stacks are not built for: two requests cannot share it without one contaminating the other, batching is complicated by every sequence wanting its own copy, and the same input can produce different outputs depending on what the module saw before — which is a problem for reproducibility, for caching, and for anything that has to be audited. None of these is unanswerable; none is answered by the architecture.

What would settle it: independent reproduction at scale, and a comparison against the strong hybrid baselines from rung 4 under matched compute rather than against a plain transformer. Long-context benchmarks are also unusually easy to overfit to — a synthetic retrieval task can be solved by a mechanism that helps nothing else — so the result to watch for is whether the gains show up on tasks nobody designed with this memory in mind.

SOLVE IT YOURSELF

Write to memory by surprise

Titans' memory is SGD-with-momentum run over the token stream, where the gradient is surprise — the prediction error on each token. This implements it: a routine line ("meeting at 3pm") barely moves the memory, while a secret code writes hard; momentum carries a spike forward so the next token keeps writing; and a forgetting gate decays what isn't refreshed, fast or slow depending on the gate. Run it and compare the write strengths, then watch memory fade under silence. Change the surprise values or the gates.

YOUR TASK

Write the body of surprise. Everything else in the file is already written; this is the function the paper is about. Press ▶ Run to check it against the 5 assertions below — they start red.

WHAT IT HAS TO SATISFY — 5 ASSERTIONS
  1. A surprising token writes more to memory than a routine one
  2. Surprise is prediction error: a bigger deviation is more surprising
  3. Momentum carries a spike forward - the next silent token still raises memory
  4. A fast forget gate decays memory faster than a slow one
  5. A higher-surprise token produces a larger write
CPython · WebAssembly
Questions

Questions people ask about Titans

How does the Titans surprise metric work?

Titans treats its long-term memory as a small network that should map each token's key to its value. When a token arrives, the memory's loss on that pair is computed, and the gradient of the loss with respect to the memory's weights is the surprise: a large gradient means the memory failed to predict this association, a small one means it already knew it. That gradient drives the write, scaled by a data-dependent rate. Momentum carries past surprise forward, so a surprising passage keeps being written for several tokens, and a forgetting gate decays old content. All three controls are computed from the input, so the model learns when to write, how hard and what to let fade.

What is the difference between Titans and test-time training (TTT) layers?

Both update an inner model by gradient descent during the forward pass, on a self-supervised loss, so reading the input trains a component of the network. TTT layers, from Sun et al. (2024), use that inner model as the hidden state of a recurrent layer and take one plain gradient step per token or mini-batch. Titans adds momentum, so past surprise keeps influencing the update, and a data-dependent forgetting gate that decays the memory. It uses a deeper MLP as the memory, and it combines the memory with attention, which handles the recent window, through its MAC, MAG and MAL designs. In Titans' formulation, a TTT-style update is the special case with no momentum and no forgetting.

What are MAC, MAG and MAL in the Titans paper?

They are three ways to combine the long-term memory with attention. Memory as context (MAC) splits the input into segments; each segment queries the memory, the recalled vectors are concatenated with persistent tokens and the segment, attention runs over that window, and its output is written back into the memory and gates the final output. Memory as gate (MAG) runs sliding-window attention and the memory as parallel branches and blends them with a learned gate. Memory as a layer (MAL) stacks the memory as a layer before sliding-window attention, like a conventional hybrid. MAC did best on the long-context recall tasks, while MAG and MAC were close on language modeling.

How is Titans trained in parallel if its memory updates one token at a time?

By relaxing the update within chunks. The sequence is split into chunks, and inside each chunk every token's gradient is computed with respect to the memory's weights as they were at the start of the chunk, rather than after the previous token's update. That turns the chunk's updates into a mini-batch gradient computation that can be written as matrix multiplications and run on accelerators efficiently. The momentum and forgetting terms, which link consecutive updates, are combined across the chunk with a parallel scan. Between chunks the memory is updated sequentially, so smaller chunks are closer to true token-by-token learning and larger chunks are faster, a speed-accuracy dial set by chunk size.

Does Titans change its weights for every request at inference time?

Only the memory module's weights, and only within the sequence being processed. The backbone, including attention, projections and the gates that control writing, is frozen after training. For each new sequence the memory starts from its learned initial state and is then written as that sequence is read, so the same model can hold different memory contents for different requests. That is what lets it carry information across millions of tokens, and it is also its serving cost: each concurrent sequence needs its own copy of the memory weights, batching is harder than for a stateless transformer, and results depend on the order in which the input arrived.

Check yourself

4 questions to test what you just read

Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.

In a scalar toy version with η = 0.9, θ = 0.1, α = 0.01, previous surprise S = 1.0 and a new gradient of 2.0, what are the new S and the new memory, starting from M = 5?

Show answer

S = 0.9 × 1.0 − 0.1 × 2.0 = 0.7. M = (1 − 0.01) × 5 + 0.7 = 4.95 + 0.7 = 5.65. Momentum kept the update positive even though this token's gradient pushes the other way.

If the forgetting gate stays at α = 0.5 for three tokens and nothing new is written, what fraction of the memory survives, and what would α = 0.01 leave?

Show answer

Each step keeps (1 − α): 0.5³ = 12.5% survives. With α = 0.01, 0.99³ ≈ 97%. Because α is computed from the input, the model can clear the memory quickly at a topic boundary and preserve it otherwise.

Why does a linear memory with no momentum and no forgetting turn the Titans update into the delta rule?

Show answer

For a matrix memory the loss ‖Mk − v‖² has gradient 2(Mk − v)k^⊤. With η = α = 0 the update is M ← M − 2θ(Mk − v)k^⊤: correct the memory by its prediction error along the key. That is DeltaNet's delta rule, so Titans generalizes it with momentum, forgetting and a deeper memory.

With chunks of 64 tokens, how many sequential memory updates does a 2,000,000-token input need, against token-by-token updating?

Show answer

2,000,000 / 64 = 31,250 sequential chunk updates, against 2,000,000 token updates. Inside each chunk the 64 gradients are computed together against the chunk-start weights, as matrix multiplications, which is what makes training practical.

Where this sits

Making the context long

Attention costs quadratic in sequence length. Six attempts to escape that, ending with two 2026 papers that give the model a memory instead.

  1. 1Transformer-XL2019
  2. 2Longformer2020
  3. 3Ring Attention2023
  4. 4Mamba2023
  5. 5Titans2025
  6. 6Engram2026

All 110 papers, in 19 ladders →

Finished this one? 0 / 110 Paper Breakdowns done
NextEngram Next on the “Making the context long” ladder · rung 6 of 6

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Paper Breakdowns