Skip to content

Compute the query magnitude once in similar_by_vector - #1905

Open
sebastianbreguel wants to merge 1 commit into
simonw:mainfrom
sebastianbreguel:perf/similar-query-magnitude
Open

sebastianbreguel wants to merge 1 commit into
simonw:mainfrom
sebastianbreguel:perf/similar-query-magnitude

Conversation

@sebastianbreguel

Copy link
Copy Markdown
Contributor

llm similar scores every stored embedding with llm.cosine_similarity(other_vector, vector), which recomputes the query vector's magnitude for each row. With 1536-dimension vectors that is about a quarter of the work. This computes the query magnitude once and keeps the rest of the arithmetic the same, so llm similar gets about 24% faster and returns the same scores, bit for bit.

Numbers

Time spent in Collection.similar_by_id(..., number=10), median of 10 interleaved runs, 1536-dimension vectors:

Rows macOS main macOS branch Linux main Linux branch
2,500 240 ms 182 ms 289 ms 221 ms
5,000 481 ms 362 ms 577 ms 447 ms
10,000 951 ms 725 ms 1,260 ms 902 ms
20,000 1,940 ms 1,460 ms 2,450 ms 1,810 ms

Whole-process wall time drops by 14% to 23%. Peak RSS does not change.

macOS arm64 native, Python 3.14. Linux arm64 in Docker on the same Mac (4 CPUs, 2 GiB, Python 3.13).

Same behavior

  • The new expression is dot_product / (other_magnitude * query_magnitude), the same operations in the same order as cosine_similarity(a=other_vector, b=vector), so every score is identical, not just close.
  • I compared the full ranking (every id and score, number above the row count) on main and on the branch for all four databases: identical.
  • pytest: 1599 passed. ruff, black --check and mypy are clean.

One difference: similar_by_vector no longer goes through llm.cosine_similarity, so monkeypatching that function no longer changes llm similar. I did not find anything in the repo that relies on it.

To revert, put back the return llm.cosine_similarity(other_vector, vector) line and drop query_magnitude.

Benchmark script
# usage: python bench_similar.py <src_dir> <embeddings.db> [number]
import hashlib, os, sys, time

src, db_path = sys.argv[1], sys.argv[2]
number = int(sys.argv[3]) if len(sys.argv) > 3 else 10
sys.meta_path[:] = [f for f in sys.meta_path if "editable" not in repr(f).lower()]
sys.path.insert(0, src)
import llm, sqlite_utils

collection = llm.Collection("docs", sqlite_utils.Database(db_path), create=False)
start = time.perf_counter()
entries = collection.similar_by_id("7", number=number)
print("BENCH inner_s=%.6f" % (time.perf_counter() - start))
print("DIGEST " + hashlib.md5(repr([(e.id, e.score) for e in entries]).encode()).hexdigest())

The databases hold N random Gaussian vectors (seed 0) encoded with llm.encode, in a collection created through embeddings_migrations.

The cosine similarity recomputed the query vector's magnitude for every
stored embedding. Compute it once per call; scores and ranking are unchanged.
@sebastianbreguel

sebastianbreguel commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

@simonw could you review this one and #1904 when you have time?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant