Manuscript Offprint
arXiv:2610.35679CounterFlow: Target-Conditioned Flow Matching for Visual Counterfactuals
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
In eXplainable AI, counterfactual explanations have gained significant traction by offering users direct, intuitive, and actionable insights into model decisions. We introduce CounterFlow, a novel framework based on Conditional Flow Matching that generates visual counterfactual explanations by directly steering a source image toward a user-specified target class. By leveraging target-conditioned vector fields, CounterFlow identifies highly realistic semantic modifications while requiring substantially lower computational overhead than traditional GAN- or diffusion-based architectures. Empirical evaluations on standard benchmarks demonstrate that CounterFlow achieves state-of-the-art performance in both visual realism and target class switching. By working directly in the raw pixel space, CounterFlow offers a more practical solution for real-world deployment.
1 Introduction
Context. On the one hand, in generative modeling, diffusion models currently dominate the landscape for high-quality image, video, and audio synthesis (Rombach et al., 2022; Ho et al., 2022; Liu et al., 2023a). However, they are also well-known for their slow training times and their stochastic sampling paths. To address these limitations, Lipman et al. (2023); Albergo and Vanden-Eijnden (2023); Liu et al. (2023b) introduced Conditional Flow Matching (CFM). CFM is a generative modeling framework based on Continuous Normalizing Flows (CNFs) that uses standard regression objectives for training. Moreover, instead of relying on diffusion processes, CFM generates examples by integrating the CNF's ODE along deterministic trajectories. On the other hand, the generative models' ability to generate complex data distributions and thus to produce realistic examples is particularly appealing for eXplainable Artificial Intelligence (XAI, Dwivedi et al., 2023), where one aims to produce counterfactual explanations (Wachter et al., 2017), i.e., examples (i) close to a given input, (ii) plausible, and (iii) that change the model's prediction. Unlike adversarial examples that rely on imperceptible noise to fool the classifier, counterfactual examples expose meaningful changes, helping users to trust the model while enabling developers to debug it. Our work leverages CFM to create counterfactual explanations: rather than generating images from random noise, our approach transports an input sample toward a counterfactual conditioned on a user-defined target class, while jointly optimizing for plausibility and proximity; see Figure 1.
Related Work. Prior work on image counterfactual explanations falls into two categories: instance-based and generative approaches. Instance-based methods (see e.g., Goyal et al., 2019; Keane and Smyth, 2020) select examples from the training set using similarity metrics to modify the input sample.
Corresponding Author. Email: prenom.nom@inria.fr

(a) MNIST
dog→bird
horse→truck
dog→horse
bird→deer
airplane→auto

(b) CIFAR10
Figure 1: Qualitative counterfactual explanations generated by CounterFlow on (a) MNIST and (b) CIFAR10. We show five examples per dataset as source/counterfactual pairs (source on the left of each pair, the corresponding counterfactual generated by CounterFlow on the right), and we indicate the source→target class transition above each pair. CounterFlow preserves source-specific style, such as stroke thickness and digit slant on MNIST, or object color and orientation on CIFAR10, modifying only what is needed to reach the target class.
x. However, they require access to the training set at inference and cannot tailor a minimal, plausible edit to a specific example x. We focus instead on generative approaches, a more recent line of work (Khorram and Fuxin, 2022; Jeanneret et al., 2024; Weng et al., 2024; Augustin et al., 2022; Cao et al., 2025) that produces more plausible examples, which we group by generative backbone: GANs, diffusion models, or CFM.
• GAN. C3LT (Khorram and Fuxin, 2022) encodes the input (with a VAE encoder) into a latent space, in which it learns two cycle-consistent transformations per pair of classes before decoding with the generator of a GAN. It thus requires one model set per pair, impractical for many classes, and its fidelity is bounded by the VAE's reconstruction quality.
• Diffusion. DiME (Jeanneret et al., 2024) generates a counterfactual by corrupting the input and denoising it through the backward diffusion process (an inner loop of several steps); at each outer step, the classifier gradient computed on this denoised estimate refines the corrupted instance, and the process repeats until it converges to a valid counterfactual. FastDiME (Weng et al., 2024) instead computes this gradient directly from the model's one-step denoised estimate, bypassing the inner loop entirely. ACE (Jeanneret et al., 2023) takes a different route: it builds an adversarial attack against the classifier and lets the diffusion model's own denoising process project this attack back onto the manifold of realistic images, turning an imperceptible perturbation into a semantically meaningful one. DVCE (Augustin et al., 2022) starts the reverse diffusion from a partially noised version of the input, rather than pure noise, and steers the process by projecting the gradient of an adversarially robust classifier onto a cone around the target classifier's own gradient direction whenever the two disagree, avoiding non-semantic changes. More recently, MaskDiME (Guo et al., 2026) improves on DiME's efficiency and spatial precision with a training-free, adaptive dual-mask mechanism guided by classifier gradients that restricts updates to a localized region rather than the whole image. Regardless of the specific guidance scheme, diffusion-guidance methods must reapply their guidance at every one of many denoising steps, making inference slow: DiME's inner diffusion loop scales quadratically with the number of diffusion steps, and even FastDiME's one-step approximation, despite yielding a roughly empirical speedup, only reduces this to a linear scaling and remains markedly slower than a single forward pass. ACE and DVCE compound this same per-step cost further, respectively adding an adversarial attack and a robust-classifier gradient computation at every step.
• CFM. LeapFactual (Cao et al., 2025) builds on Conditional Flow Matching (CFM) to generate counterfactuals. It learns a class-conditional generative flow from a Gaussian prior to the latent space of a pretrained VAE, and repurposes this flow for counterfactual generation through a lift-and-land procedure. Given an input, its VAE encoding is first lifted toward the prior under the input class by solving the learned ODE backward, and then landed back into the latent space under the target class by solving the ODE forward. This “leap” must be repeated a dataset-dependent number of times, with each leap requiring a VAE decoding and a classifier query.
Our work also builds on CFM, but uses it in a fundamentally different way. We directly learn a transport from an input image to its counterfactual. This avoids (i) the need for multiple costly leaps, (ii) the intermediate traversal through a prior space, and (iii) VAE encoding and decoding, whose reconstruction fidelity can limit the quality of the generated counterfactuals.
Our contributions. To address the drawbacks of the previous methods, our contributions are as follows:
• We introduce CounterFlow, the first CFM framework that directly conditions the vector field on both the source and target class, enabling a single model to transport examples between any pair of classes in their original pixel representation. Moreover, CounterFlow generates a counterfactual by integrating a single (learned) ODE from source to target, with no additional VAE decoding or iterative optimization at inference.
• To enable the learning of the transport map, we introduce two complementary contributions: a latent-space nearest-neighbor pairing strategy and an auxiliary classification loss. The pairing algorithm leverages the embedding space of a pretrained VAE to associate each source example with a semantically similar target example, thereby reducing the transport distance that the flow must learn. The auxiliary classification loss further guides the flow toward transformations that induce the desired change in the classifier's prediction.
• We provide an empirical evaluation covering conditional validity, plausibility, and computational efficiency, a combination rarely reported together in prior work, demonstrating that CounterFlow matches or improves on state-of-the-art generation quality at a fraction of the computational cost of GAN- or diffusion-based alternatives.
This objective makes an adversarial example: an example close to for the distance that classifies as .
However, this definition can yield implausible examples. Indeed, according to the true data distribution , sampling may be unlikely, i.e., may be small. Hence, in this paper, we instead adopt the definition of Artelt and Hammer (2020), where we aim to generate a plausible example , i.e., one for which is higher than a constant :
denotes the joint distribution on a sample of size m, while U is a uniform distribution on a given set.
This remains a difficult problem, as it requires both defining the distance and solving a generally non-convex optimization problem. We therefore approximate it: to generate plausible examples , we use a conditional flow matching model, introduced in the next section. Moreover, to indirectly minimize the distance while respecting the condition , we further introduce our method: CounterFlow.
3 Background on Conditional Flow Matching
Generative models aim to approximate from by starting from a base distribution (classically a standard Gaussian , with the zero vector and the -identity matrix) and learning to transport it toward the target distribution , so that . A Continuous Normalizing Flow (CNF, Chen et al., 2018) is a generative model that achieves this by defining a time-dependent velocity field parameterized by , which generates samples according to
Thanks to this equation, starting from , the point is obtained by solving the integrated version of Equation (2), i.e., we have
In other words, the distribution is defined by the push-forward measure , and so transports samples from the base distribution to the distribution . It defines a probability path interpolating between a source distribution and a target distribution . Hence, training a CNF amounts to finding such that approximates , given only . However, training CNFs through maximum likelihood can be computationally expensive due to the need to solve ODEs during optimization. Besides, there exists an infinite number of probability paths, which leads to instability during training (see e.g., Lipman et al., 2023). Hence, Flow Matching (FM) reformulates the training of continuous flows as a supervised regression problem on velocity fields. Instead of learning the transport dynamics indirectly through maximum likelihood, FM supervises the velocity field along predefined trajectories connecting the source and target distributions. The model is then trained to match this target velocity via the objective
However, depends on the unknown q, making intractable in practice. Fortunately, Lipman et al. (2023, Theorem 2) proved that the loss has the same gradient as the following loss
where is now a conditioning variable drawn from a coupling distribution that determines which distribution and target velocity govern each sample. Classically (Lipman et al., 2023; Tong et al., 2024), is a pair of examples, with
In other words, the conditional path is a Dirac point mass (i.e., a degenerate distribution) supported on , and is the (unique) velocity field consistent with through the continuity equation (Lipman et al., 2023). Moreover, does not need to be Gaussian nor to be independent (Tong et al., 2024): the same construction can transport examples between two data distributions, as we do in CounterFlow (see Section 4 further).
The above objective extends naturally to conditional generation by introducing a context variable (e.g., a class label), on which both the coupling and the velocity field depend: unlike , which only selects the path for a given pair, is additionally fed to the network itself so that the learned velocity field can be evaluated for any desired context at inference. The context and the pair are now drawn jointly from the same coupling, , and we have
Note that the path and target velocity remain indexed by z alone, as in the unconditional case, only the learned field is additionally conditioned on c, which is the mechanism CounterFlow relies on to control the source and target class at inference.
4 CounterFlow
This section introduces our method, namely CounterFlow, which learns a velocity field that generates a counterfactual to approximate Equation (1). To do so, we define the loss derived from the coupling (and a minibatch version ) together with the conditional path of Equation (5), where ; and we end by introducing the training and inference procedures of CounterFlow.
4.1 Defining the loss
Context and coupling . Since Equation (1) transports with toward a counterfactual with , we define the context as the pair of labels . Then, we sample two minibatches of size sharing this context, and , where is the set of examples in that classifies as . Finally, we pair their examples (see below) to form the set of pairs . Overall, Algorithm 1 defines the distribution where . Moreover, when we consider only one example from the minibatch , we say that (as in Equation (6)), which is equivalent to drawing and sampling uniformly a single index of the minibatch, i.e., we have , , .
Latent-space pairing. The pairing , created by Algorithm 1, aims to minimize a distance where and , which first requires the choice of the distance itself. For CounterFlow, we aim for a distance that measures whether and are semantically related; hence, we use the latent space of a frozen and pretrained Variational Autoencoder (VAE) and we set
where denotes the latent-space embedding of the input . Then, to obtain the semantically related pairs, for each example , where , we associate the closest example according to the distance , where is the index in of the nearest neighbor of (see Line 4).
Loss . We are now able to define the loss minimized during the training procedure. This loss is the weighted sum of a CFM-like loss and a loss dedicated to the change-of-class task.
Algorithm 1: PairByEmbedding
Input: VAE encoder
1: Sample the labels
2: Sample minibatches and .
3: for do
4:
5: end for
6:
7: return
Algorithm 2: Training procedure of CounterFlow
Input: Source distribution , target distribution , flow network , VAE encoder , classifier
1: while Training do
2: Sample .
3: for do
4: Sample .
5: Compute and .
6: Compute the flow matching loss .
7: Compute the classification loss
8: end for
9: Update using .
10: end while
11: return
The loss is obtained from Equation (6) with our coupling , and with the conditional path and the velocity of Equation (5):
Moreover, while Equation (1) requires generating realistic examples (according to ) with a minimal distance , it also requires an example such that . We add the loss , weighted by , to further enforce a velocity field leading in the right direction. It is defined by
where CE is the classical multiclass cross-entropy loss, and is defined as taking a small Euler step along the predicted velocity, i.e. . The weighting factor progressively increases the influence of the classification objective: close to the source, the optimization is dominated by the flow matching objective, while near the target the classification constraint becomes stronger.
4.2 Training procedure (Algorithm 2)
To minimize the loss function , we use the training loop described in Algorithm 2. A training step can be described in the following way. We first sample thanks to Algorithm 1
(line 2), which corresponds to the labels and the minibatch with the pairs of examples established using nearest-neighbor matching in the latent space of a pretrained VAE encoder. Then, for each matched pair , we sample (line 4) and construct the interpolated samples (line 5). Then, we compute the losses for in lines 6 and 7. After computing the loss on the minibatch, we update in line 9 using, e.g., Adam optimizer.
4.3 Inference
Once is trained, generating a counterfactual no longer requires any pairing, VAE encoding, or mini-batch construction. CounterFlow requires only an input sample (with the prediction ) and a desired target class . The source class is obtained using the pretrained classifier, while the target class is either specified by the user or sampled uniformly among the remaining classes. Starting from the input , we solve the learned ordinary differential equation defined in Equation (2), by integrating from to , as shown in Equation (3). The endpoint of the trajectory is returned as the generated counterfactual explanation .
5 Experiments
We now turn to an empirical evaluation of CounterFlow against state-of-the-art counterfactual generation methods. Note that our implementation is based on the torchcfm library (Tong et al., 2024), which provides the Conditional Flow Matching framework used to train CounterFlow. The source code to reproduce the experiments will be made publicly available at this link.
5.1 Setting
Datasets. We evaluate CounterFlow on two standard image classification benchmarks: MNIST and CIFAR-10, MNIST consists of 70,000 grayscale images of handwritten digits belonging to 10 classes, with a spatial resolution of pixels. CIFAR-10 contains 60,000 color images of size pixels, evenly distributed among 10 object categories. These two datasets provide complementary evaluation settings, ranging from a simple handwritten digit classification task to a natural image classification benchmark. For all experiments, we use the standard training and test splits provided with each dataset. Section A.4 discusses why we do not extend the comparison to larger benchmarks such as ImageNet.
CounterFlow’s inference. For all quantitative evaluations, CounterFlow is integrated via the Euler solver with 40 steps. This fixed-step solver provides a more deterministic evaluation protocol and allows a fair comparison of the computational cost across methods. For qualitative visualizations, we instead use the Dormand–Prince solver (Dormand and Prince, 1980) (dopri5) to obtain smoother trajectories and higher-quality visual results.
Methods. We compare CounterFlow against three recent counterfactual generation methods: C3LT (Khorram and Fuxin, 2022), FastDiME (Weng et al., 2024), and LeapFactual (Cao et al., 2025), where we use the official implementations. Among diffusion-guidance methods, we retain only FastDiME as a representative baseline: DiME and ACE are prohibitively expensive to run at scale due to their inner-loop or per-step attack computations; DVCE requires an adversarially robust classifier, a constraint that our method does not rely on and that we therefore do not impose in our experiments; and MaskDiME's masking mechanism restricts edits to a localized region, which conflicts with our evaluation setting where the change may need to affect the whole image. Beyond this choice, neither of the two remaining baselines, namely LeapFactual and FastDiME, is applicable to both datasets. LeapFactual relies on
The hyperparameters of CounterFlow are listed in Appendix.
a compact VAE latent space to remain tractable, which does not scale to CIFAR-10 without dominant reconstruction artifacts and a much costlier latent flow, so we evaluate it only on MNIST. Conversely, FastDiME depends on pretrained OpenAI diffusion models built for natural images, so we evaluate it only on CIFAR-10.
Models to be explained. To ensure a fair comparison, all methods rely on the same pretrained image classifier for a given dataset. For MNIST, we trained a simple convolutional neural network achieving an accuracy of 99.9% on the test set. For CIFAR-10, we use a pretrained RepVGG-A2 classifier (Ding et al., 2021) with publicly available weights from the pytorch-cifar-models repository (distributed through the official PyTorch Hub interface), achieving a test accuracy of 94.8%. Both classifiers are frozen during training of counterfactual models and are used consistently for counterfactual generation and metrics computation across all competing methods.
Metrics. We evaluate the counterfactual explanations along four axes: effectiveness (reaching ), proximity to the source (a distribution-level counterpart of the distance minimized per example in Equation (1), measured in a semantic feature space rather than in a pixel space), realism (the plausibility constraint , also from Equation (1)), and computational efficiency. We operationalize the evaluation of these axes through the following five metrics.
• Conditional Validity measures the proportion (in %) of generated counterfactuals that are classified as the desired target class , i.e., whether we have .
• computes the Fréchet Inception Distance between the generated counterfactuals and real samples from the target class, quantifying realism: lower values indicate that the generated samples better match the distribution of the desired class.
• computes the Fréchet Inception Distance between the generated counterfactuals and the original source class, measuring proximity to the source: lower values indicate that the counterfactuals remain closer to the original data distribution, suggesting that fewer semantic changes were applied to reach the target class.
• FLOPs / sample measures the computational cost required to generate a single counterfactual explanation. It includes the complete inference pipeline, i.e., all neural network evaluations required by the ODE solver. This metric provides an implementation-independent estimate of inference complexity.
• Model Size reports the total number of trainable parameters of each method, allowing comparison of their memory footprint and model complexity.
Following the standard definition of the Fréchet Inception Distance (FID, Heusel et al., 2017), feature statistics for and are extracted from pretrained image classification networks. For CIFAR-10, we use the pretrained Inception-V3 network available in torchvision. Since ImageNet-pretrained models are not well suited for handwritten digit recognition, for MNIST we instead compute features using the pretrained convolutional classifier employed throughout our experiments. FID is then computed between the Gaussian statistics of the extracted features from the generated counterfactuals and those of the corresponding source or target class, i.e., on the target class and on the source class. Note that, since these statistics are estimated from the subset of test examples belonging to a single class, rather than from the full test set as in standard, unconditional FID computations, the reported values are higher than those typically observed in unconditional image generation. We therefore focus on relative comparisons between methods under the same evaluation protocol rather than on the absolute reported numbers.
Table 1: (a) Quantitative results and (b) Ablation of the pairing used to train CounterFlow: latent-space nearest neighbor (Algorithm 1) vs. random. Higher conditional validity (CV) is better, while lower FID scores indicate that the generated counterfactuals are closer to the target or source distributions. Lower FLOPs/sample and model size (MS) are preferred for computational efficiency.
| Method | CV↑ | FIDt↓ | FIDs↓ | FLOPs↓ | MS↓ |
|---|---|---|---|---|---|
| MNIST | |||||
| C3LT | 99.0 | 187.89 | 4310.01 | 223.86M | 480.81M |
| LeapFactual | 98.6 | 217.08 | 2625.52 | 0.86M | 56.95K |
| CounterFlow | 99.6 | 105.70 | 3224.54 | 174.66M | 4.64M |
| CIFAR10 | |||||
| C3LT | 99.0 | 115.04 | 153.41 | 3.93G | 481.33M |
| FastDiME | 16.0 | 159.86 | 175.64 | 1586.63G | 52.55M |
| CounterFlow | 100.062.54 | 117.03 | 1.73G | 39.36M | |
(a) Quantitative results
| Pairing | CV↑ | FIDt↓ | FIDs↓ |
|---|---|---|---|
| MNIST | |||
| Random99.4 | 111.98 | 3634.20 | |
| Latent | 99.6 | 105.70 | 3224.54 |
| CIFAR10 | |||
| Random99.9 | 63.27 | 125.07 | |
| Latent | 100.062.54 | 117.03 | |
(b) Pairing used to train CounterFlow

(a) MNIST

(b) CIFAR10
Figure 2: CounterFlow trajectories for five (MNIST) and six (CIFAR10) samples, from source to target class (labeled for CIFAR10). Border color indicates the classifier's prediction along the path: red for the source class, green for the target class.
5.2 Quantitative Results
Table 1a reports the quantitative comparison between CounterFlow and representative counterfactual generation methods on MNIST and CIFAR-10; a radar-plot visualization is provided in Figure 3 in the appendix.
MNIST. CounterFlow reaches the highest conditional validity (99.6%) and the lowest target FID while remaining close to the source, confirming that the learned conditional transport reliably reaches the target class with a single ODE integration. LeapFactual stays closer to the source but has the highest target FID, reflecting a more conservative transformation. C3LT performs worst overall and requires by far the largest model, due to its per-class-pair VAE, GAN, and mapping networks.
CIFAR-10. CounterFlow is best on all five metrics: it reaches 100% conditional validity, nearly halves C3LT's target FID while also lowering its source FID by a quarter, and needs roughly half the inference FLOPs and an order of magnitude fewer parameters. Improving both FIDs at once is the signature of a near-minimal transport: counterfactuals that fall within the target class without drifting away from the source image. FastDiME reaches only 16% conditional validity despite a diffusion backbone 900× more expensive per sample, and has the worst FID on both axes; with so few samples switching class, these scores reflect generic realism rather than class transfer.
Overall, CounterFlow achieves state-of-the-art counterfactual validity and the best realism/proximity trade-off on CIFAR-10, while substantially reducing inference complexity compared with prior flow-and diffusion-based approaches.
Ablation. Table 1b shows that replacing latent-space pairing with random pairing consistently lowers conditional validity and raises both target and source FID on both datasets, mostly through the source FID on CIFAR-10. Pairing semantically similar examples yields simpler transport trajectories that are easier for the conditional velocity field to approximate, whereas random pairing often associates visually unrelated samples, leading to harder-to-learn trajectories and lower-quality counterfactuals. Section A.3 further ablates , the conditioning context and the explained classifier.
5.3 Qualitative Results
Style Preservation. Figure 1 shows five source/counterfactual pairs per dataset. On MNIST, CounterFlow preserves writer-specific style, such as stroke thickness and slant – e.g., the 4→5 transition retains the source’s thin strokes – and keeps the digit’s orientation, rather than collapsing to a generic class prototype. On CIFAR10, the same near-minimal-path behavior appears at the scene level: the background stays untouched and only the foreground object changes, often preserving its color palette and orientation while altering just the class-relevant structure.
Trajectories. Figure 2 visualizes the full integration trajectory for five counterfactuals per dataset, with the border color marking the classifier's prediction at each step (red for the source class, green for the target class). In most examples the color flips early, showing that CounterFlow reaches the target class within a small fraction of the path and spends the remaining steps refining the sample within that class rather than driving the decision itself, i.e., most of the trajectory makes the class change plausible rather than induces it. Intermediate frames stay visually close to both endpoints rather than passing through a degraded intermediate state, confirming at a finer granularity that CounterFlow produces minimal, semantically meaningful edits rather than an unconstrained image-to-image mapping. See Figures 4 and 5 in Section A.5 for additional CounterFlow trajectories.
6 Discussion
Existing image counterfactual generation methods often require heavy generative backbones, including diffusion models or multiple class-specific generative networks, making their deployment computationally demanding. CounterFlow demonstrates that Conditional Flow Matching provides a significantly simpler alternative. By learning a single target-conditioned transport field and requiring only one ODE integration at inference, our method achieves competitive or superior counterfactual quality while substantially reducing computational complexity. We believe this constitutes an important step toward making counterfactual explanations practical for interactive decision-support systems, where explanations must be generated quickly and consistently.
Despite these encouraging results, several limitations remain. First, our experiments are restricted to relatively low-resolution image datasets. Evaluating CounterFlow on larger-scale benchmarks such as ImageNet or high-resolution generative datasets would provide further evidence of its scalability. Second, our latent-space pairing strategy currently relies on nearest-neighbor retrieval using a pretrained encoder, which introduces an additional preprocessing step. Finally, while Conditional Flow Matching substantially reduces inference complexity compared to diffusion models, solving an ODE remains more expensive than a single feed-forward network.
7 Conclusion
We presented CounterFlow, a Conditional Flow Matching framework for visual counterfactual explanation generation. Unlike previous approaches relying on GANs or diffusion models, CounterFlow directly learns a target-conditioned transport field between image classes in pixel space. Experiments on MNIST and CIFAR-10 demonstrate that the proposed method achieves state-of-the-art counterfactual validity while remaining competitive in image realism and substantially reducing computational requirements.
Beyond counterfactual explanations, CounterFlow illustrates that target-conditioned flow matching can efficiently learn semantic transformations directly between complex data distributions, without relying on an intermediate noise distribution. Future work will investigate its application to larger-scale datasets and other data transformation tasks, including domain adaptation, semantic image editing, and robust model analysis.
AI use statement
We used generative AI tools (LLM-based coding assistants) to help implement and debug parts of the experimental code, and to polish the phrasing of some sentences in this manuscript. We did not use generative AI tools to generate research ideas, to design the method, or to produce or interpret experimental results. All AI-assisted code and text were reviewed, tested, and validated by the authors, who take full responsibility for the final content of this work, including text, claims, and artifacts produced with the aid of generative AI.
Ethics statement
This work introduces a method for generating visual counterfactual explanations of image classifiers, evaluated on the standard MNIST and CIFAR-10 benchmarks, which do not contain personal or sensitive data. As with other counterfactual-explanation and image-editing methods, the underlying generative technology could in principle be misused to produce misleading edited images of real people; we mitigate this risk by restricting our experiments to non-human-identifying benchmark datasets and by releasing the method as a tool for model interpretability rather than for unconstrained image generation.
Reproducibility statement
We describe the CounterFlow training and inference procedures in full in Section 4, including the pairing algorithm (Algorithm 1) and the training loop (Algorithm 2). All training hyperparameters for both datasets are listed in Table 2 in the appendix. We use only the standard, publicly available MNIST and CIFAR-10 datasets and publicly available pretrained classifiers (Section 5). Our implementation builds on the open-source torchcfm library, and we will release the source code needed to reproduce all experiments upon publication.
References
Michael S. Albergo and Eric Vanden-Eijnden. Building Normalizing Flows with Stochastic Interpolants. In International Conference on Learning Representations, 2023.
André Artelt and Barbara Hammer. On the computation of counterfactual explanations - A survey. arXiv, abs/1911.07749, 2019.
André Artelt and Barbara Hammer. Convex Density Constraints for Computing Plausible Counterfactual Explanations. In International Conference on Artificial Neural Networks, 2020.
Maximilian Augustin, Valentyn Boreiko, Francesco Croce, and Matthias Hein. Diffusion Visual Counterfactual Explanations. In Advances in Neural Information Processing Systems, 2022.
Zhuo Cao, Xuan Zhao, Lena Krieger, Hanno Scharr, and Ira Assent. LeapFactual: Reliable Visual Counterfactual Explanation Using Conditional Flow Matching. In Advances in Neural Information Processing Systems, 2025.
Tian Qi Chen, Yulia Rubanova, Jesse Bettencourt, and David Duvenaud. Neural Ordinary Differential Equations. In Advances in Neural Information Processing Systems, 2018.
Xiaohan Ding, Xiangyu Zhang, Ningning Ma, Jungong Han, Guiguang Ding, and Jian Sun. Repvgg: Making vgg-style convnets great again. In IEEE/CVF Conference on Computer Vision and Pattern Recognition, 2021.
J. R. Dormand and P. J. Prince. A Family of Embedded Runge-Kutta Formulae. Journal of Computational and Applied Mathematics, 1980.
Rudresh Dwivedi, Devam Dave, Het Naik, Smiti Singhal, Rana Omer, Pankesh Patel, Bin Qian, Zhenyu Wen, Tejal Shah, Graham Morgan, and Rajiv Ranjan. Explainable AI (XAI): Core Ideas, Techniques, and Solutions. ACM Computing Surveys, 2023.
Sven Gowal, Sylvestre-Alvise Rebuffi, Olivia Wiles, Florian Stimberg, Dan Andrei Calian, and Timothy A. Mann. Improving Robustness using Generated Data. In Advances in Neural Information Processing Systems, 2021.
Yash Goyal, Ziyan Wu, Jan Ernst, Dhruv Batra, Devi Parikh, and Stefan Lee. Counterfactual Visual Explanations. In International Conference on Machine Learning, 2019.
Changlu Guo, Anders Nymark Christensen, Anders Bjorholm Dahl, and Morten Rieger Hannemose. MaskDiME: Adaptive Masked Diffusion for Precise and Efficient Visual Counterfactual Explanations. arXiv, abs/2602.18792, 2026.
Martin Heusel, Hubert Ramsauer, Thomas Unterthiner, Bernhard Nessler, and Sepp Hochreiter. GANs trained by a two time-scale update rule converge to a local Nash equilibrium. In Advances in Neural Information Processing Systems, 2017.
Jonathan Ho, Tim Salimans, Alexey Gritsenko, William Chan, Mohammad Norouzi, and David J. Fleet. Video diffusion models. In Advances in Neural Information Processing Systems, 2022.
Guillaume Jeanneret, Loïc Simon, and Frédéric Jurie. Adversarial Counterfactual Visual Explanations. In IEEE/CVF Conference on Computer Vision and Pattern Recognition, 2023.
Guillaume Jeanneret, Loïc Simon, and Frédéric Jurie. Diffusion Models for Counterfactual Explanations. Computer Vision and Image Understanding, 2024.
Mark T Keane and Barry Smyth. Good Counterfactuals and Where to Find Them: A Case-Based Technique for Generating Counterfactuals for Explainable AI (XAI). In International Conference on Case-Based Reasoning, 2020.
Saeed Khorram and Li Fuxin. Cycle-Consistent Counterfactuals by Latent Transformations. In IEEE/CVF Conference on Computer Vision and Pattern Recognition, 2022.
Yaron Lipman, Ricky T. Q. Chen, Heli Ben-Hamu, Maximilian Nickel, and Matthew Le. Flow Matching for Generative Modeling. In International Conference on Learning Representations, 2023.
Haohe Liu, Zehua Chen, Yi Yuan, Xinhao Mei, Xubo Liu, Danilo Mandic, Wenwu Wang, and Mark D. Plumbley. AudioLDM: Text-to-Audio Generation with Latent Diffusion Models. In International Conference on Machine Learning, 2023a.
Xingchao Liu, Chengyue Gong, and Qiang Liu. Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow. In International Conference on Learning Representations, 2023b.
Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, and Björn Ommer. High-Resolution Image Synthesis With Latent Diffusion Models. In IEEE/CVF Conference on Computer Vision and Pattern Recognition, 2022.
Alexander Tong, Kilian Fatras, Nikolay Malkin, Guillaume Huguet, Yanlei Zhang, Jarrid Rector-Brooks, Guy Wolf, and Yoshua Bengio. Improving and generalizing flow-based generative models with minibatch optimal transport. Transactions on Machine Learning Research, 2024.
Sandra Wachter, Brent D. Mittelstadt, and Chris Russell. Counterfactual Explanations without Opening the Black Box: Automated Decisions and the GDPR. arXiv, abs/1711.00399, 2017.
Nina Weng, Paraskevas Pegios, Eike Petersen, Aasa Feragen, and Siavash Arjomand Bigdeli. Fast Diffusion-Based Counterfactuals for Shortcut Removal and Generation. In European Conference on Computer Vision, 2024.
A Appendix
A.1 Implementation Details
We provide the full training configuration for both datasets in Table 2 to facilitate reproducibility. Both models are trained with the Adam optimizer and an exponential moving average (EMA) of the weights, using a linear warmup schedule for both the learning rate and the classifier-guidance loss weight .
Table 2: Training hyperparameters for MNIST and CIFAR10.
| Hyperparameter | MNIST | CIFAR10 |
|---|---|---|
| Training steps | 200,000 | 400,000 |
| Warmup steps | 5,000 | 5,000 |
| Minibatch size | 256 | 256 |
| Optimizer | Adam | Adam |
| Learning rate | ||
| EMA decay | 0.9999 | 0.9999 |
| Validation ratio | 0.2 | 0.2 |
| Seed | 1 | 1 |
| 0.1 | 0.1 | |
| warmup steps | 10,000 | 10,000 |
| Noise level | 0.1 | 0.1 |
| 0.05 | 0.05 | |
| Number of residual blocks in UNet | 1 | 2 |
| Conditioning MLP | ✕ | ✓ |
| Image size () | ||
| Number of classes | 10 | 10 |
A.2 Radar plots

(a) MNIST

(b) CIFAR10
C3LT (MNIST) / C3LT (CIFAR10) LeapFactual (MNIST) / FastDiME (CIFAR10) CounterFlow (ours)
Figure 3: Radar comparison of all five metrics from Table 1a, per dataset. Each axis is min-max normalized within its dataset so that the outer edge always corresponds to the best value across methods, regardless of whether the underlying metric is originally better when higher or lower. CounterFlow reaches the outer edge on every axis on CIFAR-10 and is competitive or best on most axes on MNIST, whereas baselines tend to excel on a single axis at the expense of others.
A.3 Ablation studies on CIFAR-10
Tables 3 to 5 isolate the three design choices of CounterFlow on CIFAR-10. Every run follows the configuration of Table 2 and modifies a single factor: models are trained for 400,000 steps and evaluated on the full CIFAR-10 test set with the Euler solver and 40 steps. The rows marked (default) all correspond to the configuration reported in Table 1a. Rows marked † have a conditional validity low enough that their FID scores are computed over a mixture of successful and failed counterfactuals. Since a counterfactual that stays in the source class trivially obtains a low and a high , these values must not be read as a quality signal.
Weight of the classification loss. Table 3 varies the weight of in . The two terms are complementary, and neither is sufficient on its own. Removing the classification term ( ) leaves a purely generative transport that reaches only 68.9% conditional validity: matching the flow between the two class distributions does not guarantee that each individual sample crosses the decision boundary of , and its lower merely reflects that about a third of the samples never leave the source class. Conversely, keeping only the classification term ( , no ) collapses: with nothing anchoring the velocity field to the source–target displacement, the model drifts off the data manifold, as the FID scores above 400 make explicit, and it does not even reach a high validity (48.9%). Between these two extremes, every saturates conditional validity at 100%, so the remaining effect of is a monotonic degradation of both FID scores, from 62.38 to 74.01 on the target and from 118.23 to 121.82 on the source. We therefore use , the smallest value that already saturates validity.
Table 3: Effect of the weight of the classification loss on CIFAR-10.
| Ablated factor | CV↑ | FID | FID |
|---|---|---|---|
| 68.9 | 67.64 | 112.94 | |
| 100.0 | 62.54 | 117.03 | |
| 100.0 | 66.78 | 119.77 | |
| 100.0 | 74.01 | 121.82 | |
| 48.9 | 444.88 | 406.14 |
Conditioning context. Table 4 removes the context from the velocity field, i.e., it trains on the same latent-paired minibatches, but without indicating which transition is being realized. Conditional validity collapses from 100% to 8.6%: deprived of the context, the model can only fit the average displacement over all source–target pairs, which carries no information about the requested transition. The FID scores confirm that the resulting field is close to the identity, since the source FID falls to 83.24, well below the default 118.23, precisely because the generated images barely leave their source. Conditioning on the pair is thus not an implementation detail, but the component that turns a generic flow into a controllable, target-specific transport.
Table 4: Effect of the context conditioning the velocity field on CIFAR-10.
| Ablated factor | CV↑ | FID | FID |
|---|---|---|---|
| (default) | 100.0 | 62.54 | 117.03 |
| No context | 8.6 | 121.72 | 83.24 |
Explained classifier. A counterfactual method should not depend on the specific classifier it explains. Table 5 therefore keeps CounterFlow unchanged and only substitutes , comparing the RepVGG-A2 used throughout the paper with a deliberately mis-specified variant, namely the same network evaluated without its input normalization, which drops its accuracy to 86.3%, and with an adversarially robust PreActResNet-18 (Gowal et al., 2021). The mis-specified classifier is explained as well as the original one: validity stays at 100% and both FID scores remain within two points of the default, indicating that CounterFlow does not require the explained model to be accurate, only that it defines an exploitable decision boundary. The robust classifier behaves differently: validity drops to 83.5%, while FID reaches the lowest value we observe (55.72). This is consistent with what adversarial training is designed to achieve, namely flattening the decision boundary and suppressing the small non-robust directions that a gradient-based guidance term can exploit, so that pushes less strongly and a fraction of the samples never crosses the boundary. The counterfactuals that do cross must therefore carry a genuine, large-scale semantic change, which is what brings them closer to the target distribution; note that the 16.5% of samples that remain in the source class can only inflate FID, so this value is, if anything, pessimistic. Explaining a robust model is thus harder for CounterFlow, but yields more plausible counterfactuals, which is coherent with diffusion-based methods that explicitly require an adversarially robust classifier (Augustin et al., 2022).
Table 5: Effect of the explained classifier on CIFAR-10. Accuracy (Acc.) is the test accuracy in % of the explained classifier itself, not a property of the generated counterfactuals.
| Explained classifier | Acc. | CV↑ | FID | FID |
|---|---|---|---|---|
| RepVGG-A2 (default) | 94.8 | 100.0 | 62.54 | 117.03 |
| RepVGG-A2 w/o input normalization | 86.3 | 100.0 | 64.03 | 115.30 |
| Robust PreActResNet-18 (Gowal et al., 2021) | 87.5 | 83.5 | 55.72 | 119.89 |
A.4 Choice of datasets
We restrict our experiments to MNIST and CIFAR-10, the largest settings in which all compared methods can be run with their official implementations, the same classifier, and the same evaluation protocol. For instance, extending this comparison to ImageNet raises the following issues.
Baselines. C3LT requires a separate model for each pair of classes, i.e., 499,500 models for the 1,000 classes of ImageNet. Hence, its ImageNet experiments are qualitative, restricted to five pairs of classes, and use latent codes sampled from a pretrained GAN rather than real images (Khorram and Fuxin, 2022). LeapFactual relies on a latent space in which inputs can be faithfully encoded, and each of its leaps requires decoding the latent code and querying the classifier; its only large-scale experiment is a binary task on images generated by a pretrained GAN (Cao et al., 2025). Diffusion-based methods do apply to ImageNet, but at a high cost: on CIFAR-10, FastDiME already requires about more FLOPs per counterfactual than CounterFlow (Table 1a), and ACE is evaluated on only three pairs of ImageNet classes (Jeanneret et al., 2023).
Evaluation. Our and are computed against the test images of a single class, whereas ImageNet provides only 50 validation images per class, which makes such estimates unreliable. Moreover, the number of ordered source-target pairs grows from 90 to 999,000. As noted by Jeanneret et al. (2023), counterfactual explanation methods still lack an appropriate testbed on such complex datasets.
CounterFlow. In principle, CounterFlow applies to ImageNet by adapting its U-Net architecture. However, unlike the baselines, which build on generative models pretrained at a considerable computational cost, CounterFlow would have to be trained from scratch in pixel space, which exceeds our computational budget. Moreover, the number of source–target contexts grows quadratically with the number of classes, so that each context would be seen less often during training. We leave this large-scale study to future work.
A.5 Additional Results

Figure 4: Additional CounterFlow trajectories on MNIST, from source to target class. Border color indicates the classifier's prediction along the path: red for the source class, green for the target class, and orange for any other class.
horse → airplane
airplane → ship
dog → deer
automobile → bird
cat → dog
truck → automobile
bird → horse
airplane → cat
frog → dog
horse → airplane
truck → ship
airplane → horse
Figure 5: Additional CounterFlow trajectories on CIFAR10, from source to target class. Border color indicates the classifier's prediction along the path: red for the source class, green for the target class, and orange for any other class.