Skip to content

Compute pseudobulk and clustering centroids from sparse matrices without densifying - #250

Open
rpinho wants to merge 1 commit into
ArcInstitute:mainfrom
rpinho:sparse-pseudobulk
Open

rpinho wants to merge 1 commit into
ArcInstitute:mainfrom
rpinho:sparse-pseudobulk

Conversation

@rpinho

@rpinho rpinho commented Nov 17, 2026

Copy link
Copy Markdown

PerturbationAnndataPair._bulk_anndata and ClusteringAgreement._centroid_ann convert a sparse expression matrix to a dense cells × genes array before averaging cells per perturbation, and _bulk_anndata copies that array again into a polars frame. On a synthetic pair of 50,000-cell × 6,000-gene float32 CSR matrices (5% nonzero, 200 perturbations plus control), building the pair and computing mae and discrimination_score(metric="l1") took a median of 1.93 s before and 0.65 s after (5 alternating runs each, h5ad loading excluded, Apple M5 Pro), and process peak RSS fell from 3.16 GB to 0.66 GB; for ClusteringAgreement on a 50,000 × 4,000 float32 pair, peak RSS fell from 2.43 GB to 0.82 GB with runtime within 3%. The patch adds a private helper that sums rows per group with a sparse indicator-matrix product in 4,096-row blocks, accumulates in float64 and returns the input's floating dtype, and uses it for sparse inputs in both places, while dense inputs keep the existing code path. For float32 inputs the pseudobulk arrays and the MAE and L1 discrimination scores were byte-identical to main in every run, and MetricsEvaluator(..., skip_de=True).compute(profile="anndata") on a 10,000 × 2,000 float32 pair produced identical result tables; for float64 inputs the summation order differs, so 27% of pseudobulk entries changed by at most 5.3e-16 relative and 17 of 100 MAE values by at most 3.0e-16 relative, while discrimination scores were unchanged. The new tests compare sparse (CSR and CSC; float32, float64 and int32) against dense inputs for pseudobulks, including inputs that span more than one block, and for clustering centroids; the full test suite and ruff format --check pass, and ty check reports the same 7 diagnostics as on main.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LKxc9GKLwnyeV2jaZBxH9N

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a new utility function _sparse_group_mean to compute group means for sparse matrices without densifying the entire input, and updates _bulk_anndata and _centroid_ann to utilize this function. A new test file was added to verify the implementation against dense equivalents. The reviewer provided a high-severity suggestion to optimize memory usage in the _sparse_group_mean function by using active group indexing to avoid allocating large dense arrays in each iteration.

Comment thread src/cell_eval/utils.py
Comment on lines +24 to +30
for start in range(0, groups.size, 4096):
stop = min(start + 4096, groups.size)
membership = csr_matrix(
(np.ones(stop - start), (inverse[start:stop], np.arange(stop - start))),
shape=(keys.size, stop - start),
)
sums += (membership @ matrix[start:stop].astype(np.float64)).toarray()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

When the number of unique groups (keys.size) is large, constructing membership with shape (keys.size, stop - start) and converting the product to a dense array via .toarray() will allocate a dense array of shape (keys.size, matrix.shape[1]) in every iteration. For large datasets or high-cardinality grouping variables, this can lead to massive memory overhead (potentially causing Out-Of-Memory errors) and significant performance degradation due to repeated large allocations.

By restricting membership to only the active groups present in the current block, we can reduce the size of the intermediate dense array to (active_keys.size, matrix.shape[1]) (where active_keys.size is at most 4096, and often much smaller), and then perform an in-place addition using advanced indexing: sums[active_keys] += ....

Suggested change
for start in range(0, groups.size, 4096):
stop = min(start + 4096, groups.size)
membership = csr_matrix(
(np.ones(stop - start), (inverse[start:stop], np.arange(stop - start))),
shape=(keys.size, stop - start),
)
sums += (membership @ matrix[start:stop].astype(np.float64)).toarray()
for start in range(0, groups.size, 4096):
stop = min(start + 4096, groups.size)
active_keys, local_inverse = np.unique(inverse[start:stop], return_inverse=True)
membership = csr_matrix(
(np.ones(stop - start), (local_inverse, np.arange(stop - start))),
shape=(active_keys.size, stop - start),
)
sums[active_keys] += (membership @ matrix[start:stop].astype(np.float64)).toarray()
References
  1. Do not prioritize micro-optimizations (e.g., optimizing collection conversions) on code paths where performance is heavily dominated by much larger operations (like matrix copies).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant