Repository navigation
Match the guide assignment mixture model and parameters to pertpy - #852
Conversation
d7077f5 to
62ab04d
Compare
62ab04d to
211f824
Compare
The CUDA EM kernel fitted the Poisson-Gaussian mixture with approximate M-steps for the Poisson rate and the Gaussian scale, a single start, a 90 iteration cap and a Gaussian weight clipped to at least 1 %, so its thresholds differed from pertpy's and crispat's converged MAP estimates. The mixture is now fit by the same multi-start MAP-EM as pertpy on the distinct count values of every guide, with CuPy over all guides and starts, discarding label-switched and degenerate optima. On Papalexi 2021 the thresholds equal pertpy's on all 111 guides and the fit takes 1.5 s on an RTX PRO 6000. `assign_mixture_model` takes pertpy's parameters (`model`, `output_layer`, `show_progress`, `n_iter`, `n_init_seeds`, `seed`) instead of `max_iter`, `tol` and `posterior_threshold`, writes the binary assignment matrix to a layer, stores `final_loss`, and emits pertpy's warnings. `assign_to_max_guide` no longer densifies sparse input and `assign_by_threshold` returns a canonical matrix without stored zeros. The CUDA kernel is removed; the wheel builds without it.
211f824 to
daea6a1
Compare
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #852 +/- ##
==========================================
+ Coverage 90.32% 90.70% +0.38%
==========================================
Files 126 126
Lines 12948 12988 +40
==========================================
+ Hits 11695 11781 +86
+ Misses 1253 1207 -46
|
The CuPy port launched about 25 small kernels per EM iteration from Python, so the fit was launch-bound: 0.4 s warm on Papalexi against 12 ms for the previous kernel and 0.11 s for pertpy's JAX run on the CPU, and 8 s at 2.5M cells x 10k guides. One block per guide and start now runs the whole multi-start MAP-EM with exact M-steps, two block reductions per iteration and the convergence rule of pertpy, which takes 0.8 ms on Papalexi and 10 ms for 10k guides. The quantile-split starts are computed once for all guides, while the prior-median starts keep their per-chunk seeds so the fits are unchanged. Thresholds stay identical to pertpy main on Papalexi (111/111), Schraivogel (86/86), Gasperini (95/95), Replogle exp. 6 (54/54) and the synthetic set (33/33). The threshold scan runs on the GPU as a segmented scan over counts, and per-cell labels are built from category codes instead of a pandas groupby join, which removes the 0.1 to 0.2 s host-side tail on screens with millions of cells or many dual-guide cells. assign_mixture_model now takes 35 ms on Papalexi and 0.1 s for 2.5M cells x 10k guides after warm-up, where the previous kernel runs out of memory because it densifies the counts.
After the fused EM kernel the fit itself took under a millisecond, but assign_mixture_model still spent 35 ms on Papalexi in CuPy and Python around it: nine chunk launches with their own random generators and selections, about a hundred small CuPy ops for the quantile-split starts, a CuPy threshold scan, a COO sort for the binary matrix and pandas string handling for the labels. The quantile-split starts and the prior medians of the standard normal draws are now computed inside the EM kernel, a second kernel keeps the admissible start with the lowest loss and scans the counts for the threshold, so the fit is two launches and one device-to-host copy. The prior draws come from one generator seeded with `seed` for all guides instead of one generator per chunk, which was the cost of nine cuRAND initialisations and is also more seed-robust. The binary matrix reuses the CSC order of the counts, multi-guide labels are uniquified by a lexsort on the GPU and the categories are built without hashing when guide names cannot collide with the labels. Warm calls take 8 ms on Papalexi, Schraivogel and Gasperini, 12 ms on Replogle exp. 6 and 49 ms for 2.5M cells x 10k guides, against 12, 6, 13, 26 ms and out of memory for the previous kernel. Thresholds agree with pertpy main on 18,373 of 18,379 guides over nine datasets; the six others have a Gaussian posterior of 0.5 at the threshold count, and the two Schraivogel non-targeting guides among them agree with crispat run to convergence.
assign_mixture_model, assign_by_threshold and assign_to_max_guide now read CSR, CSC and dense counts with format-specific nanobind kernels (value histogram, threshold assignment, max guide), templated on float/double values and int32/int64 indices, so the count matrix is never converted, densified or copied; only COO becomes CSR. The EM fit and threshold selection run as one binding, and the mixture wrapper module is folded into _guide_assignment.py. The EM fit accumulates the Poisson sums per value as pertpy does, instead of as differences of large float32 totals. Behaviour follows pertpy main: labels write "multiple" last and use pertpy's sorted categories, and duplicate labels no longer crash; on sparse input assign_to_max_guide only uses stored counts and treats NaN as the maximum; thresholds are compared in the data's precision; duplicate stored entries are summed; learning_rate is accepted as deprecated. Bugs fixed: negative counts next to NaN are rejected, NaN counts no longer crash, empty or guide-less input works, adata.X is never modified, and label building no longer slows with the most-assigned cell. New tests run every input layout through tiny histogram and chunk sizes, so the overflow-buffer and chunked paths are exercised, and cover NaN, ties, empty input and label edge cases checked against pertpy's logic. Signed-off-by: Intron7 <[email protected]>
|
Pushed 7ed9868 on top of 6925a63: read guide counts in their own layout and match pertpy main's edge cases.
Behaviour follows pertpy main: labels write "multiple" last and use pertpy's sorted categories, and duplicate labels no longer crash; on sparse input Bugs fixed: negative counts next to NaN are rejected, NaN counts no longer crash, empty or guide-less input works, New tests run every input layout through tiny histogram and chunk sizes, so the overflow-buffer and chunked paths are exercised, and cover NaN, ties, empty input and label edge cases checked against pertpy's logic.
Thresholds agree with pertpy main on 110/111 Papalexi guides and on 497/500 and 4969/5000 synthetic guides; the remaining differences are near-ties and one near-empty Papalexi guide (SPI1g1) where the random prior starts differ. |
…py-parity # Conflicts: # docs/release-notes/0.19.0.md # src/rapids_singlecell/pertpy_gpu/_guide_assignment.py # tests/pertpy/test_guide_assignment.py
…Python path Correctness: sparse input with mixed index dtypes or strided arrays is rebuilt through the cupyx constructor instead of copy(), which raised; assign_to_max_guide compares sparse counts in the data's precision, as the dense path does, and handles dense input without guides; fit_poisson_gauss checks its array shapes and the number of starts (n_init_seeds above the grid limit is a ValueError); the threshold scan uses 64-bit counts; X_to_GPU treats cupyx COO matrices as already on the GPU instead of warning; the nb_require message no longer names rank_genes_groups. Speed: wide guide libraries get up to 2^20 column blocks, so one long column is no longer serialised in a single block, and the Newton solvers stop at their fixed point (bit-identical, ~25% less fit time). Slimming: cp.unique/bincount derive the distinct values; both max-guide paths write order keys that are decoded on the host, dropping the finish kernel; kernel layout constants are read from the module; the duplicate dense-vs-sparse test is folded into test_layouts_match, which now also covers CSC with int64 indices and float64 data and mixed index dtypes. Signed-off-by: Intron7 <[email protected]>
Used by the current guide assignment in scverse/rapids-singlecell#852.
Types the dense, CSR or CSC helpers explicitly (GPU_ARRAY_TYPE now includes COO, which they never receive), rebuilds strided sparse input from an explicit (data, indices, indptr) tuple, keeps the GPU and host copies of codes and inverse in separate variables, passes the categories as an Index as pandas-stubs expects, and lets _format_guides take the array it is given. With the stubs from scverse/cupy-stubs#10 the module type checks, so once they are released it can leave the mypy ratchet.
Drops the comments that walk through what a kernel or helper does and cuts the rest to one line each.
It already converts CuPy dense and sparse input to NumPy, so the local _dense helper is redundant.
Signed-off-by: Intron7 <[email protected]>
assign_mixture_modelnow fits the Poisson-Gaussian mixture with the same multi-start MAP-EM as pertpy (scverse/pertpy#1172) on the distinct count values of every guide in fused CUDA kernels with a block per guide and start, takes pertpy's parameters (model,output_layer,show_progress,n_iter,n_init_seeds,seedreplacemax_iter,tolandposterior_threshold) and writes the binary assignment matrix to a layer; the previous EM kernel, whose approximate single-start fit swapped the mixture components on 13 Papalexi guides and assigned every expressing cell to them, is replaced.assign_to_max_guideno longer densifies sparse input andassign_by_thresholdreturns a canonical matrix without stored zeros.Agreement of per-guide thresholds and cell-guide assignments with pertpy main, with crispat's
ga_poisson_gauss(default 500 SVI steps, and run to convergence with 5000 steps) and with the previous kernel (0.16.0), on four public screens with raw guide counts and one synthetic set:The remaining differences to converged crispat are guides where crispat's SVI converges to a singular solution (a Gaussian collapsed onto one count value) that both pertpy and this PR reject, and one flat two-optima synthetic guide where the random prior starts differ between CuPy and JAX. Thresholds agree with pertpy main on 18,373 of 18,379 guides over these five datasets and four synthetic screens of up to 2.5M cells x 10,000 guides; the six others have a Gaussian posterior of exactly 0.5 at the threshold count, so the result depends on the rounding of the EM path, and the two Schraivogel non-targeting guides among them agree with crispat run to convergence.
Runtime of one
assign_mixture_modelcall with the counts already on the GPU, first call in a fresh process and in parentheses a second call, on an RTX PRO 6000 Blackwell and a 32-core Threadripper PRO 7975WX; pertpy runs JAX on the CPU and crispat its default 500 SVI steps:The first call includes about 130 ms of CUDA and CuPy warm-up. The previous kernel densifies the count matrix, so it runs out of memory beyond 1M cells, and its single-digit milliseconds on small screens come from 90 approximate single-start iterations that give the wrong components on 13 Papalexi guides.