C ONTRASTIVE B EHAVIORAL S IMILARITY E MBEDDINGS FOR G ENERALIZATION IN R EINFORCEMENT L EARNING
Rishabh Agarwal ∗
Google Research, Brain Team {rishabhagarwal, marlosm, psc, bellemare}@google.com
A BSTRACT
Reinforcement learning methods trained on few environments rarely learn policies that generalize to unseen environments.
To improve generalization, we incorporate the inherent sequential structure in reinforcement learning into the representation learning process.
This approach is orthogonal to recent approaches, which rarely exploit this structure explicitly.
Speciﬁcally, we introduce a theoretically motivated policy similarity metric (PSM) for measuring behavioral similarity between states.
PSM assigns high similarity to states for which the optimal policies in those states as well as in future states are similar.
We also present a contrastive representation learning procedure to embed any state similarity metric, which we instantiate with PSM to obtain policy similarity embeddings (PSEs 1 ).
We demonstrate that
PSEs improve generalization on diverse benchmarks, including LQR with spurious correlations, a jumping task from pixels, and Distracting DM Control Suite.
I NTRODUCTION
[Figure]
Current reinforcement learning (RL) approaches often learn policies that do not generalize to environments different than those the agent was trained on, even when these environments are semantically equivalent (Tachet des Combes et al., 2018; Song et al., 2019; Cobbe et al., 2019).
For example, consider a jumping task where an agent, learning from pixels, needs to jump over an obstacle (Figure 1).
Deep RL agents trained on a few of these tasks with different obstacle positions struggle to solve test tasks where obstacles are at previously unseen locations.
Recent solutions to circumvent poor generalization in RL are adapted from supervised learning, and, as such, largely ignore the sequential aspect of RL.
Most of these solutions revolve around enhancing the learning process, including data augmentation ( e.g., Kostrikov et al., 2020; Lee et al., 2020a), regularization (Cobbe et al., 2019; Farebrother et al., 2018), noise injection (Igl et al., 2019), and diverse training conditions (Tobin et al., 2017); they rarely exploit properties of the sequential decision making problem such as similarity in actions across temporal observations.
Instead, we tackle generalization by incorporating properties of the RL problem into the representation learning process.
Our approach exploits the fact that an agent, when operating in environments with similar underlying mechanics, exhibits at least short sequences of behaviors that are similar across these environments.
Concretely, the agent is optimized to learn an embedding in which states are close when the agent’s optimal policies in these states and future states are similar.
This notion of proximity is general and it is applicable to observations from different environments.
Speciﬁcally, inspired by bisimulation metrics (Castro, 2020; Ferns et al., 2004), we propose a novel policy similarity metric (PSM).
PSM (Section 3) deﬁnes a notion of similarity between states originated from different environments by the proximity of the long-term optimal behavior from these states.
PSM is reward-agnostic, making it more robust for generalization compared to approaches that rely on reward information.
We prove that PSM yields an upper bound on suboptimality of policies transferred from one environment to another (Theorem 1), which is not attainable with bisimulation.
We employ PSM for representation learning and introduce policy similarity embeddings (PSEs) for deep RL.
To do so, we present a general contrastive procedure (Section 4) to learn an embedding based on any state similarity metric.
PSEs are the instantiation of this procedure with PSM.
PSEs are appealing for generalization as they encode task-relevant invariances by putting behaviorally equivalent states together.
This is unlike prior approaches, which rely on capturing such invariances without being explicitly trained to do so, for example, through value function similarities across states ( e.g., Castro & Precup, 2010), or being robust to ﬁxed transformations of the observation space ( e.g., Kostrikov et al., 2020; Laskin et al., 2020a).
PSEs lead to better generalization while being orthogonal to how most of the ﬁeld has been tackling generalization.
We illustrate the efﬁcacy and broad applicability of our approach on three existing benchmarks speciﬁcally designed to test generalization: (i) jumping task from pixels (Tachet des
Combes et al., 2018)
(Section 5), (ii) LQR with spurious correlations (Song et al., 2019)
(Section 6.1), and (iii) Distracting DM Control Suite (Stone et al., 2021; Zhang et al., 2018b)
(Section 6.2).
Our approach improves generalization compared to a wide variety of approaches including standard regularization (Farebrother et al., 2018; Cobbe et al., 2019), bisimulation (Castro & Precup, 2010; Castro, 2020; Zhang et al., 2021), out-of-distribution generalization (Arjovsky et al., 2019) and state-of-the-art data augmentation (Kostrikov et al., 2020; Lee et al., 2020a).
P RELIMINARIES
We describe an environment as a Markov decision process (MDP) (Puterman, 1994)
M =
( X , A , R, P, γ ) , with a state space X , an action space A , a reward function R , transition dynamics P , and a discount factor γ ∈ [0 , 1) .
A policy π ( · | x ) maps states x ∈ X to distributions over actions.
Whenever convenient, we abuse notation and write π ( x ) to describe the probability distribution π ( · | x ) , treating π ( x ) as a vector.
In RL, the goal is to ﬁnd an optimal policy π ∗ that maximizes the cumulative expected return E a t ∼ π ( · | x t ) [ (cid:80) t γ t R ( x t , a t )] starting from an initial state x 0 .
We are interested in learning a policy that generalizes across related environments.
We formalize this by considering a collection ρ of MDPs, sharing an action space A but with disjoint state spaces.
We use X and Y to denote the state spaces of speciﬁc environments, and write R X , P X for the reward and transition functions of the MDP whose state space is X , and π ∗X for its optimal policy, which we assume unique without loss of generality.
For a given policy π , we further specialize these into R π X and P π X , the reward and state-to-state transition dynamics arising from following π in that MDP.
We write S for the union of the state spaces of the MDPs in ρ .
Concretely, different MDPs correspond to speciﬁc scenarios in a problem class (Figure 1), and S is the space of all possible conﬁgurations.
Used without subscripts, R , P , and π refer to the reward and transition function of this “union MDP”, and a policy deﬁned over S ; this notation simpliﬁes the exposition.
We measure distances between states across environments using pseudometrics 2 on S ; the set of all such pseudometrics is M , and M p is the set of metrics on probability distributions over S .
In our setting, the learner has access to a collection of training MDPs {M i } Ni =1 , drawn from ρ .
After interacting with these environments, the learner must produce a policy π over the entire state space
S , which is then evaluated on unseen MDPs from ρ .
Similar in spirit to the setting of transfer learning (Taylor & Stone, 2009), here we evaluate the policy’s zero-shot performance on ρ .
Our policy similarity metric (Section 3) builds on the concept of π - bisimulation (Castro, 2020).
Under the π -bisimulation metric, the distance between two states, x and y , is deﬁned in terms of the difference between the expected rewards obtained when following policy π .
The π -bisimulation metric d π satisﬁes a recursive equation based on the 1-Wasserstein metric W 1 : M → M p , where
W 1 ( d )( A, B ) is the minimal cost of transporting probability mass from A to B (two probability distributions on S ) under the base metric d (Villani, 2008).
The recursion is
[Equation]
To achieve good generalization properties, we learn an embedding function z θ : S → R k that reﬂects the information encoded in the policy similarity metric; this yields a policy similarity embedding (Section 4).
We use contrastive methods (Hadsell et al., 2006; Oord et al., 2018) whose track record for representation learning is well-established.
We adapt SimCLR (Chen et al., 2020), a popular contrastive method for learning embeddings of image inputs.
Given two inputs x and y , their embedding similarity is s θ ( x, y ) =
sim ( z θ ( x ) , z θ ( y )) , where sim ( u, v ) =
u T v (cid:107) u (cid:107)(cid:107) v (cid:107) denotes the cosine similarity function.
SimCLR aims to maximize similarity between augmented versions of an image ( e.g., crops, colour changes) while minimizing its similarity to other images.
The loss used by
SimCLR for two versions x, y of an image, and a set X (cid:48) containing other images is:
[Equation]
where λ is an inverse temperature hyperparameter.
The overall SimCLR loss is then the expected value of (cid:96) θ ( x, y ; S ) , when x , y , and X (cid:48) are drawn from some augmented training distribution.
P OLICY S IMILARITY M ETRIC
A useful tool in learning a policy that generalizes is to understand which states result in similar behavior, and which do not.
To be maximally effective, this similarity should go beyond the immediately chosen action and consider long-term behavior.
In this regards, the π -bisimulation metrics are interesting as they are based on the full sequence of future rewards received from different states.
However, considering rewards can be both too restrictive (when the policies are the same, but the obtained rewards are not; see Figure D.1) or too permissive (when the policies are different, but the obtained rewards are not; see Figure 3a).
In fact, π -bisimulation metrics actually lead to poor generalization in our experiments (Sections 5.1 and 5.2).
To address this issue, we instead consider the similarity between policies themselves.
We replace the absolute reward difference by a probability pseudometric between policies, denoted D IST .
Additionally, since we would like to perform well in unseen environments, we are interested in similarity in optimal behavior.
We thus use π ∗ as the grounding policy.
This yields the policy similarity metric (PSM), for which states are close when the optimal policies in these states and future states are similar.
For a given D IST , the PSM d ∗ : S × S
→ R satisﬁes the recursive equation
[Equation]
The D IST term captures the difference in local optimal behavior (A) while W 1 captures long-term optimal behavior difference (B); the exact weights assigned to the two are given by the discount factor.
Furthermore, when D IST is bounded, d ∗ is guaranteed to be ﬁnite.
While there are technically multiple PSMs (one for each D IST ), we omit this distinction whenever clear from context.
A proof of the uniqueness of d ∗ is given in Proposition B.1.
Our main use of PSM will be to compare states across environments.
In this context, we identify the terms in Equation 3 with speciﬁc environments for clarity and write (despite its technical inaccuracy)
[Equation]
PSM is applicable to both discrete and continuous action spaces.
In our experiments, D IST is the total variation distance ( TV ) when A is discrete, and we use the (cid:96) 1 distance between the mean actions of the two policies when A is continuous.
PSM can be computed iteratively using dynamic programming (Ferns et al., 2011) (more details in Section D.1).
Furthermore, when π ∗ is unavailable on training environments, we replace it by an approximation ˆ π ∗ to obtain an approximate PSM, which is close to the exact PSM depending on the suboptimality of ˆ π ∗ (Proposition D.3).
Despite resembling π -bisimulation metrics in form, the PSM possesses different characteristics which are better suited to the problem of generalizing a learned policy.
To illustrate this point, consider the following simple nearest-neighbour scheme:
Given a state y ∈ Y , denote its closest match in X by ˜ x
y :=
arg min x ∈X d ∗ ( x, y ) .
Suppose that we use this scheme to transfer π ∗X to M Y , in the sense that we behave according to the policy ˜ π
( y ) =
π ∗X (˜ x y ) .
We can then bound the difference between ˜ π and π ∗Y , something that is not possible if d ∗ is replaced by a π -bisimulation metric.
Theorem 1.
[Bound on policy transfer] For any y ∈ Y , let Y ty ∼ P ˜ π
( · | Y t − 1 y ) deﬁne the sequence of random states encountered starting in Y
y = y and following policy
˜ π .
We have:
[Equation]
[Table]
[Equation]
[Table]
[Equation]
The proof is in the Appendix (Section B).
Theorem 1 is non-vacuous whenever d ∗ (˜ x y , y ) <
1 / (1+ γ ) .
In particular, d ∗ (˜ x y , y ) = 0 implies that the transferred policy is optimal.
Although this scheme is not practical (computing d ∗ requires knowledge of π ∗Y ), it shows that meaningful policy generalization can be obtained if we can ﬁnd a mapping that generalizes across S .
Put another way, PSM gives us a principled way of lifting generalization across inputs (a supervised learning problem) to generalization across environments.
We now describe how to employ PSM for learning representations that put together states in which the agent’s long-term optimal behavior is similar.
L EARNING C ONTRASTIVE M ETRIC E MBEDDINGS
To generalize a learned policy to new environments, we build on the success of contrastive representations (Section 2).
Given a state similarity metric d , we develop a general procedure (Algorithm 1) to learn contrastive metric embeddings (CMEs) for d .
We utilize the metric d for deﬁning the set of positive and negative pairs, as well as assigning importance weights to these pairs in the contrastive loss (Equation 4 ).
We ﬁrst apply a transformation to convert d to a similarity measure Γ , bounded in [0, 1] for “soft” similarities.
In this work, we transform d using the Gaussian kernel with a positive scale parameter β , that is, Γ( x, y ) =
exp( − d ( x, y ) /β ) .
β controls the sensitivity of the similarity measure to d .
Second, we select the positive and negative pairs given a set of states X (cid:48) ⊆
X and Y from MDPs
M X , M Y respectively.
For each anchor state y ∈ Y , we use its nearest neighbor in X (cid:48) based on the similarity measure Γ to deﬁne the positive pairs { (˜ x y , y ) } , where ˜ x y =
argmax x ∈X (cid:48)
Γ( x, y ) .
The remaining states in X (cid:48) , paired with y , are used as negative pairs.
This choice of pairs is motivated by Theorem 1, which shows that if we transfer the optimal policy in M X to the nearest neighbors deﬁned using PSM, its performance in M Y has suboptimality bounded by PSM.
Next, we deﬁne a soft version of the SimCLR contrastive loss (Equation 2) for learning the function z θ , which maps states (usually high-dimensional) to embeddings.
Given a positive state pair (˜ x y , y ) , the set X (cid:48) , and the similarity measure Γ , the loss (pseudocode provided in Section J.2) is given by (cid:96)
[Equation]
where we use the same notation as in Equation 2.
Following SimCLR, we use a non-linear projection of the representation as z θ (Figure A.1).
The agent’s policy is an afﬁne function of the representation.
The total contrastive loss for M X and M Y utilizes the optimal trajectories τ ∗X
= { x t } Nt =1 and τ ∗Y = { y t } Nt =1 , where x t +1 ∼ P π ∗ X ( · | x t ) and y t +1 ∼ P π ∗ Y ( · | y t ) .
We set X (cid:48) =
τ
∗X and deﬁne
L θ ( M X , M Y ) =
E y ∼ τ ∗Y [ (cid:96) θ (˜ x y , y ; τ ∗X )]
where ˜ x y = argmax x ∈ τ ∗X Γ( x, y ) .
We refer to CMEs learned with policy similarity metric as policy similarity embeddings (PSEs) .
PSEs can trivially be combined with data augmentation by using augmented states when computing state embeddings.
We simultaneously learn PSEs with the RL agent by adding L CME (Algorithm 1) as an auxiliary objective during training.
Next, we illustrate the beneﬁts from this auxiliary objective.
J UMPING T ASK FROM P IXELS : A C ASE S TUDY
Task Description .
The jumping task (Tachet des Combes et al., 2018)
(Figure 1) captures, using well-deﬁned factors of variations, whether agents can learn the correct invariances required for generalization, directly from image inputs.
The task consists of an agent trying to jump over an obstacle.
The agent has access to two actions: right and jump .
The agent needs to time the jump
[Table]
Height
T T T
T T T
T
T
T T T
T
T
T
T T T
T ( [Table]
T T
T T T
T
T T T T T
T
T T T T T T (b) “Narrow” grid
T
T T T
T T T T
T T T T T
T T T T
T
[Figure]
precisely, at a speciﬁc distance from the obstacle, otherwise it will eventually hit the obstacle.
Different tasks consist in shifting the ﬂoor height and/or the obstacle position. To generalize, the agent needs to be invariant to the ﬂoor height while jump based on the obstacle position. The obstacle can be in 26 different locations while the ﬂoor has 11 different heights, totaling 286 tasks. Problem Setup .
We split the problem into 18 seen (training) and 268 unseen (test) tasks to stress test generalization using a few changes in the underlying factors of variations seen during training. The small number of positive examples 3 results in a highly unbalanced classiﬁcation problem with low amounts of data, making it challenging without additional inductive biases. Thus, we evaluate generalization in regimes with and without data augmentation. The different grids conﬁgurations (Figure 2) capture different types of generalization: the “wide” grid tests generalization via “interpolation”, the “narrow” grid tests out-of-distribution generalization via “extrapolation”, and the random grid instances evaluate generalization similar to supervised learning where train and test samples are drawn i.i.d.
from the same distribution.
We used RandConv (Lee et al., 2020a), a state-of-the-art data augmentation for generalization.
For hyperparameter selection, we evaluate all agents on a validation set containing 54 unseen tasks in the “wide” grid (Figure 2a) and pick the parameters with the best validation performance.
We use these ﬁxed parameters for all grid conﬁgurations to show the robustness of PSEs to hyperparameter tuning.
We ﬁrst compute the optimal trajectories in the training tasks.
Using these trajectories, we compute
PSM using dynamic programming (Section D.1).
We train the agent by imitation learning, combined with an auxiliary loss for PSEs (Section 4).
More details are in Section G.
5. E VALUATING G ENERALIZATION ON J UMPING T ASK
We show the efﬁcacy of PSEs compared to common generalization approaches such as regularization ( e.g., Cobbe et al., 2019; Farebrother et al., 2018), and data augmentation ( e.g., Lee et al., 2020a;
Laskin et al., 2020a), which are quite effective on pixel-based RL tasks.
We also contrast PSEs with bisimulation transfer (Castro & Precup, 2010), a tabular state-based transfer approach based on bisimulation metrics which does not do any learning and bisimulation preserving representations (Zhang et al., 2021), showing the advantages of PSM over a prevalent state similarity metric. [Figure]
We ﬁrst investigated how well PSEs generalize over existing methods without incorporating additional domain knowledge during training.
Table 1 summarizes, in the setting without data augmentation, the performance of these methods in different train/test splits ( c.f. Figure 2 for a detailed description).
PSEs, with only 18 examples, already leads to better performance than standard regularization.
PSEs also outperform bisimulation transfer in the “wide” and random grids.
Although bisimulation transfer is impractical 4 when evaluating zero-shot generalization, we still performed this comparison, unfair to PSEs, to highlight their efﬁcacy.
PSEs perform better because, in contrast to bisimulation,
PSM is reward agnostic ( c.f. Proposition D.1)
– the expected return of the jump action is quite different depending on the obstacle position ( c.f. Figure G.2 for a visual juxtaposition of PSM and bisimulation).
[-[Figure] ) PSM + (cid:96) 2 embeddings 02 02 02 
 [Figure]-] Overall, these results are promising because they place PSEs as an effective generalization method that does not rely on data augmentation.
