1 Introduction
Imagine that a month ago Alice had two job offers from companies and . She decided to join because of the larger salary, in spite of an awkward feeling during the job interview. Since then she learned a lot about and recently received information about from a friend, prodding her now to imagine what would have happened had she joined . Reevaluating her decision in hindsight in this way, she concludes that she made a regrettable decision. She could and should have known that was a better choice, had she only interpreted the cues during the interview correctly… This example tries to illustrate the everyday human capacity to reason about alternate, counterfactual outcomes of past experience with the goal of “mining worlds that could have been” (Pearl & Mackenzie, 2018). Social psychologists theorize that such cognitive processes are beneficial for improving future decision making (Roese, 1997). In this paper we aim to leverage possible advantages of counterfactual reasoning for learning decision making in the reinforcement learning (RL) framework.
In spite of recent success, learning policies with standard, modelfree RL algorithms can be notoriously data inefficient. This issue can in principle be addressed by learning policies on data synthesized from a model. However, a mismatch between the model and the true environment, often unavoidable in practice, can cause this approach to fail (Talvitie, 2014), resulting in policies that do not generalize to the real environment (Jiang et al., 2015). Motivated by the introductory example, we propose the CounterfactuallyGuided Policy Search (CFGPS) algorithm: Instead of relying on data synthesized from scratch by a model, we train policies on model predictions of alternate outcomes of past experience from the true environment under counterfactual actions, i.e. actions that had not actually been taken, while everything else remaining the same (Pearl, 2009). At the heart of CFGPS are structural causal models (SCMs) which model the environment with two ingredients (Wright, 1920)
: 1) Independent random variables, called
scenarios here, summarize all aspects of the environment that cannot be influenced by the agent, e.g. the properties of the companies in Alice’s job search example. 2) Deterministic transition functions (also called causal mechanisms) take these scenarios, together with the agent’s actions, as input and produce the predicted outcome. The central idea of CFGPS is that, instead of running an agent on scenarios sampled de novo from a model, we infer scenarios in hindsight from given offpolicy data, and then evaluate and improve the agent on these specific scenarios using given or learned causal mechanisms (Balke & Pearl, 1994). We show that CFGPS generalizes and empirically improves on a vanilla modelbase RL algorithm, by mitigating model mismatch via “grounding” or “anchoring” modelbased predictions in inferred scenarios. As a result, this approach explicitly allows to tradeoff historical data for model bias. CFGPS differs substantially from standard offpolicy RL algorithms based on Importance Sampling (IS), where historical data is reweighted with respect to the importance weights to evaluate or learn new policies (Precup, 2000). In contrast, CFGPS explicitly reasons counterfactually about given offpolicy data. Our main contributions are:
We formulate modelbased RL in POMDPs in terms of structural causal models, thereby connecting concepts from reinforcement learning and causal inference.

We provide the first results, to the best of our knowledge, showing that counterfactual reasoning in structural causal models on offpolicy data can facilitate solving nontrivial RL tasks.
The paper is structured as follows. We first give a selfcontained, highlevel recapitulation of structural causal models and counterfactual inference, as these are less widely known in the RL and generative model communities. In particular we show how to model POMDPs with SCMs. Based on this exposition, we first consider the task of policy evaluation and discuss how we can leverage counterfactual inference in SCMs to improve over naive modelbased methods. We then generalize this approach to the policy search setting resulting in the CFGPS algorithm. We close by highlighting connections to previously proposed algorithms and by discussing assumptions and limitations of the proposed method.
2 Preliminaries
We denote random variables (RVs) with capital letters, e.g. , and particular values with lower caps, e.g. . For a distribution
over a vectorvalued random variable
, we denote the marginal over by (and density ); however we often omit the subscript if it is clear from the context, e.g. as in. We assume the episodic, Partially Observable Markov Decision Process (POMDP) setting with states
, actions and observations , for . For ease of notation, we assume that includes the reward . The undiscounted return is denoted by . We consider stochastic policies over actions conditioned on observation histories . We denote the resulting distribution over trajectories induced by running in the environment with and the corresponding density by .2.1 Structural Causal Models
Definition 1 (Structural causal model).
A structural causal model (SCM) over is given by a DAG over nodes , independent noise RVs with distributions and functions such that , where are the parents of in . An SCM entails a distribution with density over .
We also refer to as scenarios and to as causal mechanisms. We give a (broad) definition of an intervention in an SCM. This also includes what is known as stochastic interventions or mechanism changes (Korb et al., 2004) which generalize atomic interventions (Pearl, 2009).
Definition 2 (Intervention in SCM).
An intervention in an SCM consists of replacing some of the original with other functions where are the parents in a new DAG . We denote the resulting SCM with with distribution and density .
SCM representation of POMDPs
We can represent any given POMDP (under a policy ) by an SCM over trajectories in the following way. We express all conditional distributions, e.g. the transition kernel , as deterministic functions with independent noise variables , such as . This is always possible using autoregressive uniformization, see Lemma 2 in the appendix. The DAG of the resulting SCM is shown in fig. 1. This procedure is closely related to the ‘reparameterization trick’ for models with locationscale distributions (Kingma & Welling, 2013; Rezende et al., 2014). We denote the distribution over entailed by the SCM with and its density by to highlight the role of ; note the difference to the true environment distribution with density . Running a different policy instead of in the environment can be expressed as an intervention consisting of replacing by . We denote the resulting model distribution over trajectories with (analogously ).
Intuition
Here, we illustrate the main advantage of SCMs using the example of Alice’s job choice from the introduction. We model it as contextual bandit with feedback shown in fig. 1. Alice has some initial knowledge given by the context that is available to her before taking action of joining company or . We model Alice’s decision as , where captures potential indeterminacy in Alice’s decision making. The outcome also depends on the scenario , capturing all relevant, unobserved and highly complex properties of the two companies such as working conditions etc. Given this model, we can reason about alternate outcomes and for same the scenario . This is not possible if we only model the outcome on the level of the conditional distribution
2.2 Counterfactual inference in SCMs
For an SCM over , we define a counterfactual query as a triple of observations of some variables , an intervention and query variables . The semantics of the query are that, having observed , we want to infer what would have been had we done intervention , while ‘keeping everything else the same’. Counterfactual inference (CFI) in SCMs answers the query in the following way (Balke & Pearl, 1994):

Infer the unobserved noise source conditioned on the observations , i.e. compute and replace the prior with . Denote the resulting SCM by .

Perform intervention on . This yields , which entails the counterfactual distribution . Return the marginal .
Note that our definition explicitly allows for partial observations in accordance with Pearl (2009). A sampledbased version, denoted as CFI, is presented in Algorithm 1. An interesting property of the counterfactual distribution is that marginalizing it over observations
yields an unbiased estimator of the density of
under intervention .Lemma 1 (CFI for simulation).
Let observations come from a SCM with density . Then the counterfactual density is an unbiased estimator of , i.e.
The proof is straightforward and outlined in the Appendix A. This lemma and the marginal independence of the leads to the following corollary; the proof is given in the appendix.
Corollary 1 (Mixed counterfactual and prior simulation from an SCM).
Assume we have observations . We can simulate from , under any intervention , i.e. obtain unbiased samples from , by first sampling values for an arbitrary subset from the posterior and the remaining from the prior , and then computing with noise .
The corollary essentially states that we can sample from the model , by sampling some of the from the prior, and inferring the rest from data (as long as the latter was also sampled from ). We will make use of this later for running a POMDP model on scenarios inferred from data while randomizing the action noise . We note that the noise variables from the posterior are not independent anymore. Nevertheless, SCMs with nonindependent noise distributions arising from counterfactual inference, denoted here by , are commonly considered in the literature (Peters et al., 2017).
Intuition
Returning to Alice’s job example from the introduction, we give some intuition for counterfactual inference in SCMs. Given the concrete outcome , under observed context and having joined company , Alice can try to infer the underlying scenario that she experiences; this includes factors such as work conditions etc. She can then reason counterfactually about the outcome had she joined the other company, which is given by . This can in principle enable her to make better decisions in the future in similar scenarios by changing her policy such that the action with the preferred outcome becomes more likely under . In particular she can do so without having to use her (likely imperfect) prior model over possible companies . She can use the counterfactual predictions discussed above instead to learn from her experience. We use this insight for counterfactual policy evaluation and search below.
3 Offpolicy evaluation: Modelfree, modelbased and counterfactual
To explain how counterfactual reasoning in SCMs can be used for policy search, we first consider the simpler problem of policy evaluation (PE) on offpolicy data. The goal of offpolicy PE is to determine the value of a policy , i.e. its expected return , without running the policy itself. We assume that we have data consisting of logged episodes from running a behavior policy . A standard, modelfree approach to PE is to use Importance sampling (IS): We can estimate the policy’s value as , where is the empirical return of and are importance weights. However, if the trajectory densities and
are very different, then this estimator has large variance. In the extreme case, IS can be useless if the support of
does not contain that of , irrespective of how much data from is available.If we have access to a model , then we can evaluate the policy on synthetic data, i.e. we can estimate . This is called modelbased policy evaluation (MBPE). However, any bias in propagates from to the estimate . In the following, we assume that is a SCM and we show that we can use counterfactual reasoning for offpolicy evaluation (CFPE). As the main result for this section, we argue that we expect CFPE to be less biased than MBPE, and we illustrate this point with experiments.
3.1 Counterfactual offpolicy evaluation
Naive MBPE with a SCM simply consist of sampling the scenarios from the prior, and then simulating a trajectory from the functions and computing its return. However, given data from , our discussion of counterfactual inference in SCMs suggests the following alternative strategy: Assuming no model mismatch, i.e. , we can regard the task of offpolicy evaluation of as a counterfactual query with data , intervention and query variable . In other words, instead of sampling from the prior as in MBPE, we are free to the scenarios from the posterior . The algorithm is given in Algorithm 1. Lemma 1 guarantees that this results in an unbiased estimate:
Corollary 2 (CFPE is unbiased).
Assuming no model mismatch, CFPE is unbiased.
Furthermore, Corollary 1 allows us to also sample some of the noise variables from the prior instead of the posterior, we can e.g. randomize the counterfactual actions by resampling the action noise .
Motivation
When should one prefer CFPE over the more straightforward MBPE? Assuming a perfect model, Corollary 2 states that both yield the same answer in expectation for perfect models. For imperfect models however, these algorithms can differ substantially. MBPE relies on purely synthetic data, sampled from the noise distribution . In practice, this is usually approximated by a parametric density model, which can lead to underfitting in case of complex distributions. This is a wellknown effect in generative models with latent variables: In spite of recent research progress, e.g. models of natural images are still unable to accurately model the variability of the true data (Gregor et al., 2016). In contrast, CFPE samples from the posterior , which has access to strictly more information than the prior by taking into account additional data . This seminonparametric distribution can help to debias the model by effectively winnowing out parts of the domain of which do not correspond to any real data. We substantiate this intuition with experiments below; a concrete illustration for the difference between the prior and posterior / counterfactual distribution is given in fig. 4 in the appendix and discussed in appendix D. Therefore, we conclude that we expect CFPE to outperform MBPE, if the transition and reward kernels are accurate models of the environment dynamics, but if the marginal distribution over the noise sources is difficult to model.
3.2 Experiments
Environment
As an example, we use a partiallyobserved variant of the SOKOBAN environment, which we call POSOKOBAN. The original SOKOBAN puzzle environment was described in detail by Racanière et al. (2017); we give a brief summary here. The agent is situated in a grid world and its five actions are to move to one of four adjacent tiles and a NOOP. In our variant, the goal is to push all three boxes onto the three targets. As boxes cannot be pulled, many actions result irreversibly in unsolvable states. Episodes are of length , and pushing a box onto a target yields a reward of , removing a box from a target yields , and solving a level results in an additional reward of . The state of the environment consists in a
matrix of categorical variables taking values in
indicating if the corresponding tile is empty, a wall, box, target, agent, or a valid combinations thereof (box+target and agent+target). In order to introduce partial observability, we define the observations as the state corrupted by i.i.d. (for each tile and time step) flipping each categorical variable to the “empty” state with probability
. Therefore, the state of the game is largely unobserved at any given time, and a successful agent has to integrate observations over tens of time steps. Initial states , also called levels, which are the scenarios in this environment, are generated randomly by a generator algorithm which guarantees solvability (i.e. all boxes can be pushed onto targets). The environment is visualized in fig. 3 in the appendix.Given the full state of POSOKOBAN, the transition kernel is deterministic and quite simple as only the agent and potentially an adjacent box moves. Inferring the belief state, i.e. the distribution over states given the history of observations and actions, can however range from trivial to very challenging, depending on the amount of available history. In the limit of a long observed history, every tile is eventually observed and the belief state concentrates on a single state (the true state) that can be easily inferred. With limited observed history however, inferring the posterior distribution over states (belief state) is very complex. Consider e.g. the situation in the beginning of an episode (before pushing the first box). Only the first observation is available, however we know that all POSOKOBAN levels are initially guaranteed to be solvable and therefore satisfy many combinatorial constraints reflecting that the agent is still able to push all boxes onto targets. Learning a compact parametric model of the initial state distribution from empirical data is therefore difficult and likely results in large mismatch between the learned model and the true environment.
Results
To illustrate the potential advantages of CFPE over MBPE we perform policy evaluation in the POSOKOBAN environment. We first generate a policy that we wish to evaluate, by training it using a previouslyproposed distributed RL algorithm (Espeholt et al., 2018)
. The policy is parameterized as a deep, recurrent neural network consisting of a 3layer deep convolutional LSTM
(Xingjian et al., 2015) with 32 channels per layer and kernel size of 3. To further increase computational power, the LSTM ticks twice for each environment step. The output of the agent is a value function and a softmax yielding the probabilities of taking the 5 actions. In order to obtain an SCM of the environment, for the sake of simplicity, we assume that the groundtruth transition, observation and reward kernels are given. Therefore the only part of the model that we need to learn is the distribution of initial states (for regular MBPE), and the density for inferring levels in hindsight for CFPE. We vary the amount of true data that we condition this inference on, ranging from (no real data, equivalent to MBPE) to (a full episode of real data is used to infer the initial state ). We train a separate model for each . To simplify model learning, both models were given access to the unobserved state during training, but not at test time. The models are chosen to be powerful, multilayer, generative DRAW models (Gregor et al., 2015) trained by approximate maximum likelihood learning (Kingma & Welling, 2013; Rezende et al., 2014). The models take as input the (potentially empty) data summarized by a backward RNN (a standard convolutional LSTM model with 32 units). The model is shown in fig. 3 in the appendix and additional details are given in appendix C. The data was collected under a uniform random policy . For all policy evaluations, we use levels from the inferred model. In order to evaluate policies of different proficiency, we derive from the original (trained) three policies ranging from almost perfect to almost random performance by introducing additional stochasticity during action selection.The policy evaluation results are shown in fig. 2. We found that for , in spite of extensive hyperparameter search, the model was unable to accurately capture the marginal distribution of initial levels in POSOKOBAN. As argued above, a solvable level satisfies a large number of complex constraints that span the entire grid world, which are hard for a parametric model to capture. Empirically, we found that the model mismatch manifested itself in samples from not being wellformed, e.g. not solvable, and hence the performance of the policies are very different on these synthetic levels compared to levels sampled form . However, inferring levels from full observed episodes i.e. was reliable, and running on these resulted in accurate policy evaluation. The figure also shows the tradeoff between policy evaluation accuracy and the amount of offpolicy data for intermediate amounts of the data . We also want to emphasize that in this setting, modelfree policy evaluation by IS fails. The uniform behavior policy was too different from , resulting in a relative error for all .
4 OffPolicy improvement: Counterfactuallyguided policy search
In the following we show how we can leverage the insights from counterfactual policy evaluation for policy search. We commence by considering a modelbased RL algorithm and discuss how we can generalize it into a counterfactual algorithm to increase its robustness to model mismatch. We chose a particular algorithm to start from to make a connection to the previously proposed Guided Policy Search algorithm (Levine & Koltun, 2013; Levine & Abbeel, 2014), but we think a larger class of MBRL algorithms can be generalized in an analogous manner.
4.1 Starting point: Vanilla modelbased RL with return weighted regression
We start from the following algorithm. We assume we have a model of the environment with trajectory distribution . Our current policy estimate is improved at iteration using returnweighted regression:
where is the return of trajectory . This policy improvement step can be motivated by the framework of RL as variational inference (Toussaint, 2009) and is equivalent to minimizing the KL divergence to a trajectory distribution which puts additional mass on highreturn trajectories. Although not strictly necessary for our exposition, we also allow for a dedicated proposal distribution over trajectories , under a policy . We refer to as a planner to highlight that it could consist of a procedure that solves episodes starting from arbitrary, full states sampled form the model, by repeatedly calling the model transition kernel, e.g. a search procedure such as MCTS (Browne et al., 2012) or an expert policy. Concretely, we optimize the following finite sample objective:
(1) 
We refer to this algorithm as modelbased policy search (MBPS). It is based on model rollouts spanning entire episodes. An alternative would be to consider model rollouts starting from states visited in the real environment (if available). Both versions can be augmented by counterfactual methods, but for the sake of simplicity we focus on the simpler MBPS version detailed above (also we did not find significant performance differences experimentally between both versions).
4.2 Incorporating offpolicy data: Counterfactuallyguided policy search
Now, we assume that the model is an SCM. Based on our discussion of counterfactual policy evaluation, it is straightforward to generalize the MBPS described above by anchoring the rollouts under the model in offpolicy data : Instead of sampling directly from the prior , we draw them from counterfactual distribution with data from the replay buffer, i.e. instead of sampling the scenarios from the prior we infer them from the given data. Again invoking Lemma 1, this procedure is unbiased under no model mismatch. We term the resulting algorithm CounterfactuallyGuided Policy Search (CFGPS), and it is summarized in Algorithm 1. The motivation for using CFGPS over MBPS is analogous to the advantage of CFPE over MBPE discussed in sec. 3.1. The policy in CFGPS is optimized on rollouts that are grounded in data by sampling them from the counterfactual distribution instead of the prior . If this prior is difficult to model, we expect the counterfactual distribution to be more concentrated in regions where there is actual mass under the true environment .
4.3 Experiments
We evaluate CFGPS on the POSOKOBAN environment, using a modified distributed actorlearner architecture based on Espeholt et al. (2018): Multiple actors (here 64) collect real data by running the behavior policy in the true environment . As in many distributed RL settings, is chosen to be a copy of the policy , often slightly outdated, so the data must be considered to be offpolicy. The distribution over levels is inferred from the data using from the model . We sample a scenario for each logged episode, and simulate counterfactual trajectories under the planner for each such scenario. Here, for the sake of simplicity, instead of using search, the planner was assumed to be a mixture between and a pretrained expert policy , i.e. . The schedule was set to an exponentially decaying parameter with time constant episodes. The learner performs policy improvement on using according to eqn. 1. was trained online, in the same way as in sec. 3.2. and were parameterized by deep, recurrent neural networks with the same architecture described in sec. 3.2.
We compare CFGPS with the vanilla MBPS baseline described in sec. 4.1 (based on the same number of policy updates). MBPS differs from CFGPS by just having access to an unconditional model over initial states. We also consider a method which conditions the scenario model on the very first observation , which is available when taking the first action and therefore does not involve hindsight reasoning. This is more informed compared to MBPS; however due to the noise on the observations, the state is still mostly unobserved rendering it very challenging to learn a good parametric model of the belief state . We refer to this algorithm as Guided Policy Searchlike (GPSlike), as it roughly corresponds to the algorithm presented by Levine & Abbeel (2014), as discussed in greater detail in sec. 5. Fig. 2 shows that CFGPS outperforms these two baselines. As expected from the policy evaluation experiments, initial states sampled from the models for GPS and MBPS are often not solvable, yielding inferior training data for the policy . In CFGPS, the levels are inferred from hindsight inference , yielding high quality training data. For reference, we also show a policy trained by the modelfree method of Espeholt et al. (2018) using the same amount of environment data. Not surprisingly, CFGPS is able to make better use of the data compared to the modelfree baseline as it has access to the true transition and reward kernels (which were not given to the modelfree method).
5 Related Work
Bottou et al. (2013) provide an indepth discussion of applying models to offpolicy evaluation. However, their and related approaches, e.g. (Li et al., 2015; Jiang & Li, 2015; Swaminathan & Joachims, 2015; Nedelec et al., 2017; Atan et al., 2016), rely on offpolicy evaluation based on Importance Sampling (IS), also called Propensity Score method. Although these algorithms are also termed counterfactual policy evaluation, they are not counterfactual in the sense used in this paper, where noise variables are inferred from logged data and reused to evaluate counterfactual actions. Hence, they are dogged by high variance in the estimators common to IS, in spite of recent improvements (Munos et al., 2016). Recently (Andrychowicz et al., 2017) proposed the Hindsight Experience Replay (HER) algorithm for learning a family of goal directed policies. In HER one observes an outcome in the true environment, which is kept fixed, and searches for the goaldirected policy that should have achieved this goal in order to positively reinforce it. Therefore, this algorithm is complementary to CFGPS where we search over alternative outcomes for a given policy. Our CFGPS algorithm is inspired by and extends work presented by Abbeel et al. (2006) on a method for debiasing weak models by estimating additive terms in the transition kernel to better match individual, real trajectories. The resulting model, which is a counterfactual distribution in the terminology used in our paper, is then used for modelbased policy improvement. Our work generalizes this approach and highlights conceptual connections to causal reasoning. Furthermore, we discuss the connection of CFGPS to two classes of RL algorithms in greater detail below.
Guided Policy Search (GPS)
CFGPS is closely related to GPS, in particular we focus on GPS as presented by Levine & Abbeel (2014). Consider CFGPS in the fullyobserved MDP setting where . Furthermore, assume that the SCM is structured as follows: Let be a linear function in with coefficients given by
. Further, assume an i.i.d. Gaussian mixture model on
for all . As the states are fully observed, the inference step in the CFI procedure simplifies: we can infer the noise sources (samples or MAP estimates), i.e. the unknown linear dynamics, from pairs of observed, true states . Furthermore assume that the reward is a quadratic function of the state. Then, the counterfactual distribution is a linear quadratic regulator (LQR) with timevarying coefficients . An appropriate choice for the planner is the optimal linear feedback policy for the given LQR, which can be computed exactly by dynamic programming.Observation 1.
In the MDP setting, CFGPS with a linear SCM and a dynamic programming planner for LQRs is equivalent to GPS.
Another perspective is that GPS is the counterfactual version of the MBPS procedure from sec. 4.1:
Observation 2.
In the MDP setting with a linear SCM and a dynamic programming planner for LQRs , GPS is the counterfactual variant of the MBPS procedure outlined above.
The fact that GPS is a successful algorithm in practice shows that the ‘grounding’ of modelbased search / rollouts in real, offpolicy data afforded by counterfactual reasoning massively improves the naive, ‘prior sample’based MBPS algorithm. These considerations also suggest when we expect CFGPS to be superior compared to regular GPS: If the uncertainty in the environment transition cannot be reliably identified from subsequent pairs of observations alone, we expect benefits of inferring from a larger context of observations, in the extreme case from the entire history as described above.
Stochastic Value Gradient methods
There are multiple interesting connections of CFGPS to Stochastic Value Gradient (SVG) methods (Heess et al., 2015). In SVG, a policy for a MDP is learned by gradient ascent on the expected return under a model . Instead of using the scorefunction estimator, SVG relies on a reparameterization of the stochastic model and policy (Kingma & Welling, 2013; Rezende et al., 2014). We note that this reparameterization casts into an SCM. As in GPS, the noise sources are inferred from two subsequent observed states from the true environment, and the action noise is kept frozen. As pointed out in the GPS discussion, this procedure corresponds to the inference step in a counterfactual query. Given inferred values for , gradients of the return under the model are taken with respect to the policy parameters . We can loosely interpret these gradients as counterfactual policy evaluations of policies where a single dimension of the parameter vector is perturbed.
6 Discussion
Simulating plausible synthetic experience de novo is a hard problem for many environments, often resulting in biases for modelbased RL algorithms. The main takeaway from this work is that we can improve policy learning by evaluating counterfactual actions in concrete, past scenarios. Compared to only considering synthetic scenarios, this procedure mitigates model bias. However, it relies on some crucial assumptions that we want to briefly discuss here. The first assumption is that offpolicy experience is available at all. In cases where this is e.g. too costly to acquire, we cannot use any of the proposed methods and have to exclusively rely on the simulator / model. We also assumed that there are no additional hidden confounders in the environment and that the main challenge in modelling the environment is capturing the distribution of the noise sources , whereas we assumed that the transition and reward kernels given the noise is easy to model. This seems a reasonable assumption in some environments, such as the partially observed gridworld considered here, but not all. Probably the most restrictive assumption is that we require the inference over the noise given data to be sufficiently accurate. We showed in our example, that we could learn a parametric model of this distribution from privileged information, i.e. from joint samples from the true environment. However, imperfect inference over the scenario could result e.g. in wrongly attributing a negative outcome to the agent’s actions, instead environment factors. This could in turn result in too optimistic predictions for counterfactual actions. Future research is needed to investigate if learning a sufficiently strong SCM is possible without privileged information for interesting RL domains. If, however, we can trust the transition and reward kernels of the model, we can substantially improve modelbased RL methods by counterfactual reasoning on offpolicy data, as demonstrated in our experiments and by the success of Guided Policy Search and Stochastic Value Gradient methods.
References

Abbeel et al. (2006)
Pieter Abbeel, Morgan Quigley, and Andrew Y Ng.
Using inaccurate models in reinforcement learning.
In
Proceedings of the 23rd international conference on Machine learning
, pp. 1–8. ACM, 2006.  Andrychowicz et al. (2017) Marcin Andrychowicz, Filip Wolski, Alex Ray, Jonas Schneider, Rachel Fong, Peter Welinder, Bob McGrew, Josh Tobin, OpenAI Pieter Abbeel, and Wojciech Zaremba. Hindsight experience replay. In Advances in Neural Information Processing Systems, pp. 5048–5058, 2017.
 Atan et al. (2016) Onur Atan, William R Zame, Qiaojun Feng, and Mihaela van der Schaar. Constructing Effective Personalized Policies Using Counterfactual Inference from Biased Data Sets with Many Features. arXiv preprint arXiv:1612.08082, 2016.

Balke & Pearl (1994)
Alexander Balke and Judea Pearl.
Counterfactual probabilities: Computational methods, bounds and
applications.
In
Proceedings of the Tenth international conference on Uncertainty in artificial intelligence
, pp. 46–54. Morgan Kaufmann Publishers Inc., 1994.  Bottou et al. (2013) Léon Bottou, Jonas Peters, Joaquin QuiñoneroCandela, Denis X Charles, D Max Chickering, Elon Portugaly, Dipankar Ray, Patrice Simard, and Ed Snelson. Counterfactual reasoning and learning systems: The example of computational advertising. The Journal of Machine Learning Research, 14(1):3207–3260, 2013.
 Browne et al. (2012) Cameron B Browne, Edward Powley, Daniel Whitehouse, Simon M Lucas, Peter I Cowling, Philipp Rohlfshagen, Stephen Tavener, Diego Perez, Spyridon Samothrakis, and Simon Colton. A survey of Monte Carlo tree search methods. IEEE Transactions on Computational Intelligence and AI in games, 4(1):1–43, 2012.
 Espeholt et al. (2018) Lasse Espeholt, Hubert Soyer, Remi Munos, Karen Simonyan, Volodymir Mnih, Tom Ward, Yotam Doron, Vlad Firoiu, Tim Harley, Iain Dunning, et al. IMPALA: Scalable distributed DeepRL with importance weighted actorlearner architectures. arXiv preprint arXiv:1802.01561, 2018.
 Gregor et al. (2015) Karol Gregor, Ivo Danihelka, Alex Graves, Danilo Jimenez Rezende, and Daan Wierstra. Draw: A recurrent neural network for image generation. arXiv preprint arXiv:1502.04623, 2015.
 Gregor et al. (2016) Karol Gregor, Frederic Besse, Danilo Jimenez Rezende, Ivo Danihelka, and Daan Wierstra. Towards conceptual compression. In Advances In Neural Information Processing Systems, pp. 3549–3557, 2016.
 Heess et al. (2015) Nicolas Heess, Gregory Wayne, David Silver, Tim Lillicrap, Tom Erez, and Yuval Tassa. Learning continuous control policies by stochastic value gradients. In Advances in Neural Information Processing Systems, pp. 2944–2952, 2015.
 Jiang & Li (2015) Nan Jiang and Lihong Li. Doubly robust offpolicy value evaluation for reinforcement learning. arXiv preprint arXiv:1511.03722, 2015.
 Jiang et al. (2015) Nan Jiang, Alex Kulesza, Satinder Singh, and Richard Lewis. The dependence of effective planning horizon on model accuracy. In Proceedings of the 2015 International Conference on Autonomous Agents and Multiagent Systems, pp. 1181–1189. International Foundation for Autonomous Agents and Multiagent Systems, 2015.
 Kingma & Ba (2014) Diederik P Kingma and Jimmy Ba. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980, 2014.
 Kingma & Welling (2013) Diederik P Kingma and Max Welling. Autoencoding variational Bayes. arXiv preprint arXiv:1312.6114, 2013.
 Korb et al. (2004) Kevin B Korb, Lucas R Hope, Ann E Nicholson, and Karl Axnick. Varieties of causal intervention. In Pacific Rim International Conference on Artificial Intelligence, pp. 322–331. Springer, 2004.
 Levine & Abbeel (2014) Sergey Levine and Pieter Abbeel. Learning neural network policies with guided policy search under unknown dynamics. In Advances in Neural Information Processing Systems, pp. 1071–1079, 2014.
 Levine & Koltun (2013) Sergey Levine and Vladlen Koltun. Guided policy search. In International Conference on Machine Learning, pp. 1–9, 2013.
 Li et al. (2015) Lihong Li, Shunbao Chen, Jim Kleban, and Ankur Gupta. Counterfactual estimation and optimization of click metrics in search engines: A case study. In Proceedings of the 24th International Conference on World Wide Web, pp. 929–934. ACM, 2015.
 Munos et al. (2016) Rémi Munos, Tom Stepleton, Anna Harutyunyan, and Marc Bellemare. Safe and efficient offpolicy reinforcement learning. In Advances in Neural Information Processing Systems, pp. 1054–1062, 2016.
 Nedelec et al. (2017) Thomas Nedelec, Nicolas Le Roux, and Vianney Perchet. A comparative study of counterfactual estimators. arXiv preprint arXiv:1704.00773, 2017.
 Pearl (2009) Judea Pearl. Causality: Models, Reasoning and Inference. Cambridge University Press, New York, NY, USA, 2nd edition, 2009. ISBN 052189560X, 9780521895606.
 Pearl & Mackenzie (2018) Judea Pearl and Dana Mackenzie. The Book of Why: The New Science of Cause and Effect. Basic Books, 2018.
 Peters et al. (2017) J. Peters, D. Janzing, and B. Schölkopf. Elements of Causal Inference  Foundations and Learning Algorithms. Adaptive Computation and Machine Learning Series. The MIT Press, Cambridge, MA, USA, 2017.
 Precup (2000) Doina Precup. Eligibility traces for offpolicy policy evaluation. Computer Science Department Faculty Publication Series, pp. 80, 2000.
 Racanière et al. (2017) Sébastien Racanière, Théophane Weber, David Reichert, Lars Buesing, Arthur Guez, Danilo Jimenez Rezende, Adrià Puigdomènech Badia, Oriol Vinyals, Nicolas Heess, Yujia Li, et al. Imaginationaugmented agents for deep reinforcement learning. In Advances in Neural Information Processing Systems, pp. 5690–5701, 2017.
 Rezende et al. (2014) Danilo Jimenez Rezende, Shakir Mohamed, and Daan Wierstra. Stochastic backpropagation and approximate inference in deep generative models. arXiv preprint arXiv:1401.4082, 2014.
 Roese (1997) Neal J Roese. Counterfactual thinking. Psychological bulletin, 121(1):133, 1997.
 Swaminathan & Joachims (2015) Adith Swaminathan and Thorsten Joachims. Counterfactual risk minimization: Learning from logged bandit feedback. In International Conference on Machine Learning, pp. 814–823, 2015.
 Talvitie (2014) Erik Talvitie. Model Regularization for Stable Sample Rollouts. In UAI, pp. 780–789, 2014.
 Toussaint (2009) Marc Toussaint. Robot trajectory optimization using approximate inference. In Proceedings of the 26th annual international conference on machine learning, pp. 1049–1056. ACM, 2009.
 Wright (1920) Sewall Wright. The relative importance of heredity and environment in determining the piebald pattern of guineapigs. Proceedings of the National Academy of Sciences, 6(6):320–332, 1920.
 Xingjian et al. (2015) Shi Xingjian, Zhourong Chen, Hao Wang, DitYan Yeung, WaiKin Wong, and Wangchun Woo. Convolutional LSTM network: A machine learning approach for precipitation nowcasting. In Advances in neural information processing systems, pp. 802–810, 2015.
Appendix A Proofs
a.1 Proof of Lemma 1
Proof.
We start from the fact that the density over noise sources remains the same for every intervention as are root nodes in :
This leads to:
∎
a.2 Proof of Corollary 1
Proof.
Given two sets and with and , we define and . By construction, the scenarios are independent under the prior, i.e. . Therefore and are independent. We can write:
Following the arguments from Lemma 1, the averaged inference distribution is equal to the prior . This also holds for any subset of the variables , in particular for for . Hence:
∎
Appendix B Details on casting a POMDP into SCM form
Lemma 2 (Autoregressive uniformization aka Reparametrization).
Consider random variables
with joint distribution
. There exist functions for such that with independent random variables the random variables equal in distribution, i.e. , where are defined as:Proof.
We construct the functions by induction on . Consider the conditional distribution . For fixed , denote its CDF with . We construct a random variable with independent from and . By virtue of the inverseCDF method, we have . Therefore, satisfies the above lemma. ∎
Appendix C Model architecture
We assume that we are given the true transition and reward kernels. As the transitions are deterministic in POSOKOBAN, the only part of the model that remains to be identified is the initial state distribution . We learned this model from data using a the DRAW model (Gregor et al., 2015), which is a parametric, multilayer, latent variable, neural network model for distributions. For our purposes we chose the convolutional DRAW architecture proposed by (Gregor et al., 2016). First, the observation data is summarized by a convolutional LSTM with 32 hidden units and kernel size of 3. The resulting final LSTM state is fed into a conditional Gaussian prior over the latent variables of the 8layer convDRAW model. Each layer has 32 hidden layers and the canvas had 7 layers, corresponding to the 7 channels of the categorical that we wish to model. The model (together with the backward RNN) was trained with the ADAM optimizer (Kingma & Ba, 2014) on the ELBO loss using the reparametrization trick (Kingma & Welling, 2013; Rezende et al., 2014). The minibatch size was set to 4 and the learning rate to . We want to emphasize that the DRAW latent variables are not directly the noise variables of the SCM, but integrating out these variables yields this distribution .
Appendix D Model mismatch analysis
unconditional model,  filtering model,  smoothing model, 
is indicated by a red contour of one standard deviation. The inferred mean embedding of the true levels are show as crosses, and their aggregated density is shown in blue. With increasing amount data that the model is conditioned on, the learned distributions match the data better.
Here we provide some analysis of the DRAW model over the initial state , which is the learned part of the SCM used for the policy evaluation experiments presented in 3.2. As detailed above, we trained a separate model for each parameterizing the cardinality of the data the model is conditioned on. We analyze three particular models for and which we term the unconditional / filtering / smoothing model, as they are conditioned on no data / on data that is available at test time / all data that is available in hindsight. Directly visualizing the distributions for an analysis is difficult as the domain is highdimensional and discrete. Instead we focus on the latent variables which are learned by DRAW to represent this distribution; by construction, these are jointly Normal, facilitating the analysis. In particular, we compare with the inference distribution conditioned on the true state . We loosely interpret as the ”true” embedding of the datum , whereas is the learned embedding. In a perfect model the prior matches the inference distribution on average:
i.e. every sample from the prior corresponds to real data and vice versa. We visualize the averaged prior and the averaged posterior in fig. 4. We show the two dimensions of where these distributions have the largest KL divergence. Also, the plots were whitened w.r.t. the averaged prior, i.e. the latter is a spherical Gaussian in the plots, represented by an isoprobability contour corresponding to one standard deviation. The inference distribution for each datum is visualized by its mean (cross) and a level set corresponding the one standard deviation or less. For the unconditional model , we find that the distributions are not matched well. In particular, there is a lot of prior mass that sits in regions where there is no or little true data. In the RL setting this results in synthetic data from the model that is unrealistic and training a policy on this data leads to reduced test performance. Also, as apparent from the figure, there is structure in the embedding of the true data, that is not captured at all by the prior. This effect is markedly reduced in the filtering posterior, indicating that the conditional distribution already captures the data distribution better. The smoothing model is a very good match to the data. With high probability, all tiles of the game are observed in , enabling the model to perfectly learn the belief state, which collapses in this setting to a single state.