Skip to content

Getting started

deblais is two things in one repository:

  • a header-only C++17 library, with no dependency beyond the standard library (OpenMP is used when the compiler has it);
  • a Python package built on it, for NumPy arrays and PyTorch tensors.

Both solve the same problem: the optimal transport plan between two weighted point clouds for the squared Euclidean cost, or any power \(|x - y|^p\), exactly.

Python

Installation

pip install deblais

The wheels cover x86-64 Linux and Python 3.10 to 3.13. On other platforms pip builds the package from its source distribution, which needs a C++17 compiler and CMake. To build from a checkout, tuned for your machine:

git clone https://github.com/keckj/deblais.git
pip install ./deblais -C cmake.define.DEBLAIS_NATIVE=ON

NumPy is the only dependency. PyTorch is optional: install it and tensors are accepted.

A first solve

import numpy as np
import deblais

rng = np.random.default_rng(0)
x = rng.random((100_000, 2))          # source points, one per row
y = rng.random((100_000, 2)) + 0.5    # target points

plan = deblais.solve(x, y)
print(plan)
# Plan(cost=0.502491740674, arcs=100000, shape=(100000, 100000), method='decomposition', status='optimal')

plan.cost                 # squared Wasserstein-2 distance
plan.source, plan.target  # arc k ships plan.mass[k] from x[source[k]] to y[target[k]]
plan.f, plan.g            # Kantorovich potentials (dual solution)

Without masses, each cloud is the uniform probability measure on its points. Pass a and b for weighted clouds; the two clouds may have different sizes:

a = rng.random(100_000)
b = rng.random(60_000)
plan = deblais.solve(x, y[:60_000], a / a.sum(), b / b.sum())

The plan is sparse: at most \(n + m - 1\) arcs for \(n\) sources and \(m\) targets. A few views of it:

plan.map()          # barycentric projection: where the mass of each x[i] goes on average
plan.sparse()       # scipy.sparse.coo_array of shape (n, m)
plan.dense()        # dense matrix, small problems only
plan.assignment()   # sigma with x[i] -> y[sigma[i]], when the plan is a matching

PyTorch

Tensors go in, tensors come out, on the device and with the floating point type of x. The solve itself runs on the CPU in double precision.

import torch
import deblais

x = torch.rand(20_000, 3, device="cuda", requires_grad=True)
y = torch.rand(20_000, 3, device="cuda")

loss = deblais.wasserstein2(x, y)   # scalar tensor on cuda
loss.backward()                     # x.grad: see below

The cost is differentiable with respect to the points and the masses. The gradient is the one of the envelope theorem: the optimal plan \(P\) is held fixed, so that

\[ \nabla_{x_i} W_2^2 = 2 \sum_j P_{ij} (x_i - y_j) = 2 a_i \, \bigl(x_i - T(x_i)\bigr), \qquad \frac{\partial W_2^2}{\partial a_i} = f_i , \]

with \(T\) the barycentric projection (plan.map()) and \(f\) the potential of the sources. It is exact wherever the optimal plan is unique, that is almost everywhere.

Threads and the OpenMP runtime of PyTorch

deblais is parallelized with OpenMP. threads= sets the number of threads of one solve; by default it is the OpenMP default (OMP_NUM_THREADS, or all the cores).

A process should hold a single OpenMP runtime. PyTorch ships its own copy of the GNU runtime (torch/lib/libgomp.so.1), and deblais uses it: when PyTorch is installed, import deblais loads that library first (without importing PyTorch), whatever the order of the imports. Without PyTorch, the runtime of the system is used. Check with:

deblais.openmp_info()
# {'enabled': True, 'threads': 16, 'runtime': '.../site-packages/torch/lib/libgomp.so.1'}

Note

This applies to the Linux builds of PyTorch, which use the GNU runtime. deblais is compiled with GCC and has only been measured with libgomp; a run under LLVM's libomp was more than ten times slower in our tests.

C++

Installation

The library is the include/ folder: copy it, or let CMake fetch it.

include(FetchContent)
FetchContent_Declare(deblais GIT_REPOSITORY https://github.com/keckj/deblais.git GIT_TAG v0.1.0)
FetchContent_MakeAvailable(deblais)

target_link_libraries(my_program PRIVATE deblais::deblais)

deblais::deblais brings the include path, C++17, threads and OpenMP when it is found. An installed copy (cmake --install) is found by find_package(deblais). Without CMake:

g++ -std=c++17 -O3 -march=native -fopenmp -I deblais/include my_program.cpp

Without -fopenmp the library still compiles and runs on one thread (the pricing helpers still use std::thread, so link with -pthread).

A first solve

#include <deblais/deblais.hpp>
#include <cstdio>
#include <vector>

int main() {
  // 3 points of the plane on each side, stored point after point
  const std::vector<double> x = {0, 0,  1, 0,  0, 1};
  const std::vector<double> y = {1, 1,  2, 1,  1, 2};

  const deblais::Plan plan = deblais::solve(2, x, y);

  std::printf("cost %g\n", plan.cost);
  for (std::size_t k = 0; k < plan.size(); ++k)
    std::printf("%d -> %d: %g\n", plan.source[k], plan.target[k], plan.mass[k]);
}

With masses, and without a copy of your data (Cloud is a view):

deblais::Cloud source(points_x, n, masses_a);   // const double*, size, const double* or nullptr
deblais::Cloud target(points_y, m, masses_b);

deblais::Options options;
options.threads = 8;

const deblais::Plan plan = deblais::solve<3>(source, target, options);   // dimension known at compile time

To check a result independently of the solver:

const deblais::Certificate c = deblais::certify<3>(source, target, plan);
// c.gap, c.marginal_error, c.dual_violation; c.optimal()

The examples folder has complete programs, and the C++ API reference lists everything.

Next steps