Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor/handle solve args #748

Open
wants to merge 26 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
310b273
move the alpha check to GWSolver level instead of parent classes
selmanozleyen Sep 22, 2024
6c8d42d
add tests to check if alpha fails or not
selmanozleyen Sep 22, 2024
0b06cc4
remove kwargs on a more public problem class
selmanozleyen Sep 22, 2024
feca7ec
pre-commit
selmanozleyen Sep 22, 2024
c7cceb1
add test that asserts type error when unrecognized args are given
selmanozleyen Sep 22, 2024
9edaafb
set default according to the data provided
selmanozleyen Sep 22, 2024
376eccf
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 22, 2024
01c89a2
Revert "remove kwargs on a more public problem class"
selmanozleyen Sep 22, 2024
49c8bbc
improve the tests to also use other rank solvers
selmanozleyen Sep 23, 2024
f303a14
remove skipped tests and add link to other skipped test
selmanozleyen Sep 23, 2024
9457676
Merge branch 'main' into refactor/handle-solve-args
selmanozleyen Oct 21, 2024
1582baa
adapt to was solvers new api
selmanozleyen Oct 23, 2024
a21c45f
update the tests
selmanozleyen Oct 23, 2024
a1dfd64
update tests for solvers new api
selmanozleyen Oct 23, 2024
e4dea94
adapt tests for solvers new api
selmanozleyen Oct 23, 2024
608ca73
check if it's callable for solvers initializer instance instead of st…
selmanozleyen Oct 23, 2024
ae2c681
again simply linear_ot_solver -> linear_solver
selmanozleyen Oct 23, 2024
895085d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 23, 2024
7e472dc
fix test for also fgw tests
selmanozleyen Oct 23, 2024
19d7f35
lint
selmanozleyen Oct 23, 2024
9e069bf
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 23, 2024
23c7caa
fix linting errors
selmanozleyen Oct 23, 2024
aeb1621
fix test_backend tests. There were some ignored args
selmanozleyen Oct 23, 2024
6543d57
format
selmanozleyen Oct 23, 2024
0b517a6
update test_pass_arguments
selmanozleyen Oct 23, 2024
9cb9c36
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 23, 2024
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
4 changes: 3 additions & 1 deletion src/moscot/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import Any, Literal, Mapping, Optional, Sequence, Union

import numpy as np
from ott.initializers.quadratic.initializers import BaseQuadraticInitializer

# TODO(michalk8): polish

Expand All @@ -20,8 +21,9 @@
SinkFullRankInit = Literal["default", "gaussian", "sorting"]
LRInitializer_t = Literal["random", "rank2", "k-means", "generalized-k-means"]


SinkhornInitializer_t = Optional[Union[SinkFullRankInit, LRInitializer_t]]
QuadInitializer_t = Optional[LRInitializer_t]
QuadInitializer_t = Optional[Union[LRInitializer_t, BaseQuadraticInitializer]]

Initializer_t = Union[SinkhornInitializer_t, LRInitializer_t]
ProblemStage_t = Literal["prepared", "solved"]
Expand Down
27 changes: 20 additions & 7 deletions src/moscot/backends/ott/solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import jax.numpy as jnp
import numpy as np
from ott.geometry import costs, epsilon_scheduler, geodesic, geometry, pointcloud
from ott.initializers.quadratic import initializers as quad_initializers
from ott.neural.datasets import OTData, OTDataset
from ott.neural.methods.flows import dynamics, genot
from ott.neural.networks.layers import time_encoder
Expand Down Expand Up @@ -409,13 +410,18 @@ def __init__(
**kwargs,
)
else:
linear_ot_solver = sinkhorn.Sinkhorn(**linear_solver_kwargs)
initializer = None
linear_solver = sinkhorn.Sinkhorn(**linear_solver_kwargs)
if initializer is None:
initializer = quad_initializers.QuadraticInitializer()
if isinstance(initializer, str):
raise ValueError(
"Expected `initializer` to be an instance of `ott.initializers.quadratic.BaseQuadraticInitializer`,"
f"found `{initializer}`."
)
initializer = functools.partial(initializer, **initializer_kwargs)
self._solver = gromov_wasserstein.GromovWasserstein(
rank=rank,
linear_ot_solver=linear_ot_solver,
quad_initializer=initializer,
kwargs_init=initializer_kwargs,
linear_solver=linear_solver,
initializer=initializer,
**kwargs,
)

