This post studies a generative model that works very differently from the flow matching models of the previous posts. Marginal Flows were introduced by Negri et al. in Marginal Flow: a flexible and efficient framework for density estimation. The method is simple enough to implement in an afternoon. Here it is tested on the same toy problems as before (two moons and MNIST in a VAE latent space) and compared with flow matching. All credit for the method goes to the authors. Any error in this post comes from the implementation or the reading of the paper.

The short version: a marginal flow is a mixture of Gaussians whose centers are produced by a small network from random noise. This allows one-pass sampling and a cheap likelihood, both of which flow matching lacks. The price is training time and, on the MNIST latents, sample quality, where flow matching performs better even though the marginal flow models have fewer parameters. On clearly separated modes, however, the marginal flow captures the target better (section 5).

The code is in the flow-matching repository: simple_mf_2d.ipynb, mnist/mnist_marginal_flow.ipynb, and a script (baseline_fm_vs_mf.py) that produces the flow matching baseline numbers below. All timings come from a single run on a laptop CPU.


1. What Is a Marginal Flow?

Flow matching learns a velocity field and integrates it to get samples. A marginal flow skips all of that. It models the density as an average over the parameters $w$ of a simple distribution $q(x \mid w)$:

\[q(x) = \int q(x \mid w)\, q(w)\, dw = \mathbb{E}_{w \sim q(w)}\big[q(x \mid w)\big].\]

We never write down $q(w)$. We only sample from it, by pushing noise $z \sim p_\text{base}$ through a network, $w = f_\theta(z)$. Replacing the expectation with $N_c$ samples gives the model

\[q_\theta(x) = \frac{1}{N_c} \sum_{i=1}^{N_c} q\big(x \mid f_\theta(z_i)\big), \qquad z_i \sim p_\text{base}.\]

The choice here is the one the paper uses in most of its experiments, a Gaussian with learnable diagonal variance, $q(x \mid w) = \mathcal{N}(x \mid w, \text{diag}(\sigma^2))$. So $f_\theta(z)$ is the mean of a Gaussian, and the whole model is a mixture of Gaussians whose means are random draws from a learned distribution. The $z_i$ are drawn again every time the model is evaluated, which is what separates this from a plain Gaussian mixture with $N_c$ fixed components: here the capacity doesn’t depend on $N_c$.

That is the entire model. For the 2D case it fits in a few lines:

class MarginalFlow(nn.Module):
    def __init__(self, base_dim=1, output_dim=2, hidden_dim=4):
        super().__init__()
        self.log_var = nn.Parameter(torch.zeros(output_dim))
        self.fc = nn.Sequential(
            nn.Linear(base_dim, hidden_dim), nn.ReLU(),
            nn.Linear(hidden_dim, output_dim),
        )

    def sample_weights(self, n):
        return self.fc(torch.randn(n, self.base_dim))

    def sample(self, n):
        w = self.sample_weights(n)
        return w + torch.randn_like(w) * self.log_var.exp().sqrt()

Sampling is one network call plus Gaussian noise.

Evaluating the likelihood means drawing $N_c$ values of $w$, computing the Gaussian density of $x$ under each, and averaging with a logsumexp:

def evaluate(self, x, n_samples):
    w = self.sample_weights(n_samples)
    log_probs = -0.5 * (((x.unsqueeze(1) - w.unsqueeze(0)) ** 2) / var).sum(-1) - ...
    return torch.logsumexp(log_probs, dim=1) - math.log(n_samples)

Training is maximum likelihood. The loss is the paper’s Eq. 6, $-\frac{1}{N}\sum_j \log \frac{1}{N_c}\sum_i q(x_j \mid w_i)$, with no interpolants, no time variable and no regression targets.


2. How It Differs From Flow Matching

  Flow matching Marginal flow
Network output A velocity $v_\theta(x_t, t)$ Mixture centers $f_\theta(z)$
Training objective MSE regression onto $x_1 - x_0$ Negative log-likelihood (Monte Carlo)
Sampling Integrate an ODE, many network calls One network call plus Gaussian noise
Likelihood Integrate the ODE and the divergence Average Gaussian densities
Time variable Yes No
Noise dimension Same as the data Can be lower

Some of these deserve a comment.

Simulation-free in both directions. Flow matching is simulation-free because training never integrates the ODE, but sampling still does. A marginal flow needs no integration at all. The cost appears elsewhere: every training step evaluates $N_c$ components per data point.

