Skip to content
Open
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 @@ -22,6 +22,7 @@

#### Closed issues

- Fix severe cancellation in `ot.batch.dist_batch` when samples share a large common coordinate offset: squared distances could be negative and Euclidean distances could be `NaN`, producing incorrect OT costs and transport plans. Both inputs are now shifted by a common per-batch reference point before the Gram expansion, with a non-negativity guard for residual round-off
- Fix dead links in the README (three example gallery pages and the reference [39]), the user guide and the contributing guide (PR #928)
- Fix ordinary JAX gradients for dense `ot.emd2` and preserve the magnitude and higher-order dependence of gradients supplied to `JaxBackend.set_gradients`, including the envelope gradients in `ot.solve` (Issue #625)
- Fix `ot.semidiscrete_wasserstein2_unif_circle` pairing sorted sample locations with unsorted weights, which broke permutation and rotation invariance for nonuniform weights (Issue #921)
Expand Down
19 changes: 19 additions & 0 deletions ot/batch/_linear.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,29 @@ def dist_euclidean_batch(X, Y, squared=True, nx=None):

if nx is None:
nx = get_backend(X, Y)

# Translate both point sets by a common per-batch reference point before
# forming the Gram matrix. A large common offset otherwise cancels against
# ||x||^2 + ||y||^2 and can destroy the (much smaller) squared distance.
# This translation leaves Euclidean distances unchanged mathematically,
# and remains differentiable for all backends.
if X.shape[1] > 0:
ref = X[:, 0:1, :]
elif Y.shape[1] > 0:
ref = Y[:, 0:1, :]
else:
ref = None
if ref is not None:
X = X - ref
Y = Y - ref

XX = nx.sum(X**2, axis=-1, keepdims=True)
YY = nx.sum(Y**2, axis=-1, keepdims=True)
YY = nx.transpose(YY, axes=(0, 2, 1))
M = XX + YY - 2 * nx.einsum("bid,bjd->bij", X, Y)
# Round-off can still make the diagonal slightly negative; squared
# distances are non-negative by definition.
M = nx.maximum(M, 0)
if not squared:
M = nx.sqrt(M)
return M
Expand Down
100 changes: 100 additions & 0 deletions test/batch/test_solve_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,103 @@ def test_solve_batch_device(method):
M = dist_batch(Xd, Xd)
res = solve_batch(M, reg=0.1, max_iter=10, tol=1e-5, method=method)
assert res.plan.device == Xd.device


def test_dist_batch_large_common_offset_counterexample():
"""Gram cancellation returned -8 where the exact squared distance is 6."""
X = np.array(
[
[
[100000001.0, 100000004.0, 100000001.0],
[100000003.0, 100000003.0, 100000002.0],
]
]
)
M = dist_batch(X, X, metric="sqeuclidean")
np.testing.assert_allclose(M, [[[0.0, 6.0], [6.0, 0.0]]], rtol=0, atol=0)
M1 = dist_batch(X, X, metric="euclidean")
np.testing.assert_allclose(
M1, [[[0.0, np.sqrt(6.0)], [np.sqrt(6.0), 0.0]]], rtol=0, atol=1e-12
)


@pytest.mark.parametrize("dtype,offset", [(np.float32, 1e4), (np.float64, 1e8)])
def test_dist_batch_large_offset_properties(dtype, offset):
"""Non-negativity, exact self-distance and agreement with coordinate differences."""
rng = np.random.RandomState(0)
X = (offset + rng.randn(1, 6, 13)).astype(dtype)
M = dist_batch(X, X, metric="sqeuclidean")
assert np.all(M >= 0)
atol = 1e-3 if dtype == np.float32 else 1e-12
np.testing.assert_allclose(np.diagonal(M, axis1=1, axis2=2), 0.0, rtol=0, atol=atol)
D = X[:, :, None, :].astype(np.float64) - X[:, None, :, :].astype(np.float64)
expected = np.sum(D**2, axis=-1)
rtol = 1e-3 if dtype == np.float32 else 1e-10
atol = 1e-2 if dtype == np.float32 else 1e-12
np.testing.assert_allclose(M, expected, rtol=rtol, atol=atol)
M1 = dist_batch(X, X, metric="euclidean")
assert not np.any(np.isnan(M1))


def test_dist_batch_translation_invariance_exact():
"""Distances of integer-valued points are unchanged by an exact large shift."""
rng = np.random.RandomState(42)
X = rng.randint(-4, 5, size=(1, 5, 4)).astype(np.float64)
Y = rng.randint(-4, 5, size=(1, 5, 4)).astype(np.float64)
c = 2.0**27 # X + c remains exactly representable
np.testing.assert_allclose(
dist_batch(X + c, Y + c), dist_batch(X, Y), rtol=0, atol=0
)


@pytest.mark.skipif(not torch, reason="torch not installed")
def test_dist_batch_torch_large_offset_gradient():
"""The shifted implementation keeps correct, translation-consistent gradients."""
rng = np.random.RandomState(11)
base = rng.randn(1, 4, 5)
c = 1e8

def value_and_grad(offset):
X = torch.tensor(base + offset, dtype=torch.float64, requires_grad=True)
M = dist_batch(X, X, metric="sqeuclidean")
M.sum().backward()
return M.detach(), X.grad.clone()

M_c, g_c = value_and_grad(c)
_, g_0 = value_and_grad(0.0)
D = torch.tensor(base + c, dtype=torch.float64)
expected = ((D[:, :, None, :] - D[:, None, :, :]) ** 2).sum(-1)
torch.testing.assert_close(M_c, expected, rtol=1e-10, atol=1e-10)
assert torch.isfinite(g_c).all()
torch.testing.assert_close(g_c, g_0, rtol=1e-8, atol=1e-7)


def test_solve_batch_large_common_offset():
"""A corrupted cost matrix produces a negative OT value; the fix must not."""
rng = np.random.RandomState(7)
X = 1e8 + rng.randn(2, 5, 13)
Y = 1e8 + rng.randn(2, 5, 13)
M = dist_batch(X, Y, metric="sqeuclidean")
D = X[:, :, None, :] - Y[:, None, :, :]
M_ref = np.sum(D**2, axis=-1)
kw = {
"reg": 0.1,
"method": "proximal",
"max_iter": 1000,
"tol": 1e-9,
"grad": "detach",
}
res = solve_batch(M, **kw)
res_ref = solve_batch(M_ref, **kw)
assert np.all(np.asarray(res.value_linear) > 0)
np.testing.assert_allclose(
res.value_linear, res_ref.value_linear, rtol=1e-6, atol=1e-8
)


def test_dist_batch_empty_source_samples():
"""Zero-sample batches must keep working."""
X = np.zeros((2, 0, 3))
Y = np.zeros((2, 4, 3))
assert dist_batch(X, Y).shape == (2, 0, 4)
assert dist_batch(X, X).shape == (2, 0, 0)
Loading