Skip to main content

logo torann

TORoidal Approximate Nearest Neighbours

PyPI - Version PyPI - Python Version GitHub License GitHub Actions Workflow Status GitHub last commit

torann is exact + approximate k-NN and range search on the unit torus $[0,1)^d$ under toroidal L1 — a metric mainstream ANN libraries do not offer, chosen deliberately: L1 degrades more gracefully than L2/cosine in high dimensions, and on the torus the LSH guarantee is exact. Built for ESS-style epoch workloads: static anchors, a moving candidate tier, selective updates, batch promotion.

Features

  • The metric is the contract: toroidal L1, exact distances everywhere — the LSH only filters candidates, never approximates a distance.
  • An LSH family that is exactly L1-sensitive on the torus: randomly rotated integer grids with a closed-form, seam-free collision law (see How it works).
  • ESS-shaped lifecycle: two tiers (anchors + candidates), selective update() that re-places only points whose hash cell changed, promote() as a linear merge — never a re-sort, exact after every step.
  • No brute-force fallback: under-filled queries widen buckets by prefix relaxation (contiguous sorted-key ranges), so k results are structurally guaranteed.
  • Self-tuning: fit(..., k=...) or radius=... derives the hash parameters (B, K, L) from the workload; explicit arguments always win.
  • Three interchangeable implementations of one interface (torann/base.py): exact NumPy brute force, a pure-Python LSH reference, and a Rust core (PyO3 + rayon) that produces byte-identical hash tables at 60–120× the speed. Without the compiled module — or on a CPU below the AVX2 floor — the package still runs, on the reference implementation.
  • No unsafe: the SIMD kernel is wide, a safe stable-Rust wrapper. Hand-written core::arch intrinsics were measured at 21% faster and declined; that trade is deliberate and stays open.

Installation

From PyPI

pip install torann

From source

The project is a maturin mixed Rust/Python package — a Rust toolchain is required to build the native core:

python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install .

Requirements: Python ≥ 3.12, numpy.

Rust ≥ 1.98 is required to build the native core: the distance kernel uses the algebraic floating-point methods stabilized in that release.

CPU: published x86-64 wheels are built with an AVX2 + FMA floor — Intel Haswell (2013) and AMD Excavator (2015) onward. That is not gratuitous: the distance kernel is a plain scalar loop that the compiler auto-vectorizes, and without AVX it has no 256-bit register to lower to, costing 17% (340 ms → 408 ms on the reference shape). AVX-512 is not used: it is a further 4% at d = 32 but nearly 2× worse at d = 8. On a CPU without AVX2 the compiled backend is not loaded and the pure-Python implementation is used instead, with a warning; installing from the sdist builds a native module for whatever the machine has. arm64 needs no floor — NEON is baseline there, and the kernel names no vector type, so it follows the target rather than pinning a width.

Quick Start

General LSH Collection API (create, add, update, delete, optimize)

import numpy as np
from torann import ToroidalNN

rng = np.random.default_rng(42)
nn = ToroidalNN.create(rng.random((15_000, 16)), seed=42)  # every knob defaults to "auto"

p_id = nn.add(rng.random(16))               # single point -> int ID
batch_ids = nn.add(rng.random((3_000, 16))) # batch -> int64 IdArray

nn.update(p_id, rng.random(16))             # O(1) in-place update by ID
nn.update(batch_ids, rng.random((3_000, 16)))
nn.delete(p_id)                             # or `del nn[p_id]`
nn.optimize()                               # compact tombstones & retune (also auto on drift/growth)

len(nn), batch_ids[0] in nn, nn[batch_ids[0]]  # standard Python collection protocol

# Queries (single (d,) point or (m, d) batch; rows sorted by ascending toroidal L^p distance)
res = nn.query(k=8, queries=nn[batch_ids], exclude_ids=batch_ids)
csr = nn.query_radius_csr(0.25, queries=nn[batch_ids], exclude_ids=batch_ids)

ESS Epoch Lifecycle (Two-Tier Convenience Wrappers)

nn = ToroidalNN(seed=42)
nn.fit(static, batch, k=2*d)            # build + tune from zero

for epoch in range(32):
    idx, dist = nn.query()              # each candidate vs everything
                                        # (a Neighbours pair: .ids, .distances)
    new = force_step(nn.candidates, idx, dist)   # your physics here
    nn.update(new)                      # selective refresh

nn.promote(next_batch)                  # candidates freeze into anchors
nn.demote(nn.static_ids[-4:])           # move anchors back to candidates without refit

