Skip to contents

1 Overview

On datasets with hundreds of thousands of cells, most of the runtime of a cytoGateR workflow is usually spent in two steps:

This article lists settings that reduce the runtime and memory use of these steps. Most of them trade some accuracy for speed. Before adopting a faster configuration, compare its labels with a slower run on the same data, for example with mean(new_labels == old_labels).

The code in this article is not run; replace the object names with your own.

2 Match threads to workers

Parallel workers and multi-threaded libraries can oversubscribe the CPU. If a machine’s BLAS library uses many threads and you also start several BiocParallel workers, each worker may start its own BLAS threads, which slows everything down and increases memory use.

When running several workers, limit BLAS and OpenMP to one thread per worker, for example with the RhpcBLASctl package:

RhpcBLASctl::blas_set_num_threads(1)
RhpcBLASctl::omp_set_num_threads(1)

bpparam <- BiocParallel::MulticoreParam(workers = 8)

MulticoreParam() is not available on Windows; use BiocParallel::SnowParam() there.

The random forest uses its own threads through num_threads in train_custom_randomforest() (default 2). Keep the total number of threads at or below the number of CPUs you have.

More workers is not always faster. Exact kNN is often limited by memory bandwidth, so benchmark a few values (for example 2, 4, and 8 workers).

3 Reduce the kNN ensemble

At every hierarchy node, predict_hierarchical_knn_recursive() runs length(dist_methods) * repeats bootstrap kNN searches. With the defaults (dist_methods = c("pearson", "cosine"), repeats = 5) that is ten searches per node and per chunk of cells.

A smaller ensemble is a useful first comparison:

spe <- predict_hierarchical_knn_recursive(
  spe,
  hier_ref,
  hc_tree,
  dist_methods = "cosine",
  repeats = 2,
  BPPARAM = bpparam
)

This reduces the work per node from ten searches to two. Cosine similarity is computed with a matrix product, which is typically faster than Pearson correlation.

The ensemble members are what run in parallel, so the number of busy workers is at most length(dist_methods) * repeats. With two searches per node, more than two workers brings no further speedup in this step.

4 Choose chunk_size with memory in mind

Cells are classified in chunks of chunk_size (default 1000). Each kNN search builds a similarity matrix between the chunk and the bootstrap sample of reference cells, which needs roughly

8 bytes x chunk_size x 0.8 x number of reference cells

per running search. For 100,000 reference cells, a chunk of 10,000 cells needs about 6.4 GB per search, and several searches run at once. Larger chunks are therefore not necessarily faster; if memory is tight or the machine starts swapping, reduce chunk_size. Values between 1,000 and 5,000 usually work well.

5 Use node-specific markers

By default, build_hierarchical_reference() can select the most informative markers at each node, but only when marker_stats is supplied. With top_n = NULL, or without marker_stats, every marker is used at every node.

marker_stats <- fit_marker_stats(spe, rownames(spe), assay_name = "exprs")

hier_ref <- build_hierarchical_reference(
  spe,
  hc_tree,
  marker_stats = marker_stats,
  label_col = "cleaned_core_label",
  top_n = 5
)

The speedup is moderate for small panels, but node-specific markers can also improve separation at each split.

6 Limit the number of reference cells

Each node searches all of its reference cells. Exact kNN against hundreds of thousands of cells is expensive and often unnecessary. A balanced reference with a few thousand cells per cell type can be much faster.

One way is to subsample the reference labels before building the hierarchical reference. Cells that are not sampled are marked as unknown, so they are not used as reference cells:

set.seed(1)
labels <- SummarizedExperiment::colData(spe)$cleaned_core_label
is_ref <- which(!is.na(labels) & labels != "Unassigned")
max_per_type <- 10000

keep <- unlist(lapply(split(is_ref, labels[is_ref]), function(idx) {
  if (length(idx) > max_per_type) sample(idx, max_per_type) else idx
}))

ref_spe <- spe
ref_labels <- labels
ref_labels[setdiff(is_ref, keep)] <- "Unassigned"
SummarizedExperiment::colData(ref_spe)$cleaned_core_label <- ref_labels

hier_ref <- build_hierarchical_reference(
  ref_spe,
  hc_tree,
  marker_stats = marker_stats,
  label_col = "cleaned_core_label",
  top_n = 5,
  unknown_label = "Unassigned"
)

If your data contain several images or batches, consider sampling within each image as well, so that the reference represents all of them.

7 Predict only the cells that need it

predict_hierarchical_knn_recursive() classifies every cell in the object it is given, including cells that already have a confident reference label. If you want to keep those labels, predict only the remaining cells and combine the results:

labels <- SummarizedExperiment::colData(spe)$cleaned_core_label
to_predict <- which(is.na(labels) | labels == "Unassigned")

pred <- predict_hierarchical_knn_recursive(
  spe[, to_predict],
  hier_ref,
  hc_tree,
  BPPARAM = bpparam
)

final_labels <- labels
final_labels[to_predict] <- SummarizedExperiment::colData(pred)$hier_label
SummarizedExperiment::colData(spe)$final_label <- final_labels

8 Reduce random-forest cross-validation

train_custom_randomforest() cleans the reference with repeated cross-validation. The defaults (cv_folds = 5, repeats = 10) fit 50 forests before the final model. A lighter configuration fits 9:

rf_fit <- train_custom_randomforest(
  spe,
  label_col = "cleaned_core_label",
  unknown_label = "Unassigned",
  cv_folds = 3,
  repeats = 3,
  num_threads = 4
)

Subsampling the training cells, as in the previous sections, reduces the runtime further.

9 Check what each function returns

Several functions return a list rather than an updated object. For example, predict_unknown_with_randomforest() and predict_unknown_with_knn() return a list with elements spe and prob_mat. Extract the object explicitly when chaining steps:

rf_pred <- predict_unknown_with_randomforest(
  rf_fit$spe,
  rf_fit$model,
  label_col = "cleaned_core_label",
  unknown_label = "Unassigned"
)
spe <- rf_pred$spe

Assigning the whole result where an object is expected (for example x$spe <- predict_unknown_with_randomforest(...)) stores a list instead of a SpatialExperiment, which causes errors in later steps.

10 A first configuration to benchmark

For a large dataset, a reasonable starting point is:

  • one BLAS/OpenMP thread per worker;
  • as many BiocParallel workers as allocated CPUs, up to the ensemble size;
  • chunk_size between 1,000 and 5,000;
  • dist_methods = "cosine" and repeats = 2;
  • node-specific markers with marker_stats and top_n = 5;
  • predicting only cells without a confident reference label.

Measure the runtime and label agreement against your current configuration before using it in production.