turbovec README

项目的 README,来自 github.com/RyanCodrai/turbovec。合并为一个 markdown 文件:README.md。

turbovec — Google's TurboQuant for vector search

License PyPI version crates.io version TurboQuant paper

Python · Rust · How it compares · When to use something else · API reference · Benchmarks


Ten million 768-dimensional embeddings take 31 GB of RAM as float32. turbovec holds them in 4 GB and searches them 4.4× faster than FAISS, at matching recall.

turbovec is an in-process vector index for Python and Rust. It stores each vector at 2 or 4 bits per dimension using Google Research's TurboQuant and searches that compressed form directly with agent-optimised SIMD kernels.

Python

pip install turbovec
import numpy as np
from turbovec import TurboQuantIndex

vectors = np.load("embeddings.npy").astype(np.float32)   # shape (n, 1536)

index = TurboQuantIndex(dim=1536, bit_width=4)
index.add(vectors)

scores, indices = index.search(vectors[:1], k=5)
print(indices)         # [[    0 86544  3385 84492 24967]]   int64 slot positions
print(scores.shape)    # (1, 5)                             float32 inner products

index.sync("index.tv")                  # first sync writes the file
index.add(more_vectors)
index.sync("index.tv")                  # later syncs write just the change, durably

index = TurboQuantIndex.load("index.tv")   # loads either a sync'd or a write() file

Inputs are 2-D float32 arrays of shape (n, dim); other dtypes raise rather than silently convert. Scores are inner products, so normalise your vectors if you want cosine similarity.

Need ids that survive deletes? IdMapIndex keys everything by your own uint64 ids:

from turbovec import IdMapIndex

index = IdMapIndex(dim=1536, bit_width=4)
index.add_with_ids(vectors, ids)               # ids: uint64 array, one per row

scores, ids = index.search(query, k=10)        # your ids, not slot positions
index.remove(1002)                             # O(1)

# Filter: only ids another system approved — a SQL predicate, an ACL, a time window.
allowed = np.array([1001, 1003, 1042], dtype=np.uint64)
scores, ids = index.search(query, k=10, allowlist=allowed)   # shape (1, min(k, 3))

Framework integrations are drop-in replacements for each framework's in-memory store — same public surface, same persistence, same retriever wiring: LangChain (pip install turbovec[langchain]) · LlamaIndex (turbovec[llama-index]) · Haystack (turbovec[haystack]) · Agno (turbovec[agno]).

Rust

cargo add turbovec
use turbovec::{IdMapIndex, TurboQuantIndex};

let mut index = TurboQuantIndex::new(1536, 4)?;
index.add(&vectors);                          // &[f32], row-major, n × 1536
let results = index.search(&queries, 10);     // scores and slot indices, nq × 10
index.write("index.tv")?;
let index = TurboQuantIndex::load("index.tv")?;

let mut ids = IdMapIndex::new(1536, 4)?;
ids.add_with_ids(&vectors, &[1001, 1002, 1003])?;
let (scores, found) = ids.search(&queries, 10);
ids.remove(1002);

The Rust API mirrors the Python one; docs/api.md covers both, including the file formats, sync(), calibration and the staged search.

How it compares

All figures: 100K OpenAI embeddings (d=1536 and d=3072) and GloVe (d=200), k=64, 1K queries, median of 5 runs, on a GCP c4a-standard-8 (ARM) and c3-standard-8 (x86), against FAISS at a matched bit rate. Scripts, raw JSON and every chart are in docs/benchmarks.md.

Search speed, ARM, multi-threaded: turbovec vs FAISS IndexPQFastScan

Recall at k on OpenAI d=1536: turbovec vs FAISS IndexPQ at the same bit rate

turbovec FAISS
Search, 4-bit 3.8–5.1× faster across the eight cells (ARM 4.0×, x86 4.9×) IndexPQFastScan every cell
Search, 2-bit 1.8–2.5× faster (ARM 2.05×, x86 2.35×) IndexPQFastScan every cell
Recall@1, OpenAI 0.959 / 0.981 at 4-bit, 0.901 / 0.931 at 2-bit (d=1536 / d=3072) 0.966 / 0.971, 0.876 / 0.911 IndexPQ, m matched to bit rate
Recall@1, GloVe d=200 0.860 at 4-bit, 0.572 at 2-bit 0.842, 0.565 IndexPQ, m matched to bit rate
Memory, d=1536 75 MB at 4-bit, 38 MB at 2-bit 586 MB float32 7.8× / 15.5×
Single add() 7.9–21.7 µs 6.3–12.6× slower into a trained, populated index
remove(id) 1.4–5.8 µs 0.19–1.03 s FAISS repacks all codes per call
Whole-file save 1.0–1.4× slower than FAISS write_index turbovec fsyncs and renames atomically
Load → first search 1.0–1.5× slower than FAISS read_index 40 vs 31 ms at d=1536 4-bit on x86

Both always return the true nearest neighbour within the first 8 results on the OpenAI corpora. The full suite — every chart, the raw JSON and the scripts to re-run it — is in docs/benchmarks.md.

When to use something else

How it works

Normalise each vector and store its length. Rotate every vector by one shared random orthogonal matrix, after which each coordinate follows a known distribution whatever the input. Quantise each coordinate with a Lloyd-Max codebook computed for that distribution — 4 levels at 2-bit, 16 at 4-bit — and bit-pack. At search time the query is rotated once and scored against the codebook with SIMD lookup tables; a per-vector scalar fixed at encode time removes the inner-product bias quantization introduces. An optional one-shot calibrate(sample) fits two scalars per coordinate for data that drifts from the asymptotic distribution (low-dimensional and word-vector embeddings gain most).

The full walk-through, with the maths and the references, is in docs/how-it-works.md.

Building from source

Python wheel and Rust crate
pip install maturin
cd turbovec-python && maturin build --release && pip install target/wheels/*.whl
cargo build --release

x86_64 builds target x86-64-v2 (SSE4.2, Nehalem 2008+) via .cargo/config.toml; the AVX-512 and AVX2 kernels are #[target_feature]-gated and chosen at runtime with is_x86_feature_detected!, so one binary runs everywhere and uses what the CPU has. Running the benchmark suite is described in docs/benchmarks.md.

References

turbovec (RyanCodrai/turbovec)

正在搜索数据库…

这是什么?一个向量索引库,用于在嵌入向量上做最近邻搜索,用 Rust 编写并带有 Python 绑定。它基于 Google Research 的 TurboQuant 量化技术,面向注重内存、延迟和隐私的 RAG 场景。
它是 Python 包还是 Rust crate?需要单独跑一个服务吗?两者都是:既有 Rust crate,也有 Python 包。它以进程内方式运行在你的应用里——没有服务器,也没有托管服务组件。
怎么把它加到项目里?运行 pip install turbovec,或者用可选依赖,比如 pip install turbovec[langchain],把它作为 LangChain、LlamaIndex、Haystack 或 Agno 的向量存储接入。也附带 Rust API。
搜索之前需要先在我的嵌入向量上训练索引吗?不需要——向量在添加时就直接建立索引,没有训练步骤,不用调参数,语料增大后也无需重建。可选地,用大约 1024 条样本向量调用一次 calibrate() 来提升召回率。
输入数据方面有什么要注意的坑?有:向量和查询必须是形状为 (n, dim) 的二维 float32 数组。其他数据类型会被直接拒绝,而不会悄悄转换,所以如有需要,先用 np.asarray(x, dtype=np.float32) 转换。
我的嵌入数据会留在我的电脑上吗?完全本地化:没有托管服务,任何数据都不会离开你的电脑或 VPC。再搭配一个开源嵌入模型,就能得到一套完全离线隔离的 RAG 方案。
和 FAISS 相比怎么样?在 README 的基准测试中,它在所有测试配置上都胜过 FAISS 的 IndexPQFastScan——平均快 3.4 倍(4 位量化)和 23%(2 位量化),ARM 和 x86 上都是如此。内存方面,一个用 float32 存储要占 31 GB 的 1000 万文档语料库,只需 4 GB 就放得下。不过在对 GloVe 这类低维向量做 2 位量化、k 值较大时,FAISS 仍略有优势。
可以接入哪些框架?它可以作为 LangChain、LlamaIndex、Haystack 和 Agno 内存型向量存储的即插即用替代品——公开接口和持久化行为完全一致,只需换掉 import,你的流水线接线都不用动。
每次插入或删除之后都要重建整个索引吗?不用——sync(path) 只保存自上次 sync 以来的变更(一次 fsync,崩溃安全),无论索引多大,删除或少量追加都只需几毫秒。单次 add() 耗时 6.3–19.7 微秒,IdMapIndex.remove() 是 O(1) 的交换弹出操作。
能把向量搜索和 SQL、BM25 这类其他检索器结合使用吗?可以——给 search() 传入一个 id 允许列表(或槽位位掩码)即可。过滤是在 SIMD 内核内部进行的,所以选择性强的允许列表能跳过大部分打分工作,同时仍然从允许的集合里返回最多 k 个结果,召回率不受影响。
大小
9.3 MB
星标
17.5K
更新
提交Oct 06
时长
8个月
提交 · 90 天