Skill Tracer
Skills › Scientific Agent Skills › scvi-tools › workflows.md

workflows.md

188 lines · skills/scvi-tools/references/workflows.md at 5f2bc03

Open on GitHub
1# Training, persistence and reference mapping
2
3Targets scvi-tools 1.5.1. Examples are source-verified, illustrative workflows.
4Short CPU tests exercised core fitting, metric access, save/load and minification;
5GPU, distributed, large-data, query-transfer and interpretability paths were not run.
6

Training, persistence and reference mapping

Targets scvi-tools 1.5.1. Examples are source-verified, illustrative workflows. Short CPU tests exercised core fitting, metric access, save/load and minification; GPU, distributed, large-data, query-transfer and interpretability paths were not run.

Raw lines 1 to 6
7## Prepare data before registration
8
9Start with the count-preserving example in [SKILL.md](../SKILL.md). QC thresholds
10are experiment-specific. Scanpy's `seurat_v3` HVG flavor takes counts; its default
11`seurat` flavor expects log-normalized data. Never copy an unknown `.X` into a
12layer called `counts` and assume the name proves provenance. Keep full-feature
13counts separately if later gene testing needs more than the selected HVGs.
15For QC, define mitochondrial genes before `calculate_qc_metrics`, select a naming
16convention appropriate to the organism, and set `percent_top=None` for tiny feature
17panels. Current Scanpy exposes `sc.pp.scrublet`; doublet thresholds require
18capture-specific validation. Finish subsetting with `.copy()` before setup.
19Register only justified nuisance covariates. Concatenating study and sample IDs
20creates a composite category, not a hierarchical statistical model.
22```python
23scvi.model.SCVI.setup_anndata(
24 adata, layer="counts", batch_key="sequencing_batch",
26model = scvi.model.SCVI(adata, n_latent=20, n_layers=2, gene_likelihood="nb")
27model.view_anndata_setup()
28model.train(
29 max_epochs=400, batch_size=128, train_size=0.9,
30 early_stopping=True, check_val_every_n_epoch=1,
31 plan_kwargs={"lr": 1e-3},
33```
35For SCVI, optimizer parameters such as `lr` belong in `plan_kwargs` (or the 1.5
36training-plan configuration interface), not arbitrary Lightning Trainer kwargs.
37Some specialized models define `lr` directly; check that model's signature.
38`view_anndata_setup()` is an instance method.

Prepare data before registration

Start with the count-preserving example in SKILL.md. QC thresholds are experiment-specific. Scanpy's seurat_v3 HVG flavor takes counts; its default seurat flavor expects log-normalized data. Never copy an unknown .X into a layer called counts and assume the name proves provenance. Keep full-feature counts separately if later gene testing needs more than the selected HVGs.

For QC, define mitochondrial genes before calculate_qc_metrics, select a naming convention appropriate to the organism, and set percent_top=None for tiny feature panels. Current Scanpy exposes sc.pp.scrublet; doublet thresholds require capture-specific validation. Finish subsetting with .copy() before setup. Register only justified nuisance covariates. Concatenating study and sample IDs creates a composite category, not a hierarchical statistical model.

scvi.model.SCVI.setup_anndata(
    adata, layer="counts", batch_key="sequencing_batch",
)
model = scvi.model.SCVI(adata, n_latent=20, n_layers=2, gene_likelihood="nb")
model.view_anndata_setup()
model.train(
    max_epochs=400, batch_size=128, train_size=0.9,
    early_stopping=True, check_val_every_n_epoch=1,
    plan_kwargs={"lr": 1e-3},
)

For SCVI, optimizer parameters such as lr belong in plan_kwargs (or the 1.5 training-plan configuration interface), not arbitrary Lightning Trainer kwargs. Some specialized models define lr directly; check that model's signature. view_anndata_setup() is an instance method.

