Skip to main content

Matfree: Matrix-free linear algebra in JAX

PyPI version License Python versions Docs

Randomised and deterministic matrix-free methods for trace estimation, functions of matrices, and matrix factorisations. Matfree builds on JAX.

  • ⚡ Stochastic trace estimation including batching, control variates, and uncertainty quantification
  • ⚡ A stand-alone implementation of stochastic Lanczos quadrature for traces of functions of matrices
  • ⚡ Matrix-decomposition algorithms for large sparse eigenvalue problems: tridiagonalisation, bidiagonalisation, and Hessenberg factorisation via Lanczos and Arnoldi iterations
  • ⚡ Chebyshev, Lanczos, and Arnoldi-based methods for approximating functions of large matrices
  • ⚡ Gradients of functions of large matrices (like in this paper) via differentiable Lanczos and Arnoldi iterations
  • ⚡ Partial Cholesky preconditioners with and without pivoting
  • ⚡ And much more

Everything is natively compatible with the rest of JAX: JIT compilation, automatic differentiation, vectorisation, and PyTrees. Let us know what you think about Matfree!

Installation

To install the package, run

pip install matfree

Important: This assumes you already have a working installation of JAX. To install JAX, follow these instructions. To combine Matfree with a CPU version of JAX, run

pip install matfree[cpu]

which is equivalent to combining pip install jax[cpu] with pip install matfree. (But do not only use Matfree on CPU!)

Minimal example

Import Matfree and JAX, and set up a test problem.

>>> import jax
>>> import jax.numpy as jnp
>>> from matfree import stochtrace
>>>
>>> A = jnp.reshape(jnp.arange(12.0), (6, 2))
>>>
>>> def matvec(x):
...     return A.T @ (A @ x)
...

Estimate the trace of the matrix:

>>> input_like = jnp.zeros((2,), dtype=float)
>>> sampler = stochtrace.sampler_signs(input_like, num=10_000)
>>> integrand = stochtrace.monte_carlo_trace()
>>> estimate = stochtrace.estimator_monte_carlo(integrand, sampler)
>>>
>>> key = jax.random.PRNGKey(1)
>>> trace = estimate(matvec, key)
>>>
>>> print(trace)
504.0
>>>
>>> # for comparison:
>>> print(jnp.trace(A.T @ A))
506.0

Tutorials

Find many more tutorials in Matfree's documentation.

These tutorials include, among other things:

  • Log-determinants: Use stochastic Lanczos quadrature to compute matrix functions.
  • Pytree-valued states: Combining neural-network Jacobians with stochastic Lanczos quadrature.
  • Control variates: Use control variates and multilevel schemes to reduce variances.
  • Higher moments and UQ: Compute means, variances, and other moments simultaneously.
  • Vector calculus: Use matrix-free linear algebra to implement vector calculus.
  • Low-memory trace estimation: Combine Matfree's API with JAX's function transformations for low-memory stochastic trace estimation.
  • Matrix functions: Compute matrix exponentials and other matrix functions without materialising the matrix.
  • Gaussian log-densities: Differentiate GP hyperparameters using stochastic Lanczos quadrature and CG.

Let us know what you use Matfree for!

Citation

Thank you for using Matfree! A dedicated paper about Matfree itself is in preparation.
In the meantime, if you are using Matfree's differentiable Lanczos or Arnoldi iterations, then you are using the algorithms introduced by this paper. We would appreciate it if you cited it as follows:

