Train an agent on many related tasks and it learns how to learn. On a new task it finds the prize in 2 tries. A learner that starts from scratch needs about 23.
Learn how an agent learns a new task from a few tries. We cover the task split, memory learners, MAML, task inference, and why exploration is the hard part.
Press New task, then Play. Three learners race in the same hallway. Then switch on The sign lies and race again. Then we build the meta-learner piece by piece.
You need a little Python, what a probability is, and the idea of a policy that improves from rewards (Policy Gradients). We build the rest from zero.
Re-taught from the meta-reinforcement learning lecture of Stanford CS 224R: Deep Reinforcement Learning. The explanations, toys and numbers here are our own; every toy number is illustrative.
Illustrative toy. Each try is a one-step episode: read the sign, or open one of 8 doors; the prize door pays 1. From scratch: a softmax policy over the 9 actions, trained by REINFORCE with step size 1. In 2,000 simulated runs it needed a median of 23 tries to be 90% sure (middle 80% of runs: 16 to 37). Posterior sampling opens a random unopened door: 4.5 tries on average. Meta-learned: the Chapter 4 agent after meta-training. Past try 2 it keeps its try-2 rule.
Chapter 0
See why an agent should bring its skill from old tasks to a new one, and what that costs up front
You walk into a strange kitchen. The espresso machine has odd buttons, but you pull a good shot in two minutes. You did not learn coffee from zero. You reused what you know about grind, water and pressure.
A standard RL agent starts each new task from a blank policy. In the hero, that learner needs about 23 tries for a hallway with 8 doors. Real robot tasks need far more.
Meta-reinforcement learning (meta-RL) trains an agent on many related tasks so that it learns a new task from a few tries. The related tasks form a task family: here, hallways that differ only in which door hides the prize. Training across the family is meta-training. Facing a new task from the family afterwards is meta-testing.
Meta-training is not free. Our meta-learner in Chapter 4 needed about 1,400 tasks of 2 tries each: 2,800 tries up front. After that it spends 2 tries on each new task, not 23.
Yellow is the learner from scratch, 23 tries per task. Blue is the meta-learner: 2,800 tries up front, then 2 per task. Drag the number of new tasks.
The 23 and the 2,800 come from this page's toys (the hero and Chapter 4). Real costs differ, but the shape is the same.
Each new task saves 23 − 2 = 21 tries. The 2,800 tries come back after 2,800 ÷ 21 = 133 tasks. Below that, learning from scratch is cheaper.
The failure. Meta-learning helps only on tasks from the same family. In the hero, switch on The sign lies: the test task now breaks a rule that every training task kept. The meta-learner opens the named door again and again, while the plain learner still finds the prize. To measure it, test on tasks held out from training, including some that differ a little. The fix is a wider training family, or a fall-back to slow learning when the fast guess keeps failing.
Chapter 1
Compare forward transfer, multi-task learning and meta-learning by what each gets when a new task arrives
A new hallway arrives: the prize is behind door 6. Three approaches can reuse old hallways. They differ in one thing: what the agent gets when the new task arrives.
Forward transfer trains on one source task, then fine-tunes the same weights on the new task. It helps when the two tasks are close. Here it hurts. A policy trained on door 3 is 90% sure of door 3, so it must unlearn that first.
Multi-task learning trains one policy on many tasks. The policy takes a task label z as an input, for example "the goal is door 6". Given the label, it solves a new task at once. Someone must supply z.
Meta-learning gets no label. It gets a few tries of its own and must work out the task from them. Few-shot classification works the same way: the model takes the test input and a small labelled set, and an LLM reads examples in its prompt. In RL, the agent must also collect that small set itself.
Left: the chances each approach gives the sign and the 8 doors before its first try. The prize is door 6. Right: the tries each needs. Pick an approach.
Illustrative toy, same hallway as the hero. Tries are medians of 2,000 simulated runs: REINFORCE at step size 1, until the agent is 90% sure. Forward transfer starts 90% sure of door 3.
| Approach | At test time it gets | Tries on door 6 |
|---|---|---|
| From scratch | nothing; it learns by trial | 23 |
| Forward transfer | weights from one source task | 86 |
| Multi-task | the task label z | 1 |
| Meta-learning | only its own tries | 2 |
The failure. Forward transfer can be slower than starting fresh: 86 tries against 23 here. This is negative transfer. To spot it, run a from-scratch learner on the same task and compare. The fix is to pretrain on many tasks, not one, or to reset the last layer before fine-tuning.
Chapter 2
Define a task, a task family, and the split between meta-training and meta-testing
An RL task is a full MDP. It has states, actions, a way to start, dynamics (how the world responds to an action) and a reward. In a task family, every task shares the states and the actions. The dynamics, the reward and the start can differ.
| Family | What differs between tasks |
|---|---|
| Mazes | the walls: the dynamics |
| Walking robots | the slope (dynamics) or the goal direction (reward) |
| Robot arms | which object, which goal place |
| Our hallway | which door pays: the reward |
A task distribution, p(T), says how likely each task is. The two phases use it differently:
| Phase | Tasks | What changes | What we measure |
|---|---|---|---|
| Meta-training | many, drawn from p(T) | the weights | the training objective |
| Meta-testing | new ones, held out, same p(T) | memory, or a few fast steps | the score after k tries |
The record of an agent's tries on the current task is its context, written Dtrain: each state, action, reward and next state so far. It plays the part of the task label z. Nobody hands it over; the agent collects it.
There are two ways to score a test task. In the episodic variant the agent gets k exploration episodes that do not count, then scored episodes. In the online variant every step counts, so exploring has a price.
Each tile is one try. Grey tiles are not scored. Pick a variant and a strategy, then change the number of free tries.
Illustrative toy. Episodic: k free tries, then one scored try. Online: two tries, both scored, the second shrunk by a discount of 0.9. Scores are averages over the 8 possible prize doors.
With one free try, the reader reads the sign and then opens the right door: score 1. Online, the reading try counts and pays 0, so the score is 0 + 0.9 × 1 = 0.9.
The failure. Testing on the training tasks gives great numbers that collapse on new tasks. The agent memorised the tasks; it did not learn to adapt. Measure on tasks it never trained on. The fix: split by task, never by episode.
Chapter 3
Give a network memory, feed it the rewards, and never wipe the memory inside a task
The simplest meta-learner is a network with memory, such as an RNN or a transformer. Its memory carries what it has seen on the current task. Nobody designs the learning rule; the network finds one during meta-training. That is why we call it black-box.
Two details make it different from an ordinary recurrent policy:
Call the memory after step t the hidden state ht. Call what the agent sees now ot, and its last action at−1. Call the last reward rt−1, and the episode-end flag dt−1. A network f with weights θ updates the memory:
h-t equals f-theta of h-t-minus-1, o-t, a-t-minus-1, r-t-minus-1 and d-t-minus-1.
Take the old memory h-t-minus-1. Add what the agent sees, what it did, the reward it got and whether an episode ended. The cell f-theta mixes these into the new memory h-t. A policy head reads h-t and picks the next action.
In the hallway, o-t is 8 numbers, one per door the sign can name. Add 9 for a-t-minus-1, 1 reward and 1 flag: 19 inputs. A GRU with 256 hidden units then has 212,736 weights, and a policy head over 9 actions adds 2,313.
Purple bars show what the hidden state must encode: a belief about the prize door. Press Step. Then switch on the reset and step again.
Illustrative. The real hidden state is 256 numbers, not a belief; we draw what those numbers must carry for the agent to act well.
| Method | Memory | Outer RL method | Trade-off |
|---|---|---|---|
| RL² (Duan et al.; Wang et al.) | GRU or LSTM hidden state | TRPO or A3C, on-policy | simple; needs many tasks |
| SNAIL (Mishra et al.) | temporal convolutions + attention | TRPO, on-policy | reaches far back; cost grows with the square of the length |
| PEARL (Rakelly et al.) | a latent task vector z | SAC, off-policy | reuses old data; ignores order (Chapter 6) |
The failure. Resetting the memory at each episode end is the most common bug. Try 2 becomes a guess, right 1 time in 8. To measure it, plot the return by episode number inside a task: it should rise from episode 1 to episode 2. The fix: reset only when the task changes.
Chapter 4
Train one set of weights across many tasks so that early tries buy later reward
Meta-training is an ordinary RL loop with one change: each sample is a whole task, run end to end with the memory kept.
Name the parts first. The weights are θ. A task T comes from the family p(T). The reward at step t is rt, where t counts steps across every episode of the task. The discount γ shrinks later rewards.
J of theta equals the expected value, over tasks T drawn from p of T, of the sum over t of gamma to the t times r-t.
Draw a task. Run all its episodes without wiping memory. Shrink each reward r-t by gamma once per step and add them. Average that total over many tasks. Meta-training raises J of theta.
A hallway task has 2 tries, and gamma is 0.9. The sign reader gets r-0 = 0, then r-1 = 1: a total of 0 + 0.9 × 1 = 0.9. The best guesser earns 0.35 on average. The objective prefers the reader, though reading pays nothing on the spot.
Our agent is tiny. It has five weights, each a score added to one action:
Purple: how often the agent reads the sign on try 1. Green: how often try 2 opens the prize. Bars: the five weights. Press Train, then try it with the memory reset.
Illustrative toy, trained live: 16 tasks per update, REINFORCE with a running-average baseline, step size 4, gamma 0.9. In 40 runs the agent switched to the sign after a median of 1,392 tasks (middle 80%: 582 to 2,560). 2 runs had not switched after 6,400.
Watch the purple line first fall: from 11% to about 3% in a typical run. Reading pays only once w is large, so the agent first learns to avoid the sign. Chapter 7 explains this dip.
The failure. Switch on the memory reset. Try 2 no longer knows what try 1 saw, so w gets no signal and success stays near 12%: a guess. Measure it as in Chapter 3, by return per episode number. The fix is to keep the memory for the whole task.
Chapter 5
Choose the starting weights so that one gradient step solves any task in the family
Black-box meta-RL hides the learning rule in a network. MAML (model-agnostic meta-learning; Finn, Abbeel and Levine, 2017) writes it down: take a few policy-gradient steps at test time. Meta-training picks only the start.
A toy family has two tasks. The agent picks an aim on a line. Task A's expected reward is a bump of height 1 and width 1 at −2; task B's is the same bump at +2.
The inner loop adapts to one task. Call the start θ, task i's expected reward Ji, the step size α, and the adapted weights θ′i:
Theta-prime-i equals theta plus alpha times nabla-theta of J-i of theta.
From theta, step uphill on task i's reward, scaled by alpha. The result theta-prime-i is the policy adapted to task i. In RL, a few episodes estimate the slope.
Start at theta = 0 on task B. The reward there is 0.135 and its slope is 0.271. With alpha = 7.4: theta-prime = 0 + 7.4 × 0.271 = 2.00. The reward after one step is 1.00, the top of the bump.
The outer loop moves the start, using the N tasks of a batch and a step size β:
Theta becomes theta plus beta times nabla-theta of one over N times the sum over i of J-i of theta-prime-i.
Adapt each task with one inner step and score it at theta-prime-i. Move theta uphill on the average score, by beta. The gradient passes through the inner step, so it needs the slope of a slope.
Start at theta = 0.5. Task A steps to −0.31; task B overshoots to 4.10. The average reward after the step is 0.18, and its gradient is −1.01. With beta = 0.5, theta moves to −0.005, where the average after one step is 1.00.
Top: the two task bumps, the blue start, and one inner step to each teal point. Bottom: the average reward before the step (yellow) and after it (blue). Drag the start.
Illustrative toy with the exact gradient. Each task's reward is a bump of height 1 and width 1 at −2 or +2.
The best average start sits near a goal, ±2: 0.50 before the step and after, because the far bump is flat there. The MAML start, 0, earns 0.14 before the step and 1.00 after.
The failure. At theta = 0.5 the step throws task B to 4.10, past its goal: reward 0.11, down from 0.32. Measure the reward before and after the step on held-out tasks. The fix is a smaller alpha, or several smaller steps. First-order MAML skips the slope of a slope to save compute: here it gives −0.32, not −1.01.
| Black-box | MAML | |
|---|---|---|
| What adapts | the hidden state | the weights, by gradient steps |
| Test-time cost | one forward pass per step | episodes for each gradient step |
| Task a little outside the family | may fail with no way back | keeps improving with more steps |
Chapter 6
Treat the task as a hidden variable and update a belief about it after each try
If the agent knew the task label z, it could act like a multi-task policy. In meta-RL, z is hidden. That makes meta-RL a POMDP: a decision problem where part of the state is hidden. Here the hidden part is the task.
A good POMDP agent keeps a belief: a probability for each possible task. Call the belief in task z after step t bt(z). After each try the agent sees a reward rt and a next state st+1. Bayes' rule updates the belief:
b-t-plus-1 of z is proportional to p of r-t and s-t-plus-1 given s-t, a-t and z, times b-t of z.
For each task z, ask how probable the new reward and state are if z were true. Multiply the old belief by that number. Divide every product by their total.
With made-up numbers: 8 doors at 0.125 each. A faded sign says 6; it is right 70% of the time and otherwise names another door at random. The likelihood is 0.7 for door 6 and 0.3 ÷ 7 = 0.043 for each other door. The products, 0.0875 and 0.0054, add to 0.125. So door 6 now has 0.70, every other door 0.043.
Purple bars are the belief. Tap a door to open it, or read the sign. Then switch on the faded sign.
Illustrative toy with an exact Bayes update.
A black-box RNN never runs this update. If meta-training works, its hidden state carries something that acts like the belief. PEARL (Rakelly et al., 2019) makes the inference explicit:
Call transition n's guess a bell curve N(z; μn, σn2) with mean μn and variance σn2:
q of z given D-train is proportional to the product over n of N of z, with mean mu-n and variance sigma-n squared.
Each transition gives a bell curve for z. Multiply the curves. The result is a bell curve. Its precision (one over the variance) is the sum of the precisions. Its mean is the precision-weighted average of the mu-n.
With made-up numbers: one transition says mu 1.0, variance 1.0; another says 3.0, variance 0.25. Precisions 1 and 4 add to 5, so the variance is 0.2. The mean is (1 × 1.0 + 4 × 3.0) ÷ 5 = 2.6. The surer guess pulls harder.
The failure. A product ignores order: "A then B" and "B then A" give the same z. The policy cannot use a strategy that depends on order. To measure it, shuffle the context and see that nothing changes. The fix is a recurrent or attention encoder.
Chapter 7
See why a good exploring move earns no reward of its own, and how exploring and exploiting block each other
End-to-end training optimises exploring and exploiting together for the total reward, as in Chapter 4. In principle it finds the best balance. In practice it often gets stuck.
Reading the sign is perfect exploration: one try, all the information. But it pays 0 on the spot. Its value comes one try later, and only if the agent then opens the named door. This is a credit assignment problem: the reward for a good exploring move comes late and depends on later moves.
Name the parts. Call q the chance that the try-2 policy opens the door the sign named: the agent's skill at using the sign. Reading is worth γ q. A guesser opens a door, then repeats it if it paid or tries another: (1 + 2γ) / 8. Reading wins only when:
Gamma times q is greater than one plus two gamma, over eight.
Reading the sign pays 0 now and gamma times q on try 2. Guessing pays (1 + 2 gamma) / 8 over both tries. The agent should learn to read only when gamma times q is the larger.
With gamma 0.9 the line is q > 2.8 ÷ 7.2 = 0.39. An untrained agent follows the sign only by chance: q = 1/8 = 0.125. Reading is then worth 0.11 and guessing 0.35, so training first pushes the agent away from the sign.
Purple: the value of reading the sign. Yellow: the value of guessing. The ruler marks the line q must pass. Drag q, then gamma.
Exact values for the two-try hallway with 8 doors.
This is the coupling problem (Liu, Raghunathan, Liang and Finn, 2021). The agent cannot learn to use the sign until it reads it often. It will not read it often until it can use it. That is the dip in Chapter 4.
The failure. In 2 of our 40 training runs the agent still avoided the sign after 6,400 tasks. The symptom is a plateau at the guesser's score, 0.35. Measure how often the agent takes information actions as training goes on. The fix: separate exploring from exploiting (Chapter 8), or force some exploration.
Chapter 8
Compare explorers by how much each try teaches about the task
Each fix for the coupling problem picks a different signal to explore by:
| Strategy | Explores by | Breaks when |
|---|---|---|
| End-to-end | total reward | the coupling trap of Chapter 7 |
| Posterior sampling (PEARL) | sample a task z, act as if it is true | the useful move is in no task's solution, like the sign |
| Prediction (MetaCURE, Zhang et al.) | making a model of next state and reward accurate | parts of the world are random and say nothing about the task |
| DREAM (Liu et al.) | collecting data that identifies the task | task labels are missing during meta-training |
Posterior sampling is Thompson sampling from the bandit literature. It is the hero's middle lane: it opens doors and never reads the sign.
DREAM measures a try by the information it gives about the task. Call H(z) the uncertainty about the task before the try, in bits, and H(z | D) the uncertainty left after seeing the data D:
I of z and D equals H of z minus H of z given D.
Count the bits of doubt about the task before the try. Count the bits left after it, on average. The drop is what the try taught about the task.
8 equal doors: H(z) = log2 8 = 3 bits. Reading the sign leaves 0 bits: 3 bits learned. Opening a door leaves 0 bits 1 time in 8, and log2 7 = 2.81 bits 7 times in 8. That is 2.46 on average, so a door teaches 0.54 bits. The lamp teaches 0.
A lamp now flashes a random pattern. Each row scores the three first moves the way one explorer does; the ringed move is its pick. Right: how often a door opened afterwards is right. Add lamp patterns.
Illustrative toy. Each explorer gets one try; then an executor opens one door using what that try showed. Scores: reward now (end-to-end, early in training), chance of being the sampled task's move (posterior sampling), bits of surprise (prediction), bits about the task (DREAM).
The failure. Set the lamp to 16 patterns. The prediction explorer watches the lamp: 4 bits of surprise, 0 bits about the prize. The executor then guesses, right 1 time in 8. The symptom is an explorer that keeps visiting random parts of the world. Measure information about the task, not prediction error. The fix is DREAM's: predict only what identifies the task.
Chapter 9
Use a meta-learned explorer to test hundreds of programs written for one assignment
A large intro course gets hundreds of programs for one game assignment, such as Breakout. To grade one, a person plays the game and hunts for bugs: does the ball bounce off the wall, does the game end at the floor? The 2024 paper reports 8 or more minutes of play per game.
| Meta-RL part | In grading |
|---|---|
| Task family | student programs for one assignment |
| State | the game screen |
| Actions | mouse moves and key presses |
| Exploration | which behaviours to test |
| Reward | bugs found and labelled correctly |
Each program is a new task from the same family. Bugs repeat across students, so an explorer trained on many programs learns where bugs hide and tests there first.
Six behaviours, with how often each was buggy in the training programs. The blue tester spends tests on the likeliest; the yellow one picks at random. Change the budget.
Illustrative bug rates, made up; bugs are independent. A program has 1.05 bugs on average.
With 2 tests, the meta-learned tester expects 0.30 + 0.25 = 0.55 bugs, 52% of the 1.05 a program has. The random tester expects 2/6 × 1.05 = 0.35, 33%.
Liu et al. (NeurIPS 2022) trained such an explorer on Code.org's Bounce assignment. Liu et al. (SIGCSE 2024) deployed an autograder for Breakout at Stanford. In an A/B test against manual grading it cut grading time by 44% and raised accuracy by about 6%.
The failure. A new assignment has new bug rates, so the learned priorities are wrong. Measure bugs found per test on a few hand-graded programs. The fix is to meta-train on programs of the new assignment.
Chapter 10
Keep the terms, the numbers, a checklist and the core code on one page
Meta-RL trains on a family of tasks so that a new task from the family takes a few tries. Black-box learners adapt in their memory. MAML adapts by gradient steps from a learned start. Inference methods keep a belief over tasks. The hard part is exploration: a good exploring move pays later, and only if the agent can use what it found.
| Term | One line |
|---|---|
| Task family p(T) | tasks that share states and actions; the dynamics, reward or start differ |
| Context Dtrain | the agent's own tries on this task; it replaces the task label |
| Black-box update | ht = fθ(ht−1, ot, at−1, rt−1, dt−1); memory kept across episodes |
| Meta-objective | J(θ) = ET[Σt γt rt] over all episodes of a task |
| MAML inner step | θ′i = θ + α∇Ji(θ) |
| MAML outer step | θ ← θ + β∇(1/N)ΣiJi(θ′i) |
| Belief update | bt+1(z) ∝ p(rt, st+1 | st, at, z) bt(z) |
| PEARL posterior | a product of one Gaussian per transition |
| Reading pays when | γq > (1 + 2γ)/8 in the two-try hallway |
| DREAM's signal | I(z; D) = H(z) − H(z | D): bits about the task only |
| What | Number | Why it matters |
|---|---|---|
| Tries on a new hallway | 23 scratch, 4.5 posterior sampling, 2 meta-learned | the payoff of learning to learn |
| Break-even | 2,800 ÷ 21 = 133 tasks | meta-training is an up-front cost |
| Forward transfer from door 3 | 86 tries | one source task can hurt |
| GRU, 19 inputs, 256 units | 212,736 weights | the size of a small RL² memory |
| Meta-training the 5-weight agent | median 1,392 tasks | it first avoids the sign: the coupling dip |
| MAML toy | 0.14 before, 1.00 after one step | a start judged after adaptation |
| Faded sign, 70% right | belief 0.70 on the named door | Bayes: multiply, then divide by the total |
| Reading threshold, gamma 0.9 | q > 0.39 | why end-to-end training gets stuck |
| Bits per first try | sign 3, door 0.54, lamp 0 | explore for the task, not for noise |
| Breakout autograder (2024) | 44% less grading time, about 6% more accurate | meta-RL outside robotics |
A black-box rollout keeps one hidden state for the whole task. MAML takes an inner step per task and scores the adapted weights.
pythonimport torch def blackbox_rollout(cell, head, env, task, n_episodes): # one task, several episodes, ONE memory h = torch.zeros(1, cell.hidden_size) # reset only here: a new task a_prev, r_prev, done = no_action(), 0.0, 0.0 logps, rewards = [], [] for ep in range(n_episodes): o, ended = env.reset(task), False # the task stays the same while not ended: x = torch.cat([o, a_prev, torch.tensor([r_prev, done])]) # [19] in the hallway h = cell(x[None], h) # h_t = f(h_t-1, o, a, r, d) dist = torch.distributions.Categorical(logits=head(h)) a = dist.sample() o, r, ended = env.step(a) logps.append(dist.log_prob(a)); rewards.append(r) a_prev, r_prev, done = one_hot(a), r, float(ended) return logps, rewards # one long trajectory per task def maml_outer_loss(theta, tasks, alpha, task_return): # task_return(params, task): a differentiable estimate of J_i (e.g. a surrogate loss) total = 0.0 for task in tasks: J = task_return(theta, task) g = torch.autograd.grad(J, theta, create_graph=True)[0] # keep the graph: slope of a slope theta_i = theta + alpha * g # inner step total = total + task_return(theta_i, task) # score AFTER adapting return -total / len(tasks) # minimise; outer step with beta
Now press Present or Teach and explain, from memory, why the meta-learner reads the sign and why that is hard to learn. Then go back to the hero, switch on The sign lies, and say which learner wins and why.
This lesson re-teaches the meta-reinforcement learning lecture of Stanford CS 224R: Deep Reinforcement Learning. The toys and numbers here are our own. The papers behind it: