TorchPfaffian is a Python package for efficiently computing the Pfaffian of skew-symmetric matrices using PyTorch. Designed as a PyTorch-based alternative to pfapack, it enables GPU acceleration and supports automatic differentiation, making it particularly useful in physics, quantum computing, and machine learning applications.
- Efficient Pfaffian computation for skew-symmetric matrices
- GPU acceleration via PyTorch
- Support for automatic differentiation
- Seamless integration with PyTorch tensors
With python and pip installed, run the following commands to install TorchPfaffian:
pip install torchpfaffianFor development, this project uses uv. Clone the repository and set up the environment with:
uv sync --dev --extra cpuUse the cu128 or cu130 extra instead of cpu to install a CUDA-enabled build of PyTorch. See
.github/CONTRIBUTING.md for the full contribution workflow.
A Rust-accelerated signed-Pfaffian strategy (RustPfaffianParlettReid) is available when the
package is built with its native extension. Building from source requires a Rust toolchain
(https://rustup.rs); the project builds with maturin:
uv run maturin develop --release -m rust/Cargo.tomlUse --release for an optimized build: maturin develop compiles in debug mode by default,
which makes the Rust kernel much slower. Installing a prebuilt wheel (or maturin build) is already
optimized, so this only matters for local development builds.
If the native extension is not present, the package still works using the pure-Python strategies.
import torch
from torch_pfaffian import pfaffian
# Any skew-symmetric matrix of shape (..., 2n, 2n).
matrix = torch.tensor([[0.0, -3.0], [3.0, 0.0]])
pf = pfaffian(matrix) # signed Pfaffian (default)
magnitude = pfaffian(matrix, sign=False) # |pf|, using the faster det-based pathpfaffian() selects a strategy from the input: sign=True (the default) returns the
signed Pfaffian, using the native RustPfaffianParlettReid when the extension is built and
falling back to the pure-Python PfaffianParlettReid otherwise; sign=False returns the magnitude
using a determinant-based strategy (PfaffianFDBPf when gradients are needed, otherwise
PfaffianDet). For explicit strategy selection, use get_pfaffian_function(name).
- Documentation at https://MatchCake.github.io/TorchPfaffian/.
- Github at https://github.com/MatchCake/TorchPfaffian/.
Repository:
@misc{torchpfaffian_Gince2025,
title={Torch Pfaffian},
author={Jérémie Gince},
year={2025},
publisher={Université de Sherbrooke},
url={https://github.com/MatchCake/TorchPfaffian},
}