This release is a pre-release and may not be stable for production use.
pytorch-hessian-eigenthings
The hessian-eigenthings module provides an efficient (and scalable!) way to compute the eigendecomposition of the Hessian, plus other curvature matrices like the Generalized Gauss-Newton and empirical Fisher, for an arbitrary PyTorch model. You get top eigenvalues and eigenvectors via Lanczos or stochastic power iteration, trace estimates via Hutch++, and the spectral density via Stochastic Lanczos Quadrature.
v1.0.0a1: alpha release. The
0.xAPI has been removed; pinhessian-eigenthings==0.0.2if you depend on it.
Why use this?
The eigenvalues and eigenvectors of the Hessian have been implicated in many generalization properties of neural networks. People hypothesize that "flat minima" generalize better, that Hessians of large models are very low-rank, that certain optimizers lead to flatter minima, and so on. But the full Hessian costs memory quadratic in the number of parameters, infeasible for anything but toy models.
Iterative methods like Lanczos and power iteration only need a matrix-vector product. The Hessian-vector product (HVP) is exactly that, and it costs linear memory. This library combines the HVP with iterative algorithms to compute the eigendecomposition without the quadratic memory bottleneck, and works on real models including HuggingFace and TransformerLens transformers.
Installation
pip install hessian-eigenthings
# or with HuggingFace / TransformerLens helpers:
pip install "hessian-eigenthings[transformers,transformer-lens]"
Usage
Build a CurvatureOperator from your model, run any algorithm against it.
import torch
from torch import nn
from hessian_eigenthings import (
HessianOperator, lanczos, trace, spectral_density, supervised_loss,
)
model = nn.Sequential(nn.Linear(20, 32), nn.Tanh(), nn.Linear(32, 1)).to(torch.float64)
x, y = torch.randn(128, 20, dtype=torch.float64), torch.randn(128, 1, dtype=torch.float64)
data = [(x[i:i+32], y[i:i+32]) for i in range(0, 128, 32)]
H = HessianOperator(model, data, supervised_loss(nn.functional.mse_loss))
eig = lanczos(H, k=5, seed=0) # top-5 eigenvalues + eigenvectors
t = trace(H, num_matvecs=99, seed=0) # Hutch++ trace estimate
density = spectral_density(H, num_runs=8, lanczos_steps=40, seed=0)
If you'd rather use the GGN (PSD by construction, often what's meant by "the Hessian" on classification losses), swap in GGNOperator. For per-sample-gradient outer products, EmpiricalFisherOperator. They share the same interface so all the algorithms above work on any of them.
There's a finite-difference HVP path (HessianOperator(method="finite_difference")) for when double-backward is impractical, useful with FSDP and similar setups. You can restrict to a parameter subset with param_filter=match_names("blocks.*.attn.*") for per-block analysis.
See examples/ for runnable scripts on a small MLP, HuggingFace tiny-GPT2, and a TransformerLens model. Full docs at https://noahgolmant.github.io/pytorch-hessian-eigenthings.
Working on the library
Uses uv:
git clone https://github.com/noahgolmant/pytorch-hessian-eigenthings
cd pytorch-hessian-eigenthings
uv sync --group dev --group docs --extra transformers --extra transformer-lens --extra curvlinops
uv run pytest
uv run mkdocs serve
Citing this work
If you find this repo useful and would like to cite it (as others have done, thank you!):
@misc{hessian-eigenthings,
author = {Noah Golmant and Zhewei Yao and Amir Gholami and Michael Mahoney and Joseph Gonzalez},
title = {pytorch-hessian-eigenthings: efficient PyTorch Hessian eigendecomposition},
month = oct,
year = 2018,
version = {1.0},
url = {https://github.com/noahgolmant/pytorch-hessian-eigenthings}
}
Acknowledgements
The original 2018 implementation was written with Zhewei Yao, Amir Gholami, Michael Mahoney, and Joseph Gonzalez at UC Berkeley's RISELab.
The deflated power iteration is based on code from HessianFlow (Z. Yao, A. Gholami, Q. Lei, K. Keutzer, M. Mahoney. "Hessian-based Analysis of Large Batch Training and Robustness to Adversaries", NeurIPS 2018, arXiv:1802.08241). Accelerated stochastic power iteration is from C. De Sa et al., "Accelerated Stochastic Power Iteration", PMLR 2017 (arXiv:1707.02670). The v1 refresh borrows ideas from PyHessian, curvlinops, and HessFormer.
License
MIT.
Metadata
Release files for hessian-eigenthings 1.0.0a5
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| hessian_eigenthings-1.0.0a5.tar.gz | 360.7 kB | Without provenance | Details for hessian_eigenthings-1.0.0a5.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| hessian_eigenthings-1.0.0a5-py3-none-any.whl | Python 3 | none | any | Details for hessian_eigenthings-1.0.0a5-py3-none-any.whl |
Total release size: 393.9 kB
Release files / hessian_eigenthings-1.0.0a5.tar.gz
| Download URL | hessian_eigenthings-1.0.0a5.tar.gz |
|---|---|
| Size | 360.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
741ec286623875d16006cd8a72b53738a6db2584b2135da922d17f396910c18c
|
|
BLAKE2b-256 checksum How to use checksums |
1ea48542e9a54cae0e4c50731597dcd59881d919a666e0697891673f719896f4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.9.17 {"installer":{"name":"uv","version":"0.9.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / hessian_eigenthings-1.0.0a5-py3-none-any.whl
| Download URL | hessian_eigenthings-1.0.0a5-py3-none-any.whl |
|---|---|
| Size | 33.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2f9c46cec4682389348db877c6ba08d49fbed5c3687aaf899e5c47d0f507583b
|
|
BLAKE2b-256 checksum How to use checksums |
e979c292360c7aacb1d54bdcd3f0b9c61bcf028af8b558bb93e4b5735616cb67
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.9.17 {"installer":{"name":"uv","version":"0.9.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for hessian-eigenthings 1.0.0a5
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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
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.