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 @@ -23,6 +23,7 @@
#### Closed issues

- Fix dead links in the README (three example gallery pages and the reference [39]), the user guide and the contributing guide (PR #928)
- Fix crashes in `ot.bsp.compute_bspot_bijection` on degenerate inputs: validate `n_plans` and `initial_perm` at the Python/Cython boundaries and guard the native merge against an empty candidate list. Valid inputs and seeding are unchanged.
- 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)
- Fix an out-of-bounds read in `ot.bsp.merge_bijections`: the number of plans was taken from `perms.shape[1]` (the number of samples) instead of `perms.shape[0]`, so merging fewer plans than samples read past the array and merging more silently dropped plans. A `perms` outside the documented `(n_plans, n_samples)` layout, an empty plan stack and rows that are not permutations are now rejected (PR #911, Issue #910)
Expand Down
6 changes: 6 additions & 0 deletions ot/bsp/BSP-OT_header_only.h
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,12 @@ Vec evalMappings(const BijectiveMatching& T,const cost_function& cost) {
}

BijectiveMatching MergePlansNoPar(const std::vector<BijectiveMatching> &plans, const cost_function &cost, BijectiveMatching T,bool cycle) {
// With no candidate plan there is nothing to rank or merge. Return the
// supplied starting matching (empty when none was given) before indexing
// plans[I[0]] or plans[0] below, which would read a null/empty vector.
if (plans.empty()) {
return T;
}
int s = 0;
auto I = true ? rankPlans(plans,cost) : rangeVec(plans.size());
if (T.size() == 0) {
Expand Down
14 changes: 14 additions & 0 deletions ot/bsp/bsp_ot.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,26 @@ def compute_bspot_bijection(
if X_np.ndim != 2:
raise ValueError("X and Y must be 2D arrays")

if n_plans <= 0:
raise ValueError("n_plans must be a positive integer, got {}".format(n_plans))

if initial_perm is not None:
initial_perm = list_to_array(initial_perm)
if initial_perm.shape != (X.shape[0],):
raise ValueError(
"initial_perm must have shape (n,) where n is the number of points"
)
# A non-permutation makes the native inverse construction write out of
# bounds (negative or out-of-range entries) or hang (duplicates), so
# reject it before crossing the Cython boundary. Check the exact
# integer permutation (dtype and value), not just min/max/unique:
# fractional arrays such as [0.1, 1.1, ...] and arrays containing NaN
# must be rejected here rather than relying on the Cython dtype check.
ip = np.asarray(initial_perm)
if ip.dtype.kind not in "iu" or not np.array_equal(
np.sort(ip), np.arange(X_np.shape[0])
):
raise ValueError("initial_perm must be a permutation of 0..n-1")

if gaussian_slicing == "auto":
gaussian_slicing = X_np.shape[1] <= 64
Expand Down
20 changes: 20 additions & 0 deletions ot/bsp/bsp_wrap.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,26 @@ def bsp_solve_c(np.ndarray[double, ndim=2, mode="c"] X, np.ndarray[double, ndim=
print("not contiugous")
cdef int n = X.shape[0]
cdef int d = X.shape[1]

# Guard the native boundary: a non-positive plan count would leave an
# empty candidate vector that MergePlansNoPar indexes at [0], and an
# initial plan of the wrong length or with non-permutation entries makes
# getInverse() write out of bounds (TI[T[i]] = i with T[i] negative or >= n).
if n_plans <= 0:
raise ValueError("n_plans must be a positive integer, got {}".format(n_plans))
if initial_plan is not None:
if initial_plan.shape[0] != n:
raise ValueError(
"initial_plan must have one entry per point, got {} for {} points".format(
initial_plan.shape[0], n
)
)
# The typed int buffer already rejects float/NaN arrays before this
# point; an exact sort check additionally rejects negative,
# out-of-range and duplicated entries in one step.
if not np.array_equal(np.sort(initial_plan), np.arange(n)):
raise ValueError("initial_plan must be a permutation of 0..n-1")

cdef np.ndarray[int, ndim=2, mode="c"] plans = np.zeros((n_plans,n), dtype=np.int32)
cdef np.ndarray[int, ndim=1, mode="c"] plan = np.zeros(n, dtype=np.int32)

Expand Down
90 changes: 90 additions & 0 deletions test/test_bspot.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,3 +523,93 @@ def test_bsp_permutation_structure_and_cost():
np.testing.assert_allclose(cost, np.mean(M[np.arange(80), perm]), rtol=1e-9)
for row in np.asarray(perms):
np.testing.assert_array_equal(np.sort(row), np.arange(80))


def test_bsp_rejects_nonpositive_n_plans():
# Degenerate plan counts used to segfault in MergePlansNoPar (empty plans).
A, B = _two_clouds(n=6, data_seed=1)
for bad in (0, -1):
with pytest.raises(ValueError, match="n_plans"):
ot.bsp.compute_bspot_bijection(A, B, n_plans=bad)


def test_bsp_solve_c_rejects_nonpositive_n_plans():
# Direct Cython boundary must validate too, so callers bypassing the
# public API cannot reach the native empty-plan crash.
A, B = _two_clouds(n=6, data_seed=1)
from ot.bsp.bsp_wrap import bsp_solve_c

for bad in (0, -1):
with pytest.raises(ValueError, match="n_plans"):
bsp_solve_c(
np.asarray(A, dtype=np.float64),
np.asarray(B, dtype=np.float64),
bad,
2,
)


@pytest.mark.parametrize(
"bad", [[0, 0, 2, 3], [0, 1, 2, 4], [0, 1, 2, -1]]
)
def test_bsp_rejects_invalid_initial_perm(bad):
# A non-permutation initial plan made getInverse write out of bounds
# (negative / out-of-range entry) or hang (duplicate).
rng = np.random.RandomState(11)
A = rng.rand(4, 2)
B = rng.rand(4, 2)
with pytest.raises(ValueError, match="permutation"):
ot.bsp.compute_bspot_bijection(A, B, n_plans=2, initial_perm=bad)


def test_bsp_initial_perm_wrong_length():
rng = np.random.RandomState(12)
A = rng.rand(4, 2)
B = rng.rand(4, 2)
with pytest.raises(ValueError):
ot.bsp.compute_bspot_bijection(A, B, n_plans=2, initial_perm=[0, 1, 2])


@pytest.mark.parametrize(
"bad",
[
np.array([0, 0, 2, 3], dtype=np.int32), # duplicate
np.array([0, 1, 2, 4], dtype=np.int32), # out of range
np.array([0, 1, 2, -1], dtype=np.int32), # negative
np.array([0, 1, 2], dtype=np.int32), # short buffer
],
)
def test_bsp_solve_c_rejects_invalid_initial_plan(bad):
# The direct Cython entry point must enforce the same initial-plan contract
# as the public API: an invalid permutation or a short buffer would make
# the native getInverse() write out of bounds. This test needs a rebuilt
# bsp_wrap extension (the fix lives in the Cython layer).
A, B = _two_clouds(n=4, data_seed=11)
from ot.bsp.bsp_wrap import bsp_solve_c

with pytest.raises(ValueError, match="initial_plan"):
bsp_solve_c(
np.ascontiguousarray(A, dtype=np.float64),
np.ascontiguousarray(B, dtype=np.float64),
2,
2,
bad,
)


@pytest.mark.parametrize(
"bad",
[
[0.1, 1.1, 2.1, 3.1],
[0.0, 1.0, 2.0, np.nan],
],
)
def test_bsp_rejects_non_integral_initial_perm(bad):
# Fractional/NaN arrays are not integer permutations. Cython's typed int
# buffer would reject them later, but the public API must reject them with
# a precise permutation error before crossing that boundary.
rng = np.random.RandomState(13)
A = rng.rand(4, 2)
B = rng.rand(4, 2)
with pytest.raises(ValueError, match="permutation"):
ot.bsp.compute_bspot_bijection(A, B, n_plans=2, initial_perm=bad)
Loading