Skip to main content

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 (and bfloat16 for 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.Tensor results.
  • NumPy input or .npy paths → returns numpy.ndarray results.

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 (.pt or .npy).
  • docs_path: Path to docs (.pt or .npy).
  • -k, --k: Top-K per query to keep (default: 100).
  • --metric: Similarity metric: ip (inner-product) or cosine.
  • --output-path: Optional path to save results (.pt or .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 satisfy 1 <= 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tiny_knn-0.2.0.tar.gz (46.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tiny_knn-0.2.0-py3-none-any.whl (32.6 kB view details)

Uploaded Python 3

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

Hashes for tiny_knn-0.2.0.tar.gz
Algorithm Hash digest
SHA256 04d9c1bf105998d9daf0fb20093d4f9951671223974f05bbc6dddc6d8dca78cf
MD5 c70ba6c32a4c1f639ef94088331ca008
BLAKE2b-256 9cdd332362c4db42ca18a5737db0dd5027d3f8e3a688845c53b9c9e6b730f1c5

See more details on using hashes here.

Provenance

The following attestation bundles were made for tiny_knn-0.2.0.tar.gz:

Publisher: release.yml on noosphaerenbauer/tiny-knn

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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

Hashes for tiny_knn-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8f1cc8c2862d3fc1d08e203361e344257b18bf13f0331a5c10d5365319557ef3
MD5 27e9305b1f53c0af23297e46e4c41e31
BLAKE2b-256 a5db64133c474a55de5ce5b52ffbcbb4eae8443a65200e683fb883ca15c67224

See more details on using hashes here.

Provenance

The following attestation bundles were made for tiny_knn-0.2.0-py3-none-any.whl:

Publisher: release.yml on noosphaerenbauer/tiny-knn

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page