Manuscript Offprint
arXiv:2610.13724Amortized Counterfactual Prediction with Graph Neural Networks
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
Counterfactual inference asks how an observed outcome might have differed under different circumstances, such as whether a patient would have recovered had they received a different treatment. Such questions arise whenever decisions depend on the outcomes of alternatives that were not observed. Answering counterfactual queries generally requires knowledge of the underlying causal structure, which is often unavailable in practice. A common approach is therefore to first estimate the causal graph from observational data and then perform counterfactual inference. However, errors in the estimated causal graph can propagate to downstream counterfactual predictions. To address this challenge, we introduce the Counterfactual Graph Neural Process (CFGNP), an end-to-end approach that answers counterfactual queries directly from observational data without first estimating a causal graph. CFGNP uses Graph Neural Networks (GNNs) to exploit the dual-graph structure by restricting cross-world message passing to corresponding factual-counterfactual variables. Across synthetic and image-based benchmarks, CFGNP achieves stronger predictive performance than existing approaches, including on the German Loan benchmark, where it reduces MSE from to . Furthermore, on synthetic causal graphs, a model trained only on 10-node graphs maintains strong predictive performance on graphs with up to 30 nodes, without retraining.
1 Introduction
Understanding cause-and-effect relationships is a central goal in many scientific disciplines. In medicine, researchers may wish to determine whether a treatment improves patient outcomes [Burotto et al., 2014, Stovitz and Shrier, 2019]. In economics, policymakers often aim to understand how changes in policy affect employment or inflation [Heckman and Pinto, 2022]. Similar questions arise in biology, social sciences, and machine learning [Morgan and Winship, 2007, Sanderson et al., 2022, Schölkopf et al., 2021]. Especially with the increased deployment of machine learning systems in settings where interpretability is crucial, understanding cause-and-effect relationships becomes more important [Li and Han, 2023]. In all of these settings, the objective is not merely to observe statistical associations, but to understand how outcomes would change if different actions or conditions were imposed.
Causal inference [Pearl, 2009] provides a framework for studying such questions. Unlike conventional statistical learning, causal inference seeks to uncover cause-effect relationships between variables, rather than statistical associations. The framework formalises this with the structural causal model (SCM), which specifies how variables are generated, and how they causally affect one another. Within the SCM framework, causal questions can be distinguished by the type of reasoning they require. Pearl [Pearl, 2009] differentiates between three levels: associational, interventional, and counterfactual queries. Associational queries concern relationships observed in data, while interventional queries ask how outcomes change when a variable is actively manipulated [Pearl, 1996]. Counterfactual queries go one step further by asking what would have happened in an alternative scenario, given what was observed in the factual world [Shpitser and Pearl, 2012]. Counterfactual queries are particularly important because they allow reasoning about individualized outcomes and explanations, rather than only population-level effects [Nguyen et al., 2020]. This makes them harder to solve than the other two query types as we additionally have to take the alternative hypothesis into account.
Traditional approaches to counterfactual inference typically rely on substantial prior knowledge about the underlying cause-effect relationships between variables [Nasr-Esfahany et al., 2023, Rasal et al., 2025, Ribeiro et al., 2025, Xia et al., 2022]. In practice, this often means assuming access to the causal graph, which describes these relationships. Sometimes, less information, such as the topological node ordering of the causal graph, is required [Le et al., 2024]. However, in many real-world settings, such information is unavailable or highly uncertain. This is particularly the case in domains such as medicine, biology, and the social sciences, where causal relationships may be obscured by latent confounders, incomplete observations, and complex dependencies among variables [Loh, 2025, Ruiz-Perez et al., 2024, Weberpals et al., 2024].
Hence, if there is no prior knowledge about the causal graph, we must first use observational samples to estimate the causal graph [Spirtes et al., 2001] and then use the resulting causal graph with the existing methods for counterfactual inference. However, this has two drawbacks; first, the search space of causal graphs scales super-exponentially in the number of variables [Zheng et al., 2018] and second, choosing the wrong causal graph amplifies errors and may cause the counterfactual to be incorrect [Karimi et al., 2020b]. To avoid explicitly estimating the causal graph, we instead condition the counterfactual prediction directly on observational samples. This allows the model to extract information about the underlying causal structure that is relevant to the counterfactual query, without committing to a single estimated graph. We approach this problem through meta-learning using Neural Processes (NPs) [Garnelo et al., 2018], which learn to map a set of observations to a predictive distribution. Building on Graph Neural Processes [Carr and Wingate, 2019], we further incorporate the structural constraints imposed by the dual graph into the prediction.
Based on this approach, we introduce the Counterfactual Graph Neural Process (CFGNP), an end-to-end framework for counterfactual inference under unknown causal structure. An overview of our setting is shown in Figure 1.
• We develop a Graph Neural Process architecture that conditions counterfactual predictions on observational samples (Section 4.1).
• We demonstrate that CFGNP outperforms existing counterfactual inference methods on both synthetic and real-world data (Sections 5.1 and 5.2).
• We evaluate CFGNP on counterfactual queries involving features that are unseen during training and observe strong performance in this setting (Section 5.2).
2 Related Work
Causal Discovery. For causal inference tasks such as evaluating counterfactual queries, most existing methods rely on explicit knowledge of the causal graph. Estimating this graph from associational data is known as causal discovery [Verma and Pearl, 2022]. The primary goal of causal discovery is to uncover true cause-and-effect relationships by learning the underlying structural dependencies rather than relying on statistical correlations alone [Pearl, 2009, Peters

Figure 1: Overview of the task solved by CFGNP. Unknown variables are in light grey and known variables in dark grey. Blue edges represent missing knowledge about the causal graph. The counterfactual is predicted based on the counterfactual query and additional observational samples.
et al., 2017]. Classical methodologies encompass constraint-based approaches, such as the PC algorithm [Spirites et al., 2001], and score-based frameworks, such as Greedy Equivalence Search [Chickering, 2002]. More recently, modern techniques including LiNGAM [Shimizu et al., 2006], NOTEARS [Zheng et al., 2018], and DAG-GNN [Yu et al., 2019] have advanced the field by introducing functional form assumptions, continuous optimization, and deep learning architectures. Nevertheless, key challenges remain, such as unobserved confounding [Diepen et al., 2023, Kaltenpoth and Vreeken, 2023], complex nonlinearities [Li et al., 2024], and computational scalability [Amin and Wilson, 2024, Cheng et al., 2024]. Addressing these challenges continues to make causal inference an active area of research.
Counterfactual Inference. Existing approaches attempt to learn counterfactual distributions under varying degrees of prior structural knowledge [Caron et al., 2022, Karimi et al., 2020a, Khemakhem et al., 2021]. For instance, Le et al. [2024] and Javaloy et al. [2023] use normalizing flows that require only a topological ordering of the graph nodes, whereas most alternatives assume the full causal graph. Within deep learning for counterfactual inference, Pawlowski et al. [2020] use normalizing flows to parameterize structural causal models, while recent flow-matching approaches similarly require full graph specification [Ribeiro et al., 2025]. Other methods explicitly exploit relational structure through Graph Neural Networks [Sanchez-Martin et al., 2021, Zečević et al., 2021]. This reliance on a known, estimated, or otherwise fixed causal structure can be restrictive [Caron et al., 2022, Wu et al., 2025]: the space of DAGs grows super-exponentially with the number of variables [Zheng et al., 2018], and errors in the assumed causal structure can propagate to downstream counterfactual predictions [Karimi et al., 2020b]. While end-to-end learning under uncertain causal structure has been explored for interventional inference [Dhir et al., 2025, Geffner et al., 2022], an analogous approach has not yet been established for counterfactual inference, where additional structural constraints from the dual graph can be exploited [von Kügelgen et al., 2022].
Image Counterfactuals. Several works focus specifically on image-based counterfactual generation and analysis [Luedtke and Fukumizu, 2025, Ma et al., 2026, Pawlowski et al., 2020, Rasal et al., 2025]. Among these, DeepBC [Kladny et al., 2024] performs counterfactual inference through latent exogenous variables under a known causal graph. Other recent approaches based on diffusion models [Rasal et al., 2025] and optimal transport [Ribeiro et al., 2025] similarly assume that the causal graph is known. In contrast, VCI [Wu et al., 2025] does not take an explicit causal graph as input, but instead assumes a prescribed treatment–covariate–outcome structure and uses a variational formulation to generate counterfactuals without requiring counterfactual training pairs.
Neural Processes. To address these limitations, our approach builds on Neural Processes
(NPs) [Garnelo et al., 2018], which have been successfully applied across a range of domains including Bayesian optimization and other scientific applications [Bruinsma et al., 2023, Foong et al., 2020, Kim et al., 2019]. NPs have recently been explored in causal settings, including treatment-effect estimation and Bayesian causal inference [Bynum et al., 2026, Dhir et al., 2025]. However, these works address related causal inference tasks rather than counterfactual inference. In contrast, our approach extends this framework to counterfactual inference, for which we additional leveraging GNNs to capture the structural relationships between factual and counterfactual variables [von Kügelgen et al., 2022]. Graph Neural Processes extend NPs to relational and graph-structured data [Carr and Wingate, 2019, Hu et al., 2023, Liang and Gao, 2021]. By combining these ideas, we directly map observational data to the target counterfactual distribution using GNNs over the dual-graph structure, without first estimating a causal graph.
3 Background
We now introduce notions of causal inference, neural processes, and graph neural networks.
Notation. Unstarred and starred variables denote the factual and counterfactual worlds, respectively. Let be the factual observed unit, a counterfactual condition, and the target variables. The observational context is , consisting of i.i.d. samples from the same SCM , where and denote the number of endogenous variables and context samples, respectively. We write when is informed by the observational context , and when emphasizing the model. If is unspecified, we assume the true model.
3.1 Structural Causal Models and Causal Inference
Structural Causal Model. A structural causal model (SCM) describes the causal relationships among a set of endogenous variables through a collection of structural equations . Each variable is determined by its direct causes and an exogenous noise variable according to
The exogenous variables capture factors outside the model and are assumed to be mutually independent. The causal relationships encoded by the structural equations can be represented by a directed and acyclic causal graph , where an edge indicates that . In particular, with coming from a probability distribution we can define associational queries to concern distributions with . Observational samples are sampled from . Interventional queries concern questions where we actively set nodes to a specific value and consider the outcome . (Backtracking) counterfactual queries are probability distributions, with and , of the form
concerning questions such as: given that happened, what would have happened to variables if alternatively . In particular, we use notation instead of the do-operator to make clear that we are using backtracking counterfactuals [von Kügelgen et al., 2022] and not interventionist counterfactuals [Pearl, 2009]. While interventionist counterfactuals artificially modify the structural equations in the counterfactual world, they thereby locally violate the laws of nature. In contrast, backtracking counterfactuals keep the structural equations intact and instead consider alternative exogenous conditions that could have produced .
Dual Graph. To answer backtracking counterfactuals, we need the dual graph. Figure 2 shows an example of the dual graph for backtracking counterfactuals. The dual graph consists of two copies of the same SCM. The left part, the observed factual unit, represents what actually happened, whereas the copy on the right, the counterfactual unit, represents the alternative circumstances. Both worlds are connected via the exogenous nodes, which share a probability distribution .
We can solve the counterfactual query via the abduction-marginalisation-prediction framework [von Kügelgen et al., 2022], consisting of the following steps: 1.) Abduction: We infer the joint posterior over the exogenous nodes . 2.) Marginalisation: We marginalise out to obtain . 3.) Prediction: We use the SCM to predict .