The noise can have fewer dimensions than the data. In flow matching the flow maps $\mathbb{R}^d$ to $\mathbb{R}^d$, so the noise has the data dimension. In a marginal flow, $z$ can live in $\mathbb{R}^m$ with $m < d$, and the model is concentrated around an $m$-dimensional manifold. For two moons a one-dimensional $z$ suits a curve in the plane. For MNIST a two-dimensional $z$ generates 16-dimensional latents, which can be visualized directly (section 4).

The likelihood is a random variable. Because the components are redrawn each time, $\log q_\theta(x)$ is a Monte Carlo estimate, and the log of an average is biased low for finite $N_c$. The authors discuss this in their reply to reviewers on OpenReview: the log-likelihood loss is biased because of the nonlinearity of the log, and they quantify how the bias scales with $N_c$. They also point out two ways to read the word “exact”: $q_\theta(x)$ is an unbiased estimator of the true marginal, and for a fixed set of components the mixture density is evaluated exactly. Under the second reading, a deterministic evaluation can be obtained by fixing the seed. The bias is visible in the experiments below: the same trained two-moons model has a test NLL of 1.55 when evaluated with $N_c = 100$ and 1.51 with $N_c = 1000$ (lower is better).


3. Two Moons

The unconditional model learns the moons from a 1D $z$. For the conditional one, a learned class embedding is added to a 2D $z$. The samples for each class are shown next to the data:

Conditional marginal flow on two moons

Both moons are reproduced with the right shape and noise level, including the overlap region, using a network with a single hidden layer.

To compare against flow matching, both models are trained on the same data. The flow matching model is an MLP with two hidden layers and samples with 20 midpoint steps (the solver from part 1).

Data, flow matching and marginal flow samples on two moons

The samples are visually similar. The quantitative comparison (5000 training iterations, batch size 256, 2000 test points) is:

  Flow matching Marginal flow
Parameters 4546 260
Training time 5 s 47 s
Test NLL 1.50 1.51 ($N_c = 1000$ at evaluation), 1.55 ($N_c = 100$)
Time to sample 10,000 points 71 ms (20 midpoint steps) 2 ms
Time to evaluate the log-density of 2000 points 122 ms (50 midpoint steps, exact divergence) 21 ms ($N_c = 100$)

The likelihoods are similar, and the marginal flow has 17 times fewer parameters and samples much faster. However, training is about nine times slower for the same number of iterations. A comparison at a fixed number of iterations may be unfair if one model requires many more of them, so the test NLL was tracked during training:

Iterations 200 500 1000 2000 5000 10,000
Flow matching 1.66 1.60 1.55 1.53 1.47 1.43
Marginal flow 2.26 2.17 2.01 1.85 1.52 1.47

Flow matching reaches an NLL of 1.55 after about 1000 iterations, while the marginal flow requires about 5000. Hence the marginal flow needs more iterations, and each of them is more expensive.


4. MNIST in a VAE Latent Space

The MNIST experiments reuse the setup from part 2: a convolutional VAE with a 16-dimensional latent space, trained with a classification head so the latents are class-aware. Both models train on the latent means from the same VAE, and the decoder turns their samples back into images.

The conditional marginal flow draws a 2D $z \sim \mathcal{N}(0, I)$, concatenates a learned 2D class embedding, and feeds the result to an MLP with two hidden layers of 128 units that outputs the 16D mean of a Gaussian (19,252 parameters). Like the flow matching model, it is trained for 60 epochs, with $N_c = 100$.

Side by side

Each row is one digit. Both models were trained for 60 epochs. Flow matching (left) samples with 20 midpoint steps and the marginal flow (right) in one pass.

Flow matching vs marginal flow samples per class

Flow matching generates cleaner digits that more reliably belong to the requested class, while the marginal flow produces some ambiguous ones, e.g., a 2 that resembles an 8 or a 7 that resembles a 9. To quantify this, a small CNN is trained on real MNIST images, 5000 generated latents are decoded, and the fraction of samples for which the CNN agrees with the requested class (class fidelity) is computed:

  Flow matching Marginal flow
Parameters 77,172 19,252
Training time, 60 epochs 17 s 119 s
Class fidelity of samples 96.1% (20 epochs), 97.0% (60 epochs) 92.3% (20 epochs), 93.8% (60 epochs)
Time to sample 10,000 latents 114 ms (20 midpoint steps), 554 ms (100 steps) 2.0 ms
Test NLL in latent space (nats) 6.1 7.8
Classification accuracy with Bayes’ rule 98.1% 97.0%
Time to classify 1000 latents 2.1 s 0.18 s

