Registry Mirror
Skip to content

Conversation

@avehtari

@avehtari avehtari commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

Summary

varsel() and cv_varsel() are slow for Gaussian submodels (identity link, also in the latent projection) with smooth terms or group-level terms. projpred fits each projected draw with mgcv::gam(), lme4::lmer() or gamm4::gamm4(). This PR fits all draws of a submodel together:

  • Additive submodels and submodels with random intercepts (1 | <group>): one penalized least-squares fit of all draws on a fixed basis, with shared penalty parameters.
  • Other multilevel submodels, for example with slopes (x | <group>): one relative covariance factor (theta of lme4) for all draws. Each draw gets an lmer() or gamm4() object at this theta.

In the examples below, the calls ran 2.7 to 86 times faster (medians; pepper with nloo = 50: 59 s instead of 85 min).

Changes

All fits:

  • Each smooth term and each grouping variable of a random intercept has a penalty parameter (for a grouping variable, a penalty lambda on its group-level effects). One vector of these parameters serves all draws. One Cholesky factor gives the coefficients of all draws.
  • The shared criteria (GCV for additive submodels, REML for multilevel submodels) use the weight of each draw (the cluster weight for clustered draws).
  • The global options projpred.smooth_fixed_basis = FALSE and projpred.mlvl_fixed_basis = FALSE select the per-draw fits of master.
  • This PR removes the warning "Support for additive models is still experimental." and its option projpred.warn_additive_experimental.

Additive submodels without group-level terms (R/smooth_fit.R, class subfit_smooth):

  • The basis of each smooth term comes from mgcv::smoothCon(absorb.cons = TRUE, modCon = 3) (as in brms) for all rows of the reference model data. The same basis serves all submodels and all LOO folds.
  • search_forward_gauss() ranks smooth terms from the cross-products, after the linear terms of their variables.
  • nlminb() minimizes the GCV score for the shared smoothing parameters. A compass search follows (steps of 2 to 0.25 in each log smoothing parameter), then a restart of nlminb(). nlminb() alone stopped early in flat parts of the score. The convergence check then failed in 11 of 40 seeds of the reference model of test_smooth_fit.R, and on Windows also in the CI. In the mesquite and body fat calls below, the compass search added at most 4 % to the run times and gave the same rankings.
  • as.matrix() maps the coefficients to the brms or rstanarm basis. The SD of a block is the root mean square of its coefficients in each draw.
  • projpred keeps gam() for mo() terms, offsets, gam() arguments in ..., regul below 1e-6 and missing projected responses.

Random-intercept submodels (R/mlvl_fixed.R, existing class projpred_mlvl) and additive submodels with random intercepts (R/gamm_fixed.R, class projpred_gamm_fixed):

  • The group levels become indicator columns with the penalty lambda. The penalty parameters minimize the REML criterion summed over the draws; the criterion profiles out the residual variance of each draw. With one draw and without the ridge regul * var(column), the fits are the REML fits of lmer() and gamm4().
  • The group-level SD of a draw is the square root of the mean squared group-level effect plus the mean conditional variance. projpred uses it for new group levels and for the sd_* columns of as.matrix().
  • The fits run after divmin() removes the rows with weight 0, so lost levels and new levels in LOO CV work as before.
  • In the latent projection without offsets, init_refmodel() and the LOO CV reuse the latent linear predictors (two ref_predfun() calls fewer).
  • Cases outside these fits (for example t2() terms, no intercept, more than 500 group levels, a rank-deficient model matrix) go to the fits at one theta.

Other multilevel submodels (R/slopes_fixed.R):

  • One theta minimizes the REML criterion of lme4 summed over the draws, with one sparse Cholesky factor per value of theta for all draws. A floor on the penalized residual sum of squares keeps theta finite when the submodel reproduces the draws.
  • Each draw gets the lmer() or gamm4() object at this theta, so the existing methods apply (predictions, new levels, as.matrix(), the parallel per-draw loop).
  • In a draw, the covariance matrix of the group-level effects of a term is the mean of b b' over the levels plus the mean conditional covariance. projpred uses it for new levels and for the sd_* and cor_* columns of as.matrix(). lme4's sigma times theta has no stable value when the submodel nearly reproduces the draws. In VerbAgg, the id SD of (1 | id) + btype + mode + situ was 0.25 from lme4 and 1.21 with this definition (first draw of 20 clusters).
  • projpred keeps the per-draw fits for offsets, missing values, more than 3000 group-level coefficients, the monotonic projection of mo() terms, lmer() or gamm4() arguments in ..., designs that lme4 rejects, projpred.mlvl_fixed_basis = FALSE, projpred.smooth_fixed_basis = FALSE (with smooth terms), projpred.PQL = TRUE and projpred.gaussian_not_as_generalized = FALSE. A draw whose fit at the shared theta fails gets its per-draw fit and a warning.
  • Fix: for new group levels, repair_re.merMod() and gamm4_re_b() used the covariance matrix of the first term of a grouping variable for all its terms. Now each term (for example (1 | g) + (0 + x | g)) uses its own covariance matrix.

Why shared penalty parameters

The KL projection of a Gaussian draw onto a fixed basis is the unpenalized least-squares fit. In simulations (100 data sets per case), submodels that leave out terms predicted new data worse without a penalty, by up to 0.037 log density per observation at n = 46. Without the group-level penalty, the loss was up to 0.024. The shared penalty parameters and the per-draw fits differed by at most 0.0044 (smooth terms) and 0.0018 (random intercepts) per observation. The LOO estimates differed by at most 0.0029 and 0.0033. With Stan reference models (3 cases, 5 data sets each), the full-data rankings of the random-intercept fits and of lmer() were the same in 15 of 15 data sets. No K-fold elpd difference was below -4 SE.

Speed

