Skip to content

expansion

expansion

Generable-set expansion, growing what a flow model can reach.

Distribution matching teaches a flow to reproduce its training density. Set expansion asks a different question, which valid designs can the model generate at all? This package implements Active Flow Expansion (ActFlow, De Santi et al., 2026, arXiv:2606.08802), which fine-tunes a pre-trained flow on self-generated, verifier-labelled samples chosen by active exploration in the flow's own noised representation.

Modules:

  • representation, the feature map phi_s (hidden activations of the velocity field at noise level s).
  • uncertainty, verifier-uncertainty estimators over phi_s, including the closed-form kernel posterior standard deviation (Eq. 10).
  • guidance, the uncertainty tilt p_theta * exp(sigma / beta) (Eq. 9) exposed as a Likelihood so PosteriorSolver can sample it.
  • actflow, the round loop of Algorithm 1.
  • metrics, histogram generable-set coverage for 2D problems.

The signed replay objective lives with the other losses as deltaflow.losses.SignedReplayFlowMatchingLoss.

ActFlow

ActFlow(model, verifier, optimizer, sample_shape, representation=None, uncertainty=None, loss=None, base_solver=None, tweedie=None, beta=0.1, guidance_scale=1.0, grad_normalize=False, n_steps=50, finetune_steps=100, batch_size=64, min_accepted=0, feature_batch_size=1024, cond=None)

Active Flow Expansion, verifier-guided growth of a flow's generable set.

Runs Algorithm 1 of De Santi et al. (2026). At round \(t\),

\[ \begin{aligned} &\sigma_t \leftarrow \textsc{Fit}\bigl(\{\phi^{\theta_t}_s(x_i)\}_{i \le t}\bigr), \\ &x_{t+1} \sim \tilde{p}_t \propto p_1^{\theta_t}\, \exp\!\bigl(\sigma_t(\phi^{\theta_t}_s(x)) / \beta\bigr), \\ &y_{t+1} \leftarrow \tilde{v}(x_{t+1}), \qquad \mathcal{D}_{t+1} \leftarrow \mathcal{D}_t \cup \{(x_{t+1}, y_{t+1})\}, \\ &\theta_{t+1} \leftarrow \theta_t - \eta\,\bigl(\nabla \hat{\mathcal{L}}^{+}_t - \alpha_t \nabla \hat{\mathcal{L}}^{-}_t\bigr) \quad (\text{repeated } \texttt{finetune\_steps} \text{ times}). \end{aligned} \]

The representation \(\phi^{\theta_t}_s\) is re-read from the current model every round, so the uncertainty refit uses the model's evolving features, as in the paper. beta=math.inf turns off the tilt and gives the self-training baseline (REC-F in the paper when alpha=0).

References

De Santi et al., "Active Flow Expansion for Out-of-Distribution Discovery: from Theory to Molecules" (2026), https://arxiv.org/abs/2606.08802.

Parameters:

Name Type Description Default
model Module

pre-trained velocity field (an nn.Module), fine-tuned in place.

required
verifier Callable[[Tensor], Any]

black-box validity oracle verifier(x) -> [B] returning bools or {0, 1} (values above 0.5 count as accepted). It is called without gradients and may be non-differentiable.

required
optimizer Optimizer

optimizer over model's parameters.

required
sample_shape Sequence[int]

shape of one design without the batch axis, e.g. (2,) or (1, 32, 32). The noise prior is \(\mathcal{N}(0, I)\) of this shape.

required
representation Optional[FlowRepresentation]

feature map \(\phi_s\). Defaults to FlowRepresentation(model, s=0.9) on the model output. Pass a layer to read hidden features.

None
uncertainty Optional[BaseUncertainty]

verifier-uncertainty estimator. Defaults to the paper's linear-kernel KernelUncertainty.

None
loss Optional[SignedReplayFlowMatchingLoss]

continued pre-training objective. Defaults to SignedReplayFlowMatchingLoss(alpha=0.0), i.e. flow matching on accepted samples.

None
base_solver Optional[BaseSolver]

integrator wrapped by PosteriorSolver. Defaults to EulerSolver.

None
tweedie Optional[BaseTweedie]

Tweedie decomposition matching the training path. Defaults to LinearTweedie (inside PosteriorSolver).

None
beta float

KL weight \(\beta\). Smaller explores harder.

0.1
guidance_scale float

step size on the tilt gradient (PosteriorSolver's guidance_scale).

1.0
grad_normalize bool

forwarded to PosteriorSolver.

False
n_steps int

ODE steps per self-generated batch.

50
finetune_steps int

gradient steps of the flow update per round.

100
batch_size int

minibatch size drawn from each replay buffer.

64
min_accepted int

warm-up, the flow is not updated until the accepted buffer holds at least this many samples.

0
feature_batch_size int

chunk size for reading features of the history.

1024
cond Optional[Dict[str, Any]]

conditioning forwarded unchanged to the model in sampling, features, and the loss. It must not depend on the batch size.

None
Source code in deltaflow/expansion/actflow.py
def __init__(
    self,
    model: nn.Module,
    verifier: Callable[[torch.Tensor], Any],
    optimizer: torch.optim.Optimizer,
    sample_shape: Sequence[int],
    representation: Optional[FlowRepresentation] = None,
    uncertainty: Optional[BaseUncertainty] = None,
    loss: Optional[SignedReplayFlowMatchingLoss] = None,
    base_solver: Optional[BaseSolver] = None,
    tweedie: Optional[BaseTweedie] = None,
    beta: float = 0.1,
    guidance_scale: float = 1.0,
    grad_normalize: bool = False,
    n_steps: int = 50,
    finetune_steps: int = 100,
    batch_size: int = 64,
    min_accepted: int = 0,
    feature_batch_size: int = 1024,
    cond: Optional[Dict[str, Any]] = None,
):
    if beta <= 0:
        raise ValueError(f"beta must be positive, got {beta}")
    self.model = model
    self.verifier = verifier
    self.optimizer = optimizer
    self.sample_shape = tuple(sample_shape)
    self.representation = representation or FlowRepresentation(model)
    self.uncertainty = uncertainty or KernelUncertainty()
    self.loss = loss or SignedReplayFlowMatchingLoss()
    self.base_solver = base_solver or EulerSolver(model)
    self.tweedie = tweedie
    self.beta = float(beta)
    self.guidance_scale = guidance_scale
    self.grad_normalize = grad_normalize
    self.n_steps = n_steps
    self.finetune_steps = finetune_steps
    self.batch_size = batch_size
    self.min_accepted = min_accepted
    self.feature_batch_size = feature_batch_size
    self.cond = dict(cond or {})

    ref = next(model.parameters(), None)
    self.device = ref.device if ref is not None else torch.device("cpu")
    self.dtype = ref.dtype if ref is not None else torch.get_default_dtype()

    empty = torch.empty(0, *self.sample_shape, device=self.device, dtype=self.dtype)
    self.queries = empty
    self.labels = torch.empty(0, dtype=torch.bool, device=self.device)
    self.history: List[ActFlowRound] = []

accepted property

accepted

Accepted replay buffer \(\mathcal{D}^{+}_t\).

rejected property

rejected

Rejected replay buffer \(\mathcal{D}^{-}_t\).

features

features(x)

Read \(\phi_s(x)\) from the current model in chunks.

Source code in deltaflow/expansion/actflow.py
@torch.no_grad()
def features(self, x: torch.Tensor) -> torch.Tensor:
    """Read \\(\\phi_s(x)\\) from the current model in chunks."""
    chunks = [
        self.representation(x[i : i + self.feature_batch_size], **self.cond)
        for i in range(0, x.shape[0], self.feature_batch_size)
    ]
    return torch.cat(chunks) if chunks else x.new_empty(0, 0)

fit_uncertainty

fit_uncertainty()

Refit \(\sigma_t\) on the full history with the current features.

Source code in deltaflow/expansion/actflow.py
def fit_uncertainty(self) -> None:
    """Refit \\(\\sigma_t\\) on the full history with the current features."""
    with _model_mode(self.model, training=False):
        feats = self.features(self.queries)
    self.uncertainty.fit(feats, self.labels.to(feats.dtype))

guidance

guidance()

The uncertainty tilt for the current \(\sigma_t\).

Source code in deltaflow/expansion/actflow.py
def guidance(self) -> UncertaintyGuidance:
    """The uncertainty tilt for the current \\(\\sigma_t\\)."""
    return UncertaintyGuidance(self.representation, self.uncertainty, self.beta, self.cond)

self_generate

self_generate(n)

Draw n designs from the uncertainty-tilted model (Eq. 9).

Source code in deltaflow/expansion/actflow.py
def self_generate(self, n: int) -> torch.Tensor:
    """Draw ``n`` designs from the uncertainty-tilted model (Eq. 9)."""
    x0 = torch.randn(n, *self.sample_shape, device=self.device, dtype=self.dtype)
    if math.isinf(self.beta):
        solver = self.base_solver  # no tilt: plain self-training baseline
    else:
        solver = PosteriorSolver(
            base_solver=self.base_solver,
            likelihood=self.guidance(),
            tweedie=self.tweedie,
            guidance_scale=self.guidance_scale,
            grad_normalize=self.grad_normalize,
        )
    with _model_mode(self.model, training=False):
        x = solver.sample(x0, n_steps=self.n_steps, show_progress=False, **self.cond)
    return x.detach()

query

query(x)

Label x with the verifier and return a bool tensor [B].

Source code in deltaflow/expansion/actflow.py
@torch.no_grad()
def query(self, x: torch.Tensor) -> torch.Tensor:
    """Label ``x`` with the verifier and return a bool tensor ``[B]``."""
    y = torch.as_tensor(self.verifier(x), device=self.device).flatten()
    if y.dtype != torch.bool:
        y = y.float() > 0.5
    if y.shape[0] != x.shape[0]:
        raise ValueError(f"verifier returned {y.shape[0]} labels for {x.shape[0]} samples")
    return y

update_flow

update_flow()

Signed replay continued pre-training. Returns the last loss or None.

Source code in deltaflow/expansion/actflow.py
def update_flow(self) -> Optional[float]:
    """Signed replay continued pre-training. Returns the last loss or ``None``."""
    pos, neg = self.accepted, self.rejected
    if pos.shape[0] == 0 or pos.shape[0] < self.min_accepted or self.finetune_steps <= 0:
        return None
    last = None
    with _model_mode(self.model, training=True):
        for _ in range(self.finetune_steps):
            x_pos = pos[torch.randint(pos.shape[0], (self.batch_size,), device=pos.device)]
            x_neg = None
            if neg.shape[0] > 0 and self.loss.alpha > 0:
                x_neg = neg[torch.randint(neg.shape[0], (self.batch_size,), device=neg.device)]
            loss = self.loss(self.model, x_pos, x_neg, **self.cond)
            self.optimizer.zero_grad(set_to_none=True)
            loss.backward()
            self.optimizer.step()
            last = float(loss.detach())
    return last

step

step(n_samples)

Run one round of Algorithm 1 with a batch of n_samples queries.

Source code in deltaflow/expansion/actflow.py
def step(self, n_samples: int) -> ActFlowRound:
    """Run one round of Algorithm 1 with a batch of ``n_samples`` queries."""
    self.fit_uncertainty()
    x = self.self_generate(n_samples)

    with _model_mode(self.model, training=False), torch.no_grad():
        sigma = self.uncertainty(self.representation(x, **self.cond))

    y = self.query(x)
    self.queries = torch.cat([self.queries, x])
    self.labels = torch.cat([self.labels, y])

    loss = self.update_flow()
    result = ActFlowRound(
        round=len(self.history),
        samples=x,
        labels=y,
        acceptance_rate=float(y.float().mean()),
        mean_uncertainty=float(sigma.mean()),
        n_accepted=int(self.labels.sum()),
        n_rejected=int((~self.labels).sum()),
        finetuned=loss is not None,
        loss=loss,
        alpha=self.loss.last_alpha if loss is not None else 0.0,
    )
    self.history.append(result)
    return result

run

run(n_rounds, n_samples, callback=None)

Run n_rounds rounds, calling callback(round) after each.

Source code in deltaflow/expansion/actflow.py
def run(
    self,
    n_rounds: int,
    n_samples: int,
    callback: Optional[Callable[[ActFlowRound], None]] = None,
) -> List[ActFlowRound]:
    """Run ``n_rounds`` rounds, calling ``callback(round)`` after each."""
    rounds = []
    for _ in range(n_rounds):
        r = self.step(n_samples)
        rounds.append(r)
        if callback is not None:
            callback(r)
    return rounds

ActFlowRound dataclass

ActFlowRound(round, samples, labels, acceptance_rate, mean_uncertainty, n_accepted, n_rejected, finetuned, loss, alpha)

Summary of one ActFlow round.

Attributes:

Name Type Description
round int

zero-based round index.

samples Tensor

the self-generated queries of this round.

labels Tensor

their verifier labels (bool, True means accepted).

acceptance_rate float

fraction of this round's queries accepted.

mean_uncertainty float

mean \(\sigma_t(\phi_s(x))\) of the queries under the uncertainty fitted at the start of the round.

n_accepted int

size of the accepted buffer after the round.

n_rejected int

size of the rejected buffer after the round.

finetuned bool

whether the flow was updated (False during warm-up).

loss Optional[float]

last signed-replay loss of the update, if any.

alpha float

last calibrated repulsion weight \(\alpha_t\).

UncertaintyGuidance

UncertaintyGuidance(representation, uncertainty, beta=0.1, cond=None)

Likelihood adapter for the uncertainty tilt \(p_\theta \exp(\sigma_t / \beta)\).

Implements ActFlow's active-exploration objective

\[ \tilde{p}_t \in \arg\max_q\; \mathbb{E}_{x \sim q}\bigl[\sigma_t(\phi_s(x))\bigr] - \beta\, \mathrm{KL}\bigl(q \,\Vert\, p_1^{\theta_t}\bigr), \qquad \tilde{p}_t(x) \propto p_1^{\theta_t}(x)\, \exp\!\bigl(\sigma_t(\phi_s(x)) / \beta\bigr), \]

by returning \(-\sigma_t(\phi_s(\hat{x}_1)) / \beta\) as a negative log-likelihood. Pass it to PosteriorSolver as likelihood. The solver differentiates it through FlowRepresentation and the Tweedie estimate \(\hat{x}_1\) back to the current state \(x_t\).

References

De Santi et al., "Active Flow Expansion for Out-of-Distribution Discovery: from Theory to Molecules" (2026), https://arxiv.org/abs/2606.08802.

Parameters:

Name Type Description Default
representation FlowRepresentation

the feature map \(\phi_s\).

required
uncertainty BaseUncertainty

a fitted BaseUncertainty giving \(\sigma_t\).

required
beta float

KL weight \(\beta > 0\). math.inf disables the tilt.

0.1
cond Optional[Dict[str, Any]]

conditioning forwarded unchanged to the velocity field inside \(\phi_s\) (the Likelihood protocol carries no **cond).

None
Source code in deltaflow/expansion/guidance.py
def __init__(
    self,
    representation: FlowRepresentation,
    uncertainty: BaseUncertainty,
    beta: float = 0.1,
    cond: Optional[Dict[str, Any]] = None,
):
    if beta <= 0:
        raise ValueError(f"beta must be positive, got {beta}")
    self.representation = representation
    self.uncertainty = uncertainty
    self.beta = float(beta)
    self.cond = dict(cond or {})

score

score(x)

Per-sample uncertainty \(\sigma_t(\phi_s(x))\), shape [B].

Source code in deltaflow/expansion/guidance.py
def score(self, x: torch.Tensor) -> torch.Tensor:
    """Per-sample uncertainty \\(\\sigma_t(\\phi_s(x))\\), shape ``[B]``."""
    return self.uncertainty(self.representation(x, **self.cond))

FlowRepresentation

FlowRepresentation(model, s=0.9, layer=None, interpolant=None, pool='mean', normalize=True, time_scale=1.0)

Feature map \(\phi_s : \mathcal{X} \to \mathcal{Z}_s\) read from a velocity field.

A design \(x\) is first noised to level \(s\) on the training path,

\[ x_s = (1 - s)\,x_0 + s\,x, \qquad x_0 \sim \mathcal{N}(0, I) \]

(for the default linear path), then passed through the velocity field \(v_\theta(x_s, s)\). The activation of layer is captured by a temporary forward hook and pooled to one vector per sample. With layer=None the velocity output itself is used as the representation.

Pooling rule for the captured activation \(h\), shaped [B, ...].

  • [B, D] is returned unchanged.
  • [B, N, D] (token sequences, e.g. a DiT block) is averaged over the N tokens.
  • [B, C, *spatial] (feature maps) is averaged over the spatial axes.

Use pool="flatten" to keep every coordinate instead.

Because \(x_0\) is random, \(\phi_s\) is stochastic for \(s < 1\). Pass noise explicitly for a deterministic evaluation.

References

De Santi et al., "Active Flow Expansion for Out-of-Distribution Discovery: from Theory to Molecules" (2026), https://arxiv.org/abs/2606.08802.

Parameters:

Name Type Description Default
model Callable

velocity field model(x, t, **cond).

required
s float

noise level \(s \in (0, 1]\) at which features are read.

0.9
layer Optional[Union[str, Module]]

sub-module (or its dotted name, resolved with model.get_submodule) whose output is the representation. None uses the model output.

None
interpolant Optional[BaseInterpolant]

path used to noise \(x\) to level \(s\). Defaults to LinearInterpolant, matching the usual training path.

None
pool str

"mean" (default) or "flatten".

'mean'
normalize bool

L2-normalise each feature vector. This keeps the linear kernel bounded, \(k(x, x) \le 1\), as the confidence-sequence theory assumes.

True
time_scale float

multiplies \(s\) before it reaches the model, matching BaseSolver.time_scale.

1.0
Source code in deltaflow/expansion/representation.py
def __init__(
    self,
    model: Callable,
    s: float = 0.9,
    layer: Optional[Union[str, nn.Module]] = None,
    interpolant: Optional[BaseInterpolant] = None,
    pool: str = "mean",
    normalize: bool = True,
    time_scale: float = 1.0,
):
    if not 0.0 < s <= 1.0:
        raise ValueError(f"s must lie in (0, 1], got {s}")
    if pool not in ("mean", "flatten"):
        raise ValueError(f"pool must be 'mean' or 'flatten', got {pool!r}")
    self.model = model
    self.s = float(s)
    self.layer = layer
    self.interpolant = interpolant or LinearInterpolant()
    self.pool = pool
    self.normalize = normalize
    self.time_scale = time_scale

BaseUncertainty

Bases: ABC

Base class for an uncertainty score sigma(z) over features z.

Subclasses implement fit (refit from the full query history) and __call__ (a per-sample score, differentiable in z so it can drive sampling-time guidance).

fit abstractmethod

fit(features, labels=None)

Refit on queried features [t, D] and their verifier labels [t].

Source code in deltaflow/expansion/uncertainty.py
@abstractmethod
def fit(self, features: torch.Tensor, labels: Optional[torch.Tensor] = None) -> None:
    """Refit on queried features ``[t, D]`` and their verifier labels ``[t]``."""
    raise NotImplementedError

KernelUncertainty

KernelUncertainty(kernel='linear', reg=1.0, lengthscale=1.0, max_points=None)

Bases: BaseUncertainty

Posterior standard deviation of kernel regression (ActFlow Eq. 10).

Given queried features \(Z_t = (z_1, \dots, z_t)\) with kernel matrix \((K_t)_{ij} = k(z_i, z_j)\), the uncertainty of a new point is

\[ \sigma_t^2(z) = k(z, z) - k(z, Z_t)\,\bigl(K_t + \lambda I\bigr)^{-1} k(Z_t, z), \qquad \sigma_t(z) = \sqrt{\sigma_t^2(z)}. \]

This is the posterior variance of Bayesian linear regression under Gaussian observations in the feature space of \(k\). With no queries it reduces to the prior \(k(z, z)\).

For the linear kernel \(k(z, z') = \langle z, z' \rangle\) the push-through identity gives the equivalent primal form

\[ \sigma_t^2(z) = \lambda\, z^\top \bigl(Z_t^\top Z_t + \lambda I_D\bigr)^{-1} z, \]

which costs \(\mathcal{O}(D^3)\) instead of \(\mathcal{O}(t^3)\). It is selected automatically once \(t > D\).

The score is differentiable in \(z\) (the stored Cholesky factor is a constant), so it can be back-propagated through FlowRepresentation to the sampling state. Linear algebra runs in float64 for stability and the result is cast back to the input dtype.

References

De Santi et al., "Active Flow Expansion for Out-of-Distribution Discovery: from Theory to Molecules" (2026), https://arxiv.org/abs/2606.08802. Rasmussen and Williams, "Gaussian Processes for Machine Learning" (2006), Ch. 2.

Parameters:

Name Type Description Default
kernel str

"linear" (the paper's default) or "rbf" (\(k(z, z') = \exp(-\lVert z - z' \rVert^2 / 2\ell^2)\), used in the paper's 2D experiment).

'linear'
reg float

regulariser \(\lambda > 0\) (observation-noise variance).

1.0
lengthscale float

RBF lengthscale \(\ell\). Ignored for the linear kernel.

1.0
max_points Optional[int]

if set, only the most recent max_points queries are kept, which bounds the \(\mathcal{O}(t^3)\) refit cost.

None
Source code in deltaflow/expansion/uncertainty.py
def __init__(
    self,
    kernel: str = "linear",
    reg: float = 1.0,
    lengthscale: float = 1.0,
    max_points: Optional[int] = None,
):
    if kernel not in ("linear", "rbf"):
        raise ValueError(f"kernel must be 'linear' or 'rbf', got {kernel!r}")
    if reg <= 0:
        raise ValueError(f"reg must be positive, got {reg}")
    self.kernel = kernel
    self.reg = float(reg)
    self.lengthscale = float(lengthscale)
    self.max_points = max_points
    self._z: Optional[torch.Tensor] = None
    self._y: Optional[torch.Tensor] = None
    self._chol: Optional[torch.Tensor] = None
    self._primal = False

variance

variance(features)

Return \(\sigma_t^2(z)\) with shape [B].

Source code in deltaflow/expansion/uncertainty.py
def variance(self, features: torch.Tensor) -> torch.Tensor:
    """Return \\(\\sigma_t^2(z)\\) with shape ``[B]``."""
    z = features.flatten(1).to(torch.float64)
    if self._z is None:
        return self._k_diag(z).to(features.dtype)
    z_ref = self._z.to(z.device)
    chol = self._chol.to(z.device)
    if self._primal:
        # sigma^2 = lambda * z^T (Z^T Z + lambda I)^{-1} z
        w = torch.cholesky_solve(z.T, chol)
        var = self.reg * (z.T * w).sum(0)
    else:
        k_star = self._k(z_ref, z)
        w = torch.cholesky_solve(k_star, chol)
        var = self._k_diag(z) - (k_star * w).sum(0)
    return var.to(features.dtype)

mean

mean(features)

Posterior mean of the label regression, a cheap validity surrogate.

Returns zeros if no labels were provided to fit.

Source code in deltaflow/expansion/uncertainty.py
def mean(self, features: torch.Tensor) -> torch.Tensor:
    """Posterior mean of the label regression, a cheap validity surrogate.

    Returns zeros if no labels were provided to `fit`.
    """
    z = features.flatten(1).to(torch.float64)
    if self._z is None or self._y is None:
        return torch.zeros(z.shape[0], dtype=features.dtype, device=features.device)
    z_ref = self._z.to(z.device)
    y = self._y.to(z.device)
    chol = self._chol.to(z.device)
    if self._primal:
        w = torch.cholesky_solve((z_ref.T @ y).unsqueeze(-1), chol).squeeze(-1)
        mu = z @ w
    else:
        alpha = torch.cholesky_solve(y.unsqueeze(-1), chol).squeeze(-1)
        mu = self._k(z, z_ref) @ alpha
    return mu.to(features.dtype)

generable_coverage

generable_coverage(samples, valid_fn, bounds=(-3.5, 3.5), bins=100, tau=0.01)

Histogram estimate of generable-set coverage for 2D samples.

Samples are binned on a bins x bins grid over bounds. A bin \(b\) is generable when its density estimate \(\hat{p}(b) = n_b / (N\,|b|)\) is at least \(\tau\), giving the plug-in generable set \(\hat{\Omega}^\tau\). A bin is valid when valid_fn accepts its centre, giving \(\hat{\Omega}^*\). Then

\[ \text{coverage} = \frac{|\hat{\Omega}^\tau \cap \hat{\Omega}^*|}{|\hat{\Omega}^*|}, \qquad \text{validity} = \frac{|\hat{\Omega}^\tau \cap \hat{\Omega}^*|}{|\hat{\Omega}^\tau|}. \]

Parameters:

Name Type Description Default
samples Tensor

[N, 2] model samples.

required
valid_fn Callable[[Tensor], Tensor]

verifier on [M, 2] points returning bools or {0, 1}.

required
bounds Bounds

(lo, hi) for both axes, or ((x_lo, x_hi), (y_lo, y_hi)).

(-3.5, 3.5)
bins int

bins per axis.

100
tau float

density threshold \(\tau\).

0.01

Returns:

Type Description
Dict[str, float]

A dict with coverage, validity, n_generable_bins and

Dict[str, float]

n_valid_bins.

Source code in deltaflow/expansion/metrics.py
@torch.no_grad()
def generable_coverage(
    samples: torch.Tensor,
    valid_fn: Callable[[torch.Tensor], torch.Tensor],
    bounds: Bounds = (-3.5, 3.5),
    bins: int = 100,
    tau: float = 0.01,
) -> Dict[str, float]:
    r"""Histogram estimate of generable-set coverage for 2D samples.

    Samples are binned on a ``bins x bins`` grid over ``bounds``. A bin
    \(b\) is *generable* when its density estimate
    \(\hat{p}(b) = n_b / (N\,|b|)\) is at least \(\tau\), giving the
    plug-in generable set \(\hat{\Omega}^\tau\). A bin is *valid* when
    ``valid_fn`` accepts its centre, giving \(\hat{\Omega}^*\). Then

    \[
    \text{coverage} = \frac{|\hat{\Omega}^\tau \cap \hat{\Omega}^*|}{|\hat{\Omega}^*|},
    \qquad
    \text{validity} = \frac{|\hat{\Omega}^\tau \cap \hat{\Omega}^*|}{|\hat{\Omega}^\tau|}.
    \]

    Args:
        samples: ``[N, 2]`` model samples.
        valid_fn: verifier on ``[M, 2]`` points returning bools or ``{0, 1}``.
        bounds: ``(lo, hi)`` for both axes, or ``((x_lo, x_hi), (y_lo, y_hi))``.
        bins: bins per axis.
        tau: density threshold \(\tau\).

    Returns:
        A dict with ``coverage``, ``validity``, ``n_generable_bins`` and
        ``n_valid_bins``.
    """
    if samples.dim() != 2 or samples.shape[1] != 2:
        raise ValueError(f"expected samples of shape [N, 2], got {tuple(samples.shape)}")
    (x_lo, x_hi), (y_lo, y_hi) = _axis_bounds(bounds)
    pts = samples.detach().float().cpu()
    n = pts.shape[0]
    wx, wy = (x_hi - x_lo) / bins, (y_hi - y_lo) / bins

    ix = torch.floor((pts[:, 0] - x_lo) / wx).long()
    iy = torch.floor((pts[:, 1] - y_lo) / wy).long()
    inside = (ix >= 0) & (ix < bins) & (iy >= 0) & (iy < bins)
    counts = torch.bincount(ix[inside] * bins + iy[inside], minlength=bins * bins).float()
    density = counts / max(n, 1) / (wx * wy)
    generable = density >= tau

    cx = x_lo + (torch.arange(bins, dtype=torch.float32) + 0.5) * wx
    cy = y_lo + (torch.arange(bins, dtype=torch.float32) + 0.5) * wy
    grid = torch.stack(torch.meshgrid(cx, cy, indexing="ij"), dim=-1).reshape(-1, 2)
    valid = torch.as_tensor(valid_fn(grid)).flatten().cpu()
    valid = valid if valid.dtype == torch.bool else valid.float() > 0.5

    hit = (generable & valid).sum().item()
    n_valid = int(valid.sum())
    n_gen = int(generable.sum())
    return {
        "coverage": hit / n_valid if n_valid else 0.0,
        "validity": hit / n_gen if n_gen else 0.0,
        "n_generable_bins": n_gen,
        "n_valid_bins": n_valid,
    }