Model hyperparameter tuning with scVI#

Warning

scvi.autotune development is still in progress. The API is subject to change.

Finding an effective set of model hyperparameters (e.g. learning rate, number of hidden layers, etc.) is an important component in training a model as its performance can be highly dependent on these non-trainable parameters. Manually tuning a model often involves picking a set of hyperparameters to search over and then evaluating different configurations over a validation set for a desired metric. This process can be time consuming and can require some prior intuition about a model and dataset pair, which is not always feasible.

In this tutorial, we show how to use scvi’s autotune module, which allows us to automatically find a good set of model hyperparameters using Ray Tune. We will use SCVI and a subsample of the heart cell atlas for the task of batch correction, but the principles outlined here can be applied to any model and dataset. In particular, we will go through the following steps:

  1. Installing required packages

  2. Loading and preprocessing the dataset

  3. Defining the tuner and discovering hyperparameters

  4. Running the tuner

  5. Comparing latent spaces

  6. Optional: Monitoring progress with Tensorboard

  7. Optional: Tuning over integration metrics with scib-metrics

Installing required packages#

Note

Running the following cell will install tutorial dependencies on Google Colab only. It will have no effect on environments other than Google Colab.

!pip install --quiet scvi-colab
from scvi_colab import install

install()
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable.It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning.

import tempfile

import ray
import scanpy as sc
import scvi
import seaborn as sns
import torch
from ray import tune
from scvi import autotune
scvi.settings.seed = 0
print("Last run with scvi-tools version:", scvi.__version__)
Last run with scvi-tools version: 1.2.0

Note

You can modify save_dir below to change where the data files for this tutorial are saved.

sc.set_figure_params(figsize=(6, 6), frameon=False)
sns.set_theme()
torch.set_float32_matmul_precision("high")
save_dir = tempfile.TemporaryDirectory()
scvi.settings.logging_dir = save_dir.name

%config InlineBackend.print_figure_kwargs={"facecolor": "w"}
%config InlineBackend.figure_format="retina"

Loading and preprocessing the dataset#

adata = scvi.data.heart_cell_atlas_subsampled(save_path=save_dir.name)
adata
INFO     Downloading file at /tmp/tmpyoqxn2or/hca_subsampled_20k.h5ad
AnnData object with n_obs × n_vars = 18641 × 26662
    obs: 'NRP', 'age_group', 'cell_source', 'cell_type', 'donor', 'gender', 'n_counts', 'n_genes', 'percent_mito', 'percent_ribo', 'region', 'sample', 'scrublet_score', 'source', 'type', 'version', 'cell_states', 'Used'
    var: 'gene_ids-Harvard-Nuclei', 'feature_types-Harvard-Nuclei', 'gene_ids-Sanger-Nuclei', 'feature_types-Sanger-Nuclei', 'gene_ids-Sanger-Cells', 'feature_types-Sanger-Cells', 'gene_ids-Sanger-CD45', 'feature_types-Sanger-CD45', 'n_counts'
    uns: 'cell_type_colors'

The only preprocessing step we will perform in this case will be to subsample the dataset for 2000 highly variable genes using scanpy for faster model training.

sc.pp.highly_variable_genes(adata, n_top_genes=2000, flavor="seurat_v3", subset=True)
adata
AnnData object with n_obs × n_vars = 18641 × 2000
    obs: 'NRP', 'age_group', 'cell_source', 'cell_type', 'donor', 'gender', 'n_counts', 'n_genes', 'percent_mito', 'percent_ribo', 'region', 'sample', 'scrublet_score', 'source', 'type', 'version', 'cell_states', 'Used'
    var: 'gene_ids-Harvard-Nuclei', 'feature_types-Harvard-Nuclei', 'gene_ids-Sanger-Nuclei', 'feature_types-Sanger-Nuclei', 'gene_ids-Sanger-Cells', 'feature_types-Sanger-Cells', 'gene_ids-Sanger-CD45', 'feature_types-Sanger-CD45', 'n_counts', 'highly_variable', 'highly_variable_rank', 'means', 'variances', 'variances_norm'
    uns: 'cell_type_colors', 'hvg'

Defining the tuner and discovering hyperparameters#

The first part of our workflow is the same as the standard scvi-tools workflow: we start with our desired model class, and we register our dataset with it using setup_anndata. All datasets must be registered prior to hyperparameter tuning.

model_cls = scvi.model.SCVI
model_cls.setup_anndata(adata)

Our main entry point to the autotune module is the ModelTuner class, a wrapper around ray.tune.Tuner with additional functionality specific to scvi-tools. We can define a new ModelTuner by providing it with our model class.

ModelTuner will register all tunable hyperparameters in SCVI – these can be viewed by calling info(). By default, this method will display three tables:

  1. Tunable hyperparameters: The names of hyperparameters that can be tuned, their default values, and the internal classes they are defined in.

  2. Available metrics: The metrics that can be used to evaluate the performance of the model. One of these must be provided when running the tuner.

  3. Default search space: The default search space for the model class, which will be used if no search space is provided by the user.

Running the tuner#

Now that we know what hyperparameters are available to us, we can define a search space using the search space API in ray.tune. For this tutorial, we choose a simple search space with two model hyperparameters and one training plan hyperparameter. These can all be combined into a single dictionary that we pass into the fit method.

search_space = {
    "model_params": {"n_hidden": tune.choice([64, 128, 256]), "n_layers": tune.choice([1, 2, 3])},
    "train_params": {"max_epochs": 100},
}

There are a couple more arguments we should be aware of before fitting the tuner:

  • num_samples: The total number of hyperparameter sets to sample from search_space. This is the total number of models that will be trained.

    For example, if we set num_samples=2, we might sample two models with the following hyperparameter configurations:

    model1 = {
        "n_hidden": 64,
        "n_layers": 1,
        "lr": 0.001,
    }
    model2 = {
        "n_hidden": 64,
        "n_layers": 3,
        "lr": 0.0001,
    }
    
  • max_epochs: The maximum number of epochs to train each model for.

    Note: This does not mean that each model will be trained for max_epochs. Depending on the scheduler used, some trials are likely to be stopped early.

  • resources: A dictionary of maximum resources to allocate for the whole experiment. This allows us to run concurrent trials on limited hardware.

Now, we can call fit on the tuner to start the hyperparameter sweep. This will return a TuneAnalysis dataclass, which will contain the best set of hyperparameters, as well as other information.

ray.init(log_to_driver=False)
results = autotune.run_autotune(
    model_cls,
    data=adata,
    mode="min",
    metrics="validation_loss",
    search_space=search_space,
    num_samples=5,
    resources={"cpu": 10, "gpu": 1},
)

Tune Status

Current time:2024-09-25 18:34:30
Running for: 00:03:08.13
Memory: 48.2/377.2 GiB

System Info

Using AsyncHyperBand: num_stopped=5
Bracket: Iter 64.000: -464.96080017089844 | Iter 32.000: -466.0521240234375 | Iter 16.000: -473.712646484375 | Iter 8.000: -483.68011474609375 | Iter 4.000: -496.39654541015625 | Iter 2.000: -519.4060668945312 | Iter 1.000: -590.464111328125
Logical resource usage: 10.0/64 CPUs, 1.0/1 GPUs (0.0/1.0 accelerator_type:RTX)

Trial Status

Trial name status loc model_params/n_hidde n model_params/n_layer s train_params/max_epo chs iter total time (s) validation_loss
_trainable_9374a187TERMINATED172.18.0.2:43151282100 100 70.7007 466.804
_trainable_812e8571TERMINATED172.18.0.2:46592563100 1 1.18005 592.308
_trainable_e010074aTERMINATED172.18.0.2:47611281100 32 21.9276 467.729
_trainable_822e86d0TERMINATED172.18.0.2:4865 643100 1 1.18251 638.6
_trainable_a3d3b6d5TERMINATED172.18.0.2:49672562100 100 71.0632 467.706
print(results.result_grid)
ResultGrid<[
  Result(
    metrics={'validation_loss': 466.8037414550781},
    path='/tmp/tmpyoqxn2or/scvi_3dbf91d5-7e10-4b03-b882-9ace7843f033/scvi_3dbf91d5-7e10-4b03-b882-9ace7843f033/_trainable_9374a187_1_n_hidden=128,n_layers=2,max_epochs=100_2024-09-25_18-31-22',
    filesystem='local',
    checkpoint=None
  ),
  Result(
    metrics={'validation_loss': 592.308349609375},
    path='/tmp/tmpyoqxn2or/scvi_3dbf91d5-7e10-4b03-b882-9ace7843f033/scvi_3dbf91d5-7e10-4b03-b882-9ace7843f033/_trainable_812e8571_2_n_hidden=256,n_layers=3,max_epochs=100_2024-09-25_18-31-26',
    filesystem='local',
    checkpoint=None
  ),
  Result(
    metrics={'validation_loss': 467.7285461425781},
    path='/tmp/tmpyoqxn2or/scvi_3dbf91d5-7e10-4b03-b882-9ace7843f033/scvi_3dbf91d5-7e10-4b03-b882-9ace7843f033/_trainable_e010074a_3_n_hidden=128,n_layers=1,max_epochs=100_2024-09-25_18-32-41',
    filesystem='local',
    checkpoint=None
  ),
  Result(
    metrics={'validation_loss': 638.6004028320312},
    path='/tmp/tmpyoqxn2or/scvi_3dbf91d5-7e10-4b03-b882-9ace7843f033/scvi_3dbf91d5-7e10-4b03-b882-9ace7843f033/_trainable_822e86d0_4_n_hidden=64,n_layers=3,max_epochs=100_2024-09-25_18-32-47',
    filesystem='local',
    checkpoint=None
  ),
  Result(
    metrics={'validation_loss': 467.7059020996094},
    path='/tmp/tmpyoqxn2or/scvi_3dbf91d5-7e10-4b03-b882-9ace7843f033/scvi_3dbf91d5-7e10-4b03-b882-9ace7843f033/_trainable_a3d3b6d5_5_n_hidden=256,n_layers=2,max_epochs=100_2024-09-25_18-33-13',
    filesystem='local',
    checkpoint=None
  )
]>

Comparing latent spaces#

Work in progress: please check back in the next release!

Optional: Monitoring progress with Tensorboard#

Work in progress: please check back in the next release!

Optional: Tuning over integration metrics with scib-metrics#

Work in progress: please check back in the next release!