model call per-draw (s) new (s) speedup
mesquite (latent log-normal, 4 smooth terms, n = 46) varsel() 39.3 to 41.0 1.6 to 1.7 26.0
mesquite cv_varsel(), LOO, validated search 1852 to 1917 53.5 to 59.5 31.6
corn (Gaussian, t2(), n = 3443) cv_varsel(), LOO 25.1 to 27.5 7.8 to 9.7 2.69
body fat (Gaussian, 13 smooth terms, n = 251) varsel() 203 to 206 11.1 to 11.8 17.4
simulated (1 | g) + (1 | h), Gaussian and latent Bernoulli varsel(), cv_varsel() 6.2 to 13.9 (range)
pepper (latent Bernoulli, s(water), 2 random intercepts, n = 791) cv_varsel(), nloo = 50 5097.5 59.1 86
bangladesh (latent Bernoulli, slopes, n = 1934) cv_varsel(), LOO 493.0 93.2 5.3
simulated slopes (x1 + x2 | g) + s(z), Gaussian cv_varsel(), K-fold, validated search 1021.1 273.1 3.7
  • All rows ran on CSC Roihu. The first five rows ran both fits in each process (ranges over 3 processes; the speedup is the median ratio, or the range of the ratios). The other rows ran both fits in one job (medians of 5 runs; pepper 1 run).
  • Rankings were the same, except mesquite (positions 8 and 9 swapped; elpd difference at most 2.5 at one size, SE about 3.4). The suggested sizes were the same where they were recorded (mesquite, the simulated random intercepts, bangladesh, the simulated slopes). The largest elpd difference was 0.27 (0.04 SE) for bangladesh and 1.17 (0.09 SE) for the simulated slopes.
  • The per-draw fits gave more lme4, gam() or gamm4() convergence and singular-fit warnings (for example 218 against 3 for mesquite, 81 against 0 for bangladesh).
  • In a simulation with many small groups (similar to Predictive performance gap / jumpy behavior at full size in Gaussian multilevel model #441), the lmer() path stopped with an lme4 error in 10 of 20 data sets (K-fold CV). The new fit had no error. On master, cv_varsel() of VerbAgg (lme4::VerbAgg, 7584 observations, latent cumulative) with btype * mode * situ stops with the lme4 error "not positive definite".
  • On this branch, init_refmodel() stops for the bangladesh model (mo() with smooth and group-level terms). That row ran on a local build that adds this case.

Tests

  • New files: test_smooth_fit.R, test_mlvl_fixed.R, test_gamm_fixed.R, test_slopes_fixed.R. With one draw, the fits equal the REML fits of lmer() and gamm4(), also with weights. With several draws, the coefficients equal a direct penalized solve with the shared parameters. The weights of the draws enter the criteria. The SDs and covariance matrices equal their definitions above. The files also cover predictions for new data and new levels, rows with weight 0, the latent projection, the fallbacks and the convergence warnings.
  • Changed files: the cross-product search with smooth terms (test_search_gauss.R), as.matrix() in the brms and rstanarm bases (test_smooth_basis.R), lost factor levels (test_loo_fold_projection.R), the reuse of the latent linear predictors (test_latent.R), and the per-draw tests, which now set the options to FALSE.
  • Without the changes, the new and changed test files fail (66 failures and 27 errors for the fits on a fixed basis; 58 failures and 3 errors for the fits at one theta).
  • Full suite on CSC Roihu (R 4.6.1, testthat 3.3.2, lme4 2.0.6, gamm4 0.3.0, brms 2.23.1, rstanarm 2.32.2). With NOT_CRAN=true at the branch head: 804 blocks, 65,982 expectations, 0 failed, 1 skipped, 14 warnings. In CRAN mode, before the merge of Raise five tolerances near machine precision #691 and of the GCV change of this PR: 8,483 expectations, 0 failed, 2 warnings. These warnings are the same as in the runs of Build the shared test objects with getters when a test needs them #688, Turn off gc() and use a free port for the PSOCK workers of the parallel tests #689 and Keep the brms fits of the tests between the GitHub CI runs #690 before their squash merges.
  • Not tested: K-fold CV in the new tests (it ran in the simulations above), the parallel per-draw loop with real workers (only mocks), and slopes of more than one grouping variable in a timing.

This PR was assisted by Claude

# Conflicts:
#	NEWS.md
#	tests/testthat/helpers/expectors.R
#	tests/testthat/setup.R
#	tests/testthat/test_as_matrix.R
#	tests/testthat/test_parallel.R
#	tests/testthat/test_proj_pred.R
#	tests/testthat/test_project.R
#	tests/testthat/test_refmodel.R
#	tests/testthat/test_setup.R
#	tests/testthat/test_varsel.R
# Conflicts:
#	tests/testthat/test_varsel.R
…use mu_offs only for reference models built without projpred.mlvl_proj_ref_new
…rix(), check the rank of the unpenalized part and keep gamm4 in the gamm4 tests
…ance, and accept the fixed-basis GAMM fits in the test helper
…a for all draws and weight the draws in the shared criteria
…draw-wise closures and report draw-wise fallbacks in the fits at one theta
…and show the full formula in the fallback warning
@avehtari
avehtari requested a review from aloctavodia December 1, 2026 13:57
@avehtari avehtari added the performance Performance issues (i.e., high runtime or high memory usage). label Dec 1, 2026
@avehtari
avehtari added this pull request to stack #694 December 1, 2026 14:06
… a compass search where nlminb() stops early
…e rounding noise, and skip repeated evaluations
Comment thread R/smooth_fit.R
# Columns without variance in the rows with a positive weight (for example a
# factor level that only a row with weight 0 has) get a coefficient of 0:
sd2 <- nrow(x) / (nrow(x) - 1) * diag(g_mat) / sum_w
keep <- sd2 > 1e-12 * max(sd2, 1e-300)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
keep <- sd2 > 1e-12 * max(sd2, 1e-300)
keep <- sd2 > 1e-12 * colSums(x_noi^2 * w) / sum_w

Compare each column's variance against its own weighted mean square rather than max(sd2) so that predictors on small scales are not zeroed out.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Performance issues (i.e., high runtime or high memory usage).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants