Repository navigation
Conversation
…out densifying Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LKxc9GKLwnyeV2jaZBxH9N
There was a problem hiding this comment.
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.
| 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() |
There was a problem hiding this comment.
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] += ....
| 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
- 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).
PerturbationAnndataPair._bulk_anndataandClusteringAgreement._centroid_annconvert a sparse expression matrix to a dense cells × genes array before averaging cells per perturbation, and_bulk_anndatacopies 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 computingmaeanddiscrimination_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; forClusteringAgreementon 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, andMetricsEvaluator(..., 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 andruff format --checkpass, andty checkreports the same 7 diagnostics as on main.🤖 Generated with Claude Code
https://claude.ai/code/session_01LKxc9GKLwnyeV2jaZBxH9N