Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 20 min · revision 2

Brute-Force kNN as a Baseline

Write exact k-nearest-neighbour search in NumPy with argpartition and batched matrix products, check that it is right, time it, and save its results as the ground truth for approximate indexes.

Contentsand lesson path

What you will learn

  • Implement exact k-nearest-neighbor search and use it as the baseline for an approximate index.

Prerequisites: Embeddings

01. The problem

You have 10,000 document embeddings and 200 queries, and you need the exact 10 nearest documents for every query. The result has two uses: it is a working search for a small collection, and it is the ground truth that lessons 3 and 4 compare approximate indexes against. A baseline with a bug in it would make every later measurement wrong, so it has to be simple enough to trust and fast enough to run often.

You will build it in six steps: make the data, score one query the obvious way, replace the full sort with a partial one, score many queries in one matrix product, time the variants, and finally check and save the result.

Setup: Python 3.12 or later and NumPy 2 (tested with NumPy 2.5) in a virtual environment: python -m pip install numpy. You will save two small modules, vectors.py (step 1) and knn.py (step 4), in one folder. Run the other snippets in order in a single interactive session started from that folder (python, IPython or a notebook), because later steps reuse earlier variables.

02. Step 1: make a corpus of unit vectors

Real embeddings would work here, and the practice project uses yours. For a lesson that runs anywhere in a second, make_dataset() generates stand-ins with a similar shape: 384 numbers per vector, unit length, built as random mixtures of 32 hidden "themes" plus noise, so that some vectors are much closer to each other than others. The queries come from the same process but are not in the corpus, just as real user questions are not copies of stored chunks.

Python · vectors.py
"""Synthetic stand-ins for text embeddings."""

import numpy as np


def make_dataset(
    n_docs: int, n_queries: int, dim: int = 384, n_themes: int = 32, seed: int = 0
) -> tuple[np.ndarray, np.ndarray]:
    """Unit-length float32 vectors: random mixes of hidden themes, plus noise."""
    rng = np.random.default_rng(seed)
    themes = rng.standard_normal((n_themes, dim))
    mix = rng.standard_normal((n_docs + n_queries, n_themes)) / np.sqrt(n_themes)
    vectors = mix @ themes + 0.5 * rng.standard_normal((n_docs + n_queries, dim))
    vectors = vectors.astype(np.float32)
    vectors /= np.linalg.norm(vectors, axis=1, keepdims=True)
    return vectors[:n_docs], vectors[n_docs:]
Python · interactive session
import numpy as np
from vectors import make_dataset

docs, queries = make_dataset(n_docs=10_000, n_queries=200)
print(docs.shape, docs.dtype, queries.shape)
norms = np.linalg.norm(docs, axis=1)
print(f"norms: min {norms.min():.4f}, max {norms.max():.4f}")
print(f"MiB of document vectors: {docs.nbytes / 2**20:.1f}")
Expected output
(10000, 384) float32 (200, 384)
norms: min 1.0000, max 1.0000
MiB of document vectors: 14.6

Two details matter later. The vectors are float32, the type embedding APIs and vector indexes use; float64 would double the memory and make comparisons with an index slightly inconsistent. And every norm is 1, so a dot product is a cosine similarity, as lesson 1 showed. The memory figure matches the estimate rule: 10,000 × 384 × 4 bytes.

03. Step 2: score one query and sort

Python · interactive session
query = queries[0]
sims = docs @ query                  # cosine similarity, as all vectors are unit length
print(sims.shape)

top_sorted = np.argsort(-sims)[:5]   # sort all 10,000 scores, keep the best 5
for doc_id in top_sorted:
    print(doc_id, round(float(sims[doc_id]), 4))
Expected output
(10000,)
1984 0.5479
499 0.4657
2379 0.4562
2136 0.4485
9411 0.4424

docs @ query multiplies the (10,000 × 384) matrix by the 384-number query and gives one score per document, at index positions that double as document ids. np.argsort returns the positions that would sort the array in ascending order, so sorting the negated scores puts the highest similarity first.

This is already correct exact search. Its weakness is the sort: it orders all 10,000 scores, O(N log N) work, to keep five of them.

