Torch-KF
torch-kf is a PyTorch implementation of classic Kalman filtering and smoothing, designed for batched processing of many independent signals. It supports filtering and Rauch-Tung-Striebel (RTS) smoothing, runs on CPU or GPU (via PyTorch), and natively handles batch dimensions without Python loops.
This project is inspired by Roger R. Labbe Jr.’s excellent work:
- filterpy
- Kalman and Bayesian Filters in Python (interactive book)
Currently, torch-kf focuses on traditional linear Kalman filters with Gaussian noise. In the future, it may extend to a wider range of filters (e.g. EKF, UKF, IMM, ...).
Why torch-kf?
Kalman filtering is inherently sequential in time and typically involves small matrices (often < 10×10 in physics-based models). As a result, a single Kalman filter does not benefit much from GPU acceleration and may even be faster with NumPy-based implementations such as filterpy.
However, many real-world problems involve filtering large batches of independent signals in parallel, such as:
- multi-object tracking,
- ensemble-based inference,
- large-scale simulations,
- batched time-series processing.
This is where torch-kf shines.
Key ideas
- Batch-first design: filter hundreds or thousands of independent signals at once.
- No Python loops over signals: computations are vectorized.
- Automatic parallelization: PyTorch distributes work across multiple CPU cores or runs it on GPU.
- Flexible broadcasting: states, measurements, and even models can be batched.
When many signals are filtered together, torch-kf can be orders of magnitude faster (typically up to 200× on CPU and 500×–1000× on GPU) compared to running independent filters sequentially as in filterpy.
Numerical considerations
Installation
pip
pip install torch-kf
From source
git clone git@github.com:raphaelreme/torch-kf.git # OR https://github.com/raphaelreme/torch-kf.git
cd torch-kf
pip install .
Getting started
import torch
from torch_kf import KalmanFilter, GaussianState
# Example: filtering 100 independent 2D trajectories over 1000 timesteps
# Measurements must be column vectors (..., dim, 1)
noisy_data = torch.randn(1000, 100, 2, 1)
# Initialize the Kalman filter model
# Constant-velocity model (dt = 1)
F = torch.tensor([ # Process matrix: # x_{t+1} = x_{t} + v_{t} * dt (dt = 1)
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 1],
], dtype=torch.float32)
Q = torch.eye(4) * 1.5**2
# Where only the position is measured, with some noise R
H = torch.tensor([
[1, 0, 0, 0],
[0, 1, 0, 0],
], dtype=torch.float32)
R = torch.eye(2) * 3.0**2
kf = KalmanFilter(F, H, Q, R)
# Initial belief: zero position/velocity with large uncertainty
state = GaussianState(
mean=torch.zeros(100, 4, 1),
covariance=torch.eye(4)[None].expand(100, 4, 4) * 150**2,
)
# Filter all signals at once
states = kf.filter(
state,
noisy_data,
update_first=True,
return_all=True,
)
# states.mean: (1000, 100, 4, 1)
# states.covariance: (1000, 100, 4, 4)
# Optional RTS smoothing
smoothed = kf.rts_smooth(states)
# smoothed.mean: (1000, 100, 4, 1)
# smoothed.covariance: (1000, 100, 4, 4)
# Online filtering: process measure as they come
generator = ... # Read measure from a file / sensor
for t, measure in enumerate(generator):
# A prior on timestep t
state = kf.predict(state)
# Update with measure at time t
state = kf.update(state, measure)
Tip: For standard motion models (constant velocity, acceleration, jerk), see
torch_kf.ckf, which provides helpers to construct well-scaled F, H, Q, and R matrices.
Time-varying models
Both kf.filter and kf.rts_smooth support time-varying models: when the
sampling interval changes or the sensor evolves over time, you can override the
process model (process_matrix, process_noise) and the measurement model
(measurement_matrix, measurement_noise) per step instead of using the constant
model registered on the filter. In every case, a plain 2D matrix is shared across
all steps, while a leading time axis supplies one matrix per step.
Pass the per-step models to kf.filter to run the forward pass:
states = kf.filter(
state,
noisy_data,
process_matrix=torch.stack(transitions),
process_noise=torch.stack(noises),
# measurement_matrix / measurement_noise can be overridden the same way
)
For T measures, the measurement overrides carry T entries (one per update),
while the process overrides carry one entry per prediction step: T - 1 with
update_first=True (the initial state is already the prior at t=0) or T with
update_first=False (a prediction runs before the very first update).
To smooth such a trajectory, reuse the same transition matrices and process noise covariances on the backward pass:
smoothed = kf.rts_smooth(states, process_matrix=torch.stack(transitions), process_noise=torch.stack(noises))
For T filtered states, entry t describes the transition from state t to
state t + 1, so each stack has T - 1 entries (matching kf.filter with the
default update_first=True). For batched overrides whose first batch size equals
the number of steps, pass an explicit time axis to distinguish it from the batch.
For more complex usage, predict, project and update support overriding the process & measurement matrix as well and can directly be called instead.
Examples
The examples/ folder contains simple demonstrations of constant-velocity Kalman filters (1D, 2D, …) using batched signals.
Example: filtering and smoothing noisy sinusoidal trajectories with missing (NaN) measurements:
We also benchmark torch-kf against filterpy to highlight when batched execution becomes advantageous:
For small batch sizes, PyTorch overhead dominates. As the number of signals increases, torch-kf can provide 200× speedups on CPU and 500×+ on GPU.
Contributing
Contributions are very welcome! Feel free to open an issue or submit a pull request.
Many extensions of Kalman filtering and smoothing are not yet implemented (e.g. variants, adaptive models). For a more feature-complete reference, see filterpy.
Citation
This library was originally developed for large-scale object tracking in biology. If you use torch-kf in academic work, please cite:
@inproceedings{reme2024particle,
title={Particle tracking in biological images with optical-flow enhanced kalman filtering},
author={Reme, Raphael and Newson, Alasdair and Angelini, Elsa and Olivo-Marin, Jean-Christophe and Lagache, Thibault},
booktitle={2024 IEEE International Symposium on Biomedical Imaging (ISBI)},
pages={1--5},
year={2024},
organization={IEEE}
}
Metadata
Release files for torch-kf 0.5.0
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 |
|---|---|---|---|---|
| torch_kf-0.5.0.tar.gz | 20.5 kB | Without provenance | Details for torch_kf-0.5.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| torch_kf-0.5.0-py3-none-any.whl | Python 3 | none | any | Details for torch_kf-0.5.0-py3-none-any.whl |
Total release size: 41.3 kB
Release files / torch_kf-0.5.0.tar.gz
| Download URL | torch_kf-0.5.0.tar.gz |
|---|---|
| Size | 20.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
547dfc57d47189bcb04a0b1f5752445924878855aeb8fb1dec3a8f7fa8ded705
|
|
BLAKE2b-256 checksum How to use checksums |
bd118032dd00bac3f2ef7bf96c158d89972595c80ca7d41e40268f50f4fdaa2a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.9.25
|
Release files / torch_kf-0.5.0-py3-none-any.whl
| Download URL | torch_kf-0.5.0-py3-none-any.whl |
|---|---|
| Size | 20.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7a201737fe126c201726c5b900cf7ee041d6f2c2ecf8df698b8bbd10a1eb253b
|
|
BLAKE2b-256 checksum How to use checksums |
9ae89f57c2d20ed0dbcbf9b6d6a559c83d1bac8e30111b15ba3235b210f4c1cc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.9.25
|
Security for torch-kf 0.5.0
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.