Simple Algorithm
Reinforcement Learning · Fixed Point · 26 min

Goal-Conditioned RL & Hindsight Relabeling

Universal value functions, HER, and learning many tasks at once.

One value function for every goal, and every failure a success for some other goal: these two ideas make goal-conditioned RL one of the most data-efficient corners of deep RL. They also hide a geometry and a trap. Optimal goal-reaching values define a distance that obeys the triangle inequality but not symmetry, and hindsight relabeling, exact in deterministic worlds, can make a 10% gamble look like a sure thing in stochastic ones. This lesson proves both, then follows the field's turn to supervised and contrastive objectives.

What you’ll learn

  • Formulate goal-conditioned RL, prove that optimal goal-reaching values define a quasimetric, and explain how quasimetric value learning exploits it.
  • Prove that hindsight relabeling gives correct Q-learning targets when the goal does not depend on the outcome, in particular in deterministic environments, and compute its bias in a stochastic example where it reverses the greedy choice.
  • State the GCSL lower bound, and explain why goal- and return-conditioned imitation copy lucky outcomes in stochastic environments.
  • Show that the discounted future-state distribution is a goal-conditioned Q-function, and derive what a contrastive critic learns.

Goal-reaching values and their geometry

With reward 1 on arrival and the episode ending there, the optimal value of reaching gg is V⋆(s,g)=max⁡πE[γTg−1]V^\star(s,g)=\max_\pi\E\big[\gamma^{T_g-1}\big], where TgT_g is the arrival time (and γ∞=0\gamma^\infty=0). It is convenient to drop the constant offset and work with Vˉ(s,g)=max⁡πE[γTg]=γV⋆(s,g)\bar V(s,g)=\max_\pi\E[\gamma^{T_g}]=\gamma V^\star(s,g) for s≠gs\ne g, with Vˉ(g,g)=1\bar V(g,g)=1, and the induced distance d(s,g)=log⁡Vˉ(s,g)/log⁡γ≥0d(s,g)=\log\bar V(s,g)/\log\gamma\ge0. In a deterministic world, Vˉ(s,g)=γ(shortest path length)\bar V(s,g)=\gamma^{\text{(shortest path length)}} and dd is the number of steps.

