Skip to content

[MRG] Fix segfault in ot.emd when no cost is finite - #869

Open
itzzdev09 wants to merge 2 commits into
PythonOT:masterfrom
itzzdev09:emd-all-nonfinite-cost
Open

itzzdev09 wants to merge 2 commits into
PythonOT:masterfrom
itzzdev09:emd-all-nonfinite-cost

Conversation

@itzzdev09

Copy link
Copy Markdown
Contributor

Types of changes

  • Bug fix

Description

ot.emd and ot.emd2 crash the Python interpreter with a segmentation fault when every entry of the cost matrix is NaN or infinite:

import numpy as np, ot
a, b = ot.unif(4), ot.unif(3)
ot.emd(a, b, np.full((4, 3), np.nan))   # Segmentation fault
ot.emd(a, b, np.full((4, 3), np.inf))   # Segmentation fault

Everything built on them crashes too, e.g. ot.solve, and ot.gromov.gromov_wasserstein2 with an all-NaN structure matrix. That is the case #469 reported; it was closed because a single NaN now gives a NaN result, but a fully NaN matrix still crashes.

Only the all-non-finite case crashes. With a NaN or inf row, column, block, or every entry but one, the solver returns an infeasible result (zero plan, result_code 0, the usual "Problem infeasible" warning). The dense solver call now goes through a small _emd_c_dense helper that returns that same infeasible result when no cost is finite, without calling emd_c. Every other input behaves exactly as before. With this, gromov_wasserstein2 on an all-NaN structure returns NaN, as for a single NaN.

How has this been tested

Added test_emd_no_finite_cost (NaN and inf) in test/test_ot.py. It covers emd, emd2 and gromov_wasserstein2, and it segfaults on master. test_ot.py, test_1d_solver.py, test_solvers.py and test/gromov pass (593 passed).

Checklist

  • I have added tests to cover my changes.
  • I have updated the RELEASES.md file.

@codecov

codecov Bot commented Sep 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.86%. Comparing base (98d09a1) to head (3a301c1).

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #869   +/-   ##
=======================================
  Coverage   96.86%   96.86%           
=======================================
  Files         128      128           
  Lines       26304    26324   +20     
=======================================
+ Hits        25480    25500   +20     
  Misses        824      824           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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