Skip to content

losses

losses

Training objectives: conditional flow matching, signed replay, and delta (guidance) alignment.

ConditionalFlowMatchingLoss

ConditionalFlowMatchingLoss(interpolant=None, coupling=None, loss_type='l2', time_scale=1.0)

Bases: BaseLoss

Regress a velocity field onto the conditional target velocity of a path.

Conditional flow matching trains \(v_\theta\) to match the per-pair target velocity \(u_t\) of a probability path by minimising

\[ \mathcal{L} = \mathbb{E}_{t \sim \mathcal{U}[0,1],\, x_0,\, x_1} \bigl\| v_\theta(x_t, t) - u_t \bigr\|^2, \]

where \((x_t, u_t)\) are produced by the chosen interpolant (for the linear path, \(x_t = (1-t)x_0 + t x_1\) and \(u_t = x_1 - x_0\)). Although the target is only defined conditionally on \((x_0, x_1)\), its regression minimiser is the marginal velocity field that transports noise onto data, which is exactly the field the sampler integrates.

References

Lipman et al., "Flow Matching for Generative Modeling" (2023), https://arxiv.org/abs/2210.02747.

Parameters:

Name Type Description Default
interpolant Optional[BaseInterpolant]

the probability path to regress against. Defaults to LinearInterpolant.

None
coupling Optional[BaseCoupling]

optional train-time coupling that produces \((x_0, x_1)\) pairs from a batch of \(x_1\). See deltaflow.trainer.coupling. Kept separate from interpolant on purpose, since the two decisions (which path to use, and how to pair noise with data) are independent and swappable.

None
loss_type str

one of "l2", "l1", "huber".

'l2'
time_scale float

scales the continuous \(t \in [0, 1]\) before it reaches the model, e.g. to match a diffusion-style time embedding.

1.0
Source code in deltaflow/losses/conditional_flow_matching.py
def __init__(
    self,
    interpolant: Optional[BaseInterpolant] = None,
    coupling: Optional[BaseCoupling] = None,
    loss_type: str = "l2",
    time_scale: float = 1.0,
):
    self.interpolant = interpolant or LinearInterpolant()
    self.coupling = coupling
    self.loss_type = loss_type
    self.time_scale = time_scale

DeltaAlignmentLoss

DeltaAlignmentLoss(projector, lambda_flow=1.0, lambda_align=5.0)

Bases: Module

Combined flow-matching and delta-alignment loss.

The total objective linearly combines the velocity-regression term with the multi-scale guidance-alignment term,

\[ \mathcal{L} = \lambda_\text{flow}\,\mathcal{L}_\text{flow} + \lambda_\text{align}\,\mathcal{L}_\text{align}, \]

where, at each hierarchy level \(l\), the alignment term compares the guidance-difference embeddings \(z^{(i)}_l = g_l\bigl(\text{GAP}(\Delta h^{(i)}_l)\bigr)\) of two augmented views \(i \in \{1, 2\}\) via a cosine dissimilarity,

\[ \mathcal{L}_\text{align} = \frac{1}{L}\sum_{l=1}^{L} \Bigl(1 - \cos\bigl(z^{(1)}_l, z^{(2)}_l\bigr)\Bigr), \qquad \Delta h_l = h^\text{cond}_l - h^\text{uncond}_l. \]

During the alignment phase, \(\mathcal{L}_\text{flow}\) is computed over all four velocity predictions (two views by two conditioning modes) to preserve both the guided and unguided generative pathways while the alignment term shapes the guidance representation.

References

Di Via et al., "CDPM-Align: Multi-Scale Guidance-Aligned Diffusion Pretraining for Robust Few-Shot Anatomical Landmark Detection" (2026), https://arxiv.org/abs/2606.04898.

Source code in deltaflow/losses/delta_alignment.py
def __init__(
    self,
    projector: MultiScaleProjector,
    lambda_flow: float = 1.0,
    lambda_align: float = 5.0,
):
    super().__init__()
    self.projector = projector
    self.lambda_flow = lambda_flow
    self.lambda_align = lambda_align

forward

forward(v_c1, v_u1, target_v1, v_c2, v_u2, target_v2, feats_u1, feats_c1, feats_u2, feats_c2)

Return (total_loss, detached_components).

Suffix c/u is conditional/unconditional, 1/2 the augmented view. feats_* are per-level feature dicts from the backbone for the matching pass.

Source code in deltaflow/losses/delta_alignment.py
def forward(
    self,
    v_c1: torch.Tensor,
    v_u1: torch.Tensor,
    target_v1: torch.Tensor,
    v_c2: torch.Tensor,
    v_u2: torch.Tensor,
    target_v2: torch.Tensor,
    feats_u1: Dict[str, torch.Tensor],
    feats_c1: Dict[str, torch.Tensor],
    feats_u2: Dict[str, torch.Tensor],
    feats_c2: Dict[str, torch.Tensor],
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
    """Return ``(total_loss, detached_components)``.

    Suffix ``c``/``u`` is conditional/unconditional, ``1``/``2`` the
    augmented view. ``feats_*`` are per-level feature dicts from the
    backbone for the matching pass.
    """
    # Flow-matching loss over both views and both conditioning modes.
    fm = flow_matching_velocity_loss
    loss_flow_c = (fm(v_c1, target_v1) + fm(v_c2, target_v2)) / 2
    loss_flow_u = (fm(v_u1, target_v1) + fm(v_u2, target_v2)) / 2
    loss_flow = loss_flow_c + loss_flow_u

    # Multi-scale delta-alignment loss.
    loss_align = delta_alignment_loss(feats_u1, feats_c1, feats_u2, feats_c2, self.projector)

    total = self.lambda_flow * loss_flow + self.lambda_align * loss_align

    loss_dict = {
        "loss_total": total.detach(),
        "loss_flow": loss_flow.detach(),
        "loss_align": loss_align.detach(),
    }
    return total, loss_dict

EquilibriumMatchingLoss

EquilibriumMatchingLoss(interpolant=None, coupling=None, loss_type='l2')

Bases: BaseLoss

Regress a time-invariant field onto the Equilibrium Matching target.

Equilibrium Matching (EqM) trains a field \(f_\theta\) to match an energy-compatible target along the straight noise-to-data path. For an interpolation coefficient \(\gamma \in [0, 1]\) (a noise level), noise \(x_0\) and data \(x_1\), the corrupted sample and target are produced by an EquilibriumInterpolant,

\[ x_\gamma = (1 - \gamma)\,x_0 + \gamma\,x_1, \qquad u_\gamma = c(\gamma)\,(x_1 - x_0), \]

and the objective is (the paper's Eq. 3, up to the target-sign convention below)

\[ \mathcal{L}_{\text{EqM}} = \mathbb{E}_{\gamma,\, x_0,\, x_1} \bigl\| f_\theta(x_\gamma) - u_\gamma \bigr\|^2 . \]

\(\gamma\) is implicit, and there is no time at all. Unlike flow matching, where the model is conditioned on time \(t\), an EqM field is time-invariant and noise-unconditional, \(f_\theta(x)\). The coefficient \(\gamma\) is not seen by the model, and neither is any surrogate time. This loss therefore queries the model as model(x, **cond), passing no time (and no \(\gamma\)) at all, matching BaseEquilibriumField.

Target sign. The interpolant returns \(u_\gamma = c(\gamma)(x_1 - x_0)\) (data minus noise), so the field points from noise toward data and is sampled by gradient ascent \(x \leftarrow x + \eta f(x)\) in EquilibriumSolver. This matches the official EqM code. The paper writes the mirror-image \((\epsilon - x)c(\gamma)\) with descent, the two conventions are equivalent under a global sign flip.

References

Wang and Du, "Equilibrium Matching: Generative Modeling with Implicit Energy-Based Models" (2025), https://arxiv.org/abs/2510.02300.

Parameters:

Name Type Description Default
interpolant Optional[BaseEquilibriumInterpolant]

the energy-compatible path. Defaults to EquilibriumInterpolant.

None
coupling Optional[BaseCoupling]

optional train-time coupling that produces \((x_0, x_1)\) pairs from a batch of \(x_1\). See deltaflow.trainer.coupling.

None
loss_type str

one of "l2", "l1", "huber".

'l2'
Source code in deltaflow/losses/equilibrium_matching.py
def __init__(
    self,
    interpolant: Optional[BaseEquilibriumInterpolant] = None,
    coupling: Optional[BaseCoupling] = None,
    loss_type: str = "l2",
):
    self.interpolant = interpolant or EquilibriumInterpolant()
    self.coupling = coupling
    self.loss_type = loss_type

SignedReplayFlowMatchingLoss

SignedReplayFlowMatchingLoss(base_loss=None, alpha=0.0, alpha_mode='fixed')

Bases: BaseLoss

Accept-attract, reject-repel flow matching on verifier-labelled replay.

\[ \mathcal{L}^{\text{signed}}_t(\theta) = \hat{\mathcal{L}}^{+}_t(\theta) - \alpha_t\,\hat{\mathcal{L}}^{-}_t(\theta), \qquad \hat{\mathcal{L}}^{\pm}_t(\theta) = \frac{1}{|U^{\pm}_t|} \sum_{x \in U^{\pm}_t} \ell(\theta; x), \]

where \(U^{+}_t\) and \(U^{-}_t\) are minibatches from the accepted and rejected buffers and \(\ell\) is the base_loss (conditional flow matching by default). Its gradient is the signed update \(g_t = \nabla \hat{\mathcal{L}}^{+}_t - \alpha_t \nabla \hat{\mathcal{L}}^{-}_t\).

With alpha_mode="grad_norm" the weight is recalibrated every call,

\[ \alpha_t = \alpha\, \frac{\lVert \nabla_\theta \hat{\mathcal{L}}^{+}_t \rVert_2} {\lVert \nabla_\theta \hat{\mathcal{L}}^{-}_t \rVert_2}, \]

so that \(\lVert \alpha_t \nabla \hat{\mathcal{L}}^{-}_t \rVert = \alpha \lVert \nabla \hat{\mathcal{L}}^{+}_t \rVert\). This costs two extra backward passes and requires model to be an nn.Module. The calibrated \(\alpha_t\) is detached and stored in last_alpha.

References

De Santi et al., "Active Flow Expansion for Out-of-Distribution Discovery: from Theory to Molecules" (2026), Apx. D.1, https://arxiv.org/abs/2606.08802. Alberti et al., "Data Unlearning in Diffusion Models" (ICLR 2025).

Parameters:

Name Type Description Default
base_loss Optional[BaseLoss]

per-sample objective \(\ell\), any callable base_loss(model, x1, **cond) -> scalar. Defaults to ConditionalFlowMatchingLoss.

None
alpha float

target weight. A loss weight for "fixed", a gradient-norm fraction in \([0, 1]\) for "grad_norm". 0 disables the repulsive term.

0.0
alpha_mode str

"fixed" or "grad_norm".

'fixed'
Source code in deltaflow/losses/signed_replay.py
def __init__(
    self,
    base_loss: Optional[BaseLoss] = None,
    alpha: float = 0.0,
    alpha_mode: str = "fixed",
):
    if alpha_mode not in ("fixed", "grad_norm"):
        raise ValueError(f"alpha_mode must be 'fixed' or 'grad_norm', got {alpha_mode!r}")
    if alpha < 0:
        raise ValueError(f"alpha must be non-negative, got {alpha}")
    self.base_loss = base_loss or ConditionalFlowMatchingLoss()
    self.alpha = float(alpha)
    self.alpha_mode = alpha_mode
    self.last_alpha: float = 0.0

TimeUnconditionedFlowMatchingLoss

TimeUnconditionedFlowMatchingLoss(interpolant=None, coupling=None, loss_type='l2', pass_time=False)

Bases: BaseLoss

Flow matching where the model is not given the interpolation time.

Trains \(v_\theta(x_t)\) (no \(t\)) to match the conditional target velocity:

\[ \mathcal{L} = \mathbb{E}_{t \sim \mathcal{U}[0,1],\, x_0,\, x_1} \bigl\| v_\theta(x_t) - u_t \bigr\|^2 . \]

The time-blind loss exceeds the conditioned one by a "time-blindness gap", but in high dimensions time is identifiable from the noisy interpolant itself (data concentrates near a low-dimensional subspace), so the gap is asymptotically negligible next to the coupling variance. The choice of coupling is therefore the main practical lever.

References

"What Time Is It? How Data Geometry Makes Time Conditioning Optional for Flow Matching" (2026), https://arxiv.org/abs/2605.08344.

Parameters:

Name Type Description Default
interpolant Optional[BaseInterpolant]

probability path. Defaults to LinearInterpolant.

None
coupling Optional[BaseCoupling]

optional train-time coupling producing \((x_0, x_1)\) pairs.

None
loss_type str

one of "l2", "l1", "huber".

'l2'
pass_time bool

if False (default) the model is called as model(x_t, **cond). If True it is called as model(x_t, t, **cond) with a constant zero t, for models whose signature requires a time argument (e.g. TinyVelocityField); the zero carries no information.

False
Source code in deltaflow/losses/time_unconditioned.py
def __init__(
    self,
    interpolant: Optional[BaseInterpolant] = None,
    coupling: Optional[BaseCoupling] = None,
    loss_type: str = "l2",
    pass_time: bool = False,
):
    self.interpolant = interpolant or LinearInterpolant()
    self.coupling = coupling
    self.loss_type = loss_type
    self.pass_time = pass_time

delta_alignment_loss

delta_alignment_loss(feats_u1, feats_c1, feats_u2, feats_c2, projector)

Multi-scale alignment loss on guidance-difference embeddings.

For each hierarchy level l and each of two augmented views i in {1, 2}::

delta_h_l_i = h_cond_i[l] - h_uncond_i[l]
z_l_i       = projector_l(GAP(delta_h_l_i)), L2-normalized
loss_l      = 1 - cos(z_l_1, z_l_2)

Returns the average of loss_l over all levels present in every feature dict and in projector.

Source code in deltaflow/losses/delta_alignment.py
def delta_alignment_loss(
    feats_u1: Dict[str, torch.Tensor],
    feats_c1: Dict[str, torch.Tensor],
    feats_u2: Dict[str, torch.Tensor],
    feats_c2: Dict[str, torch.Tensor],
    projector: MultiScaleProjector,
) -> torch.Tensor:
    """Multi-scale alignment loss on guidance-difference embeddings.

    For each hierarchy level ``l`` and each of two augmented views ``i in {1, 2}``::

        delta_h_l_i = h_cond_i[l] - h_uncond_i[l]
        z_l_i       = projector_l(GAP(delta_h_l_i)), L2-normalized
        loss_l      = 1 - cos(z_l_1, z_l_2)

    Returns the average of ``loss_l`` over all levels present in every
    feature dict and in ``projector``.
    """
    # Normalisation is done here with `safe_normalize` (FP16/BF16-safe).
    z_view1 = projector.project_delta_h(feats_c1, feats_u1, normalize=False)
    z_view2 = projector.project_delta_h(feats_c2, feats_u2, normalize=False)
    shared_layers = [layer for layer in z_view1 if layer in z_view2]

    total_loss = torch.tensor(0.0, device=next(iter(feats_u1.values())).device)
    for layer in shared_layers:
        z1 = safe_normalize(z_view1[layer], dim=-1)
        z2 = safe_normalize(z_view2[layer], dim=-1)
        total_loss = total_loss + clamp_loss(_cosine_dissimilarity(z1, z2), max_val=10.0)

    if not shared_layers:
        return total_loss
    return total_loss / len(shared_layers)