Skip to content

perf: faster, lower-memory training, inference and DE; bug fixes and dead-code cleanup - #4138

Open
ori-kron-wis wants to merge 25 commits into
mainfrom
Ori-perf-audit-fixes
Open

ori-kron-wis wants to merge 25 commits into
mainfrom
Ori-perf-audit-fixes

Conversation

@ori-kron-wis

Copy link
Copy Markdown
Collaborator

No description provided.

ori-kron-wis and others added 23 commits December 1, 2026 17:21
Adds tests for the data/dataloaders changes in e31a32e:
- AnnTorchDataset: unsupported data type now raises; non-CSR sparse
  converted to CSR once without mutating adata; covariate DataFrame cache
  invalidated when keys_and_dtypes changes
- ConcatDataLoader: shorter loader re-iterated, not cached; empty loader
  does not loop forever
- SemiSupervisedDataLoader: single-pass label grouping matches the old
  per-label np.where output exactly
- TileDB obs key join matches the old row-wise join
- opt-in ChunkShuffleSampler for backed AnnData

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- _iter_posterior_samples runs the encoder once with n_samples and decodes
  in bounded chunks; used by state assignment, latent time, velocity,
  expression fit and gene likelihood (expression fit / gene likelihood
  reuse the mixture distributions from generative instead of a second
  get_px call)
- get_directional_uncertainty: per-minibatch torch statistics on device
  instead of one joblib task per cell; runs under inference_mode.
  n_jobs kept in the signature, now unused. Also fixes a crash with
  gene_list (clip used unmasked spliced values)
- get_permutation_scores: one t-test per cell type over all genes; one
  AnnData copy for both shuffled layers, same numpy random stream
- velo_steady: collapse two identical branches (both zeros_like), no
  behaviour change; disabled formulas left as comments for maintainers

3000 cells x 2000 genes, 50 samples: directional uncertainty 19.7 s /
3.65 GB host -> 0.60 s / 0.01 GB host; permutation scores 6.37 -> 0.75 s.
RNG stream changes when n_samples > 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
scale(batch_key=...) writes each batch's result into one preallocated
array instead of copying, concatenating and reindexing the AnnData;
mask_markers uses views. Output identical.

1M cells x 30 markers: 6.8 s / +1.67 GB -> 0.31 s / +0.26 GB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
get_normalized_expression delegates to a private helper taking
expression_types; salient-only and specific-expression methods skip the
unused decoder branch. Public signatures and outputs unchanged.
Also fixes AttributeError in get_specific_normalized_expression with
indices_to_return_salient and adata=None.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MrVI (35 tests): sampled/normalised distances on CUDA, use_vmap=False
sampled path, OOM message only for real OOM, string-dtype design matrix,
outlier pairs on small data; equivalence with old distance, per-sample
inference, mixture log-prob and grouped-reduction formulas; seeded
equal-in-distribution checks for counterfactuals and DE; DE without
autograd.
VIVS (3 tests): gene correlations match old outer-product formula;
chunked vmap matches unchunked vmap and the loop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- epoch-end metric accumulation gives history identical (check_exact)
  to per-step logging for SCVI (with/without validation, plateau +
  early stopping), SCANVI and TOTALVI (incl. LR scheduler on elbo_train);
  only kl_weight logged from steps; on_step=True path unchanged
- TOTALVAE protein mask lookup table equals the per-panel loop bitwise,
  loss unchanged, unstackable-mask fallback, LogNormal constants,
  dispersions unchanged for all modes

Code under test landed in e31a32e.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Completes the model-level work started in e31a32e:
- get_marginal_ll: several MC samples per pass only on CUDA and only for
  modules whose marginal_ll/forward/inference/generative/loss are VAE's
  own (SCVI, LDVAE); scAR, SCANVI, AutoZI, CPU and explicit user values
  keep 1. Fixes test_scar / test_annbatch_setup_scar shape mismatch.
  Mean with return_mean=True now weighted by minibatch size (bug fix).
- transform_batch lists: encoder once per minibatch, decoder outputs
  accumulated on device (old path kept for minified models, importance
  weights and modules overriding forward)