Raw lines 7 to 39
40## Training diagnostics and model selection
42```python
43# These logged metrics are losses: lower is better.
44train_loss = model.history["elbo_train"]
45validation_loss = model.history["elbo_validation"]
46last_validation_loss = float(validation_loss.iloc[-1, 0])
47# This method returns the ELBO with the opposite sign: higher is better.
48heldout_elbo = float(model.get_elbo(indices=model.validation_indices))
49```
51Use identical train/validation splits and feature universes when tuning. Random
52cell splits share donors and do not estimate performance on new donors; use an
53external biological-sample split for that estimand. If an Optuna study minimizes
54`elbo_validation`, its direction must be `minimize`; use `maximize` only for the
55actual `get_elbo()` value. A history DataFrame is indexed with `.iloc`, not `[-1]`.
56Record the selected epoch and whether final or best weights were evaluated.
58```python
59from scvi.train import SaveCheckpoint
61model.train(
62 max_epochs=400, early_stopping=True, check_val_every_n_epoch=1,
63 enable_checkpointing=True,
64 callbacks=[SaveCheckpoint(
65 monitor="elbo_validation", mode="min", load_best_on_end=True,
66 )],
68```
70Validation must actually run and log the monitored key. The default scvi logger
71is an in-memory `SimpleLogger`; `logger=False` removes history and can conflict
72with TOTALVI's learning-rate monitor. Repeating `train` on an
73already trained model continues fitting; create a fresh model for each candidate.
74Report seeds, model parameters, split definition, stopping rule, package versions
75and hardware. A short fit with finite loss proves only mechanics.

Training diagnostics and model selection

# These logged metrics are losses: lower is better.
train_loss = model.history["elbo_train"]
validation_loss = model.history["elbo_validation"]
last_validation_loss = float(validation_loss.iloc[-1, 0])
# This method returns the ELBO with the opposite sign: higher is better.
heldout_elbo = float(model.get_elbo(indices=model.validation_indices))

Use identical train/validation splits and feature universes when tuning. Random cell splits share donors and do not estimate performance on new donors; use an external biological-sample split for that estimand. If an Optuna study minimizes elbo_validation, its direction must be minimize; use maximize only for the actual get_elbo() value. A history DataFrame is indexed with .iloc, not [-1]. Record the selected epoch and whether final or best weights were evaluated.

from scvi.train import SaveCheckpoint

model.train(
    max_epochs=400, early_stopping=True, check_val_every_n_epoch=1,
    enable_checkpointing=True,
    callbacks=[SaveCheckpoint(
        monitor="elbo_validation", mode="min", load_best_on_end=True,
    )],
)

Validation must actually run and log the monitored key. The default scvi logger is an in-memory SimpleLogger; logger=False removes history and can conflict with TOTALVI's learning-rate monitor. Repeating train on an already trained model continues fitting; create a fresh model for each candidate. Report seeds, model parameters, split definition, stopping rule, package versions and hardware. A short fit with finite loss proves only mechanics.

Raw lines 40 to 76
77## Save and reload
79```python
80model.save("scvi_model", save_anndata=True)
81restored = scvi.model.SCVI.load("scvi_model")
82# Alternatively save_anndata=False (the default), then supply the matching data:
83model.save("weights_and_registry")
84restored = scvi.model.SCVI.load("weights_and_registry", adata=adata)
85```
87Use a new directory for each model unless replacement is intended. Keep the exact
88registered genes/order, counts, batch encodings and covariates. A saved inference
89model is not automatically a full optimizer/scheduler checkpoint for faithful
90training resume. Load only trusted artifacts and record scvi/PyTorch versions.

Save and reload

model.save("scvi_model", save_anndata=True)
restored = scvi.model.SCVI.load("scvi_model")
# Alternatively save_anndata=False (the default), then supply the matching data:
model.save("weights_and_registry")
restored = scvi.model.SCVI.load("weights_and_registry", adata=adata)

Use a new directory for each model unless replacement is intended. Keep the exact registered genes/order, counts, batch encodings and covariates. A saved inference model is not automatically a full optimizer/scheduler checkpoint for faithful training resume. Load only trusted artifacts and record scvi/PyTorch versions.

Raw lines 77 to 91
92## Query-to-reference mapping (scArches)
94Assumes a trained, saved reference and query counts using compatible gene IDs and
95measurement units. Inspect reference coverage and duplicates before preparation.
97```python
98scvi.model.SCVI.prepare_query_anndata(query_adata, "scvi_model")
99query_model = scvi.model.SCVI.load_query_data(query_adata, "scvi_model")
100query_model.train(max_epochs=200, plan_kwargs={"weight_decay": 0.0})
101query_adata.obsm["X_scVI"] = query_model.get_latent_representation()
102```
104`prepare_query_anndata` pads/reorders features to the reference. Report missing
105features and stop when coverage is scientifically inadequate; zero padding cannot
106recover unmeasured genes. `load_query_data` transfers the registry and performs
107model-specific freezing. Do not manually call query setup with guessed categories
108or silently train a joint reference model instead. For labels, prefer a validated
109SCANVI reference or evaluate a classifier on reference embeddings with rejection
110for unsupported cell types. KNN labels are predictions, not verified identities.

