Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions RELEASES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

#### New features

- Accelerate supported dense NumPy Sinkhorn calls at their existing marginal tolerance and add an optional full-plan total variation stopping tolerance (Issue #934).

- `ot.dr.wda` gains `solver='torch'`, a PyTorch autodiff solver with Riemannian gradient descent, usable on installations without autograd or pymanopt, and accepting torch tensors directly (PR #858, Issue #806)
- `ot.dr` dependencies (autograd, pymanopt, scikit-learn, torch) are now imported optionally, so importing `ot.dr` no longer requires all of them; each function raises an explicit `ImportError` naming what it needs (PR #858)
Expand Down
19 changes: 19 additions & 0 deletions docs/source/user_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,25 @@ equation above is given to those functions with the parameter :code:`reg`.

More details about the algorithms used are given in the following note.

An optional :code:`plan_tol` in :any:`ot.sinkhorn` adds a stopping check for
the total variation error in the **full returned transport matrix**, rather
than just a marginal residual. It is available with :code:`method="sinkhorn"`
for one pair of strictly positive NumPy float64 histograms and a finite,
numerically safe positive Gibbs kernel. The estimate follows from an
exact-arithmetic scaling bound; its float64 evaluation is not an
interval-certified bound. If the requested tolerance cannot be verified
within the iteration budget, the opt-in mode raises an error. See the
`proof discussion and benchmarks <https://github.com/PythonOT/POT/issues/934>`_
and :ref:`sphx_glr_auto_examples_plot_sinkhorn_plan_tol.py`.
Omitting the option keeps the ordinary marginal stopping target. Eligible
positive dense NumPy calls automatically reuse matrix products and may stop
between the usual checkpoints after checking the returned marginals.
For supported NumPy warm starts, the classic solver also checks the caller's
marginal tolerance after updates 2, 3 and 4. An early return checks the row
and column residuals on the returned matrix. With :code:`log=True` the
ordinary log includes the final error and scaling vectors, so a registration
loop can use them for its next warm start.

.. note::
The main function to solve entropic regularized OT is :any:`ot.sinkhorn`.
This function is a wrapper and the parameter :code:`method` allows you to select
Expand Down
34 changes: 34 additions & 0 deletions examples/plot_sinkhorn_plan_tol.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""
Full-plan stopping for dense NumPy Sinkhorn
===========================================

A marginal residual and the error in the whole transport matrix are
different quantities. This example uses an independent, planted entropic
optimum to compare POT's standard stopping rule and the opt-in full-plan
tolerance.
"""

import numpy as np

import ot

x = np.linspace(0, 1, 64)
y = np.linspace(0, 1, 128)
M = 0.5 * (x[:, None] - y[None, :]) ** 2
reg = 0.02

# An exact positive diagonal scaling of the Gibbs kernel is the entropic
# optimum for its induced marginals. Use it as a numerical reference.
reference = np.exp(-M / reg) * (0.2 + x[:, None]) * (1.3 - y)
reference /= reference.sum()
a, b = reference.sum(axis=1), reference.sum(axis=0)

target = 2.5e-8
stock, stock_log = ot.sinkhorn(a, b, M, reg, stopThr=1e-7, log=True)
plan, plan_log = ot.sinkhorn(a, b, M, reg, stopThr=1e-7, plan_tol=target, log=True)

print(f"Requested whole-plan TV tolerance: {target:.3e}")
print(f"Observed TV (ordinary): {0.5 * np.abs(stock - reference).sum():.3e}")
print(f"Observed TV (opt-in): {0.5 * np.abs(plan - reference).sum():.3e}")
print("Float64 TV estimate: {:.3e}".format(plan_log["plan_tv_estimate"]))
print("Updates (ordinary / opt-in):", stock_log["niter"] + 1, plan_log["niter"] + 1)
94 changes: 89 additions & 5 deletions ot/bregman/_sinkhorn.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ def sinkhorn(
log=False,
warn=True,
warmstart=None,
*,
plan_tol=None,
**kwargs,
):
r"""
Expand Down Expand Up @@ -110,6 +112,20 @@ def sinkhorn(
Initialization of dual potentials. If provided, the dual potentials should be given
(that is the logarithm of the u,v sinkhorn scaling vectors)

plan_tol : float, optional
Require an estimated total variation error below this tolerance for
the full transport matrix, in addition to both marginal checks.
Supported only for `method="sinkhorn"`, single strictly positive
NumPy float64 probability marginals, and a C-contiguous cost matrix
with a numerically safe, positive Gibbs kernel. In this mode,
`verbose=True` is not supported. Invalid inputs raise
ValueError; failure to verify the tolerance (including exhaustion)
raises ArithmeticError. This float64 estimate is not an interval
certificate. When `log=True`, `plan_tv_estimate` records the estimate.
With `None`, eligible NumPy plan calls use automatic marginal stopping
at `stopThr`. Supported warm starts also check at updates 2, 3 and 4.
An early return records the final checked error when logging is enabled.

Returns
-------
gamma : array-like, shape (dim_a, dim_b)
Expand Down Expand Up @@ -161,6 +177,9 @@ def sinkhorn(

"""

if plan_tol is not None and method.lower() != "sinkhorn":
raise ValueError("plan_tol is only supported by method='sinkhorn'.")

if method.lower() == "sinkhorn":
return sinkhorn_knopp(
a,
Expand All @@ -173,6 +192,7 @@ def sinkhorn(
log=log,
warn=warn,
warmstart=warmstart,
plan_tol=plan_tol,
**kwargs,
)
elif method.lower() == "sinkhorn_log":
Expand Down Expand Up @@ -384,12 +404,17 @@ def sinkhorn2(
:ref:`[9] <references-sinkhorn2>` :ref:`[10] <references-sinkhorn2>`
"""

if kwargs.pop("plan_tol", None) is not None:
raise ValueError(
"plan_tol is only supported by sinkhorn, which returns the transport matrix."
)

M, a, b = list_to_array(M, a, b)
nx = get_backend(M, a, b)

if len(b.shape) < 2:
if method.lower() == "sinkhorn":
res = sinkhorn_knopp(
res = _sinkhorn_knopp_standard(
a,
b,
M,
Expand All @@ -400,7 +425,6 @@ def sinkhorn2(
log=log,
warn=warn,
warmstart=warmstart,
**kwargs,
)
elif method.lower() == "sinkhorn_log":
res = sinkhorn_log(
Expand Down Expand Up @@ -439,7 +463,7 @@ def sinkhorn2(

else:
if method.lower() == "sinkhorn":
return sinkhorn_knopp(
return _sinkhorn_knopp_standard(
a,
b,
M,
Expand All @@ -450,7 +474,6 @@ def sinkhorn2(
log=log,
warn=warn,
warmstart=warmstart,
**kwargs,
)
elif method.lower() == "sinkhorn_log":
return sinkhorn_log(
Expand Down Expand Up @@ -495,6 +518,8 @@ def sinkhorn_knopp(
log=False,
warn=True,
warmstart=None,
*,
plan_tol=None,
**kwargs,
):
r"""
Expand Down Expand Up @@ -550,6 +575,20 @@ def sinkhorn_knopp(
Initialization of dual potentials. If provided, the dual potentials should be given
(that is the logarithm of the u,v sinkhorn scaling vectors)

plan_tol : float, optional
Require an estimated total variation error below this tolerance for
the full transport matrix, in addition to both marginal checks.
Supported only for `method="sinkhorn"`, single strictly positive
NumPy float64 probability marginals, and a C-contiguous cost matrix
with a numerically safe, positive Gibbs kernel. In this mode,
`verbose=True` is not supported. Invalid inputs raise
ValueError; failure to verify the tolerance (including exhaustion)
raises ArithmeticError. This float64 estimate is not an interval
certificate. When `log=True`, `plan_tv_estimate` records the estimate.
With `None`, eligible NumPy plan calls use automatic marginal stopping
at `stopThr`. Supported warm starts also check at updates 2, 3 and 4.
An early return records the final checked error when logging is enabled.

Returns
-------
gamma : array-like, shape (dim_a, dim_b)
Expand Down Expand Up @@ -585,6 +624,51 @@ def sinkhorn_knopp(

"""

if plan_tol is not None:
if verbose or kwargs:
raise ValueError(
"plan_tol does not support verbose or extra solver arguments."
)
from ._sinkhorn_plan import _solve_full_plan

return _solve_full_plan(
a, b, M, reg, numItermax, stopThr, plan_tol, log=log, warmstart=warmstart
)

kernel = None
if (
type(log) is bool
and (not log or warmstart is not None)
and verbose is False
and not kwargs
and type(warn) is bool
):
from ._sinkhorn_plan import _try_marginal

plan, kernel = _try_marginal(
a, b, M, reg, numItermax, stopThr, warn, warmstart=warmstart, log=log
)
if plan is not None:
return plan
return _sinkhorn_knopp_standard(
a, b, M, reg, numItermax, stopThr, verbose, log, warn, warmstart, kernel=kernel
)


def _sinkhorn_knopp_standard(
a,
b,
M,
reg,
numItermax=1000,
stopThr=1e-9,
verbose=False,
log=False,
warn=True,
warmstart=None,
*,
kernel=None,
):
a, b, M = list_to_array(a, b, M)

nx = get_backend(M, a, b)
Expand Down Expand Up @@ -618,7 +702,7 @@ def sinkhorn_knopp(
else:
u, v = nx.exp(warmstart[0]), nx.exp(warmstart[1])

K = nx.exp(M / (-reg))
K = nx.exp(M / (-reg)) if kernel is None else kernel

Kp = (1 / a).reshape(-1, 1) * K

Expand Down
Loading
Loading