What are embeddings and how are they learned?
Written by the mlprep team · Updated
What are embeddings and how are they learned? Why do similar things end up close together in embedding space?
An embedding is a dense, low-dimensional vector representation of a discrete object — a word, a user, a product, a movie. Instead of representing "cat" as a one-hot vector of size 100,000 (one entry per vocabulary word), an embedding represents it as, say, a 300-dimensional dense vector of floats.
Why one-hot fails#
One-hot vectors have no structure: every word is equidistant from every other word. You can't express that "cat" and "kitten" are related, or that "Paris" and "France" have a similar relationship to "Berlin" and "Germany." Every word lives in its own isolated dimension.
How word2vec learns embeddings#
Word2vec (skip-gram variant) trains a shallow network to predict surrounding words given a center word. For the sentence "the cat sat on the mat," given "cat" as input, the model is trained to predict "the," "sat" (within a context window).
The training signal: if "coffee" and "tea" always appear in similar contexts (with "drink," "hot," "cup"), the model learns to give them similar representations, because similar representations make the prediction task easier. The embedding is a byproduct of solving this distributional prediction problem.
After training, the embedding matrix rows are the learned vectors. Similar words end up nearby because they were trained on the same signal.
The geometry reflects semantics#
Famous result: king - man + woman ≈ queen. The embedding space has learned that there's a "royalty" direction and a "gender" direction, and arithmetic on these vectors recovers meaningful relationships. This falls out of the training objective — the model must represent these relational patterns to predict context words accurately.
Embeddings beyond words#
The same idea applies everywhere there are discrete objects:
- Users and items in recommendation systems (collaborative filtering via matrix factorization learns user and item embeddings)
- Graph nodes (node2vec, GraphSAGE learn embeddings from graph structure)
- Products, categories, queries in e-commerce search
- Code tokens, proteins, molecules — any domain where co-occurrence or proximity signals semantic similarity
In modern neural networks, the first layer of any model that takes categorical inputs is an embedding table — a learned lookup that converts IDs to dense vectors that can be processed by subsequent layers.
You mentioned the skip-gram objective — what is the model actually optimizing, and what's the practical challenge with the vocabulary-sized softmax?
The full softmax problem#
The skip-gram model predicts context words using a softmax over the full vocabulary:
P(w_context | w_center) = exp(v_context · v_center) / Σ_w exp(v_w · v_center)
The denominator sums over all V words in the vocabulary. For V = 100,000 words and training on billions of token pairs, computing this normalization constant at every step is prohibitively expensive — O(V) per training example.
Negative sampling#
Instead of computing the full softmax, reformulate as a binary classification problem: given a (center, context) pair, is this a real co-occurrence or a noise sample?
For each real pair (w_center, w_context), sample k "negative" words w_neg from a noise distribution (roughly unigram frequency raised to the 0.75 power, which downsamples frequent words). Train the model to:
- Output high probability for the real pair
- Output low probability for the k negative pairs
L = log σ(v_context · v_center) + Σ_{k} log σ(-v_neg · v_center)
Now you only compute k+1 dot products per step instead of V. With k=5–20 negatives, training is ~100-1000× faster. The embedding quality is empirically similar or better because frequent but uninformative words (the, a, it) are downsampled.
Why it still works#
Negative sampling gives a biased but practically useful approximation to the true gradient. The key property it preserves: words that appear in similar contexts will be pulled toward each other, and words that don't co-occur will be pushed apart. The geometry of the learned space is preserved even without the exact normalization.
You've deployed an embedding model to production powering a recommendation system. What breaks over time, and how do you manage the full lifecycle of embeddings in production?
Embedding drift#
Embeddings degrade silently. Two forms:
Covariate drift: the distribution of inputs shifts — new items enter the catalog, old ones go stale, user behavior patterns change seasonally. Embeddings trained on last quarter's interaction data are stale for this quarter's content. Symptoms: recommendation diversity decreases, popular-new-item cold-start worsens, A/B tests show engagement decay vs recency-based baselines.
Model staleness: the embedding model itself hasn't been retrained, but the label distribution it was trained on has shifted (e.g., a product category mix changed, or a new content vertical launched). The model's learned representation doesn't cover the new distribution.
Detection: track the distribution of nearest-neighbor distances for a fixed probe set. If average ANN distance rises (items spreading apart) or falls (items clustering together), the embedding space has shifted. Also track click-through rate on top-k retrieved items — a leading indicator of embedding quality.
Versioning and index management#
Every time you retrain the embedding model, all existing embeddings are invalidated — the new model maps the same inputs to a completely different coordinate space. You can't mix embeddings from v1 and v2 in the same index and compare them meaningfully.
Versioning strategy:
- Train new embedding model on a shadow pipeline
- Re-embed the full item catalog with the new model (can take hours for large catalogs)
- Build the new ANN index in parallel
- Atomic swap: promote new index, deprecate old one
- Keep old index warm for a rollback window (typically 24–48 hours)
This means you need versioned embedding stores: embeddings/v12/item_embeddings.parquet, indexes/v12/hnsw.bin. Tooling must route query-time embeddings to the correct model version to match the index.
Vector DB constraints#
ANN indexes have hard constraints that don't show up until scale:
HNSW (Hierarchical Navigable Small World): the dominant index structure. Build time is O(n log n) in index size; memory footprint is roughly 4 × d × n bytes for float32 (for n=100M items at d=256 dims: ~100GB). HNSW doesn't support efficient incremental updates — new items can be inserted, but frequent insertions degrade graph quality over time. At some point, a full rebuild is required.
Exact vs approximate: HNSW returns approximate nearest neighbors — it trades recall for speed. At ef=64 (search parameter), recall@10 is typically ~95-99% vs exact search, with 100-1000× speedup. For recommendations this tradeoff is fine. For high-stakes retrieval (legal, medical document search), track recall explicitly and tune ef accordingly.
Quantization: int8 or binary quantization of embeddings reduces memory footprint 4-8× at a small recall cost. At 100M+ items this is often necessary to fit the index in GPU/CPU memory. Faiss's IVF-PQ (inverted file + product quantization) combines clustering with quantization for billion-scale indexes.
Embedding collapse#
A failure mode where training converges to a degenerate solution: most embeddings collapse to a small region of the space, making all items look similar.
Causes:
- Contrastive training with easy negatives: if all negatives are random, the loss is trivially satisfied by learned embeddings that are all near the origin. The model learns to ignore input.
- Temperature too high in InfoNCE: flattens the loss gradient; model doesn't differentiate similar vs dissimilar pairs.
- Lack of hard negatives: the model never sees near-misses and doesn't learn fine-grained discrimination.
Detection: monitor the mean pairwise cosine similarity across a random probe set. For a healthy embedding space, this should be low (near 0 for random pairs, much higher for actually similar items). If probe-pair similarity is uniformly high (above 0.8), collapse is occurring.
Fixes: add hard negative mining (in-batch negatives, ANN-mined near-duplicate negatives), reduce temperature, add a uniformity loss term (push embeddings toward the unit hypersphere uniformly).
Serving architecture#
Two patterns with different tradeoffs:
Offline index, batch embeddings: embed all items offline on a schedule (daily/hourly), build the ANN index, serve queries by embedding the query at request time and running ANN lookup against the static index. Latency: query embedding (5-20ms) + ANN lookup (1-5ms). Works for most recommendation systems. New items aren't searchable until the next batch run.
Online embedding with real-time index updates: embed new items immediately when ingested, insert into a live index. Required for news, livestreams, or marketplaces where freshness matters. HNSW supports online inserts but degrades without periodic rebuilds — schedule incremental rebuild during off-peak hours.
Two-stage serving: ANN retrieval is cheap (milliseconds for top-1000 candidates). A more expensive reranker (cross-encoder, LLM-based) runs on the candidate set. Embeddings do the coarse work; the reranker does the fine-grained work. This separation means you can use a smaller, faster embedding model for retrieval without sacrificing final ranking quality.
Senior/staff considerations#
At senior/staff level, embeddings are not just "vectors where similar things are close." They are an interface contract between training, indexing, serving, monitoring, and product behavior.
The main design questions:
- What is the positive signal? Clicks, purchases, dwell time, saves, co-occurrence, human labels, and text similarity produce different embedding spaces. The geometry reflects the training objective, not universal semantic truth.
- What negatives are used? Random negatives teach coarse separation. Hard negatives teach fine-grained discrimination. False negatives can damage the space by pushing apart items that are actually relevant.
- What invariances should the space learn? For search, lexical match may matter. For recommendations, taste similarity may matter. For moderation, policy-relevant semantics matter. One embedding model rarely serves all goals equally well.
- How is the space evaluated? Track retrieval recall@k, NDCG after reranking, ANN recall versus exact search, segment coverage, diversity, collapse metrics, and online lift. Nearest-neighbor demos are not enough.
- How are versions managed? Model, embeddings, ANN index, feature definitions, and query-time encoder must be promoted atomically.
Common traps#
- Assuming cosine similarity means semantic similarity without checking the objective.
- Mixing embeddings from different model versions in one index.
- Evaluating only aggregate recall while missing cold-start, tail-item, or minority-language failures.
- Ignoring index-level errors: quantization, stale shards, degraded HNSW graph quality, or ANN recall loss.
- Using embeddings as a black box when downstream systems depend on calibrated, stable behavior.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
Embeddings map discrete objects to dense vectors by training on a distributional objective — similar objects appear in similar contexts, so they learn similar representations. Word2vec's skip-gram predicts surrounding words; the embedding is a side effect of solving that prediction task. Full-vocabulary softmax is too slow at scale; negative sampling replaces it with a binary classification against random noise samples. In production: embeddings drift as data distribution shifts — monitor pairwise similarity and ANN retrieval quality. Retraining invalidates all existing embeddings; atomic index swaps with rollback windows are required. HNSW indexes have memory and rebuild costs that dominate at 100M+ items. Collapse (all embeddings similar) is detected by tracking probe-pair cosine similarity; fixed by hard negative mining and temperature tuning.
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- How does the transformer's embedding layer differ from word2vec, and why do contextual embeddings (BERT) outperform static ones?
- How would you design an embedding system for a cold-start problem, where new items have no interaction history?
- What's the difference between collaborative filtering embeddings and content-based embeddings, and when would you combine them?
- How do you detect and measure embedding collapse during training, and what does the uniformity-alignment framework tell you about embedding quality?
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions