A random trip reaches the far corner about once in 2,500 tries, so a plain learner sees no reward at all. Relabel each failed trip with the place it did reach, and the same agent finds the corner within a few dozen trips.
Learn how one policy serves many tasks, how the goal becomes an input, and how hindsight turns every failure into training data.
Press Play with Plain replay and watch the trips miss. Then pick Hindsight and play again. Then we build it piece by piece, from the task as an input to tasks that fight.
You need a little Python, what a probability is, and the idea of a Q-value (the value of an action in a state). We build the rest from zero.
Re-taught from the multi-task and goal-conditioned RL lecture of Stanford CS 224R: Deep Reinforcement Learning. The explanations, toys and numbers here are our own; every toy number is illustrative.
Illustrative toy. A 9 by 9 grid, start at the bottom left, goal at the top right, 16 steps apart. Each trip has 24 steps; the agent moves at random 20% of the time. A purely random trip reaches the goal with chance 0.0004 (exact, by dynamic programming). The agent indexes its value table by the offset to the goal, so what it learns about one goal carries to the others. Hindsight uses the future strategy with 4 relabelled goals per step.
Chapter 0
Count what it costs to train one specialist per task, and see when one shared policy is cheaper
A robot arm learns to reach one point on a table. It takes 500,000 steps. Now you ask for 100 different points. Trained one at a time, that is 50 million steps. Yet almost everything the arm learned, how its joints move and how far each command carries it, is the same for every point.
A task is one job with its own reward, such as "reach point 17". A specialist is a policy trained for one task. A multi-task policy is one policy that takes the task as an input and does any of them. It learns the shared part once.
How much does sharing save? Count the tasks, K. Count the steps one specialist needs, N. Call the share of knowledge that every task has in common f, from 0 to 1. Tasks get in each other's way while they share a network, so say the shared part costs c times N, with c above 1.
C-gen equals c times N, plus K times one minus f, times N.
Pay c times N once for the shared part. Then pay the unshared part, 1 minus f times N, once per task. Compare the total with K times N for K specialists.
With made-up numbers: K = 100, N = 500,000, f = 0.8, c = 3. C-gen = 1.5 million + 100 × 0.2 × 500,000 = 11.5 million steps, against 50 million for specialists. The generalist is 4.3 times cheaper.
Set C-gen below K times N and divide by N: the generalist wins when f is above c/K. With 100 tasks and c = 3, any shared share above 3% pays.
Grey is K specialists. Blue is one generalist: it learns the solid part once and the light part once per task. Move both sliders.
An illustrative cost model with N = 500,000 and c = 3. Real savings depend on how alike the tasks are.
The failure. Sharing can hurt. If two tasks need opposite things from the same weights, training one undoes the other. This is negative transfer. The symptom is a generalist that does worse on some task than its specialist. To measure it, train specialists on a few sample tasks and compare per task. Chapter 9 gives the fixes.
Chapter 1
Feed the task to the network beside the state, and score the policy by a weighted average over tasks
The same arm now has three jobs: reach left, reach right, reach up. The joints, the motors and the physics stay the same. Only the reward changes. A set of problems like this is a task family.
| Part of the problem | Across the family |
|---|---|
| States and actions | Usually the same: one robot |
| Dynamics | Usually the same: one physics |
| Reward | Different: this is what defines the task |
The policy must know which job it is doing. Give it a task identifier z: a vector that names the task. The simplest is one-hot: [0, 1, 0] means task 2.
The policy is now πθ(a | s, z), read "pi-theta of a given s and z". The network takes the state and z side by side. Seven joint angles plus a 3-number z make a 10-number input. The weights θ are the same for every task.
How do we score one policy on many tasks? Call the average return on task i Ji. Give each task a weight wi, and make the weights add to 1.
J-M-T of theta equals the sum over i of w-i times J-i of theta.
Run the policy on each task and average its return, J-i. Multiply each J-i by its weight w-i. Add them up.
With made-up returns 0.9, 0.5 and 0.2 and uniform weights of 1/3: J-MT = 0.533. Weights 0.25, 0.25 and 0.5 give 0.225 + 0.125 + 0.1 = 0.45.
The weights decide where the gradient goes. A task with weight 0.5 earns twice as much objective per unit of return as a task with weight 0.25.
Teal bars are each task's return. Purple pieces are weight times return, stacked into J-MT. Slide the weight on the hard task C.
Illustrative returns. Tasks A and B split the rest of the weight equally.
The failure. The average can hide a dead task. J-MT rises while task C stays at 0.2, because the easy tasks carry the score. To measure it, log every J-i, not only the average. The fix is to raise w-C or to sample task C more often.
Chapter 2
Use the place to reach as the task vector, and let the reward check whether the agent got there
A one-hot vector names 100 tasks. It cannot name task 101, and it says nothing about which tasks are alike. Point 17 and point 18 may be 1 cm apart, but their one-hot vectors share nothing.
So let the task vector be the goal itself. A goal g is the state you want to reach, such as the target (x, y) of the gripper. A goal-conditioned policy π(a | s, g) takes the state and the goal and acts to reach the goal. It is a multi-task policy with z = g. Nearby goals are nearby inputs, so the policy can handle a goal it never trained on.
| Goal type | Example | How the reward checks it |
|---|---|---|
| Target state | gripper at (0.3, 0.7) | distance below a tolerance |
| Image | a photo of the done table | distance between image features |
| Words | "pick up the red cup" | a learned success detector |
For a target state, the reward asks one question after each step: is the agent close enough? Call the state after the step s′ (s-prime). Call the tolerance ε (epsilon).
r of s-prime and g equals one if the distance from s-prime to g is less than epsilon, and zero otherwise.
Measure the distance from s-prime to g. If it is under epsilon, the reward is 1. If not, it is 0.
The agent lands at s′ = (0.5, 0.8) while chasing g = (1.0, 1.0). The distance is √(0.25 + 0.04) = 0.54. That is more than ε = 0.1, so r = 0.
A dense reward such as minus the distance, here −0.54, gives a signal on every step. It also pulls the agent straight at the goal, even into a wall. The sparse reward above makes no such assumption, but it is rarely 1. Chapter 4 counts how rarely.
Tap the square to move the teal goal. The blue dot is where the agent landed. Then switch to task numbers and tap somewhere new.
Illustrative. The arrows show an ideal goal-conditioned policy. The task-number policy knows three goals only.
The failure. A tolerance that is too tight means no trip ever scores; one that is too loose rewards sloppy arrivals. To measure it, plot the success rate at several values of epsilon. Pick epsilon from the job: a peg in a hole needs millimetres.
Chapter 3
Carry the goal through the Bellman backup, and watch value spread outward from the goal one step per sweep
Q-learning asks: how good is action a in state s? With a goal, the answer depends on where you are going. Turning left is good for a goal on the left and bad for one on the right. So the value takes the goal as a third input.
Call Q(s, a, g) the expected discounted return from state s, after action a, while chasing goal g. Call the reward of the step r, the next state s′, and the discount γ (gamma), a number below 1 that shrinks rewards that come later. The goal-conditioned Bellman equation links one step to the next.
Q of s, a and g equals r of s, a and g, plus gamma times the max over a-prime of Q of s-prime, a-prime and g.
Take the reward of the step. Add gamma times the best value you can get from the next state, s-prime. The goal g stays the same on both sides.
With γ = 0.95 and reward 1 on arrival: a cell next to the goal has Q = 1. A cell 2 steps away has 0 + 0.95 × 1 = 0.95. A cell 3 steps away has 0.95 × 0.95 = 0.9025. In general, d steps away gives γ to the power d − 1.
Purple is V(s, g), the best Q in each cell. Press One backup and watch value spread one step. Tap a cell to move the goal.
Illustrative grid with four wall cells. Value follows the path around the wall, not the straight line.
Look at the cells behind the wall. Their value counts the steps around it. A dense reward of minus the straight-line distance would pull the agent into the wall.
The failure. With γ = 0.5, a cell 10 steps out holds 0.5 to the 9, about 0.002. A neural network cannot tell that from 0, so far cells have no direction. To measure it, plot V against distance. The fix is a γ near 0.98.
Chapter 4
Count how rarely a random trip lands on the goal, and see why Q-learning then learns nothing
An untrained arm moves at random. Its workspace is a 1 m cube. The goal is a ball of radius 2 cm. What is the chance that a trip ends inside that ball?
Say a random trip ends at a uniform random point in the workspace. Then the chance is the goal's volume over the workspace volume. Call the tolerance ε and the workspace volume Vws.
p equals four thirds pi epsilon cubed, divided by V-w-s.
Work out the volume of the goal ball from epsilon. Divide by the workspace volume V-ws. That share is p, the chance per trip.
(4/3) × 3.1416 × 0.02 cubed = 0.0000335 m³. Over 1 m³, p = 0.0000335, about 1 trip in 29,800. With 100 trips per batch, that is about 300 batches before the first reward.
The cube in ε is the trap. Each extra dimension multiplies p by another factor near ε. A 7-joint arm has a state far bigger than 3 numbers.
Blue lines are random trips from the centre. Teal is the goal. Press Run 50 trips a few times, then shrink the goal.
Illustrative 2-D toy: each trip ends at a uniform random point, so the chance per trip is π times the radius squared.
Now see what Q-learning does with no reward. Every Q starts at 0. For every step, r = 0 and the best next Q is 0, so the target is 0 + γ × 0 = 0. Q stays 0. The policy needs value to find the goal, and value needs someone to find the goal first.
The failure. The symptom is a loss near 0, Q-values all 0, and success at 0 for millions of steps. To measure it, count the reward-1 transitions in the replay buffer. If the count is 0, nothing can learn. The fix is the next chapter.
Chapter 5
Store each failed trip a second time, with a goal it did reach, and count the rewards that creates
You aimed at (1, 1) and ended at (0.5, 0.8). The reward was 0 on every step. Now ask another question: if the goal had been (0.5, 0.8), was this trip a success? Yes. The trip is a perfect example of how to reach (0.5, 0.8).
This is hindsight experience replay, or HER (Andrychowicz et al., 2017). Every trip succeeds at something. Store it once with the goal you asked for, and again with goals it reached.
Why is this allowed? The move from s-t to s-t+1 happened, whatever goal you had in mind. The reward is a rule you wrote, so you can apply it to any goal later. And Q-learning is off-policy: it learns from any recorded step, whatever policy chose the action.
| Strategy | Relabelled goal g′ for step t |
|---|---|
| final | the last state, s-T |
| future | a random state after t; the HER paper found this worked best |
| episode | a random state from anywhere in the trip |
How many copies earn reward 1? Take step t. A future goal is one of the T − t states after it, picked at random. This step reaches only s-t+1, so the chance is 1/(T − t). Call the expected count of reward-1 copies n̄.
n-bar equals k times the sum, over t from zero to T minus one, of one over T minus t.
For each step t, the chance of reward 1 is one over the number of states left, T minus t. Add those chances over the trip. Multiply by k copies.
T = 50, k = 4: the sum is 1/50 + 1/49 + … + 1/1 = 4.50, so n̄ = 18.0. The buffer holds 50 + 200 = 250 copies, so 7.2% carry reward 1. The final strategy gives only 4, or 1.6%.
Before HER, that share was 0. The other copies still teach, because each one names a goal the trip did reach, and value flows back to them by bootstrapping (Chapter 6).
The trip missed the teal goal. Each row is one step; each chip is a relabelled goal s-j. Green chips earn reward 1. Change the strategy and k.
Illustrative: a trip of 8 steps that never revisits a cell, and reward 1 only for an exact match.
The failure. Feed relabelled data to an on-policy learner, such as plain policy gradients, and the update is wrong. Those methods need actions that the policy chose for the goal in the label. The symptom is a policy that gets worse as you add relabelled data. The fix is an off-policy learner, as in Q-learning or off-policy actor-critic.
Chapter 6
Run the Q-learning update on one failed trip, first with its real goal and then with the relabelled one
A gripper starts at s-0 = (0, 0) and aims for g = (1, 1). It moves to s-1 = (0.3, 0.1), then s-2 = (0.5, 0.4), then s-3 = (0.5, 0.8). The tolerance is 0.1. It ends 0.54 from the goal: a failure.
Q-learning nudges each Q toward its target, the reward plus γ times the best next Q. The learning rate α (alpha) sets the size of the nudge.
Q of s, a and g becomes itself plus alpha times a bracket. The bracket is r plus gamma times the max over a-prime of Q of s-prime, a-prime and g, minus the old Q.
Work out the target. Subtract the old Q to get the error. Add alpha times the error to Q.
Relabel with g′ = s-3 = (0.5, 0.8). Step s-2 to s-3 reaches g′: r = 1, target 1, Q = 0 + 0.1 × 1 = 0.1. Step s-1 to s-2 ends 0.4 away: r = 0, target 0.98 × 0.1 = 0.098, Q = 0.0098.
With the real goal, every reward is 0 and every Q is 0, so every target is 0. Nothing moves. With g′, the last step learns first and the step before learns from it.
Purple bars are Q for the three steps. Dashed lines are where they settle. Press Replay the trip several times, then switch goals.
The numbers follow the worked example: α = 0.1, γ = 0.98, tolerance 0.1.
Replay the newest step first and one sweep reaches the whole trip: 0.1, 0.0098, 0.00096. Oldest first, the first sweep moves only the last step. After many sweeps Q settles at 1, 0.98 and 0.9604, which is γ to the power of the steps left minus one.
The failure. Forget to stop at the goal and the target at s-3 becomes 1 + 0.98 × Q of the next state. Q then climbs past 1. To measure it, watch the largest Q in the batch. The fix is a "done" flag that drops the bootstrap term once the agent reaches the goal.
Chapter 7
Replace the table with a network that takes the goal as input, and ask it about goals it never saw
A gripper goal is two real numbers. There are infinitely many goals, so a table with one row per goal cannot exist. We need a function that takes the goal as an input and answers for any goal.
A universal value function approximator, or UVFA (Schaul et al., 2015), is a neural network Qθ(s, a, g). One network serves every goal. It learns from the goals it saw and interpolates: it gives sensible values for goals between them.
| Stage | Input | Output shape |
|---|---|---|
| State encoder φ | s: 7 joint angles + 7 speeds | [14] to [64] |
| Goal encoder ψ | g: a target (x, y, z) | [3] to [64] |
| Head (MLP) | φ(s), ψ(g) and the action a, side by side | [64 + 64 + 7] to [1], the Q-value |
Why two encoders? The state and the goal live in different spaces with different sizes. Each encoder maps its input to 64 numbers, and the head learns how the two relate. Both train end to end from the Q-learning loss.
Gold dots are training goals. The teal ring is your test goal. Purple is the value map each model gives for it. Tap to move the test goal; slide the training count.
Illustrative. The true value is 0.9 to the power of 40 times the distance to the goal. The smooth model blends the maps of nearby training goals with Gaussian weights; it stands in for a network.
With 12 training goals the smooth model's map is close to the truth for a new goal. With 3 it is blurry. The table knows nothing unless the goal is one of its rows. Put it with HER and the pipeline is complete:
HER supplies reward-1 examples. The UVFA spreads them to the goals in between. A 0.1 step of goal space between training goals is easy; a goal far outside them is a guess.
The failure. Ask for a goal outside the training range and the network extrapolates, often badly. The symptom is success that falls with distance from the nearest training goal. Measure it by binning test goals by that distance. The fix is to sample training goals that cover the space.
Chapter 8
Give the policy an instruction instead of a target state, and see what that costs for hindsight
"Sort the blocks by colour." Which state vector is that? There are many sorted arrangements, and no single target point. Some goals are easier to say than to place.
A language-conditioned policy π(a | s, l) takes an instruction l, such as "pick up the red cup". A pretrained language encoder turns l into a vector, and the policy reads that vector where a goal-conditioned policy reads g. The encoder is often frozen; only the state encoder and the head train.
The encoder puts instructions with the same meaning close together. The cosine similarity of two vectors measures that closeness: 1 for the same direction, 0 for unrelated. With made-up 2-number vectors (0.9, 0.3) and (0.8, 0.5): the dot product is 0.87, the lengths are 0.949 and 0.943, so the cosine is 0.97. The policy acts almost alike on both.
Each dot is an instruction. Pick one and see its two nearest neighbours by cosine. Then caption a failed trip.
Illustrative 2-D map. Real instruction vectors have hundreds of numbers.
| Goal space | New goals it can express | Hindsight relabel |
|---|---|---|
| One-hot task ID | none | not possible |
| Target state | any nearby point | free: use a reached state |
| Image | any scene you can photograph | free: use a later frame |
| Words | new combinations of known words | needs a captioner |
Hindsight with words needs a captioner: a model that writes an instruction for where the trip ended. For a trip that stopped by the drawer it writes "move the arm to the drawer". That caption becomes the relabelled goal.
Vision-language-action models such as RT-2, Octo and OpenVLA take a camera image and an instruction and output actions. They condition on the goal in the same way. Most of their training is imitation of human demonstrations, not RL.
The failure. A captioner that writes "picked up the cup" for a trip that missed the cup teaches the policy a wrong link. To measure it, check a random sample of captions by hand. The fix is to keep only captions the captioner is confident about.
Chapter 9
See how two task gradients can cancel or harm each other, and project away the conflict with PCGrad
Two tasks share one network. Task A's gradient says "turn this weight up". Task B's says "turn it down, hard". Add them and task A gets worse. This is gradient conflict.
Call task A's gradient gA and task B's gB: the directions in weight space that raise each task's return fastest. They conflict when their dot product is negative, so they point more than 90 degrees apart. PCGrad (Yu et al., 2020) removes from gA the part that points against gB.
g-A-prime equals g-A minus the fraction g-A dot g-B over the squared length of g-B, times g-B.
If g-A dot g-B is negative, find how much of g-A lies along g-B. Subtract that part. What is left of g-A is at right angles to g-B.
With made-up gradients g-A = (1, 0) and g-B = (−2, 1): the dot product is −2 and the squared length is 5. So g-A′ = (1, 0) − (−0.4)(−2, 1) = (0.2, 0.4). Check: (0.2, 0.4) · (−2, 1) = 0.
Why does it help? To first order, a step changes task A's return by g-A dot the step. The plain sum (−1, 1) changes task A by −1: worse. With PCGrad on both, g-B′ = (0, 1) and the step is (0.2, 1.4). Task A changes by +0.2 and task B by +1.0. Both improve.
Yellow is task A, pink is task B. The dashed arrow is the plain sum. Turn the angle past 90 degrees and lengthen B, then switch on PCGrad.
Illustrative 2-D gradients; real ones have millions of entries. The change in each task is the first-order estimate, the gradient dot the step.
| Problem | Symptom | Fix |
|---|---|---|
| Gradient conflict | training stalls; one task falls | PCGrad |
| Task imbalance | easy tasks done, hard ones stuck | reweight or resample tasks; GradNorm (Chen et al., 2018) |
| Forgetting | old tasks decay when new ones train | replay old data; EWC (Kirkpatrick et al., 2017) |
| Negative transfer | worse than the specialist | group related tasks; a head per task |
The failure, measured. Log the cosine between each pair of task gradients during training. A pair that stays below 0 is fighting. If one task also falls, project its gradients or split it into its own group.
Chapter 10
Keep the terms, the numbers, a checklist and the core code on one page
One policy takes the task as an input and learns what tasks share once. Make the task the goal, and nearby goals help each other. A sparse goal reward almost never fires, so relabel each trip with goals it reached and learn off-policy. A network over goals spreads that data to new goals. Watch for tasks whose gradients fight.
| Term | Meaning |
|---|---|
| Task identifier z | the input that names the task, such as one-hot [0, 1, 0] |
| Goal-conditioned policy | π(a | s, g): a multi-task policy whose task input is the goal |
| Q(s, a, g) | the value of action a in state s while chasing goal g |
| HER | store each trip again with goals it reached, and recompute the reward |
| UVFA | one network for Q over all goals |
| PCGrad | remove the part of one task's gradient that points against another's |
| What | Number | Why it matters |
|---|---|---|
| 100 tasks, 80% shared, c = 3 | 11.5 M vs 50 M steps | Sharing wins when f > c/K |
| Returns 0.9, 0.5, 0.2, weights 1/3 | J-MT = 0.533 | The weights steer the gradient |
| Value 3 steps out, γ = 0.95 | 0.9025 | Value is γ to the power d − 1 |
| 2 cm ball in a 1 m cube | 1 trip in 29,800 | Sparse rewards almost never fire |
| Hero grid, random trip | 1 in 2,500 | The plain learner sees no reward |
| HER future, T = 50, k = 4 | 18 of 250 copies, 7.2% | Reward 1 goes from none to some |
| Hand example, one sweep | 0.1, 0.0098, 0.00096 | Value flows back by bootstrapping |
| PCGrad, (1, 0) against (−2, 1) | task A: −1 to +0.2 | Projection turns harm into help |
pythonimport numpy as np def reward(s_next, g, eps=0.1): # sparse goal reward return float(np.linalg.norm(s_next - g) < eps) def her_relabel(states, actions, goal, k=4, rng=np.random): # states: [T+1, state_dim], actions: [T, act_dim], goal: [goal_dim] T, out = len(actions), [] for t in range(T): s, a, s2 = states[t], actions[t], states[t + 1] out.append((s, a, s2, goal, reward(s2, goal))) # the goal we asked for for _ in range(k): # "future" strategy g2 = states[rng.randint(t + 1, T + 1)] # a state reached later out.append((s, a, s2, g2, reward(s2, g2))) return out # T * (1 + k) transitions def td_target(q_target, r, s2, g, gamma=0.98): done = r > 0 # reaching the goal ends the trip return r + (0.0 if done else gamma * q_target(s2, g).max()) # q_target returns [n_actions]
Now press Present or Teach and explain hindsight from memory: the sparse reward, the relabel, the expected count of rewards, and the hand-worked Q-values. Then go back to the hero, run both learners, and say why one curve stays flat.
This lesson re-teaches the multi-task and goal-conditioned RL lecture of Stanford CS 224R: Deep Reinforcement Learning. The papers behind it: Schaul, Horgan, Gregor and Silver (2015), universal value function approximators; Andrychowicz et al. (2017), hindsight experience replay; Yu et al. (2020), gradient surgery for multi-task learning (PCGrad). The toys and numbers here are our own.