This vignette fits an
intercept-only Poisson GLM with a size-factor offset to each of the
18,082 genes of a 10x Visium HD lung SpatialExperiment
(443,765 bins), and ranks genes by Pearson residual variance, the first
step of glmGamPoi-style feature selection. The counts never
pass through a dense matrix or a converted copy on disk:
.rds straight into gene blocks: it inflates the file once
to index it, then reads each block in parallel, about 0.3 s per 1,000
genes.gene_blocks() opens the file once. Each
$read(k) returns block k as a cells x genes
dgCMatrix. One pass over the blocks gives the cell
totals:
it <- gene_blocks(path, block_size = 1000)
tot <- Reduce(`+`, lapply(seq_len(it$n), function(k) rowSums(it$read(k))))
keep <- tot > 0 # 756 bins are empty
sf <- tot / exp(mean(log(tot[keep])))
offset <- ifelse(keep, log(sf), 0)
weights <- as.numeric(keep) # empty bins out of the fit
X <- matrix(1, length(tot), 1, dimnames = list(NULL, "(Intercept)"))The fit takes genes x cells, so transpose each block. Pearson
residual variance comes from sparse sums,
sum(y^2 / mu) - 2 sum(y) + sum(mu), so the dense residual
matrix is never formed:
fit_block <- function(k) {
m <- it$read(k)
fit <- glmjax::fit_glm(t(m), X, offset = offset, weights = weights,
dispersion = 0, precision = "single")
b <- fit$Beta[, 1]
y <- as(m * weights, "TsparseMatrix")
mu <- exp(b[y@j + 1L] + offset[y@i + 1L])
s_y2_mu <- tapply(y@x^2 / mu, factor(y@j + 1L, levels = seq_len(ncol(m))),
sum, default = 0)
rv <- (s_y2_mu - 2 * colSums(y) + exp(b) * sum(exp(offset) * weights)) / sum(weights)
data.frame(gene = colnames(m), beta0 = b, resid_var = as.numeric(rv),
converged = fit$converged, iterations = fit$iterations)
}
res <- do.call(rbind, lapply(seq_len(it$n), fit_block))
head(res[order(-res$resid_var), ], 10)One process should hold the GPU. On a CPU, fork workers instead. Each one reads its own blocks from the shared iterator:
An intercept-only Poisson fit with an offset has a closed form,
log(sum(y) / sum(exp(offset))), over the kept cells:
The run used an NVIDIA RTX 2000 Ada laptop GPU (8 GB) with CUDA and float32 kernels.
| step | time |
|---|---|
open and index the .rds |
1.7 s |
| cell totals (18 blocks) | 6.1 s |
| fit 18,082 genes | 420 s |
| total, wall | 434 s |