diff --git a/RELEASES.md b/RELEASES.md index 78f17f27a..18e8a1c17 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -32,6 +32,7 @@ - Fix duplicate function and class descriptions in generated module API pages while preserving top-level aliases and example backreferences (Issue #527) - Fix `ot.solve_sample` with `reg` and `lazy=True` returning `value=None`, which also made the debiased lazy Sinkhorn divergence (`debias=True` or `"split"`) fail with a `TypeError` (PR #861) - Fix internal arrays created on the torch default device instead of the input device in `ot.partial.partial_wasserstein`, `ot.wasserstein_circle` (and `ot.sliced_wasserstein_sphere`), the high-dimensional Bures-Wasserstein functions in `ot.gaussian`, `ot.gmm`, `ot.lowrank_sinkhorn` with `init="deterministic"`, the semi-relaxed (F)GW barycenters and `ot.utils.projection_sparse_simplex`, which made them fail on GPU inputs. Add a `meta_default_device` test fixture to catch such allocations on CPU (PR #883, Issue #852) +- `nx.sqrtm` now clamps negative eigenvalues to zero in the NumPy, JAX, CuPy and TensorFlow backends, as the torch backend already did, so `ot.gaussian.bures_distance` and related functions no longer return NaN or raise `LinAlgError` on rank-deficient covariances. `ot.gaussian.bures_wasserstein_mapping` now warns when the returned map does not satisfy `A Cs A = Ct`, as happens for a singular source covariance (PR #905, Issue #889) - Allow `NumpyBackend.seed` to adopt an existing `np.random.RandomState` instance and remove NumPy-specific random sampling paths in sliced utilities (PR #849, Issue #848) - Remove a leftover debug `print` from `ot.utils.projection_sparse_simplex` with `axis=1`, and make the `ot.datasets.make_gauss_hd` docstring a raw string so importing `ot` no longer emits a `SyntaxWarning` (PR #860) - Fix the value reported by the entropic unbalanced OT solvers (`ot.unbalanced.sinkhorn_unbalanced`, `sinkhorn_unbalanced2`, `sinkhorn_knopp_unbalanced`, `sinkhorn_stabilized_unbalanced` and `sinkhorn_unbalanced_translation_invariant`, also exposed as `ot.solve(..., reg=..., unbalanced=...).value`): every penalization is now evaluated with the generalized KL divergence, and with `reg_type="entropy"` the constant `dim_a * dim_b` is removed so that the reported value matches the documented negative entropy regularizer. The transport plans are unchanged. `reg_type` is now handled case insensitively by all the methods and an unknown value raises a `ValueError` instead of silently falling back to `"kl"`. The docstrings now state the generalized KL convention, the regularizer `Omega_reg_type(gamma, c)` with its two cases, the keys of the `log` dictionary and the multi-histogram behaviour (PR #874) diff --git a/ot/backend.py b/ot/backend.py index b74377041..2b6aca42c 100644 --- a/ot/backend.py +++ b/ot/backend.py @@ -1078,6 +1078,11 @@ def sqrtm(self, a): Computes the matrix square root. Requires input symmetric positive semi-definite. + Eigenvalues are clamped to zero before taking the square root, since + those of a positive semi-definite matrix can come out slightly negative + from rounding. For a matrix that is not positive semi-definite, this + returns the square root of its positive part. + This function follows the api from :any:`scipy.linalg.sqrtm`, allowing batches. @@ -1577,7 +1582,9 @@ def pinv(self, a, hermitian=False): def sqrtm(self, a): L, V = np.linalg.eigh(a) - L = np.sqrt(L) + # eigenvalues of a PSD matrix can come out slightly negative from + # rounding, which would give NaN; clamp as the torch backend does + L = np.sqrt(np.maximum(L, 0)) # Q[...] = V[...] @ diag(L[...]) Q = np.einsum("...jk,...k->...jk", V, L) # R[...] = Q[...] @ V[...].T @@ -2040,7 +2047,9 @@ def pinv(self, a, hermitian=False): def sqrtm(self, a): L, V = jnp.linalg.eigh(a) - L = jnp.sqrt(L) + # eigenvalues of a PSD matrix can come out slightly negative from + # rounding, which would give NaN; clamp as the torch backend does + L = jnp.sqrt(jnp.maximum(L, 0)) # Q[...] = V[...] @ diag(L[...]) Q = jnp.einsum("...jk,...k->...jk", V, L) # R[...] = Q[...] @ V[...].T @@ -3126,7 +3135,9 @@ def pinv(self, a, hermitian=False): def sqrtm(self, a): L, V = cp.linalg.eigh(a) - L = cp.sqrt(L) + # eigenvalues of a PSD matrix can come out slightly negative from + # rounding, which would give NaN; clamp as the torch backend does + L = cp.sqrt(cp.maximum(L, 0)) # Q[...] = V[...] @ diag(L[...]) Q = cp.einsum("...jk,...k->...jk", V, L) # R[...] = Q[...] @ V[...].T @@ -3608,7 +3619,9 @@ def pinv(self, a, hermitian=False): def sqrtm(self, a): L, V = tf.linalg.eigh(a) - L = tf.sqrt(L) + # eigenvalues of a PSD matrix can come out slightly negative from + # rounding, which would give NaN; clamp as the torch backend does + L = tf.sqrt(tf.maximum(L, 0)) # Q[...] = V[...] @ diag(L[...]) Q = tf.einsum("...jk,...k->...jk", V, L) # R[...] = Q[...] @ V[...].T diff --git a/ot/gaussian.py b/ot/gaussian.py index 29c7c9c7f..7461dbf5c 100644 --- a/ot/gaussian.py +++ b/ot/gaussian.py @@ -15,6 +15,57 @@ from .utils import dots, is_all_finite, list_to_array, exp_bures +def _warn_if_map_is_inaccurate(A, Cs, Ct, nx, stacklevel): + r"""Warn when :math:`\mathbf{A}` does not push :math:`\mathbf{C}_s` onto :math:`\mathbf{C}_t`. + + The Bures-Wasserstein map is the symmetric positive definite matrix with + :math:`\mathbf{A}\mathbf{C}_s\mathbf{A} = \mathbf{C}_t`, which is unique and + given by the closed form only when :math:`\mathbf{C}_s` is non-singular. The + relative residual of that identity therefore measures directly how far the + returned map is from correct. It is compared with :math:`\varepsilon^{1/4}` + of the dtype. A matrix square root near a zero eigenvalue loses up to half + the digits, since :math:`|\sqrt{a} - \sqrt{b}| \leq \sqrt{|a - b|}`, and + correct maps between rank-deficient covariances do reach residuals near + :math:`\sqrt{\varepsilon}`, so the tolerance sits well above that; a + singular source gives residuals many orders of magnitude larger. + + Parameters + ---------- + A : array-like, shape (d, d) + Linear part of the computed map. + Cs : array-like, shape (d, d) + Source covariance. + Ct : array-like, shape (d, d) + Target covariance. + nx : backend + Backend to use for the computation. + stacklevel : int + Passed to :py:func:`warnings.warn` so the warning points at user code. + """ + try: + tiny_dtype = nx.to_numpy(nx.zeros((1,), type_as=Cs)).dtype + tol = np.finfo(tiny_dtype).eps ** 0.25 + norm_ct = float(nx.to_numpy(nx.norm(Ct))) + residual = float(nx.to_numpy(nx.norm(dots(A, Cs, A) - Ct))) + except (TypeError, ValueError): + # traced values, as under jax.jit or jax.grad, cannot be read back, + # and integer dtypes have no machine epsilon: skip the check + return + if norm_ct == 0: + return + residual /= norm_ct + if not residual <= tol: # also catches NaN + warnings.warn( + "The Bures-Wasserstein map does not transport the source covariance " + f"onto the target: relative residual of A Cs A = Ct is {residual:.1e}, " + f"above the tolerance {tol:.1e}. The source covariance is singular or " + "nearly so, and the map has lost precision accordingly. Regularize it, " + "for instance with the `reg` parameter of " + "ot.gaussian.empirical_bures_wasserstein_mapping.", + stacklevel=stacklevel, + ) + + def bures_wasserstein_mapping(ms, mt, Cs, Ct, log=False): r"""Return OT linear operator between samples. @@ -72,6 +123,28 @@ def bures_wasserstein_mapping(ms, mt, Cs, Ct, log=False): .. [2] Peyré, G., & Cuturi, M. (2017). "Computational Optimal Transport", 2018. """ + return _bures_wasserstein_mapping(ms, mt, Cs, Ct, log=log, stacklevel=4) + + +def _bures_wasserstein_mapping(ms, mt, Cs, Ct, log=False, stacklevel=4): + r"""Compute the Bures-Wasserstein map, as :py:func:`bures_wasserstein_mapping`. + + Split out so that callers inside POT can set the stack level of the + accuracy warning and have it point at user code. + + Parameters + ---------- + ms, mt, Cs, Ct, log + As for :py:func:`bures_wasserstein_mapping`. + stacklevel : int, optional + Stack level of the warning raised when the map does not transport + :math:`\mathbf{C}_s` onto :math:`\mathbf{C}_t`. 4 points at the caller of + a public function that calls this one directly. + + Returns + ------- + As for :py:func:`bures_wasserstein_mapping`. + """ ms, mt, Cs, Ct = list_to_array(ms, mt, Cs, Ct) nx = get_backend(ms, mt, Cs, Ct) @@ -84,6 +157,8 @@ def bures_wasserstein_mapping(ms, mt, Cs, Ct, log=False): b = mt - nx.dot(ms, A) + _warn_if_map_is_inaccurate(A, Cs, Ct, nx, stacklevel) + if log: log = {} log["Cs12"] = Cs12 @@ -285,9 +360,9 @@ def empirical_bures_wasserstein_mapping( Ct = nx.dot((xt * wt).T, xt) / nx.sum(wt) + reg * nx.eye(d, type_as=xt) if log: - A, b, log = bures_wasserstein_mapping(mxs, mxt, Cs, Ct, log=log) + A, b, log = _bures_wasserstein_mapping(mxs, mxt, Cs, Ct, log=log) else: - A, b = bures_wasserstein_mapping(mxs, mxt, Cs, Ct) + A, b = _bures_wasserstein_mapping(mxs, mxt, Cs, Ct) if is_input_finite and not is_all_finite(A, b): warnings.warn( diff --git a/test/test_backend.py b/test/test_backend.py index 0b784aa62..93a5817d4 100644 --- a/test/test_backend.py +++ b/test/test_backend.py @@ -934,6 +934,18 @@ def f(x): assert nx.allclose(dl_db, b) +def test_sqrtm_rank_deficient(nx): + """sqrtm must accept PSD matrices whose zero eigenvalues round negative.""" + rng = np.random.RandomState(0) + d = 10 + for rank in (9, 5, 2): + F = rng.randn(d, rank) + C = F @ F.T / rank + S = nx.to_numpy(nx.sqrtm(nx.from_numpy(C))) + assert np.all(np.isfinite(S)) + np.testing.assert_allclose(S @ S, C, atol=1e-6) + + def test_sqrtm_backward_torch(): if not torch: pytest.skip("Torch not available") diff --git a/test/test_gaussian.py b/test/test_gaussian.py index 3199e2403..d602431e6 100644 --- a/test/test_gaussian.py +++ b/test/test_gaussian.py @@ -5,6 +5,8 @@ # # License: MIT License +import warnings + import numpy as np import pytest @@ -157,12 +159,88 @@ def test_empirical_bures_wasserstein_mapping_hd(nx, bias): def test_empirical_bures_wasserstein_mapping_numerical_error_warning(): + # 766 source samples in 800 dimensions: with reg=0 the source covariance is + # singular and no Bures-Wasserstein map exists + rng = np.random.RandomState(42) + Xs = rng.rand(766, 800) * 5 + Xt = rng.rand(295, 800) * 2 + with pytest.warns(UserWarning, match="does not transport"): + ot.gaussian.empirical_bures_wasserstein_mapping(Xs, Xt, reg=0) + + +def test_empirical_bures_wasserstein_mapping_ill_conditioned_is_accurate(): + # same data with reg=1e-8: the source covariance is ill-conditioned but + # invertible, so the map exists; it used to come back NaN because rounding + # pushed eigenvalues of a PSD matrix below zero before the square root rng = np.random.RandomState(42) Xs = rng.rand(766, 800) * 5 Xt = rng.rand(295, 800) * 2 - with pytest.warns(): - A, b = ot.gaussian.empirical_bures_wasserstein_mapping(Xs, Xt, reg=1e-8) - assert not is_all_finite(A, b) + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + A, b, log = ot.gaussian.empirical_bures_wasserstein_mapping( + Xs, Xt, reg=1e-8, log=True + ) + assert is_all_finite(A, b) + Cs, Ct = log["Cs"], log["Ct"] + np.testing.assert_allclose(dots(A, Cs, A), Ct, rtol=1e-6, atol=1e-6) + + +def test_bures_wasserstein_mapping_warns_on_singular_source(): + rng = np.random.RandomState(0) + Y = rng.randn(200, 10) + Ct = np.cov(Y.T) + + Z = rng.randn(5, 10) # 5 samples in 10 dimensions + with pytest.warns(UserWarning, match="does not transport"): + ot.gaussian.bures_wasserstein_mapping( + Z.mean(0), Y.mean(0), np.cov(Z.T, bias=True), Ct + ) + + X = rng.randn(200, 10) + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + ot.gaussian.bures_wasserstein_mapping(X.mean(0), Y.mean(0), np.cov(X.T), Ct) + + +@pytest.mark.skipif(not ot.backend.jax, reason="jax not available") +def test_bures_wasserstein_mapping_jax_transforms(): + # the accuracy check reads values back to NumPy, which traced values do not + # allow; jit and grad through the mapping must still work + jax = ot.backend.jax + rng = np.random.RandomState(0) + X, Y = rng.randn(50, 5), rng.randn(60, 5) + nx = ot.backend.JaxBackend() + ms, mt, Cs, Ct = nx.from_numpy(X.mean(0), Y.mean(0), np.cov(X.T), np.cov(Y.T)) + + def f(Cs, Ct): + return ot.gaussian.bures_wasserstein_mapping(ms, mt, Cs, Ct)[0] + + np.testing.assert_allclose(jax.jit(f)(Cs, Ct), f(Cs, Ct), rtol=1e-8) + for argnums in (0, 1): + g = jax.grad(lambda Cs, Ct: f(Cs, Ct).sum(), argnums=argnums)(Cs, Ct) + assert np.all(np.isfinite(g)) + + +def test_bures_distance_rank_deficient(nx): + rng = np.random.RandomState(1) + d = 10 + for rank in (9, 5, 2): + F = rng.randn(d, rank) + C = nx.from_numpy(F @ F.T / rank) + # B(C, C) = 0 for any PSD C; this used to give NaN or LinAlgError + np.testing.assert_allclose( + nx.to_numpy(ot.gaussian.bures_distance(C, C)), 0, atol=1e-6 + ) + + # commuting case with a shared null space: B^2 = sum (sqrt(a) - sqrt(b))^2 + a = rng.rand(d) + 0.1 + b = rng.rand(d) + 0.1 + a[:4] = b[:4] = 0.0 + expected = np.sqrt(np.sum((np.sqrt(a) - np.sqrt(b)) ** 2)) + Cs, Ct = nx.from_numpy(np.diag(a), np.diag(b)) + np.testing.assert_allclose( + nx.to_numpy(ot.gaussian.bures_distance(Cs, Ct)), expected, rtol=1e-6 + ) def test_bures_wasserstein_distance(nx):