Figure 2: Example of the dual graph for a counterfactual query with a causal graph of four nodes. Light grey nodes are unknown.
Identifiability. When the underlying causal model is only partially known, a causal query may not be uniquely determined by the available information. An query is identifiable from information if all models in the considered model class that agree on the available information yield the same answer [Pearl, 2009]. This is relevant to our setting because counterfactual queries are not necessarily identifiable from observational data alone.
3.2 Neural Processes and Graph Neural Networks
Neural Processes. Neural Processes (NPs) [Garnelo et al., 2018] are probabilistic models that learn distributions over functions from a collection of related tasks. Each task is represented by a context set of observed input-output pairs and a target set at which predictions are made. NPs learn the conditional predictive distribution , thereby amortizing inference across tasks by mapping context observations directly to predictive distributions. Extensions of NPs to graph-structured domains replace neural architectures with graph-based models to capture relational structure [Ashman et al., 2024, Carr and Wingate, 2019].
Graph Neural Networks. Graph Neural Networks (GNNs) learn representations of graph-structured data by iteratively propagating information between connected nodes. Let denote the representation of node at layer , with . Following the message-passing framework [Gilmer et al., 2017], a GNN layer aggregates messages from the neighbourhood of each node,
where and are learnable message and update functions, respectively, and is permutation invariant. For directed graphs, the neighbourhood can be partitioned into incoming and outgoing neighbours, and , allowing messages to be propagated separately along each direction. This distinction is particularly relevant for causal graphs, where incoming and outgoing edges represent causal relations in opposite directions.
4 A GNN Model for Counterfactual Inference without Causal Graph Knowledge
This work focuses on predicting counterfactual distributions directly from observational data without prior knowledge about the causal graph. For each task, we observe a context set