04. Step 3: select the top k without a full sort

np.argpartition(a, kth) does a cheaper job in linear time: it rearranges the positions so that the element at index kth is the one a full sort would put there, everything before it is no larger, and everything after it is no smaller. Inside each side the order is undefined. With kth = k - 1 on the negated scores, the first k positions are exactly the k best documents, in no particular order, and sorting just those k is trivial.

Python · interactive session
def top_k(sims: np.ndarray, k: int) -> np.ndarray:
    """Indices of the k largest scores, best first, without a full sort."""
    candidates = np.argpartition(-sims, k - 1)[:k]     # the best k, in no order
    return candidates[np.argsort(-sims[candidates])]   # sort just those k


print(np.argpartition(-sims, 4)[:5])   # the right five ids, unordered
print(top_k(sims, 5))
print(np.array_equal(top_k(sims, 5), top_sorted))
Expected output (the order on the first line can differ between NumPy versions)
[1984 2379 2136  499 9411]
[1984  499 2379 2136 9411]
True

The first line shows why the second sort is needed: argpartition found the right five documents but 2379 sits ahead of 499. The total cost per query is now O(N × d) for the scores, O(N) for the partition and O(k log k) for the final sort. The scoring dominates, which is why the next step attacks it.

05. Step 4: many queries as one matrix product

Scoring queries one at a time reads the whole document matrix from memory for every query. Stacking queries into a matrix and computing queries @ docs.T gives every score at once, and the linear algebra library underneath NumPy (a BLAS) reuses each block of documents for many queries while it is in the CPU cache. The score matrix has one row per query and one column per document, so its size is the thing to watch: 200 × 10,000 float32 scores is 8 MB, but a million documents would make it 800 MB. Processing the queries in fixed-size batches keeps that bounded.

Save the function in a second file, knn.py, since the lab in lesson 4 imports it.

Python · knn.py
"""Exact k-nearest-neighbour search: the baseline for approximate indexes."""

import numpy as np


def exact_knn(
    docs: np.ndarray, queries: np.ndarray, k: int, batch_size: int = 256
) -> tuple[np.ndarray, np.ndarray]:
    """Exact top-k by dot product. Returns (ids, scores), each (n_queries, k)."""
    ids = np.empty((len(queries), k), dtype=np.int64)
    scores = np.empty((len(queries), k), dtype=np.float32)
    for start in range(0, len(queries), batch_size):
        stop = start + batch_size
        sims = queries[start:stop] @ docs.T                    # (batch, n_docs)
        best = np.argpartition(-sims, k - 1, axis=1)[:, :k]    # unordered top k
        best_sims = np.take_along_axis(sims, best, axis=1)
        order = np.argsort(-best_sims, axis=1)                 # sort k per row
        ids[start:stop] = np.take_along_axis(best, order, axis=1)
        scores[start:stop] = np.take_along_axis(best_sims, order, axis=1)
    return ids, scores
Python · interactive session
from knn import exact_knn

gt_ids, gt_scores = exact_knn(docs, queries, k=10)
print(gt_ids.shape, gt_scores.shape)
print(gt_ids[0, :5])
print(np.round(gt_scores[0, :5], 4))
print(np.array_equal(gt_ids[0, :5], top_sorted))
Expected output
(200, 10) (200, 10)
[1984  499 2379 2136 9411]
[0.5479 0.4657 0.4562 0.4485 0.4424]
True

The function does per row what step 3 did for one query. With axis=1, argpartition works on each row separately, and np.take_along_axis picks, row by row, the scores or ids at the positions it found; plain fancy indexing such as sims[best] would mix rows up. The final line confirms that the batched version agrees with the one-query version from step 2.

06. Step 5: time the variants

Python · interactive session
import time


def ms(fn, repeat: int = 5) -> float:
    """Best of several runs, in milliseconds: the least disturbed by other work."""
    best = float("inf")
    for _ in range(repeat):
        start = time.perf_counter()
        fn()
        best = min(best, time.perf_counter() - start)
    return best * 1000