@article{kraemer2024gradients,
  title={Gradients of functions of large matrices},
  author={Kr{\"a}mer, Nicholas and Moreno-Mu{\~n}oz, Pablo and Roy, Hrittik and Hauberg, S{\o}ren},
  journal={Advances in Neural Information Processing Systems},
  volume={37},
  pages={49484--49518},
  year={2024}
}

If you are using Matfree's differentiable LSMR implementation, then you are using the algorithm from this paper. We would appreciate it if you cited it as follows:

@article{roy2025matrix,
    title={Matrix-Free Least Squares Solvers: Values, Gradients, and What to Do With Them},
    author={Roy, Hrittik and Hauberg, S{\\o}ren and Kr{\"a}mer, Nicholas},
    journal={arXiv preprint arXiv:2510.19634},
    year={2025}
}

Some of Matfree's docstrings contain additional bibliographic information. For example, the matfree.bounds functions link to bibtex entries for the articles associated with each bound. Go check out the API documentation.

Use Matfree's continuous integration

To install all test-related dependencies (assuming JAX is installed; if not, run pip install .[cpu]), execute

pip install .[test]

Then, run the tests via

make test

Install all formatting-related dependencies via

pip install .[format-and-lint]
pre-commit install

and format the code via

make format-and-lint

Install the documentation-related dependencies as

pip install .[doc]

Preview the documentation via

make doc-preview

Check whether the docs can be built correctly via

make doc-build

Contribute to Matfree

Contributions are welcome!

Issues:

Most contributions start with an issue. Please don't hesitate to create issues in which you ask for features, give performance feedback, or simply want to reach out. If you already have public, (Matfree-compatible) code for the feature you're asking for, please include a link in the issue so we can get an idea how comprehensive a typical implementation is.

Pull requests:

To make a pull request, proceed as follows:

  • Fork the repository.
  • Install all dependencies with pip install .[full] or pip install -e .[full].
  • Make your changes.
  • From the project's root, run the tests via make test. Check out make format-and-lint as well. Use the pre-commit hook if you like.
  • Then, make the pull request. Choose an informative title (have a look at previous PRs if you need inspiration), link all related issues, describe the change, and pick a label (e.g. "documentation", or "enhancement"). The label is important because the release notes group the pull requests by label.

When making a pull request, keep in mind the following (rough) guidelines:

Here is what GitHub considers important for informative pull requests.

A quick unittest checklist:

Starting with a basic version of an algorithm is fine, but eventually, Matfree aims to provide robust and user friendly code. This includes testing different variations in the tests. Common considerations include:

  • Is the algorithm randomised? Then, we should test different seeds (e.g. 1, 2, 3). See the existing tests for Hessenberg adjoints for inspiration.
  • Should the algorithm support real and complex arithmetic? If so, parametrise the tests with corresponding dtypes. Use the existing tests for stochastic trace estimation for inspiration.
  • Should the algorithm work for general linear operators, e.g. functions that linearly map dictionaries to dictionaries such as Jacobians of neural networks? If so, cover this case in a test as well. See the tests and code for partial SVDs for inspiration.

If any of the current code does not fulfill these goals, reach out by opening an issue.

Extend Matfree's documentation

Write a new tutorial:

To add a new tutorial, create a Python file in tutorials/ and fill it with content. Use docstrings (mirror the style in the existing tutorials). Make sure to satisfy the formatting- and linting-requirements. That's all.

Then, the documentation pipeline will automatically convert those into a format compatible with Jupytext, which is subsequently included in the documentation. If you do not want to make the tutorial part of the documentation, make the filename have a leading underscore.

Extend the developer documentation:

To extend the developer documentation, create a new section in the README. Use a second-level header (which is a header starting with "##") and fill the section with content. Then, the documentation pipeline will turn this section into a page in the developer documentation.

Create a new module:

To make a new module appear in the documentation, create the new module in matfree/, and fill it with content. Unless the module name starts with an underscore or is placed in the backend, the documentation pipeline will take care of the rest.

Understand Matfree's API policy

Matfree is a research project, and parts of its API may change frequently and without warning.

This stage of development aligns with its current (0.y.z) version. To quote from semantic versioning:

Major version zero (0.y.z) is for initial development. Anything MAY change at any time. The public API SHOULD NOT be considered stable.

Matfree does not implement an official deprecation policy (just yet) but handles all API change communication via version increments:

  • If a change is backwards compatible (e.g., a backwards-compatible new feature or a bugfix), the patch version is incremented, e.g., from v0.1.5 to v0.1.6.
  • If a change is not backwards compatible, the minor version is incremented, e.g., from v0.1.6 to v0.2.0.

To depend on Matfree's API, pin the minor version (e.g. matfree <= 0.2.0) to avoid breaking your code, but please feel encouraged to upgrade regularly to enjoy all the new features!

Metadata

Release files for matfree 0.6.3

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

Source distribution (sdist)

Source distribution for matfree 0.6.3
File Size Uploaded
matfree-0.6.3.tar.gz 75.8 kB Details

Built distribution (wheel)

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

Total release size: 119.9 kB

Release files / matfree-0.6.3.tar.gz

Download URL matfree-0.6.3.tar.gz
Size 75.8 kB
Tags Source
SHA-256 checksum
How to use checksums
50873d853f169e8c7f77fe1648c524ae73e0171e45b65bf6b792a438a5b624dd
BLAKE2b-256 checksum
How to use checksums
c528b5ea302f983eba5ecb6e1ddf8f827fb625972dd3445e1b3ce021ae879acb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Oct 13, 2026.

Transparency log

Release files / matfree-0.6.3-py3-none-any.whl

Download URL matfree-0.6.3-py3-none-any.whl
Size 44.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b5768db7971ce8d3cef4b2c945ccc95593080cbf6ec041fac3cbb0d815daf0a2
BLAKE2b-256 checksum
How to use checksums
1b103544e312442c78a9467e4bc9ea1757727dcc535504588d31d99c6591cf27
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Oct 13, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.6.3 This release

2 release files

0.6.2

2 release files

0.6.1

2 release files

0.6.0

2 release files

0.5.5

2 release files

0.5.4

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.1

2 release files

0.5.0

2 release files

0.4.1

2 release files

0.4.0

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.1

2 release files

0.1.0

2 release files

0.0.19

2 release files

0.0.17

2 release files

0.0.16

2 release files

0.0.15

2 release files

0.0.14

2 release files

0.0.13

2 release files

0.0.11

2 release files

0.0.10

2 release files

0.0.9

2 release files

0.0.8

2 release files

0.0.7

2 release files

0.0.6

2 release files

0.0.5

2 release files

0.0.4

2 release files

0.0.3

2 release files

0.0.2

2 release files

0.0.1

2 release files

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