Figure 3: Overview of CFGNP. Observational samples are first aggregated into node-wise context representations, which are combined with the observed factual unit. Message passing between factual and counterfactual unit then produces parameters of the counterfactual predictive distribution.
of i.i.d. observational samples from an unknown SCM . Given a factual observation and a counterfactual condition , our goal is to predict the counterfactual distribution over a set of query variables . The observational context provides evidence about . We aim to directly learn the model-averaged counterfactual predictive distribution
thereby accounting for uncertainty over causal models without explicitly inferring or committing to a particular causal graph. Existing methods on the other hand try to estimate the causal graph first.
Since we intend to approximate the counterfactual probability distribution, we use the Kullback-Leibler (KL) divergence [Kullback and Leibler, 1951] as the minimization objective. Suppose we have a list of samples , where contains the factual representation , counterfactual query, and observation pattern , while contains the corresponding counterfactual target values. Let denote the distribution predicted by the model with weights , where may contain multiple target variables.
We then want to obtain the weights that minimize the KL divergence, hence
for some constant independent of the model parameters. During training we assume access to counterfactual pairs, as we sample .
Recovery of the Counterfactual Distribution. In the limit of infinite data and model capacity, minimizing the KL divergence recovers the conditional predictive distribution [Bruinsma, 2022] , with latent quantities, such as the exogenous variables, implicitly marginalized out [Gordon et al., 2019]. If the counterfactual distribution is identifiable from observational data, this predictive distribution coincides with the counterfactual distribution of the ground-truth causal model. Otherwise, the model instead recovers the model-averaged counterfactual distribution over SCMs compatible with the observations.
4.1 Approach
Figure 3 illustrates the architecture of the Counterfactual Graph Neural Process (CFGNP). Given observational samples O, a factual observation z, and a counterfactual intervention , CFGNP predicts the corresponding counterfactual outcome distribution. The architecture consists of three stages: summarizing the observational context (middle), combining it with the factual observation (top right), and propagating the resulting representation to the counterfactual unit (bottom right). We describe each component below.
Embedding Input. We project all nodes to the hidden dimension using node-wise MLPs. For O, we apply the same MLP across all nodes. For z and , we distinguish intervention nodes from the remaining nodes using separate MLPs: and for z, and and for . In , all entries outside are masked.
Observational Context Encoding. We next incorporate the observational samples O by allowing nodes within each sample to communicate and compressing their information into q. For each variable i, we introduce an aggregation node , initialized to zero, and connect the corresponding node i from every observational sample to . Since we have no prior knowledge of the causal graph, we additionally fully connect the nodes within each observational sample.
The resulting graph consists of disjoint fully connected n-node subgraphs and n aggregation nodes. A K-layer GAT [Brody et al., 2022] performs message passing, , such that captures the compressed observational context.
We then integrate this context with the factual unit . To keep the graph compact, we connect each only to its corresponding and add a self-loop to each . A 3-layer GAT propagates the contextual information to the factual unit, .
Predicting Counterfactual Distribution. The final stage aims to approximate the abduction–marginalisation–prediction steps using the context-informed factual representation and counterfactual condition . The dual graph enables these steps by coupling the factual and counterfactual worlds through connected exogenous nodes. Approximating these steps generally requires bidirectional message passing.
Because we do not have prior knowledge of the causal graph, factual and counterfactual units are fully connected. Thus, each endogenous node has direct access to the information needed to reproduce its corresponding exogenous state, allowing us to remove explicit exogenous nodes and connect only corresponding factual and counterfactual variables across worlds. In this case, a unidirectional GNN can approximate the corresponding bidirectional GNN arbitrarily well (App. 1).
As a design choice, we apply GAT layers, scaling depth with graph size while capping it at five to limit over-smoothing [Li et al., 2018]. This yields , where encodes at conditioned nodes and masks the rest.
The resulting represents the counterfactual unit. To obtain the counterfactual predictive distribution, a node-wise MLP maps to its distributional parameters. We use a mixture of Gaussians, allowing CFGNP to represent uncertainty arising from ambiguity over the underlying SCM.
Training Objective. During training CFGNP minimizes the negative-log-likelihood objective, as this is equivalent to minimizing the KL divergence [Murphy, 2022]:
Model Properties. The structure of CFGNP reflects two desirable properties. First, predictions should be independent of the ordering of variables. Permuting target nodes should induce the same permutation in the corresponding predictions, while permutations of the remaining nodes should leave predictions for unchanged. This is provided by design of GNNs (App. .3).
Second, a trained model should be applicable to graphs of different sizes and arbitrary numbers of observational samples (App. .4). This enables CFGNP to generalize beyond the graph sizes and context sizes encountered during training.
We note for completeness that, for nodes, data/hidden dimensions , observations, GNN iterations, and mixture components, one forward pass has complexity (.2):
5 Results
We evaluate CFGNP in terms of counterfactual prediction performance, generalization across causal graph sizes and unseen features, and computational efficiency, with additional experiments assessing its ability to recover analytically available counterfactual distributions with increasing context size (App. C.4). We also include an ablation study (App. C.5) where a normal transformer is run on the concatenated inputs. The results show that CFGNP performs much better than this. Baselines. We compare against the following baselines:
• VCI [Wu et al., 2025]: uses a conditional VAE with a counterfactual variational objective under a restricted causal structure.
• DeepBC [Kladny et al., 2024]: performs counterfactual inference through exogenous variables in a learned SCM, assuming a known causal graph (CG).
• VACA [Sanchez-Martin et al., 2021]: uses a variational graph autoencoder on a known CG.
• BGM [Nasr-Esfahany et al., 2023]: represents structural equations as invertible mappings between exogenous and observed variables given the causal structure.
• CFM [Le et al., 2024]: learns flow-based causal mechanisms assuming a given causal ordering.
Unlike the baseline methods, CFGNP uses counterfactual pairs during training, but no causal graph.
Metrics. We evaluate counterfactual predictions using the following metrics:
• MSE/MAE: Mean squared/absolute error (MSE/MAE) for numerical variables.
• Accuracy/ROC-AUC: Accuracy and ROC-AUC for categorical variables.
For datasets containing both numerical and categorical variables, we report metrics separately for each variable. For synthetic experiments with multiple variables, we follow Sanchez-Martin et al. [2021] and report MSE aggregated across all variables and samples.
Synthetic Datasets. For the synthetic experiments, we use the Triangle, M-shape, and German Loan benchmarks from Sanchez-Martin et al. [2021], together with randomly generated SCMs for the graph-size experiments. Triangle and M-shape have 3 and 5 nodes respectively and are evaluated with linear (LIN), nonlinear additive (NLIN), and nonlinear non-additive (NADD) mechanisms, while German Loan is a 7-node semi-synthetic seven-variable SCM inspired by the German Credit domain. Detailed definitions can be found in B.3.
Further, we conduct experiments on causal graphs of increasing size where each sample comes from its own SCM. We follow Soleymani et al. [2020]. We generate the SCMs by randomly permuting the nodes into a topological order and adding each admissible edge with probability . Each variable is generated from its direct causes using one of seven mechanisms per sample, followed by posterior additive noise (App. B.4). We consider causal graphs of sizes .
Real-world Datasets. For the real-world experiments, we use the CheXpert dataset [Irvin et al., 2019], consisting of chest X-rays (App. B.2). We augment each image with four explicit variables: age, sex, disease, and AP/PA, where AP/PA denotes the radiographic viewing direction. Following Ribeiro et al. [2025], we supply the baselines with a causal structure in which age affects disease, while age, sex, disease, and AP/PA determine the image. Since ground-truth counterfactuals are unavailable [Ma et al., 2026], we evaluate whether generated images exhibit the intended counterfactual attributes using classifiers. Details on the classifiers and image-generating CFGNP variant are provided in App. B.2. We assess whether images resemble real-world images qualitatively.
5.1 Synthetic Experiments
On synthetic experiments, we compare against VACA [Sanchez-Martin et al., 2021], BGM [Nasr-Esfahany et al., 2023], and CFM [Le et al., 2024], which have demonstrated strong performance in prior work. VACA and BGM require the full causal graph, whereas CFM only requires its topological ordering, allowing comparison across different levels of causal knowledge. For the graph-size experiments, we omit CFM as it was not computationally viable on larger causal graphs.
Counterfactual Prediction. Table 1 shows the results for the synthetic datasets. CFGNP improves across almost all variants of the datasets and in many by a substantial amount. For instance, for German loan, CFGNP has an MSE of compared to of CFM. However, on the LIN variant of M-Shape, the MSE of is higher than BGM's with .
| Dataset | Variant | BGM | VACA | CFM | CFGNP (Ours) |
|---|---|---|---|---|---|
| MSE | |||||
| Triangle | LIN | ||||
| NLIN | |||||
| NADD | |||||
| M-shape | LIN | ||||
| NLIN | |||||
| NADD | |||||
| German Loan | - | ||||
Table 1: Mean MSE ± standard deviation achieved by BGM, VACA, CFM, and CFGNP (ours) across the Triangle, M-shape, and German Loan datasets. Lower values indicate better performance. Best scores are marked in bold.
Graph-Size Experiments. For experiments with increasing graph size we use two variants of CFGNP. In one variant, CFGNP is retrained for each , while in the other, CFGNP is trained only on graphs with nodes and applied to the other graph sizes without training. We refer to this model as 10-CFGNP. Additionally, as the benchmarks require a fixed causal graph, we provide the fullest DAG, connecting each node to all topological successors. This highlights an advantage of CFGNP: when causal graphs vary across the dataset, baselines must still assume a fixed graph.
Figure 4 shows MSE with increasing graph size (note the non-linear y-axis). 10-CFGNP performs similarly to retrained CFGNP for Linear and Sum-sine, but worse for Log-sum-exp and Sqrt-sum. MSE increases for all methods, but both CFGNP variants outperform the baselines and degrade more slowly. Other mechanisms are reported in App. C.2.
5.2 CheXpert Experiments
We compare against VCI [Wu et al., 2025] and DeepBC [Kladny et al., 2024] which both have previously demonstrated strong performance. Again, VCI assumes treatment–covariate–outcome structure while DeepBC needs full graph knowledge.
Counterfactual Prediction. Table 2 shows that CFGNP performs particularly well on age,

Figure 4: Performance (MSE) of models with regard to size of the causal graph. Models are compared on causal graphs with Linear (1.), Sum-sine (2.), Log-sum-exp (3.), Sqrt-sum (4.), and Sum-sqrt (5.) structural equations. MSE mean over distinct causal graphs. Vertical lines show and quantiles.
reducing MAE from 10.88 for DeepBC to 2.71, and consistently achieves high ROC-AUC on categorical variables. For disease, for example, accuracies are around 0.87, while CFGNP achieves a ROC-AUC of 0.77, compared with 0.75 for DeepBC and 0.45 for VCI. Generated counterfactual images are provided in Appendix C.2.
| Feature | Metric | CFGNP (Ours) | DeepBC | VCI |
|---|---|---|---|---|
| Sex | Accuracy ↑ | |||
| ROC-AUC ↑ | ||||
| Age | MAE ↓ | |||
| AP/PA | Accuracy ↑ | |||
| ROC-AUC ↑ | ||||
| Disease | Accuracy ↑ | |||
| ROC-AUC ↑ |
Table 2: Performance of CFGNP, VCI, and DeepBC on the CheXpert dataset. MAE is reported for the continuous feature, while accuracy and ROC-AUC are reported for categorical features. Arrows indicate whether higher or lower values are preferred. Best values marked in bold.
Out-of-Distribution Variable-Set Experiment. We evaluate CFGNP's generalization to unseen features on CheXpert. For each OOD setting, we exclude one feature during training and evaluate on the full test set, leveraging CFGNP's ability to handle graphs of different sizes. Table 3 shows strong generalization for sex and AP/PA, with ROC-AUC above 0.99, while age and disease are more challenging, with an MAE of up to 11.53 and ROC-AUC between 0.61 and 0.64, respectively.
| Feature | Metric | OOD Sex | OOD Age | OOD AP/PA | OOD Disease |
|---|---|---|---|---|---|
| Sex | Accuracy ↑ | ||||
| ROC-AUC ↑ | |||||
| Age | MAE ↓ | ||||
| AP/PA | Accuracy ↑ | ||||
| ROC-AUC ↑ | |||||
| Disease | Accuracy ↑ | ||||
| ROC-AUC ↑ |
Table 3: OOD generalization on CheXpert. Each column indicates the feature excluded during training; evaluation is performed on the full test set containing all features. Best results in bold.
6 Conclusion
We propose CFGNP, an end-to-end architecture designed to learn counterfactual distributions directly from observational data without knowledge of the causal graph. CFGNP applies GNNs to enforce structural constraints on the dual graph implied by the notion of backtracking counterfactuals. By leveraging observational context samples alongside counterfactual queries, CFGNP directly approximates the Bayesian model-averaged counterfactual distribution. Evaluations on image and synthetic counterfactual queries have shown strong performance compared to baselines. Further experiments on synthetic datasets show that CFGNP retains strong performance on larger causal graphs compared with retraining from scratch, while outperforming baselines. Finally, we empirically validate that CFGNP performs adequately even on out-of-distribution features. In terms of limitations, the preceding capabilities come with a computational trade-off. The required observational context increases both training and inference costs. Moreover, if the counterfactual distribution is non-identifiable, CFGNP cannot recover the true distribution. However, this also applies to the baseline methods. In the future, one could incorporate priors about the causal graph. While the entire causal graph may not be known, an expert may have knowledge about the existence and absence of certain causal relationships. Taking this even further, one could provide simple distributions over edges, for instance obtained by amortized causal structure learning methods [Lorch et al., 2022].
AI use statement
In this work, we used generative AI tools for refining writing, formulating mathematical claims, assisting in the writing of proofs, and feedback on research methodology or experiments. We have not used generative AI tools for generating synthetic data sets, helping develop theoretical models or conceptual frameworks, providing critical ingredients for proving mathematical claims, implementing methods, assisting with translation, cleaning and reformatting datasets, and interpreting results. Support for qualitative and thematic data analysis and proposing or refining hypotheses are not applicable to this work. We have reviewed all AI-assisted work. We checked that the generated formulation of the claim matches the intended claim. We take responsibility for the final content of this work, including text, claims or artifacts produced with the aid of generative AI.
Ethics statement
This work uses existing datasets and collects no new human-subject data. While counterfactual models may have applications in healthcare, their predictions can reflect biases and limitations in the data and should not be used for clinical decision-making without appropriate validation.
Reproducibility statement
To support reproducibility, we provide the source code and experimental setup. The repository can be found under https://github.com/Zelos1/CFGNP. Model architectures and hyperparameters are detailed in the appendix.
References
Amin, A. N. and Wilson, A. G. (2024). Scalable and flexible causal discovery with an efficient test for adjacency. In Salakhutdinov, R., Kolter, Z., Heller, K., Weller, A., Oliver, N., Scarlett, J., and Berkenkamp, F., editors, Proceedings of the 41st International Conference on Machine Learning, volume 235 of Proceedings of Machine Learning Research, pages 1331–1358. PMLR.
Ashman, M., Diaconu, C., Kim, J., Sivaraya, L., Markou, S., Requeima, J., Bruinsma, W. P., and Turner, R. E. (2024). Translation equivariant transformer neural processes. arXiv preprint arXiv:2406.12409.
Brody, S., Alon, U., and Yahav, E. (2021). How attentive are graph attention networks? arXiv preprint arXiv:2105.14491.
Brody, S., Alon, U., and Yahav, E. (2022). How attentive are graph attention networks?
Bruinsma, W. (2022). Convolutional Conditional Neural Processes. PhD thesis.
Bruinsma, W., Markou, S., Requeima, J., Foong, A. Y. K., Andersson, T., Vaughan, A., Buonomo, A., Hosking, S., and Turner, R. E. (2023). Autoregressive Conditional Neural Processes. In International Conference on Learning Representations.
Burotto, M., Chiou, V. L., Lee, J.-M., and Kohn, E. C. (2014). The mapk pathway across different malignancies: A new perspective. Cancer, 120(22):3446–3456.
Bynum, L. E. J., Ranganath, R., and Cho, K. (2026). Computational identifiability.
Caron, A., Baio, G., and Manolopoulou, I. (2022). Counterfactual Learning with Multioutput Deep Kernels. arXiv:2211.11119 [cs].
Carr, A. and Wingate, D. (2019). Graph neural processes: Towards bayesian graph neural networks.
Cheng, Y., Li, L., Xiao, T., Li, Z., Suo, J., He, K., and Dai, Q. (2024). Cuts+: High-dimensional causal discovery from irregular time-series. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 38, pages 11525–11533.
Chickering, D. M. (2002). Optimal structure identification with greedy search. Journal of machine learning research, 3(Nov):507–554.
Dhir, A., Diaconu, C., Lungu, V. M., Requeima, J., Turner, R. E., and Wilk, M. v. d. (2025). Estimating Interventional Distributions with Uncertain Causal Graphs through Meta-Learning. arXiv:2507.05526 [cs].
Diepen, M. M. V., Bucur, I. G., Heskes, T., and Claassen, T. (2023). Beyond the markov equivalence class: Extending causal discovery under latent confounding. In van der Schaar, M., Zhang, C., and Janzing, D., editors, Proceedings of the Second Conference on Causal Learning and Reasoning, volume 213 of Proceedings of Machine Learning Research, pages 707–725. PMLR.
Foong, A., Bruinsma, W., Gordon, J., Dubois, Y., Requeima, J., and Turner, R. (2020). Meta-learning stationary stochastic process prediction with convolutional neural processes. Advances in Neural Information Processing Systems, 33:8284–8295.
Garnelo, M., Schwarz, J., Rosenbaum, D., Viola, F., Rezende, D. J., Eslami, S. M. A., and Teh, Y. W. (2018). Neural Processes. arXiv:1807.01622 [cs].
Geffner, T., Antoran, J., Foster, A., Gong, W., Ma, C., Kiciman, E., Sharma, A., Lamb, A., Kukla, M., Pawlowski, N., Allamanis, M., and Zhang, C. (2022). Deep end-to-end causal inference.
Gichoya, J. W., Banerjee, I., Bhimireddy, A. R., Burns, J. L., Celi, L. A., Chen, L.-C., Correa, R., Dullerud, N., Ghassemi, M., Huang, S.-C., et al. (2022). Ai recognition of patient race in medical imaging: a modelling study. The Lancet Digital Health, 4(6):e406–e414.
Gilmer, J., Schoenholz, S. S., Riley, P. F., Vinyals, O., and Dahl, G. E. (2017). Neural message passing for quantum chemistry. In International conference on machine learning, pages 1263–1272. Pmlr.
Gordon, J., Bronskill, J., Bauer, M., Nowozin, S., and Turner, R. E. (2019). Meta-learning probabilistic inference for prediction.
He, K., Zhang, X., Ren, S., and Sun, J. (2016). Deep residual learning for image recognition. In Proceedings of the IEEE conference on computer vision and pattern recognition, pages 770–778.
Heckman, J. J. and Pinto, R. (2022). Causality and econometrics. Working Paper 29787, National Bureau of Economic Research.
Hornik, K., Stinchcombe, M., and White, H. (1989). Multilayer feedforward networks are universal approximators. Neural networks, 2(5):359–366.
Hu, J., Liang, Y., Fan, Z., Chen, H., Zheng, Y., and Zimmermann, R. (2023). Graph neural processes for spatio-temporal extrapolation. In Proceedings of the 29th ACM SIGKDD Conference on Knowledge Discovery and Data Mining, KDD '23, page 752–763. ACM.
Irvin, J., Rajpurkar, P., Ko, M., Yu, Y., Ciurea-Ilcus, S., Chute, C., Marklund, H., Haghgoo, B., Ball, R., Shpanskaya, K., Seekins, J., Mong, D. A., Halabi, S. S., Sandberg, J. K., Jones, R., Larson, D. B., Langlotz, C. P., Patel, B. N., Lungren, M. P., and Ng, A. Y. (2019). Chexpert: A large chest radiograph dataset with uncertainty labels and expert comparison.
Javaloy, A., Sánchez-Martín, P., and Valera, I. (2023). Causal normalizing flows: from theory to practice. arXiv:2306.05415 [cs].
Javanmardi, M., Sajjadi, M., Liu, T., and Tasdizen, T. (2018). Unsupervised total variation loss for semi-supervised deep learning of semantic segmentation.
Kaltenpoth, D. and Vreeken, J. (2023). Nonlinear causal discovery with latent confounders. In Krause, A., Brunskill, E., Cho, K., Engelhardt, B., Sabato, S., and Scarlett, J., editors, Proceedings of the 40th International Conference on Machine Learning, volume 202 of Proceedings of Machine Learning Research, pages 15639–15654. PMLR.
Karimi, A.-H., Kügelgen, J. v., Schölkopf, B., and Valera, I. (2020a). Algorithmic recourse under imperfect causal knowledge: a probabilistic approach. arXiv:2006.06831 [cs].
Karimi, A.-H., von Kügelgen, J., Schölkopf, B., and Valera, I. (2020b). Algorithmic recourse under imperfect causal knowledge: a probabilistic approach.
Khemakhem, I., Monti, R. P., Leech, R., and Hyvärinen, A. (2021). Causal Autoregressive Flows. arXiv:2011.02268 [stat].
Kim, H., Mnih, A., Schwarz, J., Garnelo, M., Eslami, A., Rosenbaum, D., Vinyals, O., and Teh, Y. W. (2019). Attentive neural processes. arXiv preprint arXiv:1901.05761.
Kladny, K.-R., Kügelgen, J. v., Schölkopf, B., and Muehlebach, M. (2024). Deep Backtracking Counterfactuals for Causally Compliant Explanations. arXiv:2310.07665 [cs].
Kullback, S. and Leibler, R. A. (1951). On information and sufficiency. The annals of mathematical statistics, 22(1):79–86.
Le, M. K., Do, K., and Tran, T. (2024). Learning Structural Causal Models from Ordering: Identifiable Flow Models. arXiv:2412.09843 [cs].
Li, C., Shen, X., and Pan, W. (2024). Nonlinear causal discovery with confounders. Journal of the American Statistical Association, 119(546):1205–1214.
Li, Q., Han, Z., and Wu, X.-M. (2018). Deeper insights into graph convolutional networks for semi-supervised learning. In Proceedings of the AAAI conference on artificial intelligence, volume 32.
Li, T. and Han, L. (2023). Dealing with explainability requirements for machine learning systems. In 2023 IEEE 47th Annual Computers, Software, and Applications Conference (COMPSAC), pages 1203–1208.
Liang, H. and Gao, J. (2021). How neural processes improve graph link prediction.
Loh, W. W. (2025). Causal inference with unobserved confounding: leveraging negative control outcomes using lavaan. Multivariate Behavioral Research, 60(5):1029–1041.
Lorch, L., Sussex, S., Rothfuss, J., Krause, A., and Schölkopf, B. (2022). Amortized inference for causal structure learning.
Loshchilov, I. and Hutter, F. (2019). Decoupled weight decay regularization.
Luedtke, A. and Fukumizu, K. (2025). DoubleGen: Debiased Generative Modeling of Counterfactuals. arXiv:2509.16842 [stat].
Ma, H., Quinzan, F., Willem, T., and Bauer, S. (2026). Ai alignment in medical imaging: Unveiling hidden biases through counterfactual analysis.
Morgan, S. L. and Winship, C. (2007). Counterfactuals and causal inference. New York: Cambridge.
Murphy, K. P. (2022). Probabilistic machine learning: an introduction. MIT press.
Nasr-Esfahany, A., Alizadeh, M., and Shah, D. (2023). Counterfactual Identifiability of Bjective Causal Models. arXiv:2302.02228 [stat].
Nguyen, T.-L., Collins, G. S., Landais, P., and Le Manach, Y. (2020). Counterfactual clinical prediction models could help to infer individualized treatment effects in randomized controlled trials—an illustration with the international stroke trial. Journal of clinical epidemiology, 125:47–56.
Pawlowski, N., Castro, D. C., and Glocker, B. (2020). Deep Structural Causal Models for Tractable Counterfactual Inference. arXiv:2006.06485 [stat].
Pearl, J. (1996). A causal calculus for statistical research. In Learning from Data: Artificial Intelligence and Statistics V, pages 23–33. Springer.
Pearl, J. (2009). Causality. Cambridge University Press, 2 edition.
Peters, J., Janzing, D., and Schölkopf, B. (2017). Elements of causal inference: foundations and learning algorithms. The MIT press.
Rasal, R., Kori, A., Ribeiro, F. D. S., Xia, T., and Glocker, B. (2025). Diffusion Counterfactual Generation with Semantic Abduction. arXiv:2506.07883 [cs].
Ribeiro, F. D. S., Santhirasekaram, A., and Glocker, B. (2025). Counterfactual Identifiability via Dynamic Optimal Transport. arXiv:2510.08294 [cs].
Ruiz-Perez, D., Isabella, G., Musfiqur, S., Kalai, M., and Giri, N. (2024). Unfolding and de-confounding: biologically meaningful causal inference from longitudinal multi-omic networks using metalica. Msystems, 9(10).
Sanchez-Martin, P., Rateike, M., and Valera, I. (2021). VACA: Design of Variational Graph Autoencoders for Interventional and Counterfactual Queries. arXiv:2110.14690 [stat].
Sanderson, E., Glymour, M. M., Holmes, M. V., Kang, H., Morrison, J., Munafò, M. R., Palmer, T., Schooling, C. M., Wallace, C., Zhao, Q., et al. (2022). Mendelian randomization. Nature reviews Methods primers, 2(1):6.
Schölkopf, B., Locatello, F., Bauer, S., Ke, N. R., Kalchbrenner, N., Goyal, A., and Bengio, Y. (2021). Toward causal representation learning. Proceedings of the IEEE, 109(5):612–634.
Shimizu, S., Hoyer, P. O., Hyvarinen, A., and Kerminen, A. (2006). A linear non-gaussian acyclic model for causal discovery. Journal of Machine Learning Research, 7(72):2003–2030.
Shpitser, I. and Pearl, J. (2012). What counterfactuals can be tested. arXiv preprint arXiv:1206.5294.
Soleymani, A., Raj, A., Bauer, S., Schölkopf, B., and Besserve, M. (2020). Causal feature selection via orthogonal search. arXiv preprint arXiv:2007.02938.
Spirtes, P., Glymour, C., and Scheines, R. (2001). Causation, prediction, and search. The MIT press.
Stovitz, S. D. and Shrier, I. (2019). Causal inference for clinicians. BMJ Evidence-Based Medicine, 24(3):109–112.
Verma, T. S. and Pearl, J. (2022). Equivalence and synthesis of causal models. In Probabilistic and causal inference: The works of Judea Pearl, pages 221–236.
von Kügelgen, J., Mohamed, A., and Beckers, S. (2022). Backtracking Counterfactuals. Version Number: 3.
Weberpals, J., Raman, S. R., Shaw, P. A., Lee, H., Russo, M., Hammill, B. G., Toh, S., Connolly, J. G., Dandreo, K. J., Tian, F., et al. (2024). A principled approach to characterize and analyze partially observed confounder data from electronic health records. Clinical Epidemiology, pages 329–343.
Wu, Y., McConnell, L., and Iriondo, C. (2025). Counterfactual Generative Modeling with Variational Causal Inference. arXiv:2410.12730 [cs].
Xia, K., Pan, Y., and Bareinboim, E. (2022). Neural Causal Models for Counterfactual Identification and Estimation. arXiv:2210.00035 [cs].
Yu, Y., Chen, J., Gao, T., and Yu, M. (2019). DAG-GNN: DAG structure learning with graph neural networks. In Chaudhuri, K. and Salakhutdinov, R., editors, Proceedings of the 36th International Conference on Machine Learning, volume 97 of Proceedings of Machine Learning Research, pages 7154–7163. PMLR.
Zečević, M., Dhami, D. S., Veličković, P., and Kersting, K. (2021). Relating Graph Neural Networks to Structural Causal Models. arXiv:2109.04173 [cs].
Zhang, R., Isola, P., Efros, A. A., Shechtman, E., and Wang, O. (2018). The unreasonable effectiveness of deep features as a perceptual metric.
Zheng, X., Aragam, B., Ravikumar, P., and Xing, E. P. (2018). Dags with no tears: Continuous optimization for structure learning.
Appendix
.1 Equivalence of a Direct MPNN to a Non-directional MPNN on the Dual Graph
This section provides an expressivity result justifying the removal of explicit exogenous nodes from the dual-graph architecture.
Proposition 1 (Expressive sufficiency after eliminating exogenous nodes). Let denote the dual graph containing explicit exogenous nodes, and let denote the reduced graph obtained by removing the exogenous nodes and directly connecting each factual–counterfactual pair .
Assume that the endogenous subgraph of is fully connected. Then, for every function of the endogenous nodes that can be approximated arbitrarily well by a bidirectional MPNN on , there exists a direct MPNN on , with sufficiently large hidden dimension, that approximates the same function arbitrarily well.
Proof. A bidirectional MPNN layer on has the form
where and are neural networks handling incoming and outcoming edges respectively. Since the values of the exogenous variables are not observed, the initial exogenous embeddings are fixed constants,
Consequently, the hidden state of every exogenous node is completely determined by the hidden states of neighbouring endogenous and exogenous nodes. does not have exogenous nodes, so we model them by doubling the hidden dimension of the endogenous nodes. Instead of explicitly representing and , the direct MPNN stores their hidden states inside the corresponding endogenous representations,
Assume inductively that these augmented representations reproduce the hidden states of the bidirectional MPNN after layer .
The bidirectional update of an exogenous node is a continuous function
and analogously for . Since the endogenous graph is fully connected, node receives the representation of through an ordinary directed message. Hence, all arguments of are available locally in the augmented representations. By the universal approximation theorem [Hornik et al., 1989], an MLP can approximate arbitrarily well, allowing the direct MPNN to update the virtual exogenous states.
Next, consider the update of an endogenous node,
The virtual state is stored locally in . Because the endogenous graph is fully connected, node receives the hidden state of every endogenous node. Hence, all arguments of are available to the direct MPNN. Again, the update function can be approximated arbitrarily well by an MLP.
After each layer,
and similarly for . By induction, the hidden representations of all endogenous nodes produced by the bidirectional MPNN can be reproduced arbitrarily closely by the direct MPNN.
Since the readout is performed only on endogenous nodes, reproducing the exogenous hidden states explicitly is unnecessary.
.2 CFGNP Complexity Analysis
We calculate the complexity in each part of the module. We first note that the GAT layer has computational complexity for a graph with nodes and edges and the hidden dimensions go from to [Brody et al., 2021]. Let be the number of edges in the graph with adjacency matrix .
Changing Data Dimension
Applying the MLP to each entry in and takes
operations. Since we use throughout this work we get complexity
Propagation of Observational Information
Each layer of the GAT uses adjacency matrix
With and we get . Further, we have . For one layer we then get computational complexity
For all K layers in the block, we have computational complexity
Mixing Factual Information
Each layer in the module for mixing factual information uses adjacency matrix
With and we get computational complexity . All three layers for this module thus have complexity .
Estimating Counterfactual Graph
Each layer in this block uses adjacency matrix
We then get and . This gives us computational complexity of in each layer.
All layers together give us computational complexity for the entire block.
The MLP layer needs operations.
Overall, the computational complexity of CFGNP is
.3 Permutation Properties of CFGNP
Proposition 2. Let
denote the output of the CFGNP model restricted to the target nodes . Then the CFGNP is
-
permutation equivariant with respect to permutations of the nodes in ; and
-
permutation invariant with respect to permutations of the nodes in .
Proof. In the following, let be the matrix that has 0 on the diagonal and everywhere else 1. Let be the identity matrix. Finally, let be the matrix with only 0.
Let be the permutation matrix associated with a permutation of the variables. We use the convention , where denotes the -th standard basis vector. Consequently, for every node-indexed matrix ,
A permutation represents only a relabelling of the variables and must therefore be applied consistently to every node-indexed input. We define
for every observational sample . We further define
Let be the indicator vector of the intervention set , i.e.,
The indicator vector of the permuted intervention set is . Indeed, for every ,
which is equal to 1 precisely when , or equivalently when .
Recall that the counterfactual input contains the intervention values at the indices in and is zero elsewhere:
For every j,
Thus, the intervention values and the intervention indices are permuted consistently.
We now show the characteristics for each of the model components.
Equivariance of nodewise MLPs. We first consider the nodewise MLPs applied at the beginning of the model. For every observational sample , the same MLP is applied independently to every node. Therefore, .
For the factual observation z, define the nodewise transformation
We now verify permutation equivariance coordinatewise. For an arbitrary :
Since this equality holds for every j,
The same argument applies to the counterfactual input.
Equivariance of the GATs. We now consider the GATs. A GAT is permutation equivariant in the sense that, for a node-feature matrix H, adjacency matrix G, and permutation matrix Q,
For the observational graph, the same permutation is applied to every observational sample and to the aggregation nodes q. The corresponding block-diagonal permutation matrix is
The adjacency matrix consists only of blocks , , and . Since
we have . This suppresses the unchanged adjacency matrix from the notation,
It follows in particular that .
For the graph containing the factual representation z and the aggregated observational representation , define the permutation
Because , permutation equivariance gives
For the factual–counterfactual graph, define
With
we similarly obtain
In particular, the counterfactual representation satisfies .
The final MLP. The final MLP is applied independently to every node of , with the same parameters at each node. Therefore,
Let
denote the nodewise output containing the mixture parameters. The preceding arguments imply that the nodewise output of the model transforms as
The final nodewise output contains one row for each node, and the CFGNP returns only the rows indexed by the target set:
Moreover, the target set is relabelled according to . Since
restricting PR to the indices in yields precisely the same nodewise outputs as restricting R to , but indexed according to the permuted target nodes. Hence,
where denotes the permutation induced by on the target outputs. Therefore,
This establishes permutation equivariance with respect to the target nodes. If the permutation acts only on nodes in , then every target node is fixed and the induced permutation is the identity. The same identity therefore reduces to
which establishes permutation invariance with respect to permutations of the non-target nodes.
.4 Graph-Size and Observation-Count Transferability of CFGNP
The CFGNP architecture can be applied to causal graphs with different numbers of nodes and to observational datasets containing different numbers of samples. In particular, the learnable parameters of the model do not depend on either the graph size n or the number of observational samples . Consequently, a model trained using graphs with n nodes and observational samples can be applied, without modifying its learned parameters, to graphs with m nodes and observational samples.
We formalize this property in the following proposition.
Proposition 3 (Graph-size and observation-count transferability). Let
denote the CFGNP applied to a causal query with n endogenous variables and observational samples. Suppose that the number of message-passing layers is fixed depending on n and independently of , or, alternatively, repeated message-passing iterations reuse the same parameters.
Then the parameter space of is independent of both n and . Consequently, for arbitrary
the same parameter vector defines both
Hence, a CFGNP trained on one graph size and one number of observational samples can be evaluated on different graph sizes and different numbers of observational samples without introducing, removing, or resizing any learned parameters.
Proof. We show that every learnable component of the CFGNP is independent of both the number of endogenous variables n and the number of observational samples .
First, consider the node-wise input transformations. Let
denote the MLP applied to the observational data. For
the same map is applied independently to every node in every observational sample,
Thus, changing either n or changes only the number of evaluations of , but not its input dimension, output dimension, or learned parameters. The same argument applies to the node-wise maps , , , and .
Next, consider a GAT layer. For a node i, its update is of the form
where
and
The learnable quantities W and a depend only on the feature dimensions. They do not depend on the total number of nodes in the graph, the number of edges, or the number of observational samples represented in the graph. Changing n or therefore changes only the set of nodes and neighborhoods on which the same local update rule is evaluated.
We now consider the observational aggregation graph . For n endogenous variables and observational samples, its adjacency matrix is
Thus, contains diagonal blocks , one for each observational sample, and corresponding blocks connecting the observational nodes to the aggregation nodes .
Changing only changes the number of - and -blocks, while changing only changes their dimensions. The construction rule itself remains unchanged. Since the GAT applies the same attention and message-passing functions to every node and edge, its learned parameters are independent of both and .
In particular, if
then changing the number of observational samples only changes the size of and the number of incoming messages available to the aggregation nodes . It does not change the dimensionality of the representation associated with each endogenous variable. Hence, the remainder of the architecture receives the same type of representation regardless of .
Next, consider the graph used to combine the observational representation with the factual observation. For n variables,
For m variables, the corresponding graph is
These graphs have different dimensions but are generated according to the same construction rule. Moreover, the number no longer appears explicitly at this stage, because the observational samples have already been aggregated into the n representations contained in . Therefore, the parameters of the GAT used in this stage are independent of both n and .
The same argument applies to the graph used for counterfactual inference. For n variables,
whereas for m variables,
Changing the graph size changes only the number of nodes and edges on which the shared message-passing functions are evaluated. The learned parameters of the GAT are unchanged. Furthermore, does not affect the dimensionality of the node representations entering this stage.
Finally, the output network is applied independently and identically to each target node,
Changing the number of endogenous variables changes only the number of node-wise predictions, while changing has no effect on the dimensions of the output map. Hence, neither quantity changes the learned parameters of .
Consequently, every learned component of the CFGNP is parameterized only by quantities such as , , , and not by n or . The matrices , , and and the repetition of the observational blocks determine only the structure and size of the computational graph; they contain no learned parameters. Therefore,
for arbitrary
Thus, the same parameter vector can be applied to causal graphs with different numbers of nodes and to observational datasets containing different numbers of samples.
This establishes architectural transferability across both graph size and observation count. It does not, by itself, guarantee identical predictive performance when n or differs substantially from the values encountered during training, since such performance additionally depends on the distribution of training and test instances.
A Extended Model Architecture
In the following, let be the matrix that has 0 on the diagonal and everywhere else 1. Let be the identity matrix. Finally, let be the matrix with only 0.
A.1 Model Input
Our input is a tuple with , , and .
A.2 Changing data dimension
We apply MLPs on each node. On O we apply the same MLP across all nodes. However, for the other parts we want the model to learn to distinguish between nodes we intervene on and the rest. Therefore, we apply an MLP on the indices in z and an MLP on the other nodes. Similarly, we apply the MLP on the indices of and an MLP on the other indices.
A.3 Propagation of Observational Information
We reshape into . Furthermore, we introduce a set of nodes , initialized as .
For the GAT we use the adjacency matrix
We then propagate information on using a Graph Attention Network (GAT) consisting of layers. A single GAT layer updates each node representation by computing attention coefficients over its neighbors. Let denote the representation of node at layer . The attention coefficients are computed as
where W and a are learnable parameters. The node representations are then updated according to
Applying the entire GAT to the initial node representations yields
A.4 Mixing Factual Observation
We construct a new graph and apply a GAT consisting of three layers.
The resulting adjacency matrix is
Applying the GAT three times yields
A.5 Estimating Counterfactual Distribution
We build a new graph with adjacency matrix
To propagate information through the entire graph, we use GAT layers, collected in the MPNN , which yields
Finally, we apply an MLP with hidden dimension . After reshaping, the network outputs the parameters for each node.
B Experimental Setup
B.1 Model Hyperparameters
For the (semi-)synthetic datasets, we use a hidden dimension of 80, 5 attention heads in the graph attention network (GAT) layers [Brody et al., 2022], and a batch size of 128. For the predicted MoG we use Gaussian mixture components. For the image-based counterfactual datasets, which consist of chest X-rays, we use a hidden dimension of 256, 9 attention heads in the GAT layers, and a batch size of 32. We choose a hidden dimension of 256 to match the dimensionality of the encoded image representations, providing a natural choice for the width of the network.
We train each model for 200 epochs although we include early stopping after 25 epochs. Further, we use the AdamW [Loshchilov and Hutter, 2019] with initial learning rate and a weight decay of .
B.2 CheXpert Experiment Setup
We use for the CheXpert samples. For each image, the disease information was represented by the 13 CheXpert findings. We combine them into one No Finding attribute. The Disease attribute is just the complement. The resulting dataset has some data imbalances. The Sex feature has 41.24% female values and the rest is male. Only 17.24% of samples have PA as value and only 9.05% of the samples exhibit a disease. Finally, the average age in the samples is 60.66 years.

