Meta-Reinforcement Learning

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.

Race three learners on a new task

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

Learning to Learn

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.

Find where meta-training pays off

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.

60

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.

The road

  1. Three ways to reuse experience: what each approach gets at test time.
  2. The meta-RL problem: tasks, the family, and the train and test split.
  3. Black-box meta-RL: a network whose memory does the learning.
  4. Meta-training the learner: the hero's meta-learner, trained in the page.
  5. MAML: learn a start from which one gradient step solves the task.
  6. Task inference: a belief over tasks, and PEARL.
  7. The exploration problem: why reading the sign is hard to learn.
  8. Exploration strategies: the hero's posterior sampler, and DREAM.
  9. Finding bugs in student games: meta-RL as an autograder.
  10. The field guide: terms, numbers, code and links.
When does meta-training pay for itself?

Chapter 1

Three Ways to Reuse Experience

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.

Compare where each learner starts

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.

ApproachAt test time it getsTries on door 6
From scratchnothing; it learns by trial23
Forward transferweights from one source task86
Multi-taskthe task label z1
Meta-learningonly its own tries2

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.

At test time a policy gets the goal position as an input and acts at once. Which approach is it?

Chapter 2

The Meta-RL Problem

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.

FamilyWhat differs between tasks
Mazesthe walls: the dynamics
Walking robotsthe slope (dynamics) or the goal direction (reward)
Robot armswhich object, which goal place
Our hallwaywhich door pays: the reward

A task distribution, p(T), says how likely each task is. The two phases use it differently:

PhaseTasksWhat changesWhat we measure
Meta-trainingmany, drawn from p(T)the weightsthe training objective
Meta-testingnew ones, held out, same p(T)memory, or a few fast stepsthe 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.

Score one test task two ways

Each tile is one try. Grey tiles are not scored. Pick a variant and a strategy, then change the number of free tries.

1

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.

In meta-RL, what plays the part that the task label z plays in multi-task RL?

Chapter 3

Black-Box Meta-RL

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:

  1. The reward is an input. The network sees the last reward, so it can learn from rewards in its forward pass, with no gradient step.
  2. The memory persists across episodes. It resets only when a new task starts, not when an episode ends.

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:

Say it aloud

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.

ht
h-t the hidden state after step t: a vector of, say, 256 numbers that holds the memory.
fθ
f-theta the recurrent cell, for example a GRU, with weights theta. Meta-training tunes theta.
ht−1
h-t-minus-1 the memory one step earlier, carried across episode ends.
ot
o-t what the agent observes now: in the hallway, the sign's reading or nothing.
at−1
a-t-minus-1 the action the agent took last.
rt−1
r-t-minus-1 the reward that action earned: the input that lets the network learn.
dt−1
d-t-minus-1 1 if an episode just ended, else 0.
In plain words

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.

With numbers

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.

Step the memory through three tries

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.

MethodMemoryOuter RL methodTrade-off
RL² (Duan et al.; Wang et al.)GRU or LSTM hidden stateTRPO or A3C, on-policysimple; needs many tasks
SNAIL (Mishra et al.)temporal convolutions + attentionTRPO, on-policyreaches far back; cost grows with the square of the length
PEARL (Rakelly et al.)a latent task vector zSAC, off-policyreuses 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.

Why does a black-box meta-learner take the last reward as an input?

Chapter 4

Meta-Training the Learner

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.

  1. Draw a task from the family p(T).
  2. Run the agent for all N episodes of that task. Keep the memory across them.
  3. Add up the rewards of the whole run.
  4. Update the weights θ with an ordinary RL method: a policy gradient, PPO or SAC.
  5. Repeat with a new task.

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.

Say it aloud

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.

J(θ)
J of theta the meta-objective: what the weights theta earn on an average task.
ET ~ p(T)
the expected value over T drawn from p of T the average over many tasks from the family.
Σt
the sum over t one term per step, across all the episodes of one task.
γt
gamma to the t the discount, here 0.9, multiplied by itself t times.
rt
r-t the reward at step t.
In plain words

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.

With numbers

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:

Meta-train the hero's agent

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.

A hallway task has 2 tries and gamma 0.9. Why does the meta-objective prefer reading the sign, which pays 0?

Chapter 5

MAML: Learn Where to Start

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:

Say it aloud

Theta-prime-i equals theta plus alpha times nabla-theta of J-i of theta.

θ′i
theta-prime-i the weights after one inner step on task i.
θ
theta the shared start, the same for every task. Meta-training learns it.
α
alpha the inner step size; 7.4 in the toy.
∇θ
nabla-theta the gradient: the direction that raises the reward fastest, and how steep it is.
Ji(θ)
J-i of theta task i's expected reward at theta, from 0 to 1.
In plain words

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.

With numbers

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 β:

Say it aloud

Theta becomes theta plus beta times nabla-theta of one over N times the sum over i of J-i of theta-prime-i.

θ ←
theta becomes replace the start with a better one.
β
beta the outer step size; 0.5 in the toy.
∇θ
nabla-theta the gradient with respect to the start, passed back through each inner step.
(1/N) Σi
one over N times the sum over i the average over the N tasks of the batch; N = 2 here.
Ji(θ′i)
J-i of theta-prime-i task i's reward after adaptation, not before.
In plain words

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.

With numbers

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.

Find the start that learns fastest

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.

2.00
7.4

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-boxMAML
What adaptsthe hidden statethe weights, by gradient steps
Test-time costone forward pass per stepepisodes for each gradient step
Task a little outside the familymay fail with no way backkeeps improving with more steps
What does MAML's outer loop score?

Chapter 6

