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

Speedup (~20x) of scanpy.pp.regress_out function using Linear Least Square method. #3110

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
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 docs/release-notes/1.10.2.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@
* `pp.highly_variable_genes` with `flavor=seurat_v3` now uses a numba kernel {pr}`3017` {smaller}`S Dicks`
* Speed up {func}`~scanpy.pp.scrublet` {pr}`3044` {smaller}`S Dicks` and {pr}`3056` {smaller}`P Angerer`
* Speed up clipping of array in {func}`~scanpy.pp.scale` {pr}`3100` {smaller}`P Ashish & S Dicks`
* Speed up {func}`~scanpy.pp.regress_out` {pr}`3110` {smaller}`P Ashish & P Angerer`
77 changes: 69 additions & 8 deletions src/scanpy/preprocessing/_simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import warnings
from functools import singledispatch
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, TypeVar

import numba
import numpy as np
Expand Down Expand Up @@ -612,6 +612,53 @@ def normalize_per_cell( # noqa: PLR0917
return X if copy else None


DT = TypeVar("DT")


@numba.njit(cache=True, parallel=True)
def to_dense(
shape: tuple[int, int],
indptr: NDArray[np.integer],
indices: NDArray[np.integer],
data: NDArray[DT],
) -> NDArray[DT]:
"""\
Numba kernel for np.toarray() function
"""
X = np.empty(shape, dtype=data.dtype)

for r in numba.prange(shape[0]):
X[r] = 0
for i in range(indptr[r], indptr[r + 1]):
X[r, indices[i]] = data[i]
return X


def numpy_regress_out(
data: np.ndarray,
regressor: np.ndarray,
) -> np.ndarray:
"""\
Numba kernel for regress out unwanted sorces of variantion.
Finding coefficient using Linear regression (Linear Least Squares).
"""

@numba.njit(cache=True, parallel=True)
def get_resid(
data: np.ndarray,
regressor: np.ndarray,
coeff: np.ndarray,
) -> np.ndarray:
Comment on lines +646 to +651
Copy link
Contributor

Choose a reason for hiding this comment

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

Is the DT not important here as above?

for i in numba.prange(data.shape[0]):
data[i] -= regressor[i] @ coeff
return data

inv_gram_matrix = np.linalg.inv(regressor.T @ regressor)
coeff = inv_gram_matrix @ (regressor.T @ data)
data = get_resid(data, regressor, coeff)
return data


@old_positionals("layer", "n_jobs", "copy")
def regress_out(
adata: AnnData,
Expand Down Expand Up @@ -664,7 +711,7 @@ def regress_out(

if issparse(X):
logg.info(" sparse input is densified and may " "lead to high memory use")
X = X.toarray()
X = to_dense(X.shape, X.indptr, X.indices, X.data)

n_jobs = sett.n_jobs if n_jobs is None else n_jobs

Expand Down Expand Up @@ -715,14 +762,28 @@ def regress_out(
regres = regressors
tasks.append(tuple((data_chunk, regres, variable_is_categorical)))

from joblib import Parallel, delayed
res = None
if not variable_is_categorical:
A = regres.to_numpy()
Comment on lines 762 to +767
Copy link
Contributor

@ilan-gold ilan-gold Jul 4, 2024

Choose a reason for hiding this comment

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

I think the code before this should be refactored as well to include these new methods in the condition (i.e. at https://github.com/scverse/scanpy/pull/3110/files#diff-f9e0bdcdfc04622c421f0a5788bbba6ee0303750580d2915caba3239d799322fR759). We can just check regressors.to_numpy() for non-zero determinant before iterating through the chunk list. We don't need to make the list at all, from what I can tell, if not variable_is_categorical and the determinant is non-zero. This will also make things cleaner because we will need fewer checks. We can then use a boolean to check whether we should move into the next clause (which will include chunk creation) instead of checking res=None or not.

Does this make sense?

# if det(A.T@A) != 0 we can take the inverse and regress using a fast method.
if np.linalg.det(A.T @ A) != 0:
res = numpy_regress_out(X, A)

# for a categorical variable or if the above checks failed,
# we fall back to the GLM implemetation of regression.
if variable_is_categorical or res is None:
from joblib import Parallel, delayed

# TODO: figure out how to test that this doesn't oversubscribe resources
res = Parallel(n_jobs=n_jobs)(
delayed(_regress_out_chunk)(task) for task in tasks
)

# TODO: figure out how to test that this doesn't oversubscribe resources
res = Parallel(n_jobs=n_jobs)(delayed(_regress_out_chunk)(task) for task in tasks)
# res is a list of vectors (each corresponding to a regressed gene column).
# The transpose is needed to get the matrix in the shape needed
res = np.vstack(res).T

# res is a list of vectors (each corresponding to a regressed gene column).
# The transpose is needed to get the matrix in the shape needed
_set_obs_rep(adata, np.vstack(res).T, layer=layer)
_set_obs_rep(adata, res, layer=layer)
logg.info(" finished", time=start)
return adata if copy else None

Expand Down
Loading