In-context learning · Memory
Where Does In-Context Learning Live?
From retrieval and latent task inference to fast weights, test-time optimization, and learning from entire histories.
Give a model the same query twice, but precede it with two different sets of examples. If the answers change systematically, something has been learned from the context.
Yet the model's global parameters did not change.
So where did the learning happen?
This question is more useful than asking whether a particular architecture “has ICL.” It turns a vague capability into a concrete systems problem. New task information must be written somewhere. There must be a rule for updating that state, a rule for reading it, and a decision about when it disappears.
Different research fields have placed that temporary learning in very different objects:
- the examples themselves;
- a latent variable describing the task;
- Transformer activations;
- fast weights or recurrent state;
- an external episodic memory;
- a temporary copy of the model parameters;
- or, in continual learning, the persistent parameters themselves.
These are not merely alternative architectures. They make different promises about capacity, speed, uncertainty, correction, and forgetting. A long prompt preserves exact examples but becomes expensive to search. A latent task vector is compact but may erase exceptions. Fast weights can update indefinitely, but new writes can interfere with old ones. Explicit fine-tuning is expressive, but it spends optimizer state and risks overfitting.
Figure 1. Where learning can live. Moving right generally makes the state more compressed, more entangled with the model, and potentially longer-lived. The boundaries are not absolute: a practical system can use several carriers at once. This and the following figures are original syntheses.
The goal of this article is not to name every paper that uses the phrase in-context learning. It is to understand a small set of mechanisms well enough that we can compare them. For each family, we will ask five questions:
- What state carries the new information?
- What writes or updates that state?
- How is it read to make the next prediction?
- How long does it survive?
- What is its characteristic failure mode?
Sources were checked through August 28, 2026. Controlled theoretical results are described as such; they are not silently generalized to arbitrary pretrained language models.
Reading map
The article has four parts:
- Context without parameter updates. Examples can remain explicit, be compressed into a task posterior, or drive an algorithm inside a forward pass.
- Writable state. Fast weights, model-valued hidden states, and external memories turn inference into an update process.
- Learning from interaction. Meta-RL and Algorithm Distillation show why a history containing failures and feedback is different from a collection of expert demonstrations.
- The boundary of ICL. Test-time optimization and continual learning reveal that the important boundary is not “gradients versus no gradients,” but what changes and what survives.
1. Prediction is not yet adaptation
Let a task provide a context
followed by a query . The familiar description of in-context learning is
where the global parameters remain fixed.
That equation hides the interesting part. Any system that changes its behavior over a sequence can be written more explicitly as
Here is an example, token, transition, or feedback event; is the task-specific state after seeing it; is the write rule; and is the read rule. In an ordinary Transformer, may simply be the KV activations produced from the prompt. In a nearest-neighbor method, it is the stored dataset. In a test-time-training layer, it is a small model whose weights are updated on the sequence.
Figure 2. A common interface for very different mechanisms. The slow parameters define how to write and read; the transient state carries what was learned in the current episode or stream.
This notation separates three ideas that are often conflated.
Behavior change
A model can change its output because the prompt changes its surface format, narrows the output vocabulary, or activates a task already stored in its weights. Min et al. found settings where replacing demonstration labels with incorrect labels damaged performance much less than expected: input distribution, label space, and formatting still provided useful information. That is real context sensitivity, but it is weaker evidence for learning a new input-output mapping.
Pan et al. make the distinction explicit:
- task recognition identifies and instantiates a familiar task from pretraining;
- task learning infers a new mapping from the demonstrations themselves.
The two can coexist. A prompt saying “positive/negative” may retrieve a familiar sentiment classifier while its particular examples also adjust the decision boundary.
Strict in-context learning
In the narrowest use, global parameters remain frozen and adaptation happens through context-dependent computation or transient state. Standard prompting belongs here. So do recurrent systems whose hidden state is updated while their learned update rule remains fixed.
Inference-time learning more broadly
Some methods run gradient descent at inference and temporarily change a copy of the parameters. They violate the narrow “no weight updates” slogan, but they solve the same functional problem: use a small amount of new evidence to alter behavior before the next prediction.
Continual learning
Continual learning allows knowledge to survive across tasks by updating persistent parameters or durable memory. Its central problem is no longer just fast acquisition. It must decide what to retain without destroying older abilities.
The clean boundary is therefore lifetime, not the mere presence of gradients. A gradient can update a disposable hidden-state model and vanish at the end of the sequence. Conversely, a gradient-free write to an external database can persist for years.
| Family | State carrier | Typical write rule | Typical lifetime | Main risk |
|---|---|---|---|---|
| Context as dataset | examples or KV records | append | prompt or session | search cost, distraction |
| Latent task inference | vector or distribution | amortized aggregation/inference | episode | bottleneck, lost exceptions |
| Forward-pass algorithm | activations | learned layer computation | forward pass | brittle learned algorithm |
| Fast weights | matrix or neural model | outer product, delta rule, gradient | stream or segment | interference, drift |
| External episodic memory | indexed records | insert, update, evict | configurable | stale or wrong retrieval |
| Temporary parameters | adapted copy | explicit optimization | task or session | cost, overfitting |
| Continual learning | persistent and replay memory | training plus consolidation | indefinite | catastrophic forgetting |
With the boundaries in place, we can ask what each state buys.
2. Context as a dataset: keep the evidence explicit
The least committal strategy is not to summarize the examples at all. Keep them available and defer interpretation until the query arrives.
Suppose a new query is compared with every support example. A generic nonparametric predictor is
where is larger for examples judged relevant to the query.
Matching Networks: prediction by learned retrieval
Matching Networks apply this idea to few-shot classification. Each support example and query is embedded; an attention kernel compares the query embedding with support embeddings; the predicted class distribution is a weighted sum of support labels. Training samples many small classification episodes so that the embedding and attention rule become useful for new classes.
What did the model learn during a new episode? It did not construct a new classifier in persistent weights. The support set is the classifier. The query determines which records matter.
This design has a useful property: adding one exceptional case does not require rewriting a summary. The exception remains individually addressable. It also supports asymmetric relevance: the same support set can produce different summaries for different queries.
Its price is equally direct. Memory and read cost grow with the support set, and a bad similarity metric retrieves the wrong evidence. The system has postponed compression, not eliminated the need for an inductive bias.
Attention is a soft database lookup
A causal Transformer prompt uses a richer version of the same contract. The model stores projected key-value records for earlier tokens. A later query can form a content-dependent weighted read. Unlike Matching Networks, the records are distributed across layers and are not literal labeled examples, but the central benefit is the same: late binding. The model need not know what will matter when a token is written.
This view explains why long context can help even without any dramatic claim about “learning an optimizer.” The model can copy a format, retrieve a definition, align with a demonstration, or combine several records. Sometimes retrieval is all the task requires.
But a prompt is a poor permanent database. Exact attention spends increasing compute on every read; finite windows eventually drop records; and irrelevant examples can compete with useful ones. Long context creates capacity, not automatically good memory management.
kNN-LM and RAG: move the dataset outside the prompt
kNN-LM stores a large datastore of hidden representations and their next tokens. At inference, the current hidden state retrieves nearby keys. The resulting neighbor distribution is interpolated with the language model's own next-token distribution. Changing the datastore can adapt the system to a domain without retraining the base model.
Retrieval-Augmented Generation combines parametric generation with a nonparametric document index. A learned retriever selects passages, and the generator conditions on them. Retrieval may happen once per output sequence or repeatedly while decoding.
Neither method should automatically be called ICL. A lookup can supply missing facts without learning any new rule. But they expose an important option: the transient state need not fit inside the neural network. A system can keep high-fidelity records externally and use learned similarity as its read rule.
The central trade-off is now visible:
Keeping examples explicit preserves exceptions and enables query-dependent reads, but every future prediction must solve a retrieval problem.
3. Context as a task posterior: compress examples into a hypothesis
The opposite strategy is to assume that all context examples were generated by a shared latent task. Instead of searching the entire dataset for every query, infer the task once and predict through that compressed representation.
For a latent variable , the ideal Bayesian object is
Prediction marginalizes the uncertainty:
The examples are no longer consulted independently. They update a belief about the function that generated them.
Conditional Neural Processes: a deterministic task summary
Conditional Neural Processes encode each pair , aggregate the encodings with a permutation-invariant operation such as a mean, and decode the target from the aggregate and :
The episode-specific learner is the vector . Adding an example updates the summary; every query reads the same summary. The cost is linear to construct and constant per target after that.
The mean aggregator also reveals the limitation. Two context sets that map to the same become indistinguishable. A fixed-dimensional bottleneck must compress both global regularities and local exceptions.
Neural Processes: preserve uncertainty about the function
Neural Processes make the task state stochastic. The encoder produces a distribution over , intended to represent uncertainty over plausible functions. Sampling yields coherent function samples rather than independent uncertainty at each target.
This is not just a mathematical decoration. If two context points are compatible with several functions, a deterministic vector tends to average them. A latent distribution can preserve ambiguity until more evidence arrives.
Attentive Neural Processes: one global vector is too aggressive
Attentive Neural Processes add attention paths so that each target can read the context points most relevant to it. The result is a hybrid:
- a global latent variable captures uncertainty shared across the function;
- target-dependent attention preserves local detail.
This design is instructive beyond neural processes. Pure compression is efficient, but exact evidence still matters. A useful learner often needs both a task-level belief and a query-specific route back to individual observations.
Is ordinary language-model ICL Bayesian inference?
Xie et al. provide a formal account in which pretraining data come from a mixture of latent concepts. Long-range coherence inside a document lets a sequence model infer which latent concept generated it. A prompt containing demonstrations from one concept then behaves like evidence for that concept, so in-context prediction resembles Bayesian inference over the latent hypothesis.
The value of the paper is not that every language model literally stores a calibrated posterior. It identifies a sufficient training structure: examples within a context share a hidden cause, and pretraining rewards inferring it. Under that structure, ICL is not mysterious. It is amortized latent-variable inference learned from next-token prediction.
Task vectors: where a compressed hypothesis may appear
The posterior account says what information should be inferred. Mechanistic work asks where it appears inside the network.
Hendel et al. found that, for the tasks and models they studied, demonstration information could be compressed into a query-independent activation they call a task vector. The model could then apply the inferred task to new queries.
Todd et al. used causal interventions to identify function vectors: compact activation directions, carried substantially by a small set of attention heads, that can induce a task even in zero-shot or natural-text settings. Their interventions suggest that these activations encode more than the output label distribution.
These results do not establish one universal “ICL neuron.” They show that a useful intermediate representation can be more compact than the prompt itself. In the language of our state machine, attention first writes a task representation into activations; later layers read that representation to answer the query.
The family can be summarized in one sentence:
A latent task state is cheap to reuse and can express uncertainty, but its bottleneck decides which details can never be recovered.
4. Context as an algorithm executed in the forward pass
Task inference explains what a predictor might estimate. It does not specify the computation used to estimate it. A different line of work asks whether Transformers can implement recognizable learning algorithms inside their activations.
Linear regression makes the question concrete. Suppose each task samples a weight vector , then generates
After observing , a learner should estimate and predict . The Transformer never receives directly. It must construct the effective predictor from the examples.
Garg et al.: can a Transformer learn a function class in context?
Garg et al. trained Transformers from scratch on episodes drawn from controlled function classes. On unseen linear functions, the models approached least-squares regression; on sparse linear functions, their behavior approached algorithms such as Lasso; and they also studied decision trees and small neural networks.
The result establishes capacity in a controlled setting. The model is not merely retrieving one of the training functions: it can infer a previously unseen member of the class from examples. But the setup is deliberately cleaner than natural language pretraining. It shows that a Transformer can learn an in-context estimator, not that every pretrained Transformer uses the same estimator everywhere.
Akyürek et al.: activations can encode an implicit model
Akyürek et al. construct Transformers that implement familiar learning procedures, including gradient descent and closed-form ridge regression, and compare trained models with these algorithms. Their analysis supports a useful interpretation: the context-dependent activations encode an implicit model fitted to the demonstrations.
No global weight is updated. The forward pass creates the effect of fitting a predictor.
von Oswald et al.: a self-attention layer can equal a gradient step
von Oswald et al. give a particularly crisp construction. For a transformed linear-regression prompt, one linear self-attention layer can implement one gradient-descent step. Stacking layers can implement successive steps. Self-attention-only Transformers trained on related regression tasks converged toward this construction.
For squared error,
gradient descent performs
The key algebra is that attention naturally computes sums of outer products between representations. With the right token layout and projections, those sums contain the sufficient statistics required for the update.
The paper's restricted setting matters. A linear self-attention construction for regression is a proof of mechanism, not a universal mechanistic explanation for arbitrary LLM behavior.
Bayesian inference and gradient descent are not competing explanations
This is where paper surveys often become unnecessarily confusing. They ask whether ICL is “Bayesian inference” or “gradient descent.” The two descriptions live at different levels.
For Gaussian linear regression, Bayesian inference yields a posterior over . Its posterior mean is a ridge-like estimator. Gradient descent is one possible iterative procedure for approximating an optimizer that leads to a related prediction.
Figure 3. “What predictor should the evidence imply?” and “what computation produces that predictor?” are different questions. A posterior, an optimizer, and an activation representation can all describe the same system at different levels.
The clean decomposition is:
- Statistical target: What function of the data is being estimated—posterior predictive, least squares, ridge, nearest neighbor?
- Computational algorithm: How is that estimator calculated—closed form, gradient descent, message passing, attention?
- Neural representation: Where are the intermediate quantities stored—tokens, task vectors, residual-stream activations, fast weights?
A model may approximate a Bayesian predictor using an optimizer-like circuit whose current estimate lives in activations. There is no contradiction.
Task diversity decides whether the model retrieves or learns
Raventós et al. varied the number of linear-regression tasks seen during pretraining. Below a task-diversity threshold, the Transformer behaved like a Bayesian estimator tied to the finite pretraining task distribution. Beyond the threshold, it behaved more like generic ridge regression and generalized to new tasks outside that finite set.
The important variable was not only model scale or number of tokens. It was the diversity of latent tasks. If memorizing or selecting among known hypotheses works, training may never reward a reusable learning rule. Enough diversity makes an algorithmic solution economical.
A necessary counterweight: real pretrained LLMs are not proven gradient descent engines
Shen et al. compare predictions one would expect from gradient descent with behaviors of pretrained Transformers. They point to differences in demonstration-order sensitivity and output distributions, and argue that results from specially constructed or ICL-trained models do not yet establish the same equivalence for ordinary pretrained LLMs.
The honest conclusion is narrower and more useful:
Transformers can learn algorithms that behave like regression or optimization in their forward pass. Which algorithm a real model uses is task-, data-, and model-dependent, and must be tested rather than assumed.
5. Context as fast weights: let the sequence write a temporary model
So far, the context has been read by a fixed computation graph. Fast-weight methods make the update more explicit. The model contains a rapidly changing state that behaves like a temporary associative memory or even a small trainable model.
The original fast-weight idea: a second timescale
Ordinary parameters change slowly across training runs. Recurrent activations change at every token but are usually viewed as vectors. Ba et al. revive an intermediate object: a fast-changing weight matrix that stores recent associations and decays over time.
A simple Hebbian-style update is
where is an address, is the associated content, is a write strength, and forgets old state. Reading with query gives .
This is a model with two learning rates:
- slow training discovers how to generate useful keys, values, and update coefficients;
- fast inference writes task-specific associations into .
Linear attention is a fast-weight memory
Katharopoulos et al. rewrite kernelized attention as a recurrence. Ignoring normalization for the moment,
The entire past is folded into the matrix . Schlag et al. show that this is exactly a fast-weight programmer: an outer product writes an association, and a query reads it.
This interpretation exposes a problem hidden by the phrase “linear attention.” Repeated additive writes collide. If two similar keys point to different values, the state contains their superposition.
The delta rule writes the residual rather than the full value:
If the memory already predicts , almost nothing is written. If it is wrong, the update corrects the error. The controller can learn , so the model also learns how strongly each token should alter memory.
This is a meaningful step toward ICL: context is no longer only read. Each event is an error-correcting training example for a temporary model.
TTT layers: make the hidden state a model
Learning to (Learn at Test Time) generalizes the idea. Instead of a vector or associative matrix, the hidden state is itself a model , such as a linear layer or a small MLP. Each incoming token creates a self-supervised training example and updates that hidden model:
The outer network learns the views, targets, update behavior, and readout. The base parameters remain fixed at test time; is recurrent state. The paper calls its two instantiations TTT-Linear and TTT-MLP and evaluates them as linear-complexity sequence layers.
This is the clearest counterexample to the slogan “ICL means no gradients.” Backpropagation can be the recurrence. What matters is that it updates disposable sequence state rather than permanently rewriting the base model.
Titans: combine short-term attention with neural long-term memory
Titans develops a neural long-term memory whose parameters are updated at test time. The memory is trained with an associative objective; the gradient of that loss acts as a measure of how surprising the current input is. Momentum helps preserve the direction of related updates, while decay provides controlled forgetting.
The architecture keeps different memory timescales separate:
- local attention provides accurate short-term access;
- a neural memory compresses longer history;
- fixed persistent parameters encode task-independent knowledge.
The paper proposes several ways to combine these components rather than claiming one memory should do everything. That is the durable design lesson. Exact recent context and compressed long-term state solve different problems.
Figure 4. The fast-weight lineage. The important progression is not the paper chronology alone: the writable state becomes more expressive, while the update rule becomes more selective and more explicitly learned.
What fast weights gain—and lose
Fast weights make a context window into an online learner:
- updates can continue for an unbounded stream;
- the state can be cheaper than retaining every token;
- overwrite and forgetting can be part of the learned rule;
- the learner can correct its own current prediction.
But compression happens at write time. Once two facts collide in , a future query cannot return to the original examples unless they were also stored elsewhere. Richer state increases capacity but also increases memory bandwidth and update cost. A learned write rule can drift under distribution shift.
The characteristic contract is:
Fast weights trade exact episodic access for a state that can be continually and selectively rewritten.
6. Context as external episodic memory: separate remembering from reasoning
An internal fast state must fit the architecture's fixed capacity. External memory takes the opposite position: preserve records outside the main network and let a controller decide what to write, retrieve, and forget.
The generic system has four operations:
plus an eviction or consolidation policy. The memory may hold raw text, embeddings, key-value pairs, trajectories, or summaries.
Memory Networks: make retrieval a learned reasoning step
Memory Networks combine a long-term memory with learned input, generalization, output, and response components. Rather than forcing all knowledge into model parameters, the network retrieves supporting memories and uses them to construct an answer. Multi-hop variants can retrieve a fact, use it to form a new query, and retrieve again.
This creates an explicit division of labor: memory owns storage; the neural controller owns addressing and reasoning.
Memorizing Transformers: retrieve old internal states
Memorizing Transformers attach a non-differentiable approximate-nearest-neighbor memory to a Transformer. Past key-value representations are inserted into the memory; a later token retrieves nearby records and combines them with local attention. The paper demonstrates access to histories much longer than the local context and shows that the memory can incorporate new information at inference without retraining the base network.
The memory is episodic because records remain individually retrievable. It does not require the fixed-size superposition used by recurrent fast weights.
External memory has its own learning problem
Moving state outside the network does not remove the hard decisions. It makes them explicit:
- Write: Is this event worth storing? Should it be raw, embedded, or summarized?
- Address: What similarity should place two events near each other?
- Read: How many records should be returned, and how should conflicts be resolved?
- Update: Does a correction replace an old record or create a competing one?
- Forget: Which records are stale, redundant, private, or no longer useful?
- Consolidate: When should repeated episodes become a general rule rather than more entries?
Retrieval errors differ from compression errors. A recurrent state may have destroyed a detail before the query arrives. An external memory may still contain the detail but fail to retrieve it. This distinction matters for debugging: one calls for more representational capacity; the other for better indexing and routing.
External memory is therefore not “free context.” It turns adaptation into a database-and-controller problem, with the benefit that memory capacity and lifetime are no longer tied directly to the neural architecture.
7. Context as a learning history: examples must show improvement, not only competence
Most few-shot prompts contain successful input-output pairs. But an agent that learns through interaction receives a richer stream:
Observations reveal the situation, actions expose the learner's decision, rewards evaluate it, and termination flags define episode boundaries. Crucially, the history contains consequences. A model can compare what it tried with what happened next.
RL²: the recurrent state is the reinforcement-learning algorithm
RL² trains an RNN across a distribution of Markov decision processes. A slow outer RL algorithm updates the RNN's weights. At deployment on a new MDP, those weights stay fixed. The RNN receives observations, previous actions, rewards, and termination signals, and its hidden state persists across several episodes of the same task.
The division is precise:
- the weights encode a learned general-purpose RL algorithm;
- the activations encode that algorithm's current beliefs and exploration history on the new task.
For a bandit, the hidden state might implicitly track which arms were tried and their observed payoffs. The network need not represent explicit visit counts, but its behavior can implement the same exploration-to-exploitation transition.
This is ICL before the term became associated mainly with language models. The context is an interaction history, and the learned function consumes feedback to improve without parameter updates.
Decision Transformer: good trajectories are not automatically learning histories
Decision Transformer casts offline RL as conditional sequence modeling. It predicts actions from returns-to-go, states, and past actions. Conditioning on a high desired return can produce strong behavior.
But a sequence model that imitates successful trajectories does not necessarily learn how to improve after failure. The training sequence may show what a good policy does without showing the causal update from bad outcome to changed future action.
This distinction is easy to miss:
- a demonstration shows competence;
- a learning history shows a policy changing because of evidence.
Algorithm Distillation: imitate the process of learning
Algorithm Distillation collects complete learning histories produced while a source RL algorithm trains separately on many tasks. A causal Transformer is then trained to predict actions from the across-episode history.
Early in each history, the source algorithm explores, fails, and receives low rewards. Later, after updating, it behaves better. To predict the entire sequence, the Transformer must model this improvement pattern. At test time, its parameters remain fixed, but the new task's history enters the context and its behavior improves across episodes.
Figure 5. Training data determine which sequence-level algorithm can be distilled. A history with only final expert behavior can teach imitation. A history containing attempts and feedback can teach the transition from one policy to a better one.
Algorithm Distillation makes a broader point than its RL experiments:
If we want a model to learn at inference time, the training data should contain visible trajectories of learning.
Next-token or next-action prediction can distill an update rule only when update-induced behavior changes are present in the sequence.
What history-based learning stores
In RL², task state lives in recurrent activations. In Algorithm Distillation, it lives across the Transformer context and its derived activations. Neither method needs to expose a symbolic policy update. The outer training process discovers a sequence-to-sequence algorithm that uses evidence over time.
The failure mode is meta-overfitting. A learner trained on one family of task dynamics may internalize shortcuts that fail on a structurally different family. The system can adapt rapidly inside the envelope of learning problems demonstrated during meta-training while still lacking a universal learning rule.
8. Explicit test-time optimization: temporarily change the model
What if the forward pass cannot express the required adaptation cleanly? The most direct answer is to optimize a temporary copy of the model on the new evidence.
A naming warning is useful here. TTT layers in Section 5 are sequence-model layers whose recurrent state is trained on each token. The older and broader phrase Test-Time Training means adapting a task model at deployment with a self-supervised or support-set loss. The ideas are related, but the state being updated and the role it plays are different.
MAML: learn an initialization that is easy to update
Model-Agnostic Meta-Learning samples tasks during meta-training. For each task , an inner gradient step adapts the shared initialization:
The outer objective evaluates on held-out examples from the same task and updates so that future inner steps work better:
MAML does not learn one frozen model that directly solves every task. It learns a parameter location from which a few task-specific gradient steps produce a good model.
In our taxonomy:
- state carrier: , a temporary parameter copy;
- writer: gradient descent on support examples;
- reader: the adapted model's ordinary forward pass;
- lifetime: one task, unless explicitly retained.
Test-Time Training: create a learning signal from the input itself
Sun et al. address distribution shift when labels are unavailable at deployment. Each test input supplies a self-supervised objective. The model updates on that objective before making the main prediction. For images, the auxiliary task can encourage features that remain useful under corruption or domain shift.
TENT takes a particularly minimal form: update normalization statistics and channel-wise affine parameters by minimizing the entropy of predictions on unlabeled target batches. The model becomes more confident on the current distribution without access to source data.
These methods are adaptation, but not necessarily task inference from demonstrations. They often respond to a changing input distribution rather than infer a novel mapping. They belong in the article because they show another source of supervision: the test stream itself can define an auxiliary loss.
Few-shot TTT for structurally novel tasks
Akyürek et al. study temporary parameter updates for language models on few-shot tasks, including ARC. The support examples provide an explicit loss for test-time training. Their results show that parameter-based adaptation can solve cases where ordinary prompting struggles with structurally novel mappings.
This creates a continuum rather than a binary choice:
| Mechanism | What changes? | Update signal | Typical cost |
|---|---|---|---|
| Prompt ICL | activations/KV state | demonstrations through forward computation | one or a few forward passes |
| TTT layer | model-valued hidden state | self-supervised per-token loss | local inner updates |
| MAML-style adaptation | temporary task parameters | labeled support loss | gradient steps through task model |
| Full test-time fine-tuning | broad parameter copy | support or auxiliary loss | optimizer state and repeated passes |
Explicit optimization is attractive when the desired adaptation is too novel or precise to be elicited by a prompt. It is expensive because inference now includes training: gradients, optimizer state, step-size choices, and protection against overfitting. It also requires a trustworthy loss. Entropy minimization can confidently reinforce mistakes; self-supervised objectives can improve representation quality without aligning with the downstream task.
The main lesson is not that temporary fine-tuning should replace ICL. It is that a system can choose how much adaptation to compile into the forward pass and how much to leave as explicit optimization.
9. What continual learning contributes: a theory of retention
Strict ICL usually resets the task state at the end of a prompt or episode. A long-lived learner cannot reset everything. It must decide which information is ephemeral and which deserves consolidation.
Continual learning studies the resulting stability-plasticity dilemma:
- too much plasticity learns the present quickly but overwrites the past;
- too much stability protects old knowledge but prevents new learning.
Three families contribute different answers.
Replay: preserve representative evidence
Replay methods retain examples or generated approximations from earlier tasks and mix them into new training. Gradient Episodic Memory stores episodic examples and constrains new updates so they do not increase loss on remembered tasks. When the proposed gradient conflicts with old tasks, it is projected to a direction that respects those constraints.
Replay treats forgetting as missing evidence. The learner can remain plastic because old examples continue to participate in the update.
Consolidation: protect important parameters
Elastic Weight Consolidation estimates which parameters were important for previous tasks, using the diagonal of a Fisher-information approximation. New learning is penalized for moving those parameters too far:
Parameters with large are stiff; parameters with small remain plastic. This treats forgetting as destructive movement in a shared parameter space.
Modularity: reduce interference structurally
Parameter-isolation methods allocate different modules, masks, or subspaces to different tasks. The idea is simple: if two updates do not touch the same capacity, they cannot directly overwrite one another. The cost is growing capacity or a routing problem when task identities are unknown.
Why this matters even when state is temporary
Fast weights and long contexts face miniature versions of continual learning. A delta-rule memory must decide when a new association should overwrite an old one. A task vector must balance recent evidence against a prior. An external memory must decide what to evict. A TTT layer can drift over a stream.
The same three ideas reappear at a shorter timescale:
- replay becomes retaining or revisiting exact context records;
- consolidation becomes protecting high-confidence state from weak new evidence;
- modularity becomes routing different contexts to separate memory slots or experts.
Continual learning does not supply one missing ICL algorithm. It supplies the vocabulary and constraints for deciding what should survive.
10. The model must train on the histories it will create
An architecture can provide a writable state and still fail to learn online. The update rule is shaped by the sequence distribution seen during training.
Chan et al. show this in controlled sequence models. Data properties such as burstiness and a large number of rare classes can favor emergent ICL: repeated examples within a sequence make context informative, while diverse classes make storing every class in parameters less economical.
Algorithm Distillation provides the stronger version: if improvement across attempts is visible in training histories, next-action prediction can distill that improvement process.
There is still a distribution problem. During deployment, the model's earlier predictions help create its later context. One mistake can move the history away from expert-generated trajectories. Training only on clean, successful sequences leaves the learner unprepared for its own failures.
This is the same structural issue addressed by DAgger in imitation learning. DAgger repeatedly runs the current policy, asks an expert for the correct action on the states that policy actually visits, aggregates those states, and retrains. The training distribution gradually approaches the learner-induced deployment distribution.
For context learners, the analogous principle is:
- let the current learner generate attempts or predictions;
- preserve the resulting histories, including failures and recoveries;
- attach feedback where available;
- train the model to make the next update under those histories;
- repeat as the induced context distribution changes.
This does not require copying DAgger literally. The important idea is on-policy context generation. A learner intended to recover from its own mistakes must see contexts containing its own kinds of mistakes.
We can now separate two requirements that are often collapsed:
An architecture specifies where temporary knowledge can live. The training distribution teaches the model how to use that state under histories it will actually encounter.
One without the other is insufficient. A huge external memory with no useful write policy is a log. A meta-training distribution with visible learning but no state capacity cannot retain the evidence required to improve.
11. One design space, not one winning mechanism
The methods now fit inside the same write-read abstraction.
| Method | State carrier | Write rule | Read rule | Best at | Characteristic failure |
|---|---|---|---|---|---|
| Matching Networks / prompt attention | explicit support or KV records | append examples | query-dependent attention | exact exceptions, late binding | cost and distraction grow with context |
| CNP / NP | deterministic or stochastic latent task state | amortized aggregation/posterior update | conditional decoder | compact reuse, uncertainty | global bottleneck or underfitting |
| Task/function vectors | internal activation | attention and layer computation | downstream causal circuit | compact task control | entanglement, prompt sensitivity |
| Forward-pass regression | activations encoding an implicit estimator | learned Transformer computation | later layers/query token | compiled few-shot algorithms | narrow meta-training envelope |
| Fast weights / DeltaNet | matrix state | outer product or error-correcting delta rule | matrix query | cheap streaming adaptation | collisions and overwrite |
| TTT / Titans | linear, MLP, or neural-memory state | self-supervised gradient update | forward pass through state model | expressive long-lived state | update cost, drift, memory bandwidth |
| External memory | indexed records | insert/update/evict | kNN or learned retrieval | large high-fidelity episodic capacity | stale memory, misretrieval |
| RL² / Algorithm Distillation | recurrent state or across-episode context | consume action-feedback history | learned policy | adaptation from consequences | meta-overfitting to task family |
| MAML / test-time fine-tuning | temporary parameter copy | explicit gradient descent | adapted network | structurally novel task fitting | optimizer cost and overfitting |
| Continual learning | persistent parameters plus replay | constrained persistent training | ordinary model inference | retention across tasks | stability-plasticity trade-off |
No column dominates every other. The useful comparisons are operational.
If exact exceptions matter, keep records addressable
A global task vector cannot reliably preserve an arbitrary number of exceptions. Attention, kNN, or external memory should remain in the loop. Compression can still provide a prior or summary, but the original evidence needs a retrieval path.
If the same task state will answer many queries, compress it
Re-reading thousands of examples for every target is wasteful when they all identify one smooth latent function. Neural-process-style task states or fast weights amortize the inference cost.
If feedback arrives sequentially, use an update rule that can correct itself
Additive memories accumulate interference. Delta rules, optimizer-like state updates, and history-trained recurrent policies explicitly respond to prediction error or reward.
If the new task is outside the compiled algorithm's envelope, optimize
Forward-pass ICL is fast because meta-training has compiled an adaptation algorithm into the model. A genuinely novel structure may require temporary parameter updates, search, or an external program.
If knowledge should outlive the session, add a consolidation policy
Persistence is not a free extension of ICL. The system must decide what to store, validate, merge, and protect. Continual-learning methods become relevant precisely at this boundary.
The likely result is a hierarchy rather than a single mechanism:
- attention keeps the recent context exact;
- a latent task state captures the current hypothesis;
- fast weights absorb recurring online structure;
- external memory preserves important episodes;
- temporary optimization handles hard exceptions;
- consolidation promotes only selected knowledge into persistent parameters.
This is not a proposal for one particular architecture. It is the natural consequence of different memory objects having different strengths.
12. How should we tell whether a system is actually learning in context?
Ordinary few-shot accuracy is not enough. It can reward task recognition, formatting cues, or retrieval of a memorized template. A useful evaluation should perturb the learning process itself.
Change the mapping while preserving the surface form
Randomize label semantics or use new functions that were not present during pretraining. This separates task learning from recognizing a familiar dataset.
Measure a learning curve inside the context
Evaluate predictions after 0, 1, 2, 4, and 8 observations. A real update rule should improve systematically with informative evidence, not merely benefit from a fixed instruction prefix.
Include contradictory and corrective evidence
After the model forms a hypothesis, supply an example that falsifies it. Does the state update? Does the correction apply locally or erase unrelated knowledge? This probes plasticity and interference.
Vary order
A Bayesian posterior over exchangeable examples should be order-invariant. Gradient descent, recurrent updates, and finite-context attention generally are not. Order sensitivity can reveal the computational mechanism, although it rarely identifies one mechanism by itself.
Test delayed feedback
Place the consequence of an action far after the action. The learner must assign credit, preserve the relevant state, and update future behavior. This distinguishes a learning history from simple local pattern completion.
Remove task boundaries
Many meta-learning benchmarks announce when a task resets. Real streams often do not. Mix gradual drift, abrupt changes, and recurring tasks. The learner must infer when to preserve, revise, or reset state.
Inspect what survives
Reset the prompt, recurrent state, external memory, temporary parameters, or some combination. The resulting ablations reveal where the information actually lived. If behavior survives a context reset, the system may have written somewhere more persistent than claimed.
These tests map directly onto our five questions: carrier, write rule, read rule, lifetime, and failure mode.
13. Open problems
The learner does not know which timescale an observation deserves
One event may be a typo, a task-specific exception, a recurring pattern, or a globally important rule. Current systems often assign lifetime by architecture: tokens last one context, fast weights last one stream, parameters last indefinitely. A mature learner should infer the appropriate timescale from evidence.
Uncertainty and memory management are usually separated
Latent-variable models represent uncertainty but have limited exact memory. External memories preserve records but often rank them with point estimates. A system should use uncertainty to decide what to store, what to retrieve, and whether a correction is strong enough to overwrite an old belief.
Learned update rules can be harder to audit than learned predictions
A bad prediction is one error. A bad write rule can corrupt all future state. Online learners need evaluation for update stability, adversarial writes, recovery after false feedback, and bounded influence of any single event.
Task diversity has no simple scalar definition
Counting tasks is insufficient. Ten thousand surface variants can share one underlying algorithm, while two tasks can require incompatible causal structures. The diversity that induces a reusable learner is diversity in the latent operations the model must infer.
Consolidation needs evidence, not repetition alone
Repeated misinformation is still misinformation. Promoting transient state into persistent parameters should depend on provenance, consistency, uncertainty, and downstream validation—not merely frequency.
We still lack mechanism-level explanations for large pretrained models
Controlled regression studies reveal what Transformers can implement. Activation interventions identify compact task representations. Behavioral studies expose deviations from simple algorithms. Connecting these levels in frontier pretrained models remains open: which circuits implement which update rules, under what prompts, and how do those circuits change with scale and training data?
The useful mental model
In-context learning is not one trick hidden inside attention. It is a family of ways to create and use task-specific state while a model is running.
The examples may remain explicit. They may be compressed into a posterior or task vector. A Transformer may execute a regression algorithm in its activations. A fast-weight matrix may learn associations from prediction error. A neural hidden state may train itself on each token. An external store may preserve episodes. A recurrent policy may distill the structure of trial and error. A temporary parameter copy may be optimized when the forward pass is not enough.
Across all of them, strong inference-time learning needs three ingredients:
- Shared structure across tasks. Without reusable regularities, there is no learning algorithm to amortize.
- Writable task-specific state. New evidence needs a carrier with enough capacity and the right lifetime.
- Training histories that demonstrate adaptation. The data must reward using evidence, correction, and feedback—not only reproducing final expert behavior.
The central design question is therefore not “How do we make the model learn without changing its weights?”
It is:
What should be written, where should it live, how should new evidence revise it, and when should it be forgotten?
Future in-context learners will probably answer with several memories at once: retrieve exact episodes, infer compact task structure, update fast internal state, optimize temporarily when needed, and consolidate only what has earned the right to persist.
References and further reading
Foundations and mechanisms of ICL
- Xie et al., An Explanation of In-context Learning as Implicit Bayesian Inference, ICLR 2022.
- Chan et al., Data Distributional Properties Drive Emergent In-Context Learning in Transformers, NeurIPS 2022.
- Garg et al., What Can Transformers Learn In-Context? A Case Study of Simple Function Classes, NeurIPS 2022.
- Akyürek et al., What Learning Algorithm Is In-Context Learning? Investigations with Linear Models, ICLR 2023.
- von Oswald et al., Transformers Learn In-Context by Gradient Descent, ICML 2023.
- Raventós et al., Pretraining Task Diversity and the Emergence of Non-Bayesian In-Context Learning for Regression, NeurIPS 2023.
- Shen et al., Position: Do Pretrained Transformers Learn In-Context by Gradient Descent?, ICML 2024.
- Min et al., Rethinking the Role of Demonstrations: What Makes In-Context Learning Work?, EMNLP 2022.
- Pan et al., What In-Context Learning “Learns” In-Context: Disentangling Task Recognition and Task Learning, Findings of ACL 2023.
- Hendel et al., In-Context Learning Creates Task Vectors, Findings of EMNLP 2023.
- Todd et al., Function Vectors in Large Language Models, ICLR 2024.
Support sets, task inference, and external memory
- Vinyals et al., Matching Networks for One Shot Learning, NeurIPS 2016.
- Garnelo et al., Conditional Neural Processes, ICML 2018.
- Garnelo et al., Neural Processes, 2018 preprint.
- Kim et al., Attentive Neural Processes, ICLR 2019.
- Weston et al., Memory Networks, ICLR 2015.
- Khandelwal et al., Generalization through Memorization: Nearest Neighbor Language Models, ICLR 2020.
- Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks, NeurIPS 2020.
- Wu et al., Memorizing Transformers, ICLR 2022.
Fast weights and learning at test time
- Ba et al., Using Fast Weights to Attend to the Recent Past, NeurIPS 2016.
- Katharopoulos et al., Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention, ICML 2020.
- Schlag et al., Linear Transformers Are Secretly Fast Weight Programmers, ICML 2021.
- Sun et al., Learning to (Learn at Test Time): RNNs with Expressive Hidden States, ICML 2025.
- Behrouz et al., Titans: Learning to Memorize at Test Time, NeurIPS 2025.
Meta-learning, interaction histories, and temporary optimization
- Finn et al., Model-Agnostic Meta-Learning for Fast Adaptation of Deep Networks, ICML 2017.
- Duan et al., RL²: Fast Reinforcement Learning via Slow Reinforcement Learning, 2016 preprint.
- Chen et al., Decision Transformer: Reinforcement Learning via Sequence Modeling, NeurIPS 2021.
- Laskin et al., In-Context Reinforcement Learning with Algorithm Distillation, ICLR 2023.
- Sun et al., Test-Time Training with Self-Supervision for Generalization under Distribution Shifts, ICML 2020.
- Wang et al., Tent: Fully Test-Time Adaptation by Entropy Minimization, ICLR 2021.
- Akyürek et al., The Surprising Effectiveness of Test-Time Training for Few-Shot Learning, ICML 2025.
Retention and learner-induced histories
- Kirkpatrick et al., Overcoming Catastrophic Forgetting in Neural Networks, PNAS 2017.
- Lopez-Paz and Ranzato, Gradient Episodic Memory for Continual Learning, NeurIPS 2017.
- Ross et al., A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning, AISTATS 2011.