The likelihood and classification rows use 1000 random test latents. On the full test set the marginal flow gets 96.8%. The marginal flow still has about four times fewer parameters than flow matching.

In this setting flow matching obtains better samples and likelihoods, and it also trains faster. The advantage of the marginal flow is in inference. Sampling takes a single forward pass, which is about 55 times faster than a 20-step midpoint solver (270 times faster than with 100 steps). Classification requires ten class-conditional likelihoods per image, and it is about 11 times faster. Note that for flow matching the divergence is computed exactly, with one backward pass per latent dimension (16). A Hutchinson estimator would reduce this cost, but the ODE still has to be integrated.

How fast does each one converge?

Both models are trained for the same 60 epochs but do not improve at the same rate, so they were evaluated at several points during training:

Epoch 1 3 5 10 20 40 60
Flow matching, class fidelity 93.2% 94.2% 95.7% 95.7% 96.7% 97.3% 96.5%
Marginal flow, class fidelity 71.9% 87.3% 90.7% 91.6% 93.1% 92.8% 92.7%
Flow matching, test NLL 12.7 10.3 9.7 8.6 7.6 6.3 5.8
Marginal flow, test NLL 17.4 15.6 14.4 12.0 8.3 7.8 7.8

Class fidelity only measures whether the digit is recognizable. As a complementary metric, the Fréchet distance between generated and real latents is computed per class and averaged.

Note: Fréchet distance. It fits a Gaussian to each set of latents and compares their means and covariances (the same idea as FID, but on the VAE latents). Lower is better, and zero means the two Gaussians coincide. With finite samples it never gets there: real test latents compared with real train latents give 0.33, so values around or below that mean the generated latents are as close to the training data as held-out real ones.

Epoch 1 3 5 10 20 40 60
Flow matching 0.51 0.36 0.26 0.26 0.22 0.20 0.18
Marginal flow 2.70 1.27 0.78 0.56 0.49 0.48 0.48

Flow matching reaches the floor by epoch 5, while the marginal flow levels off at about 1.5 times that distance after 20 epochs, and its class fidelity stops improving around the same point. Flow matching reaches in 20 epochs (6 seconds) the NLL of 7.8 that the marginal flow attains after 40 epochs (79 seconds). The authors report large speedups over competing models in training and inference. In this setup the inference speedup is reproduced but the training one is not. Note that this comparison is much smaller than theirs, so the paper should be consulted for their setting before extrapolating from these numbers.

Note that the flow matching training loss is almost flat from the first epoch (between 15 and 18) while the test NLL keeps decreasing from 12.7 to 5.8. The regression target is noisy, so most of the loss is irreducible and a flat curve can hide real progress. The marginal flow loss, on the other hand, decreases steadily from 17.5 to 7.3.

The cost of the marginal flow depends on $N_c$. With 50 components instead of 100, training is roughly twice as fast per epoch, but the moons NLL after 5000 iterations is worse (1.59 instead of 1.52).

Using the likelihood

Since the marginal flow provides a cheap density, tasks that are expensive with flow matching become practical. The figure shows the test sixes with the highest and lowest likelihood under the model, with the posterior $P(6 \mid z)$ from Bayes’ rule (uniform prior over the ten class-conditional models) in the titles:

Most and least likely sixes

The top row contains clean, canonical sixes. The bottom row contains atypical ones: sixes that resemble an S, a G or a U with a loop, and one with a stray vertical stroke. Hence ranking a dataset by likelihood is a direct way to find outliers. The classifier in the table above relies on the same principle, i.e., evaluating the likelihood under each class and taking the argmax.

Looking at the noise

Since $z$ is only two-dimensional, the whole generative map can be plotted. This is the decoded output of the network over a regular grid of $z \in [-1.5, 1.5]^2$ for class 0:

Grid over the 2D latent space for class 0

The width, slant and thickness of the zero change smoothly across the grid, with some artifacts in the less populated corners. The model thus learns a 2D map of zeros without supervision, something flow matching does not provide directly since its noise has the dimension of the data.

A further degree of control is available at sampling time. A sample is $x = w + \sigma \odot \epsilon$, so the Gaussian noise can be scaled down after training (noise_scale) while keeping the mixture centers. The figure shows samples with the noise halved:

Samples with reduced noise

The generated latents also preserve the class structure of the real ones (t-SNE of generated latents on the left, the VAE’s own latents on the right):

t-SNE of generated and real latents


5. Multimodality

One more question is whether the mixture structure helps with multimodal targets. Flow matching has to turn a unimodal Gaussian into the data, so some probability mass has to be carried across the gaps between the modes. A marginal flow is a mixture, so it can put components on each mode directly.

To test this, the unconditioned version of both models is used, so that they have to find the modes by themselves. The marginal flows are sized to have about as many parameters as flow matching (two hidden layers in both), so the comparison is not about capacity.

Two moons

The noise is lowered to 0.05 so that the two moons are clearly separated, and the marginal flow is trained with a base dimension of 1 and of 2 (10,000 iterations, batch size 256, about 4.5k parameters for all three models):

Data, flow matching and marginal flows on two clearly separated moons

Flow matching leaves a cloud of samples in the gap between the moons, while both marginal flows keep the two moons clean. The numbers:

  Flow matching Marginal flow (base dim 1) Marginal flow (base dim 2)
Test NLL 0.53 0.36 0.38
Wasserstein-2 distance to data 0.091 0.054 0.084
Samples in moon 1 (data: 50%) 52.0% 50.2% 52.2%
Ambiguous samples (kNN max probability below 0.9) 1.1% 0.0% 0.2%

The marginal flow with a one-dimensional $z$ performs best, which is consistent with a model whose output is a curve plus noise. Therefore, on a target with well separated modes, the marginal flow captures the multimodality better, even with a lower-dimensional base. The Wasserstein-2 differences are small and should not be over-interpreted, but the likelihood and the absence of samples between the moons point in the same direction.

Digits 4 and 6

The moons are an ideal case, since the modes are far apart and live in two dimensions. To study a higher dimensional space where the modes overlap more, the 16-dimensional MNIST latents of just two digits (4 and 6) are used to train unconditioned models, with base dimensions of 2, 5 and 16 for the marginal flow (100 epochs; flow matching has 74.5k parameters and the marginal flows between 70.7k and 74.3k). The VAE’s classification head tells which digit a latent looks like, and a sample is counted as ambiguous if the largest class probability is below 0.9.

PCA of real and generated latents of digits 4 and 6

  Data Flow matching MF (base dim 2) MF (base dim 5) MF (base dim 16)
Test NLL   8.25 9.04 8.90 8.87
Wasserstein-2 distance to data 1.95 2.03 2.13 2.14 2.14
Samples classified as 4 49.2% 46.0% 49.6% 47.2% 49.7%
Samples classified as 6 48.2% 51.1% 45.9% 47.3% 45.1%
Samples of another digit 2.5% 2.9% 4.5% 5.5% 5.2%
Ambiguous samples 6.0% 7.4% 11.9% 13.6% 12.4%

(The Wasserstein-2 value in the data column is between two different sets of real latents, so it is the floor.)

In this case the results are reversed. Flow matching obtains the best likelihood, the smallest distance to the data and the fewest samples outside the two digits or between them, and it is close to the data in all of these metrics. All three marginal flows split the mass between 4 and 6 about right but produce more ambiguous samples than the data, and the base dimension has little effect. The advantage observed on the moons therefore does not carry over: the two digit clusters overlap substantially in the latent space, so there is no clean gap for a mixture to exploit.

This toy experiment suggests that the advantage of the marginal flow on the moons might not translate to higher dimensional spaces, where the modes are usually not so clearly separated. However, it covers a single 16-dimensional latent space with two overlapping classes, so further experiments are required to validate this observation.


Takeaways

  • A marginal flow is a mixture of Gaussians with network-generated centers. Sampling is a single forward pass and the likelihood is an average of Gaussian densities, with no ODE in either.
  • In these experiments flow matching trained faster and gave better samples. The marginal flow needed more iterations to converge, each one costing more because of the $N_c$ components. The marginal flow models had fewer parameters (17 times fewer on two moons, 4 times fewer on the MNIST latents), so these are not matched comparisons.
  • The marginal flow is more efficient at inference. Sampling and likelihood evaluation were cheaper by a factor of 6 to 40 on two moons and 11 to 55 on the MNIST latents, which makes things like likelihood-based classification and outlier ranking practical.
  • Multimodality favors the marginal flow only when the modes are clearly separated. On two well separated moons it beat flow matching even with a one-dimensional base, but on the latents of two overlapping digits flow matching was better.
  • $N_c$ is a trade-off. More components give a less biased likelihood and a better fit, at a higher cost per step.
  • A low-dimensional noise space can be inspected directly. It can be plotted, and the noise can be scaled down at sampling time.

These experiments are limited to toy problems. The paper also covers simulation-based inference, positive definite matrices and manifold learning on image latents, so it should be consulted for results on harder problems. Since the whole model is only a few dozen lines, it is easy to try on other data.