The interview problem

Practice prompt

You have unlabeled product images and want embeddings for visual search. Explain a contrastive objective, calculate a small example and design an evaluation. Similar products may appear in different records, and color sometimes distinguishes the product. Explain how these facts affect positive pairs and negatives.

Original fundamentals practice, not a reported interview. Examples are hypothetical. Primary research retrieved September 27, 2026.

1. Decide which differences should disappear

An embedding should retain differences important to the task and become less sensitive to irrelevant variation. For product search, background and lighting may be nuisances, while color, shape or a small logo can determine identity. The desired similarity relation comes before the loss function.

Two augmented views of the same source image can form a positive pair, but an augmentation is an assumption about invariance. A crop that removes the only distinguishing feature or a color transformation that changes a requested color can create misleading supervision. Inspect transformed examples with the product owner and test retrieval slices where those features matter.

A different source record is not necessarily a different semantic item. The catalog may contain duplicate photographs, alternate views or variants that should remain close for some queries and separate for others. Define those relationships rather than relying entirely on row IDs.

2. Write the objective precisely

Let an encoder produce a representation h and an optional projection network produce z, normalized to unit length. For one anchor a, identify a positive p and a candidate set C containing p and the chosen negatives, excluding the anchor itself. Let s(a,j) be the dot product of normalized embeddings and τ a positive temperature.

The anchor loss is L = −log[exp(s(a,p)/τ) / Σ(j in C) exp(s(a,j)/τ)]. This asks the model to distinguish the positive within the stated candidate set. It is not directly a calibrated probability that two real-world products match. Candidate composition changes the classification problem.

Use a numerically stable log-sum-exp implementation. Keep the positive in the denominator. Mask the anchor's self-comparison and any intentionally excluded pairs. When both views serve as anchors, average the corresponding directional losses under an explicit weighting rule.

3. Calculate a three-candidate example

Suppose the positive similarity is 0.8 and two negative similarities are 0.4 and 0.0, with τ = 0.2. The logits are 4, 2 and 0. The positive probability is exp(4)/(exp(4)+exp(2)+1) ≈ 0.8668, and the loss is approximately 0.1429.

With τ = 0.4, the logits become 2, 1 and 0. The positive probability falls to about 0.6652 and loss rises to about 0.4076. A lower temperature sharpens the distribution for these fixed similarities. This example does not prove a lower temperature is always better during training.

Let q_j denote the softmax probability assigned to candidate j. The derivative with respect to the positive similarity is (q_positive − 1)/τ, while a negative's derivative is q_negative/τ. Both the probability and the inverse-temperature factor matter. A confidently wrong hard negative can receive a strong update; tuning temperature also changes sensitivity to mislabeled pairs.

4. Explain false negatives and collapse

A negative that is actually another valid match creates contradictory pressure: the objective tries to separate items the downstream task wants together. Inspect nearest-neighbor negatives for duplicates and semantic matches. Where trustworthy metadata exists, mask known equivalent items or use a multi-positive objective with clearly defined normalization.

Do not remove every hard negative simply because it is visually similar. Near-identical products with different identifiers or features may be exactly the distinctions the search system must learn. Compare failure cases against the target relevance definition.

If all candidate similarities are equal and there are K candidates, the positive probability is 1/K and the loss is log(K). In this example K=3 gives about 1.0986. An informative representation can improve on that baseline. This does not guarantee optimization can never enter a collapsed or low-rank state; monitor embedding variance, similarity distributions and downstream discrimination.

5. Distinguish batch size from optimizer batch size

Consider a symmetric setup with 256 source images and two views per image. There are 512 anchor views. For each anchor, excluding itself leaves 511 candidates: one positive and 510 other views treated as negatives under the simplest rule.

With 32 source images per microbatch, each anchor sees only 63 candidates, including 62 negatives. Accumulating gradients over eight such microbatches increases examples per optimizer update but does not supply the missing cross-microbatch comparisons. It therefore changes the contrastive objective relative to one full 256-image batch.

A queue or cross-worker embedding exchange can enlarge the candidate set, but introduces engineering choices: representation staleness, metadata for masking and which paths receive gradients. State those choices rather than claiming all mechanisms reproduce the same large-batch gradient.

6. Budget pairwise work

A dense similarity matrix for 512 views contains 512² = 262,144 entries, about 1.05 MB at four bytes per entry. At 8,192 views it contains 67,108,864 entries, about 268.4 MB. These numbers cover only one matrix, excluding gradients, masks, temporary tensors and encoder activations.

Pairwise work grows quadratically with the number of views for this dense implementation. Chunked similarity calculations can reduce temporary memory while preserving a chosen denominator, but care is needed to retain gradients and stable normalization across chunks. Benchmark total step time and memory, not just embedding storage.

The simplest starting architecture is a versioned dataset and pair generator, encoder/projector training job, checkpoint registry, offline embedding export and a retrieval evaluation harness. Log augmentation policy, candidate sampling and temperature with every checkpoint so comparisons are interpretable.

7. Evaluate the representation, not only its loss

Use a held-out set of product families and near-duplicate groups to avoid leaking the same item across development and evaluation. Construct relevant matches from the actual search task. Report retrieval metrics at the intended candidate-catalog size, plus slices for color, viewpoint, packaging changes and rare categories.

Where appropriate, fit a linear probe on a separate labeled training split while keeping the encoder frozen, then score it on held-out data. Compare retrieval approaches on the same fixed evaluation set. Decide whether to export encoder representations or projected vectors based on downstream evidence. Lower contrastive loss on a changed candidate set is not automatically better representation quality.

Inspect whether embeddings organize products by useful identity or shortcuts such as studio background and watermark. Test natural images from the expected launch distribution, not only the training augmentations. Monitor duplicate-match quality separately from category-level similarity because the two can disagree.

8. Defend the trade-offs

Start with controlled ablations: change one augmentation, temperature or candidate strategy at a time while keeping the evaluation fixed. Record compute budget and optimization steps. If a change improves average retrieval but destroys color-sensitive queries, revisit the intended invariance instead of hiding that slice.

Foundation: identify the positive and denominator. Senior: calculate the loss and distinguish hard from false negatives. Staff: explain why accumulation changes candidate interactions and design an evaluation resistant to catalog duplicates.

Score 0–2 each for semantic task definition, loss calculation, negative quality, batch/memory reasoning and downstream evaluation. Continue with gradient accumulation.

Sources and next steps

The product-search scenarios, loss calculations and capacity examples are original. Results from visual representation research do not establish a universal best augmentation or temperature for another dataset.

Continue your preparation

Choose a connected learning path or browse more ML fundamentals questions. Read our editorial method and attribution policy.