A tiny KNN library for large Torch tensors.
Project description
tiny-knn
A tiny KNN library for finding the top-K nearest neighbors in large embedding spaces, optimized for memory efficiency.
This library works with Torch tensors, NumPy arrays, or file paths to .pt/.npy arrays. It uses GPU acceleration (via PyTorch) for fast inner-product or cosine similarity. It intelligently batches queries and chunks document matrices to manage memory.
Features
- Memory efficient: Streams large arrays from disk in manageable chunks.
- GPU accelerated: Leverages PyTorch for fast computation on CUDA-enabled GPUs.
- Mixed precision: Supports
float32,float16(andbfloat16for Torch tensors). - Simple I/O: Accepts Torch tensors, NumPy arrays, or file paths to
.pt/.npy. - CLI + Library: Use from the command line or directly in Python.
Installation
pip install .
Usage
As a Library
from tiny_knn import exact_search
import torch
import numpy as np
# Torch tensors
Q, D, dim, k = 1000, 1_000_000, 128, 100
queries_t = torch.randn(Q, dim, dtype=torch.float32)
docs_t = torch.randn(D, dim, dtype=torch.float32)
indices_t, scores_t = exact_search(queries_t, docs_t, k, metric="ip")
# NumPy arrays
queries_np = np.random.randn(Q, dim).astype(np.float32)
docs_np = np.random.randn(D, dim).astype(np.float32)
indices_np, scores_np = exact_search(queries_np, docs_np, k, metric="cosine")
# File paths (.pt or .npy)
indices, scores = exact_search("path/to/queries.pt", "path/to/docs.pt", 100, metric="ip")
The function returns a tuple (indices, scores) where both are the same type family as the inputs:
- Torch input → returns
torch.Tensorresults. - NumPy input or
.npypaths → returnsnumpy.ndarrayresults.
Shapes: indices.shape == scores.shape == (Q, k). indices are int64; scores are float32.
As a Command-Line Tool
tiny-knn also provides a command-line interface.
tiny-knn path/to/queries.(pt|npy) path/to/docs.(pt|npy) --k 100 --metric ip --output-path results.pt
Arguments:
queries_path: Path to queries (.ptor.npy).docs_path: Path to docs (.ptor.npy).-k, --k: Top-K per query to keep (default: 100).--metric: Similarity metric:ip(inner-product) orcosine.--output-path: Optional path to save results (.ptor.npz).
API Reference
exact_search(arr1, arr2, k, metric)
def exact_search(
arr1: np.ndarray | torch.Tensor | str,
arr2: np.ndarray | torch.Tensor | str,
k: int,
metric: str | None = None,
) -> tuple[Indices, Scores]
Computes exact top-K nearest neighbors using inner-product (ip) or cosine similarity (cosine).
arr1,arr2: 2D arrays of shape(N, dim)provided as Torch tensors, NumPy arrays, or file paths to.pt/.npy.k: Number of neighbors to retrieve per query. Must satisfy1 <= k <= D.metric:'ip'or'cosine'.
Returns (indices, scores) where both are either Torch tensors or NumPy arrays, matching the input type. Shapes: (Q, k).
Notes:
- Device and precision are chosen automatically (CUDA if available). Cosine similarity applies L2-normalization internally.
- The implementation batches queries and streams document chunks to control memory usage.
Development
To install the package in editable mode for development, run:
pip install -e .
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file tiny_knn-0.2.0.tar.gz.
File metadata
- Download URL: tiny_knn-0.2.0.tar.gz
- Upload date:
- Size: 46.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
04d9c1bf105998d9daf0fb20093d4f9951671223974f05bbc6dddc6d8dca78cf
|
|
| MD5 |
c70ba6c32a4c1f639ef94088331ca008
|
|
| BLAKE2b-256 |
9cdd332362c4db42ca18a5737db0dd5027d3f8e3a688845c53b9c9e6b730f1c5
|
Provenance
The following attestation bundles were made for tiny_knn-0.2.0.tar.gz:
Publisher:
release.yml on noosphaerenbauer/tiny-knn
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
tiny_knn-0.2.0.tar.gz -
Subject digest:
04d9c1bf105998d9daf0fb20093d4f9951671223974f05bbc6dddc6d8dca78cf - Sigstore transparency entry: 428921078
- Sigstore integration time:
-
Permalink:
noosphaerenbauer/tiny-knn@e77b1fb524b4d4ce596a61c2b306573d9a69cb75 -
Branch / Tag:
refs/tags/v0.2.0 - Owner: https://github.com/noosphaerenbauer
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@e77b1fb524b4d4ce596a61c2b306573d9a69cb75 -
Trigger Event:
push
-
Statement type:
File details
Details for the file tiny_knn-0.2.0-py3-none-any.whl.
File metadata
- Download URL: tiny_knn-0.2.0-py3-none-any.whl
- Upload date:
- Size: 32.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8f1cc8c2862d3fc1d08e203361e344257b18bf13f0331a5c10d5365319557ef3
|
|
| MD5 |
27e9305b1f53c0af23297e46e4c41e31
|
|
| BLAKE2b-256 |
a5db64133c474a55de5ce5b52ffbcbb4eae8443a65200e683fb883ca15c67224
|
Provenance
The following attestation bundles were made for tiny_knn-0.2.0-py3-none-any.whl:
Publisher:
release.yml on noosphaerenbauer/tiny-knn
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
tiny_knn-0.2.0-py3-none-any.whl -
Subject digest:
8f1cc8c2862d3fc1d08e203361e344257b18bf13f0331a5c10d5365319557ef3 - Sigstore transparency entry: 428921080
- Sigstore integration time:
-
Permalink:
noosphaerenbauer/tiny-knn@e77b1fb524b4d4ce596a61c2b306573d9a69cb75 -
Branch / Tag:
refs/tags/v0.2.0 - Owner: https://github.com/noosphaerenbauer
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@e77b1fb524b4d4ce596a61c2b306573d9a69cb75 -
Trigger Event:
push
-
Statement type: