gputree
Exact k-d trees on NVIDIA GPUs, for plain Python, @numba.njit functions
and @numba.cuda.jit kernels.
- A drop-in replacement for numba-kdtree,
plus a zero-dependency scikit-learn-compatible
interface (
gputree.sklearn.KDTree): exact k nearest neighbors, radius searches and radius counts, built and searched on the GPU. - Everywhere you write Python: NumPy arrays, Numba/CuPy/PyTorch CUDA
arrays, inside
@njitfunctions, and as device functions inside your own@cuda.jitkernels. - Fast: on an RTX 4060, with a million 3D points and a million queries (NumPy in and out), building takes 8 ms, 16-nearest-neighbor search 22 ms and radius search (~32 matches per query) 32 ms — 31× faster than scipy and 16× faster than numba-kdtree end to end, 11× faster than pykdtree for build + k-NN, and up to 43× faster than scipy at 10M points (details).
Contents
- Install
- Quick start
- Performance
- Usage: NumPy arrays ·
Rows·@njit· scikit-learn · device arrays · CUDA kernels - Conventions
- Examples · Development · License
Install
python -m pip install gpu-kdtree
The package is published on PyPI as gpu-kdtree (the name gputree belongs to
an unrelated project) and imported as gputree.
| Requirement | Details |
|---|---|
| OS | Linux (POSIX) |
| GPU | NVIDIA GPU with a CUDA 12 driver |
| Python | 3.12 or later |
| Dependencies | NumPy (>=1.26,<2.5), Numba (>=0.65), numba-cuda[cu12] (>=0.30), cuda-core (>=1.3) |
| Optional extras | CuPy is not required by gputree; optional test, benchmark and notebook extras can be installed with pip install "gpu-kdtree[test]", "[benchmarks]" or "[examples]" |
The first call in a fresh environment compiles CUDA kernels, which takes a few
seconds. Numba caches every kernel on disk (in NUMBA_CACHE_DIR or alongside
the package), so later processes start quickly.
Quick start
import numpy as np
from gputree import KDTree
points = np.random.default_rng(0).random((1_000_000, 3), dtype=np.float32)
queries = np.random.default_rng(1).random((1_000_000, 3), dtype=np.float32)
tree = KDTree(points) # built on the GPU
distances, indices, counts = tree.query(queries, k=16) # squared distances
neighbors, counts = tree.query_radius(queries, r=0.02) # one row per query
neighbors[0] # a NumPy view
counts = tree.query_length(queries, r=0.02) # counts only
Important: Every distance
gputreereturns is a squared Euclidean distance, unlikenumba-kdtree,scipyandscikit-learn(takenp.sqrtif you need plain distances). The inputsranddistance_upper_boundremain plain distances.
Performance
Warm medians on an NVIDIA GeForce RTX 4060 with a 24-thread CPU; uniform
float32 points, 1,048,576 random queries, k = 16 and a radius holding about
32 matches per query. Build times include copying points to the GPU; query
times include copying queries and results. Every CPU library uses all 24
threads (scipy with workers=-1, numba-kdtree's parallel methods,
pykdtree with OpenMP); pykdtree has no radius search. The ratio after a
total is how many times longer it takes than gputree. Reproduce with
benchmarks/compare.py.
Against CPU libraries (NumPy in, NumPy out)
| Points | Library | Build | k-NN, k = 16 | Radius | Total |
|---|---|---|---|---|---|
| 100,000 × 3D | gputree | 1.0 ms | 19.8 ms | 28.3 ms | 49.1 ms |
| scipy cKDTree | 17.2 ms | 163 ms | 1.18 s | 1.36 s (28×) | |
| numba-kdtree | 9.7 ms | 203 ms | 387 ms | 600 ms (12×) | |
| pykdtree | 7.0 ms | 137 ms | — | — | |
| 1,048,576 × 3D | gputree | 8.1 ms | 21.5 ms | 31.7 ms | 61.3 ms |
| scipy cKDTree | 251 ms | 287 ms | 1.39 s | 1.92 s (31×) | |
| numba-kdtree | 129 ms | 268 ms | 592 ms | 989 ms (16×) | |
| pykdtree | 91.6 ms | 236 ms | — | — | |
| 10,000,000 × 3D | gputree | 79.3 ms | 24.2 ms | 42.9 ms | 146 ms |
| scipy cKDTree | 4.12 s | 488 ms | 1.61 s | 6.22 s (43×) | |
| numba-kdtree | 1.59 s | 468 ms | 869 ms | 2.93 s (20×) | |
| pykdtree | 1.27 s | 449 ms | — | — | |
| 1,048,576 × 6D | gputree | 11.7 ms | 114 ms | 239 ms | 365 ms |
| scipy cKDTree | 304 ms | 2.85 s | 4.80 s | 7.96 s (22×) | |
| numba-kdtree | 135 ms | 2.27 s | 4.12 s | 6.53 s (18×) | |
| pykdtree | 99.1 ms | 1.93 s | — | — |
Against cudaKDTree (data on the GPU)
cudaKDTree (commit 37ce4c3) timed
from C++, against gputree's device calls (KDTree on a device array,
gputree.cuda.device_query and device_query_radius), on the same points and
queries. Each cudaKDTree cell is its fastest variant (fixed or heap candidate
list; stack or closest-corner tracking walk); its fastest k-NN variant returns
sorted rows like gputree, and its radius search runs the count, scan and fill
that a CSR result needs.
| Points | Library | Build | k-NN, k = 16 | Radius | Total |
|---|---|---|---|---|---|
| 100,000 × 3D | gputree | 0.8 ms | 15.3 ms | 25.2 ms | 41.3 ms |
| cudaKDTree | 3.5 ms | 14.6 ms | 29.7 ms | 47.8 ms (1.2×) | |
| 1,048,576 × 3D | gputree | 6.3 ms | 17.0 ms | 30.0 ms | 53.2 ms |
| cudaKDTree | 52.9 ms | 15.4 ms | 32.2 ms | 101 ms (1.9×) | |
| 10,000,000 × 3D | gputree | 69.2 ms | 22.1 ms | 40.9 ms | 132 ms |
| cudaKDTree | 671 ms | 52.4 ms | 106 ms | 830 ms (6.3×) | |
| 1,048,576 × 6D | gputree | 8.6 ms | 110 ms | 240 ms | 359 ms |
| cudaKDTree | 225 ms | 371 ms | 665 ms | 1.26 s (3.5×) |
Small batches
A call has a small fixed overhead that matters only for tiny batches: a single k-NN query takes ~0.06 ms on device arrays and ~0.10 ms from NumPy to NumPy (including host–device copies), and a single radius query ~0.11 ms. Large host batches are split into up to 8 chunks on concurrent streams so copies and kernels overlap; small host batches bypass pipelining to keep latency low.
See benchmarks/RESULTS.md
for sizes from 1,000 to 10,000,000 points, both walks, Python vs @njit vs
device timings, device functions and release history.
Usage
NumPy arrays
gputree.KDTree follows numba_kdtree.KDTree and supports standard pickle
and copy:
| Call | Returns |
|---|---|
KDTree(data) |
A tree of the (n, m) points, built on the GPU |
query(X, k=1, p=2.0, eps=0.0, distance_upper_bound=inf, return_sorted=True, walk="auto") |
(distances, indices, counts) of shapes (q, k), (q, k), (q,); missing neighbors are inf and -1 |
query_radius(X, r, p=2.0, eps=0.0, return_sorted=False, walk="auto", return_distance=False) |
(indices, counts), or (distances, indices, counts) with return_distance=True; rows are Rows |
query_length(X, r, p=2.0, eps=0.0, walk="auto") |
counts alone, several times faster than listing matches (replaces return_length=True) |
query_parallel, query_radius_parallel |
Aliases: every query already runs in parallel on the GPU |
data, idx, size |
Cached float32 points in original order (do not mutate), original indices in tree order, and point count |
Xholds the query points (NumPy or CUDA arrays), read as rows ofmcoordinates.ris a scalar radius or one per query; its magnitude is used.return_sortedorders each row. Forquery, rows are sorted by squared distance unlessFalse. Forquery_radius,False(default) leaves order unspecified (fastest);Trueor"index"sorts by original index, and"distance"sorts by squared distance, breaking ties by original index. Sorting runs on the GPU; any other value raisesValueError.walkchooses how the GPU walks the tree (see Walks).
Radius results: Rows
query_radius returns gputree.Rows: an (n,) sequence of 1-D NumPy views,
matching numba-kdtree's per-query list semantics without allocating one
Python object per query. It stores one flat array (rows.values) sliced at
rows.offsets: rows[i] is a writable NumPy view, rows[a:b] returns a
sliced Rows, and rows.counts returns the row lengths. Rows do not overlap,
so writing to one never affects another; any retained view keeps the backing
buffer alive (call rows[i].copy() to keep one row alone).
Inside @njit functions
from numba import njit
from gputree import KDTree
@njit
def neighbors(points, radius):
tree = KDTree(points) # construction runs in object mode
return tree, tree.query_radius_parallel(points, radius, return_sorted=True)
tree, (rows, counts) = neighbors(points, 0.01)
Trees can be passed to, constructed in and returned from @njit functions;
searches dispatch onto the GPU at full speed. Rows unboxes natively in
compiled code, where rows[i], len(rows) and rows.counts compile to direct
array operations. Inside @njit, return_distance must be a compile-time
constant.
The scikit-learn interface
from gputree.sklearn import KDTree as SklearnKDTree
tree = SklearnKDTree(points)
distances, indices = tree.query(queries, k=16)
indices, distances = tree.query_radius(
queries, 0.02, return_distance=True, sort_results=True
)
counts = tree.query_radius(queries, 0.02, count_only=True)
gputree.sklearn.KDTree follows sklearn.neighbors.KDTree for query,
query_radius, pickle and copy — without requiring scikit-learn to be
installed (kernel density and two-point correlation are not included).
Distances are float32 and squared, indices are int32, and negative radii match
no points. query_radius returns object arrays of 1-D views ordered by
original index (or by squared distance with sort_results=True), sorted on the
GPU. Only the Euclidean metric is supported for now: "euclidean", "l2", or
"minkowski" / "p" with p = 2.
Device arrays
gputree.cuda keeps whole batches resident on the GPU:
from numba import cuda
from gputree import cuda as gpu
device_points = cuda.to_device(points)
tree = KDTree(device_points)
distances, indices, counts = gpu.device_query(tree, device_points[:1000], k=4)
matches, counts, offsets = gpu.device_query_radius(
tree, device_points[:1000], 0.01, return_sorted=True
)
first_row = matches[offsets[0]:offsets[1]]
counts_only = gpu.device_query_length(tree, device_points[:1000], 0.01)
| Call | Returns |
|---|---|
device_query(tree, X, k=1, p=2.0, eps=0.0, distance_upper_bound=inf, *, stream=None, out=None, return_sorted=True, walk="auto") |
(distances, indices, counts) as Numba device arrays |
device_query_radius(tree, X, r, p=2.0, eps=0.0, *, stream=None, offsets=None, indices=None, return_sorted=False, walk="auto", return_distance=False, distances=None) |
(indices, counts, offsets), or (distances, indices, counts, offsets) in CSR form (offsets[-1] is the total) |
device_query_length(tree, X, r, p=2.0, eps=0.0, *, stream=None, walk="auto") |
counts as a Numba device array |
- Inputs accept any object implementing the CUDA Array Interface (Numba, CuPy,
PyTorch, …). Results are Numba device arrays (view zero-copy via
cupy.asarray(result)ortorch.as_tensor(result)). streamaccepts Numba, CuPy, PyTorch,cuda.corestreams, objects with__cuda_stream__, or raw handles (defaults to the legacy default stream).- Device coordinates are not checked for NaN to avoid host synchronization.
- Caller buffers:
out=(distances, indices, counts)fordevice_query, andoffsets,indicesanddistancesfordevice_query_radius. Supplyingindiceskeeps the entire call asynchronous; on overflow (offsets[-1] > indices.size),indicesanddistancesare left untouched andoffsetsstays valid. - Sorting runs on the GPU without host synchronization and uses a temporary
int64 buffer sized to
indices.
Inside CUDA kernels
import numpy as np
from numba import cuda, float32, int32
from gputree import cuda as gpu
K = 4
@cuda.jit(extensions=[gpu.tree_argument])
def search(tree, queries, output):
i = cuda.grid(1)
if i < queries.shape[0]:
distances = cuda.local.array(K, float32)
indices = cuda.local.array(K, int32)
gpu.nearest_k(tree, queries[i], distances, indices)
output[i, 0] = indices[0]
output[i, 1] = gpu.radius_count(tree, queries[i], 0.01)
output = cuda.device_array((1000, 2), dtype=np.int32)
search[8, 128](tree, device_points[:1000], output)
Device functions, called by one thread per query:
| Function | Behavior |
|---|---|
nearest(view, point, distance_upper_bound=inf) |
Returns (squared_distance, index) as (float32, int32), or (inf, -1) |
nearest_k(view, point, distances, indices, distance_upper_bound=inf) |
Fills float32 distances (squared) and int32 indices of length k, sorted by distance, and returns the count found (inf / -1 in unused slots) |
radius_count(view, point, r) |
Returns the number of points within r as int32 |
radius_next(view, point, r, node=0, previous=-1, row=0) |
Returns (index, node, previous, row) as int32: the next match and updated walk state |
radius_next yields matches one at a time in constant state (start at
(0, -1, 0) and stop when node < 0, which comes with index == -1):
node, previous, row = 0, -1, 0
while node >= 0:
match, node, previous, row = gpu.radius_next(tree, point, r, node, previous, row)
if match >= 0:
... # use match
pointis any 1-D array of at leastmcoordinates of any real dtype (global row or local array), converted to float32.kinnearest_khas no upper limit because the candidate heap lives in your(distances, indices)arrays;cuda.local.arrayis fastest for smallk.nearest,nearest_kandradius_countshare the exact stack walk and result objects ofdevice_query(..., walk="stack")anddevice_query_length(..., walk="stack"), producing bit-identical results at the same speed (nearestandnearest_k(k=1)also agree on ties).radius_nextruns the stack-free walk and visits matches in the order of an unsorteddevice_query_radius(..., walk="stack").- Without
tree_argument, passgpu.device_view(tree, stream)and keeptreealive until the kernel completes. Inside kernels that build or slice views directly, construct the view withgpu.DeviceView.for_dimensions(m)bound to a module-level name so Numba compiles for dimensionm.
Advanced: building trees inside a CUDA kernel (build_block / build_block_into)
gpu.build_block(points, view) builds a tree of up to 1,024 finite points
cooperatively across all threads of one block (block size must be a multiple of
32; view.points must not overlap points), sized with gpu.leaf_count(n)
and gpu.bucket_count(n):
import numpy as np
from numba import cuda, float32, int32
from gputree import cuda as gpu
n, m = 1000, 3
leaves, buckets = gpu.leaf_count(n), gpu.bucket_count(n)
view = gpu.DeviceView( # host-built: type carries m = 3
points=cuda.device_array((n, m), np.float32),
indices=cuda.device_array(n, np.int32),
lower=cuda.device_array((m, 2 * leaves), np.float32),
upper=cuda.device_array((m, 2 * leaves), np.float32),
split_axes=cuda.device_array(buckets, np.int32),
split_values=cuda.device_array(buckets, np.float32),
)
@cuda.jit
def build_and_search(source, view, nearest_other):
tree = gpu.build_block(source, view)
d2 = cuda.local.array(2, float32)
idx = cuda.local.array(2, int32)
for row in range(cuda.threadIdx.x, source.shape[0], cuda.blockDim.x):
gpu.nearest_k(tree, source[row], d2, idx) # idx[0] is self, idx[1] is nearest neighbor
nearest_other[row] = idx[1]
source = cuda.to_device(np.random.default_rng(1).random((n, m), dtype=np.float32))
nearest_other = cuda.device_array(n, np.int32)
build_and_search[1, 256](source, view, nearest_other)
To build one tree per block from sliced arrays, bind the dimension class at module scope:
View3 = gpu.DeviceView.for_dimensions(3)
@cuda.jit
def build_per_block(sources, points, indices, lower, upper, axes, values):
block = cuda.blockIdx.x
view = View3(
points[block], indices[block], lower[block], upper[block],
axes[block], values[block],
)
tree = gpu.build_block(sources[block], view)
...
For trees larger than 1,024 points inside one block, call
gpu.build_block_into(points, view, positions, work, state) with per-block
global scratch: positions (int32, shape (2, n)), work (int32, length
n) and state (int64, length n // 4 + 16).
Conventions
Types
gputree uses float32 and int32 throughout. Points and queries may be any
real (floating or integer) arrays on host or device and are converted to
float32; radii may be Python numbers or floating arrays of any precision and
are converted to float32. Values overflowing float32 become infinite and
are rejected as non-finite; booleans and complex numbers raise TypeError.
Every output is float32 (data, distances) or int32 (indices, counts,
idx, radius offsets) across Python, @njit, scikit-learn and gputree.cuda.
Trees hold at most 2**31 - 1 points, and radius queries return at most
2**31 - 2 total matches; exceeding either raises OverflowError. Pickles of
float64 trees from earlier versions convert automatically on load.
Distances and ties
- Points are ranked by squared Euclidean distance evaluated in
float32with fused multiply-adds. Every returned distance is that squared distance across every interface (takenp.sqrtfor plain distances). - Equal distances are returned in tree order.
distance_upper_boundis strict (d < bound); radiusris inclusive (d <= r). - Only the Euclidean norm (
p = 2) is supported for now; other values raiseValueError.
Results are independent of batch size. Libraries with different rounding (e.g.
float64 scipy or numba-kdtree) can disagree on points within float32
rounding error of a radius boundary or tie.
Walks
Every batched search (query, query_radius, query_length, scikit-learn
methods, and gputree.cuda.device_*, including in @njit) accepts
walk="auto":
walk |
How the GPU walks the tree |
|---|---|
"stack" |
One CUDA thread per query (cudaKDTree's stack walk) |
"warp" |
One 32-thread warp per query; serves k <= 64 (up to 2 sorted keys per lane) and all radius searches; raises ValueError for k > 64 |
"auto" (default) |
"stack" for k > 64; "warp" for small k-NN batches (<= 4,096 queries), for heavy trees (m >= 5 or n >= 2**21, except large k = 1 batches on light-count 5D+ trees), and for 16 <= k <= 64 on light trees; "stack" otherwise |
Differences from numba-kdtree
- The constructor is
KDTree(data)with a fixed balanced box-tree layout (leaves of 32–64 points, buckets of 4–8, widest-axis median splits, ties broken by original index);leafsize,compact,balancedandroot_bboxare not used. - Returned distances are squared
float32, and indices/counts areint32. query_radiusreturns(indices, counts)(or(distances, indices, counts)whenreturn_distance=True) asRows;query_lengthreplacesreturn_length=True.queryandquery_radiusacceptwalk;queryalso acceptsreturn_sorted(True by default).epsis validated and ignored;pmust be2.
Examples
examples/gputree_tour.ipynb
exercises every mode (Python NumPy, gputree.sklearn, device arrays, @njit
and @cuda.jit kernels including build_block) on a million points, validates
results against scipy, and plots timings and scaling.
Development
conda create -p "$PWD/.conda/gputree" -c conda-forge python=3.12 pip
conda activate "$PWD/.conda/gputree"
python -m pip install -e ".[test]"
python -m unittest discover -s tests -v # requires a CUDA GPU
python -m pip install -e ".[benchmarks]"
NUMBA_NUM_THREADS=24 OMP_NUM_THREADS=24 python benchmarks/compare.py
CHANGELOG.md— version history and migration guides.DESIGN.md— architecture, tree layout, GPU builder, traversals and stream pipeline.benchmarks/RESULTS.md— detailed benchmark tables across sizes, walks and versions.
License
gputree is free software under the GNU General Public License, version 3
(LICENSE). Its
thread-per-query walks and candidate lists are ported from
cudaKDTree by Ingo Wald under the
Apache License 2.0; NOTICE
lists what was adapted and
LICENSES/Apache-2.0.txt
holds that license.
Metadata
Release files for gpu-kdtree 0.8.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 |
|---|---|---|---|---|
| gpu_kdtree-0.8.0.tar.gz | 147.3 kB | Without provenance | Details for gpu_kdtree-0.8.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| gpu_kdtree-0.8.0-py3-none-any.whl | Python 3 | none | any | Details for gpu_kdtree-0.8.0-py3-none-any.whl |
Total release size: 265.3 kB
Release files / gpu_kdtree-0.8.0.tar.gz
| Download URL | gpu_kdtree-0.8.0.tar.gz |
|---|---|
| Size | 147.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
14a10216e3a51e593922fdf125f6f89f2c0928407a01ec089b9452710561af29
|
|
BLAKE2b-256 checksum How to use checksums |
6db3bb9c2154df35c337f9ff4d49e5f7302c740fc1e2f778fdf0ae3b7cb75520
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.16
|
Release files / gpu_kdtree-0.8.0-py3-none-any.whl
| Download URL | gpu_kdtree-0.8.0-py3-none-any.whl |
|---|---|
| Size | 118.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
cd4a55144df2cd177b8a609e0aae259dbde68dd23b7bfd16550ddf59fe1d35b0
|
|
BLAKE2b-256 checksum How to use checksums |
c31853a17b44fad8bee59dba5cca3323dd43a9ad549e82aedc9d1e20677508e8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.16
|
Security for gpu-kdtree 0.8.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.