Text retrieval sometimes needs to match individual query terms to different parts of a passage. A multi-vector encoder in Sentence Transformers can learn those matches from query–passage pairs and save the trained model for later retrieval.
ColBERT models retain a vector for each token instead of compressing a passage into one vector. Their MaxSim score combines the best passage-token match for each query token. Contrastive training raises the score of a relevant passage relative to other passages in the batch, so unrelated query–passage pairs provide the negative examples.
A small CPU run is suitable for learning the training and checkpoint-loading APIs before committing to a larger dataset. Eight support questions are enough to exercise that path, but a held-out ranking of two passages does not establish retrieval quality on a real corpus. Domain adaptation needs representative training pairs and a separate relevance evaluation set.
Steps to train a multi-vector encoder with Sentence Transformers:
- Activate a new Python 3.14 virtual environment in an empty project directory on Ubuntu 26.04.
$ source .venv/bin/activate
The CPU setup uses the distribution's Python 3.14 and was tested on Linux arm64. The environment must already exist before activation.
Related: Install Python on Ubuntu
Related: Create a Python virtual environment
Related: Activate a Python virtual environment - Install the CPU build of PyTorch in the active environment.
$ python -m pip install torch==2.9.1+cpu \ --index-url https://download.pytorch.org/whl/cpu
Installing the CPU wheel first avoids pulling CUDA runtime packages from PyPI. This path does not require a GPU.
- Install Sentence Transformers with its training dependencies.
$ python -m pip install "sentence-transformers[train]==6.3.0"
The training extra supplies datasets and accelerate in addition to the model dependencies. These pins belong in a new environment so they do not replace another application's package versions.
Related: Install Sentence Transformers with pip - Create a file named train_encoder.py in your text editor with the imports and training pairs below.
- train_encoder.py
from datasets import Dataset from sentence_transformers import ( MultiVectorEncoder, MultiVectorEncoderTrainer, MultiVectorEncoderTrainingArguments, ) from sentence_transformers.multi_vector_encoder import losses from sentence_transformers.sentence_transformer import ( training_args, ) train_data = Dataset.from_dict({ "query": [ "How do I reset my password?", "Where are my invoices?", "How do I create an API key?", "What is the refund period?", "How can I change my email address?", "How do I export a report?", "Where do I enable two-factor authentication?", "How do I cancel my subscription?", ], "positive": [ "Request a password reset link from the sign-in page.", "Download invoices from the billing page " "of your account.", "Create an API key in the developer dashboard.", "Refunds are available within thirty days of purchase.", "Update your email address in account settings.", "Export a report as a CSV file from the reports page.", "Enable two-factor authentication " "in security settings.", "Cancel your subscription from the billing settings.", ], })
Each row pairs a query with its relevant passage. Column order matters to the trainer, with the query first and the positive passage second. Other passages in the batch become negatives, so pairs about the same answer can create misleading negatives. The training documentation describes the supported dataset formats.
- Append the model and ranking loss at the end of train_encoder.py.
model = MultiVectorEncoder( "mixedbread-ai/mxbai-edge-colbert-v0-17m", device="cpu", model_kwargs={"dtype": "float32"}, ) model.max_seq_length = 64 loss = losses.MultiVectorMultipleNegativesRankingLoss(model)
The public 17-million-parameter ColBERT model keeps the CPU workload small. The first load downloads its weights and tokenizer without a sign-in. Float32 weights avoid mixed-precision requirements, and the 64-token limit suits these short passages but truncates longer text. The MS MARCO training example uses the same contrastive loss for passage retrieval.
- Append the CPU training configuration and checkpoint save at the end of train_encoder.py.
args = MultiVectorEncoderTrainingArguments( output_dir="training-output", use_cpu=True, per_device_train_batch_size=4, max_steps=10, learning_rate=2e-5, batch_sampler=training_args.BatchSamplers.NO_DUPLICATES, logging_steps=1, save_strategy="no", report_to="none", disable_tqdm=True, seed=42, ) trainer = MultiVectorEncoderTrainer( model=model, args=args, train_dataset=train_data, loss=loss, ) result = trainer.train() print(f"Training loss: {result.training_loss:.6f}") model.save_pretrained("trained-colbert") print("Saved model: trained-colbert")
Four pairs per batch provide in-batch negatives. The no-duplicates sampler prevents identical text within a batch, but cannot detect different passages with the same meaning. Ten optimizer steps keep this an introductory run. Periodic checkpoints are disabled; the final model, tokenizer, and module configuration are saved together in trained-colbert. External experiment reporting is disabled.
- Save train_encoder.py in the project directory.
- Run the training program in the active environment. Example output:
$ python train_encoder.py ##### snipped ##### Training loss: 1.182342 ##### snipped ##### Saved model: trained-colbert
The loss should remain finite. Ten steps demonstrate training and saving, rather than convergence on a domain dataset. A tokenizer-alignment message means the trainer is updating the model's padding metadata to match its tokenizer. The Hub may warn about unauthenticated requests; this public model does not require a token.
- Create a file named check_encoder.py in your text editor with the saved-model load and held-out inputs.
- check_encoder.py
import torch from sentence_transformers import MultiVectorEncoder model = MultiVectorEncoder( "trained-colbert", device="cpu", local_files_only=True ) query = "Where can I get a copy of my bill?" passages = [ "You can download your invoice from the billing page.", "Request a password reset link from the sign-in page.", ]
The query and invoice passage differ from the training pair. Loading by local directory uses the saved model without fetching a replacement from the Hub.
- Append token encoding and the ranking check at the end of check_encoder.py.
query_vectors = model.encode_query(query) passage_vectors = model.encode_document(passages) scores = model.similarity(query_vectors, passage_vectors)[0] assert torch.isfinite(scores).all(), "Non-finite ranking scores" assert scores[0] > scores[1], ( "The invoice passage did not rank first" ) for index in torch.argsort(scores, descending=True).tolist(): print(f"Passage {index}: {scores[index]:.4f}")
Encoding queries and documents separately preserves the model's retrieval-specific processing. Higher MaxSim scores indicate a closer match. The assertion fails if the invoice passage ties with or falls below the password passage.
- Save check_encoder.py in the project directory.
- Check the saved encoder's ranking in a fresh Python process. Example output:
$ python check_encoder.py ##### snipped ##### Passage 0: 12.4523 Passage 1: 12.3042
Passage 0, the invoice passage, should appear first with a higher score than passage 1. Scores can vary with package versions and hardware. This confirms that the checkpoint reloads and scores this held-out query; it does not measure improvement over the pretrained model.