Skip to content

[MRG] Fix catastrophic cancellation in batched Euclidean distance - #932

Open
xihaian251 wants to merge 1 commit into
PythonOT:masterfrom
xihaian251:fix/batched-euclidean-cancellation
Open

xihaian251 wants to merge 1 commit into
PythonOT:masterfrom
xihaian251:fix/batched-euclidean-cancellation

Conversation

@xihaian251

Copy link
Copy Markdown
Contributor

ot.batch.dist_batch computes squared Euclidean costs with the Gram expansion ‖x‖² + ‖y‖² − 2⟨x,y⟩ and no non-negativity guard. With a large common coordinate offset, cancellation makes the result inaccurate: negative squared distances and NaN Euclidean distances are produced, and OT costs/plans can be corrupted.

import numpy as np
from ot.batch import dist_batch

X = np.array([[[100000001., 100000004., 100000001.],
               [100000003., 100000003., 100000002.]]])

dist_batch(X, X, metric="sqeuclidean")
# master: [[[ 0., -8.], [-8.,  0.]]]   exact: [[[0., 6.], [6., 0.]]]
dist_batch(X, X, metric="euclidean")  # master: [[[0., nan], [nan, 0.]]]

For any reference c, ‖(x−c)−(y−c)‖² = ‖x−y‖². The fix shifts both inputs by a common per-batch reference point (a static slice X[:, 0:1, :], falling back to Y for empty source batches) before the Gram expansion, then clamps residual round-off at zero. Subtracting close values avoids the O(u·d·c²) absolute error of the unshifted expansion. Clipping alone is insufficient: it returns 0 instead of 6 on the reproduction above, leaves a self-distance of 256 on a float32/1e4 batch, and still produces a negative OT value in solve_batch.

Downstream, a two-problem 5×5 OT batch at offset 1e8 gives master value_linear = [4.2e−13, −12.8] and plans differing from the Oracle by up to 0.2; with the fix it gives [3.985493198744215, 3.347919393456945] (Oracle [3.985493198744212, 3.347919393456947]) and identical plans.

Six regression cases fail on master and pass with the patch: the fixed counterexample, float32 and float64 large-offset properties, exact translation invariance for representable shifts, the Torch large-offset gradient, and an end-to-end solve_batch value.

Benchmarks with one thread, 5 warmups and 15 repetitions show a typical 6–20% overhead on medium/large CPU inputs (NumPy 70.2 → 79.3 ms at (32,256,256,64)); complexity remains O(B·n·m·d).

NumPy, PyTorch CPU and JAX (eager, jit, grad) were verified locally. PyTorch CUDA and TensorFlow were not tested and are not claimed as validated. Summing ordinary Euclidean distances that contain zero self-distances produces NaN gradients because sqrt is not differentiable at zero; this is identical on master and on this patch and is out of scope. The fix targets shared coordinate offsets and does not guarantee machine precision for arbitrary layouts (for example, when the first source sample is a far outlier).

Both PRs modifying these files were integrated locally in both merge orders with #926: production code and release notes merge cleanly, the test-file append/append collision was resolved by keeping both test blocks, 139 batch tests passed in each order, and #926's 13 envelope tests and VJP numerics were unchanged. These are local integration checks, not upstream CI results.

RELEASES.md is updated to satisfy the repository's mandatory release-notes check. A clean WSL source build ran 82 batch tests (19 skipped because Torch was not installed there) and 2 doctests; a NumPy/Torch/JAX runtime ran 129 batch tests. Ruff reported no new findings, and ruff format --check and git diff --check were clean.

@codecov

codecov Bot commented Nov 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 97.09%. Comparing base (367355d) to head (bb1bb81).

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #932   +/-   ##
=======================================
  Coverage   97.09%   97.09%           
=======================================
  Files         130      130           
  Lines       27229    27299   +70     
=======================================
+ Hits        26437    26507   +70     
  Misses        792      792           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant