From 12641f50ec7970921ba94dc0daa125d0b3af525b Mon Sep 17 00:00:00 2001 From: Alex Hayes Date: Tue, 17 Nov 2026 16:34:07 -0800 Subject: [PATCH] Make factor model spectra reliable for small models fastRG's eigs_sym() and svds() methods for factor models call RSpectra on an exactly rank-k implicit operator. RSpectra's Lanczos solvers are unreliable on such operators when they are small (https://github.com/yixuan/RSpectra/issues/20): with the default ncv = min(dim, max(2k + 1, 20)), they errored or silently returned wrong values for most n = 20 models. - default to ncv = min(dim - 1, max(2k + 1, 10)) unless opts$ncv is given, which fixes every n = 20 case tested (40/40 seeds, vs 7-25/40) - warn, with a link to the RSpectra issue, when min(n, d) <= 25 - forward `which`, `opts` and `...` to RSpectra; `which` was ignored - error informatively for `sigma`, which RSpectra can't support for an implicit operator Co-Authored-By: Claude Opus 5.5 --- R/expected-spectra.R | 119 +++++++++++++++++++-- man/eigs_sym.undirected_factor_model.Rd | 28 ++++- man/svds.directed_factor_model.Rd | 26 ++++- man/svds.undirected_factor_model.Rd | 24 ++++- tests/testthat/test-spectra-small-models.R | 112 +++++++++++++++++++ 5 files changed, 291 insertions(+), 18 deletions(-) create mode 100644 tests/testthat/test-spectra-small-models.R diff --git a/R/expected-spectra.R b/R/expected-spectra.R index f5af2fe..289209d 100644 --- a/R/expected-spectra.R +++ b/R/expected-spectra.R @@ -6,12 +6,99 @@ RSpectra::svds #' @export RSpectra::eigs_sym +# below this size, RSpectra's Lanczos solvers are unreliable on the exactly +# low-rank operators that factor models produce, see +# https://github.com/yixuan/RSpectra/issues/20 +small_model_threshold <- 25 + +rspectra_issue_url <- "https://github.com/yixuan/RSpectra/issues/20" + +# RSpectra defaults to ncv = min(dim, max(2 * k + 1, 20)), which for small +# models means the Krylov subspace is (nearly) the whole space. on the exactly +# rank-k operators of factor models, this makes RSpectra error or silently +# return wrong values much more often. a smaller default is far more +# reliable. respect any ncv the user supplies +default_ncv <- function(opts, k, dim) { + if (is.null(opts$ncv)) { + ncv <- min(dim - 1, max(2 * k + 1, 10)) + + # RSpectra requires k < ncv <= dim. when that isn't possible, leave the + # choice to RSpectra + if (ncv > k && ncv <= dim) { + opts$ncv <- ncv + } + } + + opts +} + +warn_if_small_model <- function(dim, call = rlang::caller_env()) { + if (min(dim) <= small_model_threshold) { + rlang::warn( + c( + paste0( + "RSpectra can return inaccurate eigenvalues or singular values for ", + "small factor models (here min(n, d) = ", + min(dim), + ")." + ), + i = paste0("See <", rspectra_issue_url, "> for details."), + i = paste0( + "For small models, compare with `eigen()` or `svd()` of ", + "`as.matrix(expectation(model))`." + ) + ), + class = "fastRG_warning_small_model_spectra", + call = call + ) + } + + invisible(NULL) +} + +check_no_sigma <- function(sigma, call = rlang::caller_env()) { + if (!is.null(sigma)) { + rlang::abort( + c( + "`sigma` (shift-and-invert mode) is not supported for factor models.", + i = paste0( + "Use `eigs_sym(as.matrix(expectation(model)), sigma = ...)` instead." + ) + ), + call = call + ) + } + + invisible(NULL) +} + #' Compute the eigendecomposition of the expected adjacency matrix of an undirected factor model #' #' @param A An [undirected_factor_model()]. #' @param k Desired rank of decomposition. #' @inherit RSpectra::eigs_sym params details -#' @param ... Unused, included only for consistency with generic signature. +#' @param sigma Not supported for factor models, which are represented +#' implicitly. Must be `NULL`. To use shift-and-invert mode, call +#' `eigs_sym()` on `as.matrix(expectation(A))` instead. +#' @param opts Control parameters passed to [RSpectra::eigs_sym()]. See +#' the "Accuracy for small models" section for the default `ncv`. +#' @param ... Passed to [RSpectra::eigs_sym()]. +#' +#' @section Accuracy for small models: +#' +#' These methods compute spectra with RSpectra's Lanczos solvers, applied +#' implicitly to the expected adjacency matrix, which has rank `k`. RSpectra +#' is unreliable on such exactly low-rank matrices when they are small: it +#' can error with "TridiagEigen: eigen decomposition failed", or silently +#' return wrong eigenvalues or singular values (see +#' ). +#' +#' To reduce how often this happens, these methods default to a smaller +#' Krylov subspace than RSpectra does, `opts$ncv = min(dim - 1, max(2 * k + 1, 10))`, +#' unless you specify `opts$ncv` yourself. They also warn whenever +#' `min(n, d)` is 25 or less. For such small models, it is cheap and +#' reliable to compute the decomposition directly with [eigen()] or [svd()] +#' of `as.matrix(expectation(A))`. #' #' @method eigs_sym undirected_factor_model #' @export @@ -24,10 +111,20 @@ eigs_sym.undirected_factor_model <- function( ... ) { rlang::check_installed("RSpectra") + check_no_sigma(sigma) + warn_if_small_model(A$n) Ax <- function(x, args) as.numeric(args$X %*% (args$SXt %*% x)) - eigs_sym(Ax, k, n = A$n, args = list(X = A$X, SXt = tcrossprod(A$S, A$X))) + eigs_sym( + Ax, + k, + which = which, + opts = default_ncv(opts, k, A$n), + ..., + n = A$n, + args = list(X = A$X, SXt = tcrossprod(A$S, A$X)) + ) } #' Compute the singular value decomposition of the expected adjacency matrix of an undirected factor model @@ -35,7 +132,10 @@ eigs_sym.undirected_factor_model <- function( #' @param A An [undirected_factor_model()]. #' @param k Desired rank of decomposition. #' @inherit RSpectra::svds params details -#' @param ... Unused, included only for consistency with generic signature. +#' @param opts Control parameters passed to [RSpectra::svds()]. See +#' the "Accuracy for small models" section for the default `ncv`. +#' @param ... Passed to [RSpectra::svds()]. +#' @inheritSection eigs_sym.undirected_factor_model Accuracy for small models #' #' @method svds undirected_factor_model #' @export @@ -48,6 +148,7 @@ svds.undirected_factor_model <- function( ... ) { rlang::check_installed("RSpectra") + warn_if_small_model(A$n) Ax <- function(x, args) { as.numeric(args$X %*% (tcrossprod(args$S, args$X) %*% x)) @@ -62,7 +163,7 @@ svds.undirected_factor_model <- function( k = k, nu = nu, nv = nv, - opts = opts, + opts = default_ncv(opts, k, A$n), ..., Atrans = Atx, dim = c(A$n, A$n), @@ -72,10 +173,13 @@ svds.undirected_factor_model <- function( #' Compute the singular value decomposition of the expected adjacency matrix of a directed factor model #' -#' @param A An [undirected_factor_model()]. +#' @param A A [directed_factor_model()]. #' @param k Desired rank of decomposition. #' @inherit RSpectra::svds params details -#' @param ... Unused, included only for consistency with generic signature. +#' @param opts Control parameters passed to [RSpectra::svds()]. See +#' the "Accuracy for small models" section for the default `ncv`. +#' @param ... Passed to [RSpectra::svds()]. +#' @inheritSection eigs_sym.undirected_factor_model Accuracy for small models #' #' @method svds directed_factor_model #' @export @@ -88,6 +192,7 @@ svds.directed_factor_model <- function( ... ) { rlang::check_installed("RSpectra") + warn_if_small_model(c(A$n, A$d)) Ax <- function(x, args) { as.numeric(args$X %*% (tcrossprod(args$S, args$Y) %*% x)) @@ -102,7 +207,7 @@ svds.directed_factor_model <- function( k = k, nu = nu, nv = nv, - opts = opts, + opts = default_ncv(opts, k, min(A$n, A$d)), ..., Atrans = Atx, dim = c(A$n, A$d), diff --git a/man/eigs_sym.undirected_factor_model.Rd b/man/eigs_sym.undirected_factor_model.Rd index 65b0bad..f0ab641 100644 --- a/man/eigs_sym.undirected_factor_model.Rd +++ b/man/eigs_sym.undirected_factor_model.Rd @@ -13,12 +13,14 @@ \item{which}{Selection criterion. See \strong{Details} below.} -\item{sigma}{Shift parameter. See section \strong{Shift-And-Invert Mode}.} +\item{sigma}{Not supported for factor models, which are represented +implicitly. Must be \code{NULL}. To use shift-and-invert mode, call +\code{eigs_sym()} on \code{as.matrix(expectation(A))} instead.} -\item{opts}{Control parameters related to the computing -algorithm. See \strong{Details} below.} +\item{opts}{Control parameters passed to \code{\link[RSpectra:eigs]{RSpectra::eigs_sym()}}. See +the "Accuracy for small models" section for the default \code{ncv}.} -\item{...}{Unused, included only for consistency with generic signature.} +\item{...}{Passed to \code{\link[RSpectra:eigs]{RSpectra::eigs_sym()}}.} } \description{ Compute the eigendecomposition of the expected adjacency matrix of an undirected factor model @@ -72,3 +74,21 @@ following parameters: if \code{initvec} is close to an eigenvector of \eqn{A}.} } } +\section{Accuracy for small models}{ + + +These methods compute spectra with RSpectra's Lanczos solvers, applied +implicitly to the expected adjacency matrix, which has rank \code{k}. RSpectra +is unreliable on such exactly low-rank matrices when they are small: it +can error with "TridiagEigen: eigen decomposition failed", or silently +return wrong eigenvalues or singular values (see +\url{https://github.com/yixuan/RSpectra/issues/20}). + +To reduce how often this happens, these methods default to a smaller +Krylov subspace than RSpectra does, \code{opts$ncv = min(dim - 1, max(2 * k + 1, 10))}, +unless you specify \code{opts$ncv} yourself. They also warn whenever +\code{min(n, d)} is 25 or less. For such small models, it is cheap and +reliable to compute the decomposition directly with \code{\link[=eigen]{eigen()}} or \code{\link[=svd]{svd()}} +of \code{as.matrix(expectation(A))}. +} + diff --git a/man/svds.directed_factor_model.Rd b/man/svds.directed_factor_model.Rd index c00b58f..e5d4e72 100644 --- a/man/svds.directed_factor_model.Rd +++ b/man/svds.directed_factor_model.Rd @@ -7,7 +7,7 @@ \method{svds}{directed_factor_model}(A, k = min(A$k1, A$k2), nu = k, nv = k, opts = list(), ...) } \arguments{ -\item{A}{An \code{\link[=undirected_factor_model]{undirected_factor_model()}}.} +\item{A}{A \code{\link[=directed_factor_model]{directed_factor_model()}}.} \item{k}{Desired rank of decomposition.} @@ -17,10 +17,10 @@ be between 0 and \code{k}.} \item{nv}{Number of right singular vectors to be computed. This must be between 0 and \code{k}.} -\item{opts}{Control parameters related to the computing -algorithm. See \strong{Details} below.} +\item{opts}{Control parameters passed to \code{\link[RSpectra:svds]{RSpectra::svds()}}. See +the "Accuracy for small models" section for the default \code{ncv}.} -\item{...}{Unused, included only for consistency with generic signature.} +\item{...}{Passed to \code{\link[RSpectra:svds]{RSpectra::svds()}}.} } \description{ Compute the singular value decomposition of the expected adjacency matrix of a directed factor model @@ -53,3 +53,21 @@ following parameters: Default is \code{FALSE}.} } } +\section{Accuracy for small models}{ + + +These methods compute spectra with RSpectra's Lanczos solvers, applied +implicitly to the expected adjacency matrix, which has rank \code{k}. RSpectra +is unreliable on such exactly low-rank matrices when they are small: it +can error with "TridiagEigen: eigen decomposition failed", or silently +return wrong eigenvalues or singular values (see +\url{https://github.com/yixuan/RSpectra/issues/20}). + +To reduce how often this happens, these methods default to a smaller +Krylov subspace than RSpectra does, \code{opts$ncv = min(dim - 1, max(2 * k + 1, 10))}, +unless you specify \code{opts$ncv} yourself. They also warn whenever +\code{min(n, d)} is 25 or less. For such small models, it is cheap and +reliable to compute the decomposition directly with \code{\link[=eigen]{eigen()}} or \code{\link[=svd]{svd()}} +of \code{as.matrix(expectation(A))}. +} + diff --git a/man/svds.undirected_factor_model.Rd b/man/svds.undirected_factor_model.Rd index fe144b7..1e7f965 100644 --- a/man/svds.undirected_factor_model.Rd +++ b/man/svds.undirected_factor_model.Rd @@ -17,10 +17,10 @@ be between 0 and \code{k}.} \item{nv}{Number of right singular vectors to be computed. This must be between 0 and \code{k}.} -\item{opts}{Control parameters related to the computing -algorithm. See \strong{Details} below.} +\item{opts}{Control parameters passed to \code{\link[RSpectra:svds]{RSpectra::svds()}}. See +the "Accuracy for small models" section for the default \code{ncv}.} -\item{...}{Unused, included only for consistency with generic signature.} +\item{...}{Passed to \code{\link[RSpectra:svds]{RSpectra::svds()}}.} } \description{ Compute the singular value decomposition of the expected adjacency matrix of an undirected factor model @@ -53,3 +53,21 @@ following parameters: Default is \code{FALSE}.} } } +\section{Accuracy for small models}{ + + +These methods compute spectra with RSpectra's Lanczos solvers, applied +implicitly to the expected adjacency matrix, which has rank \code{k}. RSpectra +is unreliable on such exactly low-rank matrices when they are small: it +can error with "TridiagEigen: eigen decomposition failed", or silently +return wrong eigenvalues or singular values (see +\url{https://github.com/yixuan/RSpectra/issues/20}). + +To reduce how often this happens, these methods default to a smaller +Krylov subspace than RSpectra does, \code{opts$ncv = min(dim - 1, max(2 * k + 1, 10))}, +unless you specify \code{opts$ncv} yourself. They also warn whenever +\code{min(n, d)} is 25 or less. For such small models, it is cheap and +reliable to compute the decomposition directly with \code{\link[=eigen]{eigen()}} or \code{\link[=svd]{svd()}} +of \code{as.matrix(expectation(A))}. +} + diff --git a/tests/testthat/test-spectra-small-models.R b/tests/testthat/test-spectra-small-models.R new file mode 100644 index 0000000..07d8e66 --- /dev/null +++ b/tests/testthat/test-spectra-small-models.R @@ -0,0 +1,112 @@ +# eigs_sym() and svds() methods for factor models use RSpectra, which is +# unreliable on small, exactly low-rank operators +# (https://github.com/yixuan/RSpectra/issues/20). these tests cover the +# smaller default ncv, the small-model warning, and argument forwarding + +dense_top_singular <- function(model, k) { + svd(as.matrix(expectation(model)))$d[seq_len(k)] +} + +dense_top_abs_eigen <- function(model, k) { + values <- eigen(as.matrix(expectation(model)), symmetric = TRUE)$values + sort(abs(values), decreasing = TRUE)[seq_len(k)] +} + +test_that("small models give correct spectra with the default ncv", { + # with RSpectra's default ncv, these were wrong or errored in most seeds: + # directed svds was wrong in 30 of 40 seeds, undirected svds errored in 33 + for (seed in 1:15) { + set.seed(seed) + n <- 20 + + directed <- directed_factor_model( + matrix(runif(2 * n), n), + matrix(runif(4), 2), + matrix(runif(2 * n), n) + ) + undirected <- undirected_factor_model( + matrix(runif(3 * n), n), + crossprod(matrix(runif(9), 3)) + ) + + expect_warning(s_dir <- svds(directed, k = 2), class = "fastRG_warning_small_model_spectra") + expect_equal(s_dir$d, dense_top_singular(directed, 2), tolerance = 1e-6, label = seed) + + expect_warning(s_und <- svds(undirected, k = 3), class = "fastRG_warning_small_model_spectra") + expect_equal(s_und$d, dense_top_singular(undirected, 3), tolerance = 1e-6, label = seed) + + expect_warning(e_und <- eigs_sym(undirected, k = 3), class = "fastRG_warning_small_model_spectra") + expect_equal( + sort(abs(e_und$values), decreasing = TRUE), + dense_top_abs_eigen(undirected, 3), + tolerance = 1e-6, + label = seed + ) + } +}) + +test_that("small models warn and link to the RSpectra issue", { + set.seed(27) + small <- sbm(n = 25, B = diag(2) * 0.5 + 0.1) + + expect_warning(eigs_sym(small), "github.com/yixuan/RSpectra/issues/20", fixed = TRUE) + expect_warning(svds(small), class = "fastRG_warning_small_model_spectra") + + # the warning depends on the smaller dimension of directed models + rectangular <- directed_factor_model( + matrix(runif(400), 200), + diag(2), + matrix(runif(40), 20) + ) + expect_warning(svds(rectangular), class = "fastRG_warning_small_model_spectra") +}) + +test_that("larger models don't warn", { + set.seed(27) + undirected <- sbm(n = 26, B = diag(2) * 0.5 + 0.1) + directed <- directed_factor_model( + matrix(runif(200), 100), + diag(2), + matrix(runif(60), 30) + ) + + expect_no_warning(eigs_sym(undirected)) + expect_no_warning(svds(undirected)) + expect_no_warning(svds(directed)) +}) + +test_that("eigs_sym() forwards `which`", { + set.seed(27) + # B has a negative eigenvalue, so the smallest eigenvalue of E[A] is negative + model <- sbm(n = 40, B = matrix(c(0.1, 0.5, 0.5, 0.1), 2), block_sizes = c(20, 20)) + values <- eigen(as.matrix(expectation(model)), symmetric = TRUE)$values + + expect_equal(eigs_sym(model, k = 1, which = "SA")$values, min(values), tolerance = 1e-8) + expect_equal(eigs_sym(model, k = 1, which = "LA")$values, max(values), tolerance = 1e-8) + expect_equal( + eigs_sym(model, k = 2, which = "LM")$values, + values[order(abs(values), decreasing = TRUE)][1:2], + tolerance = 1e-8 + ) +}) + +test_that("opts are forwarded and a user-supplied ncv is respected", { + set.seed(27) + model <- sbm(n = 40, B = diag(3) * 0.5 + 0.1) + + # retvec = FALSE drops the eigenvectors, which only happens if opts arrive + expect_null(eigs_sym(model, opts = list(retvec = FALSE))$vectors) + + expect_equal(default_ncv(list(), k = 3, dim = 40)$ncv, 10) + expect_equal(default_ncv(list(), k = 6, dim = 40)$ncv, 13) + expect_equal(default_ncv(list(), k = 2, dim = 8)$ncv, 7) + expect_equal(default_ncv(list(ncv = 25), k = 3, dim = 40)$ncv, 25) + + # when k < ncv <= dim is impossible, leave ncv to RSpectra + expect_null(default_ncv(list(), k = 2, dim = 3)$ncv) +}) + +test_that("sigma gives an informative error for factor models", { + model <- sbm(n = 40, B = diag(2) * 0.5 + 0.1) + expect_error(eigs_sym(model, sigma = 1), "shift-and-invert") +})