{"slug": "training-and-finetuning-multi-vector-embedding-models-with-sentence-transformers", "title": "Training and Finetuning Multi-Vector Embedding Models with Sentence Transformers", "summary": "Hugging Face's Sentence Transformers library v6.0 introduces a fourth model type, MultiVectorEncoder, for ColBERT-style late interaction retrieval, along with a complete training approach. The blog post demonstrates finetuning a multi-vector model that outperforms general-purpose retrievers on medical retrieval evaluation, trained in 14.5 hours on a single RTX 3090.", "body_md": "Sentence Similarity • 0.1B • Updated • 214k • 201\n\n# Training and Finetuning Multi-Vector Embedding Models with Sentence Transformers\n\n[Update on GitHub](https://github.com/huggingface/blog/blob/main/train-multi-vector-encoder.md)\n\n[Sentence Transformers](https://sbert.net/)is a Python library for using and training embedding and reranker models for a wide range of applications, such as retrieval augmented generation, semantic search, semantic textual similarity, and more. Its v6.0 update introduces a fourth model type:\n\n`MultiVectorEncoder`\n\n, for ColBERT-style late interaction retrieval, alongside a complete training approach for it. In this blogpost, I'll show you how to use it to finetune a multi-vector model that outperforms general-purpose retrievers on your data. This method can also train strong new multi-vector models from scratch. Everything below runs on `pip install -U \"sentence-transformers[train]\"`\n\n.\nFinetuning multi-vector models involves several components: the model itself, datasets, loss functions, training arguments, evaluators, and the trainer class. I'll have a look at each of these components, accompanied by practical examples of how they can be used for finetuning strong multi-vector models.\n\nLastly, in the [Evaluation](#evaluation) section, I'll show you that my finetuned [multi-vector-encoder/mLateOn-medical](https://huggingface.co/multi-vector-encoder/mLateOn-medical) model, trained in 14.5 hours on a single RTX 3090 alongside this blogpost, easily outperforms every general-purpose retrieval model I could find on my medical retrieval evaluation: dense, sparse, lexical, and multi-vector alike.\n\nIf you're interested in finetuning dense embedding models, sparse embedding models, or rerankers instead, then consider reading through my prior [Training and Finetuning Embedding Models](https://huggingface.co/blog/train-sentence-transformers), [Training and Finetuning Sparse Embedding Models](https://huggingface.co/blog/train-sparse-encoder), and [Training and Finetuning Reranker Models](https://huggingface.co/blog/train-reranker) blogposts.\n\nThis blogpost is about\n\ntrainingmulti-vector models. If you want to learn how tousethem, from loading and encoding to indexing in vector databases, see the companion[Multi-Vector (Late Interaction) Embedding Models with Sentence Transformers]blogpost.\n\n## Table of Contents\n\n[What are Multi-Vector models?](#what-are-multi-vector-models)[Why Finetune?](#why-finetune)[Training Components](#training-components)[Model](#model)[Dataset](#dataset)[Loss Function](#loss-function)[Training Arguments](#training-arguments)[Evaluator](#evaluator)[Trainer](#trainer)[Evaluation](#evaluation)[Acknowledgements](#acknowledgements)[Additional Resources](#additional-resources)\n\n## What are Multi-Vector models?\n\nA dense embedding model compresses a whole text into a single vector, and similarity is one dot product between two such summaries. A multi-vector model (also called a late-interaction or ColBERT-style model) skips that compression. It keeps **one small vector per token** and scores a query against a document with the MaxSim operator, where every query token finds its best-matching document token and the scores are summed. Token-level matching preserves exactly the fine-grained signals that a single vector has to average away, which usually means stronger retrieval, at the cost of a bigger index.\n\nThe companion [Multi-Vector Embedding Models](https://huggingface.co/blog/multi-vector-encoder) blogpost covers the architecture, encoding, scoring, and indexing in detail, so I'll keep this section short and get to the training.\n\n## Why Finetune?\n\nFinetuning multi-vector models significantly improves their retrieval performance on your specific domain: the vocabulary, the query style, and the notion of relevance all differ between web search, legal discovery, code search, and scientific literature review. Because queries and documents are matched token by token, multi-vector models pick up fine-grained domain signals that single-vector models tend to average away, and they respond very well to even modest amounts of in-domain finetuning data.\n\nBeyond that, most released retrieval models were configured for short passages. The classic ColBERT checkpoints truncate documents at 180 or 300 tokens, and many popular dense models at 256 or 512, because their MS MARCO-style training data rarely goes beyond that. If your documents are long, these models silently discard most of every document before scoring it. On my medical evaluation with passages averaging 941 tokens, I measured that this truncation costs up to 0.24 NDCG@10, considerably more than any difference between model architectures. When you train your own model, you configure the document length that *your* data needs.\n\nLightOn ran into this same dynamic with code retrieval, where general [LateOn](https://huggingface.co/lightonai/LateOn) wasn't enough and they trained [LateOn-Code](https://huggingface.co/lightonai/LateOn-Code). Your domain, whether that's medical, legal, financial, or your company's internal documents, is not getting an official model. This blogpost shows you how to build it yourself, in a matter of hours, on a single consumer GPU.\n\n## Training Components\n\nTraining MultiVectorEncoder models involves the following components:\n\n: The model to finetune or the architecture to build fresh.**Model**: The data used for training and evaluation.** Dataset**: A function that measures the model's performance and guides the optimization process.** Loss Function**(optional): Parameters that impact training performance, tracking, and debugging.** Training Arguments**(optional): A class for evaluating the model before, during, or after training.** Evaluator**: Brings together all training components.** Trainer**\n\nLet's take a closer look at each component.\n\n## Model\n\nMulti-vector training gives you a real choice of starting point, and it matters more than you might expect.\n\n### Finetuning an existing multi-vector model\n\nIf you want to further finetune an existing multi-vector model, you don't have to worry about the architecture at all:\n\n``` python\nfrom sentence_transformers import MultiVectorEncoder\n\n# Loading in fp32 is preferred for training if your memory can handle it\nmodel = MultiVectorEncoder(\n    \"lightonai/mLateOn-unsupervised\",\n    model_kwargs={\"torch_dtype\": \"float32\"},\n    processor_kwargs={\"model_max_length\": 8192},  # the tokenizer-level token limit\n)\n```\n\nThe checkpoint brings its own recipe along: its query and document marker tokens, its projection head, its scoring skiplist. For finetuning, you generally want to keep all of that and change only what your data demands. The first thing to check is the length configuration, since many released checkpoints cap documents at 180 to 512 tokens (see [Why Finetune?](#why-finetune)), and my medical passages run to 1,400 tokens. The mLateOn family already serves the backbone's full 8192 token context, but if your starting checkpoint carries caps, lift them:\n\n```\n# Let the model read full documents instead of the caps it was trained with,\n# e.g. GTE-ModernColBERT-v1 ships with query_length=48 and document_length=300\nmodel[0].query_length = None\nmodel[0].document_length = None\n```\n\nWith the per-task caps unset, truncation falls back to the tokenizer's `model_max_length`\n\n, which is why I configure that limit at load time above.\n\nI made one more change, adding a punctuation skiplist that excludes punctuation tokens from document-side scoring and storage. In a 4-way ablation (none, punctuation, stopwords, both) it modestly won on quality, and it shrinks the document index by 9.6% on this data for free:\n\n``` python\nimport string\n\n# model[2] is the MultiVectorMask module\nmodel[2].skiplist_words = list(string.punctuation)\nmodel[2].resolve_with_tokenizer(model.tokenizer)  # token ids are cached, so re-resolve after changing\n```\n\n### Building one from a base transformer\n\nYou can also point `MultiVectorEncoder`\n\nat any base transformer, and a fresh, randomly initialized token-level projection is appended for you:\n\n``` python\nfrom sentence_transformers import MultiVectorEncoder\n\nmodel = MultiVectorEncoder(\"answerdotai/ModernBERT-base\", model_kwargs={\"torch_dtype\": \"float32\"})\n# MultiVectorEncoder(\n#   (0): Transformer({..., 'architecture': 'ModernBertModel'})\n#   (1): Dense({'in_features': 768, 'out_features': 128, 'bias': False, ...})\n#   (2): MultiVectorMask({'skiplist_words': [], 'skiplist_tasks': ['document'], ...})\n#   (3): Normalize({...})\n# )\n```\n\nThat's the classic ColBERT pipeline: a `Transformer`\n\nproducing contextualized token embeddings, a token-level `Dense`\n\nprojecting each of them down to 128 dimensions, a `MultiVectorMask`\n\ndeciding which tokens count during scoring, and a token-level `Normalize`\n\n. The projection starts random, so training is required before this model is useful. Interestingly, this works with strong dense embedding backbones too. A fresh projection on [Alibaba-NLP/gte-modernbert-base](https://huggingface.co/Alibaba-NLP/gte-modernbert-base) reached within 0.03 of the existing-checkpoint starting points in my experiments, from nothing but the projection and 25k training pairs.\n\nThe classic ColBERT tokenization tricks (`[MASK]`\n\nquery expansion, `[Q]`\n\n/ `[D]`\n\nprefix tokens, a document length cap, a punctuation skiplist) are all off by default and configurable. See [Creating Custom Models](https://sbert.net/docs/multi_vector_encoder/usage/custom_models.html) for the full set. For what it's worth, I tested `[MASK]`\n\nquery expansion in four configurations for my domain finetune and none of them made a measurable difference, so don't feel obliged to reach for the classic recipe.\n\n### Which starting point should you pick?\n\nI measured this directly while preparing this blogpost, taking six starting points and training each with the identical recipe on 25k medical question-passage pairs from [MIRIAD](https://huggingface.co/datasets/tomaarsen/miriad-4.4M-split), then evaluating on 1,000 held-out questions against a 50,000 passage corpus:\n\n| Starting point | Zero-shot NDCG@10 | After 25k pairs | Delta |\n|---|---|---|---|\n|\n\n**0.9398****+0.0311**[lightonai/mLateOn](https://huggingface.co/lightonai/mLateOn)[lightonai/LateOn-unsupervised](https://huggingface.co/lightonai/LateOn-unsupervised)**0.9206****+0.0180**[lightonai/LateOn](https://huggingface.co/lightonai/LateOn)[lightonai/GTE-ModernColBERT-v1](https://huggingface.co/lightonai/GTE-ModernColBERT-v1)[gte-modernbert-base](https://huggingface.co/Alibaba-NLP/gte-modernbert-base)The result surprised me, and it replicated across two model families. *The `-unsupervised`\n\ncheckpoints adapt to a new domain far better than their finished siblings, overtaking them despite starting lower. These checkpoints sit after large-scale contrastive pretraining but before supervised finetuning on general retrieval, so they carry all the late-interaction structure with none of the general-purpose tuning that domain training then has to undo. The finished checkpoints, by contrast, barely moved or even regressed, at every learning rate I tried.\n\nSo, if the model family you like publishes a pre-supervised checkpoint, start there. If not, a fresh projection on a strong retrieval-pretrained backbone is a close runner-up. Continuing from a fully finished checkpoint is the weakest option for domain adaptation, despite being the most natural-feeling one.\n\n## Dataset\n\nThe [ MultiVectorEncoderTrainer](https://sbert.net/docs/package_reference/multi_vector_encoder/trainer.html) uses\n\n[or](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset)\n\n`datasets.Dataset`\n\n[instances for training and evaluation. You can load data from the](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.DatasetDict)\n\n`datasets.DatasetDict`\n\n[Hugging Face Datasets Hub](https://huggingface.co/datasets)or use local data in whatever format you prefer (e.g. CSV, JSON, Parquet, Arrow, or SQL).\n\n**Note:** Lots of public datasets that work out of the box with Sentence Transformers have been tagged with `sentence-transformers`\n\non the Hugging Face Hub, so you can easily find them on [https://huggingface.co/datasets?other=sentence-transformers](https://huggingface.co/datasets?other=sentence-transformers). Consider browsing through these to find ready-to-go datasets that might be useful for your tasks, domains, or languages.\n\n### Data on the Hugging Face Hub\n\nYou can use the [ load_dataset](https://huggingface.co/docs/datasets/main/en/package_reference/loading_methods#datasets.load_dataset) function to load data from datasets on the Hub:\n\n``` python\nfrom datasets import load_dataset\n\ntrain_dataset = load_dataset(\"tomaarsen/miriad-4.4M-split\", split=\"train\")\n\nprint(train_dataset)\n\"\"\"\nDataset({\n    features: ['question', 'passage_text'],\n    num_rows: 4467542\n})\n\"\"\"\n```\n\nThis is the dataset I'll train on in this blogpost: 4.4 million medical questions from [MIRIAD](https://huggingface.co/datasets/miriad/miriad-4.4M), each paired with the source passage that contains its answer (averaging 941 tokens). Simple (query, relevant passage) pairs like these are the easiest retrieval training data to collect for your own domain, and as you'll see, they're all you need.\n\n### Local Data\n\nYou can also use [ load_dataset](https://huggingface.co/docs/datasets/main/en/package_reference/loading_methods#datasets.load_dataset) for loading local data in common file formats:\n\n``` python\nfrom datasets import load_dataset\n\ndataset = load_dataset(\"csv\", data_files=\"my_file.csv\")\n# or\ndataset = load_dataset(\"json\", data_files=\"my_file.json\")\n```\n\nAnd if your local data requires pre-processing, you can use [ datasets.Dataset.from_dict](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.from_dict) to initialize your dataset with a dictionary of lists:\n\n``` python\nfrom datasets import Dataset\n\nqueries = []\ndocuments = []\n# Open a file, perform preprocessing, filtering, cleaning, etc.\n# and append to the lists\n\ndataset = Dataset.from_dict({\n    \"query\": queries,\n    \"document\": documents,\n})\n```\n\n### Dataset Format\n\nIt is important that your dataset format matches your loss function (or that you choose a loss function that matches your dataset format). Verifying whether a dataset format works with a loss function involves two steps:\n\n- If your loss function requires a\n*Label*according to the[Loss Overview](https://sbert.net/docs/multi_vector_encoder/loss_overview.html)table, then your dataset must have a**column named \"label\" or \"score\"**. This column is automatically taken as the label. - All columns not named \"label\" or \"score\" are considered\n*Inputs*according to the[Loss Overview](https://sbert.net/docs/multi_vector_encoder/loss_overview.html)table. The number of remaining columns must match the number of valid inputs for your chosen loss. The names of these columns are**irrelevant**, only the** order matters**.\n\nThere are two multi-vector specific conventions on top of this:\n\n- Positional query and document assignment: the first column is embedded as the\n*query*and all following columns as*documents*, regardless of the column names. This default can be overridden per column via the standard`router_mapping`\n\ntraining argument. - Knowledge distillation format: one column per candidate document, i.e.\n`(query, document_1, ..., document_N, scores)`\n\nwhere`scores`\n\nis a list of N teacher scores per row. For KD datasets that store query and document*IDs*alongside separate text datasets (e.g.[lightonai/ms-marco-en-bge](https://huggingface.co/datasets/lightonai/ms-marco-en-bge)), you can useto resolve the IDs to texts on the fly.`resolve_ids`\n\n## Loss Function\n\nLoss functions quantify how well a model performs for a given batch of data, allowing an optimizer to update the model weights to produce more favourable (i.e., lower) loss values. The right loss function for your task depends on the data you have and what you're trying to achieve. You can find a full list of options in the [Loss Overview](https://sbert.net/docs/multi_vector_encoder/loss_overview.html).\n\nFor the common case of question-answer or question-passage pairs, the workhorse is in-batch negatives training with [ MultiVectorMultipleNegativesRankingLoss](https://sbert.net/docs/package_reference/multi_vector_encoder/losses.html#multivectormultiplenegativesrankingloss), where every other document in the batch acts as a negative for each query. Bigger batches mean more negatives and stronger training, so in practice you'll want its GradCache variant,\n\n[, which decouples the effective batch size from what fits on your GPU:](https://sbert.net/docs/package_reference/multi_vector_encoder/losses.html#cachedmultivectormultiplenegativesrankingloss)\n\n`CachedMultiVectorMultipleNegativesRankingLoss`\n\n``` python\nfrom sentence_transformers import MultiVectorEncoder\nfrom sentence_transformers.multi_vector_encoder.losses import CachedMultiVectorMultipleNegativesRankingLoss\n\nmodel = MultiVectorEncoder(\"lightonai/mLateOn-unsupervised\", model_kwargs={\"torch_dtype\": \"float32\"})\n\nloss = CachedMultiVectorMultipleNegativesRankingLoss(\n    model=model,\n    mini_batch_size=16,  # how many documents to encode per chunk: bounds memory, not quality\n)\n```\n\nThe `mini_batch_size`\n\nparameter bounds the memory by encoding documents in chunks of this size, while the effective contrastive batch size (128 in my run below, and in my ablations bigger batches bought nothing further) stays a free choice. GradCache guarantees identical results regardless of the chunk size, so lower it for smaller GPUs at only a wall-clock cost. When your document lengths vary a lot, consider its sibling `mini_batch_num_tokens`\n\n, which packs each chunk to a total token budget instead of a document count, so a chunk of unusually long documents can never spike your memory (my `mini_batch_size=16`\n\nat roughly 940 tokens per document corresponds to `mini_batch_num_tokens=15_000`\n\n).\n\nOne multi-vector specific trap is that the contrastive losses default to `scale=1.0`\n\n, unlike the dense embedding equivalent which defaults to `scale=20.0`\n\n. That 20.0 exists because a cosine similarity is a single value in [-1, 1], too narrow a range for a sharp softmax. A MaxSim score instead sums one best-match similarity per query token, so it already spans roughly [0, query_length]: a 32-token query can score up to 32. So don't copy `scale=20.0`\n\nover from a dense training script, since it would saturate the softmax and kill your gradients.\n\nFor distillation from a stronger teacher, which is how the strongest general-purpose late-interaction models are trained, see [ MultiVectorDistillKLDivLoss](https://sbert.net/docs/package_reference/multi_vector_encoder/losses.html#multivectordistillkldivloss) and the Knowledge Distillation tab in the\n\n[Training Overview](https://sbert.net/docs/multi_vector_encoder/training_overview.html#trainer)documentation.\n\n## Training Arguments\n\nYou can customize the training process using the [ MultiVectorEncoderTrainingArguments](https://sbert.net/docs/package_reference/multi_vector_encoder/training_args.html) class. This class lets you adjust parameters that can impact training speed and help you understand what's happening during training.\n\nFor more information on the most useful training arguments, check out the [Multi-Vector Encoder > Training Overview > Training Arguments](https://sbert.net/docs/multi_vector_encoder/training_overview.html#training-arguments). It's worth reading to get the most out of your training.\n\nHere's an example, using the values from my actual training run:\n\n``` python\nfrom sentence_transformers import MultiVectorEncoderTrainingArguments\nfrom sentence_transformers.base.sampler import BatchSamplers\n\nargs = MultiVectorEncoderTrainingArguments(\n    # Required parameter:\n    output_dir=\"models/mLateOn-medical\",\n    # Optional training parameters:\n    num_train_epochs=1,\n    per_device_train_batch_size=128,  # the effective contrastive batch, thanks to GradCache\n    per_device_eval_batch_size=16,\n    learning_rate=1e-4,\n    warmup_steps=0.05,\n    prompts={\"question\": \"[Q] \", \"passage_text\": \"[D] \"},  # the checkpoint's markers, keyed by training column\n    fp16=False,  # Set to True if you have a GPU that supports FP16\n    bf16=True,  # Set to True if you have a GPU that supports BF16\n    batch_sampler=BatchSamplers.NO_DUPLICATES,  # in-batch negatives benefit from no duplicates\n    # Optional tracking/debugging parameters:\n    eval_strategy=\"steps\",\n    eval_steps=0.1,\n    save_strategy=\"steps\",\n    save_steps=0.05,\n    logging_steps=0.01,\n    run_name=\"mLateOn-medical\",  # Will be used in e.g. Trackio, W&B, etc.\n)\n```\n\nA few of these deserve a comment:\n\n`prompts`\n\n: training does not automatically apply the prompts stored in the model, so map them onto your training columns explicitly. Here that is the checkpoint's`[Q]`\n\nmarker for the question column and`[D]`\n\nfor the passage column, keeping training consistent with inference.`max_length`\n\n(deliberately not set): this argument caps tokenization during*training only*, for when you want cheaper training than the model's full serving length. I measured what that shortcut costs on this data. Training at 512 tokens lost about 0.015 NDCG@10 for about 2x the speed, and the deficit did not shrink with more data, because the model simply never sees what got cut off. Leave it unset so training matches inference, unless you need the speedup more than the quality.`learning_rate=1e-4`\n\n: after a sweep from 5e-6 to 2e-4, I had the best luck with this higher-than-usual learning rate.\n\n## Evaluator\n\nTo track your model's performance during training, you can pass an `eval_dataset`\n\nto the trainer for evaluation loss, but concrete retrieval metrics are much more informative. Sentence Transformers includes the following built-in evaluators for multi-vector models:\n\n| Evaluator | Required Data |\n|---|---|\n`MultiVectorInformationRetrievalEvaluator` |\n\n`MultiVectorNanoBEIREvaluator`\n\n`MultiVectorTripletEvaluator`\n\n`MultiVectorRerankingEvaluator`\n\n`{'query': '...', 'positive': [...], 'negative': [...]}`\n\ndictionaries`MultiVectorDistillationEvaluator`\n\nFor domain finetuning, the [ MultiVectorInformationRetrievalEvaluator](https://sbert.net/docs/package_reference/multi_vector_encoder/evaluation.html#multivectorinformationretrievalevaluator) built from your own held-out data is the one that matters. One tip on constructing it is that the corpus should be hard enough that models can be told apart. In my case the MIRIAD questions are generated from their own source passages, which makes retrieval unusually easy. Against just the 10k gold passages, nearly every model scored above 0.97 NDCG@10. If your evaluation saturates like that, add\n\n*distractor*passages (I use deduplicated passages from the training split) until the scores spread out:\n\n``` python\nfrom datasets import load_dataset\nfrom sentence_transformers.multi_vector_encoder.evaluation import MultiVectorInformationRetrievalEvaluator\n\ndataset = load_dataset(\"tomaarsen/miriad-4.4M-split\")\n\n# Gold: 1,000 evaluation questions, each mapping to its own passage, with the\n# eval split's full ~10k unique passages as the initial corpus\ncorpus = {}\nqueries = {}\nrelevant_docs = {}\npassage_to_id = {}\nfor idx, row in enumerate(dataset[\"eval\"]):\n    if row[\"passage_text\"] not in passage_to_id:\n        passage_to_id[row[\"passage_text\"]] = f\"p{len(passage_to_id)}\"\n        corpus[passage_to_id[row[\"passage_text\"]]] = row[\"passage_text\"]\n    if idx < 1_000:\n        queries[f\"q{idx}\"] = row[\"question\"]\n        relevant_docs[f\"q{idx}\"] = {passage_to_id[row[\"passage_text\"]]}\n\n# Distractors: unique train passages that make the haystack realistic\nseen = set(passage_to_id)\nfor row in dataset[\"train\"]:\n    if len(corpus) >= 200_000:\n        break\n    if row[\"passage_text\"] not in seen:\n        seen.add(row[\"passage_text\"])\n        corpus[f\"d{len(corpus)}\"] = row[\"passage_text\"]\n\nevaluator = MultiVectorInformationRetrievalEvaluator(\n    queries=queries,\n    corpus=corpus,\n    relevant_docs=relevant_docs,\n    name=\"miriad-dev\",\n    batch_size=16,\n)\n# results = evaluator(model)\n```\n\n## Trainer\n\nThe [ MultiVectorEncoderTrainer](https://sbert.net/docs/package_reference/multi_vector_encoder/trainer.html) is where all previous components come together. Here is the complete script that trained\n\n[multi-vector-encoder/mLateOn-medical](https://huggingface.co/multi-vector-encoder/mLateOn-medical), the model from the introduction:\n\n``` python\nimport logging\nimport string\nimport traceback\n\nfrom datasets import load_dataset\n\nfrom sentence_transformers import (\n    MultiVectorEncoder,\n    MultiVectorEncoderModelCardData,\n    MultiVectorEncoderTrainer,\n    MultiVectorEncoderTrainingArguments,\n)\nfrom sentence_transformers.base.sampler import BatchSamplers\nfrom sentence_transformers.multi_vector_encoder.evaluation import MultiVectorInformationRetrievalEvaluator\nfrom sentence_transformers.multi_vector_encoder.losses import CachedMultiVectorMultipleNegativesRankingLoss\n\nlogging.basicConfig(format=\"%(asctime)s - %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\", level=logging.INFO)\n\ndef main():\n    # 1. Load the starting checkpoint: contrastively pretrained, not yet supervised\n    # Loading in fp32 is preferred for training if your memory can handle it\n    model = MultiVectorEncoder(\n        \"lightonai/mLateOn-unsupervised\",\n        model_kwargs={\"torch_dtype\": \"float32\"},\n        processor_kwargs={\"model_max_length\": 8192},\n        model_card_data=MultiVectorEncoderModelCardData(\n            language=\"en\",\n            license=\"apache-2.0\",\n            model_name=\"mLateOn finetuned on MIRIAD medical retrieval\",\n        ),\n    )\n\n    # 2. Lift the per-task length caps so training and inference see full medical passages\n    model[0].query_length = None\n    model[0].document_length = None\n\n    # 3. Skip punctuation tokens during scoring: a small quality win and a 9.6% smaller index\n    model[2].skiplist_words = list(string.punctuation)\n    model[2].resolve_with_tokenizer(model.tokenizer)\n\n    # 4. Load 1 million medical question-passage pairs\n    train_dataset = load_dataset(\"tomaarsen/miriad-4.4M-split\", split=\"train\").select(range(1_000_000))\n\n    # 5. In-batch negatives with GradCache: large effective batch, memory-bounded chunks\n    loss = CachedMultiVectorMultipleNegativesRankingLoss(model=model, mini_batch_size=16)\n\n    # 6. A light dev evaluator to watch progress during training: 500 held-out questions\n    # against the eval split's ~10k unique passages. The full 200k protocol runs afterwards.\n    eval_split = load_dataset(\"tomaarsen/miriad-4.4M-split\", split=\"eval\")\n    corpus, queries, relevant_docs, passage_to_id = {}, {}, {}, {}\n    for idx, row in enumerate(eval_split):\n        if row[\"passage_text\"] not in passage_to_id:\n            passage_to_id[row[\"passage_text\"]] = f\"p{len(passage_to_id)}\"\n            corpus[passage_to_id[row[\"passage_text\"]]] = row[\"passage_text\"]\n        if idx < 500:\n            queries[f\"q{idx}\"] = row[\"question\"]\n            relevant_docs[f\"q{idx}\"] = {passage_to_id[row[\"passage_text\"]]}\n    dev_evaluator = MultiVectorInformationRetrievalEvaluator(\n        queries=queries, corpus=corpus, relevant_docs=relevant_docs, name=\"miriad-dev\", batch_size=16\n    )\n\n    # 7. Training arguments, as discussed above\n    run_name = \"mLateOn-medical\"\n    args = MultiVectorEncoderTrainingArguments(\n        output_dir=f\"models/{run_name}\",\n        num_train_epochs=1,\n        per_device_train_batch_size=128,\n        per_device_eval_batch_size=16,\n        learning_rate=1e-4,\n        warmup_steps=0.05,\n        prompts={\"question\": \"[Q] \", \"passage_text\": \"[D] \"},\n        fp16=False,  # Set to True if you have a GPU that supports FP16\n        bf16=True,  # Set to True if you have a GPU that supports BF16\n        batch_sampler=BatchSamplers.NO_DUPLICATES,\n        eval_strategy=\"steps\",\n        eval_steps=0.1,\n        save_strategy=\"steps\",\n        save_steps=0.05,\n        logging_steps=0.01,\n        run_name=run_name,\n    )\n\n    # 8. Create a trainer & train\n    trainer = MultiVectorEncoderTrainer(\n        model=model,\n        args=args,\n        train_dataset=train_dataset,\n        loss=loss,\n        evaluator=dev_evaluator,\n    )\n    trainer.train()\n\n    # 9. Save the trained model\n    model.save_pretrained(f\"models/{run_name}/final\")\n\n    # 10. (Optional) Push it to the Hugging Face Hub\n    try:\n        model.push_to_hub(run_name)\n    except Exception:\n        logging.error(f\"Error uploading model to the Hugging Face Hub:\\n{traceback.format_exc()}\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nThat's the whole recipe: a pre-supervised checkpoint, a million domain pairs, in-batch negatives, full document length, and a higher-than-usual learning rate. The run took 14.5 hours on my single RTX 3090 at a peak of 17.5 GB VRAM, and every one of those choices was the winner of a measured comparison rather than a guess.\n\nFor readers on smaller budgets, my scaling experiments put 100k pairs (75 minutes of training) within 0.012 NDCG@10 of the full million-pair run. Most of the gain comes in the first hour.\n\n### Callbacks\n\nThe MultiVectorEncoder trainer supports various [ transformers.TrainerCallback](https://huggingface.co/docs/transformers/main_classes/callback#transformers.TrainerCallback) subclasses, including:\n\nfor logging training metrics to W&B if`WandbCallback`\n\n`wandb`\n\nis installedfor logging training metrics to TensorBoard if`TensorBoardCallback`\n\n`tensorboard`\n\nis accessiblefor tracking carbon emissions during training if`CodeCarbonCallback`\n\n`codecarbon`\n\nis installed\n\nEnable these via the `report_to`\n\ntraining argument, e.g. `report_to=[\"wandb\", \"codecarbon\"]`\n\n, with the required dependencies installed. It defaults to `\"none\"`\n\n, and `report_to=\"all\"`\n\nactivates every integration whose dependency is installed.\n\nRefer to the [Transformers Callbacks documentation](https://huggingface.co/docs/transformers/en/main_classes/callback) for more information on these callbacks and how to create your own.\n\n### Multi-Dataset Training\n\nTypically, top-performing general-purpose models are trained on multiple datasets simultaneously. However, this approach can be challenging due to the varying formats of each dataset. Fortunately, the [ MultiVectorEncoderTrainer](https://sbert.net/docs/package_reference/multi_vector_encoder/trainer.html) allows you to train on multiple datasets without requiring a uniform format. Additionally, it provides the flexibility to apply different loss functions to each dataset. Here are the steps to train with multiple datasets at once:\n\n- Use a dictionary of\ninstances (or a`datasets.Dataset`\n\n) as the`datasets.DatasetDict`\n\n`train_dataset`\n\n(and optionally also`eval_dataset`\n\n). - (Optional) Use a dictionary of loss functions mapping dataset names to losses. Only required if you wish to use different loss functions for different datasets.\n\nEach training/evaluation batch will only contain samples from one of the datasets. The order in which batches are sampled from the multiple datasets is defined by the [ MultiDatasetBatchSamplers](https://sbert.net/docs/package_reference/sentence_transformer/sampler.html#sentence_transformers.training_args.MultiDatasetBatchSamplers) enum, which can be passed to the\n\n[via](https://sbert.net/docs/package_reference/multi_vector_encoder/training_args.html)\n\n`MultiVectorEncoderTrainingArguments`\n\n`multi_dataset_batch_sampler`\n\n. Valid options are:`MultiDatasetBatchSamplers.ROUND_ROBIN`\n\n: Round-robin sampling from each dataset until one is exhausted. With this strategy, it's likely that not all samples from each dataset are used, but each dataset is sampled from equally.`MultiDatasetBatchSamplers.PROPORTIONAL`\n\n(default): Sample from each dataset in proportion to its size. With this strategy, all samples from each dataset are used and larger datasets are sampled from more frequently.\n\n## Evaluation\n\nTo find out where the finetuned model stands, I evaluated it against over 50 retrieval model configurations across four architecture families on the MIRIAD evaluation set, built exactly as in the [Evaluator](#evaluator) section above, with 1,000 held-out medical questions searching 200,000 unique passages (the 10k gold passages hidden among 190k deduplicated distractors from the training split). This corpus is four times the size of the 50,000-passage one from [Which starting point should you pick?](#which-starting-point-should-you-pick), so scores are not comparable between the two tables.\n\nThe headline results, with the full table in the collapsible below:\n\n| Model | Family | NDCG@10 |\n|---|---|---|\nmulti-vector-encoder/mLateOn-medical (mine) |\n\n**Multi-vector, finetuned****0.9139**[lightonai/mLateOn](https://huggingface.co/lightonai/mLateOn)[lightonai/GTE-ModernColBERT-v1](https://huggingface.co/lightonai/GTE-ModernColBERT-v1)(cap lifted)[Qwen/Qwen3-Embedding-4B](https://huggingface.co/Qwen/Qwen3-Embedding-4B)[voyageai/voyage-4-nano](https://huggingface.co/voyageai/voyage-4-nano)[naver/splade-v3](https://huggingface.co/naver/splade-v3)The finetuned model tops the table, beating the strongest zero-shot model of any architecture by +0.062 NDCG@10. In other words, the strongest zero-shot model returns the right passage as the very first hit for 75.8% of the queries, while the finetuned model does so for 84.9%, cutting the rank-1 error by more than a third.\n\nThe architecture pattern is just as clear, with the top of the table exclusively late interaction. On long documents, one vector per token beats one vector per document, even at matched training and matched backbones. DenseOn and LateOn share training data and architecture except for the head, and the late-interaction sibling wins by +0.12, with the multilingual pair (mDenseOn and mLateOn) replicating this at +0.13. Scale doesn't rescue single vectors either. [Qwen3-Embedding-4B](https://huggingface.co/Qwen/Qwen3-Embedding-4B), the strongest dense model with roughly 33x the active (non-embedding) parameters of mine, still stops 0.13 short, and the 8B version scores lower than the 4B.\n\nBM25 also performs surprisingly well, beating every sparse model, every truncation-capped multi-vector model, and all but three dense models: the multi-billion [Qwen3-Embedding-4B](https://huggingface.co/Qwen/Qwen3-Embedding-4B) and [8B](https://huggingface.co/Qwen/Qwen3-Embedding-8B), and [voyage-4-nano](https://huggingface.co/voyageai/voyage-4-nano), which reads its full 32k token context to edge past by just 0.006. Don't expect that to transfer to your own data though. MIRIAD's questions are generated from the passages, so the lexical overlap between a query and its gold passage is far larger than in typical retrieval, and BM25's unlimited context length lets it use every one of those overlapping words while most neural checkpoints truncate. A BM25 baseline is cheap and always worth running, just don't count on this margin.\n\nThe full field at a glance, sorted by score and colored by architecture family.\n\n## Click to see the full evaluation table\n\nModels marked `@N`\n\nare evaluated with their document length cap lifted to N tokens, since their native caps (180 to 512 tokens) would otherwise truncate the 941-token average passages. For every multi-vector model this lift was worth +0.08 to +0.24 NDCG@10 over the as-served row, and even the dense DenseOn gained +0.03 from the same treatment.\n\nNote that this does not mean that [multi-vector-encoder/mLateOn-medical](https://huggingface.co/multi-vector-encoder/mLateOn-medical) is the strongest model on *all* domains. It's simply the strongest in *my* domain. This is totally fine, as I just need this model to work well on my data.\n\nDon't underestimate the power of finetuning multi-vector models on your domain. Fourteen and a half hours on a single consumer GPU produced a model that no general-purpose retriever comes close to on this data, and the recipe is a single script with no teacher model and no mined negatives!\n\n### Optimizing the index\n\nThe fair objection to multi-vector retrieval is index size, and this domain is close to the worst case for it. Storing one vector per token, my model needs about 878 vectors per passage, so the 200,000-passage corpus takes roughly 45 GB at fp16, where a dense model needs well under 1 GB. Document length is what makes that gap so wide. The Natural Questions passages in the [companion post](https://huggingface.co/blog/multi-vector-encoder) average about 125 token vectors each, seven times fewer, so a corpus of short passages starts from a far smaller index than this one does. The [ HierarchicalTokenPooling](https://sbert.net/docs/package_reference/multi_vector_encoder/modules.html#hierarchicaltokenpooling) module compresses exactly this by clustering each document's token embeddings and storing the cluster means, keeping roughly\n\n`1 / pool_factor`\n\nof the vectors:\n\n``` python\nfrom sentence_transformers.multi_vector_encoder.modules import HierarchicalTokenPooling\n\npooling = HierarchicalTokenPooling(pool_factor=4)\ndocument_embeddings = model.encode_document(passages, token_pooling=pooling)\n```\n\nI measured it post-hoc on the finished model, with no pooling-aware training, and on long documents it is remarkably cheap.\n\nThe solid points are uncompressed embeddings, so that every family is counted the same way and scored with exact search. You would not deploy any of them like that, though. Dense indexes routinely use int8 or binary quantization with rescoring, sparse indexes compress their postings, and multi-vector indexes use PLAID-style residual compression. Don't read those points as the disk you need to buy, but as relative storage cost.\n\nToken pooling is the solid line. Halving the vector count costs 0.0033 NDCG@10 and leaves rank-1 accuracy untouched, and keeping only a quarter of them, at 11.2 GB, still scores 0.8991. The curve keeps going (I measured out to a tenth of the vectors, still at 0.8765) but there is little reason to push pooling that far once quantization is on the table, which is what the dashed line below is about.\n\nThe dashed line is what a real deployment might look like. I gave Omar Khattab early access to the model and the benchmark, and he measured these configurations with [fast-plaid](https://github.com/lightonai/fast-plaid) at 1-bit residual quantization, using compact 17-bit centroid ids and 18-bit document ids instead of its ordinary unpacked 64-bit integers, plus document-side pruning:\n\n| configuration | vectors kept | index | NDCG@10 |\n|---|---|---|---|\n| 1-bit PLAID, all vectors | 100% | 3.37 GB | 0.8984 |\n| 1-bit PLAID + pruning | 65% | 2.23 GB | 0.8830 |\n| 1-bit PLAID + pruning | 42% | 1.45 GB | 0.8642 |\n\nThat first row is 13x smaller than the raw embeddings, for 0.0155 NDCG@10. That is a far better trade than anywhere on the pooling curve. Quantization shrinks each vector while pooling and pruning cut how many you keep, so they compose, and quantization is the one to reach for first. Push further and the last row lands at 1.45 GB, *smaller* than the fp16 embeddings of [Qwen3-Embedding-8B](https://huggingface.co/Qwen/Qwen3-Embedding-8B) (1.64 GB), while scoring 0.0895 higher. The objection that multi-vector indexes are too big does not survive a properly configured index.\n\nThe pruning here is naive, meant only to establish that token reduction works on top of quantization, so read the bottom two rows as a floor rather than the frontier. If you would rather not hand-tune quantization at all, the [Indexing](https://huggingface.co/blog/multi-vector-encoder#indexing) section of the companion post covers fast-plaid, Qdrant, Weaviate, and Vespa.\n\nMulti-vector retrieval is only as expensive as its index. The raw embeddings for this corpus are 45 GB, and a properly configured index is at least 7x smaller at nearly the same accuracy. The index deserves as much of your attention as the checkpoint.\n\n## Acknowledgements\n\nThanks to [Omar Khattab](https://github.com/okhat) for measuring the quantized and pruned index configurations in [Optimizing the index](#optimizing-the-index), and for the discussions around late-interaction index costs.\n\n## Additional Resources\n\n### Training Examples\n\nThese pages have training examples with explanations as well as links to training scripts. You can use them to get familiar with the multi-vector training loop:\n\n[MIRIAD](https://sbert.net/examples/multi_vector_encoder/training/miriad/README.html): domain-specific training on medical retrieval, an earlier and simpler cousin of this blogpost's recipe[MS MARCO](https://sbert.net/examples/multi_vector_encoder/training/msmarco/README.html): contrastive and knowledge distillation recipes[Multimodal](https://sbert.net/examples/multi_vector_encoder/training/multimodal/README.html): ColPali-style visual document retrieval training[PEFT Adapters](https://sbert.net/examples/multi_vector_encoder/training/peft/README.html): parameter-efficient finetuning with LoRA\n\n### Documentation\n\nFor further learning, you may also want to explore the following resources on Sentence Transformers:\n\n[Installation](https://sbert.net/docs/installation.html)[Quickstart](https://sbert.net/docs/quickstart.html)[Usage](https://sbert.net/docs/multi_vector_encoder/usage/usage.html)[Creating Custom Models](https://sbert.net/docs/multi_vector_encoder/usage/custom_models.html)[Pretrained Models](https://sbert.net/docs/multi_vector_encoder/pretrained_models.html)[Training Overview](https://sbert.net/docs/multi_vector_encoder/training_overview.html)(This blogpost is a distillation of the Training Overview documentation)[Loss Overview](https://sbert.net/docs/multi_vector_encoder/loss_overview.html)[API Reference](https://sbert.net/docs/package_reference/multi_vector_encoder/index.html)\n\nAnd here is an advanced page that might interest you:\n\nAnd the companion blogpost, covering everything about *using* these models:", "url": "https://wpnews.pro/news/training-and-finetuning-multi-vector-embedding-models-with-sentence-transformers", "canonical_source": "https://huggingface.co/blog/train-multi-vector-encoder", "published_at": "2026-08-26 00:00:00+00:00", "updated_at": "2026-08-26 14:16:32.912581+00:00", "lang": "en", "topics": ["machine-learning", "natural-language-processing", "ai-research", "ai-tools", "ai-infrastructure"], "entities": ["Hugging Face", "Sentence Transformers", "MultiVectorEncoder", "ColBERT", "RTX 3090"], "alternates": {"html": "https://wpnews.pro/news/training-and-finetuning-multi-vector-embedding-models-with-sentence-transformers", "markdown": "https://wpnews.pro/news/training-and-finetuning-multi-vector-embedding-models-with-sentence-transformers.md", "text": "https://wpnews.pro/news/training-and-finetuning-multi-vector-embedding-models-with-sentence-transformers.txt", "jsonld": "https://wpnews.pro/news/training-and-finetuning-multi-vector-embedding-models-with-sentence-transformers.jsonld"}}