Embeddings: Representing Text as Vectors
By the Katkat team · Updated · 10 min read
Quick overview
How embedding models are trained with contrastive loss, when cosine beats dot product, how dimensionality and normalisation matter, and why domains drift.
After this lesson you will be able to explain how a text embedding model is trained and why similar texts end up close together. You will be able to say when cosine similarity and dot product give different rankings, and how to size and store vectors. You will also be able to describe how embeddings degrade when your data or model changes, and what to do about it.
What an embedding is
An embedding model maps a piece of text (a query, a sentence, a chunk of a document) to a fixed-length list of numbers, for example 768 floats. The goal is that texts with similar meaning, or texts that are relevant to each other for the task, land near each other in that vector space. Retrieval then becomes geometry: embed the query, find the nearest stored vectors. See Vector Search: HNSW, IVF and Approximate Nearest Neighbours for how that search is made fast, and Retrieval-Augmented Generation, End to End for where it sits in a full system.
Two points to get right early:
- An embedding model is not the same thing as the input embedding layer inside a chat LLM. That layer maps token IDs to vectors for the transformer to process. A text embedding model is a separate model, usually an encoder, whose job is to output one vector for a whole text.
- "Similar" is defined by the training data. A model trained to find question-answer pairs puts a question near its answer, not necessarily near other questions with the same wording.
How embedding models are trained
Most modern text embedding models follow the same recipe.
- Start from a pretrained transformer. Usually an encoder (or sometimes a decoder-only LLM) that already understands language. The text is tokenized and run through the model.
- Pool to one vector. The model produces one vector per token. These are reduced to one vector per text, commonly by averaging them (mean pooling) or by taking a special first-token vector. The result may be normalised.
- Train contrastively on pairs. The training data is pairs of texts that should be close: a query and a relevant passage, a title and its body, two paraphrases, a question and its accepted answer. Training pulls the pair together and pushes everything else away.
The standard loss is a contrastive loss, often called InfoNCE. For a batch of B pairs, each query q_i has one positive document d_i. Every other document in the batch serves as a free negative (in-batch negatives). The loss for query i is:
loss_i = −log( exp(s(q_i, d_i)/τ) / Σ_j exp(s(q_i, d_j)/τ) )
Here s is the similarity (usually cosine) and τ is a temperature, often a small value such as 0.05, that sharpens the distribution. It is a softmax cross-entropy over the batch where the "correct class" is the true pair.
A quick sanity check you can do in an interview: if the model cannot tell documents apart, all scores are equal and the loss is log B. With B = 32 that is ln 32 = 5 × ln 2 ≈ 3.47. Training should push the loss well below that.
Two practical consequences follow:
- Bigger batches give more negatives, which usually makes the signal stronger but needs more memory.
- Hard negatives matter. In-batch negatives are mostly easy (unrelated topics). Adding negatives that look relevant but are not, such as a passage from the same page that does not answer the question, teaches the model fine distinctions. The risk is false negatives: a "negative" that is actually relevant punishes the model for being right.
A typical pipeline trains first on a very large set of weakly labelled pairs (such as titles and bodies), then fine-tunes on a smaller set with human or curated labels. Some models expect different prefixes or instructions for queries and documents, because queries and documents are asymmetric. If the model card says to add a prefix, skipping it quietly lowers quality.
Cosine similarity vs dot product
Both measure how aligned two vectors are. They differ in whether length matters.
- Dot product: a·b = Σ a_i b_i. It grows with both the angle alignment and the vector lengths.
- Cosine similarity: (a·b) / (‖a‖ ‖b‖). It is the dot product of the vectors after scaling each to length 1, so it depends only on direction.
Worked example. Take a query q = (1, 0) and two documents d1 = (2, 2) and d2 = (1, 0.1).
| Document | Dot product with q | Length | Cosine with q |
|---|---|---|---|
| d1 = (2, 2) | 2 | √8 ≈ 2.83 | 2 / 2.83 ≈ 0.707 |
| d2 = (1, 0.1) | 1 | √1.01 ≈ 1.005 | 1 / 1.005 ≈ 0.995 |
Dot product ranks d1 first because it is longer. Cosine ranks d2 first because it points almost exactly the same way as q. If vector length carries no meaning in your model, cosine is the safer choice, since a long vector would otherwise win regardless of direction.
Length can sometimes carry information. Some models, and some recommender-style systems, deliberately let vector norm encode something like popularity or confidence, and then dot product is the intended metric. The rule is to use the metric the model was trained with. The model's documentation states it.
Normalisation
If you scale every vector to unit length (L2 normalisation), three things become equivalent:
- Dot product equals cosine similarity, because both norms are 1.
- Ranking by cosine equals ranking by Euclidean distance, because for unit vectors ‖a−b‖² = 2 − 2·cos(a,b). For example, a cosine of 0.8 gives a squared distance of 2 − 1.6 = 0.4.
- You can use a fast inner-product index and still get cosine results.
That is why many systems normalise at write time and use dot product at query time: one cheap operation per comparison, and the same answer as cosine. The failure mode is inconsistency. If stored vectors are normalised but query vectors are not (or the reverse), or an index is configured for Euclidean distance while you think it is doing cosine, rankings can be subtly wrong without any error message. Check what your vector store's "cosine", "dot" and "L2" options actually do. For a hands-on version, see Implement Top-k Retrieval with Cosine Similarity.
Dimensionality
Dimensionality is the length of the vector. Common sizes are in the hundreds to a few thousand. Higher dimensions can hold more distinctions, but with diminishing returns, and every extra dimension costs memory, index build time and query time.
Worked example: storage. Storing 1 million vectors as 32-bit floats (4 bytes per number):
| Dimensions | Bytes per vector | 1M vectors |
|---|---|---|
| 384 | 1,536 | 1.536 GB |
| 768 | 3,072 | 3.072 GB |
| 1,536 | 6,144 | 6.144 GB |
| 3,072 | 12,288 | 12.288 GB |
These are the raw vectors only. An approximate-nearest-neighbour index such as HNSW adds graph overhead on top, so budget more than the table shows. Going from 768 to 3,072 dimensions multiplies storage by 4 for the same number of chunks.
Ways to shrink this:
- Lower precision. Storing 768 dimensions as 8-bit integers takes 768 bytes per vector, so 1M vectors is 0.768 GB, a 4x reduction from float32. Some quality loss is possible, so measure it.
- Truncatable (Matryoshka-style) embeddings. Some models are trained so the first k dimensions form a usable smaller embedding. Truncating 1,536 to 256 cuts storage by 6x (1.024 GB per million) at some accuracy cost. This only works for models trained for it. Truncating an ordinary embedding can damage it badly. After truncating, re-normalise.
- Pick a smaller model if evaluation shows no loss on your data.
Do not assume more dimensions means better retrieval for your task. The only reliable way to decide is to measure recall on your own queries.
Choosing between options
| Decision | Option | When it fits | Watch out for |
|---|---|---|---|
| Metric | Cosine | Direction is meaning; most text models | Cost of computing norms if not pre-normalised |
| Metric | Dot product on unit vectors | Same ranking as cosine, fastest | Forgetting to normalise queries |
| Metric | Dot product on raw vectors | Model trained so norm carries signal | Long vectors dominate |
| Metric | Euclidean (L2) | Index default in some stores | Equivalent to cosine only if normalised |
| Size | Small (about 384 to 768) | Large corpora, tight memory or latency | Lower ceiling on fine distinctions |
| Size | Large (1,536 and up) | Hard, nuanced retrieval, smaller corpora | Storage and index cost scale linearly |
| Model | General-purpose | Broad, everyday text | Weaker on jargon |
| Model | Fine-tuned on your domain | Specialised vocabulary, stable domain | Needs labelled or synthetic pairs and re-indexing |
Embedding length limits also matter. Models accept only a maximum number of tokens and truncate or reject beyond that, and one vector for a very long text blurs many topics together. This is why chunking is part of retrieval quality, not just a preprocessing step.
Domain drift
Embeddings are only as good as the match between the model's training distribution and your data. Two related problems fall under "drift".
Domain mismatch. A general model may map specialist terms poorly. Internal product codenames, legal clauses, medical abbreviations, or code identifiers might be tokenised into meaningless pieces and placed near unrelated text. Symptoms: retrieval looks fine on everyday queries but fails on jargon, or exact identifiers are missed.
Change over time. Your corpus gains new terms, products and phrasing. User queries shift. And if you ever change the embedding model, the old vectors become incompatible: vectors from different models (or even different versions) live in different spaces, and comparing them is meaningless. You must re-embed the whole corpus, or run old and new indexes side by side during a migration, and store the model name and version alongside each vector.
What to do:
- Build a small labelled evaluation set of real queries with known relevant chunks, and track recall@k and similar metrics on it regularly. See Evaluating a RAG System.
- Add lexical matching so exact terms are not lost. See Hybrid Search and Reranking.
- Fine-tune the embedding model on in-domain pairs, possibly with synthetic queries generated from your documents, if the gap is large and the domain is stable.
- Version your index by model, and plan re-embedding as a normal operation, not an emergency.
How does this come up in interviews?
1. How is a text embedding model trained? Start from a pretrained transformer, pool token outputs into one vector, and train on pairs of related texts with a contrastive loss. Each query is pulled toward its positive and pushed away from the other documents in the batch, plus hard negatives. Mention temperature, batch size and the risk of false negatives.
2. When would cosine similarity and dot product rank results differently? When vector lengths differ. Dot product rewards long vectors, while cosine looks only at direction. If vectors are L2-normalised, the two are identical, so many systems normalise once and use the cheaper dot product. Say that the right metric is the one the model was trained with.
3. How would you choose the embedding dimension for 20 million chunks? Compute storage first: 20M × 768 × 4 bytes is about 61 GB in float32, and 1,536 dimensions doubles it, before index overhead. Then evaluate recall on your own queries for a few model sizes, and consider quantisation or truncatable embeddings if memory is the constraint. Pick the smallest option that meets the quality target.
4. Retrieval quality has dropped since launch. What do you check? Check whether the corpus or query distribution has shifted, whether anything changed in the embedding model, chunking or normalisation, and whether new documents were embedded with a different model version than old ones. Rerun the labelled evaluation set to localise the drop. Fixes include re-embedding, hybrid search, or domain fine-tuning.
5. Can you swap in a better embedding model without downtime? Not by replacing vectors in place, because new and old vectors are not comparable. Build a second index with the new model, backfill it, compare quality on an evaluation set, then switch queries over and retire the old index. See Debugging a RAG system for a related diagnostic approach.
Common mistakes
- Saying "embeddings capture meaning" without noting that similarity is defined by the training task and data.
- Using cosine in one place and Euclidean or raw dot product in another without checking the index configuration.
- Normalising stored vectors but not query vectors, or the reverse.
- Mixing vectors from different embedding models or versions in one index.
- Assuming higher dimensionality always improves retrieval, without measuring on your own data.
- Truncating dimensions of a model that was not trained to support it, or forgetting to re-normalise afterwards.
- Ignoring the model's maximum input length, so long chunks are silently truncated.
- Skipping the query or document prefix that the model expects.
- Having no labelled evaluation set, so drift is noticed only through user complaints.