Simple Algorithm
Reinforcement Learning · Fixed Point · 28 min

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

DerivationThe Bayes-adaptive MDP
  1. b′(M) ∝ b(M) PM(s′∣s,a) pM(r∣s,a)b'(\mathcal M)\ \propto\ b(\mathcal M)\,P_{\mathcal M}(s'\mid s,a)\,p_{\mathcal M}(r\mid s,a)

    As in any POMDP, the belief bt(M)=p(M∣ht)b_t(\mathcal M)=p(\mathcal M\mid h_t) is a sufficient statistic of the history (Belief MDPs & α-Vectors). After observing (s,a,r,s′)(s,a,r,s') it updates by Bayes' rule, with the likelihood of the observed reward and transition under each task:

  2. Vh⋆(s,b)=max⁡a EM∼b E(r,s′)∼M(⋅∣s,a)[r+γ Vh−1⋆(s′, b′(s,a,r,s′))]V^\star_h(s,b)=\max_a\ \E_{\mathcal M\sim b}\ \E_{(r,s')\sim\mathcal M(\cdot\mid s,a)}\Big[r+\gamma\,V^\star_{h-1}\big(s',\,b'(s,a,r,s')\big)\Big]

    Planning over hyperstates (s,b)(s,b), with outcomes predicted by the posterior mixture of tasks, gives the Bellman equation of the Bayes-adaptive MDP (Duff, 2002), here with hh steps to go:

  3. 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

DerivationThe value of information in a two-pull bandit
  1. E[θ∣success]=0.8⋅0.8+0.2⋅0.2=0.68,E[θ∣failure]=0.2⋅0.8+0.8⋅0.2=0.32\E[\theta\mid\text{success}]=0.8\cdot0.8+0.2\cdot0.2=0.68,\qquad\E[\theta\mid\text{failure}]=0.2\cdot0.8+0.8\cdot0.2=0.32

    Arm 1 pays 1 with probability θ\theta, where θ=0.2\theta=0.2 or 0.80.8 with prior 12\tfrac12 each; arm 2 pays 0.50.5 surely. Two pulls, no discounting. Without learning, both arms are worth E[θ]=0.5\E[\theta]=0.5 per pull: total 1.0. Now pull arm 1 first and update. A success has probability 0.50.5 and raises the posterior of θ=0.8\theta=0.8 to 0.80.8; a failure lowers it to 0.20.2:

  2. 0.5+0.5⋅0.68+0.5⋅0.5=1.09 > 1.00.5+0.5\cdot0.68+0.5\cdot0.5=1.09\ >\ 1.0

    The second pull follows the posterior: arm 1 after a success (0.68>0.50.68>0.5), arm 2 after a failure (0.32<0.50.32<0.5). The Bayes-optimal plan therefore earns

  3. 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.

Predict before you look

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 0.5+0.5⋅max⁡(0.68,0.6)+0.5⋅max⁡(0.32,0.6)=0.5+0.34+0.3=1.140.5+0.5\cdot\max(0.68,0.6)+0.5\cdot\max(0.32,0.6)=0.5+0.34+0.3=1.14; pulling arm 2 twice gives 1.21.2 (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 π(at∣ht)\pi(a_t\mid h_t) 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 p(M)p(\mathcal M) 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.

Check your understanding

Ideally, what must an RL² agent's hidden state encode to act Bayes-optimally?

  1. The full history of the trial, verbatim
  2. The identity of the current task, which the agent observes
  3. Enough to determine the posterior over tasks given the trial so far, together with the current state
  4. 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

DerivationMAML’s meta-gradient, and the term that teaches exploration
  1. θM′=θ+α g^M(θ;D),D∼πθ in M,max⁡θ EM∼p ED[JM(θM′)]\boldsymbol\theta'_{\mathcal M}=\boldsymbol\theta+\alpha\,\hat g_{\mathcal M}(\boldsymbol\theta;\mathcal D),\qquad\mathcal D\sim\pi_{\boldsymbol\theta}\text{ in }\mathcal M,\qquad\max_{\boldsymbol\theta}\ \E_{\mathcal M\sim p}\,\E_{\mathcal D}\big[J_{\mathcal M}(\boldsymbol\theta'_{\mathcal M})\big]

    MAML (Finn, Abbeel & Levine, 2017) meta-learns an initialization. For each task, one policy-gradient step from θ\boldsymbol\theta uses an estimate g^M(θ;D)\hat g_{\mathcal M}(\boldsymbol\theta;\mathcal D) computed from a batch D\mathcal D of trajectories of πθ\pi_{\boldsymbol\theta} in M\mathcal M, and the meta-objective scores the adapted policy:

  2. ∇θJM(θM′)=(I+α∇θg^M(θ;D))⊤∇θ′JM(θM′)\nabla_{\boldsymbol\theta}J_{\mathcal M}(\boldsymbol\theta'_{\mathcal M})=\big(I+\alpha\nabla_{\boldsymbol\theta}\hat g_{\mathcal M}(\boldsymbol\theta;\mathcal D)\big)^\top\nabla_{\boldsymbol\theta'}J_{\mathcal M}(\boldsymbol\theta'_{\mathcal M})

    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:

  3. ∇θED[JM(θM′)]=ED[(I+α∇θg^M)⊤∇θ′JM(θM′)+JM(θM′) ∇θlog⁡πθ(D)]\nabla_{\boldsymbol\theta}\E_{\mathcal D}\big[J_{\mathcal M}(\boldsymbol\theta'_{\mathcal M})\big]=\E_{\mathcal D}\Big[\big(I+\alpha\nabla_{\boldsymbol\theta}\hat g_{\mathcal M}\big)^\top\nabla_{\boldsymbol\theta'}J_{\mathcal M}(\boldsymbol\theta'_{\mathcal M})+J_{\mathcal M}(\boldsymbol\theta'_{\mathcal M})\,\nabla_{\boldsymbol\theta}\log\pi_{\boldsymbol\theta}(\mathcal D)\Big]

    But the batch was sampled from πθ\pi_{\boldsymbol\theta}, so its distribution depends on θ\boldsymbol\theta too. The score-function identity adds a second term, with log⁡πθ(D)\log\pi_{\boldsymbol\theta}(\mathcal D) the sum of the log-probabilities of the batch's actions:

  4. 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 c={(s,a,r,s′)}c=\{(s,a,r,s')\} into a posterior qϕ(z∣c)q_\phi(z\mid c) over a latent task zz, built as a product of Gaussian factors, one per transition, so the order of transitions does not matter. The policy π(a∣s,z)\pi(a\mid s,z) and critic Q(s,a,z)Q(s,a,z) are trained off-policy with soft actor–critic. On a new task it samples zz from the current posterior, acts for an episode as if zz 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 q(m∣ht)q(m\mid h_t) over a latent task embedding mm, updated at every step and trained like a variational autoencoder to predict the trial's past and future rewards and transitions from mm. 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.

MethodWhere adaptation happensHow it exploresMeta-trainingWhat it approximates
RL²recurrent hidden statelearned, implicitlyon-policy RL over trialsthe Bayes-optimal policy
MAMLgradient steps from a learned initializationpre-update policy, through the score-function termon-policy, second ordera good starting point for gradient adaptation
PEARLposterior over a latent task, from contextposterior sampling, one sample per episodeoff-policy (SAC)posterior sampling
VariBADbelief over a latent task, updated every stepbelief-conditioned policyon-policy RL with a VAEthe Bayes-optimal policy
Check your understanding

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?

  1. Posterior sampling: sample a goal location from the posterior and head there for the whole episode
  2. A belief-conditioned policy that sweeps the circle and updates its belief at every step
  3. MAML with one gradient step after the episode
  4. 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.

DerivationWhy predicting optimal actions yields posterior sampling
  1. M⋆(a∣s,D)=Pr⁡(a⋆=a∣s,D)M^\star(a\mid s,\mathcal D)=\Pr\big(a^\star=a\mid s,\mathcal D\big)

    The expected negative log-likelihood is minimized by the true conditional distribution of the label given the inputs, so an exact minimizer outputs

  2. Pr⁡(a⋆=a∣s,D)=∑τTpre(τ∣D) πτ⋆(a∣s)\Pr\big(a^\star=a\mid s,\mathcal D\big)=\sum_\tau\mathcal T_{\text{pre}}(\tau\mid\mathcal D)\,\pi^\star_\tau(a\mid s)

    Expand over the unknown task. Compliance means the dataset's actions carry no information about τ\tau beyond the transitions and rewards they produced, so the posterior over tasks is the Bayesian posterior of the prior Tpre\mathcal T_{\text{pre}} given the observed data:

  3. 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 Tpre\mathcal T_{\text{pre}}, 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 104010^{40} 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 (s,b)(s,b), 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.

Question 1

What is the state of the Bayes-adaptive MDP of a meta-RL problem?

  1. The environment state alone
  2. The environment state together with the posterior over tasks
  3. The identity of the current task
  4. 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 bb, must be part of the state; the hyperstate (s,b)(s,b) evolves deterministically given each observation through Bayes' rule. The Bellman equation over hyperstates yields the Bayes-optimal policy.

Question 2

In MAML for RL, what does the meta-gradient term E[JM(θM′) ∇θlog⁡πθ(D)]\E\big[J_{\mathcal M}(\boldsymbol\theta'_{\mathcal M})\,\nabla_{\boldsymbol\theta}\log\pi_{\boldsymbol\theta}(\mathcal D)\big] do?

  1. It corrects for the curvature of the return
  2. It regularizes the adapted policy toward the initialization
  3. Nothing: it has zero expectation
  4. 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 πθ\pi_{\boldsymbol\theta}, so changing θ\boldsymbol\theta 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.

Question 3

Why is posterior sampling generally not Bayes-optimal?

  1. 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
  2. It ignores the prior
  3. It needs to observe the task identity
  4. 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.

Question 4

Under its assumptions, what does a decision-pretrained transformer do when deployed online on a new task from the pretraining distribution?

  1. It imitates the algorithm that generated its pretraining data
  2. It acts Bayes-optimally
  3. It behaves like posterior sampling with the pretraining task distribution as its prior
  4. 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).