Embedding models fine-tuned for different tasks can favor different kinds of sentence similarity. A weight merge combines compatible Sentence Transformers models into one checkpoint that can be saved and reused without running both parents at inference time.
Compatibility involves more than matching embedding dimensions. The models need matching architectures, module configurations, tokenizer vocabularies, and tensor shapes, with compatible tokenization and a common training ancestor. Quantized checkpoints and models with attached PEFT adapters are unsuitable for this API.
A merge can lose accuracy even when it loads successfully. Comparing both parents and the reloaded merge on the same STS Benchmark test split exposes that tradeoff for sentence similarity; choosing a production model still needs evaluation on its intended tasks.
Steps to merge Sentence Transformers models:
- Create a project virtual environment with Python 3.14 on Ubuntu 26.04.
$ python3 -m venv .venv
Python 3.14 on Linux ARM64 needs a source build of immutables with the compiler and headers installed below. The CPU path uses public MiniLM checkpoints and requires no Hugging Face account. Tested with Sentence Transformers 6.3.0.
Related: Create a Python virtual environment - Activate the project environment.
$ source .venv/bin/activate
- Refresh Ubuntu's package index.
$ sudo apt-get update
- Install the compiler and Python headers needed to build the merge dependency on Ubuntu.
$ sudo apt-get install build-essential python3-dev
The immutables dependency has no Python 3.14 wheel for Linux ARM64, so pip builds it from source.
- Install CPU-only PyTorch in the active environment.
$ python -m pip install torch \ --index-url https://download.pytorch.org/whl/cpuThis avoids downloading CUDA libraries for a CPU merge.
Related: How to install Sentence Transformers with pip - Install Sentence Transformers with its merge extra.
$ python -m pip install "sentence-transformers[merge]==6.3.0"
The extra installs mergekit and its datasets dependency. Merging holds the input models, result, and working tensors in memory; large checkpoints can need substantially more RAM than inference.
Related: Upstream model-merging documentation - Create merge_models.py in your text editor with the input checkpoints and output directory.
- merge_models.py
from pathlib import Path from datasets import load_dataset from sentence_transformers import SentenceTransformer from sentence_transformers.sentence_transformer.evaluation \ import EmbeddingSimilarityEvaluator output_dir = Path("merged-MiniLM-L6") if output_dir.exists(): raise FileExistsError( f"Choose a new output directory: {output_dir}" ) model_ids = [ "sentence-transformers/all-MiniLM-L6-v2", "sentence-transformers/multi-qa-MiniLM-L6-cos-v1", ] parents = [ SentenceTransformer(name, device="cpu") for name in model_ids ] for model in parents: model.max_seq_length = 256 dimension = model.get_embedding_dimension() print("Input dimensions:", dimension)
These are the compatible MiniLM inputs used by upstream. Both use a 256-token limit here so evaluation compares the same input length. Local checkpoint paths can replace the model IDs when their architecture, modules, and tokenizer are compatible. The directory guard prevents a rerun from overwriting an existing result.
- Append the shared STS test evaluator below the input-loading code.
data = load_dataset("sentence-transformers/stsb", split="test") evaluator = EmbeddingSimilarityEvaluator( sentences1=data["sentence1"], sentences2=data["sentence2"], scores=data["score"], name="stsb-test", main_similarity="cosine", similarity_fn_names=["cosine"], write_csv=False, ) print("STS test pairs:", len(data))
The evaluator compares cosine similarities with human similarity scores. Higher Spearman correlation means closer agreement with their ranking. The public test split supplies the same labeled pairs for each model.
- Append the weighted-merge code below the evaluator.
merged = SentenceTransformer.merge( models=parents, method="linear", parameters={"weight": [0.6, 0.4]}, ) merged.save_pretrained(str(output_dir)) print("Saved:", output_dir)
The weights give the first input a 60% contribution and the second 40%. The merge uses float32 on CPU by default and inherits configuration and prompts from the first input. Structural incompatibility raises an error rather than producing a usable merge.
- Append the reload and three-model comparison at the end of merge_models.py.
reloaded = SentenceTransformer(str(output_dir), device="cpu") print( "Reloaded dimensions:", reloaded.get_embedding_dimension(), ) print("Cosine Spearman:") for label, model in [ ("all-MiniLM", parents[0]), ("multi-qa", parents[1]), ("merged-reloaded", reloaded), ]: results = evaluator(model) score = results[evaluator.primary_metric] print(f"{label}: {score:.4f}")
The third score comes from the saved checkpoint, so its evaluation also tests whether the local model can be loaded and used for encoding.
- Save merge_models.py.
- Run merge_models.py for the three-model STS comparison. Example output:
$ python merge_models.py ##### snipped ##### Input dimensions: 384 Input dimensions: 384 STS test pairs: 1379 ##### snipped ##### Saved: merged-MiniLM-L6 ##### snipped ##### Reloaded dimensions: 384 Cosine Spearman: all-MiniLM: 0.8203 multi-qa: 0.7598 merged-reloaded: 0.8106
The first execution downloads models and data and may display an unauthenticated Hub warning; these public downloads do not require a token. The reloaded merge scores 0.8106, below the first parent’s 0.8203 on this split. The output directory remains available for subsequent model loading. STS scores measure sentence similarity, not retrieval quality or an improvement on every task.