Skip to main content

Tests PyPI Python Docs License

mgsl

mgsl is an implementation of the Metric Gaussian Stochastic Localisation (MGSL) algorithm, written in jax. Broadly, MGSL can be understood as a variational inference (VI) method that produces independent posterior samples. The approximation to the posterior includes all correlations, and does not assume any particular variational family. As such, MGSL is particularly well suited to massive-scale inference problems where the posterior is non-Gaussian, but still unimodal.

Documentation: https://tomhilder.github.io/mgsl/

Status: under heavy development. MGSL is an in-progress research project, and this code will certainly evolve. Expect bugs, quirks, breaking changes and mistakes. Many properties of the method are still unknown: there is (currently) no principled way to choose the tuning parameters (the number of observation-time steps, and the number of MGVI samples and iterations per step). Essentially nothing is known yet about the error properties of the posterior approximation.

Please report bugs and problems through GitHub Issues, and get in touch before publishing comparisons with MGSL.

The algorithm operates by running localisation "paths". Each of these paths is independent, and produces a single posterior sample.

In a bit more detail, each path follows the observation process $\mathbf{Y}_\tau = \tau \mathbf{X} + \mathbf{W}_\tau$ where $\mathbf{X} \sim p(\mathbf{x} \mid \mathbf{d})$ is a currently unknown posterior sample, $\mathbf{W}_\tau$ is a standard Brownian motion process. The observation time $\tau$ grows until $\mathbf{Y}_\tau / \tau$ converges to $\mathbf{X}$. Given $\mathbf{Y}_\tau = \mathbf{y}$, the unknown follows the localising distribution $\pi_\tau(\mathbf{x} \mid \mathbf{y}) \propto p(\mathbf{x} \mid \mathbf{d})\, \mathcal N(\mathbf{y} \mid \tau \mathbf{x}, \tau \mathbf{I})$. At every step mgsl approximates $\pi_\tau$ as a Gaussian, with parameters determined by a matrix-free MGVI fit, and then increments $\mathbf{y}$ as if $\mathbf{X}$ were drawn from that Gaussian.

The model must be setup in a particular way to use mgsl. Namely, the parameters must be a single vector with independent standard normal priors on all entries. Typically this is done by using transformations to obtain the priors of interest. The likelihood must also provide its Fisher metric in terms of matrix-vector products. mgsl can work with any jax model, and also works out-of-the-box with nifty.re models through a provided adaptor.

Why MGSL

  • No global variational family. MGSL assumes no global family: it builds a global approximation out of many local Gaussian fits, one per step along each localisation path. It is designed for posteriors that are non-Gaussian.
  • Scales linearly in dimension. Every fit is implicit and matrix-free: we never build a dense covariance matrix, and use only Jacobian-vector products and conjugate-gradient solves via the Fisher metric. Like typical MGVI, we keep all correlations between parameters (full rank) at a cost only linear in the number of model parameters.
  • Embarrassingly parallel. Each sample comes from its own path, independent of all others. If you have N GPUs (or CPU cores), you can run N samples simultaneously. If your model is cheap this can be worth it on CPU, but generally for larger models it's better to do one sample at a time on CPU.

The most noteworthy (known) limitations are that MGSL is still approximate, and that it cannot handle multimodal distributions.

Installation

pip install mgsl
# or
uv add mgsl

or the latest version from GitHub:

pip install "git+https://github.com/TomHilder/mgsl.git"
# or
uv add "mgsl @ git+https://github.com/TomHilder/mgsl.git"

(or of course by ssh instead).

jax is a runtime dependency. nifty.re is required if you wish to use the adaptor.

Quick start

A simple linear model with Gaussian noise:

from dataclasses import replace

import jax
import jax.numpy as jnp

import mgsl

jax.config.update("jax_enable_x64", True)  # recommended: tighter solver tolerances

n_latent, n_data, sigma = 3, 20, 0.1
A = jax.random.normal(jax.random.key(0), (n_data, n_latent))
data = A @ jnp.ones(n_latent) + sigma * jax.random.normal(jax.random.key(1), (n_data,))


def forward(x):  # latent x ~ N(0, I) -> prediction of the data
    return A @ x


lik = mgsl.gaussian(forward, data, noise_std=sigma)

options = mgsl.MGVIOptions(
    n_samples_mgvi=1,  # residual draws per local mgvi fit (doubled in practice via mirror samples)
    n_iter_mgvi=1,  # mgvi rounds per localisation step: (draw residuals, Newton) per step
    newton=mgsl.NewtonOptions(maxiter=5),
)

# Initialise from a longer MGVI fit
fit = mgsl.mgvi_fit(jax.random.key(3), lik, jnp.zeros(n_latent), replace(options, n_iter_mgvi=10))

schedule = mgsl.Schedule(n_paths=256, tau_start=1.0, tau_final=1e5, n_tau=32)
result = mgsl.sample(jax.random.key(4), lik, fit.mean, schedule, options)

result.samples  # (256, 3) NumPy array: posterior samples
result.diagnostics.ess_fraction  # (256, 31): local ESS fraction per path and step
result.failures.totals()  # solver failure counts (always recorded)

There are no defaults for the schedule or for the number of samples and rounds of the local fits: they depend on the problem. This is an active research project and we currently do not have a confident enough understanding of the algorithm to make many recommendations here. The user guide goes into some detail in terms of diagnostics however, and also covers nifty.re models, resuming runs, batches and devices, and power-user options. Example notebooks are in examples/.

Citation

MGSL paper coming soon.

MGSL builds on previous work in:

  • Stochastic localisation: R. Eldan (2013), Thin shell implies spectral gap up to polylog via a stochastic localization scheme, Geometric and Functional Analysis; A. El Alaoui, A. Montanari and M. Sellke (2022), Sampling from the Sherrington-Kirkpatrick Gibbs measure via algorithmic stochastic localization, FOCS; A. Montanari (2023), Sampling, diffusions, and stochastic localization.
  • Stochastic localization via iterative posterior sampling (SLIPS): L. Grenioux, M. Noble, M. Gabrié and A. O. Durmus (2024), ICML.
  • Implicit Gaussian variational inference: J. Knollmüller and T. A. Enßlin (2019), Metric Gaussian variational inference (MGVI); P. Frank, R. Leike and T. A. Enßlin (2021), Geometric variational inference, Entropy (geoVI); G. Edenhofer et al. (2024), Re-envisioning numerical information field theory (NIFTy.re): a library for Gaussian processes and variational inference, Journal of Open Source Software.

Licence

GNU General Public License v3.0 or later; see LICENSE.

Development

uv sync
uv run pytest            # add -m slow for slow tests
uv run ruff check . && uv run ruff format .
uv run mkdocs build --strict

Metadata

Release files for mgsl 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mgsl 0.1.2
File Size Uploaded Provenance Actions
mgsl-0.1.2.tar.gz 48.3 kB With provenance Details for mgsl-0.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mgsl 0.1.2
File Interpreter ABI Platform Actions
mgsl-0.1.2-py3-none-any.whl Python 3 none any Details for mgsl-0.1.2-py3-none-any.whl

Total release size: 100.8 kB

Release files / mgsl-0.1.2.tar.gz

Download URL mgsl-0.1.2.tar.gz
Size 48.3 kB
Tags Source
SHA-256 checksum
How to use checksums
8cc9f3caf8b252b71123a37918de51a780ff5454dc6ca74b937f8cbfd9931312
BLAKE2b-256 checksum
How to use checksums
f1f4e7f6650253596f4274e9cb3e0d5d30fd3f5553dfafdbd95a96a5aaf6a879
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / mgsl-0.1.2-py3-none-any.whl

Download URL mgsl-0.1.2-py3-none-any.whl
Size 52.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
35256e76404783d13a88bcaf4cd4d5772e2600be99eabcd99d3385f17e9a31da
BLAKE2b-256 checksum
How to use checksums
5d49f490dca1447b3940dc81a7220a66c5d43953a677a64b96f76a7a78eff0ce
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for mgsl 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for mgsl-0.1.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.2 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page