Meta-RL as Task Inference

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:

Say it aloud

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.

bt+1(z)
b-t-plus-1 of z the new belief that the task is z.
∝
is proportional to equal after dividing by the total, so the beliefs add to 1.
p(rt, st+1 | st, at, z)
p of r-t and s-t-plus-1 given s-t, a-t and z the likelihood: how probable the reward and next state are if task z is true.
bt(z)
b-t of z the old belief in task z.
In plain words

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 numbers

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.

Update a belief over the prize door

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:

  1. An encoder reads each transition (s, a, r, s′) on its own and outputs a Gaussian guess about z.
  2. The guesses multiply into one Gaussian, q(z | Dtrain).
  3. The agent samples z from it and runs a policy π(a | s, z).
  4. SAC trains the policy off-policy, reusing old data from a replay buffer.

Call transition n's guess a bell curve N(z; μn, σn2) with mean μn and variance σn2:

Say it aloud

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.

q(z | Dtrain)
q of z given D-train PEARL's belief about the task vector z, given the context.
Πn
the product over n multiply one factor per transition in the context.
N(z; μn, σn2)
N of z with mean mu-n and variance sigma-n squared transition n's bell curve: its best guess and how unsure it is.
In plain words

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 numbers

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.

Eight doors start at 0.125 each. You open door 2 and it is empty. What is the belief in door 5 now?

Chapter 7

The Exploration Problem

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:

Say it aloud

Gamma times q is greater than one plus two gamma, over eight.

γ
gamma the discount on try 2's reward, from 0 to 1.
q
q the chance that try 2 opens the door the sign named, from 0 to 1.
(1 + 2γ) / 8
one plus two gamma, over eight the guesser's value: a 1-in-8 hit now, then a second chance worth 2 in 8.
In plain words

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 numbers

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.

Find when reading the sign pays

Purple: the value of reading the sign. Yellow: the value of guessing. The ruler marks the line q must pass. Drag q, then gamma.

0.125
0.90

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.

Gamma is 0.9. Above which skill q is reading the sign worth more than guessing?

Chapter 8

Exploration Strategies

Compare explorers by how much each try teaches about the task

Each fix for the coupling problem picks a different signal to explore by:

StrategyExplores byBreaks when
End-to-endtotal rewardthe coupling trap of Chapter 7
Posterior sampling (PEARL)sample a task z, act as if it is truethe useful move is in no task's solution, like the sign
Prediction (MetaCURE, Zhang et al.)making a model of next state and reward accurateparts of the world are random and say nothing about the task
DREAM (Liu et al.)collecting data that identifies the tasktask 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:

Say it aloud

I of z and D equals H of z minus H of z given D.

I(z; D)
I of z and D the mutual information: the bits about the task z that the data D gives.
H(z)
H of z the entropy of the task: how unsure you are before the try, in bits.
H(z | D)
H of z given D how unsure you are after the try, averaged over what it could show.
In plain words

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.

With numbers

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.

Distract the explorers with a lamp

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.

4

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.

With 8 equally likely doors, how many bits about the task does opening one door give?

Chapter 9

Finding Bugs in Student Games

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 partIn grading
Task familystudent programs for one assignment
Statethe game screen
Actionsmouse moves and key presses
Explorationwhich behaviours to test
Rewardbugs 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.

Spend a test budget on one program

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.

2

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.

Why is grading student games a meta-RL problem?

Chapter 10

The Field Guide

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.

Terms and equations

TermOne line
Task family p(T)tasks that share states and actions; the dynamics, reward or start differ
Context Dtrainthe agent's own tries on this task; it replaces the task label
Black-box updateht = fθ(ht−1, ot, at−1, rt−1, dt−1); memory kept across episodes
Meta-objectiveJ(θ) = ET[Σt γt rt] over all episodes of a task
MAML inner stepθ′i = θ + α∇Ji(θ)
MAML outer stepθ ← θ + β∇(1/N)ΣiJi(θ′i)
Belief updatebt+1(z) ∝ p(rt, st+1 | st, at, z) bt(z)
PEARL posteriora product of one Gaussian per transition
Reading pays whenγq > (1 + 2γ)/8 in the two-try hallway
DREAM's signalI(z; D) = H(z) − H(z | D): bits about the task only

The numbers from this page

WhatNumberWhy it matters
Tries on a new hallway23 scratch, 4.5 posterior sampling, 2 meta-learnedthe payoff of learning to learn
Break-even2,800 ÷ 21 = 133 tasksmeta-training is an up-front cost
Forward transfer from door 386 triesone source task can hurt
GRU, 19 inputs, 256 units212,736 weightsthe size of a small RL² memory
Meta-training the 5-weight agentmedian 1,392 tasksit first avoids the sign: the coupling dip
MAML toy0.14 before, 1.00 after one stepa start judged after adaptation
Faded sign, 70% rightbelief 0.70 on the named doorBayes: multiply, then divide by the total
Reading threshold, gamma 0.9q > 0.39why end-to-end training gets stuck
Bits per first trysign 3, door 0.54, lamp 0explore for the task, not for noise
Breakout autograder (2024)44% less grading time, about 6% more accuratemeta-RL outside robotics

Before you trust a meta-RL run

The core, in code

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

Keep going

The takeaway. Meta-RL turns many slow tasks into one fast learner. Judge it on new tasks from the same family, keep its memory for the whole task, and check that it learned to explore, not only to exploit.
Your black-box meta-learner scores the same in episode 1 and episode 3 of each test task. What is the first thing to check?

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.

Credit and source

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:

CS 224R: Meta-Reinforcement Learning
The course site · MAML · PEARL · Back to Gleams