print(f"argsort, one query:      {ms(lambda: np.argsort(-sims)[:10]):.3f} ms")
print(f"argpartition, one query: {ms(lambda: top_k(sims, 10)):.3f} ms")
loop = ms(lambda: [top_k(docs @ q, 10) for q in queries], repeat=3)
batch = ms(lambda: exact_knn(docs, queries, k=10), repeat=3)
print(f"200 queries, one by one: {loop:.1f} ms ({loop / 200:.3f} ms per query)")
print(f"200 queries, batched:    {batch:.1f} ms ({batch / 200:.3f} ms per query)")
Illustrative output from one run on a desktop CPU (your timings will differ)
argsort, one query:      0.670 ms
argpartition, one query: 0.111 ms
200 queries, one by one: 792.5 ms (3.963 ms per query)
200 queries, batched:    44.7 ms (0.223 ms per query)

Absolute timings depend on the CPU, the number of cores, the BLAS library NumPy was built with and whatever else the machine is doing; repeat the script and the one-by-one figure alone can change severalfold. The ratios are what to read. Partial selection beats a full sort several times over, and batching is roughly an order of magnitude cheaper per query than a loop. Taking the best of several runs filters out pauses caused by other programs, which is why the helper reports the minimum rather than the mean.

Note the scale, too: at 10,000 vectors exact search costs well under a millisecond per query when batched. Lesson 4 shows what an approximate index buys at this size, and it is less than you might expect.

07. Step 6: check the baseline and save it

Python · interactive session
# 1. Scores must come out in descending order for every query.
assert np.all(np.diff(gt_scores, axis=1) <= 0)

# 2. A stored document used as a query must find itself first, with score 1.0.
self_ids, self_scores = exact_knn(docs, docs[[7, 42, 9_999]], k=3)
print(self_ids[:, 0], np.round(self_scores[:, 0], 4))

# 3. Save the baseline next to the data it was computed from.
np.save("docs.npy", docs)
np.save("queries.npy", queries)
np.save("gt_ids.npy", gt_ids)
print("saved", gt_ids.shape, "ground-truth ids")
Expected output
[   7   42 9999] [1. 1. 1.]
saved (200, 10) ground-truth ids

The checks are cheap and catch the usual baseline bugs. Ascending instead of descending order fails the first. Mixed-up rows, a missing normalisation or an off-by-one in the partition fail the second, because a unit vector scores 1.0 against itself (up to float32 rounding) and no other unit vector can score higher.

Saving the vectors together with the ground truth matters more than it looks. The ids in gt_ids.npy are row positions in docs.npy; if you re-embed, reorder or add documents, the saved neighbours no longer mean anything and you must recompute them. In a real project, store the embedding model name and a hash of the input next to the files so a stale baseline is easy to spot.

08. Common mistakes

09. Check your understanding

Practice check · 3 questions

Reading the baseline code

Answer from the code you ran in this lesson.

Q1. After idx = np.argpartition(-sims, 9)[:10], what does idx hold?
Q2. Why does exact_knn() process the queries in batches of 256 instead of all at once?
Q3. A teammate builds the query set by sampling 200 rows from docs.npy itself. What happens to the exact top-10 results?
Practice only: not graded, not saved, not evidence.

10. Apply it

Run the baseline on the practice project data you prepared in lesson 1:

  1. Load your 10,000 embeddings and your held-out query embeddings, and assert that both are float32 and unit length.
  2. Compute the exact top 10 for every query with exact_knn(), run the two checks from step 6 (use a few stored vectors for the self-match check), and save the ids together with the name of the embedding model.
  3. Time the batched search with the ms() helper and note the cost per query. Multiply by 100 to get a rough figure for a million documents of the same size, and compare it with your latency budget. That comparison decides whether you need the approximate index from the rest of this skill at all.

11. Review prompt

Without looking back:

  1. Write the three lines at the heart of exact_knn(): the scores, the partition and the final sort. Which one dominates the cost?
  2. Why is queries @ docs.T cheaper per query than a Python loop over docs @ q?
  3. Which two checks would catch a broken baseline, and what does each one catch?
  4. Name three changes after which a saved ground truth is no longer valid.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check