Contrastive Behavioral Similarity Embeddings for Generalization in Reinforcement Learning

Rishabh Agarwal, Marlos C. Machado, Pablo Samuel Castro, Marc G. Bellemare

Introduction

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 jumping tasks with different obstacle positions struggle to successfully jump in 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.

Specifically, inspired by bisimulation metrics (Castro, 2020; Ferns et al., 2004), we propose a novel policy similarity metric (PSM). PSM (Section 3) defines 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 fixed 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 field has been tackling generalization. We illustrate the efficacy and broad applicability of our approach on three existing benchmarks specifically 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) (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; Laskin et al., 2020a; Lee et al., 2020a).

Preliminaries

We are interested in learning a policy that generalizes across related environments. We formalize this by considering a collection ρ\rho of MDPs, sharing an action space A{\mathcal{A}} but with disjoint state spaces. We use X{\mathcal{X}} and Y{\mathcal{Y}} to denote the state spaces of specific environments, and write RXR_{\mathcal{X}}, PXP_{\mathcal{X}} for the reward and transition functions of the MDP whose state space is X{\mathcal{X}}, and πX∗\pi^{*}_{{\mathcal{X}}} for its optimal policy, which we assume unique without loss of generality. For a given policy π\pi, we further specialize these into RXπR^{\pi}_{{\mathcal{X}}} and PXπP^{\pi}_{{\mathcal{X}}}, the reward and state-to-state transition dynamics arising from following π\pi in that MDP.

In our setting, the learner has access to a collection of training MDPs {Mi}i=1N\{{\mathcal{M}}_{i}\}_{i=1}^{N}, drawn from ρ\rho. After interacting with these environments, the learner must produce a policy π\pi over the entire state space S{\mathcal{S}}, which is then evaluated on unseen MDPs from ρ\rho. Similar in spirit to the setting of transfer learning (Taylor & Stone, 2009), here we evaluate the policy’s zero-shot performance on ρ\rho.

Policy Similarity Metric

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 π\pi-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 2) or too permissive (when the policies are different, but the obtained rewards are not; see Figure 5(a)). In fact, π\pi-bisimulation metrics actually lead to poor generalization in our experiments (Sections 5.1 and 5.2).

The Dist term captures the difference in local optimal behavior (A) while W1{\mathcal{W}}_{1} captures long-term optimal behavior difference (B); the exact weights assigned to the two are given by the discount factor. Furthermore, when Dist is bounded, d∗d^{*} is guaranteed to be finite. While there are technically multiple PSMs (one for each Dist), we omit this distinction whenever clear from context. A proof of the uniqueness of d∗d^{*} is given in Proposition A.1.

Our main use of PSM will be to compare states across environments. In this context, we identify the terms in Equation 3 with specific environments for clarity and write (despite its technical inaccuracy)

Learning Contrastive Metric Embeddings

To generalize a learned policy to new environments, we build on the success of contrastive representations (Section 2). Given a state similarity metric dd, we develop a general procedure (Algorithm 1) to learn contrastive metric embeddings (CMEs) for dd. We utilize the metric dd for defining the set of positive and negative pairs, as well as assigning importance weights to these pairs in the contrastive loss (Equation 44).

We first apply a transformation to convert dd to a similarity measure Γ\Gamma, bounded in for “soft” similarities. In this work, we transform dd using the Gaussian kernel with a positive scale parameter β\beta, that is, Γ(x,y)=exp⁡(−d(x,y)/β)\Gamma(x,y)=\exp(-d(x,y)/\beta). β\beta controls the sensitivity of the similarity measure to dd.

where we use the same notation as in Equation 2. Following SimCLR, we use a non-linear projection of the representation as zθz_{\theta} (Figure 3). The agent’s policy is an affine function of the representation.

The total contrastive loss for MX{\mathcal{M}}_{{\mathcal{X}}} and MY{\mathcal{M}}_{{\mathcal{Y}}} utilizes the optimal trajectories τX∗={xt}t=1N\tau^{*}_{\mathcal{X}}=\{x_{t}\}_{t=1}^{N} and τY∗={yt}t=1N\tau^{*}_{\mathcal{Y}}=\{y_{t}\}_{t=1}^{N}, where xt+1∼PXπ∗(⋅ ∣ xt)x_{t+1}\sim P^{\pi^{*}}_{\mathcal{X}}(\cdot\,|\,x_{t}) and yt+1∼PYπ∗(⋅ ∣ yt)y_{t+1}\sim P^{\pi^{*}}_{\mathcal{Y}}(\cdot\,|\,y_{t}). We set X′=τX∗{\mathcal{X}}^{\prime}=\tau^{*}_{\mathcal{X}} and define

