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.x API has been removed; pin hessian-eigenthings==0.0.2 if 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 )
... continue reading