16 min read
End-to-End Test-Time Training for Long Context
At context, TTT-E2E scales like full attention while keeping inference latency constant; its three-billion-parameter model is faster on an H100. Instead of expanding attention, it compresses the context into Transformer weights through next-token prediction.
By the end you should be able to trace a token into updated weights, compute a test-time gradient step, and diagnose when weight compression loses details that full attention retains.
Contents
Context as continual learning
Why recast long-context modeling as learning rather than architecture design?
Near the start of a 128-thousand-token book, Mira hides the brass key in the blue atlas. Much later, the model must predict “atlas,” but the sentence has already fallen outside its sliding attention window. The recent window cannot directly revisit the original words.
The obvious repair is global attention: retain every earlier token so the late prediction can inspect the original sentence directly. That preserves the clue, and it also commits the model to revisiting an ever-growing record. Treating long memory as an attention-design problem makes this trade look unavoidable: either keep direct access to the whole book or give up direct access to the early sentence. Is exact access to every old token really the only form memory can take?
The alternative starts by changing the role assigned to context. During ordinary pre-training, text is training data: prediction errors alter weights, and those weights retain useful regularities without storing a searchable copy of every sentence. The paper applies that same logic during inference. As the model reads the given context, it continues next-token training and compresses what it has read into mutable weights, while the underlying architecture remains a Transformer with sliding-window attention. [1]
For Mira’s sentence, the intended causal chain is concrete even before specifying the update rule. The sentence appears while it is still locally available. Predicting its tokens creates learning signals. Those signals alter the model’s test-time weights. After the sentence leaves the window, later predictions use those altered weights, so information extracted from the sentence can still affect “atlas.” The old tokens are no longer directly addressable; their useful structure has changed the model that reads the rest of the book.
This is why the recasting matters. Architecture design asks where to route information between token representations. Continual learning asks what the current context can teach the model before that context disappears. The second question permits persistent memory without global attention: a fixed local window handles recent detail, while mutable weights carry compressed effects of earlier text. Compression is not a lossless archive; it can preserve useful structure while leaving out exact details. [1] For Mira’s clue, later predictions can use only what the updates preserved, not search the old sentence directly.
But “the sentence changes the weights” is still only a description. Which prediction is scored, what loss is produced, and how does that one token cause a specific weight change?
Next-token weight updates
How does token change memory state ?
Mira’s sentence passes beyond the sliding window and disappears from direct attention. A model with fixed weights can use “blue” to predict “atlas” while both are visible, but that prediction cannot alter the weights that process later text. The missing operation must turn the prediction at position into a weight change that survives after the sentence leaves the window.
The obvious attempt is to treat the context only as input: predict each token, discard the error, and continue. Test-time training instead treats each observed token as a label for a small training example. The model predicts from the preceding token using the current test-time weights , then cross-entropy measures the mismatch as the token loss . The paper performs this update sequentially at every position. [2]
Trace the atlas sentence through that rule. Before observing “atlas,” the model assigns a distribution over possible next tokens. The observed token determines the loss; the loss determines a gradient; the gradient changes the weights. Because those changed weights process later text, the local error can affect a prediction long after the original words leave the window. This is compression rather than an explicit record: the update does not append the sentence to a searchable cache. It changes many weight coordinates according to one prediction error.
One coordinate of the weight update
Move the gradient component across zero. When the selected learning rate is positive, a positive component lowers the selected weight coordinate and a negative component raises it; when the learning rate is zero, the coordinate does not change.
This isolates one scalar coordinate of . The previous coordinate and are held at their selected values while the gradient component varies; all other weight coordinates are held fixed, so the curve is not the complete model update.
A token therefore changes memory through a concrete local chain: prediction, loss, gradient, weight update. But usefulness does not follow from mutability alone. After thousands of context-dependent steps, a poor initial state can drift into weights that no longer predict well. The unresolved requirement is an initialization designed to remain effective after being changed repeatedly.
End-to-end meta-learning
Why optimize initialization through the test-time updates?
When the early “atlas” sentence changes the weights, the model that later predicts “atlas” is no longer the model that began the book. The obvious training objective evaluates every token loss at the unchanged initialization . [4] But test-time training updates the weights after each token, so this frozen objective does not evaluate the states used during deployment. [3] [5]
Suppose this objective finds a that predicts the book well before adaptation. The first token update moves it to , the second starts from and produces , and the process continues. [3] None of the frozen-state losses measures whether those updated states are useful. [4] A low loss at therefore says little about the state that must later recover the atlas clue.
This changes what training asks of the initialization. The inner loop applies token-driven updates from through the later states, while the outer loop optimizes using the losses along that trajectory. [5] Changing changes the first update; that changes the next state and update; the chain eventually changes the loss on the later “atlas” target. [3] Because the objective measures losses at those updated states, it can favor an initialization whose adaptation leads toward lower-loss states rather than one that works only before adaptation. [6]
To optimize , differentiation must follow that entire chain. Each state update already contains a gradient of a token loss, so differentiating the outer loss through the update produces gradients of gradients. Standard optimizers can then use the resulting outer gradient to meta-learn the initialization. [5]
Training and deployment now agree about when losses are measured: after the relevant online updates. But agreement does not remove the cost of processing those updates in order, and a step based on one token can be unstable. The remaining problem is how to replace one-token steps without losing nearby context. [5]
Mini-batches and sliding windows
How do batch size and window size jointly preserve context?
Mira’s phrase can fit inside one update batch, yet “brass,” “key,” and “blue” cannot change the weights used to predict later words in that same batch. Increasing TTT batch size therefore buys parallel work by making local predictions share a stale state; the write arrives only at the batch boundary. The obvious move—just group more token losses—turns the model into a bigram within each batch: every prediction uses the pre-batch weights, so later predictions miss more preceding context. [7]
This update replaces sequential steps with one step built from token contributions. The paper uses the larger batch to improve parallelism and stability, while recovers token-by-token updating. [7] But batching has not solved Mira’s local context problem: until the boundary, the mutable weights contain nothing written by the current batch.
Sliding-window attention supplies the missing path. Its attention window exposes each prediction to recent tokens directly, without waiting for a gradient update. If , the earliest words in a batch can leave the window before its final predictions; they are then absent from both the stale weights and local attention. Setting prevents that gap: while the batch is being processed, attention can still reach its earlier tokens. Once the boundary is crossed, the averaged gradient compresses that batch into the updated weights. [7]
The two paths now divide the work. Sliding-window attention preserves nearby details such as the relation among “brass key,” “blue,” and “atlas”; updated weights carry compressed information across batch and window boundaries. Mini-batching stabilizes the write, and the window covers context while that write is pending. [7]
This hybrid has local memory and persistent memory, but its gradient still needs a destination. Sending the update through more layers increases backpropagation cost, while updating attention and normalization caused outer-loop instability in the reported setup. [7] The unresolved choice is which parameters should become the persistent state.
Updated MLP state
Which parameters should store compressed context, and why?
Mira’s atlas clue must survive after its sentence leaves the attention window. Updating only a small part of the Transformer limits storage, but updating more layers requires more computation to backpropagate each test-time gradient update. The obvious choice—make the whole network mutable—therefore incurs the largest inner-loop cost. [9]
The first cut is by parameter type. A Transformer block contains attention, normalization, and a feed-forward multilayer perceptron, or MLP. TTT-E2E freezes embeddings, normalization parameters, and attention parameters because updating them in the inner loop made the outer loop unstable. Only the MLP weights become persistent context state. This keeps the sliding-window mechanism fixed while gradient updates write information such as the relation between “brass key” and “blue atlas” into ordinary model parameters. [10]
Updating every MLP is still the naive extreme. More mutable MLPs provide more storage, so compression can discard less context, but reaching early blocks requires backpropagating through more of the network. The paper instead updates regular MLPs in only the last quarter of Transformer blocks: fewer blocks shorten the backward path, while each selected MLP offers a larger effective state than the smaller multi-head MLPs considered in the alternative design. [9] [11]
Why the last quarter rather than a smaller slice? In a 24-block ablation, updating only one or three blocks failed to scale with context length like full attention; updating six or twelve blocks did scale, and twelve performed roughly like six. The final design therefore uses six mutable blocks in that model—the last quarter—rather than paying to update twelve. [12]
Mutable state creates a second risk: the atlas update could overwrite knowledge acquired during pretraining. Each updated block therefore receives a separate static MLP as safe storage for pretrained knowledge, while the mutable MLP carries context-specific changes. The network’s MLP widths are reduced so this duplication does not increase the total parameter count. [13]
The resulting division is concrete: frozen attention retains the sliding-window mechanism, mutable MLPs in the last quarter store compressed context, and parallel static MLPs protect pretrained knowledge. [10] [9] [13] That capacity may retain the atlas relation. But this design alone does not establish whether an unrelated UUID will survive compression.
Context scaling versus recall
What does TTT-E2E gain, and what does weight compression sacrifice?
Mira’s sentence creates two different memory tests. Predicting “atlas” can exploit patterns learned from the surrounding book, while reproducing an unrelated UUID requires preserving an arbitrary string exactly. The obvious hope is that low next-token loss implies both abilities. It does not: a fixed-size compressed state can retain regularities that improve prediction while discarding details that looked useless when they arrived. [14]
For language modeling, that compression works unusually well. On the paper’s token-index evaluation at and , TTT-E2E stays below full attention in loss throughout each context; most of its aggregate advantage comes from earlier tokens. [15] Across context lengths, the three-billion-parameter model scales like full attention while retaining constant inference latency, reaching a reported speedup over full attention at on an H100. [1] The mutable weights therefore capture enough book-level structure for earlier text to keep helping later predictions without an expanding full-attention cache.
Now ask for the UUID instead of “atlas.” Needle in a Haystack is a recall evaluation in which the target string is deliberately irrelevant to its surrounding passage. Full attention can revisit the keys and values of every previous token, so irrelevance does not force deletion. TTT-E2E instead compresses the passage into weights; an arbitrary UUID supplies little reusable next-token structure and may be omitted as noise. The paper reports that full attention dramatically outperforms TTT-E2E and the other compressed-state methods on these tasks, especially at long context. [14] This is not a contradiction with the loss result. Average language-model loss rewards useful regularities; exact retrieval penalizes losing even one otherwise useless detail.
The hook resolves as a trade. TTT-E2E compresses context into mutable weights through next-token prediction, and its reported inference latency stays constant with context length. [1] That compression can leave out irrelevant details such as a recall target, while full attention keeps keys and values for all previous tokens and dominates the long-context recall tests. [14] Efficient learned memory is not nearly lossless recall.
Transfer set
Put the pieces together
These questions combine mechanisms from more than one section. Work from the causal chain before opening the answer.
- 01
Mira’s sentence begins at the first position of a batch with , while sliding-window attention uses . The model must use the relation between “brass key” and “blue atlas” near the end of that batch and again much later. Trace the two memory paths and identify where the first gap appears.
Show answer
Inside the batch, the weights remain at the pre-batch state until all token gradients are averaged. By the end of the batch, the earliest words have also left the -token window, so neither the stale weights nor local attention carries the complete nearby relation. Setting keeps the sentence locally reachable until the batch update compresses its learning signals into weights for later use. [8] [7]
- 02
Suppose the mutable MLPs begin from an initialization trained only with , while the separate static MLPs remain unchanged. Why does protecting pretrained knowledge not ensure that the later state can predict “atlas”?
Show answer
The static MLPs protect pretrained knowledge, but they do not prepare the mutable MLPs for their update trajectory. Because evaluates every loss at unchanged , it never rewards an initialization whose token-driven updates produce a useful later state. The end-to-end objective must evaluate losses at and differentiate through the updates so the mutable state learns how to retain context without relying on the static path. [6] [4] [5] [13]
- 03
At context, replace the late request for “atlas” with a request for the unrelated UUID verbatim. Combine next-token weight updates, the chosen mutable state, and the difference between compression and full attention to predict which memory system has the advantage.
Show answer
Each token changes the mutable last-quarter MLPs through next-token gradients, so earlier context can influence later predictions after leaving the sliding window. That fixed mutable state stores compressed predictive structure rather than a directly searchable copy of every token. The atlas relation can therefore improve later prediction, while the arbitrary UUID may be discarded; full attention has the advantage on the UUID because it retains access to all previous keys and values. This resolves the hook and throughline concretely: next-token training buys efficient long-context memory by writing useful context into weights instead of expanding attention, but the same compression that avoids the growing attention record prevents nearly lossless recall. [3] [9] [1] [14]
References
- [1]“We formulate long-context language modeling as a problem in continual learning rather than architecture design. Under this formulation, we only use a standard architecture -- a Transformer with sliding-window attention. However, our model continues learning at test time via next-token prediction on the given context, compressing the context it reads into its weights.”
- [2]“One way to give our baseline architecture some memory is to train it on the context. Similar to standard pre-training, we can predict and compare it to at every as an exercise. Specifically, denote the baseline architecture as with weights , then the standard next-token prediction loss at time can be written as: \begin{equation} \ell_t(W) = \texttt{CE}\left(f(x_{t-1}; W), x_t\right). \end{equation} We update at test time for every , in sequential order, with gradient descent:”
- [3]“\begin{equation} \label{eq:toy} W_t = W_{t-1} - \eta,\nabla\ell_t(W_{t-1}), \end{equation}”
- [4]“\begin{equation} \label{eq:wrong} \mathcal{L}{\texttt{naive}}(W_0; X) = \frac{1}{T}\sum{t=1}^{T}\ell_t(W_0). \end{equation}”
- [5]“For gradient-based optimization, computing for the E2E entails computing gradients of gradients, since the update rule in Equation~\ref{eq:toy} itself contains a gradient operation. Fortunately, modern frameworks for automatic differentiation can efficiently compute gradients of gradients with minimal overhead~\cite{jax2018github, engstrom2025optimizing}. Once is computed, we can plug it into standard optimizers. In the field of meta-learning, gradient steps on are called the \emph{outer loop}, and on the \emph{inner loop}.”
- [6]“\begin{equation} \label{eq:toy_train} \mathcal{L}(W_0; X) = \frac{1}{T}\sum_{t=1}^{T}\ell_t(W_{t-1}) = \frac{1}{T}\sum_{t=1}^{T} \texttt{CE}\left(f(x_{t-1}; W_{t-1}), x_t\right). \end{equation}”
- [7]“It is important to set so our model can remember the context within each mini-batch before TTT has a chance to update its weights.”
- [8]“\begin{equation} \label{eq:main} W_i = W_{i-1} - \eta,\frac{1}{b}\sum_{t=(i-1)b+1}^{ib}\nabla\ell_t(W_{i-1}), \end{equation}”
- [9]“In general, less information is lost during compression when we have a larger amount of storage. In our case, the information is the context, and the storage is the updated MLP layers. However, updating more layers also implies more computation to back-propagate the gradients. Therefore, we have an intuitive trade-off between computational cost and the ability to scale with context length, as we will illustrate with ablations in Section~\ref{sec:results}. We choose to TTT only the last 1/4 of the blocks according to the ablations, but other experimental setups, especially those with even longer contexts, might require a different choice.”
- [10]“We freeze the embedding layers, normalization layers, and attention layers during TTT, since updating them in the inner loop causes instability in the outer loop. Therefore, the MLP layers are the only ones updated during TTT.”
- [11]“And if we remove difference 4 by reverting to regular MLPs (instead of multi-head MLPs with LoRA), then we have a larger effective state at the cost of more compute (and memory).”
- [12]“We experiment with updating the last 1/2, 1/4, and 1/8 of the layers. For our 760M model with a total of 24 layers, these ratios translate to the last 12, 6, and 3 layers. We also experiment with updating only the final layer. From the rightmost panel of Figure~\ref{fig:ablations}, we observe that when updating only 1 or 3 layers, our method does not scale with context length in the same way as full attention. When updating 6 or 12 layers, our method does scale. However, updating 12 layers only performs at roughly the same level as 6. Therefore, we always update the last 1/4 regardless of model size.”
- [13]“In the blocks updated during TTT, we add a static, second MLP layer as a ``safe'' storage for pre-trained knowledge. For fair comparison with the baselines, we reduce the hidden dimension of the MLPs throughout the entire network (including those frozen during TTT), so the total number of parameters remains the same.”
- [14]“From Table~\ref{tab:niah}, we observe that Transformer with full attention dramatically outperforms the other methods, including ours, especially in long context. This observation, combined with findings from our previous subsections, supports the intuition that the strength of full attention lies in its nearly lossless recall. This strength is inherent to the design of self-attention, which attends to the keys and values of all previous tokens in its cache. In contrast, the key mechanism in our method is compression, which leaves out seemingly irrelevant details, such as the target string.”
- [15]“We make the following observations from both panels of Figure~\ref{fig:token}: \vspace{-0.5ex} \begin{itemize}[itemsep=2pt, topsep=0pt, parsep=0pt, partopsep=0pt] \item TTT-E2E is the only method that always achieves lower losses than full attention throughout the entire context length. \item The difference in test loss between TTT-E2E and full attention is small around the end of the context window. The aggregated advantage of TTT-E2E over full attention mostly comes from the earlier tokens. \end{itemize}”
- [16]“At training time, TTT-E2E takes gradients of gradients, which is a much less optimized procedure compared to training a regular Transformer. As shown in the left panel Figure~\ref{fig:training_eff}, our training latency is faster than full attention at 128K context length, but slower at 8K. Since most of the training compute is typically spent on pre-training with short context, the training latency of our current implementation remains a significant limitation.”