Age: loss
Age: val MAE
No Finding: loss
No Finding: val AUC
Sex: loss
Sex: val AUC
Figure 5: The training curves of the classifiers and regression models used for the classification of the generated CheXpert images.
Counterfactual Evaluation. To evaluate which attributes a generated counterfactual image exhibits, we use classifiers/regression models. For the classifiers and regression models of attributes Sex, AP/PA, Age, and Disease we stick closely to Gichoya et al. [2022]. We apply the pretrained ResNet [He et al., 2016] and subsequently apply multiple MLP layers. For regression attributes we have final dimension 1 and for the classification attributes we apply the softmax activation function in the end to normalize the outputs to probabilities. We add here the performance of the classification/regression models of the features. The Sex classifier has a test accuracy of 0.9901 and a ROC-AUC of 0.9995. The Age regression model has MAE 6.1473. Further, the AP/PA classifier has both accuracy and ROC-AUC of 1.0. Finally, the No Finding classifier has accuracy 0.9010 and ROC-AUC 0.9314. Figure 5 shows the training curves for each of the classifiers.
CheXpert training objective. To the normal classification/regression losses we also add a reconstruction loss to ensure that the images look like actual images. We use MSE, LPIPS[Zhang et al., 2018], and the total variation [Javanmardi et al., 2018] of , to get
with , , and . The resulting total loss combines the classification, regression, and reconstruction objectives:
where C and R denote the sets of classification and regression features, respectively.
B.3 Synthetic Experiments Setup
This appendix gives the complete definitions of the SCMs used in the (semi-) synthetic experiments. Their definitions follow the benchmark specification in Appendix E of Sanchez-Martin et al. [2021]. They are reproduced here so that the experimental data-generating processes can be understood without the original paper. We also keep to Sanchez-Martin et al. [2021] for the computation of the standard deviation of the test MSE. We train the model with 5 different seeds and then compute mean and standard deviation of the runs. We use in all synthetic experiments.
B.3.1 Triangle

Figure 6: The causal graph of the triangle dataset. The causal graph has three nodes and three edges.
The Triangle SCM has the underlying causal graph as depicted in Figure 6. Hence affects through the direct path and through the mediated path .
Exogenous distributions. For the LIN and NLIN variants,
For NADD,
The remaining noises are
Here the second parameter of follows the convention used in the benchmark specification.
Linear (LIN).
Nonlinear additive (NLIN).
The causal mechanisms are nonlinear, but each exogenous variable enters its structural equation additively.
Nonlinear non-additive (NADD).
The function returns the sign of its argument.
B.3.2 M-graph

Figure 7: The causal graph of the M-shape data. It has five nodes and four edges.
The M-graph contains five endogenous variables as shown in Figure 7. All exogenous variables are independent standard normal variables:
Linear (LIN).
Nonlinear additive (NLIN).
Nonlinear non-additive (NADD).
B.3.3 German Loan

Figure 8: The causal graph of the German loan data. The nodes are real attributes used for German credit rating system. they are connected based on the real-world connections.
The Loan benchmark is a semi-synthetic SCM from the causal-recourse literature and is inspired by the German Credit domain. It contains seven endogenous variables as shown in Figure 8. In the figure, G is gender, A age, E education, L loan amount, D loan duration, I income, and S savings.
The structural assignments are
Here is one if and zero otherwise.
The exogenous distributions are
B.4 Structural Equations for Artificial Graphs
Variables are generated as , where is sampled from the following set of transformations:
Linear:
Sum-sqrt:
Sum-sine:
Sum-tanh:
Geometric mean:
Log-sum-exp:
Sqrt-sum:
B.5 Identifiability in a Two-Node SCM
Setup. Let follow the SCM
where , are independent, and
Here a controls the observational mechanism, whereas controls the cross-world coupling.
Proposition 4 (Observational invariance). For every ,
Hence the observational distribution is independent of . The same is true of the intervention .
Proof. Since
we have , which gives (51). Under ,
again independently of .
Backtracking semantics. Let the factual evidence be
To construct a counterfactual world satisfying , we use the minimum-change exogenous coupling
Equivalently, (52) is the solution of
for any . Thus backtracking changes only the exogenous realization necessary to produce while preserving the downstream noise .
Theorem 5 (Backtracking counterfactual). Under (48)–(52),
where
and
Moreover, (53) is identical to the corresponding abduction-action-prediction counterfactual.
Proof. The evidence fixes and imposes
With , Gaussian conditioning gives
Backtracking changes to while preserving W, hence
Therefore
and
Since
substitution yields (53)–(54). The interventional abduction–action–prediction construction evaluates the same quantity under the same conditional law (55), so the two counterfactual distributions coincide.
Corollary 6 (Cross-world non-identifiability). Although is invisible to every observational and interventional distribution, it changes the backtracking counterfactual whenever is non-constant. In particular,
For ,
whereas for the counterfactual has positive conditional variance for almost every with .
For ,
and
Use the prior
and let
be observational context data generated from (51). Writing
we get for the optimal backtracking predictive
Proposition 7 (Exact posterior and model average). The likelihood is independent of , so
With
we have
where
Consequently,
where
Proof. Proposition 4 implies that the likelihood does not depend on , which yields the posterior factorization. (60) is the Gaussian posterior for weighted linear regression. Finally, substituting into (53) gives
Marginalizing the Gaussian posterior over a gives (61).
Identifiable versus non-identifiable regimes. Let
denote the backtracking counterfactual under the true mechanism. As ,
and therefore
If , the limit in (62) equals . If instead is non-degenerate, then for almost every with the map
is non-constant, so the limiting Bayes predictor remains a genuine mixture over observationally indistinguishable cross-world mechanisms.
Thus even infinite observational data identifies a but not : uncertainty about the observational mechanism vanishes, while uncertainty about the backtracking counterfactual need not.
C Additional Results
C.1 Additional CheXpert Results
C.1.1 CheXpert Experiments
We include some counterfactual images generated by the model.
Original

