Contrastive Learning as Goal-Conditioned Reinforcement Learning
Abstract
In reinforcement learning (RL), it is easier to solve a task if given a good representation.
While deep RL should automatically acquire such good representations, prior work often finds that learning representations in an end-to-end fashion is unstable and instead equip RL algorithms with additional representation learning parts (e.g., auxiliary losses, data augmentation).
How can we design RL algorithms that directly acquire good representations?
In this paper, instead of adding representation learning parts to an existing RL algorithm, we show (contrastive) representation learning methods can be cast as RL algorithms in their own right.
To do this, we build upon prior work and apply contrastive representation learning to action-labeled trajectories, in such a way that the (inner product of) learned representations exactly corresponds to a goal-conditioned value function.
We use this idea to reinterpret a prior RL method as performing contrastive learning, and then use the idea to propose a much simpler method that achieves similar performance.
Across a range of goal-conditioned RL tasks, we demonstrate that contrastive RL methods achieve higher success rates than prior non-contrastive methods, including in the offline RL setting.
We also show that contrastive RL outperforms prior methods on image-based tasks, without using data augmentation or auxiliary objectives.
Introduction
Representation learning is an integral part of reinforcement learning (RL 2 ) algorithms.
While such representations might emerge from end-to-end training [7, 79, 119, 126], prior work has found it necessary to equip RL algorithms with perception-specific loss functions [32, 44, 71, 89, 91, 101, 116, 140] or data augmentations [69, 73, 116, 118], effectively decoupling the representation learning problem from the reinforcement learning problem.
Given what prior work has shown about RL in the presence of function approximation and state aliasing [2, 135, 138] it is not surprising that end-to-end learning of representations is fragile [69, 73]: an algorithm needs good representations to drive the learning of the RL algorithm, but the RL algorithm needs to drive the learning of good representations.
So, can we design RL algorithms that do learn good representations without the need for auxiliary perception losses?
Rather than using a reinforcement learning algorithm also to solve a representation learning problem, we will use a representation learning algorithm to also solve certain types of reinforcement learning problems, namely goal-conditioned RL.
Goal-conditioned RL is widely studied [6, 15, 22, 62, 80, 120], and intriguing from a representation learning perspective because it can be done in an entirely self-supervised manner, without manually-specified reward functions.
We will focus on contrastive (representation) learning methods, using observations from the same trajectory (as done goal encoder,
[Figure]
, future state, random state, : "Is this a future state or random state?"
in prior work [95, 109]) while also including actions as an additional input (See Fig. 1).
Intuitively, contrastive learning then resembles a goal-conditioned value function: nearby states have similar representations and unreachable states have different representations.
We make this connection precise, showing that sampling positive pairs using the discounted state occupancy measure results in learning representations whose inner product exactly corresponds to a value function.
In this paper, we show how contrastive representation learning can be used to perform goalconditioned RL.
We formally relate the learned representations to reward maximization, showing that the inner product between representations corresponds to a value function.
This framework of contrastive RL generalizes prior methods, such as C-learning [29], and suggests new goal-conditioned
RL algorithms.
One new method achieves performance similar to prior methods but is simpler; another method consistently outperforms the prior methods.
On goal-conditioned RL tasks with image observations, contrastive RL methods outperform prior methods that employ data augmentation and auxiliary objectives, and do so without data augmentation or auxiliary objectives.
In the offline setting, contrastive RL can outperform prior methods on benchmark goal-reaching tasks, sometimes by a wide margin.
Related Work
This paper will draw a connection between RL and contrastive representation learning, building upon a long line of contrastive learning methods in NLP and computer vision, and deep metric learning [17, 53, 54, 54, 56, 77, 84, 86, 87, 94, 95, 108, 109, 113, 122, 129, 132].
Contrastive learning methods learn representations such that similar (“positive”) examples have similar representations and dissimilar (“negative”) examples have dissimilar representations.
3 While most methods generate the “positive” examples via data augmentation, some methods generate similar examples using different camera viewpoints of the same scene [109, 122], or by sampling examples that occur close in time within time series data [4, 95, 109, 118].
Our analysis will focus on this latter strategy, as the dependence on time will allow us to draw a precise relationship with the time dependence in RL.
Deep RL algorithms promise to automatically learn good representations, in an end-to-end fashion.
However, prior work has found it challenging to uphold this promise [7, 79, 119, 126], prompting many prior methods to employ separate objectives for representation learning and RL [32, 44, 71, 89, 91, 100, 101, 116, 118, 140, 143].
Many prior methods choose a representation learning objectives that reconstruct the input state [32, 47, 49, 50, 71, 91, 93, 141] while others use contrastive representation learning methods [89, 95, 111, 116, 118].
Unlike these prior methods, we will not use a separate representation learning objective, but instead use the same objective for both representation learning and reinforcement learning.
Some prior RL methods have also used contrastive learning to acquire reward functions [14, 20, 33, 38, 63, 67, 92, 133, 134, 146], often in imitation learning settings [37, 55].
In contrast, we will use contrastive learning to directly acquire a value function, which (unlike a reward function) can be used directly to take actions, without any additional RL.
This paper will focus on goal-conditioned RL problems, a problem prior work has approached using temporal difference learning [6, 29, 62, 80, 103, 106], conditional imitation learning [22, 41, 83, 105, 120], model-based methods [23, 107], hierarchical RL [90], and planning-based methods [30, 93, 105, 115].
The problems of automatically sampling goals and exploration [24, 35, 85, 98, 144] are orthogonal to this work.
Like prior work, we will parametrize the value function as an inner product between learned representations [34, 58, 106].
Unlike these prior methods, we will learn a value function directly via contrastive learning, without using reward functions or TD learning.
Our analysis will be most similar to prior methods [11, 15, 29, 103] that view goal-conditioned RL as a data-driven problem, rather than as a reward-maximization problem.
Many of these methods employ hindsight relabeling [6, 26, 62, 78], wherein experience is relabeled with an outcome that occurred in the future.
Whereas hindsight relabeling is typically viewed as a trick to add on top of an RL algorithm, this paper can roughly be interpreted as showing that the hindsight relabeling is a standalone RL algorithm.
Many goal-conditioned methods learn a value function that captures the similarity between two states [29, 62, 91, 125].
Such distance functions are structurally similar to the critic function learned for contrastive learning, a connection we make precisely in Sec. 4.
In fact, our analysis shows that C-learning [29] is already performing contrastive learning, and our experiments show that alternative contrastive RL methods can be much simpler and achieve higher performance.
Prior work has studied how representations related to reward functions using the framework of universal value functions [12, 106] and successor features [9, 52, 81].
While these methods typically require additional supervision to drive representation learning (manually-specified reward functions or features), our method is more similar to prior work that estimates the discounted state occupancy measure as an inner product between learned representations [11, 131].
While these methods use temporal difference learning, ours is akin to Monte Carlo learning.
While Monte Carlo learning is often (but not always [23]) perceived as less sampling efficient, our experiments find that our approach can be as sample efficient as TD methods.
Other prior work has focused on learning representations that can be used for planning [59, 82, 104, 105, 128].
Our method will learn representations using an objective similar to prior work [105, 109], but makes the key observation that the representation already encodes a value function: no additional planning or RL is necessary to choose actions.
Please see Appendix A for a discussion of how our work relates to unsupervised skill learning.
Preliminaries
Goal-conditioned reinforcement learning.
The goal-conditioned RL problem is defined by states s t ∈ S , actions a t , an initial state distribution p 0 ( s ) , the dynamics p ( s t +1 | s t , a t ) , a distribution over goals p g ( s g ) , and a reward function r g ( s, a ) for each goal.
This problem is equivalent to a multi-task RL [5, 45, 121, 130, 139], where tasks correspond to reaching goals states.
Following prior work [11, 15, 29, 103], we define the reward as the probability (density) of reaching the goal at the next time step:[-
-]
[Equation]
This reward function is appealing because it avoids the need for a human user to specify a distance metric (unlike, e.g., [6]).
Even though our method will not estimate the reward function, we will still use the reward function for analysis.
For a goal-conditioned policy π ( a | s, s g ) , we use π ( τ | s g ) to denote the probability of sampling an infinite-length trajectory τ =
( s 0 , a 0 , s 1 , a 1 , · · · ) .
We defined the expected reward objective and Q-function as
[Equation]
Intuitively, this objective corresponds to sampling a goal s g and then optimizing the policy to go to that goal and stay there.
Finally, we define the discounted state occupancy measure as [55, 142]
[Equation] [Equation]
where p πt ( s ) is the probability density over states that policy π visits after t steps.
Sampling from the discounted state occupancy measure is easy: the first sample a time offset from a geometric distribution ( t ∼ G EOM (1 − γ ) ), and then look at what state the policy visits after exactly t steps.
We will use s t + to denote states sampled from the discounted state occupancy measure.
Because our method will combine experience collected from multiple policies, we also define the average stationary distribution as p π ( ·|· ) ( s t + = s | s, a ) ≜ (cid:82) p π ( ·|· ,s g )
( s t + = s | s, a ) p
π ( s g | s, a ) ds g , where p π ( s g | s, a ) is the probability of the commanded goal given the current state-action pair.
This stationary distribution is equivalent to that of the policy π ( a | s ) ≜ (cid:82) π ( a | s, s g )
p π ( s g | s ) ds g
Contrastive representation learning.
Contrastive representation learning methods [17, 46, 53, 54, 61, 77, 84, 86, 87, 122, 124, 129] take as input pairs of positive and negative examples, and learn representations so that positive pairs have similar representations and negative pairs have dissimilar representations.
We use ( u, v ) to denote an input pair (e.g., u is an image, and v is an augmented version of that image).
Positive examples are sampled from a joint distribution p ( u, v ) , while negative examples are sampled from the product of marginal distributions, p ( u ) p ( v ) .
We will use an objective based on binary classification [77, 86, 87, 94].
Let f ( u, v ) =
ϕ ( u ) T ψ ( v ) be the similarity between the representations of u and v .
We will call f the critic function 5 and note that its range is ( −∞ , ∞ ) .
We will use NCE-binary [84] objective (also known as InfoMAX [54]):
[Equation]
[Table]
Contrastive Learning as an RL Algorithm
This section shows how to use contrastive representation to directly perform goal-conditioned RL.
The key idea (Lemma 4.1) is that contrastive learning estimates the Q-function for a certain policy and reward function.
To prove this result, we relate the Q-function to the state occupancy measure (Sec. 4.1) and then relate the optimal critic function to the state occupancy measure (Sec. 4.2).
This result allows us to propose a new algorithm for goal-conditioned RL based on contrastive learning.
Unlike prior work, this algorithm is not adding contrastive learning on top of an existing RL algorithm.
This framework generalizes C-learning [29], offering a cogent explanation for its good performance while also suggesting new methods that are simpler and can achieve higher performance.
4.1 Relating the Q-function to probabilities
This section sets the stage for the main results of this section by providing a probabilistic perspective goal-conditioned RL.
The expected reward objective and associated Q-function in (Eq. 2) can equivalently be expressed as the probability (density) of reaching a goal in the future:
Proposition 1 (rewards → probabilities) .
The Q-function for the goal-conditioned reward function r g (Eq. 1) is equivalent to the probability of state s g under the discounted state occupancy measure:
[Equation]
The proof is in Appendix B. Translating rewards into probabilities not only makes it easier to analyze the goal-conditioned problem, but also means that any method for estimating probabilities (e.g., contrastive learning) can be turned into a method for estimating this Q-function.
4.2 Contrastive Learning Estimates a Q-Function
We will use contrastive learning to learn a value function by carefully choosing the inputs u and v .[-
-]
The first input, u , will correspond to a state-action pair, u = ( s t , a t ) ∼ p ( s, a ) .
In practice, these pairs are sampled from the replay buffer.
Including the actions in the input is important because it will allow us to determine which actions to take to reach a desired future state.
The second variable, v , is a future state, v = s f .
For the “positive” training pairs, the future state is sampled from the discounted state occupancy measure, s f ∼ p π ( ·|· ) ( s t + | s t , a t ) .
For the “negative” training pairs, we sample a future state from a random state-action pair: s f ∼ p ( s t + ) ≜ (cid:82) p π ( ·|· ) ( s t + | s, a ) p ( s, a ) dsda .
With these inputs, the contrastive learning objective (Eq. 4) can be written as
[Equation]
where L ( s, a, s + f , s − f ) ≜ log σ ( f ( s, a, s + f ) (cid:124) (cid:123)(cid:122) (cid:125)
ϕ
( s,a ) T ψ ( s + f ) )
+ log(1 − σ ( f ( s, a, s − f ) (cid:124) (cid:123)(cid:122) (cid:125) ϕ
( s
[Equation] a ) T ψ ( s − f ) )) .
Intuitively, the critic function f ( u = ( s t , a t ) , v = s f ) now tells us the correlation between the current state-action pair and future outcomes, analogous to a Q-function.
We therefore can use the critic function in the same way as actor-critic RL algorithms [66], figuring out which actions lead to the desired outcome.
Because the Bayes-optimal critic function is a function of the state occupancy measure [84], f ∗ ( s, a, s g ) = log (cid:16)
[Equation]
) (cid:17) , it can be used to express the Q-function:
Lemma 4.1.
The critic function that optimizes Eq.
6 is a Q-function for the goal-conditioned reward function (Eq. 1), up to a multiplicative constant
[Equation]
The critic function can be viewed as an unnormalized density model, where p ( s g ) is the partition function.
Much of the appeal of contrastive learning is it avoids estimating the partition function [46], which can be challenging; in the RL setting, it will turn out that this constant can be ignored when selecting actions.
Our experiments show that learning a normalized density model works well when s g is low-dimensional, but struggles to solve higher-dimensional tasks.
This lemma relates the critic function to Q π ( ·|· ) s f ( s, a ) , not Q π ( ·|· ,s f ) s f ( s, a ) .
The underlying reason is that the critic function combines together experience collected when commanding different goals.
Prior goal-conditioned behavioral cloning methods [22, 41, 83, 120] perform similar sharing, but do not analyze the relationship between the learned policies and Q functions.
Sec.
4.5 shows that this critic function can be used as the basis for a convergent RL algorithm under some assumptions.
4.3 Learning the Goal-Conditioned Policy
The learned critic function not only tells us the likelihood of future states, but also tells us how different actions change the likelihood of a state occurring in the future.
Thus, to learn a policy for reaching a goal state, we choose the actions that make that state most likely to occur in the future:
[Equation]
The approximation above reflects errors in learning the optimal critic, and will allow us to prove that this policy loss corresponds to policy improvement in Sec.
4.5, under some assumptions.
In practice, we parametrize the goal-conditioned policy as a neural network that takes as input the state and goal and outputs a distribution over actions.
The actor loss (Eq. 7) is computed by sampling states and random goals from the replay buffer, sampling actions from the policy, and then taking gradients on the policy using a reparametrization gradient.
On tasks with image observations, we add an action entropy term to the policy objective.
4.4 A Complete Goal-Conditioned RL Algorithm
The complete algorithm alternates between fitting the critic function using contrastive learning, updating the policy using Eq. 7, and collecting more data.
Alg.
1 provides a JAX [13] implementation of the actor and critic losses.
Note that the critic is parameterized as an inner product between a representation of the state-action pair, and a representation of the goal state:
f
( s, a, s g ) =
ϕ ( s, a ) T ψ ( s g ) .
This parameterization allows for efficient computation, as we can compute the goal representations just once, and use them both in the positive pairs and the negative pairs.
While this is common practice in representation learning, it is not exploited by most goal-conditioned RL algorithms.
We refer to this method as contrastive RL (NCE) .
In Appendix C, we derive a variant of this method ( contrastive RL (CPC) ) that uses the infoNCE bound on mutual information. dim) g , repr sa repr # <
sa
, g > for all i, eye
) def batch size, dim) sa_repr
= sa_ batch_dim, repr_dim) g_repr = g_encoder goals) # (batch_dim, repr_dim) logits einsum >i', sa_repr, g sa
i
, g i > Contrastive RL (NCE) is an on-policy algorithm because it only estimates the Q-function for the policy that collected the data. However, in practice, we take as many gradient steps on each transition as standard off-policy RL algorithms [40, 48].
Please see Appendix E for full implementation details.
We will also release an efficient implementation based on ACME [57] and JAX [13].
On a single
TPUv2, training proceeds at 1100 batchessec for state-based tasks and 105 batchessec for image-based tasks; for comparison, our implementation of DrQ on the same hardware setup runs at 28 batchessec ( 3 .
9 × slower).
Architectures and hyperparameters are described in Appendix E.
4.5 Convergence Guarantees
In general, providing convergence guarantees for methods that perform relabeling is challenging.
Most prior work offers no guarantees [6, 22, 23] or guarantees under only restrictive assumptions [41, 120].
To prove that contrastive RL converges, we will introduce an additional filtering step into the method, throwing away some training examples.
Precisely, we exclude training examples ( s, a, s f ) if the probability of the corresponding trajectory τ i : j
= ( s i , a i , s i +1 , a i +1 , · · · , s j , a j ) sampled from π ( τ | s g ) under the commanded goal s g is very different from the trajectory’s probability under the actually-reached goal s
[Equation]
While this modification is necessary to prove convergence, ablation experiments in Appendix Fig.show that the filtering step can actually hurt performance in practice, so we do not include this filtering step in the experiments in the main text.
We can now prove that contrastive RL performs approximate policy improvement.
Lemma 4.2 (Approximate policy improvement) .
Assume that states and actions are tabular and assume that the critic is Bayes-optimal.
Let π ′ ( a | s, s g ) be the goal-conditioned policy obtained after one iteration of contrastive RL with a filtering parameter of ϵ .
Then this policy achieves higher rewards than the initial goal-conditioned policy:
[Equation]
The proof is in Appendix B.
This result shows that performing contrastive RL on static dataset results in one step of approximate policy improvement.
Re-collecting data and then applying contrastive RL over and over again corresponds to approximate policy improvement (see [10, Lemma 6.2]).
In summary, we have shown that applying contrastive learning to a particular choice of inputs results in an RL algorithm, one that learns a Q-function and (under some assumptions) converges to the reward-maximizing policy.
Contrastive RL (NCE) is simple: it does not require multiple
Q-values [40], target Q networks [88], data augmentation [69, 73], or auxiliary objectives [116, 137].
[Figure]
4.6 C-learning as Contrastive Learning
C-learning [29] is a special case of contrastive RL: it learns a critic function to distinguish future goals from random goals.
Compared with contrastive RL (NCE), C-learning learns the classifier using temporal difference learning.
8 Viewing C-learning as a special case of contrastive RL suggests that contrastive RL algorithms might be implemented in a variety of different ways, each with relative merits.
For example, contrastive RL (NCE) is much simpler than C-learning and tends to perform a bit better.
Appendix D introduces another member of the contrastive RL family ( contrastive RL (NCE + C-learning) )
that tends to yield the best performance .
Experiments
Our experiments use goal-conditioned RL problems to compare contrastive RL algorithms to prior non-contrastive methods, including those that use data augmentation and auxiliary objectives.
We then compare different members of the contrastive RL family, and show how contrastive RL can be effectively applied to the offline RL setting.
Appendices E, F, and G contain experiments, visualizations, and failed experiments.
5.1 Comparing to prior goal-conditioned RL methods
Baselines.
We compare three baselines.
“HER” [80] is a goal-conditioned RL method that uses hindsight relabeling [6] with a high-performance actor-critic algorithm (TD3).
This baseline is representative of a large class of prior work that uses hindsight relabeling [6, 76, 102, 106].
Like contrastive RL, this baseline does not assume access to a reward function.
The second baseline is goal-conditioned behavioral cloning (“GCBC”)
[16, 22, 25, 41, 83, 96, 117, 120], which trains a policy to reach goal s g by performing behavioral cloning on trajectories that reach state s g .
GCBC is a simple method that achieves excellent results [16, 25] and has the same inputs as our method ( ( s, a, s f ) triplets).
A third baseline is a model-based approach that fits a density model to the future state distribution p π ( ·|· ) ( s t + | s, a ) and trains a goal-conditioned policy to maximize the probability of the commanded goal.
This baseline is similar to successor representations [21] and prior multi-step models [23, 60].
Both contrastive RL (Alg. 1) and this model-based approach encode the future state distribution, but the output dimension of this model-based method depends on the state dimension.
We, therefore, expect this approach to excel in low-dimensional settings but struggle with image-based tasks.
Where possible, we use the same hyperparameters for all methods. We will [Figure]
a t [Figure] fetch reach
[Figure]
sawyer push [Figure] fetch push
[Figure] 41e sawyer bin contrastive RL (NCE) [Figure] AE
TD [Figure]
CURL include additional representation learning baselines when studying representations in the subsequent section.
Tasks.
We compare it to a suite of goal-conditioned tasks, mostly taken from prior work.
Four standard manipulation tasks include fetch reach and fetch push from Plappert et al.
[97] and sawyer push and sawyer bin from Yu et al.
We evaluate these tasks both with state-based observations and (unlike most prior work) image-based observations.
The sawyer bin task poses an exploration challenge, as the agent must learn to pick up an object from one bin and place it at a goal location in another bin; the agent does not receive any reward shaping or demonstrations.
We include two navigation tasks: point Spiral11x11 is a 2D maze task with image observations and ant umaze [36] is a 111-dimensional locomotion task that presents a challenging low-level control problem.
Where possible, we use the same initial state distribution, goal distribution, observations, and definition of success as prior work.
Goals have the same dimension as the states, with one exception: on the ant umaze task, we used the global XY position as the goal.
We illustrate three of the tasks to the right.
The agent does not have access to any ground truth reward function.
We report results in Fig.
2, using five random seeds for each experiment and plotting the mean and standard deviation across those random seeds.
On the state-based tasks (Fig. 2a), most methods solve the easiest task ( fetch reach ) while only our method solves the most challenging task ( sawyer bin ).
Our method also outperforms all prior methods on the two pushing tasks.
The model-based baseline performs best on the ant umaze task, likely because learning a model is relatively easy when the goal is lower-dimensional (just the XY location).
On the image-based tasks (Fig. 2b), most methods make progress on the two easiest tasks ( fetch reach and point Spiral11x11 ); our method outperforms the baselines on the three more challenging tasks.
Of particular note is the success on sawyer push and sawyer bin : while the success rate of our method remains below 50%, no baselines make any progress on learning these tasks.
These results suggest that contrastive RL (NCE) is a competitive goal-conditioned RL algorithm.
5.2 Comparing to prior representation learning methods
We hypothesize that contrastive RL may automatically learn good representations.
To test this hypothesis, we compare contrastive RL (NCE) to techniques proposed by prior work for representation learning.
These include data augmentation [69, 73, 136] (“DrQ”) and auxiliary objectives based on an autoencoder [32, 91, 93, 137] (“AE”) and a contrastive learning objective (“CURL”) that generates positive examples using data augmentation, similar to prior work [89, 116, 118].
Because prior work has demonstrated these techniques in combination with actor-critic RL algorithms, we will use these techniques in combination with the actor-critic baseline from the previous section (“TD3 + HER”).
While contrastive RL (NCE) resembles a contrastive representation learning method, it does not include any data augmentation or auxiliary representation learning objectives.
We show results in Fig.
4, with error bars again showing the mean and standard deviation across 5 random seeds.
While adding the autoencoder improves the baseline on the fetch reach and adding DrQ improves the baseline on the sawyer push , contrastive RL (NCE) outperforms the prior methods on all tasks.
Unlike these methods, contrastive RL does not use auxiliary objectives or additional domain knowledge in the form of image-appropriate data augmentations. These experiments do not show that representation learning is never useful, and do not show that contrastive
[Figure]
sawyer
[Figure]
sawyer push
[Figure] RL cannot be improved with additional representation learning machinery.
Rather, they show that designing RL algorithms that structurally resemble contrastive representation learning yields bigger improvements than simply adding representation learning tricks on top of existing RL algorithms
5.3 Probing the dimensions of contrastive RL
Up to now, we have focused on the specific instantiation of contrastive RL spelled out in Alg. 1.
However, there is a whole family of RL algorithms with contrastive characteristics.
C-learning is a contrastive RL algorithm that uses temporal difference learning (Sec. 4.6).
Contrastive RL (CPC) is a variant of Alg.
1 based on the infoNCE objective [95] that we derive in Appendix C Contrastive
RL (NCE + C-learning) is a variant that combines C-learning with Alg.
D (see Appendix D.).
The aim of these experiments are to study whether generalizing C-learning to a family of contrastive RL algorithms was useful: do the simpler methods achieve similar performance, and do other methods achieve better performance?
We present results in Fig.
5, again plotting the mean and standard deviation across five random seeds.
Contrastive RL (CPC) outperforms contrastive RL (NCE) on three, suggesting that swapping one mutual information estimator for another can sometimes improve performance, though both estimators can be effective.
C-learning outperforms contrastive RL (NCE) on three tasks but performs worse on other tasks.
Contrastive RL (NCE + C-learning) consistently ranks among the best methods.
These experiments demonstrate that the prior contrastive RL method, C-learning [29], achieves good results on most tasks; generalizing C-learning to a family of contrastive RL algorithms resulting in new algorithms that achieve higher performance and can be much simpler. 5.4 Partial Observability and Moving Cameras [Figure] Many realistic robotics tasks exhibit partial observability, and have cameras that are not fixed but rather attached to moving robot parts.
Our next experiment tests if contrastive RL can cope with these sorts of challenges.
To study this question, we modified the sawyer push task so that the camera tracks the hand at a fixed distance, as if it were rigidly mounted to the arm. This means that, at the start of the episode, the scene is occluded by the wall at the edge of the table, so the agent cannot see the location of the puck (see Fig. 6 (left)). Nonetheless, contrastive RL (NCE) successfully handles this partial observability, achieving a success rate of around 35%. Fig.(left) shows an example rollout and Fig.
6 (right) shows the learning curve.
For comparison, the success rate when using the fixed static camera was 75%.
Taken together, these results suggest that contrastive RL can cope with moving cameras and partial observability, while also suggesting that improved strategies (e.g., non-Markovian architectures) might achieve even better results.
[Table]
5.5 Contrastive RL for Offline RL
Our final experiment studies whether the benefits from contrastive RL (NCE) transfer to the offline RL setting, where the agent is prohibited from interacting with the environment.
We use the benchmark
AntMaze tasks from the D4RL benchmark [36], as these are goal-conditioned tasks commonly studied in the offline setting.
We adapt contrastive RL (NCE) to the offline setting by adding an additional (goal-conditioned) behavioral cloning term to the policy objective (Eq. 7), using a coefficient of λ :
[Equation]
Note that setting λ = 1 corresponds to GCBC [16, 22, 25, 41, 83, 96, 117, 120], which we will include as a baseline.
Following TD3+BC [39], we learn multiple critic functions (2 and 5) and take the minimum when computing the actor update.
We also compare to prior offline RL methods that eschew
TD learning: (unconditional) behavioral cloning (BC), the implementation of GCBC from [25] (which refers to GCBC as RvS-G), and a recent method based on the transformer architecture (DT [16]).
Lastly, we compare with two more complex methods that use TD learning: TD3+BC [39] and
IQL [68].
Unlike contrastive RL and GCBC, these TD learning methods do not perform goal relabeling. We use the numbers reported for these baselines in prior work [25, 68]. As shown in Table 1, contrastive RL (NCE) outperforms all baselines on five of the six benchmark tasks. Of particular note are the most challenging “-large” tasks, where contrastive RL achieves a 7% to 9% absolute improvement over IQL.
We note that IQL does not use goal relabeling, which is the bedrock of contrastive RL. Compared to baselines that do not use TD learning, the benefits are more pronounced, with a median (absolute) improvement over GCBC of 15%. The performance of contrastive RL improves when increasing the number of critics from 2 to 5 , suggesting that the key to solving more challenging offline RL tasks may be increased capacity, rather than TD learning. Taken together, these results show the value of contrastive RL for offline goal-conditioned tasks.
In this paper, we showed how contrastive representation learning can be used for goal-conditioned RL. This connection not only lets us re-interpret a prior RL method as performing contrastive learning, but also suggests a family of contrastive RL methods, which includes simpler algorithms, as well as algorithms that attain better overall performance. While this paper might be construed to imply that RL is more or less important than representation learning [72, 75, 112, 114], we have a different takeaway: that it may be enough to build RL algorithms that look like representation learning.
One limitation of this work is that it looks only at the goal-conditioned RL problems.
How these methods might be applied to arbitrary RL problems remains an open problem, though we note that recent algorithms for this setting [28] already bear a resemblance to contrastive RL.
Whether the rich set of ideas from contrastive learning might be used to construct even better RL algorithms likewise remains an open question.
Acknowledgements. Thanks to Hubert Tsai, Martin Ma, and Simon Kornblith for discussions about contrastive learning. Thanks to Kamyar Ghasemipour, Suraj Nair, and anonymous reviewers for feedback on the paper. Thanks to Ofir Nachum, Daniel Zheng, and the JAX and Acme teams for helping to release and debug the code.
This material is supported by the Fannie and John Hertz Foundation and the NSF GRFP (DGE1745016). UC Berkeley research is also supported by gifts from Alibaba, Amazon Web Services, Ant Financial, CapitalOne, Ericsson, Facebook, Futurewei, Google, Intel, Microsoft, Nvidia, Scotiabank, Splunk and VMware. A Additional Related Work
Our work is also related to unsupervised skill discovery [1, 19, 27, 42, 52, 74, 110], in that the algorithm learns multiple policies by interacting in the environment without a reward function. Both these skill learning algorithms and our contrastive algorithm optimize a lower bound on mutual information. Indeed, prior work has discussed the close connection between mutual information and goal-conditioned RL [19, 127]. The key challenge in making this connection is grounding the skills, so that each skill corresponds to a specific goal-conditioned policy.
While the skills can be grounded by manually-specifying the critic used for maximizing mutual information [19], manually-specifying the critic for high-dimensional tasks (e.g., images) would be challenging.
Our work takes a different approach to grounding, one based on reasoning directly about continuous probabilities.
In the end, our method will learn skills that each corresponds to a specific goal-conditioned policy and will be scalable to high-dimensional tasks.
Fig.
7 highlights some of the connections between related work.
Prior work has thoroughly explained how many representation learning methods correspond to a lower bound on mutual information [84, 99].
Prior work in RL has proposed unsupervised skill learning algorithms using similar mutual information objectives [1, 27, 42], and more recent work has connected these unsupervised skills learning algorithms to goal-reaching.
The key contribution of this paper is to connect representation learning to goal-conditioned RL.
B Proofs B.1 Q-function are equivalent to the discounted state occupancy measure
This section proves Proposition 1.
We start by recalling the definition of the discounted state occupancy measure (Eq. 3):
[Equation] We first analyze the term for t = 0 , and then analyze the term for t > 0 . The probability of visiting a state at time t = 0 is just the initial state distribution: [Equation]
We can now rewrite Eq.
8 as [Equation] For t > 1 , we can write the term as follows: [Equation]
In the second line, we have used the Markov property to say that the probability of visiting s g at time t depends only on dynamics, p ( s t +1 | s t , a t ) .
In the third line, we have rewritten the expectation over trajectories, using s t − 1 and a t − 1 and the t − 1 th state-action pair in the trajectory.
Substituting this into Eq.
9, we get
[Equation]
On the second line, we have changed the bounds of the summation to start at 0, and changed the terms inside the summation accordingly.
On the third line, we applied linearity of expectation to move the summation inside the expectation.
On the fourth line, we applied linearity of expectation again to move the term for t = 0 inside the expectation. Finally, we substituted the definition of r g ( s, a ) to obtain the desired result. B.2 Contrastive RL is Policy Improvement This section proves the Contrastive RL (NCE) corresponds to policy improvement, yielding policies with higher rewards at each iteration (Lemma 4.2).
Proof.
The main idea of the proof is to relate the Q-values for the average policy to the Q-values for the goal-conditioned policy.
We do this by employing the result from [31, Appendix C.2], where ϵ is the parameter for filtered relabeling (Sec. 4.5):
[Equation]
This result means that we are doing policy improvement with approximate Q-values.
Then, [10, Lemma 6.1] tells that doing policy improvement using approximate Q-values gives us approximate policy improvement:
[Equation]
C Contrastive RL (CPC)
In this section, we derive a version of contrastive RL based on the infoNCE objective [95].
Compared with the NCE objective used in contrastive RL (NCE), this objective uses a categorical cross entropy loss instead of a binary cross entropy loss.
We replace Eq.
6 with the following infoNCE objective [95]: [Equation] where p (1) is the first coordinate of the softmax over the critic: [Equation]
The optimal critic for the infoNCE loss satisfies [84, 95, 99]
[Equation]
where c ( s, a ) is an arbitrary function.
Thus, there are many optimal critics.
Choosing actions that maximize the critic f ∗ does not necessarily correspond to choosing actions that maximize the probability of the future state.
Thus, we need to regularize c ( s, a ) so that it does not depend on a .
We do this by introducing a regularizer, based on [123]:
[Equation]
To provide some intuition for this regularizer
[Equation]
consider applying this regularizer to an optimal critic:
[Equation]
In the third line we ignore the positive term; this is reasonable if the batch size is large enough. In the third line we replaced the sum with an expectation; this is biased because log( · ) is not a linear function. Thus, this regularizer (approximately) regularizes c ( s, a ) to be close to 1 for all states and actions. By reducing the dependency of c ( s, a ) on the actions a , we can ensure that actions that maximize the critic do maximize the probability of reaching the desired goal.
In practice, we add this regularizer with the infoNCE objective, using a coefficient of 1e-2 on the regularizer. D Contrastive RL (NCE + C-learning) In this section we describe contrastive RL (NCE + C-learning) the combined NCE + C- learning method used in Sec. 5.3 (Fig. 5).
Mathematically, the NCE + C-learning objective is a simple, unweighted sum of the C-learning objective and the NCE objective: [Equation] While we could use half the batch to compute each of the loss terms, we can increase the effective sample size by being careful with how the terms are estimated. First, we note that the first two terms of each loss are similar – sample a future state (either the next state or a future state) and label it as a positive.
We can thus combine these two terms by sampling from a mixture of these two distributions, ˜ p ( s f | s t , a t ) =
[Equation] p [Equation] [Equation]
+
[Equation]
and scaling the resulting loss by 1 + 1 − γ = 2 − γ : [Equation] This trick increases the effective sample size by 96% ( 130 → 256 , as measured using [64]). Both losses also contain terms that are an expectation over random goals.
We can likewise combine those terms: [Equation] Note that estimating the first term in L 2 requires sampling an action for each next state and goal pair.
This prohibits us from using the same outer product trick as in Sec. 4.4 to estimate this term. While we could still use that trick to estimate the second term in L 2 , we found that doing so hurt performance.
We hypothesize that the reason is that this creates an imbalance in the gradients – some goals are labeled as negatives but are not also labeled as positives.
Thus, we do not use the outer product trick for this method.
The final objective is L ( f ) = L 1 ( f ) + L 2 ( f ) . E Experimental Details
We implemented contrastive RL and the baselines using the ACME RL library [57] in combination with JAX [13]. Precisely, we took the SAC agent 9 and made the modifications below.
Unless otherwise mentioned, we used the same hyperparameters as this implementation. Implemented environments that returned observations that contained the original observation concatenated with the goal.
While the goals are resampled when sampling from the replay buffer, assuming that observations include the goals means that the Q-function and policy networks do not need to include an additional input for the goal.
Modified the replay buffer to use trajectories rather than transitions. This allows us to sample ( s t , a t , s f ) triplets. Modified the critic network to be parametrized as an inner product between state-action representations and goal representations. Modified the critic loss based on Alg. 1.
Note that the actor loss does not need to be modified (except for removing the entropy term for state-based tasks).
We summarize the hyperparameters in Table 2. Both the state-action encoder and the goal encoder are fully-connected neural networks with 2 layers of size 256 with ReLU activations. We found that normalizing the final representation, applying a final activation function [Table]
or using a learnable temperature hurt performance, so we do not use these tricks. For image-based tasks, observations have size (64 , 64 , 3) [Table] and we use a CNN encoder from prior work [88] to encode the observations before passing them to the encoders.
The policy has a similar architecture: an image-encoder for image-based tasks, followed by 2 fully connected layers with size 256 and ReLU activations.
[Table] [Table] E.1 Environments
fetch reach (image, state) – This task is taken from Plappert et al. This task involves moving a robotic arm to a goal location in free space. The benchmark specifies success as reaching within 5cm of the goal.
fetch push (image, state) – This task is taken from Plappert et al. This task involves using a robotic arm to push an object across a table to a goal location. The benchmark specifies success as reaching within 5cm of the goal. sawyer push (image, state) – This task is taken from Yu et al.
This task involves using a robotic arm to push an object across table to a goal location. The benchmark specifies success as reaching within 5cm of the goal. ant umaze (state) – This task is taken from Fu et al. This task involves controlling an ant-like robot towards a goal location, which is sampled randomly in a “U”-shaped maze.
Unlike all other tasks in this paper, the goal was lower dimensional than the observation: the goal was just the XY coordinate of the desired position. Following prior work [15, 115], success is defined as reaching within 0.5m of the goal. sawyer bin (image, state) – This task is taken from Yu et al. This task involves using a robotic arm to pick up a block from one bin and place it at a goal location in another bin.
The benchmark specifies success as reaching within 5cm of the goal. point Spiral11x11 (image) – This task is an image-based version of the 2D navigation tasks in Eysenbach et al. This task involves directly controlling the XY coordinates of an agent to reach a goal in a spiral-shaped maze (see Fig. 16). We define success as reaching within 2m of the goal.
To study the learned representations in isolation we take the state-action representations ϕ ( s, a ) trained on the image-based point NineRooms task, and run a linear probe [3, 51] experiment to see whether the representations have learned to encode task-relevant information (the shortest path distance to the goal). We use the task of nine-room navigation and run Contrastive RL and TD3+HER on it. We visualize the environment in Fig.
8a and the agent randomly initialized in one of the nine rooms is commanded to go to the goal position. We dump the replay buffer during training as the dataset and run a linear regression to predict the shortest distance between the agent and the goal. Note that this shortest path distance is not the Euclidean distance since there are walls blocking the way. Fig.
8b shows that features learned by contrastive RL can predict this distance better than all baselines.
As shown in Fig. 8b, contrastive RL (NCE) learns representations that achieve lower test error than those learned by TD3+HER and by a random CNN encoder. F.2 When is contrastive learning better than learning a foreward model? [Figure]
In Fig.
2a, we observed that the model-based baseline performed well on the ant umaze task, but poorly on many of the other tasks. One explanation is that the model-based approach will perform well when the goal is relatively low-dimensional, and that contrastive learning will be more useful in settings with higherdimensional goals. We tested this experiment on the 7-dimensional sawyer push environment. We applied both contrastive RL and the modelbased baseline to versions of this task where the goal was varied from 1-dimensional to 7dimensional.
Note that changing the goal dimension changes the task: a 1-dimensional goal corresponds to moving the gripper to the correct X position, whereas a 7-dimensional goal corresponds to moving the object and gripper to the correct poses. We measured the Euclidean distance to the goal ( ↓ is better). We show results in Fig. As expected, higher-dimensional goals are a bit more challenging to achieve.
What we are really interested in is the gap between the model-based approach and the contrastive RL, which opens up starting with a 4-dimensional goal.
Altogether, this (a) Nine-Room environment.
[Figure]
experiment provides some evidence that contrastive RL may be preferred over a forward model, even for tasks with very low dimensional goals. [Figure] F.3 Goals used in the actor loss In theory
[Figure]
the distribution of goals for the actor loss (Eq. 7) does not affect the optimal policy, as long as the distribution has full support. In our experiments [Figure] we sampled these goals randomly
[Figure]
in the same way that we sampled negative examples for contrastive learning. We ran an ablation experiment to study this decision [Figure] and show results in Fig.
These results show that sampling future goals consistently performs poorly [Figure] perhaps because it results in only training the policy on how to reach “easy” goals. A mixture of future goals and random goals works much better
[Figure]
but the best results seem to come from training on only random goals [Figure] F.4 Transferring representations to solve new tasks In this experiment, we studied whether the representations learned by contrastive RL (NCE) for one task might be useful for solving another task.
We started by training contrastive RL (NCE) on three image-based tasks: fetch push , sawyer push , and sawyer bin .
The observations for all tasks look different and the sawyer and fetch tasks have different robots.
The two sawyer tasks look the most similar because they both come from the metaworld [139] benchmark suite.
We used the representations learned for each of these tasks to initialize a second contrastive RL agent, which we used to solve this same set of tasks.
We were primarily interested in transfer – do the representations from one task help in learning to solve another task? Intuitively, even if the tasks are different, a good representation will capture some structural properties (e.g., identifying the robot arm, and identifying objects), which should transfer across the task. We show results in Fig. After training on the first task for 1M environment steps, we used the learned representation as initialization for solving the new task.
On the fetch push task, we see little benefit from using pretrained representations, perhaps because the task is relatively easy.
On the sawyer push , we see the largest benefit from pretraining the representations on the same task as the target task. More interestingly, we see a small benefit from taking the representations learned on the sawyer bin task and using those to solve the sawyer push . On the most challenging task, sawyer bin , using representations pretrained on either fetch push or sawyer bin can accelerate the solving of this task. Taken together, these results suggest that transferring the representations from one task to another is sometimes useful.
F.5 Robustness to Environment Perturbations
We ran an preliminary experiment to study whether the image-based policies learned by contrastive RL (NCE) were robust to perturbations in the environment. We took an agent trained on the fetch push with imageobservations, and evaluated the agent on four variants of the environment (see Fig. • Original environment, without modification; • Object color changed from black to red; • Table color changed from white to yellow; • Initial arm position moved towards the camera. In each setting, we evaluate the success rate over 20 trials, and repeated 5 times to compute standard deviations (for a total of 100 trials).
The learned agent was robust to the object color, with the success rate changing from 78 ± 5% to 73 ± 10% .
The agent was also robust to the change in initial position ( 87 ± 6% ).
However, changing the table color caused the agent to fail ( 0 ± 0% ), perhaps because the table color consumes a large fraction of the image pixels.
F.6 Additional figures
[Figure]
This section presents additional figures. • Fig. 13 compares contrastive RL (NCE) with varying values of the filtering parameter ϵ , described in Sec. 4.5. • Fig.
14 – This plot shows a TSNE embedding of the state-action representations ϕ ( s, a ) for one trajectory of the bin picking task. This experiment uses image observations.
• Fig.
15 – This plot shows a TSNE embedding of the state-action representations from the same bin picking task. We sampled states and actions using a trained agent. After computing the TSNE embedding, we used RasterFairy [65] to rectify the embeddings to a grid.
• Fig. 16 – A TSNE embedding of image representations from the point Spiral11x task. • Fig. 17 – Using the same representations for the point Spiral11x11 task, we measure the similarity between the critic gradients when evaluated at the same state but different goals, ⟨ ∂f∂s | ( s,g ) , ∂f∂s | ( s,g ′ ) ⟩ .
[Figure]
[Figure] G Failed Experiments Representation normalization : We experimented with many ways of normalizing the learned representations, including L2 normalization, scaling the representations by a learned temperature parameter, and applying an elementwise tanh activation. None of these modifications consistently improved performance.
Momentum encoder : Prior contrastive learning methods have found it useful to use a target encoder or momentum buffer. We experimented with many similar tricks, including using a momentum buffer for goal representations, sampling some fraction of goal representations from a fixed random distribution, increasing the learning rate for the state encoder’s final layer, and decreasing the learning rate for all layers in the goal encoder. None of these tricks consistently improved performance.
Frame stacking – This tended to decrease performance slightly. Loss scaling – Our contrastive RL (NCE) method uses the negative label much more often than the positive label. We tried scaling the loss terms so that the negative and positive examples received the same total weight, but found this had no effect on performance.