Meta-RL & In-Context Reinforcement Learning
RL², Bayes-adaptive agents, and transformers that learn to reinforcement-learn in context.
Train a recurrent network on thousands of bandit problems and it stops being a policy for any one of them: it becomes a learning algorithm that explores a new problem, then exploits it, without a single gradient step at test time. This lesson says what such a learner should converge to, the Bayes-optimal policy of the Bayes-adaptive MDP, and how close the main families come: recurrent learners, gradient-based learners, inference-based learners, and transformers that learn to reinforcement-learn in context, one of which provably performs posterior sampling.
What you’ll learn
- Formulate meta-RL as a POMDP over tasks, derive the Bellman equation of the Bayes-adaptive MDP, and compute the value of exploration in a small example.
- Explain why the optimum of the meta-RL objective is Bayes-optimal, and what the evidence says about memory-based learners reaching it.
- Derive MAML's meta-gradient for RL, including the term that teaches exploration, and contrast posterior-sampling exploration (PEARL) with belief-conditioned policies (VariBAD).
- State the theorem that a decision-pretrained transformer performs posterior sampling, with its conditions, and say what algorithm distillation and AdA do and do not show.
Meta-RL is a POMDP over tasks
As in any POMDP, the belief is a sufficient statistic of the history (Belief MDPs & α-Vectors). After observing it updates by Bayes' rule, with the likelihood of the observed reward and transition under each task:
Planning over hyperstates , with outcomes predicted by the posterior mixture of tasks, gives the Bellman equation of the Bayes-adaptive MDP (Duff, 2002), here with steps to go:
Its optimal policy is Bayes-optimal: no policy earns more in expectation over the prior. Exploration is not a separate mechanism: an action is worth taking for its information exactly when the improvement of later decisions under the updated belief repays its immediate cost. The price is computational, because the hyperstate space is continuous and grows with the history. Exact solutions exist only in special cases, such as the Gittins index for discounted bandits with independent arms (The Gittins Index), and sample-based planners such as BAMCP (Guez, Silver & Dayan, 2012) approximate the rest.
What exploration is worth, and who learns it
Arm 1 pays 1 with probability , where or with prior each; arm 2 pays surely. Two pulls, no discounting. Without learning, both arms are worth per pull: total 1.0. Now pull arm 1 first and update. A success has probability and raises the posterior of to ; a failure lowers it to :
The second pull follows the posterior: arm 1 after a success (), arm 2 after a failure (). The Bayes-optimal plan therefore earns
The extra 0.09 is the value of the information the first pull buys. A myopic agent, comparing expected immediate rewards only, sees a tie and has no reason to explore; the Bayes-adaptive value sees the option to switch.
Same problem, but arm 2 now pays 0.6 surely. What is the Bayes-optimal expected total over the two pulls?
Show the answer
1.2
Exploring first gives ; pulling arm 2 twice gives (and pulling it first leaves no time to use what arm 1 would reveal). So the Bayes-optimal agent does not explore at all: the information is worth less than the 0.1 it would cost.
RL² (Duan et al., 2016) and Wang et al. (2016) represent with a recurrent network whose hidden state runs through the whole trial and whose inputs include the previous action and reward (in RL², also a flag marking the end of each episode); an ordinary RL algorithm trains its weights on trial returns. That is exactly the objective above, so over sufficiently expressive networks its optimum is the Bayes-optimal policy, and since the belief is a sufficient statistic, an optimal hidden state need not store the history, only enough of it to determine the posterior.
Whether training finds that optimum is an empirical matter. On random bandits and small MDPs, RL² performed close to algorithms designed with optimality guarantees (Duan et al., 2016). Ortega et al. (2019) argued that memory-based meta-learning amortizes Bayesian inference over the task distribution, and Mikulik et al. (2020) found that meta-trained recurrent agents on prediction and bandit tasks behaved like Bayes-optimal agents and shared their computational structure: each could be approximately simulated by the other, and Bayes-optimal agents are fixed points of meta-training.
Two caveats. The optimum is Bayes-optimal for the training prior: on tasks outside a meta-learner can be confidently wrong. And learning to explore is hard for the outer loop, because exploration in early episodes pays off only in later ones, a long-range credit-assignment problem.
Ideally, what must an RL² agent's hidden state encode to act Bayes-optimally?
- The full history of the trial, verbatim
- The identity of the current task, which the agent observes
- Enough to determine the posterior over tasks given the trial so far, together with the current state
- The gradient of the trial's return
Show the answer
C. Enough to determine the posterior over tasks given the trial so far, together with the current state
The pair (current state, belief) is a sufficient statistic: the Bayes-adaptive Bellman equation depends on the history only through it. Anything more is redundant for acting, and anything less loses information that a Bayes-optimal agent would use.
Gradient-based and inference-based meta-learners
MAML (Finn, Abbeel & Levine, 2017) meta-learns an initialization. For each task, one policy-gradient step from uses an estimate computed from a batch of trajectories of in , and the meta-objective scores the adapted policy:
For a fixed batch, the chain rule through the update brings in the Jacobian of the step, which contains the Hessian of the estimated return:
But the batch was sampled from , so its distribution depends on too. The score-function identity adds a second term, with the sum of the log-probabilities of the batch's actions:
The second term is how MAML learns to explore: pre-update behavior is reinforced when the data it gathers lead to a good adapted policy. Stadie et al. (2018) and Rothfuss et al. (2019) analyzed this term and showed that estimators which drop it remove the pre-update policy's incentive to explore. First-order variants also drop the Hessian, trading adaptation quality for computation.
Gradient-based adaptation keeps improving with more data, even on unfamiliar tasks, because it is ordinary RL from a good starting point; but a few gradient steps from a few episodes use the data far less efficiently than a learned inference procedure. Two methods make the inference explicit with a latent task variable.
PEARL (Rakelly, Zhou, Quillen, Finn & Levine, 2019) encodes a context of transitions into a posterior over a latent task , built as a product of Gaussian factors, one per transition, so the order of transitions does not matter. The policy and critic are trained off-policy with soft actor–critic. On a new task it samples from the current posterior, acts for an episode as if were true, adds the transitions to the context and samples again: posterior sampling (Posterior Sampling & Deep Exploration). Off-policy meta-training made it far more sample-efficient to meta-train than on-policy RL² or MAML, as reported.
VariBAD (Zintgraf et al., 2020) aims at the Bayes-adaptive policy itself. A recurrent encoder maintains an approximate posterior over a latent task embedding , updated at every step and trained like a variational autoencoder to predict the trial's past and future rewards and transitions from . The policy receives the posterior's mean and variance and is trained by RL. Because it conditions on its own uncertainty, it can explore systematically within an episode, which posterior sampling cannot.
| Method | Where adaptation happens | How it explores | Meta-training | What it approximates |
|---|---|---|---|---|
| RL² | recurrent hidden state | learned, implicitly | on-policy RL over trials | the Bayes-optimal policy |
| MAML | gradient steps from a learned initialization | pre-update policy, through the score-function term | on-policy, second order | a good starting point for gradient adaptation |
| PEARL | posterior over a latent task, from context | posterior sampling, one sample per episode | off-policy (SAC) | posterior sampling |
| VariBAD | belief over a latent task, updated every step | belief-conditioned policy | on-policy RL with a VAE | the Bayes-optimal policy |
Each trial is a single episode in which the agent must find a goal hidden somewhere on a circle, rewarded only on reaching it. Which approach can, in principle, act close to Bayes-optimally?
- Posterior sampling: sample a goal location from the posterior and head there for the whole episode
- A belief-conditioned policy that sweeps the circle and updates its belief at every step
- MAML with one gradient step after the episode
- All of them equally, given enough meta-training
Show the answer
B. A belief-conditioned policy that sweeps the circle and updates its belief at every step
With one episode, information is only useful within the episode. A belief-conditioned policy can search, rule out locations as it passes them, and change course. Posterior sampling commits to one guess per episode, and a gradient step after the episode comes too late to help.
Transformers that reinforcement-learn in context
In-context RL asks a sequence model to improve on a new task from the experience in its context window alone. Algorithm distillation (Laskin et al., 2023) records the learning histories of a source RL algorithm, long sequences spanning many episodes during which it improves on each of many tasks, and trains a causal transformer to predict the source's next action from the preceding history. To predict what a learning algorithm does next, the model must model how it improves; at test time, with frozen weights, it improves in context on new tasks. The authors reported in-context learners that were more data-efficient than the source algorithm, in environments with sparse rewards, combinatorial task structure and pixel observations.
The expected negative log-likelihood is minimized by the true conditional distribution of the label given the inputs, so an exact minimizer outputs
Expand over the unknown task. Compliance means the dataset's actions carry no information about beyond the transitions and rewards they produced, so the posterior over tasks is the Bayesian posterior of the prior given the observed data:
A draw from the model is therefore a draw of a task from the posterior followed by that task's optimal action. Posterior sampling proper keeps one sampled task for a whole episode; the theorem's version of the model also conditions on the current episode's partial trajectory, which makes successive actions consistent with a single posterior draw. The original architecture is an approximation to it. And because the posterior uses the structure of , the learned algorithm can beat the one that generated its data.
At larger scale, the Adaptive Agent (AdA; Adaptive Agent Team, 2023) combined meta-RL over XLand 2.0, a procedurally generated space of more than 3D tasks, with a transformer memory spanning several episodes (trials, in AdA's terms), an automated curriculum keeping tasks at the edge of the agent's ability, and distillation. On held-out tasks it improved over a few episodes, within minutes, on a timescale comparable to human players, and its adaptation improved with network size, memory length and the richness of the training distribution, as reported.
What in-context RL shows, as of the mid-2020s: sequence models can implement learning algorithms in their activations, and under idealized assumptions the algorithm learned from optimal-action labels is posterior sampling, which can outperform its data's source by exploiting the structure of the task distribution. What it does not yet show: reliable improvement far outside the pretraining distribution, over horizons much longer than the training contexts, or guarantees for transformers trained to finite accuracy on realistic data.
Key takeaways
- Meta-RL is a POMDP over tasks; its optimum is the Bayes-optimal policy of the Bayes-adaptive MDP over hyperstates , which explores exactly when information is worth its cost (1.09 versus 1.0 in the two-pull bandit, and no exploration once the safe arm pays 0.6).
- Memory-based meta-learners such as RL² have the Bayes-optimal policy as their ideal and need only track the posterior; on bandit and prediction tasks they have been found to behave like Bayes-optimal agents, but only for their training prior.
- MAML adapts by policy-gradient steps; its meta-gradient has a Hessian term and a score-function term that rewards informative pre-update behavior. PEARL explores by posterior sampling over a latent task; VariBAD conditions on a belief and can explore within an episode.
- Transformers can reinforcement-learn in context: algorithm distillation imitates learning histories, and a decision-pretrained transformer that predicts optimal actions performs posterior sampling under stated conditions, with regret bounds that can beat its data's source.
- AdA showed fast in-context adaptation across a vast procedurally generated task space; as of the mid-2020s, how far in-context RL extends beyond its training distribution remains open.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
What is the state of the Bayes-adaptive MDP of a meta-RL problem?
- The environment state alone
- The environment state together with the posterior over tasks
- The identity of the current task
- The parameters of the policy
Show the answer
B. The environment state together with the posterior over tasks
The task is hidden, so the agent's knowledge about it, the posterior , must be part of the state; the hyperstate evolves deterministically given each observation through Bayes' rule. The Bellman equation over hyperstates yields the Bayes-optimal policy.
In MAML for RL, what does the meta-gradient term do?
- It corrects for the curvature of the return
- It regularizes the adapted policy toward the initialization
- Nothing: it has zero expectation
- It credits the pre-update policy for gathering data that make the adaptation step effective, which is what teaches it to explore
Show the answer
D. It credits the pre-update policy for gathering data that make the adaptation step effective, which is what teaches it to explore
The batch used for the inner update is sampled from , so changing changes which data the update sees. The score-function term reinforces pre-update behavior in proportion to how good the adapted policy turned out to be.
Why is posterior sampling generally not Bayes-optimal?
- It acts optimally for one sampled task at a time, so it never takes actions whose only value is information and cannot hedge within an episode
- It ignores the prior
- It needs to observe the task identity
- It is Bayes-optimal; only its computation differs
Show the answer
A. It acts optimally for one sampled task at a time, so it never takes actions whose only value is information and cannot hedge within an episode
An action that is optimal for no single task, such as listening in the tiger problem or probing which task is active, is never chosen by posterior sampling, although a Bayes-optimal agent may choose it. Posterior sampling is attractive for its regret guarantees and simplicity, not for Bayes-optimality.
Under its assumptions, what does a decision-pretrained transformer do when deployed online on a new task from the pretraining distribution?
- It imitates the algorithm that generated its pretraining data
- It acts Bayes-optimally
- It behaves like posterior sampling with the pretraining task distribution as its prior
- It acts greedily with respect to the empirical mean rewards
Show the answer
C. It behaves like posterior sampling with the pretraining task distribution as its prior
Predicting the optimal action from data yields the posterior predictive of the optimal action, so sampling from the model samples a task from the posterior and acts optimally for it. With the history-conditioned version, whole trajectories match posterior sampling, which is how it can beat its data's source.
Further reading
- Y. Duan, J. Schulman, X. Chen, P. L. Bartlett, I. Sutskever & P. Abbeel, "RL²: Fast reinforcement learning via slow reinforcement learning," arXiv:1611.02779 (2016).
- C. Finn, P. Abbeel & S. Levine, "Model-agnostic meta-learning for fast adaptation of deep networks," ICML (2017).
- L. Zintgraf, K. Shiarlis, M. Igl, S. Schulze, Y. Gal, K. Hofmann & S. Whiteson, "VariBAD: A very good method for Bayes-adaptive deep RL via meta-learning," ICLR (2020).
- J. N. Lee, A. Xie, A. Pacchiano, Y. Chandak, C. Finn, O. Nachum & E. Brunskill, "Supervised pretraining can learn in-context reinforcement learning," NeurIPS (2023).
- J. Beck, R. Vuorio, E. Z. Liu, Z. Xiong, L. Zintgraf, C. Finn & S. Whiteson, "A tutorial on meta-reinforcement learning," Foundations and Trends in Machine Learning 18(2–3), 224–384 (2025); first released as "A survey of meta-reinforcement learning," arXiv:2301.08028 (2023).