Counterfactual
Factual - Counterfactual
Figure 9: Example counterfactual of a CheXpert image. Observed factual unit (left) has age 80 and the intervention value is 58 in the counterfactual (middle). The difference between the pixels is on the right.
Original

Counterfactual
Factual - Counterfactual
Figure 10: Example counterfactual of a CheXpert image. Observed factual unit (left) has AP/PA as 1 and the intervention value is 0 in the counterfactual (middle). The difference between the pixels is on the right.
Original

Countertactual
Factual - Counterfactual
Figure 11: An image where the observed factual unit of age is 74 and the counterfactual intervention is 85.
C.1.2 CheXpert Out-of-Distribution Experiment
This model was trained with sex chosen to be the out-of-distribution feature. However, during inference the sex feature is included again to test the performance.
Out-of-Distribution Feature Sex. We here include the results when the model was trained with OOD feature sex.
Original

Countertactual
Factual - Counterfactual
Figure 12: An image where the observed factual unit of age is 65 and the counterfactual intervention is 72. The model was trained with OOD index sex.
Original

Countertactual
Factual - Counterfactual
Figure 13: An image where the observed factual unit of AP/PA is 0 and the counterfactual intervention is 1. The model was trained with OOD index sex.
Out-of-Distribution Feature Age. We here include the results when the model was trained with OOD feature age.
Original

