Multi-Task and Goal-Conditioned RL

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.

Reach the far corner

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

One Policy for Many Tasks

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.

Say it aloud

C-gen equals c times N, plus K times one minus f, times N.

Cgen
C-gen the total steps to train one generalist for all tasks.
c
c the interference factor: how much more the shared part costs because tasks compete. Here 3.
N
N the steps one specialist needs, here 500,000.
K
K the number of tasks.
f
f the shared share of the knowledge, from 0 to 1. So 1 minus f is the part each task must learn alone.
In plain words

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 numbers

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.

Price specialists against one generalist

Grey is K specialists. Blue is one generalist: it learns the solid part once and the light part once per task. Move both sliders.

100
80%

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.

The road

  1. The task as an input: one network, a task vector, and the average over tasks.
  2. The goal as the task: the place to reach becomes the input, and the reward checks it.
  3. Goal-conditioned values: the Bellman backup with the goal carried along.
  4. Why sparse rewards starve learning: the hero's plain learner, explained.
  5. Hindsight relabelling: the hero's second button, and how many rewards it creates.
  6. Hindsight by hand: three Q-values, step by step.
  7. One network for every goal: universal value functions and goals never seen.
  8. Goals in words: instructions as goals, and the robots that use them.
  9. When tasks fight: gradient conflict and PCGrad.
  10. The field guide: terms, numbers, code and links.
There are 10 tasks, each needing N steps alone. They share 80% of their knowledge, and interference makes the shared part cost 3N. What does one generalist cost?

Chapter 1

The Task as an Input

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 problemAcross the family
States and actionsUsually the same: one robot
DynamicsUsually the same: one physics
RewardDifferent: 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.

Say it aloud

J-M-T of theta equals the sum over i of w-i times J-i of theta.

JMT(θ)
J-M-T of theta the multi-task objective: one score for the shared weights θ.
Σi
the sum over i one term for each task, from 1 to K.
wi
w-i the weight of task i. Uniform weights are 1/K each.
Ji(θ)
J-i of theta the average return of the policy on task i, with z set to task i.
In plain words

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 numbers

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.

Weigh the three tasks

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.

0.33

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.

Tasks A, B and C have returns 0.8, 0.6 and 0.1 and weights 0.5, 0.25 and 0.25. What is J-MT?

Chapter 2

The Goal as the Task

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 typeExampleHow the reward checks it
Target stategripper at (0.3, 0.7)distance below a tolerance
Imagea photo of the done tabledistance 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).

Say it aloud

r of s-prime and g equals one if the distance from s-prime to g is less than epsilon, and zero otherwise.

r(s′, g)
r of s-prime and g the reward for landing in state s′ while chasing goal g.
1[ · ]
one if 1 when the test inside the brackets is true, 0 when it is false.
‖s′ − g‖
the distance from s-prime to g the straight-line distance between where the agent is and where it should be.
ε
epsilon the tolerance: how close counts as reached, here 0.1.
In plain words

Measure the distance from s-prime to g. If it is under epsilon, the reward is 1. If not, it is 0.

With numbers

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.

Place a goal anywhere

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.

0.10

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.

Why can a goal-conditioned policy handle a goal it never trained on, when a one-hot policy cannot?

Chapter 3

Goal-Conditioned Values

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.

Say it aloud

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.

Q(s, a, g)
Q of s, a and g the value of taking action a in state s while chasing goal g.
r(s, a, g)
r of s, a and g the reward of this one step: 1 if it reaches g, else 0.
γ
gamma the discount, here 0.95. Each step of delay multiplies value by it.
maxa′
the max over a-prime the best action in the next state: the largest of its Q-values.
Q(s′, a′, g)
Q of s-prime, a-prime and g the value one step later, with the same goal g.
In plain words

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 numbers

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.

Back up value from the goal

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.

0.95

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.

Reward is 1 on reaching the goal and the episode ends. With γ = 0.9, what is V for a cell 3 steps from the goal?

Chapter 4

Why Sparse Rewards Starve Learning

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.

Say it aloud

p equals four thirds pi epsilon cubed, divided by V-w-s.

p
p the chance that one random trip ends inside the goal.
(4/3) π ε3
four thirds pi epsilon cubed the volume of a ball of radius ε, the goal region. ε is 0.02 m.
Vws
V-w-s the volume of the workspace, here 1 cubic metre.
In plain words

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.

With numbers

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

Count the lucky trips

Blue lines are random trips from the centre. Teal is the goal. Press Run 50 trips a few times, then shrink the goal.

0.05

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.

A goal disk of radius 0.05 sits in a 1 by 1 square, and trips end at uniform random points. About how many trips per hit?

Chapter 5

Hindsight Relabelling

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.

  1. Pick a goal g and run a trip of T steps: s-0, a-0, s-1, …, s-T.
  2. Store each step as (s-t, a-t, s-t+1, g) with its reward.
  3. For each step, pick k more goals g′ from states the trip reached. Recompute the reward for each g′ and store those copies too.
  4. Train Q(s, a, g) on batches drawn from all of them.

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.

