Sub topic 4
Where embeddings come from: transformer encoders, pooling, and contrastive training
This chapter explains how a model turns a sentence into one fixed-size vector. It assumes you know basic Python, what a neural network does in general, and how dot products and vector lengths work. You do not need to know transformer internals in detail. The chapter gives the working model you need to choose, debug, and fine-tune embedding models.
The three stages in one picture
An embedding model is a pipeline of three stages. A tokenizer splits text into tokens. A transformer encoder turns each token into a context-aware vector. A pooling step collapses those per-token vectors into one vector for the whole text. Training decides what that final vector means.
Tokenization
A tokenizer maps text to integer ids from a fixed vocabulary. Most encoders use subword tokenization (WordPiece or BPE), so a rare word like "unhappiness" may become pieces such as "un", "##happi", "##ness". Common words stay whole. This means the model never sees an unknown word, but long or unusual text uses more tokens than you might expect.
Every model has a maximum sequence length, often 256 or 512 tokens. Text beyond that limit is truncated and silently ignored by the model. This is the reason chunking (a later chapter) matters.
The tokenizer also adds special tokens. BERT-style models add a [CLS] token at the start and a [SEP] token at the end. When you batch sentences of different lengths, shorter ones get padding tokens, and an attention mask marks which positions are real.
The transformer encoder
An encoder is a stack of identical layers. Each layer has two main parts:
- Self-attention. Every token looks at every other token in the sequence and mixes in information from the ones that matter for it. Attention is bidirectional, so the vector for "bank" can use both "river" before it and "fishing" after it.
- A feed-forward network. It transforms each token's vector independently after attention.
Each token also gets a position signal, so the model knows word order. The input to the first layer is the token's learned vector plus its position information. After the last layer, the output is one vector per input token. These are called contextual embeddings, because the same word gets a different vector in different sentences.
Embedding models use encoders (BERT, MiniLM, MPNet, and similar) rather than text-generating decoders. Encoders see the whole text at once in both directions, which suits the task of summarizing it. Some newer embedding models start from decoder-style language models, but they still end with a pooling step.
A base model such as BERT is pretrained with masked language modeling: hide some tokens and predict them. That teaches rich token-level representations. It does not produce good sentence vectors by default. Averaging raw BERT outputs gives vectors where unrelated sentences often have surprisingly high similarity. The next two sections show what fixes this.
Pooling: many vectors to one
For a text with n tokens, the encoder outputs a matrix of shape (n, hidden_size). Pooling reduces it to a single vector of shape (hidden_size,). Three strategies are common:
| Strategy | How it works | Typical use |
|---|---|---|
| Mean pooling | Average the token vectors, ignoring padding | Most sentence-transformers models, such as all-MiniLM-L6-v2 |
| CLS pooling | Use the vector at the first (`[CLS]`) position | Some BGE models, and the original BERT classification setup |
| Max pooling | Take the largest value per dimension | Rare in modern embedding models |
The pooling strategy is part of the model. A model trained with mean pooling and used with CLS pooling gives worse vectors, with no error message. Always use the pooling that the model's documentation specifies.
The most common bug in hand-written pooling is averaging over padding. In a batch, padded positions hold meaningless vectors. You must multiply by the attention mask before summing, and divide by the count of real tokens, not by the padded length.
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel
name = "sentence-transformers/all-MiniLM-L6-v2"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name)
model.eval()
sentences = [
"How do I reset my password?",
"Steps to recover access to your account",
"The weather is sunny today and I plan to walk to the park",
]
batch = tokenizer(sentences, padding=True, truncation=True, return_tensors="pt")
with torch.no_grad():
out = model(**batch)
hidden = out.last_hidden_state # (batch, tokens, 384)
mask = batch["attention_mask"].unsqueeze(-1).float() # (batch, tokens, 1)
summed = (hidden * mask).sum(dim=1) # padding contributes zero
counts = mask.sum(dim=1).clamp(min=1e-9) # real tokens per sentence
mean_pooled = summed / counts
embeddings = F.normalize(mean_pooled, p=2, dim=1) # unit length
print(hidden.shape) # padded to the longest sentence
print(embeddings.shape) # torch.Size([3, 384])The sentence-transformers library from the previous chapters does exactly these steps inside model.encode. Writing them out once shows you where the vector comes from and what could go wrong.
Why contrastive training makes vectors useful
Pooling alone does not make the vector mean anything. Meaning comes from fine-tuning the encoder on pairs of texts that should be close. This is contrastive training.
The training data is a large set of positive pairs: a question and its answer passage, a title and its article body, two paraphrases, or a search query and a clicked result. For each pair, the model should place the two vectors close together and place unrelated texts far apart.
The usual method uses in-batch negatives. Take a batch of B pairs (q_i, d_i). Encode all queries and all documents. For query q_i, the matching document d_i is the positive, and the other B - 1 documents in the batch serve as negatives for free. Compute a B × B matrix of similarities. Each row is treated as a classification problem: the correct "class" is the diagonal entry. The loss is cross-entropy over the row, often called InfoNCE or multiple-negatives ranking loss.
import torch
import torch.nn.functional as F
def in_batch_contrastive_loss(q, d, temperature=0.05):
"""q, d: (batch, dim) tensors where q[i] and d[i] are a positive pair."""
q = F.normalize(q, dim=1)
d = F.normalize(d, dim=1)
logits = (q @ d.T) / temperature # (batch, batch) similarity matrix
labels = torch.arange(q.size(0)) # the positive for row i is column i
return F.cross_entropy(logits, labels)
torch.manual_seed(0)
q = torch.randn(4, 8)
good_d = q + 0.1 * torch.randn(4, 8) # documents close to their queries
bad_d = torch.randn(4, 8) # documents unrelated to queries
print(float(in_batch_contrastive_loss(q, good_d))) # low loss
print(float(in_batch_contrastive_loss(q, bad_d))) # higher lossSeveral details affect results:
- Temperature divides the similarities before the softmax. A small value like 0.05 sharpens the distribution and punishes near-miss negatives harder. It is a tuned hyperparameter.
- Batch size matters. Larger batches supply more negatives per step, so the task gets harder and the vectors get more discriminating. This is why embedding models are often trained with very large batches.
- Hard negatives are documents that look relevant but are not, for example a passage that shares keywords with the query without answering it. Adding them to training teaches the model finer distinctions than random negatives do.
- False negatives are a risk. If another document in the batch is actually relevant to a query, treating it as a negative pushes the model in the wrong direction. Cleaner data and deduplication reduce the problem.
Training typically happens in two phases. First comes large-scale weakly supervised pretraining on hundreds of millions of noisy pairs. Then comes fine-tuning on smaller curated datasets with hard negatives. Because the training pairs are mostly query-to-passage or paraphrase pairs, the model learns that "close" means "one text is a good answer to, or restatement of, the other."
What this implies for how you use embeddings
Training explains several behaviors you will see later:
- Similarity reflects the training objective. A model trained on question-to-answer pairs is good at retrieval. A model trained on paraphrase pairs may rank a near-duplicate above a real answer.
- Domain shift hurts. A model trained mostly on web text may place legal or medical jargon poorly, because it rarely saw those words in pairs.
- Asymmetric models need prefixes. Some models were trained with markers such as
query:andpassage:in front of the text. If you omit them, you run the model in a mode it was not trained for. - Length limits are architectural. Position handling and training length cap the usable input. Longer text is cut off, not summarized.
- Vectors from different models are incompatible. Each model defines its own space. Even two models with the same dimension produce vectors that cannot be compared with each other.
Common errors
- Pooling over padding tokens, which makes a sentence's vector depend on what else is in its batch.
- Using CLS pooling on a mean-pooling model, or the reverse.
- Forgetting
truncation=Trueand getting an error, or exceeding the maximum length and losing the tail of the text. - Calling
model.train()accidentally during inference, which leaves dropout on and makes embeddings vary between runs. Usemodel.eval()andtorch.no_grad(). - Assuming a bigger hidden size means better quality. Training data and objective usually matter more than dimension.
Exercise
In the pooling code, you remove the attention mask and simply compute hidden.mean(dim=1). The sentence "How do I reset my password?" is encoded once alone and once in a batch with a much longer sentence. Why can its embedding differ between the two runs, and how does the mask fix it?
Show answer
In the batch, the short sentence is padded to the length of the longest one. Without the mask, the average includes the padding positions' vectors, so the result depends on how much padding was added, which depends on the other sentences in the batch. Alone, there is no padding. Multiplying the hidden states by the attention mask zeroes the padded positions, and dividing by the count of real tokens (the mask sum) averages only over real tokens. The embedding then no longer depends on batch composition, apart from tiny numerical differences.
Exercise
A contrastive batch has 32 query-document pairs. How many negatives does each query see from in-batch negatives, and why does doubling the batch size usually help the model?
Show answer
Each query sees 31 negatives, the other 31 documents in the batch. Doubling the batch to 64 gives 63 negatives per query. More negatives make each classification harder, so the model must separate the true match from more competitors and learns finer distinctions. The cost is more memory per training step.