Skip to content

[MRG] Fix circular OT costs and derivatives when all shifted CDF entries are negative - #938

Open
xihaian251 wants to merge 3 commits into
PythonOT:masterfrom
xihaian251:phase34-circle-cdf-wrap-fix
Open

xihaian251 wants to merge 3 commits into
PythonOT:masterfrom
xihaian251:phase34-circle-cdf-wrap-fix

Conversation

@xihaian251

Copy link
Copy Markdown
Contributor

[MRG] Fix circular OT costs and derivatives when all shifted CDF entries are negative

User impact

ot.lp.solver_circle can silently return a badly wrong optimal cost and
derivative for valid float64 inputs. In a deterministic public-API example,
master returns 0.8049522235041142; an independent SciPy LP solver and an
exact Fraction breakpoint enumeration both give 0.03158514371890842.
The solver terminates normally: there is no warning or exception.

Failure mechanism

Both ot_cost_on_circle and derivative_cost_on_circle shift target CDFs by
the fractional part of theta:

v_cdf_theta = v_cdf - (theta - floor(theta))
mask_n = v_cdf_theta < 0
mask_p = v_cdf_theta >= 0

When theta is a tiny negative number, theta - floor(theta) can round to
1.0. If accumulated weights end slightly below one after finite summation,
all shifted CDF entries are negative. The current guard

if nx.any(mask_n) and nx.any(mask_p):
    v_cdf_theta[mask_n] += 1

then skips the required wrap. searchsorted uses negative CDFs and evaluates
the wrong quantile mapping. Because the condition is batch-global, adding an
unrelated batch with a non-negative CDF can change the value of a failing batch.

Deterministic public-API reproducer

import numpy as np
from ot.lp.solver_circle import binary_search_circle

x = np.array([0.16941984065866045, 0.1836324134419436, 0.44653045879629283,
              0.4820980124097798, 0.4917087310586765, 0.8126037842950916,
              0.8510944169432116, 0.9797740750713527])
y = np.array([0.27379110343532287, 0.3658703056370922, 0.471481879564172,
              0.4991513312359799, 0.634675836166241, 0.7040614541610074,
              0.8349212395014908])
a = np.array([0.11527813452574018, 0.13388447349681654, 0.1598842189785102,
              0.06981890027127201, 0.16354173746775985, 0.1749747944285811,
              0.037675572756166016, 0.14494216807515392])
b = np.array([0.043465847478736226, 0.07830347135588803, 0.15577476895197248,
              0.058202097877683455, 0.2908482240722164, 0.2924309055386121,
              0.08097468472489115])
print(binary_search_circle(x, y, a, b, p=2, eps=1e-6))
# master:     [0.80495222]
# corrected:  [0.03158514]

Helper-level batch-composition violation

Separately, with fixed theta=-1e-17, legal normalized inputs
x=(0, 1/8, 1/4), y=(0, 1/8, 1/4, 7/8), a=(2,3,1)/6, b=(1,1,3,2)/7:

batch layout master cost for A patched cost for A
A alone 1.0576636904761905 0.14322916666666669
A+B 0.14322916666666669 0.14322916666666669
B+A 0.14322916666666669 0.14322916666666669
A+A 1.0576636904761905 0.14322916666666669

This is a helper-level counterexample with fixed theta; the public-API
counterexample above is separate and does not rely on helper manipulation.
Left and right derivatives show the same composition dependence on master and
are invariant after the patch.

Independent oracles and exact certificate

  • SciPy linprog on the full circular cost matrix.
  • Exact Fraction breakpoint enumeration of the periodic quantile objective.
  • Wolfram exact rational certificate for the all-negative intermediate state:
    with δ=2⁻⁵³ and cu=cv=(1/2, 1−δ), no wrap gives
    13510798882111489/18014398509481984; wrapping gives 0.

Across 1200 deterministic cases, maximum absolute error versus LP drops from
0.773367 to 1.397e-9. A remaining small optimizer gap is documented and is
not claimed to be eliminated by this patch.

Minimal fix

One guard in each function:

-    if nx.any(mask_n) and nx.any(mask_p):
+    if nx.any(mask_n):
         v_cdf_theta[mask_n] += 1

Ordinary mixed-sign and all-non-negative paths are unchanged. In 200 ordinary
cases, 199 outputs are bitwise identical; the changed case is a master error.

Tests

  • Three regression tests cover the public-API wrong value, direct all-negative
    CDF continuity, and full batch-composition invariance of cost, dCp and
    dCm.
  • Master: 3 failed. Patched: 3 passed.
  • Mutation controls: keeping only the cost fix fails all three tests; keeping
    only the derivative fix fails the batch-invariance test. Both fixes are
    necessary.
  • pytest test/test_circle_wrap_regression.py test/test_circle_solver.py test/sliced/test_spherical_sliced.py -q: 87 passed on the final commit.
  • A earlier full pytest run on commit 0696d9b gave 3637 passed, 468 skipped,
    6 xfailed and one local distutils/MSVC test_helpers environment failure
    that also fails on frozen master. It was not rerun on the final test-only
    commit d18bfe0.
  • pre-commit run --all-files and git diff --check: passed.
  • Native extensions are unchanged and identical between comparison trees.

Relation to #936

Issue #936, reported by @Luminousyyh, concerns non-termination from midpoint
stagnation. Its proposed one-line midpoint exit is a separate fix and is
not part of this PR. This PR does not solve that infinite-loop problem,
does not claim Closes/Fixes #936, and does not claim all finite-precision
errors are eliminated. It only fixes the distinct silent wrong-value bug in
the all-negative CDF wrap branch.

Beihai added 3 commits November 24, 2026 14:40
When the fractional shift rounds to 1 and accumulated marginals fall
slightly below 1, every shifted CDF can be negative. The existing guard
required both positive and negative entries, so the wrap was skipped and
the returned objective and derivatives were wrong. Wrap whenever a negative
CDF exists; add a regression test with an independent LP/exact value.
Check cost and both one-sided derivatives in the batch-composition
regression, and correct the circular optimal transport wording.
@codecov

codecov Bot commented Nov 24, 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 (d18bfe0).

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #938   +/-   ##
=======================================
  Coverage   97.09%   97.09%           
=======================================
  Files         130      131    +1     
  Lines       27229    27281   +52     
=======================================
+ Hits        26437    26489   +52     
  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