diff --git a/CHANGELOG.md b/CHANGELOG.md index b268fb6..30437bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ internal versions are summarized under 0.3.33. - A successful `--consume-only` run removes the producers' `producer_N.done` markers, and `vector_build_multi.sbatch` and each producer remove old ones when they start, so the next multi-node job waits for its producers and `--rebuild` is no longer blocked. (#5) - The batch scripts and the cluster guide remove the writer guard litkit creates, `workspace/sqlite/faiss_writer.guard`, instead of `workspace/.writer_guard`. (#15) - Builds commit articles in batches instead of one at a time. A producer commits a tar's articles only at the tar boundary, just before it finalizes the tar's segments, so after a failed flush or a job killed mid-tar, a restart without `--rebuild` processes them again instead of skipping them with no vectors. A writer commits at each flush, once the batch is embedded, at each checkpoint and at each tar boundary, so a failed embedding rolls back only the articles since the last of those; earlier rows of the batch still wait for the backfill. Without `--strict-ingest`, an error after which SQLite has rolled back the batch, such as a full disk, now stops the build instead of skipping the article. (#13) +- Removing vectors from a FAISS index before re-adding them (`--update`, backfill, segment ingestion) takes time proportional to the index size instead of index size times IDs removed. Removing 20,000 IDs from 1M vectors took 10.3 s and now takes 0.03 s. (#14) ## [0.3.36] - 2026-11-30 diff --git a/src/litkit/index/ids.py b/src/litkit/index/ids.py index 7d7d0c9..d12d8b3 100644 --- a/src/litkit/index/ids.py +++ b/src/litkit/index/ids.py @@ -23,29 +23,21 @@ def _eprint(msg: str = "", *, end: str = "\n") -> None: def make_id_selector(ids_like: list[int] | np.ndarray) -> Any: """Create a FAISS IDSelector for the given IDs. - - Compatible with both newer (IDSelectorArray) and older (IDSelectorBatch) - FAISS versions. Falls back to returning the raw int64 array if no - selector class is available. - + + Uses IDSelectorBatch, a hash set behind a Bloom filter, as FAISS's own + remove_ids(ndarray) does. IDSelectorArray tests membership by scanning the + whole ID array, and remove_ids() runs that test once per stored vector, so + removing k IDs from N vectors cost O(N * k) (#14). The exception: an IVF + index with a hashtable direct map accepts only IDSelectorArray, and FAISS's + remove_ids(ndarray) switches to it there. litkit never sets one. + Args: ids_like: List or array of integer IDs - + Returns: - FAISS IDSelector object, or numpy int64 array as fallback + FAISS IDSelectorBatch over a copy of the IDs """ - ids_arr = np.asarray(ids_like, dtype="int64") - - # Try newer name first, then older name - Sel = getattr(faiss, "IDSelectorArray", None) - if Sel is None: - Sel = getattr(faiss, "IDSelectorBatch", None) - - if Sel is not None: - return Sel(ids_arr) - - # Fallback: return raw array (caller must handle differently) - return ids_arr + return faiss.IDSelectorBatch(np.asarray(ids_like, dtype="int64")) def safe_remove_ids(index: faiss.Index, sel: Any) -> int: diff --git a/tests/test_index.py b/tests/test_index.py index 89c1b5f..3fd36bf 100644 --- a/tests/test_index.py +++ b/tests/test_index.py @@ -3,6 +3,7 @@ import json import os +import time from functools import partial import faiss @@ -116,6 +117,51 @@ def test_safe_remove_ids(unit_vectors, capsys): assert capsys.readouterr().err == "" # and silent +@pytest.mark.parametrize("kind", ["flat", "ivfpq"]) +@pytest.mark.parametrize( + "remove", + [ + [], + [7, 7, 7], # repeated + [3, 10**6], # one not in the index + [2**40 + 5, 2**33], # above 32 bits + list(range(0, 400, 3)), + ], +) +def test_make_id_selector_removes_exactly_the_given_ids(unit_vectors, make_index, kind, remove): + """Control for #14: the selector changed from IDSelectorArray to IDSelectorBatch, + a Bloom filter in front of a hash set; it must still remove exactly these IDs.""" + ids = np.concatenate([np.arange(398), [2**40 + 5, 2**33]]).astype("int64") + index = make_index(kind, unit_vectors(len(ids), DIM), ids) + expected = set(ids.tolist()) - set(remove) + assert safe_remove_ids(index, make_id_selector(remove)) == len(ids) - len(expected) + assert faiss_present_ids(index) == expected + + +def test_removing_many_ids_costs_about_as_much_as_removing_few(rng): + """#14: remove_ids() tests every stored ID against the selector. IDSelectorArray + scans its whole ID list for each test, so removing k IDs from N vectors cost + O(N * k): about 300 times as long for 20,000 IDs as for 20 here.""" + n = 100_000 + X = rng.random((n, DIM), dtype=np.float32) + + def seconds(k): + best = float("inf") + for _ in range(3): + index = faiss.IndexIDMap2(flat_ip_index(DIM)) + index.add_with_ids(X, np.arange(n, dtype="int64")) + sel = make_id_selector(rng.choice(n, size=k, replace=False)) + t0 = time.perf_counter() + removed = safe_remove_ids(index, sel) + best = min(best, time.perf_counter() - t0) + if removed != k: + raise RuntimeError(f"removed {removed} of {k}") + return best + + few, many = seconds(20), seconds(20_000) + assert many < 10 * few + 0.01, (few, many) + + # ------------------------------------------------------------- approximate