Mid-level interview questionAsked at Harvey · interview write-up
In a notebook, implement embedding retrieval with cosine similarity. How does cosine relate to the dot product, and when would you choose each?
Model answer
import numpy as np
def top_k_cosine(q, docs, k=5, eps=1e-12):
n = np.linalg.norm(docs, axis=1, keepdims=True)
d = docs / np.maximum(n, eps)
qn = q / max(np.linalg.norm(q), eps)
scores = d @ qn
idx = np.argsort(-scores)[:k]
return idx, scores[idx]
Cosine is the dot product of unit-length vectors, so normalise once at indexing and any dot-product index ranks by cosine. Raw dot product also rewards vector length. Follow how the embedding model was trained: cosine for most sentence-embedding models, dot product when the model puts meaningful signal, such as popularity, in the norm. Guard against zero vectors.
Practise the rest
17 Embeddings questions, 492 in all, each with a model answer. Free.
More from Harvey interview questions.
More Embeddings interview questions
- What is an embedding table, and what does it mean for two embeddings to be similar?
- People say 'embedding' for three different things. What are they, and why does the difference matter?
- Your vector database only supports dot-product search, but your embedding model's documentation says to compare vectors with cosine similarity. What do you do, and why does it work?
- You're building search over medicine leaflets with a small English embedding model, and you plan to reply 'no answer found' whenever the top cosine score is below 0.5. What risks do you raise before this ships?
- Your team switches to a newer embedding model with the same 384 dimensions and starts embedding incoming queries with it. Search quality collapses, but nothing errors. Explain what happened and how you'd run the migration.
- Embedding models return 1,536 or 3,072 numbers per text. What do those sizes mean?