nn.query_radius(0.25)                   # range query, one Neighbours per query
nn.query_radius(0.25, pad=True)         # the same, dense and -1/inf padded
csr = nn.query_radius_csr(0.25)         # zero-padding CSRNeighbours(indptr, ids, distances)
forces = csr.weighted_directions(nn.points, nn.candidates, weights)
nn.query(k=8, queries=Q, exact=True)    # exact escape available on every query method

Public Native Kernels (torann.native)

Backend-agnostic geometric kernels backed by Rust when available with transparent NumPy fallbacks (no need to import torann.rust or check availability):

from torann import native

forces_csr = native.weighted_directions_csr(points, queries, csr.indptr, csr.ids, weights)
forces_dense = native.weighted_directions(points, queries, ids, weights)
D = native.pairwise_lp(queries, points, p=0.5, rooted=True)  # exact toroidal L^p (default rooted=True)

Inputs may be any finite coordinates (reduced mod 1; NaN or inf raises ValueError and leaves the index unchanged; unknown/deleted IDs raise KeyError; non-integer IDs raise TypeError). Every result row of query, query_radius, and query_radius_csr is guaranteed sorted by ascending toroidal $L^p$ distance ($0 < p \le 1$), ties by ascending external ID, on every backend (both brute and LSH), with self excluded by default when queries=None. exclude_ids is per-query, not a global blacklist: exclude_ids[i] is skipped only for query i (-1 skips nothing).

Parameter Defaults & Tuning Sources

Every ToroidalNN parameter has a documented default ("auto" where tuned by heuristic, with None accepted as an alias):

Parameter Default Tuning / Calibration Source
p 1.0 Toroidal $L^p$ exponent in (0, 1]
recall "auto" 0.96 ($p=1$), 0.98 ($p<1$) for the $k$-th neighbour
num_tables "auto" Analytical wall-crossing model ($L \in [4, 24]$)
resolution "auto" Data-driven cell count ($B \in [2, 8]$)
dims_per_table "auto" Bucket-load rule $\operatorname{round}(\log_B(n / \text{target}))$
target_bucket_size "auto" max(32, k_hint)
probes "auto" Joint 1-wall / 2-wall planner (0–8; default 4)
query_block_size "auto" One block per worker thread (batched join reuse)
brute_threshold / *_knn / *_radius "auto" Measured _CROSSOVER table (re-measurable via tune_thresholds)
backend "auto" First installed of "rust", "python"
auto_optimize True Retunes on drift ($\ge 0.15\times$), growth ($\ge 1.5\times$), or tombstones ($\ge 0.25$)

API Stability & Deprecation Policy

The public API is defined by torann.__all__ (ToroidalNN, Neighbours, CSRNeighbours, IdArray, DistArray, available_backends, native, toroidal_separation, tune_thresholds) and torann.native.__all__ (weighted_directions, weighted_directions_csr, pairwise_lp). Both ToroidalNN.update(ids, points) and the single-argument candidate form ToroidalNN.update(coordinates) are stable public APIs. Any future breaking change or removal of a public symbol will emit a DeprecationWarning for at least one minor release before removal.

How it works

The metric

On the torus, distance wraps: per dimension it is $\min(|a_i-b_i|,, 1-|a_i-b_i|)$, and the metric is the sum. Near an edge the nearest region of a query is not where a seam-blind index looks — it wraps around every boundary it touches. The teal points are the true 12-NN of the star:

the toroidal nearest region

The region follows the query around the torus:

the nearest region wraps

At d=16, distance concentration makes wrapping the common case: almost every true neighbour pair wraps in at least one dimension, which is why a seam-blind exact search misses ~74 % of the true toroidal neighbours (examples/compare_faiss.py).

The hash

One hashed dimension, with integer resolution $B \ge 2$ and a random offset $u \sim U[0,1)$:

$$c(x) = \lfloor B,((x+u) \bmod 1) \rfloor \qquad P[c(x){=}c(y)] = \max(0,, 1 - B\delta)$$

Because $B$ is an integer, the $B$ arcs tile the circle exactly — the grid has no seam, and the collision law is exact, not approximate (dots are measured frequencies):

the offset integer grid the collision law is exact

A table concatenates $K$ sampled dimensions into a base-$B$ key, each with its own offset, so a pair collides with probability $\prod_j \max(0, 1-B\delta_j) \le e^{-B \sum_j \delta_j}$ over the table's coordinates; averaged over which dimensions are drawn, a pair at toroidal L1 distance $r$ collides with probability $(1 - Br/d)^K \le e^{-BKr/d}$ while every $\delta_i \le 1/B$ — inherently an L1 guarantee, which is why L1 is the public contract and no other metric is offered. A uniformly random pair collides per dimension with probability exactly $1/B$ (closed-form bucket load $n/B^K$), and a point that moves by $s$ changes its cell with probability $B s$ — churn is proportional to movement, which is what makes selective updates cheap. The rejected alternatives (p-stable projections cannot wrap; integer projections alias far points onto near ones) are measured in exploration/.

The index

index representation

Sorted key arrays make a bucket a contiguous range (an $O(1)$ direct-address offset table serves the static tier), keys are digit concatenations so prefix relaxation — dropping low-order digits — widens a bucket into a wider contiguous range without any distance scan, and every gathered candidate is refined with the exact toroidal L1 before the top-k. Full details: torann/lsh.py — the reference implementation, normative for the L1 hash.

Scope: what torann answers, and what it does not

torann answers geometric questions about points on the torus — which points are near which, and how far apart they are. That is the index, and it is also torann.metrics: a metric like toroidal_separation is one exact k-NN scan, so it belongs beside the scan.

from torann import toroidal_separation

toroidal_separation(design)            # maximin separation of a point set
toroidal_separation(batch, anchors)    # ...of a batch added to existing points

torann does not decide what a "good" point set is. Ranking one design against another depends on the purpose the points serve, not on the geometry, so that judgement belongs to the caller. torann/metrics.py documents which competing metrics were measured and how each behaves — including the ones that stop discriminating in high dimension — so a caller can choose with numbers in front of it. It does not choose.

That line is drawn deliberately. When a metric's definition lived in one project and the choice of metric in another, a rename in one silently outlived the other: scripts asked for keys that no longer existed and died in their reporting after completing every run, and one printed a lower-is-better number under a higher-is-better heading for weeks without ever failing. Definitions here, choices in the caller.

Benchmarks

Measured on an AMD Ryzen AI 7 PRO 350 (16 threads), d=16, k=32, on a build carrying the AVX2 floor described under Installation — which is what the published wheels now ship, so these are numbers you get rather than numbers only the developer got. Regenerate the full grids, crossover and complexity tables with python examples/benchmark.py:

These figures predate the Rust 1.98 distance kernel and are now conservative. That rewrite is worth 8–50% on the query path depending on dimensionality, and d = 16 — the dimension charted here — is near the top of that range at ~27%. The plots are regenerated by the command above; the numbers below have not been re-measured since.

queries vs n

On the workload this library exists for — the ESS main loop, simulated end to end (examples/ess_sim.py) — torann is 1.7× faster than FAISS Flat rebuilt per epoch and correct, where FAISS's exact seam-blind L1 delivers 0.25–0.28 recall against the true toroidal neighbours:

the ESS main loop

Queries run 11–148 µs at 16 threads across n ∈ [20k, 1M] on torus data — 60–120× the NumPy pipeline — with 0.9–2.1 ms selective updates and ~1 s builds at n = 1M (HNSW: 24–32 s). On wrap-free data (FAISS's best case) torann sits within 1.06–1.56× of FAISS's exact SIMD Flat scan at equal ≈ 1.0 recall. Python and Rust implementations produce byte-identical hash tables, so their recall is identical by construction.

Running Unit Tests

The conformance suite runs once per installed backend and checks byte-identical tables plus equivalent query results across the whole lifecycle, using the standard unittest framework:

python3 -m venv venv
VIRTUAL_ENV=$PWD/venv maturin develop --release --group test   # builds torann/_native*.so in place
PYTHONPATH=. TORANN_REQUIRE_NATIVE=1 venv/bin/python -m unittest discover -s test

TORANN_REQUIRE_NATIVE=1 fails the run when the extension did not load (0 asserts the pure-Python backend); without it, a missing .so makes every native test skip and the suite still passes.

Documentation

The library uses Google-style docstrings; the API documentation is generated with pdoc by a GitHub Action and published here. To preview locally:

pip install pdoc
pdoc --math -d google torann torann.wrapper torann.base torann.brute torann.lsh torann.rust

Development

The checks in CI also run at commit time:

pre-commit install
pre-commit run --all-files   # check the tree without committing

The hooks call machine-installed tools (language: system) at exactly the versions pinned in pyproject.toml's lint, test and build dependency groups, which is what .github/workflows/main.yml installs; Rust is pinned to 1.99.1 in all three workflows. Each commit is gated on: an in-place release build into ./venv (maturin develop), ruff check, ruff format --check, basedpyright, vulture, the unit tests against the native build and against a copy without it, coverage (--fail-under=93), cargo fmt --check, cargo clippy --release -D warnings (plain and --features stats) and cargo test. Formatting-only commits are listed in .git-blame-ignore-revs (git config blame.ignoreRevsFile .git-blame-ignore-revs).

publish.yml builds the wheels and sdist on a release, tests the installed Linux wheel from a tree with no sources, then uploads to PyPI; docs.yml builds the pdoc site on every push to main.

python examples/ess_sim.py             # the ESS main loop end to end, vs FAISS
python examples/bench_backends.py      # per-op grid over (n, d, backend)
python examples/crossover.py           # brute vs LSH crossover n*(d, backend)
python examples/compare_faiss_flat.py  # non-toroidal throughput vs FAISS
python examples/figures.py             # regenerate the README method figures
python examples/plot_benchmarks.py     # regenerate the benchmark figures
python exploration/exp_1d.py           # regenerate the concept experiments

maturin build --release produces the complete wheel (Cargo.toml + src/lib.rs are the native core; torann/ is the Python package). The C contender from the phase-6 bake-off is preserved at tag archive/backend-c.

Authors

License

This project is licensed under the MIT License - see the LICENSE file for details.

Metadata

Release files for torann 0.8.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for torann 0.8.1
File Size Uploaded Provenance Actions
torann-0.8.1.tar.gz 224.2 kB Without provenance Details for torann-0.8.1.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for torann 0.8.1
File Actions
torann-0.8.1-cp311-abi3-win_amd64.whl CPython 3.11 abi3 Windows x86-64 Details for torann-0.8.1-cp311-abi3-win_amd64.whl
torann-0.8.1-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.11 abi3 Linux glibc 2.17+ x86-64 Details for torann-0.8.1-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
torann-0.8.1-cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl CPython 3.11 abi3 Linux glibc 2.17+ ARM64 Details for torann-0.8.1-cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
torann-0.8.1-cp311-abi3-macosx_11_0_arm64.whl CPython 3.11 abi3 macOS 11.0+ ARM64 Details for torann-0.8.1-cp311-abi3-macosx_11_0_arm64.whl
torann-0.8.1-cp311-abi3-macosx_10_12_x86_64.whl CPython 3.11 abi3 macOS 10.12+ x86-64 Details for torann-0.8.1-cp311-abi3-macosx_10_12_x86_64.whl

Total release size: 2.7 MB

Release files / torann-0.8.1.tar.gz

Download URL torann-0.8.1.tar.gz
Size 224.2 kB
Tags Source
SHA-256 checksum
How to use checksums
d04681e34f70c63d0b196c53309e1d0dbca536215486601976ba0e5be7302e5f
BLAKE2b-256 checksum
How to use checksums
c1f234be1ac03b87bed51a8e59d2a8d93221e1836901cfa4ed56f04aa6496c03
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / torann-0.8.1-cp311-abi3-win_amd64.whl

Download URL torann-0.8.1-cp311-abi3-win_amd64.whl
Size 419.7 kB
Tags CPython 3.11 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
240b6c7e998f83ab282ee93745165064d835129fb370632084388665cac9ed40
BLAKE2b-256 checksum
How to use checksums
e83a324d87b0776450e1b6581c31a1623c84ca1c3423af3a47d1b75463892c0b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / torann-0.8.1-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL torann-0.8.1-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 530.5 kB
Tags CPython 3.11 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
9241c29e08e468f0d7f723284e87d89e89b753378a56944c94cc6454756ee336
BLAKE2b-256 checksum
How to use checksums
8aae468b85272352fe6f53eb776f121ef48b26a38b08177bdf016376769d9840
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / torann-0.8.1-cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl

Download URL torann-0.8.1-cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Size 518.7 kB
Tags CPython 3.11 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
54e8f5f86092498352908ec3cf68c6c010c1a18f55cc0f2122b68a1b682ece51
BLAKE2b-256 checksum
How to use checksums
8537bab9b9e0b2b455aae85abbae577b5e9205e669eed2d924236a337e2b6d96
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / torann-0.8.1-cp311-abi3-macosx_11_0_arm64.whl

Download URL torann-0.8.1-cp311-abi3-macosx_11_0_arm64.whl
Size 482.5 kB
Tags CPython 3.11 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
e3a8925dfe0b40b978c9a66d5ba13e2e29f7e214c544de447e38959df475b937
BLAKE2b-256 checksum
How to use checksums
27f50fd3c4f1a9d38bfd8de5567ef15fe4c1fa25bc39842a013a790ac5c5e956
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / torann-0.8.1-cp311-abi3-macosx_10_12_x86_64.whl

Download URL torann-0.8.1-cp311-abi3-macosx_10_12_x86_64.whl
Size 502.4 kB
Tags CPython 3.11 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
51a23ff0417ca078b1f34a993ee66057130f869ef84592c747c76123381d62ae
BLAKE2b-256 checksum
How to use checksums
9d4988732aed12c85499f48f7bea0f9fca1c247df78c1d470571e684fdd94aad
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for torann 0.8.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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page