Pooling without the attention mask makes a sentence vector depend on its batch. Mask-aware mean and last-token pooling, and a test that embeds texts alone and batched.
The same question, two different vectors
Dinky maintains the help-desk search at Belgavi's Book Store. Customer questions are embedded with an encoder model and compared with a small set of help articles. To save money, the indexing job embeds questions in batches of 32 instead of one at a time. After the change, a regression check found something odd: the question "can i return a paperback after thirty days" sometimes retrieved the returns policy and sometimes the order tracking page. Same text, same model, same weights. The only difference was which other questions happened to share its batch.
The cause was one line in a custom pooling function: the sentence vector was the mean of the encoder's final hidden states over every position in the padded row. When a short question shares a batch with a long one, the tokenizer pads the short row to the long row's length, and the mean now includes the pad positions. The vector depends on the length of the longest neighbour.
Padding is not a model bug. The encoder receives an attention mask that tells it which positions are real, and in a correctly implemented encoder the hidden states of real tokens do not depend on how much padding follows them. What the pad positions hold is a different matter: the model computes something there, nothing constrains it, and nobody trained it to be harmless. Every pooling step must therefore use the mask too.
Three ways pooling reads a pad
- Mean without the mask.
last_hidden_state.mean(dim=1)divides by the padded length and adds the pad states. The vector moves toward whatever the pad states look like, and further the more padding there is. - Last token by position. Decoder-style embedding models often take the hidden state of the final token. With right padding,
last_hidden_state[:, -1]is a pad position for every row shorter than the longest. - First token by position. Models that use a first-position summary token are safe with right padding, but if a tokenizer is configured to pad on the left, position 0 is a pad for short rows.
Each of these works perfectly when texts are embedded one at a time, because a batch of one has no padding. That is why the bug survives unit tests and appears when someone batches for throughput.
Mask-aware pooling
The fix is to use the attention mask in the pooling arithmetic, not just in the forward pass. Masked mean pooling multiplies by the mask and divides by the number of real tokens:
import torch
def masked_mean(last_hidden_state, attention_mask):
mask = attention_mask.unsqueeze(-1).to(last_hidden_state.dtype)
summed = (last_hidden_state * mask).sum(dim=1)
counts = mask.sum(dim=1).clamp(min=1e-9)
return summed / counts
def last_real_token(last_hidden_state, attention_mask):
# index of the last position whose mask is 1, for either padding side
seq_len = attention_mask.shape[1]
flipped = attention_mask.flip(1).to(torch.int64).argmax(dim=1)
idx = seq_len - 1 - flipped
return last_hidden_state[torch.arange(last_hidden_state.shape[0]), idx]These two PyTorch functions are written for illustration and are not executed by the companion tests, which run the same arithmetic in plain Python on synthetic vectors. Their logic is what the sentence-transformers library does. In its pooling module at v6.3.0 (released 11 November 2026), mean pooling multiplies the token embeddings by the mask and divides by the clamped mask sum, the CLS mode takes the first position whose mask is 1, and last-token mode finds the last position whose mask is 1 by flipping the mask. If you load a model through that library you get mask-aware pooling. The risk is in code that calls the encoder directly and reimplements pooling in a line or two, which is common in inference servers, batch jobs and ports to other runtimes.
The worked example
The companion example replaces the encoder with synthetic token vectors so the effect can be inspected exactly. Each word gets a six-dimensional vector: a weight of 1 on a topic dimension (returns, time window, price, gift card, order tracking, other) plus small deterministic noise. Pad positions get a fixed vector pointing mostly at the order-tracking dimension, scaled by an adjustable magnitude. The vectors are not contextual and not trained, so the size of the effect is illustrative, not a measurement of any real model. What matters is whether the pooled query vector is the same alone and in a batch.
The query has eight tokens. In a batch with a sixteen-token partner it gains eight pad positions. Four help articles are embedded alone and scored by cosine similarity.
| Pooling | Cosine of query alone vs in batch | Top article alone | Top article in batch |
|---|---|---|---|
| Mean, pads included | 0.768 | returns | tracking |
| Mean, mask-aware | 1.0 | returns | returns |
| Last position, right padding | -0.080 | price drop | tracking |
| Last real token, right padding | 1.0 | price drop | price drop |
| First position, left padding | 0.218 | gift cards | tracking |
| First real token, left padding | 1.0 | gift cards | gift cards |
Two further rows explain the shape of the problem. With only four pad positions the unmasked mean still has cosine 0.915 and the top article happens to survive, which is how the bug hides in batches of similar lengths. With pad vectors set to zero the unmasked mean keeps the direction but shrinks the vector by the real fraction of the row; after normalisation the cosine is 1.0, but any system that scores by unnormalised dot product still sees a batch-dependent score.
The first and last-token rankings differ from the mean rankings because the synthetic vectors are not contextual: the last word of the query is days, so its vector points at the time dimension. With a real encoder trained for last-token pooling, that position summarises the sequence. Only the comparison between alone and in-batch is meaningful here.
The interactive lab exposes every control: pooling rule, padding side, partner length, pad magnitude and normalisation, with a trace that names the positions each rule reads.
Failure modes beyond the obvious
- Padding side set by a different component. Some tokenizers default to left padding for generation. If the same tokenizer object is reused for embedding, a first-position pooling that was correct becomes wrong without any code change.
- Exported models. ONNX or other runtime exports sometimes drop the pooling module and leave it to the caller. Reimplementing it from memory is where the unmasked mean appears.
- Mixed batch and single paths. Index documents in batches and embed queries one at a time, and every document carries a batch-dependent error the queries do not. Recall drops and nobody can reproduce it with a single example.
- Instruction prefixes. Some models expect a prompt prefix that should be excluded from pooling. sentence-transformers handles that by zeroing the prompt positions in the mask; a custom version must do the same, and must account for left padding when it does.
Verification
The test that catches every variant is short. Embed each text alone, embed the same texts in a batch with a much longer neighbour, and require the vectors to match within numerical tolerance:
def test_batch_invariance(embed, texts, long_text, tol=1e-5):
for t in texts:
alone = embed([t])[0]
batched = embed([t, long_text])[0]
assert max(abs(a - b) for a, b in zip(alone, batched)) < tol, tRun it for both padding sides if your tokenizer can be configured either way. The companion tests check the mask-aware rules on 300 random combinations of query, padding side, partner length, pad magnitude and normalisation, and require batch invariance every time. Real models running in reduced precision may differ in the last few bits between batch sizes because kernels sum in a different order; set the tolerance from a measured baseline, not from zero, and investigate anything an order of magnitude larger.
When this does not apply
Models that embed one text per call, or pipelines that sort texts into length buckets with no padding, never pool a pad. Bucketing reduces the error but does not remove it, and it is not a substitute for masked pooling. If your embedding API is a hosted endpoint, the provider pools for you; the batch-invariance test is still a cheap way to confirm it.
Interactive experiment
Embedding Pooling: Watch Padding Change a Sentence Vector. Synthetic browser-local fixtures, adjustable inputs, decision traces and JSON export.