Skip to content
Edit this page View source of this page

Wasserstein-DRO and Lipschitz regularization

Introductions to Wasserstein-DRO often state that it is equivalent to regularization. This page checks the equivalence numerically, because the statement is easy to misread. It does not say that the robust value is approximately a penalty, and it does not allow an arbitrary norm as the penalty. It concerns the Lipschitz modulus of the loss, measured in the same ground metric that defines the transport cost.

For a type-1 ball of radius \(\rho\) around a nominal \(\hat{P}\) and a loss \(\ell\) that is Lipschitz with respect to the ground metric, the Kantorovich-Rubinstein duality bounds the worst case by \(\mathbb{E}_{\hat{P}}[\ell] + \rho \cdot \mathrm{Lip}(\ell)\). The bound holds with equality when the space is unbounded and the loss attains its Lipschitz modulus as a slope at infinity, as the softplus loss used below does. In the strong dual of Gao and Kleywegt (2022), the inner supremum \(\sup_z \{\ell(z) - \gamma \lvert z - \hat{z} \rvert\}\) is then infinite for \(\gamma < \mathrm{Lip}(\ell)\) and equal to \(\ell(\hat{z})\) for \(\gamma \ge \mathrm{Lip}(\ell)\), so the dual minimum is attained at \(\gamma = \mathrm{Lip}(\ell)\) and gives

\[ \sup_{q \,:\, W(q, \hat{P}) \le \rho} \mathbb{E}_q[\ell] \;=\; \mathbb{E}_{\hat{P}}[\ell] \;+\; \rho \cdot \mathrm{Lip}(\ell). \]

Wu, Li and Mao1 prove exact equivalences of this kind in a much broader setting than the one used here, for general Wasserstein balls and general decision criteria. This page checks the finite-support special case that Optora solves.

What the discrete dual computes

WassersteinAmbiguitySet has no notion of a Lipschitz constant. It solves the exact discrete dual

\[ \inf_{\gamma \ge 0} \; \gamma \rho + \sum_i \hat{p}_i \max_j \big( \ell_j - \gamma \, c_{ij} \big), \]

and the regularization identity follows from it. Since \(c_{ii} = 0\), once \(\gamma\) is large enough that no transport is profitable, the inner maximum is attained at \(j = i\) for every \(i\). The objective then reduces to \(\mathbb{E}_{\hat{P}}[\ell] + \gamma\rho\), which is strictly increasing in \(\gamma\). The smallest \(\gamma\) at which this happens is

\[ L_n = \max_{i \ne j} \frac{|\ell_i - \ell_j|}{c_{ij}}, \]

which is the Lipschitz modulus of the loss restricted to the sample. The minimizer therefore never lies above \(L_n\), and for every radius below a positive threshold it lies exactly at \(L_n\), which gives

\[ \sup_{q \,:\, W(q, \hat{P}) \le \rho} \mathbb{E}_q[\ell] = \mathbb{E}_{\hat{P}}[\ell] + \rho \, L_n . \]

This is the equivalence on a finite support. Robustifying the empirical risk over a small Wasserstein ball is the same as penalizing the empirical Lipschitz modulus, with \(\rho\) as the regularization weight. It differs from the population statement above only by the gap between \(L_n\) and \(\mathrm{Lip}(\ell)\).

The two ways the gap closes

If the surrogate is built with the true constant, the gap splits into a term that vanishes as the sample refines and a term that vanishes as the ball shrinks,

\[ \underbrace{\mathbb{E}_{\hat{P}}[\ell] + \rho \, \mathrm{Lip}(\ell)}_{\text{surrogate}} \;-\; \underbrace{\sup_{q} \mathbb{E}_q[\ell]}_{\text{exact dual}} \;=\; \rho \big( \mathrm{Lip}(\ell) - L_n \big) \;+\; \underbrace{\text{concavity correction}}_{\to\, 0 \text{ as } \rho \to 0}. \]
Limit What closes the gap What the script plots
\(\rho \to 0\) the exact value is concave in \(\rho\) with tangent \(\mathbb{E}_{\hat{P}}[\ell] + \rho L_n\) at the origin, and it equals this tangent below a threshold radius, so the correction vanishes left panel, where the normalized gap flattens onto \(\mathrm{Lip}(\ell) - L_n\)
\(n \to \infty\) a larger sample contains steeper secants, so \(L_n \uparrow \mathrm{Lip}(\ell)\) right panel, where that plateau decreases toward zero

The script divides the gap by \(\rho\) throughout. Without the division the raw gap would shrink with \(\rho\) for any loss, and the small-radius panel would show nothing specific to the Lipschitz modulus.

Why softplus

The loss is \(\ell(z) = \log(1 + e^z)\) on a deterministic quantile discretization of \(\mathcal{N}(0, 1)\), with \(c_{ij} = |z_i - z_j|\).

It is exactly \(1\)-Lipschitz, because its derivative is the sigmoid, whose supremum is \(1\). The sigmoid is strictly below \(1\) everywhere, so the slope \(1\) is approached only as \(z \to \infty\) and never attained. Every secant slope is therefore below \(1\), so \(L_n < 1\) at every finite sample size and the sample-size axis has a nonzero gap to show.

A piecewise-linear loss would hide the effect

Take \(\ell(z) = |z|\) instead. Any two support points on the same side of the origin attain the full slope, so \(L_n = \mathrm{Lip}\) as soon as the sample has two such points, and the small-radius gap is zero to machine precision. That case is better suited to a unit test than to a plot, and it is tested in tests/dro/test_equivalences.py::test_small_radius_dual_equals_lipschitz_regularized_expectation. The same file covers the type-2 (squared-distance) counterpart, where the radius acts as a gradient-norm penalty instead.

Reading the output

The printed table gives \(L_n\), the measured normalized gap and the predicted deficiency \(1 - L_n\) side by side. They agree to every printed digit at every sample size, and the script asserts agreement within \(5 \times 10^{-3}\). The figure shows the result in two ways.

  • Left panel. The normalized gap against the radius, one curve per sample size, each with a dotted line at its own \(1 - L_n\). Each curve lies on its dotted line below a threshold radius and rises above it at larger radii, where the dual minimizer \(\gamma^\star\) moves below \(L_n\) and the worst case grows more slowly than linearly in \(\rho\). The threshold shrinks as \(n\) grows, because it is the transport cost of the first profitable move, which falls as the support becomes denser.
  • Right panel. The small-radius plateau against the sample size, on log-log axes, with the closed-form \(1 - L_n\) overlaid. The two lines coincide, which shows that the exact dual value equals the regularized objective \(\mathbb{E}_{\hat{P}}[\ell] + \rho L_n\) at this radius, up to floating-point rounding.

The dual is piecewise linear, so Optora bisects it

The objective above is a nonnegative combination of maxima of affine functions of \(\gamma\), so it is convex and piecewise linear, and its minimizer generically lies at a kink. A fixed-step gradient method cannot make the gradient norm small there. It oscillates across the kink and never passes a gradient-norm stopping test. WassersteinAmbiguitySet therefore bisects the sign change of the derivative, which is monotone in \(\gamma\), in a fixed number of steps set by the dtype. The worst case is then read off the primal transport plan, so the value is exact to working precision and the measured gap matches \(1 - L_n\) up to rounding.

The dual's kink at \(L_n\)

The equivalence is a statement about the minimizer of the dual, and the animation follows that minimizer as the radius shrinks over four and a half decades. Subtracting \(\mathbb{E}_{\hat{P}}[\ell]\) and dividing by \(\rho\) gives the curve in the left panel a fixed shape. To the right of \(L_n\), where no transport is profitable, it is the line \(\gamma\). To the left it rises steeply, by a term that scales as \(1/\rho\). For a large radius this rise is gentle and the minimizer lies below \(L_n\). As the radius shrinks the rise steepens and the minimizer is fixed at the kink. The middle panel shows the same behavior from the primal side. By the envelope theorem \(\mathrm{d}V/\mathrm{d}\rho\) equals \(\gamma^\star\), and the animation takes it from autograd. It settles at \(L_n\) for every sample size, below the true constant. The right panel is the normalized gap of the static figure, with markers moving along it.

The normalized Wasserstein dual in gamma, the derivative of the worst case in the radius, and the normalized gap, as the radius shrinks The normalized Wasserstein dual in gamma, the derivative of the worst case in the radius, and the normalized gap, as the radius shrinks
The left panel shows the normalized dual objective at $n = 64$, with its minimizer, the sample modulus $L_n$ dotted and the true Lipschitz constant dashed. The middle panel shows $\mathrm{d}V/\mathrm{d}\rho$ for three sample sizes, each settling on its own $L_n$. The right panel shows the normalized gap, which flattens at $\mathrm{Lip} - L_n$.