Query-to-reference mapping (scArches)

Assumes a trained, saved reference and query counts using compatible gene IDs and measurement units. Inspect reference coverage and duplicates before preparation.

scvi.model.SCVI.prepare_query_anndata(query_adata, "scvi_model")
query_model = scvi.model.SCVI.load_query_data(query_adata, "scvi_model")
query_model.train(max_epochs=200, plan_kwargs={"weight_decay": 0.0})
query_adata.obsm["X_scVI"] = query_model.get_latent_representation()

prepare_query_anndata pads/reorders features to the reference. Report missing features and stop when coverage is scientifically inadequate; zero padding cannot recover unmeasured genes. load_query_data transfers the registry and performs model-specific freezing. Do not manually call query setup with guessed categories or silently train a joint reference model instead. For labels, prefer a validated SCANVI reference or evaluate a classifier on reference embeddings with rejection for unsupported cell types. KNN labels are predictions, not verified identities.

Raw lines 92 to 111
112## Minification for supported RNA models
114Minification stores posterior parameters and can omit counts. It is not weight
115quantization and does not shrink every model. Preserve the full count dataset and
116model first. The method replaces `model.adata` and returns `None`:
118```python
119qzm, qzv = model.get_latent_representation(return_dist=True)
120model.adata.obsm["X_latent_qzm"] = qzm
121model.adata.obsm["X_latent_qzv"] = qzv
122model.minify_adata()
123model.save("minified_scvi", save_anndata=True)
124mini_model = scvi.model.SCVI.load("minified_scvi")
125```
127Do not pass `adata` as the first positional argument; that argument is a
128minification-type string. Default minification removes counts, so full training,
129raw-count statistics and methods needing counts may be unavailable. Verify the
130specific downstream method before replacing a full-data artifact.

Minification for supported RNA models

Minification stores posterior parameters and can omit counts. It is not weight quantization and does not shrink every model. Preserve the full count dataset and model first. The method replaces model.adata and returns None:

qzm, qzv = model.get_latent_representation(return_dist=True)
model.adata.obsm["X_latent_qzm"] = qzm
model.adata.obsm["X_latent_qzv"] = qzv
model.minify_adata()
model.save("minified_scvi", save_anndata=True)
mini_model = scvi.model.SCVI.load("minified_scvi")

Do not pass adata as the first positional argument; that argument is a minification-type string. Default minification removes counts, so full training, raw-count statistics and methods needing counts may be unavailable. Verify the specific downstream method before replacing a full-data artifact.

Raw lines 112 to 131
132## Data loading and memory
134```python
135from scvi.dataloaders import AnnDataLoader
136loader = AnnDataLoader(model.adata_manager, batch_size=128, shuffle=False)
137for tensors in loader:
138 # A dictionary of registered tensors, for a custom model/training loop.
139 break
140```
142`AnnDataLoader` takes an `AnnDataManager`, not an unregistered AnnData object,
143and lives in `scvi.dataloaders`, not `scvi.data`. Backed H5AD can support certain
144access patterns, but a model/setup/preprocessing step can still materialize arrays.
145A backed flag is not an out-of-core guarantee. For atlas-scale workloads, use the
146current Annbatch/AnnCollection/Census/Lamin data-loader tutorials and the relevant
147optional dependencies, then measure actual resident memory and I/O.
149Normalized expression, feature correlation and posterior samples may produce large
150dense arrays. Restrict `gene_list`, `indices`, sample counts and batch size. Do not
151assign a selected-gene matrix into a full-shape `adata.layers` slot.

Data loading and memory

from scvi.dataloaders import AnnDataLoader
loader = AnnDataLoader(model.adata_manager, batch_size=128, shuffle=False)
for tensors in loader:
    # A dictionary of registered tensors, for a custom model/training loop.
    break

