Skip to content
mlmentorship

Implement memory-bounded batched top-k retrieval

Retrieve top-k cosine neighbors for many queries without materializing the full query-by-item score matrix.

Published · 7 min read ·Core ·Mixed

ML implementation · active recall

Practice before you read

40 minutes. Clarify the contract, implement a correct baseline, test edge cases, then optimize.

ML implementation · closed-book attempt

Implement memory-bounded batched top-k retrieval

Clarify the contract, implement a correct baseline, test edge cases, then optimize.

Problem

Context. Floating matrices Q and X have shapes (num_queries, dim) and (num_items, dim) with matching feature dimensions. The full score matrix exceeds available memory. Task. Return item indices and cosine scores shaped (num_queries, k), sorted by nonincreasing score for each query. For query [1, 0], items [[1, 0], [0, 1], [-1, 0]], and k = 2, return indices [0, 1], scores [1, 0]. Constraints. Use 1 <= k <= num_items, a positive block size, and finite representable arithmetic. For exact cosine under the reference's norm floor, nonzero norms must be at least 1e-12; zero vectors score zero. Preserve inputs and avoid the full score matrix. Tied membership and ordering may be arbitrary unless a stricter policy is added.

40:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Trace why keeping only each block's local top-k and merging it with the running top-k preserves the exact global top-k without storing the full query-by-item score matrix.

Learning objective

Score bounded item blocks and merge per-query top-k with global item identities

Score bounded item blocks and merge per-query top-k with global item identitiesNormalize rows, score one item block, and merge local candidates with per-query running top-k. Carry global item identities with scores. Discarded fixed-score items cannot overtake enough retained candidates. Process the final partial block at its actual size. Zero vectors score zero; ties need a policy for reproducibility. Blocking saves score memory, not exhaustive scoring work.Per-query score blocks feed a boundedrunning frontierToy queries: x-axis, y-axis, zero.Items zero/one/two: x-axis, y-axis,negative x-axis. Keep two; block sizetwo.First score block: items zero and oneQuery 0: block scores 1, 00Score 11Score 0Query 1: block scores 0, 11Score 10Score 0Query 2: block scores 0, 00Score 01Score 0Final partial block: item two onlyQuery 0: block scores -10Score 11Score 0Query 1: block scores 01Score 10Score 0Query 2: block scores 00Score 01Score 0Circles retain global item IDs, notblock-local offsets. Scores remainsorted per query.Invariant: retain the best two amongevery item seen. A discardedfixed-score item has two candidatesahead under the declared tie order.Later items cannot move it ahead ofthem.Query zero finishes with items zeroand one, scores one and zero. Itemtwo scores minus one and cannotenter.Zero query scores all items zero.This display breaks ties by item ID;the reference permits any tiedmembership unless a stricter policyis added.Toy score blocks hold six then threescalars, never the full nine-scorematrix. Retained state holds sixID/score pairs. Normalized inputs useadditional storage.Score-block storage scales with querycount and block size; running resultsscale with query count and k. Everyitem is still scored: blocking doesnot remove exhaustive scoring work.
Read it this way: Normalize rows, score one item block, and merge local candidates with per-query running top-k. Carry global item identities with scores. Discarded fixed-score items cannot overtake enough retained candidates. Process the final partial block at its actual size. Zero vectors score zero; ties need a policy for reproducibility. Blocking saves score memory, not exhaustive scoring work. Can an earlier discarded fixed score overtake the retained frontier later?
Full interview answer 7 min read

Implement exact top-k cosine retrieval for query matrix Q and item matrix X. The full Q @ X.T matrix does not fit in memory.

Retrieve the highest-scoring item indices for many queries without storing the full query-by-item similarity matrix.

Problem

Context. Floating matrices Q and X have shapes (num_queries, dim) and (num_items, dim) with matching feature dimensions. The full score matrix exceeds available memory.

Task. Return item indices and cosine scores shaped (num_queries, k), sorted by nonincreasing score for each query. For query [1, 0], items [[1, 0], [0, 1], [-1, 0]], and k = 2, return indices [0, 1], scores [1, 0].

Constraints. Use 1 <= k <= num_items, a positive block size, and finite representable arithmetic. For exact cosine under the reference’s norm floor, nonzero norms must be at least 1e-12; zero vectors score zero. Preserve inputs and avoid the full score matrix. Tied membership and ordering may be arbitrary unless a stricter policy is added.

Contract

Q: float array [num_queries, dim]
X: float array [num_items, dim]
k: 1 <= k <= num_items
block_size: number of items scored at once
return: item indices and cosine scores [num_queries, k], sorted descending

Handle zero vectors explicitly. State whether they produce score zero or an error.

Baseline reasoning

Normalize rows once, then process item blocks:

  1. Score Q_normalized @ X_block_normalized.T.
  2. Take each query’s top-k within the block.
  3. Merge those candidates with the running top-k.
  4. Repeat until all items are consumed.

The running state is only O(num_queries × k), and each score block is O(num_queries × block_size).

Reference drawing

Learning objective

Score bounded item blocks and merge per-query top-k with global item identities

Score bounded item blocks and merge per-query top-k with global item identitiesNormalize rows, score one item block, and merge local candidates with per-query running top-k. Carry global item identities with scores. Discarded fixed-score items cannot overtake enough retained candidates. Process the final partial block at its actual size. Zero vectors score zero; ties need a policy for reproducibility. Blocking saves score memory, not exhaustive scoring work.Per-query score blocks feed a boundedrunning frontierToy queries: x-axis, y-axis, zero.Items zero/one/two: x-axis, y-axis,negative x-axis. Keep two; block sizetwo.First score block: items zero and oneQuery 0: block scores 1, 00Score 11Score 0Query 1: block scores 0, 11Score 10Score 0Query 2: block scores 0, 00Score 01Score 0Final partial block: item two onlyQuery 0: block scores -10Score 11Score 0Query 1: block scores 01Score 10Score 0Query 2: block scores 00Score 01Score 0Circles retain global item IDs, notblock-local offsets. Scores remainsorted per query.Invariant: retain the best two amongevery item seen. A discardedfixed-score item has two candidatesahead under the declared tie order.Later items cannot move it ahead ofthem.Query zero finishes with items zeroand one, scores one and zero. Itemtwo scores minus one and cannotenter.Zero query scores all items zero.This display breaks ties by item ID;the reference permits any tiedmembership unless a stricter policyis added.Toy score blocks hold six then threescalars, never the full nine-scorematrix. Retained state holds sixID/score pairs. Normalized inputs useadditional storage.Score-block storage scales with querycount and block size; running resultsscale with query count and k. Everyitem is still scored: blocking doesnot remove exhaustive scoring work.
Derivation
PassScore this blockLocal top-2Running top-2
X[0:3]0:.82 · 1:.31 · 2:.760:.82 · 2:.760:.82 · 2:.76keep 2 of 3
X[3:6]3:.91 · 4:.44 · 5:.683:.91 · 5:.683:.91 · 0:.82merge 2 + 2 → keep 2
X[6:8]6:.79 · 7:.957:.95 · 6:.797:.95 · 3:.91final exact top-2
move left to right within each row, then down. An item discarded from a block already has at least k items in that same block ranked ahead of it, so it cannot enter the global top-k. Only the previous 2 winners and the new 2 local winners reach the next merge; the full score row never exists. Original example based on the exact-selection semantics in NumPy's argpartition documentation.
Check: Which two items prove that candidate 5 cannot enter the global top two?
Read it this way: Normalize rows, score one item block, and merge local candidates with per-query running top-k. Carry global item identities with scores. Discarded fixed-score items cannot overtake enough retained candidates. Process the final partial block at its actual size. Zero vectors score zero; ties need a policy for reproducibility. Blocking saves score memory, not exhaustive scoring work. Can an earlier discarded fixed score overtake the retained frontier later?

Reference implementation sketch

import numpy as np


def row_normalize(a, eps=1e-12):
    norms = np.linalg.norm(a, axis=1, keepdims=True)
    return a / np.maximum(norms, eps)


def exact_topk_cosine(q, x, k, block_size=4096):
    if q.ndim != 2 or x.ndim != 2 or q.shape[1] != x.shape[1]:
        raise ValueError("incompatible shapes")
    if not 1 <= k <= x.shape[0]:
        raise ValueError("invalid k")

    qn = row_normalize(q)
    best_scores = np.full((q.shape[0], k), -np.inf)
    best_indices = np.full((q.shape[0], k), -1, dtype=np.int64)

    for start in range(0, x.shape[0], block_size):
        stop = min(start + block_size, x.shape[0])
        scores = qn @ row_normalize(x[start:stop]).T
        local_k = min(k, stop - start)
        local = np.argpartition(scores, -local_k, axis=1)[:, -local_k:]
        local_scores = np.take_along_axis(scores, local, axis=1)
        local_indices = local + start

        merged_scores = np.concatenate([best_scores, local_scores], axis=1)
        merged_indices = np.concatenate([best_indices, local_indices], axis=1)
        keep = np.argpartition(merged_scores, -k, axis=1)[:, -k:]
        best_scores = np.take_along_axis(merged_scores, keep, axis=1)
        best_indices = np.take_along_axis(merged_indices, keep, axis=1)

    order = np.argsort(-best_scores, axis=1)
    return (
        np.take_along_axis(best_indices, order, axis=1),
        np.take_along_axis(best_scores, order, axis=1),
    )

Complexity

  • Time: for exact scoring, plus top-k selection
  • Peak score memory: for block size
  • Persistent result memory:

Blocking fixes memory, not exact-computation cost. For very large catalogs, discuss ANN indexing after producing a correct baseline.

L4, L5, and L6 signals

  • L4: correct simple implementation with shapes, tests, and complexity.
  • L5: block processing, vectorization, edge cases, and benchmark plan.
  • L6: distinguishes exact from ANN, reasons about host/device transfer, mixed precision, batching, index freshness, and quality/latency/cost trade-offs.

Tests to write

  • Compare against a full score matrix on a small random case.
  • k = 1, k = num_items, and final partial block.
  • Duplicate scores and deterministic ordering policy.
  • Zero query and item vectors.
  • One query, one item, and invalid shapes.

Common mistakes

  • Materializing the full score matrix despite the constraint.
  • Normalizing inside the query loop.
  • Using full sort instead of top-k selection.
  • Returning unsorted final candidates.
  • Claiming blocking changes asymptotic compute.

Related: approximate nearest neighbors, embedding similarity, and two-tower retrieval.