Jumping Task from Pixels: A Case Study

Task Description. The jumping task (Tachet des Combes et al., 2018) (Figure 1) captures, using well-defined 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 precisely, at a specific distance from the obstacle, otherwise it will eventually hit the obstacle. Different tasks consist in shifting the floor height and/or the obstacle position. To generalize, the agent needs to be invariant to the floor height while jump based on the obstacle position. The obstacle can be in 26 different locations while the floor 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 examplesWe have 18 different trajectories with several examples for the action right, but only one instance of jump action per trajectory, leading to just 18 total instances of the action jump. results in a highly unbalanced classification 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 configurations (Figure 4) 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 4(a)) and pick the parameters with the best validation performance. We use these fixed parameters for all grid configurations to show the robustness of PSEs to hyperparameter tuning. We first compute the optimal trajectories in the training tasks. Using these trajectories, we compute PSM using dynamic programming (Section C.1). We train the agent by imitation learning, combined with an auxiliary loss for PSEs (Section 4). More details are in Section F.

We show the efficacy 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.

We first 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 4 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 impracticalBisimulation transfer assumes oracle access to dynamics and rewards on unseen environments as well as tabular state space to compute the exact bisimulation metric (Section B). when evaluating zero-shot generalization, we still performed this comparison, unfair to PSEs, to highlight their efficacy. PSEs perform better because, in contrast to bisimulation, PSM is reward agnostic (c.f. Proposition C.1) – the expected return of the jump action is quite different depending on the obstacle position (c.f. Figure F.2 for a visual juxtaposition of PSM and bisimulation). 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-specific augmentation also succeeds in the jumping task. Thus, it is not surprising that RandConv is so effective compared to techniques without augmentation. Table 1 (2nd2^{nd} row) shows that PSEs substantially improve the performance of RandConv across all grid configurations. Moreover, Table 1 (2nd2^{nd} row) illustrates that when combined with RandConv, bisimulation preserving representations (Zhang et al., 2021) diminish generalization by 30−50%30-50\% relative to PSEs.

Notably, Table 1 (1st1^{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.

2 Understanding gains from PSEs: Ablations and Visualizations

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

3 Effect of Policy Suboptimality on PSEs

To understand the sensitivity of learning effective PSEs to the quality of the policies, we compute PSEs using ϵ\epsilon-suboptimal policies on the jumping task, which take the optimal action with probability 1−ϵ1-\epsilon and the subopotimal action with probability ϵ\epsilon.

We evaluate the generalization performance of PSEs for increasingly suboptimal policies, ranging from the optimal policy (ϵ=0\epsilon=0) to the uniform random policy (ϵ=0.5\epsilon=0.5). To isolate the effect of suboptimality on PSEs, the agent still imitates the optimal actions during training for all ϵ\epsilon.

Figure 6 shows that PSEs show near-optimal generalization with ϵ≤0.4\epsilon\leq 0.4 while degrade generalization with an uniform random policy. This result is well-aligned with Proposition C.3, which shows that for policies with decreasing suboptimality, the PSM approximation becomes more accurate, resulting in improved PSEs. Overall, this study confirms 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.

4 Jumping Task with Colors: Where Task-dependent Invariance Matters

The task-dependent invariances captured by PSEs are usually orthogonal to task-agnostic invariances from data augmentation. This difference is important because, for certain RL tasks, data augmentation can erroneously alias states with different optimal behavior. Domain knowledge is often required to select appropriate augmentations, otherwise augmentations can even 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 F.5). In this modified 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 difficulty as the original jumping task while the green obstacle task is easier. We jointly train the agent with 18 training tasks each, for both obstacle colors, on the “wide” grid and evaluate generalization on unseen red tasks.

Figure 7 shows the large performance gap between PSEs and data augmentation with RandConv. All methods solve the green obstacle tasks (Table F.1). As opposed to the original jumping task (c.f. Table 1), data augmentation inhibits generalization since RandConv forces the agent to ignore color, conflating the red and green tasks (Figure F.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.

Additional Empirical Evaluation

In this section, 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 with continuous actions, using Distracting DM Control Suite (Stone et al., 2021).

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 feature-based 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 using 2 environments with fixed distractors. This policy is evaluated on environments with unseen distractors.

All methods optimally solve the training environments; however, the baselines perform abysmally in terms of generalization compared to state aggregation with PSM (Figure 8), indicating their reliance on distractors. PSM obtains near-optimal generalization which we corroborate through this conjecture (Section G.1): Assuming zero state aggregation error with PSM, the policy learned using gradient descent is independent of the distractors. Refer to Section G for a detailed discussion.

2 Distracting DM Control Suite

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 π∗\pi^{*} for computing PSM as well as collecting data for optimizing PSEs. Even with this approximation, PSEs outperform state-of-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 specific frame. The video and the frame are randomly sampled every new episode. We use 2 videos during training (Figure 9) and evaluate generalization on 30 unseen videos (Figure H.1).

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

Related Work

PSM (Section 3) is inspired by bisimulation metrics (Section B). However, different than traditional bisimulation (e.g., Larsen & Skou, 1991; Givan et al., 2003; Ferns et al., 2011), PSM is more tractable as it defined with respect to a single policy similar to the recently proposed π∗\pi^{*}-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 π∗\pi^{*}-bisimulation distance between them (Proposition C.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. (2020); 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 significantly 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. Furthermore, for certain RL tasks, it can be unclear what an optimality invariant augmentation would look like (Section 5.4). PSM can quantify the invariance of such augmentations (Proposition C.2).

Conclusion

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 benefits of contrastive learning for representations based on a similarity metric. PSEs combine these two ideas to improve generalization. Overall, this paper shows the benefits of exploiting the inherent structure in RL for learning effective representations.

References

Appendix

We begin by defining some notation which will be used throughout these results:

We now proceed with some technical lemmas necessary for the main result.

Note that the dual of the linear program for computing W1(d)(PX,PY){\mathcal{W}}^{1}(d)(P_{\mathcal{X}},P_{\mathcal{Y}}) is given by

Using the dual formulation subject to the constraints above, W1(d){\mathcal{W}}^{1}(d) can be written as

Note that we have the following equality, where 0\mathbf{0} is a vector of zeros:

is a contraction mapping and has a unique fixed point for a bounded distdist.

Thus, ∥F(d)−F(d′)∥≤γ∥d−d′∥\|{\mathcal{F}}(d)-{\mathcal{F}}(d^{\prime})\|\leq\gamma\|d-d^{\prime}\|, so that F{\mathcal{F}} is a contracting mapping for γ<1\gamma<1 and has an unique fixed point d∗d^{*}. ∎

Let Ptπ(y′∣y)P^{\pi}_{t}(y^{\prime}|y) denote the probability of ending in state y′∈Yy^{\prime}\in Y after tt steps when following policy π\pi and starting from state yy. We then have:

Thus, by induction, it follows that for all nn:

Appendix B Bisimulation metrics

Notation. We use the notation as defined in Section 2.

Since we are only interested in computing the coupling between the states in X{\mathcal{X}} and Y{\mathcal{Y}}, the above formulation assumes that PX(y)=0P_{\mathcal{X}}(y)=0 for all y∈Yy\in{\mathcal{Y}} and PY(x)=0P_{\mathcal{Y}}(x)=0 for all x∈Xx\in{\mathcal{X}}. The computation of d∼d_{\sim} is expensive and requires a tabular representation of the states, rendering it impractical for large state spaces. On-policy bisimulation (Castro, 2020) (e.g., π∗\pi^{*}-bisimulation) is tied to specific behavior policies and is much easier to approximate than bisimulation.

Appendix C Policy Similarity Metric

In general, PSM for a given Dist across MDPs MX{\mathcal{M}}_{\mathcal{X}} and MY{\mathcal{M}}_{\mathcal{Y}} is given by

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∗d^{*} takes the following form in deterministic environments:

where x′=PXπ∗(x)x^{\prime}=P^{\pi^{*}}_{\mathcal{X}}(x), y′=PYπ∗(y)y^{\prime}=P^{\pi^{*}}_{\mathcal{Y}}(y) are the next states from taking actions πX∗(x)\pi^{*}_{{\mathcal{X}}}(x), πX∗(y)\pi^{*}_{{\mathcal{X}}}(y) from states x, yx,\ y respectively. Furthermore, we assume that Dist between terminal states from MX{\mathcal{M}}_{\mathcal{X}} and MY{\mathcal{M}}_{\mathcal{Y}} is zero. Note that the form of Equation C.2 closely resembles the update rule in Q-learning, and as such, can be efficiently computed with samples using approximate dynamic programming. Given access to optimal trajectories τX∗={xt}t=1N\tau^{*}_{\mathcal{X}}=\{x_{t}\}_{t=1}^{N} and τY∗={yt}t=1N\tau^{*}_{\mathcal{Y}}=\{y_{t}\}_{t=1}^{N}, where xt+1=PXπ∗(xt)x_{t+1}=P^{\pi^{*}}_{\mathcal{X}}(x_{t}) and yt+1=PYπ∗(yt)y_{t+1}=P^{\pi^{*}}_{\mathcal{Y}}(y_{t}), Equation C.2 can be solved using exact dynamic programming; we provide pseudocode in Section I.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.

C.2 PSM Connections to Data Augmentation and Bisimulation

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 C.1 implies that states similar under PSM would have similar optimal policies yet can have arbitrarily large bisimulation distance between them.

For example, consider the two semantically equivalent environments in Figure 2 with πX∗(x0)=πY∗(y0)=a0\pi^{*}_{\mathcal{X}}(x_{0})=\pi^{*}_{\mathcal{Y}}(y_{0})=a_{0} and πX∗(x1)=πY∗(y1)=a1\pi^{*}_{\mathcal{X}}(x_{1})=\pi^{*}_{\mathcal{Y}}(y_{1})=a_{1} but different rewards rx,ryr_{x},r_{y} respectively. Whenever ry>(1+1/γ) rxr_{y}>(1+1/\gamma)\ r_{x}, bisimulation metrics incorrectly imply that x0x_{0} is more behaviorally similar to y1y_{1} than y0y_{0}.

For the MDPs shown in Figure 2, to determine which yy state is behaviorally equivalent to x0x_{0}, we look at the distances computed by bisimulation metric d∼d_{\sim} and π∗\pi^{*}-bisimulation metric d∼∗d^{*}_{\sim}:

Thus, ry>(1+1/γ) rxr_{y}>(1+1/\gamma)\ r_{x} implies that d∼(x0,y1)<d∼(x0,y0)d_{\sim}(x_{0},y_{1})<d_{\sim}(x_{0},y_{0}) as well as d∼∗(x0,y1)<d∼∗(x0,y0)d^{*}_{\sim}(x_{0},y_{1})<d^{*}_{\sim}(x_{0},y_{0}).

Connection to data augmentation. Data augmentation often assumes access to optimality invariant transformations, e.g., random crops or flips 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 flipped in a goal reaching task with left and right actions, the optimal actions would also be flipped to take left actions instead of right and vice versa. Proposition C.2 states that PSMs can precisely quantify the invariance of such augmentations.

For an MDP MXM_{\mathcal{X}} and its transformed version Mψ(X)M_{\psi({\mathcal{X}})} for the data augmentation ψ\psi, d∗(x,ψ(x))d^{*}(x,\psi(x)) indicates the optimality invariance of ψ\psi for any x∈Xx\in{\mathcal{X}}.

C.3 PSM with Approximately-Optimal Policies

Since Dist is assumed to be a pseudometric and W1{\mathcal{W}}_{1} is a probability metric, it implies that dd is a pseudometric as (1) dd is non-negative, that is, d\big{(}(x,\pi_{1}),(y,\pi_{2})\big{)}\geq 0, (2) dd is symmetric, that is, d\big{(}(x,\pi_{1}),(y,\pi_{2})\big{)}=d\big{(}(x,\pi_{1}),(y,\pi_{2})\big{)}, and dd satisfies the triangle inequality, that is, d\big{(}(x,\pi_{1}),(y,\pi_{2})\big{)}<d\big{(}(x,\pi_{1}),(z,\pi_{3})\big{)}+d\big{(}(z,\pi_{3}),(y,\pi_{2})\big{)}. 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.

The PSM d∗d^{*} and approximate PSM d^\hat{d} are instantiations of the generalized PSM (Equation C.3) with both input policies as π∗\pi^{*} and π^\hat{\pi} respectively.

Appendix D L2 Metric Embeddings

Appendix E Extended Related Work

Generalization across different tasks used to be described as transfer learning. In the past, most transfer learning approaches relied on fixed 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 overfit 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 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.

Meta-learning is also related to generalization. Meta-learning methods try to find 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 findings (e.g., Farebrother et al., 2018).

There are several other approaches for tackling zero-shot generalization in RL, but they often rely on domain-specific 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).

Appendix F Jumping Task with Pixels

Detailed Task Description. The jumping task consists of an agent trying to jump over an obstacle on a floor. The environment is deterministic with the agent observing a reward of +1+1 at each time step. If the agent successfully reaches the rightmost side of the screen, it receives a bonus reward of +100+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. Specifically, the network consists of 3 convolutional layers of sizes 32, 64, 64 with filter sizes 8×88\times 8, 4×44\times 4 and 3×33\times 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=64k=64 units for the non-linear projection to obtain the embedding zθz_{\theta} (Figure 3). We compute the embedding using the penultimate layer in the jumping task network. Hyperparameters are reported in Table F.2.

F.2 Hyperparameters

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 F.7) was selected by using the environments nearby to the training environments whose floor height differ by 1 or whose obstacle position differ by 1.

Please note that Table F.3 and Table F.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 F.3, leading to different parameters for both PSEs as well as RandConv. Evaluating PSEs with the jumping task hyperparameters from Table F.3 instead of the ones in Table F.4 leads to a small drop (-4%) on the jumping task with colors (Section 5.4). Nevertheless, PSEs still outperform other methods in Section 5.4.

Appendix G LQR: Additional Details

Optimal control with linear dynamics and quadratic cost, commonly known as LQR, has been increasingly used as a simplified 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:

We use overparametrized policies with two linear layers, i.e., K=K1K2K=K_{1}K_{2}, where K1(o)K_{1}(o) is the learned representation for observation oo. We learn KK 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.

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

Assuming zero state aggregation error with policy similarity metric (PSM), the policy matrix KK learned using gradient descent is independent of the distractors.

For LQR domains x,yx,y, an observation pair (otx{o_{t}}^{x}, oty{o_{t}}^{y}) has zero PSM iff the underlying state sts_{t} is same for both the observations in the pair. This is true, as (a) both domains has the same transition dynamics, as specified by Equation G.1, and (b) the optimal policy is deterministic and is completely determined by the current state sts_{t} at any time tt.

Zero state-aggregation error with squared loss implies that for pair (otx{o_{t}}^{x}, oty{o_{t}}^{y}) corresponding to sts_{t},

As Equation G.2 holds for all states visited by the optimal policy in an infinite horizon LQR, it follows that Kd(Wdx−Wdy)=0K_{d}(W_{d^{x}}-W_{d^{y}})=0.

Furthermore, it is well-known that gradient descent tends to find 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 Kd=0K_{d}=0 which we found to be true in practice. ∎

Appendix H Distracting Control Suite

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 floor grid is semi-transparent with transparency coefficient 0.3. We take the first 2 videos in the DAVIS 2017 training 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 first frame is reached at which point the video is played backwards. This way, the background motion is always smooth and without “cuts”.

The policy evaluation step learns the critic Qθ(st,at)Q_{\theta}(s_{t},a_{t}) network by optimizing a single-step of the soft Bellman residual

where D{\mathcal{D}} is a replay buffer of transitions, θ′\theta^{\prime} 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 fits the actor policy πθ(at∣st)\pi_{\theta}(a_{t}|s_{t}) network by optimizing the objective

Finally, the temperature α\alpha is learned with the loss

Following Kostrikov et al. (2020), we use clipped double Q-learning for the critic, where each QQ-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 ReLUs that outputs mean and covariance for the diagonal Gaussian that represents the policy. The hidden dimension is set to 10241024 for both the critic and actor.

H.2 Encoder Network

We employ the encoder architecture from Kostrikov et al. (2020). This encoder consists of four convolution layers with 3×33\times 3 kernels and 3232 channels. The ReLU activation is applied after each convolutional layer. We use stride to 11 everywhere, except of the first convolutional layer, which has stride 22. The output of the convnet is feed into a single fully-connected layer normalized by LayerNorm. Finally, we apply tanh nonlinearity to the 5050 dimensional output of the fully-connected 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).

H.3 Contrastive Metric Embedding Loss

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 I.1 for pseudo-code), using such action sequences.

H.4 Training and Evaluation Setup

For evaluation, we use the first 30 videos from the DAVIS 2017 validation dataset (see Figure H.1). Each checkpoint is evaluated by computing the average episode return over 100 episodes from the unseen environments. All experiments are performed with five random seeds per task used to compute means and standard deviations/errors of their evaluations. We use K=2,M=2K=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 H.3. We construct an observational input as a 33-stack of consecutive frames (Kostrikov et al., 2020), where each frame is an RGB rendering of size 84×8484\times 84 from the th camera. We then divide each pixel by 255255 to scale it down to $$ range. For data augmentation, we maintain temporal consistency by using the same crop augmentation across consecutive frames.

H.5 Generalization Curves

Appendix I Pseudo code

I.2 Contrastive Loss