Approximates the posterior of a parameter vector from its log density alone, using the approximation pipeline of INLAvaan (Jamil & Rue, 2026a, 2026b) with no latent field and nothing model-specific. The pipeline has four stages:
Joint Gaussian (Laplace). The posterior mode \(\vartheta^*\) and the inverse Hessian \(\Omega\) there give a Gaussian approximation \(N(\vartheta^*, \Omega)\) and the Laplace estimate of the log marginal likelihood.
VB mean correction. The Gaussian is recentred at \(\tilde\vartheta = \vartheta^* + \hat\delta\), the mean that maximises its expected log-posterior, with the covariance unchanged.
Skew-normal marginals. For each parameter, the log-posterior is scanned along the conditional mode path of the Gaussian, corrected for the changing volume of the other parameters, and fitted by a skew-normal \(SN(\hat\xi_j, \hat\omega_j, \hat\alpha_j)\).
Gaussian copula draws.
sampling()couples the skew-normal marginals through the correlations of \(\Omega\).
Stages 2 and 3 are optional and independent of each other.
vb_correction = "none" skips the VB correction, which leaves the marginals
unchanged (they are scanned around the mode) but gives the Laplace log
marginal likelihood. marginals = "gaussian" skips the scans and uses the
Gaussian's own marginals \(N(\tilde\vartheta_j, \Omega_{jj})\), centred at
the VB mean (or at the mode when vb_correction = "none"); sampling() then
draws from the joint Gaussian. So
vb_correction = "none", marginals = "gaussian" is the Laplace approximation
alone, and marginals = "gaussian" alone is the Laplace approximation with
the VB correction.
Usage
inla_vanilla(
logpost,
init,
grad = NULL,
hess = NULL,
...,
vb_correction = c("onestep", "full", "none"),
marginals = c("skewnorm", "gaussian"),
marginal_scan = c("linear", "exact", "laplace", "plain"),
tk_fallback = FALSE,
transform = TRUE,
cores = NULL,
verbose = FALSE,
silent = FALSE,
control = list(),
vb = NULL,
width = NULL
)Arguments
- logpost
A function
logpost(theta, ...)returning the log-posterior density (up to a constant) at the named numeric vectortheta, on the unconstrained scale. See the section on writinglogpost.- init
A named numeric vector of starting values. Its length sets the number of parameters and its names label them; unnamed values are called
theta[1],theta[2], ..., and a repeated name is numbered in the same way.- grad
Optional function
grad(theta, ...)returning the gradient oflogpostas a numeric vector. WhenNULL(the default), finite differences are used.- hess
Optional function
hess(theta, ...)returning the Hessian oflogpost, the m x m matrix of its second derivatives (a sparse matrix from the Matrix package, and a number when m = 1, work too). It needsgrad. WhenNULL(the default), finite differences ofgradare used.- ...
Further arguments passed to
logpost,gradandhess, such as the data. As instats::nlminb(), they come after the gradient and the Hessian, and the arguments after them (vb_correction,marginals,marginal_scan,tk_fallback,transform,cores,verbose,silent,control, and the deprecatedvbandwidth) must be given by their full names, so data arguments cannot partially match them. A data argument cannot take one of those names. The arguments before them can be matched, as innlminb(): a data argument namedgorgrwould be taken asgrad, and one namedhorheashess, so give it a longer name.- vb_correction
The VB mean correction:
"onestep"(the default) takes one Newton step from the mode,"full"iterates to the VB solution, and"none"leaves it out. Abbreviations such as"one"work too. See the section on the VB correction. The correction enters the log marginal likelihood, and the skew-normal means are checked against it (seesummary.inla_vanilla()).- marginals
The marginal of each parameter:
"skewnorm"(the default) fits a skew-normal to a scan of the log-posterior;"gaussian"uses the Gaussian marginal of the Laplace approximation, centred at the VB mean unlessvb_correction = "none", with no scans."skewnormal"is the same as"skewnorm", and abbreviations such as"skew"and"gauss"work too.- marginal_scan
How each skew-normal scan is taken, and how it accounts for the changing volume of the other parameters, the width term \(\gamma_j(t) = -\frac12 \log|H_{-j}|\) (see the section on the scans). With m parameters and
n_gridscan points, per parameter:"linear"(the default): its linear term \(\gamma_j' t\), as in INLAvaan, from 4gradcalls, and one more for all the parameters together (2m + 5logpostcalls withoutgrad), on top of then_grid - 1logpostcalls of the scan."exact": the exact width term along the same straight scan, from the Hessian of the other parameters at each scan point: aboutn_grid - 1times 2(m - 1)gradcalls (n_grid - 1hesscalls withhess, orn_grid - 1times (m - 1)mlogpostcalls withoutgrad)."laplace": the Laplace marginal of Tierney and Kadane (1986). At each scan point the other parameters are moved to their conditional mode bystats::nlminb(), started from the straight scan, and the height and the width term are taken there: the calls of"exact"plus those ofn_grid - 1conditional optimisations, typically 5 to 20logpostandgradcalls each withgrad, and many more without."plain": no width term, only then_grid - 1logpostcalls of the scan. It shows what the volume correction adds.
With one parameter there is no width term, and the four are the same scan (
"plain"leaves out the volume correction's rounding error). Abbreviations work. Ignored for Gaussian marginals.- tk_fallback
Logical. Rescan with
marginal_scan = "laplace"every parameter whoseridge_bendis flagged (above 0.25, seesummary.inla_vanilla())? DefaultFALSE, so that a fit costs whatmarginal_scansays and gives the same marginals whatever its diagnostics. The parameters rescanned are listed infit$fallbackand bysummary.inla_vanilla(). Ignored for Gaussian marginals and withmarginal_scan = "laplace".- transform
Logical. Report a parameter named
log_x,logit_xoratanh_xon its natural scale, asx? DefaultTRUE.FALSEreports every parameter on the scale oflogpost. Either way the fit itself is the same (see the section on natural-scale summaries).- cores
The number of CPU cores for the skew-normal scans, and for
loo()andwaic()on this fit.NULL, the default, followsfuture::plan(), and is serial if no plan is set.1is serial whatever the plan. Needs the future package (see the section on parallel computation).- verbose
Logical. Print a full diagnostic of each stage under its progress line? Default
FALSE. See the section on output.- silent
Logical. Print nothing at all, and muffle the warnings and messages raised during the fit? Default
FALSE. The warnings are still recorded infit$warnings. Cannot be combined withverbose = TRUE.- control
The tuning of the fit: the limits of the mode search, the VB correction and the scans, from
vanilla_control(), or a list with some of its entries.- vb
Deprecated: the name of
vb_correctionbefore inlavanilla 26.11.24, where"off"is now"none". It still works, with a warning.- width
Deprecated: the name of
marginal_scanbefore inlavanilla 26.11.24, with the values"trace"(now"linear"),"cmp"(now"exact") and"tk"(now"laplace"). It still works, with a warning.
Value
An object of class inla_vanilla, with methods for print(),
summary(), coef(), plot(), sampling(), diagnostics() and
timing(). It is a list
holding, among other things:
summary: the posterior summary table (mean, SD, quantiles, mode), with the transformed parameters on their natural scale.transform: a data frame with a row per parameter: its name ininit(parameter), the name it is reported under (name) and its transform (transform:"log","logit","atanh", or"identity"for none).mode,cov: the Laplace mode and covariance, on the scale oflogpost, as is everything below.mean_vb: the VB-corrected mean (the mode whenvb_correction = "none").sn: the skew-normal parametersxi,omegaandalphaper parameter (withalpha = 0for Gaussian marginals).vb_correction,marginals,marginal_scan,tk_fallback,cores,verbose,silent: the settings the fit used (marginal_scanisNAfor Gaussian marginals).fallback: the parameters thattk_fallbackrescanned withmarginal_scan = "laplace"(empty when there were none).logml: the log marginal likelihood, andlogml_laplaceits Laplace part.version: the version of inlavanilla that made the fit, the string inDESCRIPTION(for example"26.11.23", a date as in R-INLA).print()andsummary()show it in their headers.diagnostics: the checks of each stage, whichdiagnostics()returns under INLAvaan's names andsummary.inla_vanilla()explains.optimholds the return code, message and iterations ofstats::nlminb()(the iterations of both runs if it was restarted, the code and message of the run that was kept), the gradient of minus the log-posterior at the mode (grad), the whitened gradient there (grad_mode), and the condition number of the Hessian, on the raw scale (hess_cond) and in posterior-SD units (hess_cond_cor).vbholds the iterations of the VB correction, whether it stopped at the first step (one_pass), whether it fell back tostats::nlminb()(fallback), the check of a one-step correction (its three numbers incheck, whether it failed and the VB equation was solved insolve, and the parameter its warning names incheck_worst), and the Kullback-Leibler divergence of the shift (kld_global); it isNULLwhenvb_correction = "none".marginalsis a data frame with a row per parameter:mode_shift_sigma,kld,vb_shift,vb_shift_sigma,nmad,alpha,unscanned_mass,vb_step_sigma,grad_gap,mean_gap,gamma1,tailsandridge_bend, withNAfor the checks the fit did not run, andmarginal_scan, the scan of each parameter (see the section on the scans).scan: the scans the skew-normals were fitted to, forplot(fit, type = "sn_fit"): the gridzin posterior SDs from the mode, the log-posterior at each point (logpost, a column per parameter: along the CMP, or at the conditional modes formarginal_scan = "laplace"), the width term added to it (width, zero at the mode), and the log scale factorlogCof each fit on that grid. It isNULLfor Gaussian marginals.workers: the number of parallel jobs the scans ran on, 1 for a serial fit (see the section on parallel computation).timing: the elapsed time of each stage of the fit, in seconds, whichtiming()returns.warnings: the messages of the warnings raised during the fit, as a character vector of plain text, each message once (empty when there were none). They are recorded whether or notsilentisTRUE.
Writing logpost
The approximation works on an unconstrained scale: every parameter must be free to take any real value. Reparameterise anything constrained, for example a standard deviation \(\sigma > 0\) as \(\log\sigma\), a probability as its logit, or a correlation as its Fisher \(z\). Means and regression coefficients need no change.
Return -Inf wherever the density is zero or cannot be evaluated, such as
outside the support or where a matrix is not positive definite. NA and
NaN count the same, and so does any value at or below \(-10^{39}\),
such as the -1e40 that some code, lavaan's likelihoods among it, returns
where it fails. The scans and the VB nodes reach several posterior SDs from
the mode, and an error raised there stops the fit.
logpost is then the log density of the parameters you pass. When a
prior is stated on the natural scale, include the log-Jacobian of the
transformation: with \(\vartheta = \log\sigma\) and a prior
\(p(\sigma)\), the prior term is \(\log p(e^\vartheta) + \vartheta\).
Leaving it out targets a different posterior, not a worse approximation of
the same one, and nothing downstream can detect it.
The choice of parameterisation also sets the quality of the approximation,
since each parameter gets its own skew-normal on the scale you choose.
Scales on which the posterior is close to Gaussian (log standard
deviations, Fisher-\(z\) correlations, logits) work best. A parameter
named for its scale is reported on the natural one (see the next section),
and other derived quantities are available through
sampling(fit, fun = ...).
The log marginal likelihood is an estimate of \(\log p(y)\) only when
logpost returns the full \(\log p(y, \vartheta)\), including every
normalising constant of the likelihood and the prior. Otherwise it is off by
the missing constants.
Natural-scale summaries
Name a parameter for the scale it is on and the results are reported on its natural scale. The name is a prefix from the table, an underscore, and the name of the natural-scale parameter:
Name in init | logpost receives | Reported as |
log_sigma | \(\log\sigma\) | sigma, \(e^\vartheta\) |
logit_p | \(\log\{p / (1 - p)\}\) | p, \(1 / (1 + e^{-\vartheta})\) |
atanh_rho | \(\operatorname{artanh}\rho\) | rho, \(\tanh\vartheta\) |
The log suits a positive parameter (an SD, a variance, a precision, a rate or a shape), the logit one between 0 and 1 (a probability), and the inverse hyperbolic tangent, Fisher's \(z\), one between -1 and 1 (a correlation). These are the scales R-INLA itself works on, for nearly all of its hyperparameters: the log, the logit, and for a correlation \(\log\{(1 + \rho) / (1 - \rho)\}\), which is twice Fisher's \(z\).
Nothing changes in the fit. logpost, grad, hess, the loglik of
loo() and the fun of sampling() all receive the parameter under the
name and on the scale of init, and logpost must still include the
log-Jacobian of a prior stated on the natural scale. Only the results are
mapped back, each from its own skew-normal marginal: print(),
summary(), coef() and plot() show sigma, and sampling() returns
draws of it. The quantiles are the fitted quantiles mapped through the
transform. The mean, SD and mode are those of the natural-scale
distribution, so the mean of sigma is not the exponential of the mean of
log_sigma. A line under the table says which rows were mapped, and
fit$transform lists them. The diagnostics stay on the scale of the
computation, under the names in init.
A prefix counts only when an underscore and a name follow it, in lower
case, so logistic, log_ and Log_sigma are left alone. A name that
would clash, such as log_sigma beside a parameter called sigma, is
left on its own scale with a warning. Only these one-to-one maps of a
single parameter are recognised: a quantity that depends on several
parameters, such as a covariance, comes from sampling(fit, fun = ...).
transform = FALSE reports every parameter as logpost receives it, and
summary(), plot() and sampling() take the same argument for a fit
already made.
Accuracy
The skew-normal marginals capture skewness that the Laplace approximation
misses, and they are accurate to the extent that a skew-normal fits each
marginal (see the diagnostics in summary.inla_vanilla()). Like INLAvaan,
each marginal is scanned along a straight line through the mode, and the
changing volume of the other parameters enters only to first order. When a
parameter's spread depends strongly on another, poorly determined
parameter, its marginal comes out too narrow, by a factor that vanishes as
O(1/n). Examples are a regression coefficient or a mean when the noise SD
is uncertain. For a normal mean with unknown variance the SD is about 11%
too small at n = 12, 3% at n = 50, and under 1% at n = 200. The
ridge_bend diagnostic of summary.inla_vanilla() flags this narrowing
where it predicts about 10% or more. By default
(marginal_scan = "linear") this is the scan of INLAvaan;
marginal_scan = "laplace", or tk_fallback = TRUE for the flagged
parameters only, removes the narrowing at a higher cost (see the section on
the scans).
A skew-normal also cannot follow a tail heavier than a Gaussian's. In a
structural equation model with 39 parameters and n = 75, the data could not
keep two residual variances away from zero, so on the log scale their
posteriors had a long, exponential left tail, set by the prior. Checked
against MCMC, those two skew-normal marginals were less than half as wide
as the posterior, with the 2.5% quantile about 2 posterior SDs too high;
the other 37 were within 7% in SD. On the variance scale, where the tail
near zero is compressed, the two were much closer: means 0.2 posterior SDs
too high and SDs 10 to 15% too small. INLAvaan's marginals of this model
are the same as inlavanilla's: Jamil and Rue (2026a, Section 4.4) find
the same miss in the lower tail of a variance near zero, the boundary
pile-up that a unimodal skew-normal cannot capture. No check is aimed at
this. The ridge_bend diagnostic of summary.inla_vanilla() flagged one
of the two (0.44), but the other's ridge bend (0.11) was no larger than
that of marginals within 7% in SD, and the tails check, which looks only
4 posterior SDs either side of the mode (the Laplace SDs), missed both.
The scans
Each skew-normal scan follows the conditional mode path (CMP) of the
Laplace Gaussian, \(\vartheta(t) = \vartheta^* + t v_j\) with
\(v_j = \Omega_{\cdot j} / \sqrt{\Omega_{jj}}\), so that \(t\) counts posterior SDs. The log marginal
is then about the height of the log-posterior along the path plus the
width term \(\gamma_j(t) = -\frac12 \log|H_{-j}(t)|\), where \(H_{-j}\) is the negative Hessian of
the log-posterior with row and column j deleted: the log-volume of the
other parameters. marginal_scan sets how the scan is taken, in four
levels that each remove one error:
"plain"leaves the width term out, and fits the heights alone."linear", the default and INLAvaan's, linearises the width term, \(\gamma_j(t) \approx \gamma_j' t\), with the slope from whitened differences of the gradient (Jamil & Rue, 2026a, Corollary 3.3). Its difference from"plain"is the volume correction."exact"takes \(\gamma_j(t)\) exactly along the same path. Its difference from"linear"is the error of the linearisation."laplace"moves the other parameters to their conditional mode at each point of the scan and takes the height and the width term there: the Laplace approximation of the marginal (Tierney & Kadane, 1986), INLA's "Laplace strategy". Its difference from"exact"is the error of the straight path, which theridge_benddiagnostic ofsummary.inla_vanilla()predicts.
The skew-normal is fitted to the corrected heights in the same way for
all four, on the same grid. tk_fallback = TRUE keeps the cheap scan
for every parameter but those whose ridge bend is flagged, and rescans
those with "laplace". In fit$diagnostics$marginals, marginal_scan
gives the scan each parameter used and gamma1 the slope of its width term
at the mode (for "exact" and "laplace", a central difference across the
mode, and NA for "plain"). The ridge bend of a parameter scanned with
"laplace" is still reported, but not flagged.
Gradients and Hessians
grad is optional. Without it, derivatives come from finite differences
of logpost, and the number of calls grows with the square of the number
of parameters m. The mode and Hessian take about m^2 + 6m calls, and the
marginals about m(n_grid + 2m + 6), with 2(m - 1) more for each parameter
whose ridge bend is above 0.1. The VB correction takes 2(m + 1)(m + 2) + 8m
calls, or (m + 1)(m + 2) per sweep with vb_correction = "full": it needs
no derivatives, because Stein's identity gives the expected gradient from
values of logpost alone. With vb_correction = "full", the VB mean is then
exact
when the log-posterior is a polynomial of degree four in whitened
coordinates, and up to degree six with grad. On test models it was about
0.01 posterior SDs from exact VB (0.003 with grad), and up to 0.1 on a
strongly skewed posterior (0.03 with grad), against a VB error of 0.01 to
0.2 SDs from the posterior mean itself. On the most skewed posteriors the VB
correction of vb_correction = "full" may then not settle, and the fit says
it has not converged (see summary.inla_vanilla()); grad is the remedy.
With grad, every stage is more accurate. The fit is also faster when a
gradient call costs about as much as a logpost call, as a hand-written
gradient usually does, since it then makes far fewer calls in all. A
gradient by automatic differentiation (RTMB, TMB) costs about two, and
beyond a handful of parameters the fit is still several times faster than
without one (four times at m = 39). The default VB correction,
vb_correction = "onestep", takes 2m + 1 gradient calls, about as many as
one numerical Hessian, and vb_correction = "full" takes at most (m + 1)(m +
2) + 1 per sweep, usually about four sweeps. Beyond a handful of parameters
the marginals are the slowest stage, along with the VB correction under
vb_correction = "full". vb_correction = "none" skips the VB correction
(and its term in the log marginal likelihood), and the skew-normal marginals
do not depend on it; marginals = "gaussian" saves the calls of the scans.
hess is optional too, and needs grad, as in stats::nlminb(). With
it, stats::nlminb() takes Newton steps to the mode, and the Hessian at
the mode is the supplied one. The VB correction does not use it, nor do the
default marginals, whose volume correction takes 4m + 1 grad calls for all
the parameters together, where a Hessian each would cost far more.
marginal_scan = "exact" and "laplace" do use it. The fit is the one
grad alone gives, to the error of its finite differences (about 1e-8,
relative), except that the mode is found more precisely, and that the VB
correction of a fit that fails its check can stop sooner (see "The VB
correction"). A dense Hessian costs about m gradients, so this takes a little
longer: a structural equation model with 39 parameters and an
automatic-differentiation Hessian (RTMB) took 0.18 s with it and 0.17 s
without.
The fit goes straight to the mode: at init it only checks that logpost,
grad and hess return finite values of the right shape. A supplied grad
is compared with logpost at the mode, and the Hessian there, whether taken
from grad or supplied, is checked for symmetry, with a warning if either
check fails (see grad_gap in summary.inla_vanilla()). Without hess, the
comparison reads differences the fit takes there anyway to set its steps, at
no cost in calls. With hess it takes them for the check alone, at steps
set from the diagonal of hess: 2 logpost calls per parameter, so about
2m calls, and more for a parameter whose diagonal is far off, where the step
search goes on (up to 60 calls for that parameter). A supplied hess
is also checked at the mode against central differences of grad, along two
directions, with a warning if it does not match, and its diagonal is part of
what grad_gap compares with logpost. Any R function works for logpost,
grad and hess, including compiled code (Rcpp, TMB) and RTMB, which
differentiates R code. An RTMB function can return the log-posterior itself,
and its obj$fn, obj$gr and obj$he are then passed as they are. For a
TMB template that returns the negative log-posterior, pass
function(x) -obj$fn(x), function(x) -as.vector(obj$gr(x)) and
function(x) -obj$he(x), with init = obj$par; its repeated names (one per
element of a parameter vector) are numbered, as beta[1], beta[2], and so
on. TMB gives no Hessian for a model with random effects.
The VB correction
The VB mean correction moves the centre of the Laplace Gaussian towards the posterior, keeping its covariance. It maximises the expected log-posterior under that Gaussian, so that at the solution the gradient, averaged over the Gaussian, is zero.
vb_correction = "onestep" takes the first Newton step towards that
solution, with the Laplace curvature, and stops. With a gradient, the average
is taken over the mode and \(\pm\sqrt 3\) along each axis of
the symmetric square root of the covariance, taken on the correlation scale.
Without one, it is one pass of Stein's identity on the rule of
vb_correction = "full". Most of the movement is in that step, and exact VB
is itself an approximation to the posterior mean with an error of the same
order.
One step is the first iterate of a fixed-point map, and it approximates the
solution only where that map is a contraction. The fit checks this, with a
second sweep at the step. The step must reduce the residual of the VB
equation (vb_lhat in diagnostics(), the ratio of the residual at the step
to the one at the mode, below 1), and the slope of the map along the step
must lie between -1 and 1 at the mode and at the step (vb_j0 and vb_j1).
When the check passes, the one step is the correction. When it fails, the
posterior is far from Gaussian along the step, and the fit solves the VB
equation instead, on the same sweeps and from the mode, by Broyden's method.
It then raises a warning that names the parameter the one step moved
furthest. The warning comes whether or not the solve converged, since it is
about the posterior and not the solver: treat the posterior means, the log
marginal likelihood, loo() and waic() of such a fit with care, and
compare with MCMC if they matter. vb_solve in diagnostics() says whether
the solve ran, and vb_step_sigma is then the step still to go where it
stopped, which is recorded and not flagged. If logpost or grad is not
finite at a node around the mode there is no step to check, and the
optimiser of vb_correction = "full" takes over.
The check, the solve, the warning and the diagnostics are the same with and
without a gradient. Only the sweep differs. With a gradient it is 2m + 1
gradients, so the correction of a fit that passes takes 4m + 2 gradient
calls. Without one it is a Stein pass of (m + 1)(m + 2) values of logpost,
and the two slopes take 4m values each. The sweeps of a correction, the two
of the check among them, are capped at twice the number of calls that the
mode and Hessian took, divided by 2m + 1. A fit that passes the check takes
its two sweeps and never meets the cap. With a gradient the correction of a
fit that fails it therefore costs no more than twice what the mode and
Hessian did. Without one the cap is the same number of sweeps, each of which
costs more: a fit that fails the check can then spend up to
2(m + 1)(m + 2) / (2m + 1) times the calls of its mode and Hessian, about m
times, on the correction. That is the price of a fit without a gradient, and
grad is the remedy. The factor of two is vb_budget in
vanilla_control(), and Inf there removes the cap.
With hess the mode and Hessian usually take fewer calls than with grad
alone, so the cap is lower. A fit that fails the check can then stop its
solve sooner, and land elsewhere than the same fit without hess. A larger
vb_budget narrows that difference, and Inf removes it.
A large first step can also overstate the VB term of the log marginal
likelihood, so after a shift above 1 posterior SD, which is flagged, compare
models with care: vb_correction = "full" may be closer.
vb_correction = "full" iterates to the solution, on a degree-5 rule with at
most (m + 1)(m + 2) + 1 nodes, and hands over to stats::nlminb() if it does
not converge.
Parallel computation
Set cores to run the per-parameter scans of the skew-normal marginals in
parallel:
cores <- parallelly::availableCores(omit = 1)
fit <- inla_vanilla(logpost, init, marginal_scan = "laplace", cores = cores)parallelly::availableCores() counts the cores the machine offers, and
omit = 1 leaves one free. A fit never asks for more workers than the
machine offers. The results and the progress line are those of a serial fit.
A long scan uses all the cores, a shorter one fewer, and a scan expected to
take under a second stays serial. The mode, the Hessian and the VB correction
stay serial, so the gain is largest with marginal_scan = "laplace" or
"exact", where the scans are nearly the whole fit: about 7.5 times faster
on 12 cores on test models. With the default scan the scans are about half of
a slow fit, and it was about 1.5 times at most.
cores needs the future package, which is optional. It uses forked workers
where those are safe, in a terminal on macOS or Linux, and separate R
sessions elsewhere: on Windows, in RStudio, and in Positron's console, which
refuses to fork. Forks share everything. Separate sessions need the package
installed, not just loaded with devtools::load_all(), and are sent your
functions and data. Compiled code (Rcpp, TMB, RTMB) cannot be sent, so the
fit first checks that a worker gets the same value at the mode, and
otherwise runs serially with a message.
To use separate sessions with compiled code, rebuild it on each worker: put whatever creates it in a function, and call that function again when the process is not the one that started the fit. With RTMB and random effects (without them, RTMB needs none of this):
build <- function() {
RTMB::MakeADFun(model, parameters, random = "u", silent = TRUE)
}
obj <- build()
pid <- Sys.getpid()
rebuild <- function() {
if (Sys.getpid() != pid) {
obj <<- build()
pid <<- Sys.getpid()
}
}
logpost <- function(theta) {
rebuild()
-obj$fn(theta)
}
grad <- function(theta) {
rebuild()
-obj$gr(theta)
}With Rcpp, rebuild() calls Rcpp::sourceCpp(file, cacheDir = dir) instead,
with a dir of your own so that the workers share one compiled copy. The
RTMB and Rcpp articles on the package website have worked versions.
With cores left at NULL the fit follows a plan set with future::plan(),
and runs serially if there is none, so a plan can apply to every fit in a
session. cores = 1 runs serially whatever the plan. loo() and waic()
use the setting of the fit.
Output
By default each stage prints one line as it finishes, with the time it
took, and shows a progress bar while it runs for longer than half a
second, or than the option cli.progress_show_after when it is set. In
knitr or Quarto documents, where a bar cannot redraw in place, a larger
cli.progress_show_after in the setup chunk keeps bars out of the output.
Warnings, such as a gradient that does not match logpost, are signalled
as usual. A fit whose checks look off, such as a mode that was not
reached, ends with one warning that lists them, as INLAvaan's does (see
summary.inla_vanilla() and diagnostics()).
verbose = TRUE adds a full diagnostic of the fit, in grey lines under
each stage. It reports what the fit computes anyway, with no further calls
of logpost or grad:
Before the mode search: the parameters, where the derivatives come from, and
logpostatinit.The mode: the message, iterations and evaluations of
stats::nlminb(), and whether it was restarted with the parameters rescaled (the iterations and evaluations are then the totals over both runs, and the restart line gives each run's own iterations); the log-posterior at the mode, the whitened gradient there (which decides the restart) and the largest Newton step in posterior SDs (which the fit-time warning checks); how the Hessian was taken (and, for a suppliedgrad, the asymmetry of the Hessian and its gap fromlogpost, and, for a suppliedhess, how far it is from central differences ofgrad); the largest posterior correlation and the smallest eigenvalue of the correlation matrix, which is near zero when some combination of the parameters is poorly identified, and the condition number of the Hessian in posterior-SD units; and the Laplace log marginal likelihood.The VB correction: the largest step, in posterior SDs, at each fixed-point iteration, whether Anderson acceleration or the fallback optimiser was used (and, after the fallback, the step still to go where it landed, and whether it was rerun from there), the largest shift, and the term it adds to the log marginal likelihood.
The marginals: the shape, NMAD, ridge bend, tails, unscanned mass and volume correction
gamma1of each parameter, with the values thatsummary.inla_vanilla()flags marked.The calls of
logpost,gradandhessin each stage, and in all, with the total time.
For the iteration trace of stats::nlminb() itself, pass
control = vanilla_control(nlminb = list(trace = 1)).
silent = TRUE prints nothing, for simulations and other repeated fits:
no progress bars and no stage lines, and every warning and message raised
during the fit, including those of logpost, grad and hess, is
muffled. Errors are still raised. Output printed with cat() or
print(), by logpost, grad, hess or the trace of stats::nlminb(),
is not captured.
Whatever the level, the warnings raised during the fit are recorded in
fit$warnings, so that a simulation can check them afterwards.
References
Jamil, H., & Rue, H. (2026a). Approximate Bayesian inference for structural equation models using integrated nested Laplace approximations (arXiv:2603.25690 [stat.ME]). arXiv. https://doi.org/10.48550/arXiv.2603.25690
Jamil, H., & Rue, H. (2026b). Implementation and workflows for INLA-based approximate Bayesian structural equation modelling (arXiv:2604.00671 [stat.CO]). arXiv. https://doi.org/10.48550/arXiv.2604.00671
Tierney, L., & Kadane, J. B. (1986). Accurate approximations for posterior moments and marginal densities. Journal of the American Statistical Association, 81(393), 82–86. https://doi.org/10.1080/01621459.1986.10478240
See also
sampling() for posterior draws and derived quantities,
summary.inla_vanilla() and diagnostics() for diagnostics.
Examples
# Normal data with unknown mean and standard deviation, on the scale
# (mu, log sigma)
set.seed(1)
y <- rnorm(30, mean = 5, sd = 2)
logpost <- function(theta) {
mu <- theta[["mu"]]
sigma <- exp(theta[["log_sigma"]])
sum(dnorm(y, mu, sigma, log = TRUE)) +
dnorm(mu, 0, 10, log = TRUE) + # prior on mu
dexp(sigma, rate = 1, log = TRUE) + # prior on sigma ...
theta[["log_sigma"]] # ... and its Jacobian
}
# The parameter named log_sigma is reported as sigma
fit <- inla_vanilla(logpost, init = c(mu = 0, log_sigma = 0))
#> ✔ Found the posterior mode in 10 iterations [2ms]
#> ✔ VB mean correction, max shift 0.25σ [1ms]
#> ✔ Fitted 2 skew-normal marginals [5ms]
fit
#> ── INLAvanilla v26.12.01 ────────────────────── Skew-normal + one-step VB ──
#>
#> Log marginal likelihood: -66.38 · Converged in 10 iterations (12ms)
#>
#> Mean SD 2.5% 50% 97.5% Mode
#> 1 mu 5.159 0.327 4.517 5.159 5.800 5.159
#> 2 sigma 1.867 0.246 1.458 1.841 2.422 1.793
#>
#> ℹ Natural scale: sigma = exp(log_sigma).
# The same fit as logpost sees it
summary(fit, transform = FALSE)$table
#> Mean SD 2.5% 50% 97.5% Mode
#> mu 5.1588166 0.3272992 4.5168194 5.1589904 5.7998267 5.1593379
#> log_sigma 0.6157719 0.1293211 0.3767418 0.6103815 0.8847449 0.5993436
# A quantity of several parameters, through the draws
cv <- sampling(fit, fun = function(theta) {
exp(theta[["log_sigma"]]) / theta[["mu"]]
})
quantile(cv, c(0.025, 0.5, 0.975))
#> 2.5% 50% 97.5%
#> 0.2688632 0.3571155 0.4917361
# A full diagnostic of each stage
fit <- inla_vanilla(logpost, init = c(mu = 0, log_sigma = 0), verbose = TRUE)
#> ℹ 2 parameters: mu and log_sigma
#> Derivatives by finite differences of logpost
#> logpost at init -481.47
#> ✔ Found the posterior mode in 10 iterations [1ms]
#> nlminb: relative convergence (4), after 10 iterations (14 function and 26
#> gradient evaluations)
#> logpost at the mode -65.06, whitened gradient 9e-08σ, Newton step 9e-08σ
#> (warning > 0.1σ)
#> Hessian by second differences of logpost: 6 calls, and 12 more to set the
#> steps
#> Posterior correlation matrix: largest correlation -0.0042 (mu,
#> log_sigma), smallest eigenvalue 1
#> Hessian condition number 1, in SD units (warning > 1e+08)
#> Laplace log marginal likelihood -66.41
#> 63 logpost calls
#> ✔ VB mean correction, max shift 0.25σ [2ms]
#> Fixed-point steps, largest over the parameters (σ): 0.25
#> One-step check: contraction ratio 0.032, slope along the step -0.031 at
#> the mode and 0.029 at the step (passes below 1 in size)
#> One step, accepted
#> Largest shift 0.25σ, for log_sigma (warning > 1σ)
#> KL term 0.031, giving a log marginal likelihood of -66.38
#> 28 logpost calls
#> ✔ Fitted 2 skew-normal marginals [5ms]
#> Shape NMAD Ridge bend Tails Unscanned gamma1
#> mu -0.25 4.2e-05 0.13 ok 6.4e-05 -0.00014
#> log_sigma 1.32 0.0076 3.6e-06 ok 0.00057 0.13
#> ! marks what summary() flags: NMAD > 0.1, ridge bend > 0.25, heavy tails,
#> unscanned mass > 0.05
#> 68 logpost calls
#> ℹ Done: 159 logpost calls in 28ms
# Nothing printed, as in a simulation; any warnings are kept in the fit
fit <- inla_vanilla(logpost, init = c(mu = 0, log_sigma = 0), silent = TRUE)
fit$warnings
#> character(0)
