Token Pooling-Aware Training for Multi-Vector Embedding Models
Token Pooling Aware Training for Multi Vector Embedding Models Multi vector embedding models give each query token an opportunity to match a document token. This makes them expr...
By Software Development Team
Token Pooling-Aware Training for Multi-Vector Embedding Models
Multi-vector embedding models give each query token an opportunity to match a document token. This makes them expressive for search, but document representations can become large. A corpus containing millions of documents may require hundreds of millions of vectors.
Token pooling reduces this footprint by merging similar token vectors. More aggressive compression, however, can remove information that is useful for retrieval. Pooling-aware training teaches an encoder to preserve retrieval-relevant information even after its document vectors are merged.
With pool_factor=4, an ordinarily trained model retained 94.6% of its unpooled NanoBEIR nDCG@10 while reducing the number of document vectors by 4x. Pooling-aware training increased retention to 97.8% at the same storage budget.
Why Multi-Vector Retrieval Uses Many Vectors
A single-vector embedding model compresses an entire document into one vector. Multi-vector models such as ColBERT instead retain contextual token vectors, allowing different parts of a query to match different parts of a document.
For example, a query about a laptop with long battery life may match information about the laptop in one part of a document and battery endurance in another. With MaxSim scoring, each query vector selects its strongest document-vector match, and those scores are summed:
MaxSim(Q, D) = sum over q in Q of max over d in D of q^T d
Even with the 2-bit or 4-bit residual quantization supported by Fast-PLAID, storing hundreds of vectors per document can be expensive. At 4 bits per residual coordinate, 200 vectors with 128 dimensions require 12.8 KB of quantized residuals per document, or 12.8 GB for one million documents. Pooling each document to 50 vectors reduces that figure to 3.2 GB at the same dimensionality and precision.
Many document vectors are similar because several tokens may describe related concepts. Those similarities create an opportunity to represent multiple vectors together.
Token Pooling
HierarchicalTokenPooling groups similar token embeddings with Ward hierarchical clustering. It begins with one group per token vector and repeatedly merges the pair of groups that produces the smallest increase in within-group spread.
Spread is measured as the sum of squared distances from each vector to its group's mean. Ward's method therefore favors compact groups of similar vectors. The merges form a hierarchy of progressively larger groups, allowing the compression level to be selected according to a storage budget. Each group is represented by its mean, and the resulting vectors are normalized again for MaxSim scoring.
Compression can be made proportional to document length:
from sentence_transformers.multi_vector_encoder.modules import HierarchicalTokenPooling
pooling = HierarchicalTokenPooling(pool_factor=4)
With pool_factor=4, documents retain approximately one quarter of their original vectors. Longer documents can therefore retain proportionally more capacity. By default, the first token is protected from merging, and pooling applies only to document embeddings. Query embeddings remain unchanged.
Choosing a Pooling Budget
HierarchicalTokenPooling provides three main controls:
| Setting | Meaning |
|---|---|
max_tokens=16 | A maximum of 16 vectors per document, including protected tokens. |
pool_factor=4 | Approximately one quarter of each document's original vectors. |
distance_threshold=... | A shared Ward merge-distance threshold, allowing vector counts to vary according to embedding geometry. |
The distinction is important when document lengths vary. With pool_factor=4, a longer document retains approximately one quarter of its vectors, so its representation grows with its content. With distance_threshold, the vector count can increase when a document contains more distinct embeddings that need to be preserved.
Calibrating Adaptive Pooling
Adaptive pooling uses a shared distance threshold. Similar embeddings are merged more aggressively, while documents with more distinct content retain more vectors. This approach can be used with any multi-vector model, including one that was not trained with a pooling-aware objective.
A threshold can be calibrated for a target average vector count using a representative corpus sample:
from sentence_transformers import MultiVectorEncoder
from sentence_transformers.multi_vector_encoder.modules import HierarchicalTokenPooling
model = MultiVectorEncoder("lightonai/LateOn")
calibration_embeddings = model.encode_document(calibration_documents)
threshold = HierarchicalTokenPooling.calibrate_distance_threshold(
calibration_embeddings,
target_tokens=16,
)
pooling = HierarchicalTokenPooling(distance_threshold=threshold)
document_embeddings = model.encode_document(
documents_to_index,
token_pooling=pooling,
)
Calibration requires only document embeddings and returns a threshold that can be reused during indexing. The target is an average, so individual documents may receive more or fewer than 16 vectors. The achieved average may also change when the threshold is applied to another corpus.
Token Pooling-Aware Training
Pooling can improve storage efficiency for an ordinarily trained multi-vector model. The challenge arises when a document contains a retrieval-relevant distinction that becomes harder to recover after its vectors are merged. The original training objective did not require the model to work with compressed representations, but training can be adapted to include that requirement.
The principle is similar to Matryoshka embeddings. Matryoshka training applies a retrieval objective at multiple embedding widths, teaching smaller prefixes to remain useful. Pooling-aware training applies the objective to representations containing different numbers of token vectors.
Each training batch in this example contributes two losses:
- Retrieval using the original document embeddings.
- Retrieval after compressing documents to approximately one quarter of their original vectors.
The losses are averaged:
L = 0.5 * L_unpooled + 0.5 * L_pooled
The first term trains the model for retrieval with its full representations. The second teaches it to arrange token embeddings so that useful matches survive pooling. Both objectives update the same encoder, providing feedback before and after compression.
Ward clustering makes discrete decisions about which tokens belong together. During training, HierarchicalTokenPooling uses a straight-through estimator to pass gradients from pooled vectors to their member tokens without differentiating the cluster assignments. The encoder can therefore learn from retrieval errors produced by its pooled representations.
A Loss Wrapper in Sentence Transformers
MultiVectorTokenPoolingLoss wraps an existing multi-vector retrieval loss and applies it with selected poolers:
from sentence_transformers import MultiVectorEncoder
from sentence_transformers.multi_vector_encoder.losses import (
CachedMultiVectorMultipleNegativesRankingLoss,
MultiVectorTokenPoolingLoss,
)
from sentence_transformers.multi_vector_encoder.modules import HierarchicalTokenPooling
model = MultiVectorEncoder(
"answerdotai/ModernBERT-base",
similarity_fn_name="maxsim",
)
pooling = HierarchicalTokenPooling(pool_factor=4)
base_loss = CachedMultiVectorMultipleNegativesRankingLoss(
model,
mini_batch_size=64,
)
loss = MultiVectorTokenPoolingLoss(
model,
base_loss,
token_poolings=[None, pooling],
weights=[0.5, 0.5],
)
CachedMultiVectorMultipleNegativesRankingLoss provides the retrieval objective. It trains each query to score its relevant document above the negative documents in the batch. By default, it uses model.similarity, including the model's similarity and kernel settings. A model configured with similarity_fn_name="meanmaxsim" would use MeanMaxSim during training.
Gradient caching lets the encoder process small mini-batches while retaining a larger set of in-batch negatives. The training script uses mini-batches of 64 and a training batch size of 256.
MultiVectorTokenPoolingLoss adds the compression objective. In the example, None represents the original embeddings and pooling represents the factor-4 variant. Their weights average the two losses. Pooling variants reuse the computed token embeddings, so each additional pooler adds clustering and scoring work without requiring another encoder pass.
Poolers can also be custom BaseTokenPooling implementations that preserve gradients through their input embeddings. This allows the objective to be adapted to the representation used at deployment.
A complete training script includes the dataset, trainer, validation loss, and small retrieval evaluations during training. From a repository checkout, the ordinary and pooling-aware variants can be run with uv:
uv run examples/multi_vector_encoder/training/token_pooling/training_cached_contrastive.py --baseline
uv run examples/multi_vector_encoder/training/token_pooling/training_cached_contrastive.py
The script declares its training and kernel dependencies, allowing uv to install them. Compatible kernels are enabled automatically.
The same training can be run on a cloud GPU with Hugging Face Jobs:
pip install -U huggingface_hub
hf auth login
hf jobs uv run \
--flavor a10g-small \
--timeout 4h \
--secrets HF_TOKEN \
-- https://raw.githubusercontent.com/huggingface/sentence-transformers/main/examples/multi_vector_encoder/training/token_pooling/training_cached_contrastive.py
This command runs the pooling-aware variant on an A10G GPU with a four-hour limit. Passing HF_TOKEN as a secret allows the script to upload the trained model to the associated Hub account. Adding --baseline after the script URL runs the ordinary-loss variant.
Optional Kernel Acceleration
Kernels can accelerate MaxSim scoring, Ward clustering, and supported backbone operations. Install the required dependencies with:
pip install -U "sentence-transformers[train,kernels]"
Enable kernels when initializing the model:
model = MultiVectorEncoder(
"answerdotai/ModernBERT-base",
device="cuda",
similarity_fn_name="maxsim",
use_kernels=True,
)
pooling = HierarchicalTokenPooling(pool_factor=4)
Hierarchical poolers inherit the model's kernel settings by default, so enabling kernels on the model is sufficient.
Sentence Transformers selects compatible kernels for the environment and uses the existing implementation when no replacement is available. The default MaxSim kernel scores queries against documents without constructing the full token-similarity matrix in memory, but it requires CUDA and Triton.
The default Ward clustering kernel runs hierarchical clustering on CUDA instead of the CPU. It is reported as 30 to 150 times faster than SciPy, depending on the configuration.
Using the Trained Model
A pooling-aware model can generate compressed document embeddings while leaving query embeddings unchanged. Kernel settings are not saved with the model, so use_kernels=True must be supplied during loading when kernel acceleration is desired for inference:
from sentence_transformers import MultiVectorEncoder
from sentence_transformers.multi_vector_encoder.modules import HierarchicalTokenPooling
model = MultiVectorEncoder("tomaarsen/mve-ModernBERT-base-token-pooling")
pooling = HierarchicalTokenPooling(pool_factor=4)
queries = ["Which planet is known as the Red Planet?"]
documents = [
"Venus is often called Earth's twin because of its similar size and proximity.",
"Mars, known for its reddish appearance, is often referred to as the Red Planet.",
"Jupiter, the largest planet in our solar system, has a prominent red spot.",
]
query_embeddings = model.encode_query(queries)
document_embeddings = model.encode_document(
documents,
token_pooling=pooling,
)
print([len(embedding) for embedding in document_embeddings])
## [5, 6, 5]
print(model.similarity(query_embeddings, document_embeddings))
## tensor([[16.0037, 25.9879, 22.8159]], device='cuda:0')
## Without token pooling:
## [18, 21, 19]
## tensor([[16.6115, 27.6060, 24.1766]], device='cuda:0')
The pooler reduces the three documents from 58 vectors to 16. Mars still receives the highest similarity score, followed by Jupiter and Venus, so the ranking is preserved despite the smaller document representation.
pool_factor can be changed at inference to explore a different storage budget with the same trained model. For repeated use, token_pooling=pooling can be supplied when initializing MultiVectorEncoder to make it the runtime default. The pooler's tasks setting continues to control which inputs are compressed, such as documents only.
Evaluation Results
Two models were trained from answerdotai/ModernBERT-base, each with a new 128-dimensional token projection:
tomaarsen/mve-ModernBERT-base-token-pooling-baseline, trained with only the cached contrastive loss.tomaarsen/mve-ModernBERT-base-token-pooling, trained with the cached contrastive loss wrapped around the unpooled and factor-4 objectives.
Both runs used one epoch over the same 120,000 MS MARCO triplets, seed 42, and matching initialization and optimization settings. The training token cap was 300, and short queries were expanded to at least 32 token positions to provide additional contextual query vectors. The loss was the only difference between the experiments, and no hyperparameter search was performed.
The models were evaluated on NanoBEIR@13 using mean nDCG@10. The results compare ordinary and pooling-aware training with pool factors of 2, 3, 4, and 6, as well as unpooled retrieval. Fixed caps and adaptive thresholds are also included.
| Pooling at inference | Mean vectors | Ordinary model | Pooling-aware model | Gain (points) |
|---|---|---|---|---|
| Unpooled | 193.22 | 51.84 | 52.39 | +0.55 |
pool_factor=2 | 96.86 | 50.10 | 51.74 | +1.64 |
pool_factor=3 | 64.74 | 49.70 | 51.45 | +1.76 |
pool_factor=4 | 48.68 | 49.03 | 51.23 | +2.20 |
pool_factor=5 | 39.04 | 48.13 | 50.28 | +2.15 |
pool_factor=6 | 32.62 | 47.07 | 49.85 | +2.78 |
max_tokens=64 | 54.76 | 49.27 | 50.89 | +1.63 |
max_tokens=32 | 29.58 | 48.25 | 50.12 | +1.87 |
max_tokens=16 | 15.60 | 46.61 | 49.26 | +2.65 |
max_tokens=8 | 7.99 | 43.12 | 46.61 | +3.48 |
max_tokens=4 | 4.00 | 37.22 | 43.00 | +5.78 |
distance_threshold (calibrated) | 54.76 | 50.10 | 51.24 | +1.14 |
distance_threshold (calibrated) | 29.58 | 48.38 | 50.96 | +2.58 |
distance_threshold (calibrated) | 15.60 | 47.23 | 49.63 | +2.41 |
For adaptive pooling, a separate threshold was calibrated for each encoder and NanoBEIR corpus. The calibration used unpooled document embeddings to match the average vector counts under caps of 64, 32, and 16. Short documents caused the resulting averages to fall below those caps.
At the trained pool_factor=4, nDCG@10 increased from 49.03 to 51.23, while the number of stored document vectors fell by 74.8% compared with unpooled retrieval. Score retention increased from 94.6% to 97.8%, calculated as pooled mean nDCG@10 divided by each model's own unpooled mean. Unpooled retrieval also improved, from 51.84 to 52.39.
The gains extended to fixed caps and adaptive pooling, although training used only the full representation and proportional pooling. At an average of 29.58 vectors per document, adaptive pooling retained 97.3% of the pooling-aware model's unpooled score while storing 84.7% fewer document vectors. The ordinarily trained model retained 93.3% at the same budget.
Combining Compression Techniques
Multi-vector indexes can combine several compression methods:
- Embedding quantization to 4, 2, or 1 bit per coordinate, for example with Fast-PLAID, to reduce storage per coordinate.
- Token pooling to reduce the number of document vectors, optionally with pooling-aware fine-tuning.
- Matryoshka token embeddings to reduce the dimensionality of each token vector, optionally with fine-tuning for smaller widths.
When a model's default dimensionality is greater than 128, Matryoshka truncation and fine-tuning may also be considered earlier in the process. These techniques can be combined, but the resulting index size and retrieval quality should be evaluated with the target search engine and corpus.
MultiVectorMatryoshkaLoss trains token embeddings to remain useful after truncation. It can be wrapped with MultiVectorTokenPoolingLoss to train for both lower dimensionality and fewer document vectors while reusing encoder embeddings across compression settings.
The evaluation script measures unpooled retrieval, caps of 64, 32, 16, 8, and 4 vectors, and pool factors from 2 through 6. These measurements can be used to examine the quality and storage tradeoff for a particular model and corpus.
References
- Stefan Josef, Learn to Pool: Lightweight Fine-Tuning for Flexible Multi-Vector Compression.
- Benjamin Clavié, Antoine Chaffin, and Griffin Adams, Reducing the Footprint of Multi-Vector Retrieval with Minimal Performance Impact via Token Pooling.
- Antoine Chaffin, After the party comes the free lunch: regularizing ColBERT models to enhance pooling capabilities and reduce index footprint.
- Luyu Gao, Yunyi Zhang, Jiawei Han, and Jamie Callan, Scaling Deep Contrastive Learning Batch Size under Memory Limited Setup.
- Introduction to Matryoshka Embedding Models.