- raw count statistics as weighted column sums of the full matrix
  (handles explicit zeros, repeated indices); one-pass per-group cache
  for annbatch DE raw statistics
- minification copies annotations only (AnnData and MuData)
- TOTALVI library_size applied once, not once per transform batch (bug)

RNG stream changes for transform-batch lists and, on CUDA, for SCVI /
LDVAE marginal LL. Tests compare old vs new statistically there and
exactly elsewhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Drop zero-reference helpers (_convert_mean_disp_to_counts_logits,
save_cluster_xlsx, densify, simple_reciprocal), unused constants and type
aliases, write-only attributes (MrVI backend, _da_log_probs,
MULTIVAE.n_modalities, CellAssign shrinkage), an unused AutoZI library
parameter computation, unused imports, a self-assignment, redundant pass
statements and commented-out code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…sphinx

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Saved models and legacy dataset stubs that no test, loader or workflow
reads (about 9 MB).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…l.read_mudata

TOTALVAE.get_sample_dispersion had no callers and could not run: it passed
a label argument inference() does not take and read px_/py_ keys that only
generative() returns. HubModel.read_mudata read the .h5mu file with
anndata.read_h5ad; it now uses mudata.read_h5mu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Prior, GaussianPrior, MogPrior and VampPrior are not used by any model
(SysVI ships its own copy). Instantiating them now emits a
DeprecationWarning announcing removal in v1.6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…mpy conversion

- One ParamReprMixin replaces eight identical __repr__ methods in
  scvi.distributions.
- SemiSupervisedAdversarialTrainingPlan reuses
  AdversarialTrainingPlan.loss_adversarial_classifier instead of a copy.
- SCAR's ambient profile uses the shared _as_numpy_array helper.

Behaviour is unchanged. The two configure_optimizers copies differ (one
passes verbose=True to ReduceLROnPlateau) and are left as is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
log_fn (NB log-likelihood functions), pseudocount (cytovi
clip_lfc_factory) and importance_weighting_kwargs (methylVI
get_normalized_methylation / get_specific_normalized_methylation) never
had any effect. Passing a non-default value now emits a FutureWarning
announcing removal in v1.6; results are unchanged. log_mixture_nb no
longer forwards log_fn, and get_specific_normalized_methylation no longer
forwards the unused transform_batch/weights into
get_normalized_methylation's **kwargs, so neither warns spuriously.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…g nothing

setup_anndata has been deprecated since 1.4 and only warned, then
returned without registering anything, so the failure surfaced later and
far from its cause. It now raises NotImplementedError pointing to
MULTIVI.setup_mudata.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
get_specific_normalized_methylation accepted transform_batch but dropped
it, so batch correction in differential_methylation had no effect.
get_normalized_methylation gains transform_batch (encoder sees the
observed batch, decoder the requested one; a list averages over batches,
as in RNASeqMixin), and the specific/DE helper forwards it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Typo `self.pseudoinputs_` raised AttributeError when more than one
categorical covariate was present.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…device

Prior parameters now take device and dtype from per_batch_efficiency.
Not a behaviour change: torch already broadcasts the 0-dim CPU scalars
with accelerator tensors (checked on CUDA, values bitwise-equal); this
makes the intent explicit after a review flagged it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Regression test for get_latent_time with n_samples > 1 over several
minibatches (mean and max statistics): output is (n_cells, n_genes) with
return_mean and (n_samples, n_cells, n_genes) without. The bug existed
only in the intermediate state pushed in e31a32e.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Distribution __repr__ is shared via a plain helper assigned as
  __repr__ instead of a ParamReprMixin base class. The mixin appeared
  as an undocumented private base of 8 public distributions, giving 8
  "reference target not found" warnings, and changed their documented
  bases. Bases are now as on main; reprs unchanged.
- CHANGELOG: anndata.read_h5ad is not in anndata's intersphinx
  inventory; use a literal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test_hub_model_read_mudata failed on CUDA CI (anndata 0.13.2, mudata
0.3.8): mudata < 0.4 passes anndata 0.13's layers[None] (which backs X)
to write_elem. Filter it while writing the fixture, as
scvi.autotune._experiment._write_mudata_compat does. Checked with both
CI's and current versions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ori-kron-wis ori-kron-wis self-assigned this Dec 3, 2026
@ori-kron-wis ori-kron-wis added cuda tests Run test suite on CUDA optional tests Run optional tests on-merge: backport to 1.5.x on-merge: backport to 1.5.x labels Dec 3, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-03T14:35:27.818772Z 8810db0 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8810db0e63

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/scvi/dataloaders/_ann_dataloader.py Resolved
  - ConcatDataLoader: drop chunk_size and preload_nchunks before building
    the outer torch DataLoader. Passing them through datasplitter_kwargs
    with SCANVI raised "unexpected keyword argument 'chunk_size'".
  - METHYLVI.get_normalized_methylation: a None entry in transform_batch
    now decodes with the observed batch. After a named batch it reused
    that batch, so ["batch_1", None] decoded both as batch_1.
  - Tests for both; each fails before the fix.
  - CHANGELOG 1.5.3: add {pr}`4138` to the dead-code entries and add the
    Added / Changed / Fixed entries for the performance and bug-fix work.
@codecov

codecov Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.11917% with 147 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.12%. Comparing base (f72ce50) to head (1f375bc).

Files with missing lines Patch % Lines
src/scvi/dataloaders/_custom_dataloaders.py 25.00% 24 Missing ⚠️
src/scvi/external/velovi/_model.py 85.61% 20 Missing ⚠️
src/scvi/train/_trainingplans.py 87.61% 14 Missing ⚠️
src/scvi/external/mrvi/_model.py 93.08% 13 Missing ⚠️
src/scvi/model/_utils.py 91.09% 13 Missing ⚠️
src/scvi/criticism/_ppc.py 82.14% 10 Missing ⚠️
src/scvi/model/utils/_annbatch_de_core.py 84.74% 9 Missing ⚠️
src/scvi/model/_totalvi.py 85.71% 7 Missing ⚠️
src/scvi/external/mrvi/_module.py 81.81% 6 Missing ⚠️
src/scvi/model/base/_differential.py 73.91% 6 Missing ⚠️
... and 10 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4138      +/-   ##
==========================================
+ Coverage   89.42%   90.12%   +0.69%     
==========================================
  Files         247      247              
  Lines       24470    25115     +645     
==========================================
+ Hits        21882    22634     +752     
+ Misses       2588     2481     -107     
Flag Coverage Δ
cuda 78.96% <88.82%> (+2.60%) ⬆️
integration 78.93% <88.82%> (+2.60%) ⬆️
optional 47.13% <48.63%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/scvi/autotune/_experiment.py 86.54% <ø> (-0.07%) ⬇️
src/scvi/criticism/_constants.py 100.00% <ø> (ø)
src/scvi/data/_built_in_data/_loom.py 100.00% <ø> (ø)
src/scvi/data/_preprocessing.py 85.55% <100.00%> (+6.57%) ⬆️
src/scvi/data/_utils.py 87.86% <100.00%> (-0.07%) ⬇️
src/scvi/dataloaders/_ann_dataloader.py 97.59% <100.00%> (+3.47%) ⬆️
src/scvi/dataloaders/_concat_dataloader.py 92.50% <100.00%> (+1.87%) ⬆️
src/scvi/dataloaders/_samplers.py 100.00% <100.00%> (ø)
src/scvi/distributions/__init__.py 100.00% <ø> (ø)
src/scvi/distributions/_beta_binomial.py 97.82% <100.00%> (-0.14%) ⬇️
... and 53 more

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  On CUDA, torch.cdist and the on-device index_add_ group sums do not
  guarantee d[i, j] == d[j, i] bit-for-bit, so get_local_sample_distances
  could return matrices that scipy.spatial.distance.squareform rejects
  ("Distance matrix 'X' must be symmetric"), breaking the MrVI tutorial's
  dendrogram. Symmetrize the cdist output (zero diagonal) and the grouped
  distance sums. Tighten tests to require exact symmetry and squareform
  compatibility for all groups.

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

cuda tests Run test suite on CUDA on-merge: backport to 1.5.x on-merge: backport to 1.5.x optional tests Run optional tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant