-
Notifications
You must be signed in to change notification settings - Fork 757
perf: welford's algorithm for mean-var aggregation #4147
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
Merged
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
21f5ddc
perf: welford's algorithm for mean-var
ilan-gold 514bd17
chore: relnote
ilan-gold 48230af
Merge branch 'main' into ig/welford
ilan-gold afc24a1
Merge branch 'main' into ig/welford
ilan-gold 35b0ff6
Merge branch 'main' into ig/welford
ilan-gold 05daadb
chore: add cancelling test
ilan-gold e437714
chore: finish sentence
ilan-gold ec72679
chore: relnote
ilan-gold 9dcfcc7
chore: add context
ilan-gold 3fa0884
Merge branch 'main' into ig/welford
ilan-gold bd85e03
perf: less memory touches
ilan-gold 497809e
refactor: cleanup
ilan-gold 25e6bfc
chore: csc benchmarks
ilan-gold 1a19312
Merge branch 'main' into ig/welford
ilan-gold 81ae72b
Merge branch 'main' into ig/welford
ilan-gold 9004cc0
fix: tests
ilan-gold cc5ac95
Merge branch 'ig/welford' of github.com:scverse/scanpy into ig/welford
ilan-gold eb03735
Merge branch 'main' into ig/welford
ilan-gold ff0ac25
chore: spelling
ilan-gold File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| Use [Welford's algorithm][] for mean-var calculation in {func}`scanpy.get.aggregate` for in-memory (i.e., non-dask) arrays {smaller}`I Gold` | ||
|
|
||
| [Welford's algorithm]: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -48,69 +48,136 @@ def agg_sum_csc(indicator: CSRBase, data: CSCBase, out: np.ndarray) -> None: | |
| out[cat, col] += data.data[j] | ||
|
|
||
|
|
||
| @njit | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should make these |
||
| def mean_var_dense( | ||
| indicator: CSRBase, data: NDArray | ||
| ) -> tuple[NDArray[np.float64], NDArray[np.float64]]: | ||
| # Welford's online algorithm, parallelized over categories. The indicator | ||
|
flying-sheep marked this conversation as resolved.
|
||
| # CSR lists which observations belong to each category, allowing mask | ||
| # handling to be folded in naturally. | ||
| n_cats = indicator.shape[0] | ||
| n_features = data.shape[1] | ||
| mean = np.zeros((n_cats, n_features), dtype="float64") | ||
| var = np.zeros((n_cats, n_features), dtype="float64") | ||
|
|
||
| for cat in numba.prange(n_cats): | ||
| start = indicator.indptr[cat] | ||
| stop = indicator.indptr[cat + 1] | ||
| n = 0 | ||
| for row_num in range(start, stop): | ||
| obs = indicator.indices[row_num] | ||
| n += 1 | ||
| for col in range(n_features): | ||
| value = np.float64(data[obs, col]) | ||
| delta = value - mean[cat, col] | ||
| mean[cat, col] += delta / n | ||
| delta2 = value - mean[cat, col] | ||
| var[cat, col] += delta * delta2 | ||
| if n > 0: | ||
| for col in range(n_features): | ||
| var[cat, col] /= n | ||
| return mean, var | ||
|
|
||
|
|
||
| @njit | ||
| def mean_var_csr( | ||
| indicator: CSRBase, | ||
| data: CSCBase, | ||
| ) -> tuple[NDArray[np.float64], NDArray[np.float64]]: | ||
| mean = np.zeros((indicator.shape[0], data.shape[1]), dtype="float64") | ||
| var = np.zeros((indicator.shape[0], data.shape[1]), dtype="float64") | ||
|
|
||
| for cat_num in numba.prange(indicator.shape[0]): | ||
| # Welford's online algorithm over nonzeros, then merge with the block of | ||
| # implicit zeros per (category, feature). Merging a Welford accumulator | ||
| # (n_A, mean_A, M2_A) with k zeros gives: | ||
| # mean = mean_A * n_A / (n_A + k) | ||
| # M2_new = M2_A + mean_A^2 * n_A * k / (n_A + k) | ||
| n_cats = indicator.shape[0] | ||
| n_features = data.shape[1] | ||
| mean = np.zeros((n_cats, n_features), dtype="float64") | ||
| var = np.zeros((n_cats, n_features), dtype="float64") | ||
|
|
||
| for cat_num in numba.prange(n_cats): | ||
| start_cat_idx = indicator.indptr[cat_num] | ||
| stop_cat_idx = indicator.indptr[cat_num + 1] | ||
| n_obs = stop_cat_idx - start_cat_idx | ||
| if n_obs == 0: | ||
| continue | ||
|
|
||
| n_nonzero = np.zeros(n_features, dtype=np.int64) | ||
|
|
||
| for row_num in range(start_cat_idx, stop_cat_idx): | ||
| obs_per_cat = indicator.indices[row_num] | ||
|
|
||
| start_obs = data.indptr[obs_per_cat] | ||
| end_obs = data.indptr[obs_per_cat + 1] | ||
|
|
||
| for j in range(start_obs, end_obs): | ||
| col = data.indices[j] | ||
| value = np.float64(data.data[j]) | ||
| value = data.data[j] | ||
| mean[cat_num, col] += value | ||
| var[cat_num, col] += value * value | ||
|
|
||
| n_obs = stop_cat_idx - start_cat_idx | ||
| mean_cat = mean[cat_num, :] / n_obs | ||
| mean[cat_num, :] = mean_cat | ||
| var[cat_num, :] = (var[cat_num, :] / n_obs) - (mean_cat * mean_cat) | ||
| n = n_nonzero[col] + 1 | ||
| n_nonzero[col] = n | ||
| m = mean[cat_num, col] | ||
| delta = value - m | ||
| m += delta / n | ||
| mean[cat_num, col] = m | ||
| var[cat_num, col] += delta * (value - m) | ||
|
|
||
| for col in range(n_features): | ||
| n_nz = n_nonzero[col] | ||
| k = n_obs - n_nz | ||
| if k > 0 and n_nz > 0: | ||
| mean_a = mean[cat_num, col] | ||
| mean[cat_num, col] = mean_a * n_nz / n_obs | ||
| var[cat_num, col] += mean_a * mean_a * n_nz * k / n_obs | ||
| var[cat_num, col] /= n_obs | ||
| return mean, var | ||
|
|
||
|
|
||
| @njit | ||
| def mean_var_csc( | ||
| indicator: CSRBase, data: CSCBase | ||
| ) -> tuple[NDArray[np.float64], NDArray[np.float64]]: | ||
| # Welford's online algorithm, parallelized over columns. For each column | ||
| # we accumulate per-category over the explicit nonzeros, then merge each | ||
| # category's accumulator with its block of implicit zeros (see merge | ||
| # formula in `mean_var_csr`). | ||
| n_cats = indicator.shape[0] | ||
| n_features = data.shape[1] | ||
| obs_to_cat = np.full(data.shape[0], -1, dtype=np.int64) | ||
|
|
||
| mean = np.zeros((indicator.shape[0], data.shape[1]), dtype="float64") | ||
| var = np.zeros((indicator.shape[0], data.shape[1]), dtype="float64") | ||
|
|
||
| for cat in range(indicator.shape[0]): | ||
| n_obs_per_cat = np.zeros(n_cats, dtype=np.int64) | ||
| for cat in range(n_cats): | ||
| n_obs_per_cat[cat] = indicator.indptr[cat + 1] - indicator.indptr[cat] | ||
| for k in range(indicator.indptr[cat], indicator.indptr[cat + 1]): | ||
| obs_to_cat[indicator.indices[k]] = cat | ||
|
|
||
| for col in numba.prange(data.shape[1]): | ||
| mean = np.zeros((n_cats, n_features), dtype="float64") | ||
| var = np.zeros((n_cats, n_features), dtype="float64") | ||
|
|
||
| for col in numba.prange(n_features): | ||
| n_nonzero = np.zeros(n_cats, dtype=np.int64) | ||
| start = data.indptr[col] | ||
| end = data.indptr[col + 1] | ||
|
|
||
| for j in range(start, end): | ||
| obs = data.indices[j] | ||
| cat = obs_to_cat[obs] | ||
|
|
||
| if cat != -1: | ||
| value = np.float64(data.data[j]) | ||
| value = data.data[j] | ||
| mean[cat, col] += value | ||
| var[cat, col] += value * value | ||
|
|
||
| for cat_num in numba.prange(indicator.shape[0]): | ||
| start_cat_idx = indicator.indptr[cat_num] | ||
| stop_cat_idx = indicator.indptr[cat_num + 1] | ||
| n_obs = stop_cat_idx - start_cat_idx | ||
| mean_cat = mean[cat_num, :] / n_obs | ||
| mean[cat_num, :] = mean_cat | ||
| var[cat_num, :] = (var[cat_num, :] / n_obs) - (mean_cat * mean_cat) | ||
| if cat == -1: | ||
| continue | ||
| value = np.float64(data.data[j]) | ||
| n = n_nonzero[cat] + 1 | ||
| n_nonzero[cat] = n | ||
| m = mean[cat, col] | ||
| delta = value - m | ||
| m += delta / n | ||
| mean[cat, col] = m | ||
| var[cat, col] += delta * (value - m) | ||
|
|
||
| for cat in range(n_cats): | ||
| n_obs = n_obs_per_cat[cat] | ||
| if n_obs == 0: | ||
| continue | ||
| n_nz = n_nonzero[cat] | ||
| k = n_obs - n_nz | ||
| if k > 0 and n_nz > 0: | ||
| mean_a = mean[cat, col] | ||
| mean[cat, col] = mean_a * n_nz / n_obs | ||
| var[cat, col] += mean_a * mean_a * n_nz * k / n_obs | ||
| var[cat, col] /= n_obs | ||
| return mean, var | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.