Skip to content

Match the guide assignment mixture model and parameters to pertpy - #852

Merged
Intron7 merged 14 commits into
mainfrom
guide-assignment-pertpy-parity
Oct 29, 2026
Merged

Intron7 merged 14 commits into
mainfrom
guide-assignment-pertpy-parity

Conversation

@Zethson

@Zethson Zethson commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

assign_mixture_model now 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, seed replace max_iter, tol and posterior_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_guide no longer densifies sparse input and assign_by_threshold returns 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:

Dataset Cells x guides PR = pertpy (thresholds) PR = crispat converged PR = crispat default (500 steps) Previous rsc kernel = pertpy Cell-guide Jaccard PR vs pertpy Cell-guide Jaccard previous rsc vs pertpy
Papalexi 2021 (ECCITE-seq, CRISPRko) 20,729 x 111 111/111 109/111 91/111 78/111 1 0.3573
Schraivogel 2020 (TAP-seq, CRISPRi) 21,977 x 86 84/86 86/86 85/86 66/86 0.9996 0.9982
Gasperini 2019 subset (high MOI, CRISPRi) 45,919 x 95 95/95 94/95 92/95 62/95 1 0.9973
Replogle 2020 exp. 6 (direct capture, dual guide) 75,348 x 54 54/54 54/54 15/54 39/54 1 0.3375
Synthetic (11 regimes x 3 guides) 20,000 x 33 33/33 30/33 18/33 20/33 1 0.5469

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_model call 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:

Dataset Cells x guides This PR (GPU) Previous kernel 0.16.0 (GPU) pertpy main (CPU) crispat (1 process) crispat (32 processes)
Papalexi 2021 20,729 x 111 144 ms (8 ms) 38 ms (12 ms) 3.90 s (112 ms) 2 min 6.50 s
Schraivogel 2020 21,977 x 86 140 ms (8 ms) 29 ms (6 ms) 1.99 s (73 ms) 2 min 5.10 s
Gasperini 2019 subset 45,919 x 95 141 ms (8 ms) 37 ms (13 ms) 1.52 s (492 ms) 2 min 5.30 s
Replogle 2020 exp. 6 75,348 x 54 144 ms (12 ms) 49 ms (26 ms) 4.45 s (608 ms) 2 min 10.0 s
Synthetic (11 regimes) 20,000 x 33 144 ms (11 ms) 30 ms (6 ms) 3.99 s (192 ms) 1 min 4.10 s
Synthetic, low MOI 200,000 x 1,000 133 ms (15 ms) 2.15 s (389 ms) 6.29 s (4.41 s) not run not run
Synthetic, MOI 10 500,000 x 2,000 175 ms (39 ms) 298 ms (167 ms) 8.55 s (6.78 s) not run not run
Synthetic, low MOI 1.0M x 5,000 151 ms (30 ms) out of memory 20.1 s (18.2 s) not run not run
Synthetic, genome-wide scale 2.5M x 10,000 169 ms (49 ms) out of memory 4.03 s (2.19 s) not run not run

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.

@Zethson
Zethson force-pushed the guide-assignment-pertpy-parity branch 2 times, most recently from d7077f5 to 62ab04d Compare October 20, 2026 12:48
@Zethson
Zethson force-pushed the guide-assignment-pertpy-parity branch from 62ab04d to 211f824 Compare October 20, 2026 13:05
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.
@Zethson
Zethson force-pushed the guide-assignment-pertpy-parity branch from 211f824 to daea6a1 Compare October 20, 2026 14:57
@codecov-commenter

codecov-commenter commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.66355% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.70%. Comparing base (6ce9114) to head (7ed9868).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
.../rapids_singlecell/pertpy_gpu/_guide_assignment.py 97.66% 5 Missing ⚠️
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     
Files with missing lines Coverage Δ
src/rapids_singlecell/_cuda/__init__.py 81.08% <ø> (ø)
.../rapids_singlecell/pertpy_gpu/_guide_assignment.py 97.84% <97.66%> (+23.88%) ⬆️

... and 1 file with indirect coverage changes

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]>
@Intron7

Intron7 commented Oct 21, 2026

Copy link
Copy Markdown
Member

Pushed 7ed9868 on top of 6925a63: read guide counts in their own layout and match pertpy main's edge cases.

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.

assign_mixture_model, warm time per call and extra GPU memory, RTX PRO 6000 Blackwell (CSR input; CSC is within a few ms). The last column is the kernel version just before the edge-case fixes; I will post final numbers, including Papalexi tiled to 10M cells and the 7.9M-cell X-Atlas/Orion guide calls, once those runs finish.

Dataset pertpy main (CPU) pertpy main (GPU) 6925a63 this commit
Papalexi 20.7k x 111 258 ms 144 ms 11 ms (115 MB) 8 ms (18 MB)
Synthetic 100k x 500 1.34 s 698 ms 27 ms (50 MB) 25 ms (22 MB)
Synthetic 1M x 5,000 10.7 s 4.21 s 178 ms (996 MB) 167 ms (139 MB)
Synthetic 2.5M x 10,000 61 s 2.97 s 138 ms (5.0 GB) 64 ms (339 MB)

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.

Zethson and others added 2 commits October 29, 2026 12:13
…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]>
Zethson added a commit to scverse/cupy-stubs that referenced this pull request Oct 29, 2026
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.
@Intron7 Intron7 added the skip-gpu-ci Report GPU CI as passed without running it; for PRs that cannot affect GPU code label Oct 29, 2026
@Intron7
Intron7 enabled auto-merge (squash) October 29, 2026 13:42
@Intron7
Intron7 disabled auto-merge October 29, 2026 13:42
@Intron7
Intron7 merged commit b1de455 into main Oct 29, 2026
24 of 27 checks passed
@Intron7
Intron7 deleted the guide-assignment-pertpy-parity branch October 29, 2026 17:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-gpu-ci Report GPU CI as passed without running it; for PRs that cannot affect GPU code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants