Metadata-Version: 2.2
Name: frnn_cuda
Version: 3.1.1
Summary: Standalone CUDA fixed-radius nearest-neighbor library
Author: libFRNN contributors
License:                                  Apache License
                                    Version 2.0, January 2004
                                 http://www.apache.org/licenses/
         
            TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
         
            1. Definitions.
         
               "License" shall mean the terms and conditions for use, reproduction,
               and distribution as defined by Sections 1 through 9 of this document.
         
               "Licensor" shall mean the copyright owner or entity authorized by
               the copyright owner that is granting the License.
         
               "Legal Entity" shall mean the union of the acting entity and all
               other entities that control, are controlled by, or are under common
               control with that entity. For the purposes of this definition,
               "control" means (i) the power, direct or indirect, to cause the
               direction or management of such entity, whether by contract or
               otherwise, or (ii) ownership of fifty percent (50%) or more of the
               outstanding shares, or (iii) beneficial ownership of such entity.
         
               "You" (or "Your") shall mean an individual or Legal Entity
               exercising permissions granted by this License.
         
               "Source" form shall mean the preferred form for making modifications,
               including but not limited to software source code, documentation
               source, and configuration files.
         
               "Object" form shall mean any form resulting from mechanical
               transformation or translation of a Source form, including but
               not limited to compiled object code, generated documentation,
               and conversions to other media types.
         
               "Work" shall mean the work of authorship, whether in Source or
               Object form, made available under the License, as indicated by a
               copyright notice that is included in or attached to the work
               (an example is provided in the Appendix below).
         
               "Derivative Works" shall mean any work, whether in Source or Object
               form, that is based on (or derived from) the Work and for which the
               editorial revisions, annotations, elaborations, or other modifications
               represent, as a whole, an original work of authorship. For the purposes
               of this License, Derivative Works shall not include works that remain
               separable from, or merely link (or bind by name) to the interfaces of,
               the Work and Derivative Works thereof.
         
               "Contribution" shall mean any work of authorship, including
               the original version of the Work and any modifications or additions
               to that Work or Derivative Works thereof, that is intentionally
               submitted to Licensor for inclusion in the Work by the copyright owner
               or by an individual or Legal Entity authorized to submit on behalf of
               the copyright owner. For the purposes of this definition, "submitted"
               means any form of electronic, verbal, or written communication sent
               to the Licensor or its representatives, including but not limited to
               communication on electronic mailing lists, source code control systems,
               and issue tracking systems that are managed by, or on behalf of, the
               Licensor for the purpose of discussing and improving the Work, but
               excluding communication that is conspicuously marked or otherwise
               designated in writing by the copyright owner as "Not a Contribution."
         
               "Contributor" shall mean Licensor and any individual or Legal Entity
               on behalf of whom a Contribution has been received by Licensor and
               subsequently incorporated within the Work.
         
            2. Grant of Copyright License. Subject to the terms and conditions of
               this License, each Contributor hereby grants to You a perpetual,
               worldwide, non-exclusive, no-charge, royalty-free, irrevocable
               copyright license to reproduce, prepare Derivative Works of,
               publicly display, publicly perform, sublicense, and distribute the
               Work and such Derivative Works in Source or Object form.
         
            3. Grant of Patent License. Subject to the terms and conditions of
               this License, each Contributor hereby grants to You a perpetual,
               worldwide, non-exclusive, no-charge, royalty-free, irrevocable
               (except as stated in this section) patent license to make, have made,
               use, offer to sell, sell, import, and otherwise transfer the Work,
               where such license applies only to those patent claims licensable
               by such Contributor that are necessarily infringed by their
               Contribution(s) alone or by combination of their Contribution(s)
               with the Work to which such Contribution(s) was submitted. If You
               institute patent litigation against any entity (including a
               cross-claim or counterclaim in a lawsuit) alleging that the Work
               or a Contribution incorporated within the Work constitutes direct
               or contributory patent infringement, then any patent licenses
               granted to You under this License for that Work shall terminate
               as of the date such litigation is filed.
         
            4. Redistribution. You may reproduce and distribute copies of the
               Work or Derivative Works thereof in any medium, with or without
               modifications, and in Source or Object form, provided that You
               meet the following conditions:
         
               (a) You must give any other recipients of the Work or
                   Derivative Works a copy of this License; and
         
               (b) You must cause any modified files to carry prominent notices
                   stating that You changed the files; and
         
               (c) You must retain, in the Source form of any Derivative Works
                   that You distribute, all copyright, patent, trademark, and
                   attribution notices from the Source form of the Work,
                   excluding those notices that do not pertain to any part of
                   the Derivative Works; and
         
               (d) If the Work includes a "NOTICE" text file as part of its
                   distribution, then any Derivative Works that You distribute must
                   include a readable copy of the attribution notices contained
                   within such NOTICE file, excluding those notices that do not
                   pertain to any part of the Derivative Works, in at least one
                   of the following places: within a NOTICE text file distributed
                   as part of the Derivative Works; within the Source form or
                   documentation, if provided along with the Derivative Works; or,
                   within a display generated by the Derivative Works, if and
                   wherever such third-party notices normally appear. The contents
                   of the NOTICE file are for informational purposes only and
                   do not modify the License. You may add Your own attribution
                   notices within Derivative Works that You distribute, alongside
                   or as an addendum to the NOTICE text from the Work, provided
                   that such additional attribution notices cannot be construed
                   as modifying the License.
         
               You may add Your own copyright statement to Your modifications and
               may provide additional or different license terms and conditions
               for use, reproduction, or distribution of Your modifications, or
               for any such Derivative Works as a whole, provided Your use,
               reproduction, and distribution of the Work otherwise complies with
               the conditions stated in this License.
         
            5. Submission of Contributions. Unless You explicitly state otherwise,
               any Contribution intentionally submitted for inclusion in the Work
               by You to the Licensor shall be under the terms and conditions of
               this License, without any additional terms or conditions.
               Notwithstanding the above, nothing herein shall supersede or modify
               the terms of any separate license agreement you may have executed
               with Licensor regarding such Contributions.
         
            6. Trademarks. This License does not grant permission to use the trade
               names, trademarks, service marks, or product names of the Licensor,
               except as required for reasonable and customary use in describing the
               origin of the Work and reproducing the content of the NOTICE file.
         
            7. Disclaimer of Warranty. Unless required by applicable law or
               agreed to in writing, Licensor provides the Work (and each
               Contributor provides its Contributions) on an "AS IS" BASIS,
               WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
               implied, including, without limitation, any warranties or conditions
               of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
               PARTICULAR PURPOSE. You are solely responsible for determining the
               appropriateness of using or redistributing the Work and assume any
               risks associated with Your exercise of permissions under this License.
         
            8. Limitation of Liability. In no event and under no legal theory,
               whether in tort (including negligence), contract, or otherwise,
               unless required by applicable law (such as deliberate and grossly
               negligent acts) or agreed to in writing, shall any Contributor be
               liable to You for damages, including any direct, indirect, special,
               incidental, or consequential damages of any character arising as a
               result of this License or out of the use or inability to use the
               Work (including but not limited to damages for loss of goodwill,
               work stoppage, computer failure or malfunction, or any and all
               other commercial damages or losses), even if such Contributor
               has been advised of the possibility of such damages.
         
            9. Accepting Warranty or Additional Liability. While redistributing
               the Work or Derivative Works thereof, You may choose to offer,
               and charge a fee for, acceptance of support, warranty, indemnity,
               or other liability obligations and/or rights consistent with this
               License. However, in accepting such obligations, You may act only
               on Your own behalf and on Your sole responsibility, not on behalf
               of any other Contributor, and only if You agree to indemnify,
               defend, and hold each Contributor harmless for any liability
               incurred by, or claims asserted against, such Contributor by reason
               of your accepting any such warranty or additional liability.
         
            END OF TERMS AND CONDITIONS
         
            APPENDIX: How to apply the Apache License to your work.
         
               To apply the Apache License to your work, attach the following
               boilerplate notice, with the fields enclosed by brackets "[]"
               replaced with your own identifying information. (Don't include
               the brackets!)  The text should be enclosed in the appropriate
               comment syntax for the file format. We also recommend that a
               file or class name and description of purpose be included on the
               same "printed page" as the copyright notice for easier
               identification within third-party archives.
         
            Copyright [yyyy] [name of copyright owner]
         
            Licensed under the Apache License, Version 2.0 (the "License");
            you may not use this file except in compliance with the License.
            You may obtain a copy of the License at
         
                http://www.apache.org/licenses/LICENSE-2.0
         
            Unless required by applicable law or agreed to in writing, software
            distributed under the License is distributed on an "AS IS" BASIS,
            WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            See the License for the specific language governing permissions and
            limitations under the License.
         
Classifier: Programming Language :: C++
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Operating System :: POSIX :: Linux
Project-URL: Repository, https://github.com/xju2/libFRNN
Requires-Python: >=3.9
Requires-Dist: numpy>=1.23
Description-Content-Type: text/markdown

# 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:

1. accumulate squared Euclidean distance in `float32` dimension order with
   one fused multiply-add per coordinate;
2. include candidates whose squared distance is less than or equal to
   `radius * radius`;
3. order each query row by `(squared_distance, original_database_index)`;
4. retain the first `max_neighbors` entries;
5. 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:

```text
query_count * database_count * dimension * ceil(max_neighbors / 8)
    <= 2,000,000
```

Callers can force either exact path for measurement or diagnosis:

```cpp
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:

```bash
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.

```bash
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:

```cmake
find_package(frnn CONFIG REQUIRED)
target_link_libraries(my_target PRIVATE frnn::frnn)
```

The synchronous host interface accepts row-major coordinates:

```cpp
#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:

```cpp
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:

```bash
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](#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:

```bash
python -m pip install .
```

or build a wheel:

```bash
python -m pip install build
python -m build
python -m pip install dist/frnn_cuda-*.whl
```

The Python API is:

```python
frnn_cuda.build_edges(
    query,
    database=None,
    *,
    radius: float,
    max_neighbors: int,
    exclude_self: bool = True,
    directed: bool | None = None,
) -> numpy.ndarray
```

For example:

```python
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:

```bash
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:

```python
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:

```bash
python tests/test_torch.py
```

To test an installed package rather than the source tree:

```bash
python tests/test_python.py
```

## Implementation layers

- `frnn` is 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.
- `_frnn` is built only with `FRNN_BUILD_PYTHON=ON`; it validates NumPy arrays
  and calls the public host API without reimplementing the algorithm.
- `_frnn_torch` is built only with `FRNN_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:

```bash
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:

```bash
./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.
