Sub topic 14
Scaling to large catalogs
This chapter assumes you know the neighborhood methods and matrix factorization from earlier chapters, and that you are comfortable with NumPy arrays and cosine similarity.
Why brute force stops working
A neighborhood method compares one entity to every other. With n items, the full item-item similarity matrix has n² entries. At 100,000 items that is 10 billion values, which is too large to store densely and too slow to recompute often. Scoring one user against every item is also linear in catalog size. At low latency targets, that cost is too high.
Matrix factorization helps with storage, because you keep k numbers per user and item instead of a similarity matrix. Serving still needs the top-N items for a user, which means finding the item vectors with the highest dot product with the user vector. Done exactly, that is one pass over the catalog per request.
Three standard reductions
- Prune the neighbor lists. Keep only the top
mmost similar items per item, for examplem = 50. Storage drops fromn²ton·m. Prediction uses only the stored neighbors. - Precompute offline. Similarities and factors change slowly. Compute them in a batch job, store the results, and serve lookups online.
- Approximate nearest neighbor (ANN) search. Return neighbors that are probably the closest, in sublinear time. You trade a small loss in recall for a large speedup.
How ANN indexes work
Most ANN methods avoid scanning everything by narrowing the search to a candidate set.
- Locality-sensitive hashing (LSH): similar vectors tend to land in the same hash bucket.
- Inverted file (IVF): cluster the vectors, then search only the clusters nearest to the query.
- Graph indexes such as HNSW: walk a graph of near neighbors toward the query.
The sketch below uses random-hyperplane LSH for cosine similarity. It compares the approximate result to exact search.
import numpy as np
rng = np.random.default_rng(0)
n_items, dim, n_bits, n_tables, top = 5000, 16, 8, 6, 10
Q = rng.normal(size=(n_items, dim))
Q /= np.linalg.norm(Q, axis=1, keepdims=True)
query = rng.normal(size=dim)
query /= np.linalg.norm(query)
weights = 1 << np.arange(n_bits)
def codes_for(X, planes):
return ((X @ planes) > 0).astype(int) @ weights
tables = []
for _ in range(n_tables):
planes = rng.normal(size=(dim, n_bits))
tables.append((planes, codes_for(Q, planes)))
# Exact search: scans every item.
exact = np.argsort(Q @ query)[::-1][:top]
# Approximate search: union of matching buckets, then exact re-rank.
candidates = set()
for planes, codes in tables:
q_code = codes_for(query[None, :], planes)[0]
candidates.update(np.where(codes == q_code)[0].tolist())
cand = np.array(sorted(candidates))
approx = cand[np.argsort(Q[cand] @ query)[::-1][:top]]
recall = len(set(exact) & set(approx)) / top
print(f"scanned {len(cand)} of {n_items} items, recall@{top} = {recall:.2f}")Adding tables raises recall and scans more items. Adding bits per table does the opposite. Every ANN library exposes similar knobs.
Common errors
- Dot product versus cosine. Factorization models rank by dot product, which depends on vector length. Many ANN indexes assume cosine or Euclidean distance. Either normalize the vectors, or use an index that supports maximum inner product search.
- Not measuring recall. Always compare ANN output to exact search on a sample of queries. Report recall of the ANN result separately from the recommendation metrics.
- Stale indexes. New items are missing until the index is rebuilt or updated. This also worsens cold start.
- Pruning too hard. Very small neighbor lists leave users with few rated neighbors, so many predictions fall back to the global mean.
Exercise
An item-item similarity matrix for 200,000 items is stored densely as 32-bit floats. Roughly how much memory does it need, and how much does keeping the top 50 neighbors per item need if each neighbor stores a 4-byte id and a 4-byte similarity?
Show answer
Dense: 200,000² × 4 bytes = 160 billion bytes, about 160 GB. Pruned: 200,000 × 50 × 8 bytes = 80 million bytes, about 80 MB. Pruning cuts storage by a factor of 2,000.