Skip to content
zevahclePublic

About

A Metric Inverted Sample Index

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

MISIFU — a Metric Inverted Sample Index

tests license arXiv

Paper: E. Chávez, misi: a Metric Inverted Sample Index, arXiv:2608.27422 [cs.IR], 2026.

Similarity search that indexes the company an object keeps.

Draw a sample S of the database — a fraction α of it, not a constant number of pivots. Describe every object by its k_b nearest sample points (its signature), and invert that: the posting list of a sample point s holds every object that has s in its signature. A query is answered by finding the query's own nearest sample points, counting which objects share them, and verifying the best C candidates with the real distance.

Two consequences follow, and they are the reason to use this index:

  • What must stay in RAM is the sample, not the database. Postings, signatures and vectors can live on disk; the resident cost tracks α·n, which you choose.
  • It works for any metric. The core never looks at a vector — it consumes signatures. The distance lives entirely in the pluggable inner index that computes them.

misi is the Spanish call for a cat; Misifú, the archetypal cat name, is its formal one.

Status: research prototype. The API is small and tested (20 tests, exercised in CI), the C++ core is used for all reported measurements, and the accompanying paper is in preparation. Section Where it stands is explicit about what has been measured and what has not.


Install

Requires Python ≥ 3.9 and a C++17 compiler (Xcode command-line tools on macOS, build-essential on Debian/Ubuntu). Everything else is numpy.

pip install "git+https://github.com/zevahcle/MISIFU.git"

That builds the extension and installs the misifu command. To check:

misifu --help
python -c "import misifu; print(misifu.MISIFU)"

Optional extras:

pip install "misifu[hdf5] @ git+https://github.com/zevahcle/MISIFU.git"   # read ann-benchmarks .hdf5
pip install "git+https://github.com/zevahcle/graft-ann"                   # GRAFT inner index, for scale
Developing against a checkout
git clone https://github.com/zevahcle/MISIFU.git && cd MISIFU
pip install -e ".[test,hdf5]"
pytest -q                             # 20 tests, ~1 s
python experiments/smoke_random.py    # recall/cost and posting-skew on synthetic data

Sixty-second start

Make a toy dataset, then use the CLI — no Python required.

python -c "
import numpy as np
rng = np.random.default_rng(0)
X = rng.standard_normal((50_000, 32)).astype(np.float32)
np.save('vectors.npy', X); np.save('queries.npy', X[:200])
"

misifu build vectors.npy -o my-index --alpha 0.02 --k-b 32
misifu info  my-index
misifu query my-index vectors.npy --queries queries.npy -k 5 -C 2000
$ misifu info my-index
objects n      50,000
dimension d    32
sample |S|     1,000  (alpha = 0.02)
signature k_b  32   posting cap: uncapped
resolution rho 1600

The same thing from Python:

import numpy as np
from misifu import MISIFU

X = np.random.randn(100_000, 32).astype(np.float32)

idx = MISIFU(alpha=0.02, k_b=32, inner="brute").fit(X)
ids, sq_dists = idx.query(X[0], k=10, C=1000)

ids, sq_dists = idx.batch_query(Q, k=10, k_s=64, C=5000, scoring="idf")

query returns (ids, squared_L2_distances). batch_query is the path all reported throughput uses: three GIL-released C++ calls (inner search → merge → threaded verification), returning results identical to the per-query path.


The knobs, and which one to reach for

Four parameters matter. Two are frozen at build time, two are free at query time.

knob when what it does start at
alpha build sample fraction. Sets the resident cost, α·n·d bytes 0.02
k_b build signature size. Sets how much evidence each object carries 64
k_s query how many posting lists a query merges. Free recall knob k_b
C query how many candidates get a real distance. The cost dial 5000

The two build parameters are best thought of as one derived quantity: resolution ρ = k_b/α, the expected posting-list length — how far out into the database each sample point sees. misifu info prints it.

Practical guidance:

  • Want more recall, already built? Raise C first, then k_s. Neither needs a rebuild. Raising k_s above k_b is legitimate and often cheaper than raising C alone.

  • Want less memory? Lower alpha. Resolution rises to compensate, so posting lists lengthen and each query reads more — you are trading RAM for bandwidth, deliberately.

  • Hub-heavy data (word embeddings, anything with high hubness): use scoring="idf", which discounts sample points that appear in very many signatures. Worth several points of recall there; roughly neutral on isotropic data, so it is a safe default.

  • Don't know a good C? Use the adaptive budget instead:

    ids, d = idx.query(q, k=10, patience=3, batch=100, C_max=20_000)

    Verification walks down the candidate ranking in batches and stops after patience batches that fail to improve the k-th distance. It transfers across datasets far better than a tuned C, and the budget it happens to spend is a useful per-query hardness estimate (idx.last_evals).

Sweep the grid yourself:

misifu bench my-index vectors.npy --queries queries.npy --gold gt.npy \
       --k-s 32 64 -C 1000 5000 20000
  k_s        C  recall@10        qps     ms/q
   32     1000     0.8935      9,831    0.102
   32     5000     0.9865      6,151    0.163
   64     1000     0.9295      6,968    0.144
   64     5000     0.9955      4,703    0.213

Running on a small machine

This is the case the design is built for. The rule is the same for building and for serving: the sample is the only thing that needs to be resident.

Building an index bigger than your RAM

misifu build deep-10M.npy -o deep-10M-index --alpha 0.02 --k-b 64 \
       --inner graft --factory --work-dir /path/to/scratch

--factory streams the finished artifact straight to disk. Signatures are computed in chunks against the frozen inner index; the inverted file is produced by an external bucketed sort; the postings never exist in RAM. The floor is sample + inner index + one chunk + one bucket — independent of n.

From Python:

X = np.load("deep-10M.npy", mmap_mode="r")          # never fully read into RAM
MISIFU(alpha=0.02, k_b=64, inner="graft").fit(
    X, factory="deep-10M-index", work_dir="/path/to/scratch")

The output is bit-identical to the in-memory build — enforced by a test, and easy to confirm yourself:

misifu build vectors.npy -o a --alpha 0.02 --k-b 32
misifu build vectors.npy -o b --alpha 0.02 --k-b 32 --factory
cmp a/postings.misi b/postings.misi && echo identical

Measured: a 10⁷-object, 96-dimensional build completed in 462 s under an enforced 3 GiB cgroup limit (memory.peak equal to the cap; the kernel reclaimed throughout), within 8% of the same build run uncapped. On a fanless M-series laptop the same build takes about 7 minutes from a memmap.

Build on one machine, serve on another

The artifact does not contain the vectors. They belong to the dataset and are supplied again at load time — a np.memmap is fine, because verification is the only thing that touches them, and it touches them at C random rows per query.

X = np.load("deep-10M.npy", mmap_mode="r")
idx = MISIFU.load("deep-10M-index", X, inner="graft")
ids, d = idx.batch_query(Q, k=10, k_s=64, C=10_000, scoring="idf")
misifu query deep-10M-index deep-10M.npy --queries q.npy -C 10000 --inner graft

The artifact is a directory of plain arrays (postings.misi, signatures.npy, sample_idx.npy, meta.json) — copy it anywhere. The inner index is rebuilt from the sample at load, which is where the load seconds go.

misifu info reports what an artifact will actually cost you to serve:

resident when serving ~ sample vectors (0.72 GiB) + inner index + posting offsets;
the database itself is memory-mapped and touched only to verify candidates.

Determinism

Builds do not depend on thread count, insertion order, or build mode. The same inputs and seed give the same bytes. This is a property of the design — there is no incremental graph to serialise — and it is what makes "build on the server, ship the artifact" safe.


GPU

For a single-GPU box, experiments/gpu_fused.py runs the whole query pipeline on the device: two CUDA kernels (a per-query sketch accumulator over the posting stream, then survivor collection with exact forward scoring) followed by CuPy top-C selection and verification.

pip install cupy-cuda12x
python experiments/gpu_fused.py --x deep-5M.fbin --q queries.fbin \
       --artifact deep-5M-index --gold gt.npy --nq 1000

It is aimed at modest hardware. Measured on a 6 GB laptop RTX 3060, 5·10⁶ objects at α=2%, k_b=64, idf scoring, C=10⁴:

recall@10 qps resident
CPU, 16 threads 0.9926 278 —
GPU, fused kernels 0.9926 1,139 ~4 GB VRAM

A 65 W laptop GPU beats its own CPU by 4.1×. The shape of the kernel is the same memory-bound accumulation the CPU merge does, which is why it transfers: the posting stream is 45% of GPU runtime, the inner search 20%, verification 13%.

experiments/gpu_sketch.py is the same algorithm in plain CuPy — slower, much easier to read, and useful as a correctness reference.

Caveat: this is compared against its own CPU, not against a GPU ANN library. Treat the 4.1× as "the design ports to a GPU and small cards are enough", not as a competitive claim.


Reference

MISIFU(alpha=0.01, k_b=32, inner="brute", cap=0, seed=0, n_threads=0)
.fit(X, sample_idx=None, low_memory=False, factory=None, work_dir=None, chunk=…) build; returns self, or the artifact path in factory mode
.query(q, k, k_s, C, scoring, patience, batch, C_max) one query → (ids, sq_dists)
.batch_query(Q, k, k_s, C, scoring, max_rank, …) batched; the throughput path
.save(dir) / MISIFU.load(dir, X, inner=…) artifact round-trip
.rho, .list_lengths(), .last_evals resolution, posting skew, last query's budget
misifu.recall(pred_ids, gt_ids) mean recall@k

scoring is count (plain shared-neighbour count), idf (hub-discounted), rank, or rank_idf. max_rank restricts the merge to postings below a given build rank — a cost knob that trades a little recall for a shorter stream.

Inner index. inner="brute" is exact and fine up to a sample of ~10⁵. Beyond that use inner="graft" (GRAFT). Anything with build(X) / search(Q, k) -> (ids, dists) plugs in — hnswlib, FAISS, or your own:

class MyInner:
    def build(self, X_sample): ...
    def search(self, Q, k):     return ids, dists   # ids index into the sample
idx = MISIFU(alpha=0.02, k_b=64, inner=MyInner()).fit(X)

Because the core only ever sees signatures, this is also how you index a non-vector metric: supply an inner index that speaks your distance.

Coverage-driven sampling. Instead of sampling S uniformly, retire the most-loaded sample points and promote members of the most idle posting lists. Two iterations measurably improve the recall/cost frontier at every operating point tested. Recipe in experiments/run_coverage.py; pass the result as fit(X, sample_idx=...).

Merge strategies. The merge has three exact implementations that return identical results: a dense scoreboard (default), a radix-partitioned merge (automatic above ~5·10⁷ objects in batch_query), and a stratified quotiented branch-and-bound variant reachable through the C++ object (idx._inv.build_strata(bits), then batch_merge_strat). The third is experimental — exact and about 19% faster at small C, but with no automatic policy and no Python convenience wrapper yet.


Where it stands

Honest scope, because the numbers below are the ones people will quote.

Measured. Recall/throughput curves on SIFT1M, GloVe-200 and nested Deep-1M/10M/100M; build times against graph baselines on the same machines; the 3 GiB-capped build above; bit-identical build parity across modes and thread counts; the GPU pipeline against its own CPU.

Here is a full curve, from experiments/results/qps-sift-a0.02-kb64.json — SIFT1M, α=2%, k_b=64, plain count scoring, 10,000 queries, one M-series laptop, index built in 12.1 s:

k_s C recall@10 qps
32 1,000 0.9367 5,636
64 2,000 0.9787 3,197
64 5,000 0.9939 2,461
64 10,000 0.9978 1,806
64 20,000 0.9991 1,155

Read the shape of that table, not the absolute throughput: repeat runs of the identical configuration on that fanless laptop have differed by up to 25% from thermal drift alone. Every raw manifest is in experiments/results/, with its seeds and parameters.

The honest comparison. On the same dataset and machine, a well-tuned navigable graph (GRAFT, experiments/results/graftfull-sift.json) reaches 0.9916 at ~42,000 qps — about 17× MISIFU's throughput at matched recall, from an index that took roughly 9× longer to build (111.1 s vs 12.1 s). If your database fits in RAM and you want maximum queries per second, use a graph index. MISIFU's argument is what it costs to keep resident, what it costs to build, that it takes any metric, and that updates do not perturb a graph.

Not yet measured — do not assume these. End-to-end serving throughput and latency under an enforced memory cap with postings on NVMe (the build is capped and measured; the serving path is not); insert and delete throughput; recall after sustained updates; any non-vector metric at scale; comparison against disk-resident and partitioned baselines. These are in progress and the paper will report them with confidence intervals or not at all.


Reproducing the experiments

Each script writes a JSON manifest into experiments/results/ recording its seed, parameters and outputs.

# recall/cost grid on an ann-benchmarks HDF5 dataset
python experiments/run_annb.py --data sift-128-euclidean.hdf5 \
       --alpha 0.02 --k-b 64 --k-s 64 128 --C 1000 5000 10000

# throughput at matched recall
python experiments/run_qps.py --data glove-200-angular.hdf5 --normalize \
       --alpha 0.02 --k-b 64 --points 128:5000:idf

# scale runs on raw .npy, with optional coverage re-sampling
python experiments/run_deep.py --x deep-10M.X.npy --q deep-10M.Q.npy \
       --gold deep-10M.gold.npy --alpha 0.02 --k-b 64 --coverage 2 \
       --points 64:5000:idf 128:20000:idf        # k_s:C:scoring

# coverage-driven sampling, 2 iterations
python experiments/run_coverage.py --data sift-128-euclidean.hdf5 \
       --direction spread --iters 2

License

MIT — see LICENSE.

Citing

@misc{chavez2026misi,
  title         = {misi: a Metric Inverted Sample Index},
  author        = {Ch\'avez, Edgar},
  year          = {2026},
  eprint        = {2608.27422},
  archivePrefix = {arXiv},
  primaryClass  = {cs.IR},
  url           = {https://arxiv.org/abs/2608.27422}
}

About

A Metric Inverted Sample Index

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages