Skip to main content

PyTorch-native similarity search: convert FAISS indexes to nn.Module

Project description

torch-similarity-search

PyPI version Python 3.11+ License: MIT GitHub

PyTorch-native similarity search. Convert trained FAISS indexes to pure nn.Module models for GPU inference.

Train with FAISS, deploy with PyTorch.

Why?

  • No numpy overhead - FAISS requires numpy conversion; this library keeps tensors on GPU
  • TorchScript export - Deploy without FAISS dependency, load with just torch.jit.load()
  • GPU memory sharing - Index vectors stay in GPU memory alongside your embedding model
  • Triton Inference Server ready - Export once, serve anywhere

Installation

pip install torch-similarity-search

For FAISS conversion support:

pip install torch-similarity-search faiss-cpu  # or faiss-gpu

Quick Start

Convert from FAISS

import faiss
import torch
import torch_similarity_search as tss

# Train with FAISS (your existing workflow)
quantizer = faiss.IndexFlatL2(128)
index = faiss.IndexIVFFlat(quantizer, 128, 100)
index.train(vectors)
index.add(vectors)

# Convert to PyTorch
model = tss.from_faiss(index)
model = model.cuda()
model.nprobe = 10

# Search with PyTorch tensors (no numpy!)
queries = torch.randn(32, 128, device="cuda")
distances, indices = model.search(queries, k=10)

Build from Scratch

import torch
from torch_similarity_search import IVFFlatIndex

# Create and train
index = IVFFlatIndex(dim=128, nlist=100, metric="l2")
training_vectors = torch.randn(10000, 128)
index.train(training_vectors)
index.add(training_vectors)

# Move to GPU
index = index.cuda()

# Search
queries = torch.randn(32, 128, device="cuda")
distances, indices = index.search(queries, k=10)

Export for Production

# Export to TorchScript (no torch_similarity_search needed to load!)
scripted = torch.jit.script(model)
scripted.save("index.pt")

# Load anywhere - just needs PyTorch
model = torch.jit.load("index.pt")
model = model.cuda()
distances, indices = model.search(queries, k=10)

Use with Embedding Models

# End-to-end GPU inference
class SearchModel(torch.nn.Module):
    def __init__(self, encoder, index):
        super().__init__()
        self.encoder = encoder
        self.index = index

    def forward(self, text_embeddings):
        # Everything stays on GPU
        return self.index.search(text_embeddings, k=10)

# Export the complete pipeline
model = SearchModel(encoder, index)
torch.jit.script(model).save("search_pipeline.pt")

Supported Index Types

FAISS Index PyTorch Module Status
IndexFlat FlatIndex ✅ Supported
IndexIVFFlat IVFFlatIndex ✅ Supported
IndexIVFPQ IVFPQIndex ✅ Supported

API Reference

FlatIndex

Brute-force exact search - compares against all vectors. Best for small datasets or exact results.

from torch_similarity_search import FlatIndex

index = FlatIndex(
    dim=128,          # Vector dimensionality
    metric="l2",      # Distance metric: "l2", "ip" (inner product), or "cosine"
    k=10,             # Default k for forward() method
)

index.add(vectors)    # No training required
distances, indices = index.search(queries, k=10)

IVFFlatIndex

Inverted File Flat index - partitions vectors into clusters for fast approximate search.

from torch_similarity_search import IVFFlatIndex

index = IVFFlatIndex(
    dim=128,          # Vector dimensionality
    nlist=100,        # Number of clusters (higher = faster but less accurate)
    metric="l2",      # Distance metric: "l2", "ip" (inner product), or "cosine"
    nprobe=10,        # Clusters to search at query time
    k=10,             # Default k for forward() method
)

index.train(vectors)  # Train centroids first
index.add(vectors)
distances, indices = index.search(queries, k=10)

Common Methods (both index types):

Method Description
add(vectors) Add vectors to index. Accepts (n, dim) or (dim,) tensors.
search(queries, k) Find k nearest neighbors. Returns (distances, indices) tensors.
forward(queries) Same as search() but uses configured k. For TorchScript export.

IVFFlatIndex-specific:

Method/Property Description
train(vectors) Train cluster centroids via k-means. Requires n >= nlist.
nprobe Clusters to probe during search (settable, higher = more accurate)
is_trained Whether index has been trained

IVFPQIndex

Inverted File with Product Quantization - combines clustering with vector compression for memory-efficient approximate search. Best for large datasets where memory is a concern.

from torch_similarity_search import IVFPQIndex

index = IVFPQIndex(
    dim=128,          # Vector dimensionality (must be divisible by M)
    nlist=100,        # Number of IVF clusters
    M=8,              # Number of PQ subquantizers (compression factor)
    nbits=8,          # Bits per code (default: 8, meaning 256 centroids per subquantizer)
    metric="l2",      # Distance metric: "l2" or "ip" (inner product)
    nprobe=10,        # Clusters to search at query time
    k=10,             # Default k for forward() method
)

index.train(vectors)  # Train IVF centroids and PQ codebooks
index.add(vectors)
distances, indices = index.search(queries, k=10)

Compression: With M=8 and nbits=8, each 128-dim vector (512 bytes) is compressed to just 8 bytes - a 64x reduction in memory usage.

from_faiss(index)

Convert a FAISS index to PyTorch.

from torch_similarity_search import from_faiss

torch_index = from_faiss(faiss_index)  # Returns FlatIndex, IVFFlatIndex, or IVFPQIndex

Supported:

  • faiss.IndexFlatL2, faiss.IndexFlatIPFlatIndex
  • faiss.IndexIVFFlatIVFFlatIndex
  • faiss.IndexIVFPQIVFPQIndex

Requirements

  • Python 3.11+
  • PyTorch 2.0+
  • NumPy (for FAISS conversion only)
  • FAISS (optional, for conversion only)

License

MIT

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

torch_similarity_search-0.0.4.tar.gz (54.3 kB view details)

Uploaded Source

Built Distribution

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

torch_similarity_search-0.0.4-py3-none-any.whl (19.2 kB view details)

Uploaded Python 3

File details

Details for the file torch_similarity_search-0.0.4.tar.gz.

File metadata

  • Download URL: torch_similarity_search-0.0.4.tar.gz
  • Upload date:
  • Size: 54.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for torch_similarity_search-0.0.4.tar.gz
Algorithm Hash digest
SHA256 6e5146069451bb3a5424735fbd1ca987ed6d55ed6e07d8ca0ce35542f1d83c95
MD5 975067bbcef7c0e70f4901fab54ad5eb
BLAKE2b-256 14957821324b4801c7c1ff0bb84864a6bbebd7873055e3a55251d057703d66f9

See more details on using hashes here.

Provenance

The following attestation bundles were made for torch_similarity_search-0.0.4.tar.gz:

Publisher: publish.yml on mwang633/torch-similarity-search

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

File details

Details for the file torch_similarity_search-0.0.4-py3-none-any.whl.

File metadata

File hashes

Hashes for torch_similarity_search-0.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 d4e2f581d06edfe760e0c0fe0a470cc66edea2d78da84d3c3bec859dcec502eb
MD5 36de89785ae2d9698b5460f1dd35d6ab
BLAKE2b-256 885a4ede3154c40373dc78504fb9cae7eac9bce187aefbcd36b49a0d1ecbc3f4

See more details on using hashes here.

Provenance

The following attestation bundles were made for torch_similarity_search-0.0.4-py3-none-any.whl:

Publisher: publish.yml on mwang633/torch-similarity-search

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