diff --git a/RELEASES.md b/RELEASES.md index b0e12bb7c..5b3cc0cfa 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -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) diff --git a/docs/source/user_guide.rst b/docs/source/user_guide.rst index f390bf55b..57cbc0fc1 100644 --- a/docs/source/user_guide.rst +++ b/docs/source/user_guide.rst @@ -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 `_ +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 diff --git a/examples/plot_sinkhorn_plan_tol.py b/examples/plot_sinkhorn_plan_tol.py new file mode 100644 index 000000000..bbef302ce --- /dev/null +++ b/examples/plot_sinkhorn_plan_tol.py @@ -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) diff --git a/ot/bregman/_sinkhorn.py b/ot/bregman/_sinkhorn.py index 152112364..07182c8f0 100644 --- a/ot/bregman/_sinkhorn.py +++ b/ot/bregman/_sinkhorn.py @@ -30,6 +30,8 @@ def sinkhorn( log=False, warn=True, warmstart=None, + *, + plan_tol=None, **kwargs, ): r""" @@ -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) @@ -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, @@ -173,6 +192,7 @@ def sinkhorn( log=log, warn=warn, warmstart=warmstart, + plan_tol=plan_tol, **kwargs, ) elif method.lower() == "sinkhorn_log": @@ -384,12 +404,17 @@ def sinkhorn2( :ref:`[9] ` :ref:`[10] ` """ + 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, @@ -400,7 +425,6 @@ def sinkhorn2( log=log, warn=warn, warmstart=warmstart, - **kwargs, ) elif method.lower() == "sinkhorn_log": res = sinkhorn_log( @@ -439,7 +463,7 @@ def sinkhorn2( else: if method.lower() == "sinkhorn": - return sinkhorn_knopp( + return _sinkhorn_knopp_standard( a, b, M, @@ -450,7 +474,6 @@ def sinkhorn2( log=log, warn=warn, warmstart=warmstart, - **kwargs, ) elif method.lower() == "sinkhorn_log": return sinkhorn_log( @@ -495,6 +518,8 @@ def sinkhorn_knopp( log=False, warn=True, warmstart=None, + *, + plan_tol=None, **kwargs, ): r""" @@ -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) @@ -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) @@ -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 diff --git a/ot/bregman/_sinkhorn_plan.py b/ot/bregman/_sinkhorn_plan.py new file mode 100644 index 000000000..38b6c8fe4 --- /dev/null +++ b/ot/bregman/_sinkhorn_plan.py @@ -0,0 +1,500 @@ +"""Dense, opt-in full-plan stopping for positive NumPy Sinkhorn. + +The estimate is derived in exact arithmetic; float64 is not outward rounded. +See https://github.com/PythonOT/POT/issues/934 for the proof and benchmarks. +""" + +from __future__ import annotations + +import ctypes +import math +from dataclasses import dataclass +from numbers import Real +from threading import local +import warnings + +import numpy as np + +# One opportunistic entry per thread. Larger kernels are built per call. +_AUTO_BYTES = 32 * 1024 * 1024 +_cache = local() + +# A byte comparison uses no matrix-sized temporary and exits on the first difference. +# np.array_equal is the portable fallback when a C runtime symbol is unavailable. +try: + _memcmp = ctypes.CDLL(None).memcmp +except (AttributeError, OSError, TypeError): + _memcmp = None +else: + _memcmp.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t] + _memcmp.restype = ctypes.c_int + + +def _plan_factor(low, high, n): + # log cross-ratio diameter <= 2 log(high/low). Guard before dividing. + cap = float(n - 1) + if high >= (2 * cap - 1) * low: + return cap + return 0.5 * (1 + high / low) + + +@dataclass(eq=False) +class _Kernel: + matrix: np.ndarray + column_factor: float + row_factor: float + uniform_columns: np.ndarray | None = None + + def cold_columns(self, u): + if self.uniform_columns is None: + self.uniform_columns = self.matrix.T @ u + return self.uniform_columns + + +def _build_kernel(M, reg, *, shared): + # The caller selects strict or ordinary NumPy warning semantics. + K = np.empty_like(M) + np.divide(M, -reg, out=K) + np.exp(K, out=K) + low, high = K.min(), K.max() + if not (low > 1e-280 and high < 1e100): + # The standard solver can consume this already-computed kernel. + return K + factor = _plan_factor(low, high, M.shape[1]) + ratio = low / high + tau = (1 - ratio) / (1 + ratio) + propagated = min(1 + _plan_factor(low, high, M.shape[0]), factor * tau) + if shared: + K.setflags(write=False) + return _Kernel(K, factor, propagated) + + +@dataclass(frozen=True, eq=False) +class _Prepared: + cost: np.ndarray + kernel: object + + +@dataclass +class _Entry: + signature: tuple + prepared: _Prepared | None = None + skip: int = 0 + + +def _same_cost(M, saved): + # Both are live C-contiguous CPU float64 ndarrays with matching shape, checked by the caller. + if _memcmp is None: + return np.array_equal(M, saved) + return _memcmp(M.ctypes.data, saved.ctypes.data, M.nbytes) == 0 + + +def _auto_kernel(M, reg): + if 2 * M.nbytes + M.shape[1] * 8 > _AUTO_BYTES: + return _build_kernel(M, reg, shared=False) + rows, cols = M.shape + signature = (M.shape, reg, M[0, 0], M[rows // 2, cols // 2], M[-1, -1]) + entry = getattr(_cache, "entry", None) + if entry is None or entry.signature != signature: + # Samples screen candidates only. No kernel is ever reused on this basis. + _cache.entry = _Entry(signature) + elif entry.skip: + entry.skip -= 1 + elif entry.prepared is None: + cost = M.copy(order="C") + cost.setflags(write=False) + kernel = _build_kernel(cost, reg, shared=True) + if isinstance(kernel, _Kernel): + entry.prepared = _Prepared(cost, kernel) + return kernel + elif _same_cost(M, entry.prepared.cost): + return entry.prepared.kernel + else: + # If the samples match while other entries change, defer another snapshot. + entry.prepared, entry.skip = None, 8 + return _build_kernel(M, reg, shared=False) + + +def _materialize(K, u, v): + # An unshared kernel can be overwritten. Every shared-kernel solve creates its own result. + out = K if K.flags.writeable else None + plan = np.multiply(K, u[:, None], out=out) + plan *= v + return plan + + +def _residual_norm(residual): + """Euclidean norm for a real, contiguous one-dimensional residual.""" + return np.float64(math.sqrt(residual.dot(residual))) + + +def _try_marginal(a, b, M, reg, limit, tol, warn, *, warmstart=None, log=False): + """Return (plan, None) on success or (None, reusable unscaled kernel) on fallback.""" + if ( + type(a) is not np.ndarray + or type(b) is not np.ndarray + or type(M) is not np.ndarray + or a.dtype != np.float64 + or b.dtype != np.float64 + or M.dtype != np.float64 + ): + return None, None + if ( + a.ndim != 1 + or b.ndim != 1 + or M.shape != (a.size, b.size) + or min(a.size, b.size) < 2 + or not M.flags.c_contiguous + or type(limit) not in (int, np.int32, np.int64) + or limit < 11 + or type(tol) not in (float, np.float64) + or not 1e-13 <= tol < 1 + or type(reg) not in (float, int, np.float64) + or not np.isfinite(reg) + or reg <= 0 + ): + return None, None + min_a, min_b = a.min(), b.min() + if ( + not min_a > 0 + or not min_b > 0 + or not abs(a.sum() - 1.0) <= 8e-15 + or not abs(b.sum() - 1.0) <= 8e-15 + ): + return None, None + if warmstart is not None: + if not isinstance(warmstart, (tuple, list)) or len(warmstart) != 2: + return None, None + for seed, marginal in zip(warmstart, (a, b)): + if ( + type(seed) is not np.ndarray + or seed.dtype != np.float64 + or seed.shape != marginal.shape + ): + return None, None + # Outside this range let the standard loop handle floating-point + # exceptions and rollback with both original scaling vectors. + if ( + min(min_a, min_b) < 1e-100 + or not np.abs(warmstart[0]).max() < 200.0 + or not np.abs(warmstart[1]).max() < 200.0 + ): + return None, None + kernel = _auto_kernel(M, reg) + if not isinstance(kernel, _Kernel): + return None, kernel + if warmstart is not None: + return _warm_marginal( + a, b, kernel.matrix, np.exp(warmstart[0]), limit, tol, log, warn + ) + K = kernel.matrix + wide = b.size >= 4 * a.size + col_budget = (0.25 * tol) / kernel.column_factor + row_budget = (0.25 * tol) / max(kernel.row_factor, 1e-300) + u = np.full(a.size, 1.0 / a.size) + col_product = kernel.cold_columns(u) + with np.errstate(over="ignore", invalid="ignore", divide="ignore", under="ignore"): + for it in range(limit): + v = b / col_product + kv = K @ v + checkpoint = it % 10 == 0 + extra = it % 10 in (4, 7, 9) and it + 10 - it % 10 < limit + accept = wide and extra and 0.5 * np.abs(u * kv - a).sum() < row_budget + u = a / kv + if not accept: + col_product = K.T @ u + if checkpoint: + accept = _residual_norm(v * col_product - b) < tol + elif extra and not wide: + accept = 0.5 * np.abs(v * col_product - b).sum() < col_budget + if accept: + plan = _materialize(K, u, v) + z = plan.sum(axis=0) - b + if ( + _residual_norm(z) < tol + and _residual_norm(plan.sum(axis=1) - a) < tol + and (wide or checkpoint or 0.5 * np.abs(z).sum() < col_budget) + ): + return plan, None + # _materialize can overwrite an unshared kernel. + return None, None if K.flags.writeable else K + if checkpoint and not np.isfinite(u).all(): + return None, K + if not np.isfinite(u).all() or not np.isfinite(v).all(): + return None, K + plan = _materialize(K, u, v) + if not _residual_norm(plan.sum(axis=1) - a) < max(tol, 1e-12): + return None, None if K.flags.writeable else K + if warn: + warnings.warn( + "Sinkhorn did not converge. You might want to " + "increase the number of iterations `numItermax` " + "or the regularization parameter `reg`.", + stacklevel=3, + ) + return plan, None + + +def _warm_marginal(a, b, K, u, limit, tol, log, warn): + """Check the ordinary marginal tolerance at updates 1–4, 11, 21, ... .""" + errors = [] if log else None + with np.errstate(over="ignore", under="ignore", invalid="ignore", divide="ignore"): + col_product = K.T @ u + for it in range(limit): + v = b / col_product + u = a / (K @ v) + col_product = K.T @ u + ordinary = it % 10 == 0 + if it >= 4 and not ordinary: + continue + err = _residual_norm(v * col_product - b) + if not math.isfinite(err): + return None, K + if log and ordinary: + errors.append(err) + if err < tol: + break + else: + # Replay a nonfinite failure from the original inputs so that POT + # emits its usual numerical warning and returns its rollback state. + if not ( + np.isfinite(v).all() + and np.isfinite(u).all() + and np.isfinite(col_product).all() + and (u > 0).all() + and (v > 0).all() + and (col_product > 0).all() + ): + return None, K + plan = _materialize(K, u, v) + row_error = _residual_norm(plan.sum(axis=1) - a) + col_error = _residual_norm(plan.sum(axis=0) - b) + converged = (ordinary or it < 4) and err < tol + if not ( + row_error < tol + and math.isfinite(col_error) + and (not converged or col_error < tol) + ): + return None, None if K.flags.writeable else K + if converged: + if log and not ordinary: + errors.append(col_error) + elif warn: + warnings.warn( + "Sinkhorn did not converge. You might want to " + "increase the number of iterations `numItermax` " + "or the regularization parameter `reg`.", + stacklevel=3, + ) + if log: + return (plan, {"err": errors, "niter": it, "u": u, "v": v}), None + return plan, None + + +def _direction_bound(z, col, u, v, old_z, old_u, old_v, factor, target): + direction = z - old_z + squared_length = direction @ direction + if not np.isfinite(squared_length) or squared_length <= 0: + return np.inf + t = max(0.0, float(-(z @ direction) / squared_length)) + if not np.isfinite(t) or not t: + return np.inf + + # This nonnegative summand suffices to determine both rejection and retry + # when the full bound is at least four times the target. + residual_part = factor * 0.5 * np.abs(z + t * direction).sum() + if residual_part >= 4.0 * target: + return np.inf + + row_ratio = old_u / u + col_ratio = old_v / v + max_row_ratio = row_ratio.max() + m = max(0.0, t * (max_row_ratio * col_ratio.max() - 1)) + if not np.isfinite(m) or m >= 1: + return np.inf + centered = col_ratio - (col @ col_ratio) / col.sum() + chi_upper = (t * max_row_ratio) ** 2 * (col @ (centered * centered)) + entropy_part = np.sqrt(chi_upper * min(0.5, 0.25 / (1 - m))) + bound = entropy_part + residual_part + return bound if np.isfinite(bound) else np.inf + + +def _solve_full_plan(a, b, M, reg, limit, tol, target, *, log, warmstart): + """Solve the opt-in problem with the validated residual-based scheduler.""" + if not all(type(x) is np.ndarray and x.dtype == np.float64 for x in (a, b, M)): + raise ValueError("plan_tol requires NumPy float64 arrays.") + if ( + a.ndim != 1 + or b.ndim != 1 + or M.ndim != 2 + or M.shape != (a.size, b.size) + or min(a.size, b.size) < 2 + or not M.flags.c_contiguous + ): + raise ValueError( + "plan_tol requires one histogram pair and a C-contiguous cost matrix with at least two rows and columns." + ) + if not all( + isinstance(x, Real) + and not isinstance(x, (bool, np.bool_)) + and np.isfinite(x) + and x > 0 + for x in (reg, tol, target) + ): + raise ValueError( + "plan_tol requires positive finite tolerances and regularization." + ) + if ( + not isinstance(limit, (int, np.integer)) + or isinstance(limit, (bool, np.bool_)) + or limit < 1 + ): + raise ValueError("plan_tol requires a positive integer numItermax.") + if ( + not np.all(np.isfinite(a) & (a > 0)) + or not np.all(np.isfinite(b) & (b > 0)) + or abs(a.sum() - 1.0) > 8e-15 + or abs(b.sum() - 1.0) > 8e-15 + ): + raise ValueError("plan_tol requires strictly positive probability marginals.") + # The kernel range check already rejects NaN and both infinities in M. + with np.errstate(over="ignore", under="ignore", invalid="ignore", divide="ignore"): + kernel = _auto_kernel(M, reg) + if not isinstance(kernel, _Kernel): + raise ValueError( + "plan_tol requires a numerically safe, strictly positive Gibbs kernel." + ) + + K = kernel.matrix + c = min(kernel.column_factor, len(a)) + wide = len(b) >= 4 * len(a) + use_direction = M.size > 4096 + pre_budget = target / max(kernel.row_factor, 1e-300) + if warmstart is None: + u = np.full(len(a), 1.0 / len(a)) + col_product = kernel.cold_columns(u) + else: + if ( + not isinstance(warmstart, (tuple, list)) + or len(warmstart) != 2 + or not all( + type(x) is np.ndarray + and x.dtype == np.float64 + and x.shape == (n,) + and np.isfinite(x).all() + for x, n in zip(warmstart, (len(a), len(b))) + ) + ): + raise ValueError( + "plan_tol warmstart requires a pair of finite NumPy float64 log-scalings." + ) + with np.errstate(over="ignore", under="ignore"): + u = np.exp(warmstart[0]) + if not (np.isfinite(u).all() and (u > 0).all()): + raise ArithmeticError( + "Sinkhorn plan_tol warmstart scaling is outside the float64 range." + ) + col_product = K.T @ u + previous = None + retry_below = np.inf + errors = [] + with np.errstate(over="ignore", invalid="ignore", divide="ignore", under="ignore"): + for it in range(limit): + v = b / col_product + kv = K @ v + ordinary = it % 10 == 0 + extra = it % 10 in (4, 7, 9) and it + 10 - it % 10 < limit + probe = ( + ordinary + or extra + or (warmstart is not None and it < 4 and use_direction) + ) + reason = None + if wide and probe: + before = 0.5 * np.abs(u * kv - a).sum() + if before < pre_budget: + reason = "pre" + estimate = kernel.row_factor * before + u = a / kv + if reason is None: + col_product = K.T @ u + if not probe: + continue + cols_before = v * col_product + residual = cols_before - b + logged_l2 = None + if log and ordinary: + logged_l2 = np.linalg.norm(residual) + errors.append(logged_l2) + l1 = np.abs(residual).sum() + e = 0.5 * l1 + estimate = c * e + if estimate < target and ( + l1 < tol + or ( + logged_l2 if logged_l2 is not None else np.linalg.norm(residual) + ) + < tol + ): + reason = "direct" + elif ( + use_direction + and it + 1 >= 11 + and previous is not None + and e < target + and e <= retry_below + ): + old_z, old_u, old_v, old_e, old_it = previous + gap = it - old_it + fast_enough = ( + e < old_e and estimate * (e / old_e) ** (4 / gap) <= target + ) + if not fast_enough: + estimate = _direction_bound( + residual, cols_before, u, v, old_z, old_u, old_v, c, target + ) + if estimate < target: + reason = "vector" + else: + retry_below = e * max(0.25, min(0.9, target / estimate)) + if reason is None: + if use_direction and it + 1 >= 8: + previous = residual, u, v, e, it + if not np.isfinite(u).all() or not np.isfinite(v).all(): + raise ArithmeticError( + "Sinkhorn plan_tol could not be verified after numerical failure." + ) + continue + + # Recheck the materialized result, not only the scaling residual. + plan = _materialize(K, u, v) + cols = plan.sum(axis=0) + residual = cols - b + col_l2 = np.linalg.norm(residual) + if reason == "direct": + estimate = c * 0.5 * np.abs(residual).sum() + elif reason == "vector": + estimate = _direction_bound( + residual, cols, u, v, old_z, old_u, old_v, c, target + ) + if not ( + estimate < target + and col_l2 < tol + and np.linalg.norm(plan.sum(axis=1) - a) < tol + ): + raise ArithmeticError( + "Sinkhorn plan_tol could not be verified on the materialized plan." + ) + if log: + if reason == "pre" and ordinary: + errors.append(col_l2) + return plan, { + "niter": it, + "err": errors, + "u": u, + "v": v, + "plan_tv_estimate": float(estimate), + "plan_exit": reason, + } + return plan + raise ArithmeticError("Sinkhorn plan_tol was not met within numItermax.") diff --git a/test/test_sinkhorn_plan_tol.py b/test/test_sinkhorn_plan_tol.py new file mode 100644 index 000000000..25b9c988d --- /dev/null +++ b/test/test_sinkhorn_plan_tol.py @@ -0,0 +1,348 @@ +"""Regression coverage for opt-in full-plan Sinkhorn stopping.""" + +import numpy as np +import pytest + +import ot + + +def planted(n, m): + rng = np.random.default_rng(n * 1000 + m) + M = np.ascontiguousarray(rng.uniform(0.0, 1.0, (n, m))) + reg = 0.12 + kernel = np.exp(-M / reg) + P = rng.uniform(0.5, 1, n)[:, None] * kernel * rng.uniform(0.5, 1, m) + P /= P.sum() + return P.sum(axis=1), P.sum(axis=0), M, reg, P + + +@pytest.mark.parametrize("shape", [(7, 8), (19, 100), (36, 192), (73, 67)]) +def test_plan_tol_against_planted_plan(shape): + a, b, M, reg, P = planted(*shape) + target = 5e-9 + plan, info = ot.sinkhorn(a, b, M, reg, plan_tol=target, stopThr=1e-7, log=True) + observed = 0.5 * np.abs(plan - P).sum() + assert observed < target + assert observed <= info["plan_tv_estimate"] + 2e-15 + assert info["plan_tv_estimate"] < target + assert np.linalg.norm(plan.sum(axis=0) - b) < 1e-7 + assert np.linalg.norm(plan.sum(axis=1) - a) < 1e-7 + np.testing.assert_array_equal( + plan, ot.sinkhorn(a, b, M, reg, plan_tol=target, stopThr=1e-7) + ) + scaled, scaled_info = ot.sinkhorn( + a, b, M * 64, reg * 64, plan_tol=target, stopThr=1e-7, log=True + ) + np.testing.assert_array_equal(plan, scaled) + assert info["niter"] == scaled_info["niter"] + + +def test_plan_tol_default_and_non_numpy64_unchanged(): + a, b, M, reg, _ = planted(12, 14) + for dtype in (np.float32, np.float64): + args = a.astype(dtype), b.astype(dtype), M.astype(dtype), reg + baseline, history = ot.sinkhorn(*args, log=True) + same, same_history = ot.sinkhorn(*args, log=True, plan_tol=None) + np.testing.assert_array_equal(baseline, same) + assert history.keys() == same_history.keys() + assert history["niter"] == same_history["niter"] + args = a, np.stack([b, b], axis=1), M, reg + np.testing.assert_array_equal(ot.sinkhorn(*args), ot.sinkhorn(*args, plan_tol=None)) + + +@pytest.mark.parametrize("portable_comparison", [False, True]) +def test_plan_tol_mutated_cost_never_reuses_a_stale_kernel( + monkeypatch, portable_comparison +): + from ot.bregman import _sinkhorn_plan + + _sinkhorn_plan._cache.entry = None + if portable_comparison: + monkeypatch.setattr(_sinkhorn_plan, "_memcmp", None) + a, b, M, reg, _ = planted(20, 45) + old = ot.sinkhorn(a, b, M, reg, plan_tol=1e-9) + again = ot.sinkhorn(a, b, M, reg, plan_tol=1e-9) + np.testing.assert_array_equal(old, again) + M[1, 1] += 0.5 # deliberately outside the three cheap cache sampling points + fresh = ot.sinkhorn(a, b, M, reg, plan_tol=1e-9) + exact = ot.sinkhorn(a, b, M, reg, method="sinkhorn_log", stopThr=1e-14) + assert not np.array_equal(old, fresh) + assert 0.5 * np.abs(fresh - exact).sum() < 1e-9 + np.testing.assert_array_equal( + again, old + ) # returning a plan never aliases the cached kernel + + +def test_plan_tol_rejects_unsupported_instead_of_implying_success(): + a, b, M, reg, _ = planted(7, 9) + with pytest.raises(ValueError, match="only supported"): + ot.sinkhorn(a, b, M, reg, plan_tol=1e-6, method="sinkhorn_log") + with pytest.raises(ValueError, match="returns the transport matrix"): + ot.sinkhorn2(a, b, M, reg, plan_tol=1e-6) + with pytest.raises(ValueError, match="NumPy float64"): + ot.sinkhorn(a.astype("f"), b.astype("f"), M.astype("f"), reg, plan_tol=1e-6) + with pytest.raises(ValueError, match="finite tolerances"): + ot.sinkhorn(a, b, M, reg, plan_tol=np.nan) + with pytest.raises(ArithmeticError, match="numItermax"): + ot.sinkhorn(a, b, M, reg, plan_tol=1e-12, numItermax=1) + with pytest.raises(ValueError, match="one histogram pair"): + ot.sinkhorn(a, np.stack([b, b], axis=1), M, reg, plan_tol=1e-6) + a[1], a[0] = a[1] + a[0], 0.0 + with pytest.raises(ValueError, match="strictly positive probability marginals"): + ot.sinkhorn(a, b, M, reg, plan_tol=1e-6) + with np.errstate(all="ignore"): + np.testing.assert_array_equal( + ot.sinkhorn(a, b, M, reg), ot.sinkhorn(a, b, M, reg, plan_tol=None) + ) + a, b, M, reg, _ = planted(7, 9) + invalid = M.copy() + invalid[1, 1] = np.nan + with pytest.raises(ValueError, match="positive Gibbs kernel"): + ot.sinkhorn(a, b, invalid, reg, plan_tol=1e-6) + M[1, 1] = 1000.0 + with pytest.raises(ValueError, match="positive Gibbs kernel"): + ot.sinkhorn(a, b, M, reg, plan_tol=1e-6) + np.testing.assert_array_equal( + ot.sinkhorn(a, b, M, reg), ot.sinkhorn(a, b, M, reg, plan_tol=None) + ) + + +def test_plan_tol_warmstart_uses_stock_log_scaling_convention(): + a, b, M, reg, P = planted(25, 100) + _, stock = ot.sinkhorn(a, b, M, reg, stopThr=1e-12, log=True) + warm = np.log(stock["u"]), np.log(stock["v"]) + plan, info = ot.sinkhorn(a, b, M, reg, plan_tol=1e-9, warmstart=warm, log=True) + assert 0.5 * np.abs(plan - P).sum() < 1e-9 + assert info["niter"] == 0 + assert info["plan_tv_estimate"] < 1e-9 + + +def test_plan_tol_does_not_take_ordinary_early_exit(): + a = np.array([2.0, 1.0]) / 3 + b = np.array([5.0, 4.0]) / 9 + M = np.array([[0.0, np.log(2)], [np.log(2), 0.0]]) + exact = np.array([[4.0, 2.0], [1.0, 2.0]]) / 9 + ordinary, ordinary_log = ot.sinkhorn(a, b, M, 1.0, stopThr=0.1, log=True) + assert ordinary_log["niter"] == 0 + assert 0.5 * np.abs(ordinary - exact).sum() == pytest.approx(40 / 819) + with pytest.raises(ArithmeticError, match="numItermax"): + ot.sinkhorn(a, b, M, 1.0, stopThr=0.1, plan_tol=0.01, numItermax=1) + plan, info = ot.sinkhorn(a, b, M, 1.0, stopThr=0.1, plan_tol=0.01, log=True) + assert info["niter"] > 0 + assert 0.5 * np.abs(plan - exact).sum() < 0.01 + assert info["plan_tv_estimate"] == pytest.approx(0.5 * np.abs(plan - exact).sum()) + with pytest.raises(ValueError, match="only supported"): + ot.sinkhorn(a, b, M, 1.0, method="greenkhorn", plan_tol=0.01) + + +def test_ordinary_public_call_uses_marginal_path_without_imposing_plan_tol(monkeypatch): + from ot.bregman import _sinkhorn + from ot.bregman import _sinkhorn_plan + + def unexpected(*args, **kwargs): + pytest.fail("a supported ordinary solve dispatched to another solver") + + monkeypatch.setattr(_sinkhorn_plan, "_solve_full_plan", unexpected) + monkeypatch.setattr(_sinkhorn, "_sinkhorn_knopp_standard", unexpected) + a = np.array([2.0, 1.0]) / 3 + b = np.array([5.0, 4.0]) / 9 + M = np.array([[0.0, np.log(2)], [np.log(2), 0.0]]) + p = ot.sinkhorn(a, b, M, 1.0, stopThr=0.1) + exact = np.array([[4.0, 2.0], [1.0, 2.0]]) / 9 + assert np.linalg.norm(p.sum(0) - b) < 0.1 + assert np.linalg.norm(p.sum(1) - a) < 0.1 + # An ordinary call can finish even though its TV exceeds stopThr / 4. + assert np.abs(p - exact).sum() / 2 == pytest.approx(40 / 819) + + +@pytest.mark.parametrize("bad", ["zero_col", "tiny", "positive_inf", "negative", "nan"]) +def test_ordinary_kernel_fallback_matches_standard_with_one_exponential( + monkeypatch, bad +): + import warnings + from ot.bregman import _sinkhorn, _sinkhorn_plan + + a, b, M, reg, _ = planted(22, 31) + if bad == "zero_col": + M[:, 0] = 800 * reg + else: + M[0, 0] = { + "tiny": 675 * reg, + "negative": -800 * reg, + "nan": np.nan, + "positive_inf": np.inf, + }[bad] + with warnings.catch_warnings(record=True) as standard: + warnings.simplefilter("always") + expected = _sinkhorn._sinkhorn_knopp_standard(a, b, M, reg, numItermax=25) + count = 0 + original = np.exp + + def counted(x, *args, **kwargs): + nonlocal count + if getattr(x, "shape", None) == M.shape: + count += 1 + return original(x, *args, **kwargs) + + monkeypatch.setattr(np, "exp", counted) + # NumPyBackend.exp delegates to np.exp on this path. + _sinkhorn_plan._cache.entry = None + for _ in range(3): + before = count + with warnings.catch_warnings(record=True) as actual: + warnings.simplefilter("always") + got = ot.sinkhorn(a, b, M, reg, numItermax=25) + np.testing.assert_array_equal(got, expected) + assert [(r.category, str(r.message)) for r in actual] == [ + (r.category, str(r.message)) for r in standard + ] + assert count - before == 1 + + +def test_warm_strict_build_skips_uniform_product_and_cold_cache_reuses_it(monkeypatch): + from ot.bregman import _sinkhorn_plan as sp + + a, b, M, reg, _ = planted(30, 77) + sp._cache.entry = None + fresh = [] + original = sp._Kernel.cold_columns + + def traced(self, u): + fresh.append(self.uniform_columns is None) + return original(self, u) + + monkeypatch.setattr(sp._Kernel, "cold_columns", traced) + kwargs = {"warmstart": (np.zeros(len(a)), np.zeros(len(b))), "plan_tol": 1e-7} + for _ in range(2): + ot.sinkhorn(a, b, M, reg, **kwargs) + assert fresh == [] + for _ in range(2): + ot.sinkhorn(a, b, M, reg) + assert fresh == [True, False] + + +def test_ordinary_unsupported_forms_and_cost_only_bypass_fast_solver(monkeypatch): + from ot.bregman import _sinkhorn, _sinkhorn_plan + + a, b, M, reg, _ = planted(16, 21) + + def unexpected(*args, **kwargs): + pytest.fail("unsupported call touched the fast-path kernel cache") + + monkeypatch.setattr(_sinkhorn_plan, "_auto_kernel", unexpected) + cases = [ + ((a.astype("f"), b.astype("f"), M.astype("f"), reg), {}), + ((a, b, np.asfortranarray(M), reg), {}), + ((a, np.column_stack([b, b]), M, reg), {}), + ((a, b, M, reg), {"log": True}), + ((a, b, M, reg), {"warmstart": (np.log(a).astype("f"), np.log(b))}), + ((a, b, M, reg), {"numItermax": 3, "warn": False}), + ] + for args, kwargs in cases: + got = ot.sinkhorn(*args, **kwargs) + ref = _sinkhorn._sinkhorn_knopp_standard(*args, **kwargs) + if kwargs.get("log"): + assert got[1]["niter"] == ref[1]["niter"] + got, ref = got[0], ref[0] + np.testing.assert_array_equal(got, ref) + assert ot.sinkhorn2(a, b, M, reg) == np.sum( + _sinkhorn._sinkhorn_knopp_standard(a, b, M, reg) * M + ) + + +def test_default_mutated_cost_and_exhaustion_warning(): + import warnings + + from ot.bregman import _sinkhorn_plan as sp + from ot.bregman._sinkhorn import _sinkhorn_knopp_standard + + a, b, M, reg, _ = planted(17, 61) + sp._cache.entry = None + one = ot.sinkhorn(a, b, M, reg) + two = ot.sinkhorn(a, b, M.copy(), reg) + M[2, 3] += 0.5 + changed = ot.sinkhorn(a, b, M, reg) + np.testing.assert_array_equal(one, two) + assert not np.array_equal(changed, two) + sp._cache.entry = None + np.testing.assert_array_equal(changed, ot.sinkhorn(a, b, M, reg)) + # A finite marginal solve can exhaust its budget. Match POT's last iterate + # and warning policy, while the strict mode reports an unmet request. + x = np.linspace(0, 1, len(a)) + y = np.linspace(0, 1, len(b)) + M = np.ascontiguousarray((x[:, None] - y) ** 2) + args = a, b, M, 0.005 + for warn in [True, False]: + kw = dict(numItermax=11, stopThr=1e-12, warn=warn) + with warnings.catch_warnings(record=True) as standard: + warnings.simplefilter("always") + expected = _sinkhorn_knopp_standard(*args, **kw) + with warnings.catch_warnings(record=True) as actual: + warnings.simplefilter("always") + result = ot.sinkhorn(*args, **kw) + assert len(standard) == len(actual) == int(warn) + if warn: + assert str(actual[0].message) == str(standard[0].message) + np.testing.assert_allclose(result, expected, rtol=3e-13, atol=1e-16) + with pytest.raises(ArithmeticError, match="numItermax"): + ot.sinkhorn(*args, **kw, plan_tol=1e-12) + + +@pytest.mark.parametrize("step", [2, 3, 4]) +def test_ordinary_warm_checks_return_the_first_eligible_iterate(step): + a, b, M, reg, _ = planted(19, 37) + seed = (np.log(a), np.log(b)) + K = np.exp(-M / reg) + u = np.exp(seed[0]) + errors = [] + for _ in range(step): + v = b / (K.T @ u) + u = a / (K @ v) + errors.append(np.linalg.norm(v * (K.T @ u) - b)) + tol = float(np.sqrt(errors[-2] * errors[-1])) + assert errors[-1] < tol < min(errors[:-1]) + kwargs = dict(warmstart=seed, stopThr=tol) + P, info = ot.sinkhorn(a, b, M, reg, log=True, **kwargs) + assert set(info) == {"err", "niter", "u", "v"} + assert info["niter"] + 1 == step + np.testing.assert_array_equal(P, ot.sinkhorn(a, b, M, reg, **kwargs)) + np.testing.assert_allclose(P, info["u"][:, None] * K * info["v"], rtol=1e-14) + assert len(info["err"]) == 2 + assert info["err"][-1] == pytest.approx(np.linalg.norm(P.sum(0) - b)) + assert max(np.linalg.norm(P.sum(0) - b), np.linalg.norm(P.sum(1) - a)) < tol + + +@pytest.mark.parametrize( + "kind", ["budget", "zero_kernel_column", "extreme_seed", "zero_mass"] +) +def test_ordinary_warm_warning_and_rollback(kind): + import warnings + from ot.bregman._sinkhorn import _sinkhorn_knopp_standard + + a, b, M, reg, _ = planted(24, 34) + M = np.ascontiguousarray( + (np.linspace(0.0, 1.0, len(a))[:, None] - np.linspace(0.0, 1.0, len(b))) ** 2 + ) + reg = 0.005 + seed = (np.zeros_like(a), np.zeros_like(b)) + if kind == "extreme_seed": + seed[1][0] = 800.0 + elif kind == "zero_kernel_column": + M[:, 0] = 1000.0 + elif kind == "zero_mass": + a[1] += a[0] + a[0] = 0.0 + for warn in (True, False): + kw = dict(warmstart=seed, log=True, numItermax=12, stopThr=1e-13, warn=warn) + with warnings.catch_warnings(record=True) as old: + warnings.simplefilter("always") + ref, prior = _sinkhorn_knopp_standard(a, b, M, reg, **kw) + with warnings.catch_warnings(record=True) as new: + warnings.simplefilter("always") + result, history = ot.sinkhorn(a, b, M, reg, **kw) + assert [(w.category, str(w.message)) for w in old] == [ + (w.category, str(w.message)) for w in new + ] + assert history["niter"] == prior["niter"] + np.testing.assert_allclose(history["err"], prior["err"], rtol=5e-13, atol=1e-16) + np.testing.assert_allclose(result, ref, rtol=5e-13, atol=1e-16)