Expand All @@ -435,7 +441,7 @@ def _prepare(
cost_matrix_rank: Optional[int] = None,
time_scales_heat_kernel: Optional[TimeScalesHeatKernel] = None,
# problem
alpha: float = 0.5,
alpha: Optional[float] = None,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we just make a comment behind this that default is 0.5

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm actually wondering whether we should have a default alpha whenever we don't want it to be 1.0

I.e. always set it explicitly in the classes which use GW, wdyt?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I set it like this so that it doesn't change the current behaviour.

I.e. always set it explicitly in the classes which use GW, wdyt?

You mean to make non-optional? I personally prefer non-optional parameters, especially if the class is an internal solver. I also think we should rename GWSolver to FGWSolver (because it technically can solve fgw and gw) and just set alpha=1 when in a GWProblem.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that makes sense

**kwargs: Any,
) -> quadratic_problem.QuadraticProblem:
self._a = a
Expand All @@ -456,6 +462,13 @@ def _prepare(
geom_kwargs["cost_matrix_rank"] = cost_matrix_rank
geom_xx = self._create_geometry(x, t=time_scales_heat_kernel.x, is_linear_term=False, **geom_kwargs)
geom_yy = self._create_geometry(y, t=time_scales_heat_kernel.y, is_linear_term=False, **geom_kwargs)
if alpha is None:
alpha = 1.0 if xy is None else 0.5 # set defaults according to the data provided
if alpha <= 0.0:
selmanozleyen marked this conversation as resolved.
Show resolved Hide resolved
raise ValueError(f"Expected `alpha` to be in interval `(0, 1]`, found `{alpha}`.")
if (alpha == 1.0 and xy is not None) or (alpha != 1.0 and xy is None):
raise ValueError(f"Expected `xy` to be `None` if `alpha` is not 1.0, found xy={xy}, alpha={alpha}.")

selmanozleyen marked this conversation as resolved.
Show resolved Hide resolved
if alpha == 1.0 or xy is None: # GW
# arbitrary fused penalty; must be positive
geom_xy, fused_penalty = None, 1.0
Expand Down
18 changes: 1 addition & 17 deletions src/moscot/base/problems/problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,24 +430,8 @@ def solve(
solver_class = backends.get_solver(
self.problem_kind, solver_name=solver_name, backend=backend, return_class=True
)
init_kwargs, call_kwargs = solver_class._partition_kwargs(**kwargs)
# if linear problem, then alpha is 0.0 by default
# if quadratic problem, then alpha is 1.0 by default
alpha = call_kwargs.get("alpha", 0.0 if self.problem_kind == "linear" else 1.0)
if alpha < 0.0 or alpha > 1.0:
raise ValueError("Expected `alpha` to be in the range `[0, 1]`, found `{alpha}`.")
if self.problem_kind == "linear" and (alpha != 0.0 or not (self.x is None or self.y is None)):
raise ValueError("Unable to solve a linear problem with `alpha != 0` or `x` and `y` supplied.")
if self.problem_kind == "quadratic":
if self.x is None or self.y is None:
raise ValueError("Unable to solve a quadratic problem without `x` and `y` supplied.")
if alpha != 1.0 and self.xy is None: # means FGW case
raise ValueError(
"`alpha` must be 1.0 for quadratic problems without `xy` supplied. See `FGWProblem` class."
)
if alpha == 1.0 and self.xy is not None:
raise ValueError("Unable to solve a quadratic problem with `alpha = 1` and `xy` supplied.")

init_kwargs, call_kwargs = solver_class._partition_kwargs(**kwargs)
self._solver = solver_class(**init_kwargs)

# note that the solver call consists of solver._prepare and solver._solve
Expand Down
16 changes: 7 additions & 9 deletions tests/backends/ott/test_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def test_matches_ott(self, x: Geom_t, y: Geom_t, eps: Optional[float], jit: bool
thresh = 1e-2
pc_x, pc_y = PointCloud(x, epsilon=eps), PointCloud(y, epsilon=eps)
prob = quadratic_problem.QuadraticProblem(pc_x, pc_y)
sol = GromovWasserstein(epsilon=eps, threshold=thresh)
sol = GromovWasserstein(epsilon=eps, threshold=thresh, linear_solver=Sinkhorn())
solver = jax.jit(sol, static_argnames=["threshold", "epsilon"]) if jit else sol
gt = solver(prob)

Expand Down Expand Up @@ -130,7 +130,7 @@ def test_epsilon(self, x_cost: jnp.ndarray, y_cost: jnp.ndarray, eps: Optional[f
problem = QuadraticProblem(
geom_xx=Geometry(cost_matrix=x_cost, epsilon=eps), geom_yy=Geometry(cost_matrix=y_cost, epsilon=eps)
)
gt = GromovWasserstein(epsilon=eps, threshold=thresh)(problem)
gt = GromovWasserstein(epsilon=eps, threshold=thresh, linear_solver=Sinkhorn())(problem)
solver = GWSolver(epsilon=eps, threshold=thresh)

pred = solver(
Expand All @@ -157,7 +157,7 @@ def test_solver_rank(self, x: Geom_t, y: Geom_t, rank: int) -> None:
)

else:
gt = GromovWasserstein(epsilon=eps, rank=rank, threshold=thresh)(
gt = GromovWasserstein(epsilon=eps, threshold=thresh, linear_solver=Sinkhorn())(
QuadraticProblem(PointCloud(x, epsilon=eps), PointCloud(y, epsilon=eps))
)

Expand All @@ -183,7 +183,7 @@ def test_matches_ott(self, x: Geom_t, y: Geom_t, xy: Geom_t, eps: Optional[float
thresh = 1e-2
xx, yy = xy

ott_solver = GromovWasserstein(epsilon=eps, threshold=thresh)
ott_solver = GromovWasserstein(epsilon=eps, threshold=thresh, linear_solver=Sinkhorn())
problem = quadratic_problem.QuadraticProblem(
geom_xx=PointCloud(x, epsilon=eps),
geom_yy=PointCloud(y, epsilon=eps),
Expand Down Expand Up @@ -218,7 +218,7 @@ def test_alpha(self, x: Geom_t, y: Geom_t, xy: Geom_t, alpha: float) -> None:
thresh, eps = 5e-2, 1e-1
xx, yy = xy

ott_solver = GromovWasserstein(epsilon=eps, threshold=thresh)
ott_solver = GromovWasserstein(epsilon=eps, threshold=thresh, linear_solver=Sinkhorn())
problem = quadratic_problem.QuadraticProblem(
geom_xx=PointCloud(x, epsilon=eps),
geom_yy=PointCloud(y, epsilon=eps),
Expand Down Expand Up @@ -256,7 +256,7 @@ def test_epsilon(
geom_xy=Geometry(cost_matrix=xy_cost, epsilon=eps),
fused_penalty=alpha_to_fused_penalty(alpha),
)
gt = GromovWasserstein(epsilon=eps, threshold=thresh)(problem)
gt = GromovWasserstein(epsilon=eps, threshold=thresh, linear_solver=Sinkhorn())(problem)

solver = GWSolver(epsilon=eps, threshold=thresh)
pred = solver(
Expand Down Expand Up @@ -398,7 +398,5 @@ def test_plot_errors_sink(self, x: Geom_t, y: Geom_t):
out.plot_errors()

def test_plot_errors_gw(self, x: Geom_t, y: Geom_t):
out = GWSolver(a=jnp.ones(len(x)) / len(x), b=jnp.ones(len(y)) / len(y), store_inner_errors=True)(
a=jnp.ones(len(x)) / len(x), b=jnp.ones(len(y)) / len(y), x=x, y=y
)
out = GWSolver(store_inner_errors=True)(a=jnp.ones(len(x)) / len(x), b=jnp.ones(len(y)) / len(y), x=x, y=y)
out.plot_errors()
56 changes: 56 additions & 0 deletions tests/problems/base/test_general_problem.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import re
from typing import Literal, Optional, Tuple

import pytest
Expand Down Expand Up @@ -29,6 +30,29 @@ def test_simple_run(self, adata_x: AnnData, adata_y: AnnData):

assert isinstance(prob.solution, BaseDiscreteSolverOutput)

@pytest.mark.parametrize(
("kind", "rank"),
[
("linear", -1),
("linear", 5),
("quadratic", -1),
("quadratic", 5),
],
)
def test_unrecognized_args(
self, adata_x: AnnData, adata_y: AnnData, kind: Literal["linear", "quadratic"], rank: int
):
prob = OTProblem(adata_x, adata_y)
data = {
"xy": {"x_attr": "obsm", "x_key": "X_pca", "y_attr": "obsm", "y_key": "X_pca"},
}
if "quadratic" in kind:
data["x"] = {"attr": "X"}
data["y"] = {"attr": "X"}

with pytest.raises(TypeError):
prob.prepare(**data).solve(epsilon=5e-1, rank=rank, dummy=42)

@pytest.mark.fast
def test_output(self, adata_x: AnnData, x: Geom_t):
problem = OTProblem(adata_x)
Expand Down Expand Up @@ -346,3 +370,35 @@ def test_set_graph_xy_test_t(self, adata_x: AnnData, adata_y: AnnData, t: float)
assert pushed_0.shape == pushed_1.shape
assert np.all(np.abs(pushed_0 - pushed_1).sum() > np.abs(pushed_2 - pushed_1).sum())
assert np.all(np.abs(pushed_0 - pushed_2).sum() > np.abs(pushed_1 - pushed_2).sum())

@pytest.mark.parametrize(
("attrs", "alpha", "raise_msg"),
[
({"xy"}, 0.5, "type-error"),
({"xy", "x", "y"}, 0, re.escape("Expected `alpha` to be in interval `(0, 1]`, found")),
({"xy", "x", "y"}, 1.1, re.escape("Expected `alpha` to be in interval `(0, 1]`, found")),
({"xy", "x", "y"}, 0.5, None),
({"x", "y"}, 1.0, None),
({"x", "y"}, 0.5, re.escape("Expected `xy` to be `None` if `alpha` is not 1.0, found")),
],
)
def test_xy_alpha_raises(self, adata_x: AnnData, adata_y: AnnData, attrs, alpha, raise_msg):
prob = OTProblem(adata_x, adata_y)
data = {
"xy": {"x_attr": "obsm", "x_key": "X_pca", "y_attr": "obsm", "y_key": "X_pca"} if "xy" in attrs else {},
"x": {"attr": "X"} if "x" in attrs else {},
"y": {"attr": "X"} if "y" in attrs else {},
}
prob = prob.prepare(
**data,
)
if raise_msg is not None:
if raise_msg == "type-error":
with pytest.raises(TypeError):
prob.solve(epsilon=5e-1, alpha=alpha)
else:
with pytest.raises(ValueError, match=raise_msg):
prob.solve(epsilon=5e-1, alpha=alpha)
else:
prob.solve(epsilon=5e-1, alpha=alpha)
assert isinstance(prob.solution, BaseDiscreteSolverOutput)
5 changes: 2 additions & 3 deletions tests/problems/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,8 @@ def marginal_keys(request):
"threshold": "threshold",
"min_iterations": "min_iterations",
"max_iterations": "max_iterations",
"initializer_kwargs": "kwargs_init",
"warm_start": "_warm_start",
"initializer": "quad_initializer",
"warm_start": "warm_start",
"initializer": "initializer",
}

gw_lr_solver_args = {
Expand Down
10 changes: 6 additions & 4 deletions tests/problems/cross_modality/test_translation_problem.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from contextlib import nullcontext
from typing import Any, Literal, Mapping, Optional, Tuple
from typing import Any, Callable, Literal, Mapping, Optional, Tuple

import pytest

Expand Down Expand Up @@ -144,12 +144,14 @@ def test_pass_arguments(self, adata_translation_split: Tuple[AnnData, AnnData],
tp = tp.solve(**args_to_check)

solver = tp[key].solver.solver

args = gw_solver_args if args_to_check["rank"] == -1 else gw_lr_solver_args
for arg, val in args.items():
assert getattr(solver, val) == args_to_check[arg], arg
if arg == "initializer" and args_to_check["rank"] == -1:
assert isinstance(getattr(solver, val), Callable)
else:
assert getattr(solver, val) == args_to_check[arg], arg

sinkhorn_solver = solver.linear_ot_solver if args_to_check["rank"] == -1 else solver
sinkhorn_solver = solver.linear_solver if args_to_check["rank"] == -1 else solver
lin_solver_args = gw_linear_solver_args if args_to_check["rank"] == -1 else gw_lr_linear_solver_args
tmp_dict = args_to_check["linear_solver_kwargs"] if args_to_check["rank"] == -1 else args_to_check
for arg, val in lin_solver_args.items():
Expand Down
11 changes: 7 additions & 4 deletions tests/problems/generic/test_fgw_problem.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Literal, Mapping
from typing import Any, Callable, Literal, Mapping

import pytest

Expand Down Expand Up @@ -112,9 +112,12 @@ def test_pass_arguments(self, adata_space_rotate: AnnData, args_to_check: Mappin
solver = problem[key].solver.solver
args = gw_solver_args if args_to_check["rank"] == -1 else gw_lr_solver_args
for arg, val in args.items():
assert getattr(solver, val, object()) == args_to_check[arg], arg
if args_to_check["rank"] == -1 and arg == "initializer":
assert isinstance(getattr(solver, val), Callable)
else:
assert getattr(solver, val, object()) == args_to_check[arg], arg

sinkhorn_solver = solver.linear_ot_solver if args_to_check["rank"] == -1 else solver
sinkhorn_solver = solver.linear_solver if args_to_check["rank"] == -1 else solver
lin_solver_args = gw_linear_solver_args if args_to_check["rank"] == -1 else gw_lr_linear_solver_args
tmp_dict = args_to_check["linear_solver_kwargs"] if args_to_check["rank"] == -1 else args_to_check
for arg, val in lin_solver_args.items():
Expand Down Expand Up @@ -342,7 +345,7 @@ def test_passing_ott_kwargs_linear(self, adata_space_rotate: AnnData, memory: in
},
)

sinkhorn_solver = problem[("0", "1")].solver.solver.linear_ot_solver
sinkhorn_solver = problem[("0", "1")].solver.solver.linear_solver

anderson = sinkhorn_solver.anderson
assert isinstance(anderson, acceleration.AndersonAcceleration)
Expand Down
11 changes: 7 additions & 4 deletions tests/problems/generic/test_gw_problem.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Literal, Mapping
from typing import Any, Callable, Literal, Mapping

import pytest

Expand Down Expand Up @@ -117,9 +117,12 @@ def test_pass_arguments(self, adata_space_rotate: AnnData, args_to_check: Mappin
args = gw_solver_args if args_to_check["rank"] == -1 else gw_lr_solver_args
for arg, val in args.items():
assert hasattr(solver, val)
assert getattr(solver, val) == args_to_check[arg]
if arg == "initializer" and args_to_check["rank"] == -1:
assert isinstance(getattr(solver, val), Callable)
else:
assert getattr(solver, val) == args_to_check[arg]

sinkhorn_solver = solver.linear_ot_solver if args_to_check["rank"] == -1 else solver
sinkhorn_solver = solver.linear_solver if args_to_check["rank"] == -1 else solver
lin_solver_args = gw_linear_solver_args if args_to_check["rank"] == -1 else gw_lr_linear_solver_args
tmp_dict = args_to_check["linear_solver_kwargs"] if args_to_check["rank"] == -1 else args_to_check
for arg, val in lin_solver_args.items():
Expand Down Expand Up @@ -307,7 +310,7 @@ def test_passing_ott_kwargs_linear(self, adata_space_rotate: AnnData, memory: in
},
)

sinkhorn_solver = problem[("0", "1")].solver.solver.linear_ot_solver
sinkhorn_solver = problem[("0", "1")].solver.solver.linear_solver

anderson = sinkhorn_solver.anderson
assert isinstance(anderson, acceleration.AndersonAcceleration)
Expand Down
Loading
Loading