Skip to content

Sampling

mgsl.sample(key, lik, mu, schedule, options, *, calculate_diagnostics=True, batch_size=None, devices=None, vectorize=False, progress=True)

Draw schedule.n_paths posterior samples with MGSL.

Chains :func:init (at schedule.tau_start from centre mu), :func:advance (over schedule.taus) and :func:finalize. The samples are approximate: each step replaces the localising distribution by a local Gaussian fit. For a linear model with Gaussian noise and converged solves they are exact.

The run uses the dtype of mu (float64 needs jax_enable_x64; float32 works, with looser attainable solver tolerances).

Parameters:

Name Type Description Default
key Array

Random key (typed or legacy).

required
lik Likelihood
required
mu pytree

Centre the paths start from, e.g. mgvi_fit(...).mean. Its structure, shapes and dtypes define the latent.

required
schedule Schedule
required
options MGVIOptions
required
calculate_diagnostics bool

Record the local ESS and the CG and Newton statistics. Costs 2 n_samples_mgvi + 1 log-likelihood evaluations per fit. Failure counts are recorded either way.

True
batch_size int

Paths per compiled call; batches run one after another and the last one is padded. Default: all paths in one call, kept on the device between steps. Smaller batches bound device memory.

None
devices sequence of jax devices

Shard each batch over exactly these devices (batch_size must be a multiple of their number; by default all paths, padded to a multiple). Default: no sharding, whatever devices exist.

None
vectorize bool

False (default): within a call, paths run one after another, each with as many solver iterations as it needs. True: paths are batched with jax.vmap, which is faster for cheap models or on accelerators, but every solver loop then runs as long as its slowest path.

False
progress bool

Print one line per step to stderr (time, local ESS fraction, failure count). The same lines go to the "mgsl" logger at INFO level.

True

Returns:

Type Description
Result

mgsl.init(key, lik, mu, *, n_paths, tau_start, options, batch_size=None, devices=None, vectorize=False)

Start n_paths localisation paths at tau_start.

Each path starts from y = tau_start (mu + delta) + sqrt(tau_start) z, with z standard normal and delta ~ N(0, Lambda^{-1}) a draw from the Gaussian approximation at mu, whose precision metric is Lambda = I + J^T F J at mu (see :func:advance). Each path's first local fit is warm-started at mu. If N(mu, Lambda^{-1}) were the exact posterior, y would follow the exact localisation process at tau_start. Solver failures of these draws are reported by a warning.

Parameters:

Name Type Description Default
key Array

Random key of the run (typed or legacy). All later random numbers derive from it.

required
lik Likelihood
required
mu pytree

Centre the paths start from, e.g. mgvi_fit(...).mean.

required
n_paths int
required
tau_start float

Localisation time to start at (> 0).

required
options MGVIOptions

Only draw_cg (and the preconditioner) are used here.

required
batch_size int | None

See :func:sample.

None
devices int | None

See :func:sample.

None
vectorize int | None

See :func:sample.

None

Returns:

Type Description
SLState

mgsl.advance(lik, state, taus, options, *, calculate_diagnostics=True, batch_size=None, devices=None, vectorize=False, progress=True, _warn=True)

Advance every path of state along the grid taus.

At each grid point tau the path's localising distribution is fitted by MGVI, warm-started from the previous centre. The fit is a Gaussian N(xbar, Lambda^{-1}) with precision Lambda = (1 + tau) I + J^T F J at xbar (J the Jacobian of the forward model, F the Fisher metric of the noise model). The observation then moves to the next grid point, dtau later, as if the unknown were a draw from that Gaussian: y += dtau (xbar + delta) + sqrt(dtau) z, with delta ~ N(0, Lambda^{-1}) and z ~ N(0, I) fresh for every step and path.

Each step is one compiled call (for all paths, or per batch), so the grid's length and values do not cause recompilation.

Parameters:

Name Type Description Default
lik Likelihood
required
state SLState
required
taus array

Increasing grid; taus[0] must equal state.tau (relative tolerance 1e-12). Use mgsl.grid(state.tau, tau_final, n) for a geometric continuation.

required
options MGVIOptions
required
calculate_diagnostics bool

See :func:sample.

True
batch_size bool

See :func:sample.

True
devices bool

See :func:sample.

True
vectorize bool

See :func:sample.

True
progress bool

See :func:sample.

True

Returns:

Name Type Description
state SLState

At taus[-1].

report Report

With :class:MGSLDiagnostics (or None) and :class:Failures.

mgsl.finalize(lik, state, options, *, calculate_diagnostics=True, batch_size=None, devices=None, vectorize=False, progress=True, _warn=True)

Draw one sample per path from state.

Fits each path's localising distribution at state.tau and returns xbar + delta, with xbar the fit's centre and delta ~ N(0, Lambda^{-1}) a draw from it (see :func:advance). The state is not changed, so it can still be advanced further and finalised again. Samples of paths whose fit hit a non-finite log-likelihood are NaN.

Parameters:

Name Type Description Default
lik Likelihood
required
state SLState
required
options MGVIOptions
required
calculate_diagnostics bool

See :func:sample.

True
batch_size bool

See :func:sample.

True
devices bool

See :func:sample.

True
vectorize bool

See :func:sample.

True
progress bool

See :func:sample.

True

Returns:

Name Type Description
samples pytree

Structured like the latent, with leading axis n_paths; NumPy arrays on the host.

report Report

With the terminal :class:FitDiagnostics (or None) and :class:Failures.

mgsl.mgvi_fit(key, lik, x0, options)

MGVI fit of the posterior (no localisation), e.g. to find the centre paths start from.

Runs options.n_iter_mgvi rounds; each draws options.n_samples_mgvi mirrored residuals at the current centre and runs Newton-CG on the sample-averaged negative log posterior. A fit of the full posterior from a cold start usually needs more rounds than the warm-started fits inside a run, e.g. dataclasses.replace(options, n_iter_mgvi=10). Check convergence, e.g. by comparing the centre after more rounds.

Parameters:

Name Type Description Default
key Array
required
lik Likelihood
required
x0 pytree

Starting centre (e.g. zeros, the prior mean).

required
options MGVIOptions
required

Returns:

Type Description
MGVIResult

mgsl.Result dataclass

Output of :func:sample.

Attributes:

Name Type Description
samples pytree

Structured like the latent, with leading axis n_paths; NumPy arrays on the host. NaN for paths that hit a non-finite log-likelihood (see failures.nonfinite).

state SLState

The paths' state at tau_final; continue it with :func:advance.

schedule Schedule
diagnostics MGSLDiagnostics or None

None if calculate_diagnostics=False.

failures Failures

Solver failure counts of the whole run (start, steps and terminal fit); always present.

mgsl.Report

Bases: NamedTuple

What a call recorded besides its main output.

Attributes:

Name Type Description
diagnostics MGSLDiagnostics or FitDiagnostics or None

:class:MGSLDiagnostics from :func:advance, :class:FitDiagnostics (the terminal fit) from :func:finalize; None if calculate_diagnostics=False.

failures Failures

Always present.

mgsl.MGVIResult

Bases: NamedTuple

Result of :func:mgvi_fit.

Attributes:

Name Type Description
mean pytree

Centre of the fitted Gaussian, structured like the latent.

residuals pytree

n_samples_mgvi residuals drawn at the centre, leading axis n_samples_mgvi; the samples of the fitted Gaussian are mean +- residuals.

failures Failures

Solver failure counts of the fit (arrays of shape (1,)).