PyTorch DTW C++ extension
Dynamic time warping (DTW) and soft-DTW in native PyTorch, with CPU and CUDA backends.
pip install torchdtw
Two variants are implemented: the exact DTW (dtw, dtw_batch, dtw_path), and
soft-DTW (soft_dtw, soft_dtw_batch), its differentiable relaxation
(Cuturi & Blondel, 2017) to use as a loss.
This package requires PyTorch 2.10 or later. It is developed using the PyTorch 2.10 Stable ABI, and compiled with instructions for CUDA cards from Volta to Blackwell. It is available on Linux (with CUDA support), macOS, and Windows (without CUDA). This was originally made for fastabx, but it can be used in other projects.
Usage
This package provides:
dtw
dtw(distances, sx=None, sy=None, *, normalize=True)
Compute the DTW cost of a pair of sequences, or of each pair in a batch of independent pairs.
With 3D distances, only the (sx[b], sy[b]) sub-block of each pair is read.
For B independent pairs, prefer this to dtw_batch + .diagonal(), which computes all B^2 pairs, or to a
loop of 2D calls. Use +inf to mask forbidden alignments. NaN distances are unsupported: the result is
unspecified and may differ between the CPU and CUDA backends.
Parameters:
- distances (
Tensor) – A 2D tensor of shape (N, M) with the pairwise distances between the frames of two sequences, or a 3D tensor of shape (B, N, M) for B independent pairs. - sx (
Tensor | None) – An optional 1D integer tensor of shape (B,) with the lengths of the first sequences, at most N. Defaults to N. Only with 3Ddistances. - sy (
Tensor | None) – An optional 1D integer tensor of shape (B,) with the lengths of the second sequences, at most M. Defaults to M. Only with 3Ddistances. - normalize (
bool) – Whether to divide the cost by the length of the warping path.
Returns:
Tensor– A scalar tensor with the cost for 2Ddistances, a 1D tensor of shape (B,) with the costs for 3D ones.
dtw_batch
dtw_batch(distances, sx=None, sy=None, *, symmetric=False, normalize=True)
Compute the DTW cost between all pairs of sequences of two batches, on the distances 4D tensor.
Only the (sx[i], sy[j]) sub-block of each pair is read, so the padding beyond the sequence lengths is ignored.
Use +inf to mask forbidden alignments. NaN distances are unsupported: the result is unspecified and may
differ between the CPU and CUDA backends.
Parameters:
- distances (
Tensor) – A 4D tensor of shape (n1, n2, s1, s2) with the pairwise distances between the frames of two batches of sequences. - sx (
Tensor | None) – An optional 1D integer tensor of shape (n1,) with the lengths of the first batch, at most s1. Defaults to s1. - sy (
Tensor | None) – An optional 1D integer tensor of shape (n2,) with the lengths of the second batch, at most s2. Defaults to s2. - symmetric (
bool) – Whether the two batches are the same: only the pairsi < jare computed, and mirrored, and the diagonal is 0, the cost of a sequence with itself when the distance of a frame to itself is 0. Requiresn1 == n2. - normalize (
bool) – Whether to divide each cost by the length of its warping path.
Returns:
Tensor– A 2D tensor of shape (n1, n2) with the costs.
dtw_path
dtw_path(distances)
Compute the DTW path of the given distances 2D tensor.
No CUDA variant or batched implementation are provided for now. Use +inf to mask forbidden alignments.
NaN distances are unsupported and give an unspecified path.
Parameters:
- distances (
Tensor) – A 2D tensor of shape (n, m) with the pairwise distances between two sequences.
Returns:
Tensor– A 2D tensor of shape (*, 2) with the indices of the path, from (0, 0) to (n - 1, m - 1).
soft_dtw
soft_dtw(distances, sx=None, sy=None, *, gamma=1.0, bandwidth=-1, normalize=False)
Compute the soft-DTW cost of a pair of sequences, or of each pair in a batch of independent pairs.
Soft-DTW replaces the minimum over alignments of DTW by the soft minimum
-gamma * log(sum(exp(-cost / gamma))), so it is differentiable with respect to distances. Unlike
dtw, the cost is not normalized by the path length by default. With 3D distances, only the
(sx[b], sy[b]) sub-block of each pair is read.
Parameters:
- distances (
Tensor) – A 2D tensor of shape (N, M) with the pairwise distances between the frames of two sequences, or a 3D tensor of shape (B, N, M) for B independent pairs, e.g.torch.cdist(x, y) ** 2for sequences x of shape (B, N, D) and y of shape (B, M, D). Must have a floating dtype. - sx (
Tensor | None) – An optional 1D integer tensor of shape (B,) with the lengths of the first sequences, at most N. Defaults to N. Only with 3Ddistances. - sy (
Tensor | None) – An optional 1D integer tensor of shape (B,) with the lengths of the second sequences, at most M. Defaults to M. Only with 3Ddistances. - gamma (
float) – The smoothing parameter, positive. - bandwidth (
int) – Width of the Sakoe-Chiba band around the diagonal of each pair, in steps along the longer sequence. Negative values disable the band. - normalize (
bool) – Whether to divide the cost of each pair bysx[b] + sy[b] - 1, the length of its longest alignment path.
Returns:
Tensor– A scalar tensor with the cost for 2Ddistances, a 1D tensor of shape (B,) with the costs for 3D ones.
soft_dtw_batch
soft_dtw_batch(distances, sx=None, sy=None, *, gamma=1.0, bandwidth=-1, symmetric=False, normalize=False)
Compute the soft-DTW cost between all pairs of sequences of two batches, on the distances 4D tensor.
Same as soft_dtw, for every pair (i, j) instead of B independent pairs. Only the (sx[i], sy[j])
sub-block of each pair is read.
Parameters:
- distances (
Tensor) – A 4D tensor of shape (n1, n2, s1, s2) with the pairwise distances between the frames of two batches of sequences. Must have a floating dtype. - sx (
Tensor | None) – An optional 1D integer tensor of shape (n1,) with the lengths of the first batch, at most s1. Defaults to s1. - sy (
Tensor | None) – An optional 1D integer tensor of shape (n2,) with the lengths of the second batch, at most s2. Defaults to s2. - gamma (
float) – The smoothing parameter, positive. - bandwidth (
int) – Width of the Sakoe-Chiba band, as insoft_dtw. Negative values disable the band. - symmetric (
bool) – Whether the two batches are the same: only the pairsi <= jare computed, from the blocksdistances[i, j], and mirrored. Unlike indtw_batch, the diagonal is computed. Requiresn1 == n2. - normalize (
bool) – Whether to divide the cost of each pair bysx[i] + sy[j] - 1, as insoft_dtw.
Returns:
Tensor– A 2D tensor of shape (n1, n2) with the costs.
Soft-DTW
Like the exact DTW, soft-DTW takes the distances between the frames of the sequences, so any distance works. For example, with the squared Euclidean distance:
loss = soft_dtw(torch.cdist(x, y) ** 2, sx, sy, gamma=0.1).mean()
The soft-DTW kernels started as torchsoftdtw.
Benchmark
Check this folder for comparisons against reference implementations.
Building from source
To build the CUDA backend from source, CUDA must be found by PyTorch (for example
with CUDA_HOME). The GPU architectures to compile for are set by
TORCH_CUDA_ARCH_LIST. If it is not set, the build targets the architectures of the
visible GPUs only, and fails if no GPU is visible. Set it to build for other GPUs:
TORCH_CUDA_ARCH_LIST="7.0;7.5;8.0;8.6;9.0;10.0;12.0+PTX" pip install --no-build-isolation torchdtw
ROCm backend
The published wheels do not include a ROCm backend. To get one, build from source on Linux in an environment with a ROCm build of PyTorch, setting the AMD GPU architectures you target:
PYTORCH_ROCM_ARCH="gfx90a;gfx942;gfx1100" pip install --no-build-isolation torchdtw
The ROCm backend is built from the same CUDA kernel and gives the same results and error checks as the CUDA backend.
Performance
For many DTWs on short sequences, prefer dtw_batch over a Python loop of dtw calls.
A single dtw_batch launches one CUDA kernel (one block per pair) or one parallel CPU
loop, amortizing dispatch, allocation, and launch overhead across the whole batch.
For B independent pairs, prefer dtw on 3D distances of shape (B, N, M), with sx and
sy, to dtw_batch followed by .diagonal(), which computes all B^2 pairs and needs B
times the distances memory, or to a loop of 2D dtw calls.
On CUDA, each pair is computed by one block, which keeps three anti-diagonals of the
dynamic program in shared memory when they fit: when distances.size(-1) is at most 2730
for dtw and dtw_batch in float32, float16, bfloat16, uint8, int8 and int16 (1638 in
float64, int32 and int64), and 4096 for soft_dtw and soft_dtw_batch (2048 in float64).
Beyond, they are kept in global memory, with no limit on the sequence lengths other than
sx[i] + sy[j] - 1 <= 65535 for each pair.
The forward pass of soft-DTW only keeps the matrix its backward pass needs, of the
size of distances, when distances requires grad. Under torch.no_grad(), or for
inputs that do not require grad, it uses no memory beyond its output.
Edge cases
The CPU and CUDA backends give bit-identical results, except for NaN distances, which are unsupported: their result is unspecified and may differ between the backends. Ties between alignments break as diagonal <= left <= up.
Dtypes
distances dtype |
dtw, dtw_batch, dtw_path |
soft_dtw, soft_dtw_batch |
|---|---|---|
| float32, float64 | Accumulated in the input dtype. | Accumulated in the input dtype. |
| float16, bfloat16 | Accumulated in float32, cast back to the input dtype: an unnormalized cost beyond its range is inf. |
Same. |
| uint8, int8, int16 | Accumulated in int32, or in int64 on the CPU when the longest path could overflow int32. | Rejected. |
| int32, int64 | Accumulated in int64: int64 costs are exact. | Rejected. |
| bool, complex | Rejected. | Rejected. |
With integer distances:
- The normalized cost is divided in int64, rounded toward zero.
- The unnormalized cost is cast to the input dtype, and wraps:
dtw(torch.full((1, 3), 100, dtype=torch.int8), normalize=False)is 44.
sx and sy can have any integer dtype (uint8, int8, int16, int32, int64, uint16, uint32, uint64), the same
for both, and must be on the device of distances.
Sizes and lengths
| Case | CPU | CUDA |
|---|---|---|
2D dtw or soft_dtw with n == 0 or m == 0 |
Empty pair: cost 0, as in the batch ops. | Same. |
dtw_path with n == 0 or m == 0 |
Empty path, of shape (0, 2). | Same. |
Empty batch: n1 == 0, n2 == 0 or B == 0 |
Empty output. | Empty output. |
s1 == 0 or s2 == 0, or a length <= 0 |
Empty pair: cost 0, and gradient 0 for soft-DTW. | Same. |
A length larger than the padded size (sx[i] > s1) |
Raises. | Device-side assert. |
| A uint64 length >= 2^63 | Raises. | Device-side assert. |
A pair whose longest path has more than 65535 cells (n + m - 1 > 65535 for dtw, sx[i] + sy[j] - 1 > 65535 for the others) |
No limit. | Raises when neither sx nor sy is given (checked on the padded sizes); device-side assert otherwise. |
n1 or n2 above 2^31 - 1, or more than 2^31 - 1 pairs with symmetric |
No limit. | Raises. |
Values
- Use
+infto mask forbidden alignments. If every alignment of a pair goes through a masked cell, its cost is+inf, for DTW and for soft-DTW. - With
symmetric,dtw_batchdoes not read the blocksdistances[i, j]withi >= j: its diagonal is 0.soft_dtw_batchdoes not read the blocks withi > j, and computes the diagonal, since the soft-DTW cost of a sequence with itself is not 0. - Soft-DTW tends to the unnormalized DTW cost as
gammatends to 0. - The Sakoe-Chiba band of soft-DTW is floored at half the slope of the diagonal joining the first and last frames
of each pair, so that an alignment always exists, even with
bandwidth=0.
Gradients
dtw,dtw_batchanddtw_pathare not differentiable: no gradient flows back todistances. Use soft-DTW for gradients.- Soft-DTW gives no gradient (zeros) to the padding beyond
sxandsy, to empty pairs, and withsymmetricto the blocks it does not read. - Soft-DTW is differentiable once: its backward pass is not differentiable, so second-order derivatives through it are not available.
Devices
dtw_pathonly has a CPU kernel: a CUDA input is copied to the host, and the path back to the device.- On Windows, torchdtw is built without CUDA support, and CUDA inputs raise.
- The ROCm backend has the same edge cases as the CUDA backend.
Citation
Please cite the fastabx paper if you use this package in your work:
@misc{fastabx,
title={fastabx: A library for efficient computation of ABX discriminability},
author={Maxime Poli and Emmanuel Chemla and Emmanuel Dupoux},
year={2025},
eprint={2505.02692},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2505.02692},
}
Metadata
Release files for torchdtw 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 |
|---|---|---|---|---|
| torchdtw-0.5.0.tar.gz | 148.1 kB | Without provenance | Details for torchdtw-0.5.0.tar.gz |
Built distributions (wheels)
| File | Actions Reset | |||
|---|---|---|---|---|
| torchdtw-0.5.0-cp312-abi3-win_amd64.whl | CPython 3.12 | abi3 | Windows x86-64 | Details for torchdtw-0.5.0-cp312-abi3-win_amd64.whl |
| torchdtw-0.5.0-cp312-abi3-manylinux_2_28_x86_64.whl | CPython 3.12 | abi3 | Linux glibc 2.28+ x86-64 | Details for torchdtw-0.5.0-cp312-abi3-manylinux_2_28_x86_64.whl |
| torchdtw-0.5.0-cp312-abi3-manylinux_2_28_aarch64.whl | CPython 3.12 | abi3 | Linux glibc 2.28+ ARM64 | Details for torchdtw-0.5.0-cp312-abi3-manylinux_2_28_aarch64.whl |
| torchdtw-0.5.0-cp312-abi3-macosx_11_0_arm64.whl | CPython 3.12 | abi3 | macOS 11.0+ ARM64 | Details for torchdtw-0.5.0-cp312-abi3-macosx_11_0_arm64.whl |
Total release size: 10.8 MB
Release files / torchdtw-0.5.0.tar.gz
| Download URL | torchdtw-0.5.0.tar.gz |
|---|---|
| Size | 148.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
771210fb71d7891152c5c15a506f61d8ae84dea333e0c174e4a685334bdb1a31
|
|
BLAKE2b-256 checksum How to use checksums |
ae8e7f0273e36831f3f3a79ca050d08f202f2d254b73fcebab9180376d58cb76
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / torchdtw-0.5.0-cp312-abi3-win_amd64.whl
| Download URL | torchdtw-0.5.0-cp312-abi3-win_amd64.whl |
|---|---|
| Size | 292.2 kB |
| Tags | CPython 3.12 Windows x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
3bdc0b0a717616c4eaee75190474b052fe7d01d92b53552ce6316e529973dc3b
|
|
BLAKE2b-256 checksum How to use checksums |
ba16e34965f8d5c822d1a609182061b742009d51c85043f388932e7e7eaae1c3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / torchdtw-0.5.0-cp312-abi3-manylinux_2_28_x86_64.whl
| Download URL | torchdtw-0.5.0-cp312-abi3-manylinux_2_28_x86_64.whl |
|---|---|
| Size | 5.1 MB |
| Tags | CPython 3.12 Linux glibc 2.28+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
50c082fdebc15b0cfd3d9dd9b513f95b88fdd6ee538cb1b1f7d98c55e924259f
|
|
BLAKE2b-256 checksum How to use checksums |
2751a036f0fb6122c62c35bc760803c53d2ef8009483c313c62c91fc5854bfb2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / torchdtw-0.5.0-cp312-abi3-manylinux_2_28_aarch64.whl
| Download URL | torchdtw-0.5.0-cp312-abi3-manylinux_2_28_aarch64.whl |
|---|---|
| Size | 5.1 MB |
| Tags | CPython 3.12 Linux glibc 2.28+ ARM64 abi3 |
|
SHA-256 checksum How to use checksums |
79bff659e66e8660720df5a7c5c6cbcdc3a27a2030bf04b0812e4a5202d0c30c
|
|
BLAKE2b-256 checksum How to use checksums |
4e990fad51d4e7601853143f51ea657ec3fce9c6bf9c0d3d475c967e2eeee7d3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / torchdtw-0.5.0-cp312-abi3-macosx_11_0_arm64.whl
| Download URL | torchdtw-0.5.0-cp312-abi3-macosx_11_0_arm64.whl |
|---|---|
| Size | 105.0 kB |
| Tags | CPython 3.12 abi3 macOS 11.0+ ARM64 |
|
SHA-256 checksum How to use checksums |
0e17f2737d29894ce74f88d19232ba0afeda049404b2ad14ee051ca4fbc332f7
|
|
BLAKE2b-256 checksum How to use checksums |
72c97c3870e024cd3d77a436a4c1ebfe75e85ae9d756719e9e0bccfbea4101ef
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for torchdtw 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.