StrategyRelabelled goal g′ for step t
finalthe last state, s-T
futurea random state after t; the HER paper found this worked best
episodea 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̄.

Say it aloud

n-bar equals k times the sum, over t from zero to T minus one, of one over T minus t.

n̄
n-bar the expected number of relabelled copies with reward 1, per trip.
k
k relabelled goals per step, here 4.
Σt=0T−1
the sum over t from zero to T minus one one term for each step of the trip. T is the trip length, here 50.
1/(T − t)
one over T minus t the chance that a future goal for step t is the next state.
In plain words

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.

With numbers

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

Relabel one failed trip

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.

4

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.

With the future strategy, T = 50 and k = 4, about what share of the stored copies have reward 1?

Chapter 6

Hindsight by Hand

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.

Say it aloud

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.

Q(s, a, g) ←
Q of s, a and g becomes replace the stored value with the right-hand side.
α
alpha the learning rate, here 0.1: move one tenth of the way to the target.
r + γ maxa′ Q(s′, a′, g)
the target the step's reward plus gamma, here 0.98, times the best value in the next state. At the goal the trip ends, so the target is r alone.
In plain words

Work out the target. Subtract the old Q to get the error. Add alpha times the error to Q.

With numbers

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.

Replay the trip and watch Q fill in

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.

After the first relabelled update, Q(s-2, a-2, g′) = 0.1. What does the next update give Q(s-1, a-1, g′), with α = 0.1 and γ = 0.98?

Chapter 7

One Network for Every Goal

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.

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

Ask about a goal it never saw

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.

12

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:

  1. Sample a goal g. Run a trip with the greedy action of Qθ(s, a, g), plus some random moves.
  2. Store the trip with g and with k hindsight goals.
  3. Sample a batch (s, a, r, s′, g). Compute the target y = r + γ max over a′ of Q(s′, a′, g), read from a slowly updated copy of the network.
  4. Step θ to shrink (Qθ(s, a, g) − y) squared. Repeat.

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.

Why does a UVFA use separate encoders for the state and the goal?

Chapter 8

Goals in Words

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.

Find an instruction's neighbours

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 spaceNew goals it can expressHindsight relabel
One-hot task IDnonenot possible
Target stateany nearby pointfree: use a reached state
Imageany scene you can photographfree: use a later frame
Wordsnew combinations of known wordsneeds 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.

Why is hindsight relabelling harder for language goals than for target states?

Chapter 9

When Tasks Fight

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.

Say it aloud

g-A-prime equals g-A minus the fraction g-A dot g-B over the squared length of g-B, times g-B.

gA′
g-A-prime task A's gradient with the conflict taken out.
gA
g-A task A's raw gradient.
gA · gB
g-A dot g-B the dot product: multiply matching entries and add. Negative means conflict.
‖gB‖2
the squared length of g-B g-B dot itself.
gB
g-B task B's gradient. PCGrad does the same to it, with A and B swapped.
In plain words

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 numbers

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.

Turn two gradients against each other

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.

153°
2.25

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.

ProblemSymptomFix
Gradient conflicttraining stalls; one task fallsPCGrad
Task imbalanceeasy tasks done, hard ones stuckreweight or resample tasks; GradNorm (Chen et al., 2018)
Forgettingold tasks decay when new ones trainreplay old data; EWC (Kirkpatrick et al., 2017)
Negative transferworse than the specialistgroup 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.

g-A = (1, 0) and g-B = (0, 1). What does PCGrad do to g-A?

Chapter 10

The Field Guide

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.

Terms

TermMeaning
Task identifier zthe 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
HERstore each trip again with goals it reached, and recompute the reward
UVFAone network for Q over all goals
PCGradremove the part of one task's gradient that points against another's

The numbers from this page

WhatNumberWhy it matters
100 tasks, 80% shared, c = 311.5 M vs 50 M stepsSharing wins when f > c/K
Returns 0.9, 0.5, 0.2, weights 1/3J-MT = 0.533The weights steer the gradient
Value 3 steps out, γ = 0.950.9025Value is γ to the power d − 1
2 cm ball in a 1 m cube1 trip in 29,800Sparse rewards almost never fire
Hero grid, random trip1 in 2,500The plain learner sees no reward
HER future, T = 50, k = 418 of 250 copies, 7.2%Reward 1 goes from none to some
Hand example, one sweep0.1, 0.0098, 0.00096Value flows back by bootstrapping
PCGrad, (1, 0) against (−2, 1)task A: −1 to +0.2Projection turns harm into help

Before you trust a goal-conditioned run

The core: relabel, then update

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]

Keep going

The takeaway. Make the task an input, and every trip becomes data for some task. A trip that missed its goal reached a different one, and an off-policy learner can use it.
Which learner can train on hindsight-relabelled data without a correction?

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.

Credit and source

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.

CS 224R: Multi-Task and Goal-Conditioned RL
The course site · HER · PCGrad · Back to Gleams