Nevertheless, PSEs are complementary to data augmentation, which consistently improves generalization in deep RL.
We compared RandConv combined with PSEs to simply using RandConv.
Domain-speciﬁc augmentation also succeeds in the jumping task.
Thus, it is not surprising that
RandConv is so effective compared to techniques without augmentation.
Table 1 ( 2 nd row) shows that PSEs substantially improve the performance of RandConv across all grid conﬁgurations.
Moreover, Table 1 ( 2 nd row) illustrates that when combined with RandConv, bisimulation preserving representations (Zhang et al., 2021) diminish generalization by 30 − 50% relative to PSEs.
Notably, Table 1 ( 1 st row) indicates that learning-based methods are ineffective on the “narrow” grid without data augmentation.
That said, PSEs do work quite well when combined with RandConv.
However, even with data augmentation, generalization in “narrow” grid happens only around the vicinity of training tasks, exhibiting the challenge this grid poses for learning-based methods.
We believe this is due to the poor extrapolation ability of neural networks ( e.g., Haley & Soloway, 1992;
Xu et al., 2020), which is more perceptible without prior inductive bias from data augmentation.
5. U NDERSTANDING GAINS FROM PSE S : A BLATIONS AND V ISUALIZATIONS
[Table]
PSM 17.5 (8.4) 87.0 (10.1)
PSEs are contrastive metric embeddings (CMEs) learned with PSM.
We investigate the gains from
CMEs (Section 4) and PSM (Section 3) by ablating them.
CMEs can be learned with any state similarity metric – we use π ∗ - bisimulation (Castro, 2020) as an alternative.
Similarly, PSM can be used with any metric embedding – we use (cid:96) 2 -embeddings (Section E) as an alternative, which Zhang et al.
(2021) employed with π ∗ -bisimulation for learning representations in a single task RL setting.
For a fair comparison, we tune hyperparameters for 128 trials for each ablation entry in Table 2.
Table 2 show that PSEs ( = PSM + CMEs) generalize signiﬁcantly better than π ∗ -bisimulation with CMEs or (cid:96) 2 -embeddings, both of which signiﬁcantly degrade performance ( − 60% and − 45% , respectively).
This is expected, as π ∗ -bisimulation imposes the incorrect invariances for the jumping task ( c.f. Figures G.2a and G.2d).
Additionally, looking at the rows of Table 2, CMEs are superior than (cid:96) 2 -embeddings for PSM while inferior for π ∗ -bisimulation.
This result is in line with the hypothesis that CMEs better enforce the invariances encoded by a similarity metric compared to (cid:96) 2 -embeddings ( c.f. Figures 3b and 3c).
Visualizing learned representations .
We visualize the metric embeddings in the ablation above by projecting them to two dimensions with UMAP (McInnes et al., 2018), a popular visualization technique for high dimensional data which better preserves the data’s global structure compared to other methods such as t-SNE (Coenen & Pearce, 2019).
Figure 3 shows that PSEs partition the states into two sets: (1) states where a single suboptimal action leads to failure (all states before jump ) and (2) states where actions do not affect the ﬁnal outcome (states after jump ).
Additionally, PSEs align the labeled states in the ﬁrst set, which have a
PSM distance of zero.
These aligned states have the same distance from the obstacle, the invariant feature that generalizes across tasks.
On the other hand, (cid:96) 2 -embeddings
(Zhang et al., 2021) with
PSM do not align states with zero PSM except the state with the jump action – poor generalization, as observed empirically, is likely due to states with the same optimal behavior ending up with distant embeddings.
CMEs with π ∗ -bisimulation align states with π ∗ -bisimulation distance of zero – such states are equidistant from the start state and have different optimal behavior for any pair of tasks with different obstacle positions (Figure G.2c).
5. J UMPING T ASK WITH C OLORS : W HERE T ASK - DEPENDENT I NVARIANCE M ATTERS
[Figure]
PSEs capture invariances that are usually orthogonal to task-agnostic invariances from data augmentation.
This difference is important because, for certain tasks, data augmentation can erroneously alias states with different optimal behavior.
Domain knowledge is often required to select appropriate augmentations, otherwise augmentations can hurt generalization.
In contrast, PSEs do not require any domain knowledge but instead exploit the inherent structure of the RL tasks.
To demonstrate the difference between PSEs and data augmentation, we simply include colored obstacles in the jumping task (see Figure G.5).
In this modiﬁed task, the optimal behavior of the agent depends on the obstacle color: the agent needs to jump over the red obstacle but strike the green obstacle to get a high return.
The red obstacle task has the same difﬁculty as the original jumping task while the green obstacle task is easier.
We jointly train the agent withtraining tasks each, for both obstacle colors, and evaluate generalization on unseen red tasks.
Figure 4 shows the large performance gap between PSEs and data augmentation with RandConv.
All methods solve the green obstacle tasks (Table G.1).
As opposed to the original jumping task ( c.f. Table 1), data augmentation inhibits generalization since RandConv forces the agent to ignore color, conﬂating the red and green tasks (Figure G.6).
PSEs still outperform regularization and data augmentation.
Furthermore, data augmentation performs better when combined with PSEs.
Thus, PSEs are effective even when data augmentation hurts performance.
5. E FFECT OF P OLICY S UBOPTIMALITY ON PSE S
To understand the sensitivity of learning effective PSEs to the quality of the policies, we compute PSEs using (cid:15) -suboptimal policies on the jumping task, which take the optimal action with probability 1 − (cid:15) and the subopotimal action with probability (cid:15) . We evaluate the generalization performance of
PSEs for increasingly suboptimal policies, ranging from the optimal policy ( (cid:15) = 0 ) to the uniform random policy ( (cid:15)
= 0 . 5 ).
To isolate the effect of suboptimality on PSEs, the agent still imitates the optimal actions during training for all (cid:15) .
[Figure]
Figure 5 shows that PSEs show near-optimal generalization with (cid:15) ≤ 0 .
4 while degrade generalization with an uniform random policy.
This result is well-aligned with Proposition D.3, which shows that for policies with decreasing suboptimality, PSM approximation becomes more accurate, resulting in improved PSEs.
Overall, this study conﬁrms that the utility of PSEs for generalization is robust to suboptimality.
One reason for this robustness is that
PSEs are likely to align states with similar long-term greedy optimal actions, resulting in good performance even with suboptimal policies that preserve these greedy actions.
A DDITIONAL E MPIRICAL E VALUATION
In this section [Figure] we exhibit that PSM ignores spurious information for generalization using a LQR task (Song et al., 2019) with non-image inputs.
Then, we demonstrate the scalability of PSEs without explicit access to optimal policies in an RL setting
[Figure] with continuous actions, using Distracting DM Control Suite (Stone et al., 2021; Zhang et al., 2018b).
6. LQR WITH S PURIOUS C ORRELATIONS
[Figure]
We show how representations learned using PSM, when faced with semantically equivalent environments, can learn the main factors of variation and ignore spurious correlations that hinder generalization.
We use LQR with distractors (Song et al., 2019; Sonar et al., 2020) to assess generalization in a featurebased RL setting with linear function approximation.
The distractors are input features that are spuriously correlated with optimal actions and can be used for predicting these actions during training, but hurt generalization.
The agent learns a linear policy usingenvironments with ﬁxed distractors.
This policy is evaluated on environments with unseen distractors.
We aggregate state pairs in training environments with near-zero PSM.
We contrast this approach with (i) IPO (Sonar et al., 2020), a policy optimization method based on IRM (Arjovsky et al., 2019) for outof-distribution generalization, (ii) overparametrization, which leads to better generalization via implicit regularization (Song et al., 2019), and (iii) weight sparsity using (cid:96) 1 -regularization since the policy weights which generalize in this task are sparse.
All methods optimally solve the training environments; however, the baselines perform abysmally in terms of generalization compared to state aggregation with PSM (Figure 6), indicating their reliance on distractors.
PSM obtains near-optimal generalization which we corroborate through this conjecture (Section H.1): Assuming zero state aggregation error with PSM, the policy learned using gradient descent is independent of the distractors .
Refer to Section H for a detailed discussion.
6. D ISTRACTING DM C ONTROL S UITE
Finally, we demonstrate scalability of PSEs on the Distracting DM Control Suite (DCS)
(Stone et al., 2021), which tests whether agents can ignore high-dimensional visual distractors irrelevant to the RL task.
Since we do not have access to optimal training policies, we use learned policies as proxy for π ∗ for computing PSM as well as collecting data for optimizing PSEs.
Even with this approximation, PSEs outperform stateof-the-art data augmentation.
DCS extends DM Control (Tassa et al., 2020) with visual distractions.
We use the dynamic background distractions (Stone et al., 2021; Zhang et al., 2018b) where a video is played in the background from a speciﬁc frame.
The video and the frame are randomly sampled every new episode.
We use 2 videos during training (Figure 7) and evaluate generalization on 30 unseen videos (Figure I.1). [Table]
All agents are built on top of SAC (Haarnoja et al., 2018) combined with DrQ (Kostrikov et al., 2020), an augmentation method with state-of-the-art performance on DM control.
Notably, DrQ outperforms
CURL (Laskin et al., 2020b), a strong contrastive method for RL.
Without data augmentation on DM control, SAC performs poorly, even during training (Kostrikov et al., 2020).
We augment DrQ with an auxiliary loss for learning PSEs and compare it with DrQ (Table 3).
Orthogonal to DrQ, PSEs align representations of different states across environments based on PSM ( c.f. Figure A.1).
All agents are trained for 500K environment steps with random crop augmentation.
For computing PSM, we use policies learned by DrQ pretrained on training environments for 500K steps.
First, we investigate how much better PSEs generalize relative to DrQ, assuming the agent is provided with PSM beforehand.
The agent’s policy is randomly initialized so that additional gains over DrQ can be attributed to the auxiliary information from PSM.
The substantial gains in Table 3 indicate that PSEs are more effective than DrQ for encoding invariance to distractors.
Since PSEs utilize PSM approximated using pretrained policies, we also compare to a DrQ agent where we initialize it using these pretrained policies.
This comparison provides the same auxiliary information to DrQ as available to PSEs, thus, the generalization difference stems from how they utilize this information.
Table 3 demonstrates that PSEs outperform DrQ with pretrained initialization, indicating that the additional pretraining steps are more judiciously utilized for computing PSM as opposed to just longer training with DrQ. More details, including learning curves, are in Section I.
R ELATED W ORK
PSM (Section 3) is inspired by bisimulation metrics (Section C).
However, different than traditional bisimulation ( e.g., Larsen & Skou, 1991; Givan et al., 2003; Ferns et al., 2011), PSM is more tractable as it deﬁned with respect to a single policy similar to the recently proposed π ∗ -bisimulation (Castro, 2020; Zhang et al., 2021).
However, in contrast to PSM, bisimulation metrics rely on reward information and may not provide a meaningful notion of behavioral similarity in certain environments (Section 5).
For example, states similar under PSM would have similar optimal policies, yet can have arbitrarily large π ∗ -bisimulation distance between them (Proposition D.1).
PSEs (Section 4) use contrastive learning to encode behavior similarity (Section 3) across MDPs.
Previously, contrastive learning has been applied for imposing state self-consistency (Laskin et al., 2020b), capturing predictive information (Oord et al., 2018; Mazoure et al., 2020; Lee et al., 2020b) or encoding transition dynamics (van der Pol et al., 2020; Stooke et al., 2020; Schwarzer et al., 2020) within an MDP.
These methods can be integrated with PSEs to encode additional invariances.
Interestingly, in a similar spirit to PSEs, Pacchiano et al.
Moskovitz et al.
(2021) explore comparing behavioral similarity between policies to guide policy optimization within an MDP.
PSEs are complementary to data augmentation methods (Kostrikov et al., 2020; Lee et al., 2020a;
Raileanu et al., 2020; Ye et al., 2020), which have recently been shown to signiﬁcantly improve agents’ generalization capabilities.
In fact, we combine PSEs to state-of-the-art augmentation methods including random convolutions (Lee et al., 2020a;
Laskin et al., 2020a) in the jumping task and
DrQ (Kostrikov et al., 2020) on Distracting Control Suite, leading to performance improvement.
C ONCLUSION
This paper advances generalization in RL by two contributions: (1) the policy similarity metric (PSM) which provides a new notion of state similarity based on behavior proximity, and (2) contrastive metric embeddings , which harness the beneﬁts of contrastive learning for representations based on a similarity metric.
PSEs combine these two ideas to improve generalization.
Overall, this paper shows the beneﬁts of exploiting the inherent structure in RL for learning effective representations. A L EARNING C ONTRASTIVE M ETRIC E MBEDDINGS Policy [Figure]
Input Augmentation Representation Projection
[Figure]
Contrastive
Learning
[Figure]
B P ROOFS
We begin by deﬁning some notation which will be used throughout these results:
• We denote E t ≥
[ γ t TV (˜ π ( Y ty ) , π ∗ ( Y ty ))]
=
E Y ty (cid:104)(cid:80) t ≥
γ t TV (˜ π
( Y ty ) , π ∗ ( Y ty ))
(cid:105) • For any y ∈ Y , let Y ty ∼ P
˜ π
( ·| Y t − 1 y ) , where Y
y =
y .
• TV n ( Y k y ) =
E
[Equation]
We now proceed with some technical lemmas necessary for the main result.
Lemma 1.
Given any two pseudometrics 5 d, d (cid:48) ∈ M and probability distributions P X , P Y where
X , Y ⊂ S , we have:
[Equation]
Proof.
Note that the dual of the linear program for computing W 1 ( d )( P X , P Y ) is given by
[Equation]
Using the dual formulation subject to the constraints above, W 1 ( d ) can be written as
[Equation]
Lemma 2.
Given any y 0 ∈ Y , we have:
[Equation]
Proof.
[Equation]
[Table]
[Equation]
[Table]
[Equation]
[Table]
[Equation]
Lemma 3.
Given any y 0 ∈ Y [Equation] if TV n ( Y 0 y 1 ) ≤ 1+ γ 1 − γ d ∗ (˜ x y 1 , y 1 ) , we have:
[Equation]
Proof.
Note that we have the following equality, where 0 is a vector of zeros:
[Equation]
which is the same form as the primal LP for W 1 ( d ∗ )
( P π ∗ ( ·| y 0 ) , P π ∗ ( ·| ˜ x y 0 )) .
By assumption, we have that
[Equation]
This implies that 1 − γ 1+ γ TV n ( Y 0 · ) is a feasible solution to W 1 ( d ∗ )(
[Equation]
π ∗ ( ·| y
[Equation]
P [Equation] ∗ [Equation]
[Equation]
and the result follows.
Proposition B.1.
The operator F given by:
[Equation]
is a contraction mapping and has a unique ﬁxed point for a bounded dist .
Proof.
We ﬁrst prove that F is contraction mapping.
Then, a simple application of the Banach Fixed
Point Theorem asserts that F has a unique ﬁxed point.
Note that for all pseudometrics d, d (cid:48) ∈ M , and for all states x ∈ X , y ∈ Y ,
[Equation]
Lemma
[Equation]
Thus, (cid:107)F ( d ) − F ( [Equation] ) (cid:107) ≤ γ (cid:107) d − d (cid:48) (cid:107) , so that F is a contracting mapping for γ < 1 and has an unique ﬁxed point d ∗ .
Theorem 1.
[Bound on policy transfer] For any y ∈ Y , let Y ty ∼ P ˜ π
( · | Y t − 1 y ) deﬁne the sequence of random states encountered starting in Y
y = y and following policy
˜ π .
We have:
[Equation]
Proof.
We will prove this by induction.
Assuming that the bound holds for TV n , we prove the bound holds for TV n +1 .
The base case for n = 1 follows from TV (˜ π ( y ) , π ∗ ( y ))
=
TV ( π ∗ (˜ x y ) , π ∗ ( y ))
≤ d ∗ (˜ x y , y ) .
Note that TV n ≤ [Equation] since the TV distance per time-step can be at most 1.
Let P πt ( y (cid:48) | y ) denote the probability of ending in state y (cid:48)
∈ Y after t steps when following policy π and starting from state y .
We then have:
[Equation]
Lemma 2 ≤ (cid:88)
y k ∈ Y P ˜ πk ( y k | y )   TV (˜ π ( y k ) , π ∗ ( y k )) + 2 γ 1 − γ TV (
˜ π
( y k ) , π ∗ ( y k ))
+ γ (cid:88)
y k +1 ∈ Y
P π ∗ ( y k +1 | y k ) TV n ( Y
y k +1 ) 

Lemma 3 ≤ (cid:88)
y k ∈ Y
P ˜ πk ( y k | y ) [ TV (˜ π
( y k ) , π ∗ ( y k ))
+ γ (cid:18) 2 1 − γ TV (˜ π ( y k ) , π ∗ ( y k )) + 1 + γ 1 − γ W 1 ( d ∗ ) (cid:16) P π ∗ ( ·| ˜ x y k ) , P π ∗ ( ·| y k ) (cid:17)(cid:19)(cid:21) = (cid:88)
y k ∈ Y
P ˜ πk
( y k | y ) {+(cid:20) 
+}
+ γ 1 − γ (cid:16) TV ( π ∗ (˜ x y k ) , π ∗ ( y k ))
+ γW 1 ( [-Y 
-]d ∗ )( P π ∗ ( ·| ˜ x y k ) , P π ∗ ( ·| y k ))
(cid:17)(cid:21) ≤ (cid:88)
y k ∈ Y
P ˜ πk ( y k | y )1 + γ 1 − γ d ∗ (˜ x y k , y k )
Thus, by induction, it follows that for all n :
[Equation]
which completes the proof.
C B ISIMULATION METRICS
Notation .
We use the notation as deﬁned in Section 2.
Bisimulation metrics (Givan et al., 2003; Ferns et al., 2011) deﬁne a pseudometric d ∼ : S × S → R where d ∼ ( x, y ) is deﬁned in terms of distance between immediate rewards and next state distributions.
Deﬁne F e ∼ : M → M by
[Equation]
then, F e ∼ has a unique ﬁxed point d ∼ which is a bisimulation metric.
F e ∼ uses the 1-Wasserstein metric W 1 : M → M p .
The 1-Wasserstein distance W 1 ( d ) under the pseudometric d can be computed using the dual linear program:
[Equation]
Since we are only interested in computing the coupling between the states in X and Y , the above formulation assumes that P X ( y ) =
for all y ∈ Y and P Y ( x ) =
for all x ∈ X .
The computation of d ∼ is expensive and requires a tabular representation of the states, rendering it impractical for large state spaces.
On-policy bisimulation (Castro, 2020) ( e.g., π ∗ -bisimulation) is tied to speciﬁc behavior policies and is much easier to approximate than bisimulation.
D P OLICY S IMILARITY M ETRIC D. C OMPUTING PSM
In general, PSM for a given D IST across MDPs M X and M Y is given by
[Equation]
Since our main focus is showing the utility of PSM for generalization, we simply use environments where PSM can be computed using dynamic programming.
Using a similar observation to Castro (2020), we assert that the recursion for d ∗ takes the following form in deterministic environments:
[Equation]
where x (cid:48)
=
P π ∗ X ( x ) , y (cid:48)
=
P π ∗ Y ( y ) are the next states from taking actions π ∗X ( x ) , π ∗X ( y ) from states x, y respectively.
Furthermore, we assume that D IST between terminal states from M X and M Y is zero.
Note that the form of Equation D.2 closely resembles the update rule in Q-learning, and as such, can be efﬁciently computed with samples using approximate dynamic programming.
Given access to optimal trajectories τ ∗X = { x t } Nt =1 and τ ∗Y = { y t } Nt =1 , where x t +1 =
P π ∗ X ( x t ) and y t +1 =
P π ∗ Y ( y t ) , Equation D.2 can be solved using exact dynamic programming; we provide pseudocode in Section J.1.
There are other ways to approximate the Wasserstein distance in bisimulation metrics ( e.g., Ferns et al., 2006; 2011; Castro, 2020; Zhang et al., 2021).
That said, approximating bisimulation (or PSM) for stochastic environments remains an exciting research direction (Castro, 2020).
Investigating other distance metrics for long-term behavior difference in PSM is also interesting for future work.
D. PSM C ONNECTIONS TO D ATA A UGMENTATION AND B ISIMULATION
Connection to bisimulation .
Although bisimulation metrics have appealing properties such as bounding value function differences ( e.g., (Ferns & Precup, 2014)), they rely on reward information and may not provide a meaningful notion of behavioral similarity in certain environments.
Proposition D.1 implies that states similar under PSM would have similar optimal policies yet can have arbitrarily large bisimulation distance between them. [Figure] y [Figure]
“ Cake ” a 1 , “No Cake” a [Figure] , “Cake” a 1 , r x “ No Cake ” a 0 , aa 0 , r y “ Cake ” a 1 , “No Cake” a 0 , “Cake” a 1 , r y “ No Cake ” a 0 , a Proposition D.1.
There exists environments M X and M Y such that ∀ ( x, y
) ∈ L where L = { ( x, y ) | x ∈ X , y ∈ Y , d [Equation] y
[Equation] − (cid:15) for any given (cid:15) > 0 .
For example, consider the two semantically equivalent environments in Figure D.1 with π ∗X ( x 0 ) =
π ∗Y ( y 0 )
= a 0 and π ∗X ( x 1 ) =
π ∗Y ( y 1 ) =
a 1 but different rewards r x , r y respectively.
Whenever r y > (1 + 1 /γ ) r x , bisimulation metrics incorrectly imply that x 0 is more behaviorally similar to ythan y 0 .
For the MDPs shown in Figure D.1, to determine which y state is behaviorally equivalent to x 0 , we look at the distances computed by bisimulation metric d ∼ and π ∗ -bisimulation metric d ∗∼ :
[Equation]
Thus, r y > (1 + 1 /γ ) r x implies that d ∼ ( x 0 , y 1 ) <
d ∼ ( x 0 , y 0 ) as well as d ∗∼ ( x 0 , y 1 ) < d ∗∼ ( x 0 , y 0 ) .
Connection to data augmentation.
Data augmentation often assumes access to optimality invariant transformations, e.g., random crops or ﬂips in image-based benchmarks (Laskin et al., 2020a;
Kostrikov et al., 2020).
However, for certain RL tasks, such augmentations can erroneously alias states with different optimal behavior and hurt generalization.
For example, if the image observation is ﬂipped in a goal reaching task with left and right actions, the optimal actions would also be ﬂipped to take left actions instead of right and vice versa.
Proposition D.2 states that PSMs can precisely quantify the invariance of such augmentations.
Proposition D.2.
For an MDP M X and its transformed version M ψ ( X ) for the data augmentation ψ , d ∗ ( x, ψ ( x )) indicates the optimality invariance of ψ for any x ∈ X .
D. PSM WITH A PPROXIMATELY -O PTIMAL P OLICIES
Generalized Policy Similarity Metric for arbitrary policies .
For a given D IST , we deﬁne a generalized PSM d : ( S × Π) ×
( S × Π) → R where Π is the set of all policies over S .
d satisﬁes the recursive equation:
[Equation]
Since D IST is assumed to be a pseudometric and W 1 is a probability metric, it implies that d is a pseudometric as (1) d is non-negative, that is, d (cid:0) ( x, π 1 ) , ( y, π 2 ) (cid:1) ≥ 0 , (2) d is symmetric, that is, d (cid:0) ( x, π 1 ) , ( y, π 2 ) (cid:1) =
d (cid:0) ( x, π 1 ) , ( y, π 2 ) (cid:1) , and d satisﬁes the triangle inequality, that is, d (cid:0) ( x, π 1 ) , ( y, π 2 ) (cid:1) <
d (cid:0) ( x, π 1 ) , ( z, π 3 ) (cid:1) + d (cid:0) ( z, π 3 ) , ( y, π 2 ) (cid:1) .
Using this notion of generalized PSM, we show that the approximation error in PSM from using a suboptimal policy is bounded by the policy’s suboptimality.
Thus, for policies with decreasing suboptimality, the PSM approximation becomes more accurate, resulting in improved PSEs.
Proposition D.3.
[Approximation error in PSM] Let ˆ d : S × S
→ R be the approximate PSM computed using a suboptimal policy ˆ π deﬁned over S , that is, ˆ d ( x, y )
=
D IST (cid:0) ˆ π ( x ) , ˆ π ( y ) (cid:1) + γ W 1 ( ˆ d ) (cid:0) P ˆ π ( · | x ) , P ˆ π ( · | y ) (cid:1) .
We have:
[Equation]
Long-term suboptimality difference from x
[Equation]
Long-term suboptimality difference from y .
Proof.
The PSM d ∗ and approximate PSM ˆ d are instantiations of the generalized PSM (Equation D.3) with both input policies as π ∗ and ˆ π respectively. [Equation] [Equation] (cid:1)
[Equation]
(cid:0) ( [Equation] , ˆ π [Equation]
[Equation] , π ∗ ) (cid:1) ∵ ˆ d ( x, y ) =
d (cid:0) ( x, ˆ π ) , ( y, ˆ π ) (cid:1)
Similarly , ˆ d ( x, y ) − d ∗ ( x, y ) <
d (cid:0) ( x, π ∗ ) , ( x, ˆ π ) (cid:1) + d (cid:0) ( y, ˆ π ) , ( y, π ∗ ) (cid:1)
E L2 M ETRIC E MBEDDINGS
Another common choice (Zhang et al., 2021) for learning metric embeddings is to use the squared loss ( i.e., l 2 -loss) for matching the euclidean distance between the representations of a pair of states to the metric distance between those states.
Concretely, for a given d ∗ and representation f θ , the loss L ( θ ) =
E s i ,s j
[( (cid:107) f
θ ( s i ) − f θ ( s j ) (cid:107) 2 − d ∗
s i , s j )) 2 ] is minimized.
However, it might be too restrictive to match the exact metric distances, which we demonstrate empirically by comparing lmetric embeddings with CMEs (Section 5.2).
F E XTENDED R ELATED W ORK
Generalization across different tasks used to be described as transfer learning .
In the past, most transfer learning approaches relied on ﬁxed representations and tackled different problem formulations (e.g., assuming shared state space).
Taylor & Stone (2009) present a comprehensive survey of the techniques at the time, before representation learning became so prevalent in RL.
Recently, the problem of performing well in a different, but related task, started to be seen as a problem of generalization ; with the community highlighting that deep RL agents tend to overﬁt to the environments they are trained on (Cobbe et al., 2019; Witty et al., 2018; Farebrother et al., 2018;
Juliani et al., 2019; Kostrikov et al., 2020; Song et al., 2019; Justesen et al., 2018; Packer et al., 2018).
Prior generalization approaches are typically adapted from supervised learning, including data augmentation, regularization (Cobbe et al., 2019; Farebrother et al., 2018), stochasticity (Zhang et al., 2018c), noise injection (Igl et al., 2019; Zhang et al., 2018a), more diverse training conditions (Rajeswaran et al., 2017; Witty et al., 2018) and self-attention architectures (Tang et al., 2020).
In contrast, PSEs exploits behavior similarity (Section 3), a property related to the sequential aspect of RL.
Furthermore, for certain RL tasks, it can be unclear what an optimality invariant data augmentation would look like (Section 5.3).
PSM can quantify the invariance of such augmentations (Proposition D.2).
Meta-learning is also related to generalization.
Meta-learning methods try to ﬁnd a parametrization that requires a small number of gradient steps to achieve good performance on a new task (Finn et al., 2017).
In this context, various meta-learning approaches capable of zero-shot generalization have been proposed (Li et al., 2018; Agarwal et al., 2019; Balaji et al., 2018).
These approaches typically consist in minimizing the loss in the environments the agent is while adding an auxiliary loss for ensuring improvement in the other (validation) environments available to the agent.
Nevertheless,
Tachet des Combes et al.
(2018) has shown that meta-learning approaches fail in the jumping task which we also observed empirically.
Others have also reported similar ﬁndings (e.g., Farebrother et al., 2018).
There are several other approaches for tackling zero-shot generalization in RL, but they often rely on domain-speciﬁc information.
Some examples include knowledge about equivalences between entities in the environment (Oh et al., 2017) and about what is under the agent’s control (Ye et al., 2020).
Causality-based methods are a different way of tackling generalization, but current solutions do not scale to high-dimensional observation spaces (e.g., Killian et al., 2017; Perez et al., 2020; Zhang et al., 2020).
G J UMPING T ASK WITH P IXELS
[Figure]
Detailed Task Description .
The jumping task consists of an agent trying to jump over an obstacle on a ﬂoor.
The environment is deterministic with the agent observing a reward of +1 at each time step.
If the agent successfully reaches the rightmost side of the screen, it receives a bonus reward of +100 ; if the agent touches the obstacle, the episode terminates.
The observation space is the pixel representation of the environment, as depicted in Figure 1.
The agent has access to two actions: right and jump .
The jump action moves the agent vertically and horizontally to the right.
Architecture .
The neural network used for Jumping Task experiment is adapted from the Nature
DQN architecture.
Speciﬁcally, the network consists of 3 convolutional layers of sizes 32, 64,with ﬁlter sizes 8 × 8 , 4 × 4 and 3 × 3 and strides 4, 2, and 1, respectively.
The output of the convnet is fed into a single fully connected layer of size 256 followed by ’ReLU’ non-linearity.
Finally, this
FC layer output is fed into a linear layer which computes the policy which outputs the probability of the jump and right actions.
Contrastive Embedding .
For all our experiments, we use a single ReLU layer with k = 64 units for the non-linear projection to obtain the embedding z θ (Figure A.1).
We compute the embedding using the penultimate layer in the jumping task network.
Hyperparameters are reported in Table G.2.
Total Loss .
For jumpy world, the total loss is given by L IL + α L CME where L IL is the imitation learning loss, L CME is the auxiliary loss for learning PSEs with the coefﬁcient α . [Figure] [Figure] Bisimulation
[Figure]
[Figure]
y
[Figure]
y [Figure] yyyy PSM 0 .0 .0 .0 .1 .1 .1 .1 .
[Figure]
True Similarity 0 .0 .0 .0 .0 .1 .
[Figure]
[Figure]
G. J UMPING T ASK FROM C OLORS
[Table]
[Figure]
H YPERPARAMETERS
For hyperparameter selection, we evaluate all agents on a validation set containing 54 unseen tasks in the “wide” grid and pick the parameters with the best validation performance.
The validation set (Figure G.7) was selected by using the environments nearby to the training environments whose ﬂoor height differ by 1 or whose obstacle position differ by 1.
[Table]
Adam
Batch size (Imitation)
Num training tasks Γ -scale Parameter ( β ) 0.
Embedding size ( k )
Batch Size ( L CME ) | τ ∗ X | T T T
T
T
T
T
T
T
T
T
T
T
T
T
T T T V
V V V V V
V
V V
V
V V
V
V
V
V
V
V
V V
V V V
V
V
V
V
V
V
V
V
V
V
V
V
V V
V
V V V
V V
V
V
V V
V V
V
V
V V V [Table]
[Table] [Table] Please note that Table G.3 and Table G.4 correspond to two different tasks: one uses the standard jumping task with white obstacles, while the other uses colored obstacles where the optimal policies depend on color.
For fair comparison, we tune hyperparameters for all the methods using Bayesian optimization (Golovin et al., 2017).
We use the best parameters among these tuned hyperparameters and the ones found in Table G.3, leading to different parameters for both PSEs as well as RandConv.
Evaluating PSEs with the jumping task hyperparameters from Table G.3 instead of the ones in
Table G.4 leads to a small drop (-4%) on the jumping task with colors (Section 5.3).
Nevertheless,
PSEs still outperform other methods in Section 5.3.
H LQR: A DDITIONAL D ETAILS
Optimal control with linear dynamics and quadratic cost, commonly known as LQR, has been increasingly used as a simpliﬁed surrogate for deep RL problems (Recht, 2019).
Following Song et al.
(2019); Sonar et al.
(2020), we analyze the following LQR problem for assessing generalization: minimize
[Equation]
subject to
[Equation]
(H.1) where D is the initial state distribution, s t ∈ R n s is the (hidden) true state at time t, a t ∈ R n a is the control action, and K is the linear policy matrix.
The agent receives the input observation o t , which is a linear transformation of the state s t .
W c and W d are semi-orthogonal matrices to prevent information loss for predicting optimal actions.
An environment corresponds to a particular choice
[Table] [Table] of W d ; all other system parameters ( A, B, Q, R, W c ) are ﬁxed matrices which are shared across environments and unknown to the agent.
The agent learns the policy matrix K using N training environments based on Equation H.1.
At test time, the learned policy is evaluated on environments with unseen W d .
The generalization challenge in this setup is to ignore the distractors: W c s t ∈ R n s represents the state features invariant across environments while W d s t ∈ R n d is a high-dimensional distractor of size n s , n d , respectively, such that n s << n d .
Furthermore, the policy matrix which generalizes across all environments is K (cid:63) =
[Equation]
P [Equation] (cid:21) T , where P (cid:63) corresponds to the optimal LQR solution with access to state s t .
However, for a single environment with distractor W d , multiple solutions exist, for instance, K (cid:63) (cid:48) = (cid:20)
[Equation]
∀ α ∈ [0 , 1] .
Note that the distractors are an order of magnitude larger than the invariant features in o t and dependence on them is likely to cause the agent to act erratically on inputs with unseen distractors, resulting in poor generalization.
We use overparametrized policies with two linear layers, i.e., K = K 1 K 2 , where K 1 ( o ) is the learned representation for observation o .
We learn K using gradient descent using the combined cost on 2 training environments with varying number of distractors.
We aggregate observation pairs with near-zero PSM by matching their representations using a squared loss.
We use the open-source code released by Sonar et al.
(2020) for our experiments.
[Table]
The reliance on distractors for IPO also highlights a limitation of IRM: if a model can achieve a solution with zero training error, then any such solution is acceptable by IRM regardless of its generalization ability – a common scenario with overparametrized deep neural nets (Jin et al., 2020).
H. N EAR - OPTIMALITY OF PSM A GGREGATION
Conjecture 1.
Assuming zero state aggregation error with policy similarity metric (PSM), the policy matrix K learned using gradient descent is independent of the distractors.
Proof.
For LQR domains x, y , an observation pair ( o tx , o ty ) has zero PSM iff the underlying state s t is same for both the observations in the pair.
This is true, as (a) both domains has the same transition dynamics, as speciﬁed by Equation H.1, and (b) the optimal policy is deterministic and is completely determined by the current state s t at any time t .
Assume o tx =
(cid:20) 0 .
[Equation]
W
[Equation]
W d x (cid:21) s t and o ty =
(cid:20)
[Equation] [Equation] W [Equation]
W d y (cid:21) s t for distractor semi-orthogonal matrices W d X and
W d Y , respectively.
Furthermore, the representation is given by K 1 ( o tx ) and K 1 ( o ty ) respectively.
Assume that K 1 =
[ K s
K d ] where K s ∈ R h × n s and K d ∈ R h × n d and K 1 ∈ R h × ( n s + n d ) .
Zero state-aggregation error with squared loss implies that for pair ( o tx , o ty ) corresponding to s t ,
[Equation]
As Equation H.2 holds for all states visited by the optimal policy in an inﬁnite horizon LQR, it follows that K d ( W d x − W d y ) = 0 .
Furthermore, it is well-known that gradient descent tends to ﬁnd low-rank solutions due to implicit regularization (Arora et al., 2019; Gunasekar et al., 2017), e.g., with small enough step sizes and initialization close enough to the origin, gradient descent on matrix factorization converges to the minimum nuclear norm solution for 2 layer linear networks (Gunasekar et al., 2017).
Based on this, we conjecture that K d = 0 which we found to be true in practice.
I D ISTRACTING C ONTROL S UITE
We use the same setup as Kostrikov et al.
(2020); Stone et al.
(2021) for implementation details and training protocol.
For completeness, we describe the details below.
Dynamic Background Distractions .
In Distracting Control Suite (Stone et al., 2021), random backgrounds are projected from scenes of the DAVIS 2017 dataset (Pont-Tuset et al., 2017) onto the skybox of the scene.
To make these backgrounds visible for all tasks and views, the ﬂoor grid is semi-transparent with transparency coefﬁcient 0.3.
We take the ﬁrst 2 videos in the DAVIStraining set and randomly sample a scene and a frame from those at the start of every episode.
In the dynamic setting, the video plays forwards or backwards until the last or ﬁrst frame is reached at which point the video is played backwards.
This way, the background motion is always smooth and without “cuts”.
Soft Actor-Critic .
Soft Actor-Critic (SAC) (Haarnoja et al., 2018) learns a state-action value function
Q θ , a stochastic policy π θ and a temperature α to ﬁnd an optimal policy for an MDP ( S , A , p, r, γ ) by optimizing a γ -discounted maximum-entropy objective.
θ is used generically to denote the parameters updated through training in each part of the model.
The actor policy π θ ( a t | s t ) is a parametric tanhGaussian that given s t samples a t = tanh( µ θ ( s t )
+ σ θ ( s t ) (cid:15) ) , where (cid:15) ∼ N (0 , 1) and µ θ and σ θ are parametric mean and standard deviation.
The policy evaluation step learns the critic Q θ ( s t , a t ) network by optimizing a single-step of the soft
Bellman residual
[Equation]
where D is a replay buffer of transitions, θ (cid:48) is an exponential moving average of the weights.
SAC uses clipped double-Q learning, which we omit for simplicity but employ in practice.
The policy improvement step then ﬁts the actor policy π θ ( a t | s t ) network by optimizing the objective
[Equation]
Finally, the temperature α is learned with the loss
[Equation]
where ¯ H ∈ R is the target entropy hyper-parameter that the policy tries to match, which in practice is usually set to ¯ H = −|A| .
I. A CTOR AND C RITIC N ETWORKS
Following Kostrikov et al.
(2020), we use clipped double Q-learning for the critic,
where each
Q -function is parametrized as a 3-layer MLP with ReLU activations after each layer except of the last.
The actor is also a 3-layer MLP with ReLU s that outputs mean and covariance for the diagonal
Gaussian that represents the policy.
The hidden dimension is set to 1024 for both the critic and actor.
I. E NCODER N ETWORK
We employ the encoder architecture from Kostrikov et al.
This encoder consists of four convolution layers with 3 × 3 kernels and 32 channels.
The ReLU activation is applied after each convolutional layer.
We use stride to 1 everywhere, except of the ﬁrst convolutional layer, which has stride 2 .
The output of the convnet is feed into a single fully-connected layer normalized by LayerNorm .
Finally, we apply tanh nonlinearity to the 50 dimensional output of the fullyconnected layer.
We initialize the weight matrix of fully-connected and convolutional layers with the orthogonal initialization and set the bias to be zero.
The actor and critic networks both have separate encoders, although we share the weights of the conv layers between them.
Furthermore, only the critic optimizer is allowed to update these weights ( i.e., we stop the gradients from the actor before they propagate to the shared convolutional layers).
I. C ONTRASTIVE M ETRIC E MBEDDING L OSS
For all our experiments, we use a single ReLU layer with k = 256 units for the non-linear projection to obtain the embedding z θ (Figure A.1).
We compute the embedding using the penultimate layer in the actor network.
For picking the hyperparameters, we used 3 temperatures [0 . 1 , 0 .
01 , 1 . 0] andauxiliary L CME loss coefﬁcients [1 , 3 , 10] using “Ball In Cup Catch” as the validation environment.
All other hyperparameters are the same as prior work (see Table I.2).
We approximate optimal policies with the policies obtained after training a DrQ agent for 500K environment steps.
Since a given action sequence from this approximate policy has the same performance across different training environments, we compute the PSM across training environments, via dynamic programming (see Section J.1 for pseudo-code), using such action sequences.
Total Loss .
The total loss is given by L RL + α L CME where L RL is the reinforcement learning loss which combines J π ( D ) , J π ( D ) , and J α ( D ) ), while L CME is the auxiliary loss for learning PSEs with the coefﬁcient α .
I. T RAINING AND E VALUATION S ETUP
For evaluation, we use the ﬁrst 30 videos from the DAVIS 2017 validation dataset (see Figure I.1).
Each checkpoint is evaluated by computing the average episode return over 100 episodes from the unseen environments.
All experiments are performed with ﬁve random seeds per task used to compute means and standard deviations/errors of their evaluations.
We use K = 2 , M = 2 as prescribed by Kostrikov et al.
(2020) for DrQ.
Following Kostrikov et al.
(2020) and Stone et al.
(2021), we use a different action repeat hyper-parameter for each task, which we summarize in Table I.3.
We construct an observational input as a 3 -stack of consecutive frames (Kostrikov et al., 2020), where each frame is an RGB rendering of size 84 × 84 from the 0 th camera.
We then divide each pixel by 255 to scale it down to [0 , 1] range.
For data augmentation, we maintain temporal consistency by using the same crop augmentation across consecutive frames.
[Table]
[Table] [Table] [Figure] [Table]
[Figure]
[Table]
I. G ENERALIZATION C URVES
[Figure]
R e t u
[Figure]
n
[Figure]
[Figure]
J
P
SEUDO
CODE
J. D YNAMIC P ROGRAMMING FOR C OMPUTING PSM
1 def metric_fixed_point(cost_matrix, gamma=0.99, eps=1e-7): """DP for
calculating PSM in environments with deterministic dynamics
[Figure] cost_matrix: DIST matrix where entries at index (i, j) is DIST , y_ ) gamma: Metric discount factor.
eps: point iteration.
""" d np.zeros_like(cost_ ) def operator(d_cur): d_new =
* cost_matrix discounted_d_cur = gamma * d_cur d_new[:-1, :-1] += discounted_d_cur[1:, 1:] d_new[:-1, -1] += discounted_d_cur[1:, -1] d_new[-1, :-1]
+= discounted_d_cur[-1, 1:] return d_new 17while
True: d_new = operator(d) if np.sum(np.abs(d - d_new)) <
eps: break else: d = d_new
[:] return d
J. C ONTRASTIVE L OSS
beta=1.0): """Contrative Loss with embedding similarity ."
"" metric_shape = tf.shape(metric_values) ## z_\theta(X): embedding_1 = nn_model.representation(X)
## z_\theta(Y): embedding_2 = nn_model.representation(Y)
## similarity_matrix = cosine_similarity(embedding_1, embedding_  ## metric_values =
PSM(X, Y) similarity_matrix
/= temperature neg_logits
= similarity_matrix
13col_indices = tf.cast(tf.argmin(metric_values, axis=1), dtype=tf.int32) [-pos_indices
-]pos_indices1 =
.stack( (tf range(metric_shape[0], dtype=tf.int32), col_indices), axis=1) pos_logits1 =
tf.gather_nd(similarity_matrix, pos_indices1) 18metric_values /= beta similarity_measure = tf.exp(-metric_values)
pos_weights1 =
-tf.gather_nd(metric_values, pos_indices1)
pos_logits1 += _weights  negative_weights = tf.math.log((1.0 - similarity_measure) + neg_logits1 += tf.tensor_scatter_nd_update
( negative_weights, pos_indices1, pos_weights1) 26neg_logits1 = tf.math.reduce_logsumexp(neg_logits1, axis=1) return tf.reduce_mean(neg_logits1 - pos_logits1)
# Equationa