DerivationOptimal goal-reaching values define a quasimetric
  1. Vˉ(s,g) ≥ E[γTw+Tg′]=E[γTw] E[γTg′]=Vˉ(s,w) Vˉ(w,g)\bar V(s,g)\ \ge\ \E\big[\gamma^{T_w+T'_g}\big]=\E\big[\gamma^{T_w}\big]\,\E\big[\gamma^{T'_g}\big]=\bar V(s,w)\,\bar V(w,g)

    Fix s,w,gs,w,g. Run an optimal policy for reaching ww; on arrival switch to an optimal policy for reaching gg. Because the dynamics are Markov, the time from ww to gg is independent of how ww was reached, and arriving at gg earlier only helps:

  2. d(s,g) ≤ d(s,w)+d(w,g)d(s,g)\ \le\ d(s,w)+d(w,g)

    Take log⁡\log and divide by log⁡γ<0\log\gamma<0, which reverses the inequality. With d(s,s)=0d(s,s)=0, this is the triangle inequality:

  3. d(s,g) ≤ ∑i=0n−1d(si,si+1) ≤ nfor any path s=s0→s1→⋯→sn=gd(s,g)\ \le\ \sum_{i=0}^{n-1}d(s_i,s_{i+1})\ \le\ n\quad\text{for any path }s=s_0\to s_1\to\dots\to s_n=g

    Symmetry fails in general: rolling down a hill is quicker than climbing it, and a one-way door makes d(s,g)d(s,g) finite and d(g,s)d(g,s) infinite. A function with d(s,s)=0d(s,s)=0 and the triangle inequality but no symmetry is a quasimetric. Among all quasimetrics with d(s,s′)≤1d(s,s')\le1 for every one-step transition, the shortest-path distance is the largest, since the triangle inequality bounds any of them by the length of every path:

This geometry is a strong inductive bias. Quasimetric RL (QRL; Wang, Torralba, Isola & Zhang, 2023) parameterizes dθd_{\boldsymbol\theta} with an architecture that is a quasimetric by construction, then maximizes E[dθ(s,g)]\E[d_{\boldsymbol\theta}(s,g)] over random pairs subject to dθ(s,s′)≤1d_{\boldsymbol\theta}(s,s')\le1 on observed transitions; by the argument above, the optimum in a deterministic environment is the shortest-path distance. A network that must obey the triangle inequality cannot represent many wrong value functions, and it generalizes across goals accordingly. The same reachability function reappears in side-effect penalties (Goal Misgeneralization & Side Effects).

Predict before you look

In a deterministic world with γ=0.9\gamma=0.9, Vˉ(s,w)=0.81\bar V(s,w)=0.81 and Vˉ(w,g)=0.729\bar V(w,g)=0.729. What lower bound does the triangle inequality give for Vˉ(s,g)\bar V(s,g)?

Show the answer

0.59

Vˉ(s,g)≥0.81×0.729=0.59049=0.95\bar V(s,g)\ge0.81\times0.729=0.59049=0.9^5: ww is 2 steps from ss and gg is 3 steps from ww, so gg is at most 5 steps from ss. A shorter route that bypasses ww would only raise the value.

Why relabeling is valid, and when it is not

Hindsight relabeling trains on tuples (s,a,s′,g)(s,a,s',g) drawn from a replay distribution ρ\rho in which gg may have been chosen after the fact. Whether that is legitimate depends on one question: does the way gg was chosen depend on s′s'?

DerivationThe bias of relabeled targets, by Bayes’ rule
  1. Q(s,a,g)=Eρ[rg(s′)+γmax⁡a′Q(s′,a′,g) ∣ s,a,g]Q(s,a,g)=\E_\rho\Big[r_g(s')+\gamma\max_{a'}Q(s',a',g)\ \Big|\ s,a,g\Big]

    Tabular Q-learning on data from ρ\rho converges, under the usual conditions, to the fixed point of the update averaged over the replay distribution:

  2. ρ(s′∣s,a,g)=P(s′∣s,a) ρ(g∣s,a,s′)ρ(g∣s,a)\rho(s'\mid s,a,g)=P(s'\mid s,a)\,\frac{\rho(g\mid s,a,s')}{\rho(g\mid s,a)}

    The Bellman equation needs s′∼P(⋅∣s,a)s'\sim P(\cdot\mid s,a). By Bayes' rule, the replay distribution of s′s' given (s,a,g)(s,a,g) reweights PP by how likely the relabeling procedure was to pick gg after landing in s′s':

  3. If gg is chosen without looking at s′s' (the commanded goal, or a goal drawn at random), the ratio is 1 and the fixed point is Q⋆Q^\star. If s′s' is a deterministic function of (s,a)(s,a), only one s′s' appears and the ratio is irrelevant: relabeling is unbiased in deterministic environments. Otherwise next states from which gg was later reached are overweighted, and values of risky actions are inflated.

DerivationA risky shortcut that relabeling prefers
  1. Q⋆(s,risky,g)=0.1,Q⋆(s,safe,g)=γ2=0.81Q^\star(s,\text{risky},g)=0.1,\qquad Q^\star(s,\text{safe},g)=\gamma^2=0.81

    From ss, action risky reaches gg in one step with probability 0.1 and otherwise falls into an absorbing pit; action safe reaches gg surely in three deterministic steps. Reward 1 on reaching gg, γ=0.9\gamma=0.9. The true values favor safe:

  2. Q^(s,risky,g)=0.1 (1−p) q+0.1 p(1−p) q+0.1 p\hat Q(s,\text{risky},g)=\frac{0.1\,(1-p)\,q+0.1\,p}{(1-p)\,q+0.1\,p}

    Replay each stored transition with its commanded goal with probability 1−p1-p, or with the goal achieved at the end of its episode with probability pp; commanded goals equal gg with probability qq. Tuples (s,risky,g)(s,\text{risky},g) then arise from commanded goals (weight (1−p)q(1-p)q, success rate 0.1) and from relabeling, which yields goal gg only when the step succeeded (weight 0.1p0.1p, always a success):

  3. Q^(s,risky,g)=0.0002+0.080.002+0.08≈0.98 > 0.81\hat Q(s,\text{risky},g)=\frac{0.0002+0.08}{0.002+0.08}\approx0.98\ >\ 0.81

    The safe path is deterministic, so its estimate is unbiased, Q^(s,safe,g)=0.81\hat Q(s,\text{safe},g)=0.81. With HER's typical four relabeled replays per original one, p=0.8p=0.8, and many possible goals, say q=0.01q=0.01, the risky action looks almost certain to succeed, and the greedy policy takes the 10% gamble:

Predict before you look

Redo the estimate with fewer possible goals: p=0.8p=0.8 and q=0.1q=0.1. What value does relabeled Q-learning assign to the risky action?

Show the answer

0.82

Q^=0.1⋅0.2⋅0.1+0.1⋅0.80.2⋅0.1+0.08=0.002+0.080.02+0.08=0.0820.1=0.82\hat Q=\frac{0.1\cdot0.2\cdot0.1+0.1\cdot0.8}{0.2\cdot0.1+0.08}=\frac{0.002+0.08}{0.02+0.08}=\frac{0.082}{0.1}=0.82. Still above the safe action's 0.81, and far above the true 0.1. The bias shrinks as qq grows, because commanded goals, which are chosen independently of the outcome, then make up more of the data.

USHER (Schramm, Deng, Granados & Boularias, 2023) corrects the bias with importance weights built from learned estimates of the goal-selection densities, the ratio in the Bayes formula above, keeping relabeling's sample efficiency. The authors report HER taking a short, risky path in a discrete task and running a red light in a driving task, while USHER did neither, at roughly 2.5 times the network evaluations per update. Deterministic benchmarks, such as the robotic tasks HER was introduced on, never exposed the problem.

Supervised goal reaching, and imitating luck

Goal-conditioned supervised learning (GCSL; Ghosh, Gupta, Reddy, Fu, Devin, Eysenbach & Levine, 2021) drops value functions altogether. Any trajectory demonstrates how to reach the states it visited, so each tuple (st,at,g=st+h,h)(s_t,a_t,g=s_{t+h},h) is a labeled example, and the policy π(a∣s,g,h)\pi(a\mid s,g,h) is fit by maximum likelihood. The fitted policy then collects data for commanded goals, the data are relabeled, and the fit repeats. The objective is the probability of being at the goal at the final step, J(π)=Eg[Pr⁡πg(ST=g)]J(\pi)=\E_g\big[\Pr_{\pi_g}(S_T=g)\big].

DerivationConditioning on an outcome imitates luck
  1. Pr⁡(At=a∣St=s,O)=πb(a∣s) Pr⁡(O∣s,a)∑a′πb(a′∣s) Pr⁡(O∣s,a′)\Pr(A_t=a\mid S_t=s,O)=\frac{\pi_b(a\mid s)\,\Pr(O\mid s,a)}{\sum_{a'}\pi_b(a'\mid s)\,\Pr(O\mid s,a')}

    Supervised methods that condition on an outcome OO (reaching gg, reaching it within hh steps, achieving return RR) fit the behavior policy's actions among trajectories with that outcome. With enough data they learn the conditional distribution given by Bayes' rule:

  2. Pr⁡(risky∣s, g reached at t=1)=1,whilePr⁡(g reached at t=1∣s,risky)=0.1\Pr(\text{risky}\mid s,\ g\text{ reached at }t=1)=1,\qquad\text{while}\qquad\Pr(g\text{ reached at }t=1\mid s,\text{risky})=0.1

    This chooses actions in proportion to how often they led to OO, not how reliably. If outcomes are deterministic given (s,a)(s,a), every action in the support achieves OO for sure, and imitating them is optimal. In the risky shortcut, the outcome "reach gg in one step" was produced only by the risky action, so the policy conditioned on it gambles every time:

  3. Return-conditioned sequence models are the same construction with OO = "return RR" (RL as Sequence Modeling). Paster, McIlraith & Ba (2022) showed that decision transformers and related methods fail in stochastic environments for exactly this reason, since a high return can be luck, and proposed conditioning on the average return of clusters of trajectories, which the environment's randomness affects less.

Check your understanding

A return-conditioned policy is trained on logged episodes of the risky-shortcut task in which both actions were taken often. From ss it is commanded to achieve return 1, which only successful risky steps ever produced (the safe path returns 0.810.81). What happens?

  1. It takes the safe path, which is optimal
  2. It achieves return 1 every time, since it imitates successful episodes
  3. It takes the risky step and achieves return 1 only 10% of the time, an expected return of 0.1
  4. It cannot act, since a return of exactly 1 is out of distribution
Show the answer

C. It takes the risky step and achieves return 1 only 10% of the time, an expected return of 0.1

Among logged trajectories with return 1 from ss, the first action is always risky, so the conditioned policy takes it. Its success still has probability 0.1: imitation copies the choice, not the luck. Commanding return 0.81 would have produced the safe path and a better expected return.

Contrastive critics and offline goal reaching

DerivationThe future-state density is a goal-conditioned Q-function
  1. p+π(sf∣s,a)=(1−γ)∑t≥0γt Pr⁡π(St+1=sf∣S0=s,A0=a)p^\pi_+(s_f\mid s,a)=(1-\gamma)\sum_{t\ge0}\gamma^t\,\Pr\nolimits^\pi\big(S_{t+1}=s_f\mid S_0=s,A_0=a\big)

    Define a policy's discounted future-state distribution: the distribution of the state reached after a geometrically distributed number of steps, the successor representation written as a density (Successor Representations & Features):

  2. Qπ(s,a,g)=Eπ[∑t≥0γt rg(St,At) ∣ s,a]=(1−γ)∑t≥0γtPr⁡π(St+1=g∣s,a)=p+π(g∣s,a)Q^\pi(s,a,g)=\E^\pi\Big[\sum_{t\ge0}\gamma^t\,r_g(S_t,A_t)\ \Big|\ s,a\Big]=(1-\gamma)\sum_{t\ge0}\gamma^t\Pr\nolimits^\pi(S_{t+1}=g\mid s,a)=p^\pi_+(g\mid s,a)

    Take the reward rg(st,at)=(1−γ)Pr⁡(St+1=g∣st,at)r_g(s_t,a_t)=(1-\gamma)\Pr(S_{t+1}=g\mid s_t,a_t), the scaled probability of landing on gg next. Its action value sums these probabilities along the trajectory, which is exactly the future-state density:

  3. f⋆(s,a,g)=log⁡p+π(g∣s,a)p(g)=log⁡Qπ(s,a,g)−log⁡p(g)f^\star(s,a,g)=\log\frac{p^\pi_+(g\mid s,a)}{p(g)}=\log Q^\pi(s,a,g)-\log p(g)

    Contrastive RL (Eysenbach, Zhang, Levine & Salakhutdinov, 2022) estimates it without temporal-difference learning. Positives pair (s,a)(s,a) with a future state of the same trajectory, at a geometrically distributed offset; negatives pair it with states from other trajectories, distributed as the marginal p(sf)p(s_f). A critic f(s,a,sf)=ϕ(s,a)⊤ψ(sf)f(s,a,s_f)=\boldsymbol\phi(s,a)^\top\boldsymbol\psi(s_f) trained to tell them apart (binary NCE with balanced classes) converges to the log density ratio:

  4. arg max⁡af⋆(s,a,g)=arg max⁡aQπ(s,a,g)\argmax_a f^\star(s,a,g)=\argmax_a Q^\pi(s,a,g)

    For a fixed goal the subtracted term does not depend on the action, so the critic ranks actions exactly as QπQ^\pi does and supports greedy policy improvement. Here representation learning and goal-conditioned value learning are the same problem:

Offline, goal-conditioned learning meets the distribution shift of Offline RL. OGBench (Park, Frans, Eysenbach & Levine, 2025) collects 85 datasets over 8 types of environments with reference implementations of six methods: goal-conditioned behavior cloning, implicit value and Q-learning variants, quasimetric RL, contrastive RL, and HIQL, a hierarchical method that predicts subgoals as latent states and that the authors found strong across the board. As of the mid-2020s, which family wins depends on the dataset. Stitching datasets, in which no single trajectory connects start and goal, are built to defeat pure imitation, which can only reproduce behavior that some trajectory contains.

Key takeaways

  • Optimal goal-reaching values satisfy Vˉ(s,g)≥Vˉ(s,w) Vˉ(w,g)\bar V(s,g)\ge\bar V(s,w)\,\bar V(w,g), so log⁡Vˉ/log⁡γ\log\bar V/\log\gamma is a quasimetric (path length in deterministic worlds); the shortest-path distance is the largest quasimetric consistent with one-step transitions, which quasimetric RL exploits.
  • Relabeled Q-learning is correct when the goal does not depend on the outcome, and always in deterministic environments; otherwise replay reweights next states by ρ(g∣s,a,s′)/ρ(g∣s,a)\rho(g\mid s,a,s')/\rho(g\mid s,a), and a 10% gamble can be valued at 0.98.
  • GCSL fits relabeled actions by maximum likelihood and maximizes a lower bound J≥JGCSL−4T(T−1)α2+CJ\ge J_{\text{GCSL}}-4T(T-1)\alpha^2+C; conditioning on outcomes, whether goals or returns, imitates luck when outcomes are random.
  • The discounted future-state density p+π(g∣s,a)p^\pi_+(g\mid s,a) is a goal-conditioned Q-function, and a contrastive critic learns its log-ratio to p(g)p(g), which is all greedy improvement needs.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why is d(s,g)=log⁡Vˉ(s,g)/log⁡γd(s,g)=\log\bar V(s,g)/\log\gamma a quasimetric but generally not a metric?

  1. It is a metric: symmetric and satisfying the triangle inequality
  2. It satisfies d(s,s)=0d(s,s)=0 and the triangle inequality, but reaching gg from ss can be much easier than the reverse, so it need not be symmetric
  3. It violates the triangle inequality in stochastic environments
  4. It is undefined whenever some goal is unreachable
Show the answer

B. It satisfies d(s,s)=0d(s,s)=0 and the triangle inequality, but reaching gg from ss can be much easier than the reverse, so it need not be symmetric

Concatenating an optimal policy to ww with one from ww to gg gives Vˉ(s,g)≥Vˉ(s,w)Vˉ(w,g)\bar V(s,g)\ge\bar V(s,w)\bar V(w,g), stochastic environments included, by the Markov property. Asymmetry comes from the dynamics: one-way doors, slopes, irreversible actions.

Question 2

When is relabeling with goals achieved later in the episode guaranteed to give correct Q-learning targets?

  1. When k=4k=4 relabeled goals are used per transition
  2. When the goal space equals the state space
  3. When the behavior policy is greedy
  4. When transitions are deterministic
Show the answer

D. When transitions are deterministic

The replay distribution of s′s' given (s,a,g)(s,a,g) is P(s′∣s,a)P(s'\mid s,a) times ρ(g∣s,a,s′)/ρ(g∣s,a)\rho(g\mid s,a,s')/\rho(g\mid s,a). With deterministic transitions only one s′s' is possible, so the reweighting cannot change anything; with stochastic ones it overweights outcomes from which gg was later reached.

Question 3

GCSL's guarantee J(π)≥JGCSL(π)−4T(T−1)α2+CJ(\pi)\ge J_{\text{GCSL}}(\pi)-4T(T-1)\alpha^2+C is tightest when what holds?

  1. The new policy stays close to the one that collected the data, ideally α=0\alpha=0
  2. The horizon TT is long
  3. The environment is stochastic
  4. Goals are relabeled at random rather than with achieved states
Show the answer

A. The new policy stays close to the one that collected the data, ideally α=0\alpha=0

The penalty 4T(T−1)α24T(T-1)\alpha^2 vanishes for on-policy data and grows quadratically with both the horizon and the policy change, which is why GCSL iterates: collect with the current policy, relabel, refit.

Question 4

What does the optimal binary-NCE contrastive critic f(s,a,g)f(s,a,g) represent, with positives drawn from the same trajectory's future and negatives from other trajectories?

  1. The probability of reaching gg on the next step
  2. The shortest-path distance from ss to gg
  3. log⁡p+π(g∣s,a)−log⁡p(g)\log p^\pi_+(g\mid s,a)-\log p(g): a goal-conditioned Q-value up to a goal-dependent term that leaves the greedy action unchanged
  4. The reward function of the task
Show the answer

C. log⁡p+π(g∣s,a)−log⁡p(g)\log p^\pi_+(g\mid s,a)-\log p(g): a goal-conditioned Q-value up to a goal-dependent term that leaves the greedy action unchanged

Telling joint samples from products of marginals has the log density ratio as its optimal logit, and the future-state density is the Q-function of the reward (1−γ)Pr⁡(St+1=g∣s,a)(1-\gamma)\Pr(S_{t+1}=g\mid s,a). The goal-only term cancels when actions are compared.

Further reading

  • T. Schaul, D. Horgan, K. Gregor & D. Silver, "Universal value function approximators," ICML (2015).
  • M. Andrychowicz, F. Wolski, A. Ray, J. Schneider, R. Fong, P. Welinder, B. McGrew, J. Tobin, P. Abbeel & W. Zaremba, "Hindsight experience replay," NeurIPS (2017).
  • D. Ghosh, A. Gupta, A. Reddy, J. Fu, C. Devin, B. Eysenbach & S. Levine, "Learning to reach goals via iterated supervised learning," ICLR (2021).
  • B. Eysenbach, T. Zhang, S. Levine & R. Salakhutdinov, "Contrastive learning as goal-conditioned reinforcement learning," NeurIPS (2022).
  • L. Schramm, Y. Deng, E. Granados & A. Boularias, "USHER: Unbiased sampling for hindsight experience replay," Conference on Robot Learning, PMLR 205 (2023).