AnnDataLoader takes an AnnDataManager, not an unregistered AnnData object, and lives in scvi.dataloaders, not scvi.data. Backed H5AD can support certain access patterns, but a model/setup/preprocessing step can still materialize arrays. A backed flag is not an out-of-core guarantee. For atlas-scale workloads, use the current Annbatch/AnnCollection/Census/Lamin data-loader tutorials and the relevant optional dependencies, then measure actual resident memory and I/O.

Normalized expression, feature correlation and posterior samples may produce large dense arrays. Restrict gene_list, indices, sample counts and batch size. Do not assign a selected-gene matrix into a full-shape adata.layers slot.

Raw lines 132 to 152
153## Hardware and failure diagnosis
155```python
156model.train(accelerator="cpu", devices=1) # Explicit reproducible smoke backend.
157# Hardware-dependent examples, not exercised in this refresh:
158# model.train(accelerator="gpu", devices=1, precision="16-mixed")
159# model.train(accelerator="gpu", devices=2)
160```
162`accelerator='auto'` selects a supported backend; inspect the training logs.
163CUDA and MPS availability and supported probability kernels depend on the installed
164PyTorch build. Version 1.5.1 expands MPS distribution support. Multi-GPU training
165needs a compatible launch context and distributed strategy; do not infer correctness
166from a single-device run. Mixed precision can destabilize count-distribution losses;
167compare finite loss and outputs before using it broadly.
169For NaNs, inspect the **registered** layer for finite, nonnegative, appropriately
170scaled input, positive library sizes, valid categories and missing values. Preserve
171raw counts for count models. Reduce learning rate through the correct training-plan
172argument and verify validation loss. More layers/latent dimensions or stronger
173covariate injection are hypotheses to evaluate, not guaranteed integration fixes.
174`torch.cuda.empty_cache()` cannot free live tensors.
176For interpretability, do not feed `model.module` directly to `shap.DeepExplainer`
177with arbitrary matrices: scvi modules expect structured registered tensors and
178produce structured outputs. SCANVI exposes `shap_predict` and integrated-gradient
179classification options with an `interpretability` extra; define the prediction
180being explained and follow its official tutorial. Generative correlations are
181model-derived associations, not regulatory causality.
183Sources: [training mixins](https://github.com/scverse/scvi-tools/blob/1.5.1/src/scvi/model/base/_training_mixin.py),
184[training metrics](https://github.com/scverse/scvi-tools/blob/1.5.1/src/scvi/train/_metrics.py),
185[minification source](https://github.com/scverse/scvi-tools/blob/1.5.1/src/scvi/model/base/_base_model.py),
186[query mapping](https://github.com/scverse/scvi-tools/blob/1.5.1/src/scvi/model/base/_archesmixin.py),
187[AnnDataLoader](https://docs.scvi-tools.org/en/stable/api/reference/scvi.dataloaders.AnnDataLoader.html),
188[SCVI API](https://docs.scvi-tools.org/en/stable/api/reference/scvi.model.SCVI.html).

Hardware and failure diagnosis

model.train(accelerator="cpu", devices=1)  # Explicit reproducible smoke backend.
# Hardware-dependent examples, not exercised in this refresh:
# model.train(accelerator="gpu", devices=1, precision="16-mixed")
# model.train(accelerator="gpu", devices=2)

accelerator='auto' selects a supported backend; inspect the training logs. CUDA and MPS availability and supported probability kernels depend on the installed PyTorch build. Version 1.5.1 expands MPS distribution support. Multi-GPU training needs a compatible launch context and distributed strategy; do not infer correctness from a single-device run. Mixed precision can destabilize count-distribution losses; compare finite loss and outputs before using it broadly.

For NaNs, inspect the registered layer for finite, nonnegative, appropriately scaled input, positive library sizes, valid categories and missing values. Preserve raw counts for count models. Reduce learning rate through the correct training-plan argument and verify validation loss. More layers/latent dimensions or stronger covariate injection are hypotheses to evaluate, not guaranteed integration fixes. torch.cuda.empty_cache() cannot free live tensors.

For interpretability, do not feed model.module directly to shap.DeepExplainer with arbitrary matrices: scvi modules expect structured registered tensors and produce structured outputs. SCANVI exposes shap_predict and integrated-gradient classification options with an interpretability extra; define the prediction being explained and follow its official tutorial. Generative correlations are model-derived associations, not regulatory causality.

Sources: training mixins, training metrics, minification source, query mapping, AnnDataLoader, SCVI API.

Raw lines 153 to 188