Counterfactual
Factual - Counterfactual
Figure 14: An image where the observed factual unit is age 30 and the counterfactual intervention is age 52. The model was trained with OOD index age.
Original

Counterfactual
Factual - Counterfactual
Figure 15: An image where the observed factual unit of sex is 1 and the counterfactual intervention is 0. The model was trained with OOD index age.
Out-of-Distribution Feature AP/PA. We here include the results when the model was trained with OOD feature AP/PA.
Original

Counterfactual
Factual - Counterfactual
Figure 16: n image where the observed factual unit of sex is 0 and the counterfactual intervention is 1. The model was trained with OOD index AP/PA.
Original

Counterfactual
Factual - Counterfactual
Figure 17: An image where the observed factual unit is age 26 and the counterfactual intervention is age 64. The model was trained with OOD index AP/PA.
Out-of-Distribution Feature Disease. We here include the results when the model was trained with OOD feature disease.
Original

Counterfactual
|Factual - Counterfactual|
Figure 18: An image where the observed factual unit of AP/PA is 0 and the counterfactual intervention is 1. The model was trained with OOD index disease.
Original

Counterfactual
|Factual - Counterfactual|
Figure 19: An image where the observed factual unit is age 67 and the counterfactual intervention is age 37. The model was trained with OOD index disease.
C.2 Graph Size Results


Figure 20: Performance (MSE) of models with regard to the size of the causal graph for sqrt-sum (left) and sum-sqrt (right) structural equations. The MSE is averaged over distinct causal graphs. Vertical lines show the 25th and 75th quantiles.


Figure 21: Performance (MSE) of models with regard to the size of the causal graph for geometric-mean (left) and sum-tanh (right) structural equations. The MSE is averaged over distinct causal graphs. Vertical lines show the 25th and 75th quantiles.
C.3 Runtime of Experiments
As before, we use a batch size of 128 for the (semi-)synthetic experiments and a batch size of 32 for the CheXpert dataset. All experiments are run on an NVIDIA H100 GPU.
| Dataset | CFGNP (Ours) | BGM | CFM | VACA |
|---|---|---|---|---|
| German Loan | 31.5719s | 5.2537s | 115.1188s | 5.3015s |
| Triangle LIN | 8.1853s | 2.9878s | 26.3716s | 3.7258s |
| Triangle NLIN | 7.9175s | 3.0323s | 26.2195s | 3.7365s |
| Triangle NADD | 7.9084s | 3.0364s | 26.3470s | 3.7963s |
| M-Shape LIN | 12.9088s | 3.3865s | 41.5352s | 3.8361s |
| M-Shape NLIN | 12.9274s | 3.3941s | 41.8969s | 3.8385s |
| M-Shape NADD | 12.9784s | 3.4396s | 41.9043s | 3.8209s |
| Artificial Size 10 | 18.4545s | 3.8820s | – | 2.4226s |
| Artificial Size 15 | 27.6381s | 5.3534s | – | 2.6127s |
| Artificial Size 20 | 39.2469s | 9.2543s | – | 2.6588s |
| Artificial Size 25 | 54.7471s | 8.5072s | – | 2.5591s |
| Artificial Size 30 | 74.2878s | 13.9569s | – | 2.7384s |
Table 4: Runtime comparison of CFGNP (Ours), BGM, CFM, and VACA across (semi-) synthetic datasets. The datasets were used throughout the results section.
| Dataset | CFGNP (Ours) | VCI | DeepBC |
|---|---|---|---|
| CheXpert | 47.7369s | 3.8506s | 6032.4057s |
Table 5: Runtime comparison of CFGNP (Ours), VCI, and DeepBC on the CheXpert dataset.
C.4 Convergence in (Non-)Identifiable Cases
We empirically evaluate the convergence behaviour of CFGNP.
To this end, we evaluate CFGNP on an SCM for which the ground-truth counterfactual distribution can be computed analytically. We consider a causal graph with two nodes and at most one edge. In Appendix B.5, we show that, under certain choices of parameters, such an SCM is identifiable. Furthermore, we analytically compute the ground-truth counterfactual distribution
given the true causal graph and structural mechanisms.
We compare the distribution predicted by CFGNP to both and
which conditions only on the observations rather than on knowledge of the SCM ().
Subsequently, we repeat the experiment for a non-identifiable parameterization of the two-node SCM.
In both cases, we use 40000 samples, split into 21000 train samples, 9000 validation samples, and 10000 test samples.

Figure 22: KL divergences for the two-node experiments across different numbers of observations supplied to each sample. Vertical lines show the 10th and 90th quantiles. Results are shown for the identifiable (left) and non-identifiable (right) settings.
C.5 Transformer Ablation
To assess the importance of the CFGNP architecture, we consider a Transformer-based ablation that replaces the core CFGNP processing mechanism with a standard Transformer encoder while retaining the same input and output representations. The observation, factual unit, and counterfactual/intervention inputs are first embedded separately using the same embedding dimensionality as CFGNP. Again, eparate embeddings are retained for intervened and non-intervened variables. Then, we concatenate all these vectors and run a transformer architecture on them. The output of the transformer for is handled in the same way as for CFGNP
Unless stated otherwise, all hyperparameters are kept identical to those used for CFGNP, including the base hidden dimension, number of attention heads, number of mixture components, and input/output dimensionality. As in CFGNP, the effective embedding dimension is given by the base hidden dimension multiplied by the number of attention heads. The Transformer-specific hyperparameters are five encoder layers, a feed-forward dimension of four times the embedding dimension, a dropout rate of 0.1, and GELU activations. Pre-layer normalization is used within each Transformer encoder layer, followed by a final layer normalization after the encoder stack.
Table 6 compares the resulting Transformer ablation against the full CFGNP model.
| Dataset | Variant | CFGNP (Ours) | Transformer |
|---|---|---|---|
| MSE | |||
| Triangle | LIN | ||
| NLIN | |||
| NADD | |||
| M-shape | LIN | ||
| NLIN | |||
| NADD | |||
| German Loan | - | ||
Table 6: Mean MSE standard deviation of the full CFGNP model and the Transformer ablation across the Triangle, M-shape, and German Loan datasets. Lower values indicate better performance. Best scores are marked in bold.