KatInterview

Embedding Similarity: Top-K Retrieval and Evaluation

Machine LearningModel answer
HardModel answerMachine Learningembeddingssimilarityevaluation

Last updated

Implement cosine-similarity ranking over a set of candidate embeddings, handle edge cases explicitly, and reason through how you would evaluate whether the results are actually useful.

Embedding Similarity: Top-K Retrieval and Evaluation

You are building a feature that surfaces related items to a user based on vector embeddings. Each item is represented as a dense numeric vector of fixed dimension d. Given a single query embedding and a collection of candidate embeddings (each paired with a unique identifier), your task is to return the top k most similar candidates using cosine similarity.

What You Are Expected to Do

  1. Clarify the setup — before writing code, ask the questions you would ask an interviewer to nail down the representation and success criteria.
  2. Implement top_k_similar — a Python function with the signature below. Handle all edge cases explicitly; do not silently swallow them.
  3. Discuss scaling — explain how your approach changes as the candidate set grows from thousands to hundreds of millions.
  4. Describe evaluation — explain how you would measure, offline and online, whether the similarity is actually good.
def top_k_similar(
    query: list[float],
    candidates: dict[str, list[float]],
    k: int,
) -> list[tuple[str, float]]:
    """
    Return the top-k candidates most similar to the query,
    ranked by cosine similarity, descending.

    Parameters
    ----------
    query      : 1-D numeric vector (the reference embedding)
    candidates : mapping of unique id -> embedding vector
    k          : number of results to return

    Returns
    -------
    List of (id, similarity_score) tuples, length min(k, eligible candidates),
    sorted by score descending; ties broken alphabetically by id.
    """

Constraints and Edge-Case Rules

  • All valid embeddings share the same dimension d.
  • If the query embedding itself appears among the candidates (matched by value or by a special sentinel id), exclude it from results.
  • Zero vectors: a zero-norm vector has undefined cosine similarity — return a score of 0.0 for any such candidate, and if the query is a zero vector raise a ValueError.
  • Missing or non-numeric values: skip any candidate whose vector contains None, NaN, or non-numeric entries, but do not crash.
  • Dimension mismatch: skip candidates whose vector length differs from the query's.
  • Invalid k: raise a ValueError for k ≤ 0; if k exceeds the number of eligible candidates, return all eligible candidates.
  • Ties: break deterministically by candidate id, ascending alphabetically.

Clarifying Questions Worth Raising

Think about — and briefly address — the following before diving into code:

  • What does the embedding encode? Visual appearance, behavioral co-engagement, text semantics, or a blend?
  • Is "similar" defined by human judgment, by downstream click or save behavior, or both?
  • How large is the candidate pool, and is exact nearest-neighbor search acceptable?
  • What is the deployment latency budget, and does it affect whether retrieval must be approximate?

Hints

Hint 1

Cosine similarity is a dot product divided by the product of the two L2 norms. Compute each piece separately so you can catch the zero-norm case before dividing.

Hint 2

Sort a list of (score, id) tuples in a single pass using a compound sort key — primary: score descending, secondary: id ascending — rather than sorting twice.

Hint 3

For offline evaluation, think in two layers: does the ranked list match human or behavioral ground truth (NDCG, MRR, precision@k), and does the similarity generalize across meaningful slices (topic, modality, popularity tier)?