The figure

The figure is rendered from this script when the site is built, so it always shows the output of the current code.

Gap between the Lipschitz surrogate and the exact Wasserstein worst case, per unit radius, against the radius and the sample size Gap between the Lipschitz surrogate and the exact Wasserstein worst case, per unit radius, against the radius and the sample size
In the left panel, the excess of the surrogate over the exact value per unit radius flattens at the Lipschitz deficiency $\mathrm{Lip} - L_n$ as the radius shrinks. The right panel shows that this deficiency vanishes as the sample refines.

Source

tutorials/05_wasserstein_lipschitz_equivalence.py
"""Wasserstein-DRO as Lipschitz regularization.

Wasserstein-DRO is often justified by an equivalence with regularization.
On a type-1 Wasserstein ball built from a ground metric, robustifying an
expected loss is the same as penalizing the Lipschitz modulus of the loss. The linear
surrogate this suggests is

    sup_{q : W(q, nominal) <= radius} E_q[loss]  ~  E_nominal[loss]
                                                    + radius * Lip(loss)

which is the "robustness = regularization" reading of the ball radius.
Under this reading the radius adds a penalty proportional to how fast the
loss can change per unit of transport.

On a finite support the identity holds exactly. The exact discrete dual
solved by `WassersteinAmbiguitySet` is minimized at `gamma = L_n` for
every sufficiently small radius, where

    L_n = max_{i != j} |loss_i - loss_j| / cost_ij

is the Lipschitz modulus of the loss *restricted to the sample*. The dual
value is then exactly `E_nominal[loss] + radius * L_n`, so the gap against
the surrogate built from the true constant `Lip(loss)` is

    gap(radius) = radius * (Lip(loss) - L_n) + (concavity correction)

The concavity correction vanishes as the radius shrinks, and the first
term vanishes as the sample refines and `L_n -> Lip(loss)`. This script
measures both limits. It uses `softplus` as the loss, whose Lipschitz
constant is exactly 1 because its derivative is the sigmoid. The slope 1
is only approached asymptotically, so `L_n < 1` strictly at every finite
sample size.

Reference:
    Qinyu Wu, Jonathan Yu-Meng Li, Tiantian Mao, "On Generalization and
    Regularization via Wasserstein Distributionally Robust Optimization",
    Management Science (2025). arXiv:2212.05716.

Run:
    python tutorials/05_wasserstein_lipschitz_equivalence.py
"""

import matplotlib.pyplot as plt
import torch
from _plotting import save_figure

from optora.dro import WassersteinAmbiguitySet

LIPSCHITZ_CONSTANT = 1.0
RADII = torch.logspace(-4.0, 0.5, steps=12, dtype=torch.float64)
RADIUS_SWEEP_SIZES = (16, 64, 256)
SAMPLE_SIZES = (8, 16, 32, 64, 128, 256)
SMALL_RADIUS = 1e-3


def empirical_measure(
    num_samples: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """Build a deterministic `num_samples`-point discretization of N(0, 1).

    Support points are the midpoint quantiles of the standard normal, so
    the sample refines deterministically as `num_samples` grows and no seed
    is involved. The ground cost is the Euclidean metric on the support,
    which makes the ambiguity set a type-1 Wasserstein ball.

    Args:
        num_samples: Number of support points.

    Returns:
        A tuple `(nominal, loss, cost)` holding the uniform empirical
        distribution, the softplus loss evaluated on the support, and the
        pairwise ground cost matrix.
    """
    quantiles = (torch.arange(num_samples, dtype=torch.float64) + 0.5) / num_samples
    support = torch.special.ndtri(quantiles)
    loss = torch.nn.functional.softplus(support)
    cost = torch.abs(support.unsqueeze(-1) - support.unsqueeze(-2))
    nominal = torch.full_like(support, 1.0 / num_samples)
    return nominal, loss, cost


def empirical_lipschitz_constant(loss: torch.Tensor, cost: torch.Tensor) -> float:
    """Return the largest loss increment per unit of transport on the sample."""
    increments = torch.abs(loss.unsqueeze(-1) - loss.unsqueeze(-2))
    # The diagonal has a zero increment, and the added identity only avoids 0/0.
    separation = cost + torch.eye(cost.shape[-1], dtype=cost.dtype)
    return torch.max(increments / separation).item()


def normalized_gap(
    nominal: torch.Tensor, loss: torch.Tensor, cost: torch.Tensor, radius: float
) -> float:
    """Return `(surrogate - exact dual value) / radius` at `radius`.

    Dividing by the radius removes the trivial part of the convergence. The
    absolute gap shrinks with the radius for any loss, whereas the
    normalized gap isolates the Lipschitz deficiency `Lip(loss) - L_n` that
    the small-radius limit should expose.
    """
    ambiguity_set = WassersteinAmbiguitySet(nominal=nominal, cost=cost, radius=radius)
    exact = ambiguity_set.worst_case_expectation(loss).item()
    surrogate = torch.sum(nominal * loss).item() + radius * LIPSCHITZ_CONSTANT
    return (surrogate - exact) / radius


def main() -> None:
    fig, (ax_radius, ax_samples) = plt.subplots(1, 2, figsize=(11, 4))

    print("normalized gap (surrogate - exact) / radius, by sample size")
    for num_samples in RADIUS_SWEEP_SIZES:
        nominal, loss, cost = empirical_measure(num_samples)
        lipschitz = empirical_lipschitz_constant(loss, cost)
        gaps = [normalized_gap(nominal, loss, cost, radius.item()) for radius in RADII]
        deficiency = LIPSCHITZ_CONSTANT - lipschitz
        print(
            f"  n={num_samples:<4} L_n={lipschitz:.6f} "
            f"Lip - L_n={deficiency:.6f} "
            f"gap(radius->0)={gaps[0]:.6f} gap(radius={RADII[-1]:.3f})={gaps[-1]:.6f}"
        )
        assert min(gaps) > -1e-3
        assert abs(gaps[0] - deficiency) < 5e-3
        line = ax_radius.semilogx(RADII, gaps, marker="o", label=f"n = {num_samples}")
        ax_radius.axhline(deficiency, color=line[0].get_color(), linestyle=":")

    ax_radius.set_xlabel("Wasserstein radius")
    ax_radius.set_ylabel("(surrogate - exact) / radius")
    ax_radius.set_title("small radius: gap flattens at Lip - L_n")
    ax_radius.legend()

    print(f"\nsmall-radius limit at radius={SMALL_RADIUS}, by sample size")
    measured_gaps = []
    deficiencies = []
    for num_samples in SAMPLE_SIZES:
        nominal, loss, cost = empirical_measure(num_samples)
        lipschitz = empirical_lipschitz_constant(loss, cost)
        gap = normalized_gap(nominal, loss, cost, SMALL_RADIUS)
        measured_gaps.append(gap)
        deficiencies.append(LIPSCHITZ_CONSTANT - lipschitz)
        print(
            f"  n={num_samples:<4} L_n={lipschitz:.6f} "
            f"measured gap={gap:.6f} Lip - L_n={LIPSCHITZ_CONSTANT - lipschitz:.6f}"
        )

    decrements = torch.diff(torch.tensor(measured_gaps, dtype=torch.float64))
    is_decreasing = bool(torch.all(decrements < 0.0))
    print(f"gap decreases as the sample refines: {is_decreasing}")
    assert is_decreasing

    ax_samples.loglog(
        SAMPLE_SIZES, measured_gaps, marker="o", label="measured gap / radius"
    )
    ax_samples.loglog(
        SAMPLE_SIZES,
        deficiencies,
        marker="x",
        linestyle="--",
        label="Lip - L_n (predicted)",
    )
    ax_samples.set_xlabel("sample size n")
    ax_samples.set_ylabel("(surrogate - exact) / radius")
    ax_samples.set_title("growing sample: Lipschitz deficiency vanishes")
    ax_samples.legend()

    fig.tight_layout()
    save_figure(fig, "05_wasserstein_lipschitz_equivalence")


if __name__ == "__main__":
    main()

  1. Qinyu Wu, Jonathan Yu-Meng Li and Tiantian Mao, "On Generalization and Regularization via Wasserstein Distributionally Robust Optimization", Management Science (2025). arXiv:2212.05716. ↩