libFRNN
libFRNN is a standalone C++17/CUDA fixed-radius nearest-neighbor library. Its
core has no dependency on Python, PyTorch, ATen, c10, TBB, NumPy, or a Python
binding framework. The optional frnn_cuda Python package provides a thin
NumPy binding and can additionally build a separate PyTorch adapter over the
same installed C++ API.
The implementation supports dimensions 1 through 32. It automatically dispatches small workloads to exact CUDA brute force and larger workloads to a dense uniform grid. The grid indexes up to three coordinates for dimensions 1–4 and four coordinates for dimensions 5–32; candidate distances always use every input dimension.
Algorithm and exactness
Both production search paths select the same canonical edge set:
- accumulate squared Euclidean distance in
float32dimension order with one fused multiply-add per coordinate; - include candidates whose squared distance is less than or equal to
radius * radius; - order each query row by
(squared_distance, original_database_index); - retain the first
max_neighborsentries; - apply self-loop and directed/undirected edge filtering.
Neighbor indices and final edges are exact, not recall-based. Duplicate
coordinates retain distinct original indices, radius boundaries are
inclusive, and equal-distance ties prefer the lower original index. Internal
squared distances are not part of the public output. The independent CPU
oracle uses std::fma to make the same accumulation contract explicit and
includes exact-boundary, adjacent nextafter, and rounding-sensitive
high-dimensional cases.
The grid path builds bounds, assigns database points to dense cells, performs a prefix sum and counting sort, and searches only cells intersecting each query radius. Sorted coordinates use AoS through dimension 4 and SoA above dimension 4; separate query/reference calls read the original AoS database. Identical query/reference calls process queries in the existing spatial ordering and write results back by original index. Four-dimensional grids reject corner cells whose bounding boxes cannot intersect the radius. Query cell ranges, cell boxes, and rejection thresholds are conservatively expanded for float32 roundoff. Specialized distance kernels cover dimensions 1, 2, 3, 4, 8, 12, and 16, with a generic exact path through dimension 32.
High-dimensional kernels first use grouped SoA loads as a conservative reordered screen. Candidates close enough to matter are recomputed in canonical dimension order, so the screen cannot change membership or ordering. Low-dimensional search uses 256-thread blocks; high-dimensional search uses 128 threads.
For large K, selection begins as a sorted insertion list and converts to a
deterministic max-heap only after a query accepts 24 candidates. This avoids
heap overhead for sparse queries and avoids quadratic insertion shifting for
dense queries. An internal -1 index marks the end of a short neighbor row;
sentinels are not exposed in edge output. The final heap is emitted without
sorting. Edges are grouped by ascending source index; target order within
each source is unspecified, while nearest-K membership and tie-breaking
remain unchanged.
Automatic brute-force dispatch uses this overflow-safe work rule:
query_count * database_count * dimension * ceil(max_neighbors / 8)
<= 2,000,000
Callers can force either exact path for measurement or diagnosis:
frnn::BuildOptions options;
options.algorithm = frnn::SearchAlgorithm::grid;
// or frnn::SearchAlgorithm::brute_force
The forced choices change only the algorithm, not result semantics.
PCA-rotated grid indexing
For dimensions above four, the grid indexes only the first four coordinates, so its pruning power depends on how much of the data's variance those coordinates carry. When the highest-variance directions do not align with the first axes, cells are unevenly populated and more candidates survive pruning.
libFRNN can rotate the point cloud into its principal-component frame before placing points into cells, so the four indexed columns hold the highest-variance directions. The rotation is computed in the caller's CUDA stream from the data's covariance matrix and is orthonormal, hence distance-preserving.
The rotation affects only cell placement and axis-aligned bounding-box pruning. Candidate distances and acceptance are always evaluated in the original, un-rotated frame, so the emitted edge set is identical to a build with the rotation disabled. The feature trades a small one-time rotation cost for fewer surviving candidates; on a 12-dimensional embedding (271,663 points, K=1000, radius=0.12) it measured about a 1.5x end-to-end speedup on an NVIDIA A100 with identical output.
Rotation is selected automatically: it is enabled when the dimension exceeds
four and disabled otherwise. The FRNN_PCA_ROTATE environment variable
overrides the heuristic — set it to 1 to force rotation on or 0 to force
it off:
FRNN_PCA_ROTATE=1 ./build/frnn_benchmark --embedding data/embedding_data.csv
FRNN_PCA_ROTATE=0 ./build/frnn_benchmark --embedding data/embedding_data.csv
Because output is identical either way, the override exists for measurement and diagnosis rather than to change results.
C++ installation and use
Required tools are CMake 3.20 or newer, a C++17 compiler, and a compatible CUDA
Toolkit. CUDA architectures are configured through CMake's standard
CMAKE_CUDA_ARCHITECTURES variable.
cmake -S . -B build-cpp \
-DCMAKE_BUILD_TYPE=Release \
-DFRNN_BUILD_TESTS=ON \
-DFRNN_BUILD_PYTHON=OFF
cmake --build build-cpp --parallel
ctest --test-dir build-cpp --output-on-failure
cmake --install build-cpp --prefix "$PWD/install"
BUILD_SHARED_LIBS=ON is the default. Set it to OFF for a static core
library. A downstream CMake project consumes either form with:
find_package(frnn CONFIG REQUIRED)
target_link_libraries(my_target PRIVATE frnn::frnn)
The synchronous host interface accepts row-major coordinates:
#include <frnn/frnn.hpp>
std::vector<float> points = /* [num_points, dimension] */;
auto edges = frnn::buildEdges(
frnn::PointView{points.data(), num_points, dimension},
0.5F,
32);
The returned std::vector<frnn::Edge> owns row-major [num_edges, 2] signed
64-bit pairs. The one-input convenience overload removes self-loops and emits
an undirected pair once, with source > target. Duplicate coordinates remain
distinct points; duplicate edge pairs are not emitted. Radius comparison is
inclusive. Candidates are ordered by squared distance, then by target index,
before max_neighbors truncation.
The historical vector interface remains available:
frnn::buildEdges(query, database, edge_list, num_points, dimension,
radius, max_neighbors);
Its output is flattened [2, num_edges]: all sources followed by all targets.
It preserves the historical same-set, no-self-loop, one-undirected-pair
behavior.
Asynchronous device API
frnn::buildEdgesAsync accepts DevicePointView values whose pointers already
reside on the active CUDA device, a caller-owned DeviceEdgeBuffer, a reusable
Workspace, and a caller-provided cudaStream_t. The output edge storage is
row-major [capacity, 2]; edge_count is a device-resident signed 64-bit
scalar. Use requiredEdgeCapacity(query_count, max_neighbors) to size it.
Passing edges=nullptr requests count-only execution; in that mode capacity
is ignored and the exact device-resident count is still populated.
After synchronizing that count, materializeEdgesAsync can write the prepared
edges into an exactly sized device allocation without repeating the search.
Every memory operation, prefix sum, and kernel is enqueued on the supplied
stream. The device API does not copy input coordinates to the host. Call
Workspace::reserve before an asynchronous region to avoid allocation-related
synchronization when a workspace grows. A reserved workspace has no per-call
allocation on the warm path. Use a separate workspace for concurrently
executing calls.
The device API does not synchronize the supplied stream. It reports launch and CUDA API errors immediately; execution errors are observed when the caller synchronizes. Device callers must provide finite coordinates because checking device values on the host would break asynchronous execution. The synchronous host API validates all coordinates, copies inputs to the device, runs count-first, allocates exact edge storage, and copies the output to the host.
Python installation and use
The package requires Python 3.9+ and NumPy. It does not require or import
PyTorch. The frnn_cuda name intentionally allows it to coexist with the
original PyTorch package named frnn.
Install the prebuilt wheel (Linux x86_64, CPython 3.9-3.14) from PyPI:
python -m pip install frnn_cuda
The wheels need only an NVIDIA driver supporting CUDA 12.8; the CUDA runtime is bundled. They contain code for compute capabilities 7.0 through 12.0 (Volta to Blackwell) and PTX for newer GPUs. They provide the NumPy API; the optional PyTorch API must be built against your PyTorch and is therefore never in a wheel (see Optional PyTorch CUDA interface).
To build from source, the build machine must provide an NVIDIA CUDA Toolkit
with nvcc and CUDA headers/libraries compatible with its compiler and
installed NVIDIA driver, plus pybind11 and scikit-build-core. Failure to locate
CUDA is reported by CMake's required CUDA language/toolkit checks. Build and
install with a standard command:
python -m pip install .
or build a wheel:
python -m pip install build
python -m build
python -m pip install dist/frnn_cuda-*.whl
The Python API is:
frnn_cuda.build_edges(
query,
database=None,
*,
radius: float,
max_neighbors: int,
exclude_self: bool = True,
directed: bool | None = None,
) -> numpy.ndarray
For example:
import numpy as np
import frnn_cuda
points = np.asarray(points, dtype=np.float32, order="C")
edges = frnn_cuda.build_edges(points, radius=0.5, max_neighbors=32)
Inputs must be C-contiguous NumPy float32 arrays shaped
[num_points, dimension]. The result is a NumPy int64 array shaped
[2, num_edges]. Non-array inputs, non-float32 dtypes, non-contiguous or
non-2D arrays, dimensions outside [1, 32], non-finite coordinates, invalid
radii, and negative neighbor limits are rejected.
When database is omitted, the input is treated as one point set:
directed=None produces unique undirected pairs, and exclude_self=True
removes self-loops. Setting directed=True emits both directions where each is
selected. When database is supplied, directed query-to-database output is
required and self-loop removal has no effect because the arrays represent
different sets.
The radius boundary is inclusive. max_neighbors is applied per query after
self-loop exclusion. Equal-distance candidates are resolved by the lower
target index, so tie handling is deterministic. Duplicate coordinates are
allowed and retain their separate indices.
The Python call is synchronous. It copies both NumPy inputs from host memory to CUDA memory, calls the public standalone C++ API, synchronizes, and copies edges back to NumPy-owned host memory. Python users never manage internal grid or workspace buffers. Device-resident Python array interoperability is not provided by the base NumPy binding.
Optional PyTorch CUDA interface
The standalone library and the Python package neither require nor import
PyTorch. The PyTorch extension is built automatically whenever the Python
running the build can import a CUDA build of torch (FRNN_BUILD_TORCH=AUTO,
the default); CPU-only and ROCm builds of PyTorch are skipped. Because the
extension must match the installed PyTorch, it is not part of the PyPI wheels:
build from source in the environment that has PyTorch, without pip isolation so
CMake sees that installation:
python -m pip install scikit-build-core pybind11 numpy # plus torch, if not installed
# --force-reinstall --no-cache-dir rebuild even if a wheel is already installed or
# cached; --no-deps leaves the environment's other packages as they are.
python -m pip install --force-reinstall --no-cache-dir --no-deps \
--no-binary frnn_cuda --no-build-isolation frnn_cuda
# or, from a checkout or a release tag:
python -m pip install --no-build-isolation .
python -m pip install --no-build-isolation "git+https://github.com/xju2/libFRNN.git@v3.1.0"
The CMake log says libFRNN: CUDA PyTorch found, building frnn_cuda.torch, or
why it skipped the extension. Pass -DFRNN_BUILD_TORCH=ON (in CMAKE_ARGS) to
make a missing or CPU-only PyTorch an error instead, or -DFRNN_BUILD_TORCH=OFF
to never build the extension. With pip's default build isolation, PyTorch is
usually hidden from the build and the extension is skipped.
Torch_DIR or CMAKE_PREFIX_PATH may be supplied explicitly when using a
standalone LibTorch installation. With pip-installed PyTorch, CMake obtains the
prefix from torch.utils.cmake_prefix_path automatically.
The PyTorch API is deliberately separate so importing frnn_cuda does not
import PyTorch:
import torch
from frnn_cuda.torch import build_edges
points = torch.rand((100_000, 3), dtype=torch.float32, device="cuda")
edges = build_edges(points, radius=0.03, max_neighbors=32)
Inputs must be contiguous, two-dimensional CUDA torch.float32 tensors on the
same device. The result is a CUDA torch.int64 tensor shaped [2, num_edges]
on that device. Coordinates and edges are never copied to the host. The
operation uses PyTorch's current CUDA stream; because the output length is
data-dependent, it synchronizes that stream to read the 8-byte edge count and
again before releasing its temporary workspace. Device inputs must contain
finite coordinates, matching the C++ device API contract. Edge indices are
discrete and no autograd operation is registered.
When database is omitted, the call first tries the exact kd-leaf fast path
(frnn::buildEdgesFastDevice), the device-resident form of the NumPy fast
path: points are read in place, edges never leave the GPU, and the result is a
contiguous [2, num_edges] tensor sorted by (source, target), so repeated
calls return identical tensors. The fast path declines, and the general path
below runs, for fewer than 64 points, a dimension other than 2, 3, 4, 6, 8, 12
or 16, non-finite coordinates, or any point with more than max_neighbors
in-radius neighbors (truncation needs the general path's ordered selection).
Either way the edge set is the same. On a real 271,663-point, 12-dimensional
tracking embedding (radius 0.12, 9.28 million edges, A100), the fast path takes
23.6 ms against 89 ms for the general path.
The general path's [2, num_edges] result is a zero-copy transpose of
row-major core storage and is therefore not contiguous; call
edges.contiguous() only when a downstream operation requires it.
Run the optional binding tests against the installed package with:
python tests/test_torch.py
To test an installed package rather than the source tree:
python tests/test_python.py
Implementation layers
frnnis the independently buildable/installable C++/CUDA core. It owns grid construction, prefix sums, counting sort, nearest-neighbor selection, workspace allocation, edge filtering, and CUDA error reporting.<frnn/frnn.hpp>provides host and device C++ interfaces over that core._frnnis built only withFRNN_BUILD_PYTHON=ON; it validates NumPy arrays and calls the public host API without reimplementing the algorithm._frnn_torchis built only withFRNN_BUILD_TORCH=ON; it registers the device-resident Torch operator and calls the public asynchronous device API.
The original kernel sources were derived from https://github.com/murnanedaniel/FRNN and https://github.com/lxxue/prefix_sum.
Benchmarking
Build and run the reproducible benchmark with:
cmake -S . -B build \
-DCMAKE_BUILD_TYPE=Release \
-DFRNN_BUILD_TESTS=ON \
-DFRNN_BUILD_BENCHMARKS=ON
cmake --build build --parallel
./build/frnn_benchmark \
--full \
--warmup 10 \
--iterations 50 \
--output benchmarks/results/local.csv
The CSV contains build/compiler/GPU metadata and separate rows for workspace allocation, cold device latency, warm CUDA-event latency, synchronized device host latency, device-to-host output transfer, and host API end-to-end latency. It reports minimum, p50, p95, mean, and standard deviation.
The supplied real embedding can be measured without including CSV parsing in the timed region:
./build/frnn_benchmark \
--embedding data/embedding_data.csv \
--warmup 10 \
--iterations 30 \
--output benchmarks/results/local-real.csv
python tests/compare_reference_edges.py --minimum-agreement 1.0
Use --algorithm grid or --algorithm brute_force to measure crossover
points. The immutable baseline, retained experiments, and final machine-
readable data live in benchmarks/results/. Profiling observations, rejected
experiments, and remaining bottlenecks are in
docs/optimization_log.md; the final comparison is in
docs/performance_report.md.
Known limitations
- The grid uses at most four coordinates for indexing, although distance and acceptance use every coordinate. For dimensions above four, automatic PCA-rotated indexing (see above) aligns those coordinates with the highest-variance directions without changing output.
- Dense or highly correlated high-dimensional clouds can still generate many candidates and dominate latency.
- The host convenience API is synchronous and creates a fresh device workspace per call; repeated low-latency applications should use the device API and a reserved workspace.
- Device output capacity remains caller-managed. Count-only mode is available when allocating the conservative capacity is undesirable.
- The current library supports any non-negative K that fits device memory; it does not expose neighbor distances as a public output.
Metadata
Release files for frnn-cuda 3.1.1
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 |
|---|---|---|---|---|
| frnn_cuda-3.1.1.tar.gz | 184.0 kB | Without provenance | Details for frnn_cuda-3.1.1.tar.gz |
Built distributions (wheels)
Total release size: 22.7 MB
Release files / frnn_cuda-3.1.1.tar.gz
| Download URL | frnn_cuda-3.1.1.tar.gz |
|---|---|
| Size | 184.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ef73b48d666d45746bc0dcab8a0eff1cba556e8f7029a231e08662b28315ddf6
|
|
BLAKE2b-256 checksum How to use checksums |
269a94621f020e58310da8a1e6280e58ee87587613ca3257c49e2c024e5106a6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / frnn_cuda-3.1.1-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
| Download URL | frnn_cuda-3.1.1-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl |
|---|---|
| Size | 3.8 MB |
| Tags | CPython 3.14 Linux glibc 2.24+ x86-64 Linux glibc 2.28+ x86-64 |
|
SHA-256 checksum How to use checksums |
b6230be9d2f777a116c22e023e402937f7d458688afbc995a1d8163d729ca0cc
|
|
BLAKE2b-256 checksum How to use checksums |
0c10c6e9abb36160eae1230153c241787b95b265335fe9d47903604b19e66d2e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / frnn_cuda-3.1.1-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
| Download URL | frnn_cuda-3.1.1-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl |
|---|---|
| Size | 3.8 MB |
| Tags | CPython 3.13 Linux glibc 2.24+ x86-64 Linux glibc 2.28+ x86-64 |
|
SHA-256 checksum How to use checksums |
cca66c933cb9e42f684fe69f34ea66a560434b45380e03e8f523620b96e35b1d
|
|
BLAKE2b-256 checksum How to use checksums |
f7eb60bd81b7062a304bbba0a044ea933b74c86902af741e7619fe55a8625343
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / frnn_cuda-3.1.1-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
| Download URL | frnn_cuda-3.1.1-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl |
|---|---|
| Size | 3.8 MB |
| Tags | CPython 3.12 Linux glibc 2.24+ x86-64 Linux glibc 2.28+ x86-64 |
|
SHA-256 checksum How to use checksums |
d9f5525d7caab0a41a57144609a0ba1a4bf0cb6171bfe29944c22132b069cb8c
|
|
BLAKE2b-256 checksum How to use checksums |
4a0dd07a3c583af9c4c0e85e0cd50b4827e77900771c96491e7aec23816b7145
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / frnn_cuda-3.1.1-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
| Download URL | frnn_cuda-3.1.1-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl |
|---|---|
| Size | 3.8 MB |
| Tags | CPython 3.11 Linux glibc 2.24+ x86-64 Linux glibc 2.28+ x86-64 |
|
SHA-256 checksum How to use checksums |
da17ea9d792035006c7762a49ebd0493fe24f92150a636d395b9284ea08a5bf0
|
|
BLAKE2b-256 checksum How to use checksums |
d49919e631c53e3a8398d5f5ac44d9869ab1b6b28d87760cf614a5a9dc258930
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / frnn_cuda-3.1.1-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
| Download URL | frnn_cuda-3.1.1-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl |
|---|---|
| Size | 3.8 MB |
| Tags | CPython 3.10 Linux glibc 2.24+ x86-64 Linux glibc 2.28+ x86-64 |
|
SHA-256 checksum How to use checksums |
5d192a22ba096f49c9fccb8e1a932465830914afdcdb7b50725f1ebacfc4af2a
|
|
BLAKE2b-256 checksum How to use checksums |
b67ca36e3e96b036488d3c336c31074fdbb104cea4fc84068d4d3bdc190f9dd2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / frnn_cuda-3.1.1-cp39-cp39-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
| Download URL | frnn_cuda-3.1.1-cp39-cp39-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl |
|---|---|
| Size | 3.8 MB |
| Tags | CPython 3.9 Linux glibc 2.24+ x86-64 Linux glibc 2.28+ x86-64 |
|
SHA-256 checksum How to use checksums |
ad8b816c827e10e19e451ef6e155e6e099a923b754781786141bd603e101daa1
|
|
BLAKE2b-256 checksum How to use checksums |
4c294c38769057dfda8d50df463e8aa7a5dd4c35bd970be539cda12753651e8b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Security for frnn-cuda 3.1.1
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.