Finetuning Sentence Transformer models often heavily improves the performance of the model on your use case, because each task requires a different notion of similarity. For…
Training Overview
Why Finetune?
Finetuning Sentence Transformer models often heavily improves the performance of the model on your use case, because each task requires a different notion of similarity. For example, given news articles:
- "Apple launches the new iPad"
- "NVIDIA is gearing up for the next GPU generation"
Then the following use cases, we may have different notions of similarity:
- a model for classification of news articles as Economy, Sports, Technology, Politics, etc., should produce similar embeddings for these texts.
- a model for semantic textual similarity should produce dissimilar embeddings for these texts, as they have different meanings.
- a model for semantic search would not need a notion for similarity between two documents, as it should only compare queries and documents.
Also see Training Examples for numerous training scripts for common real-world applications that you can adopt.
Training Components
Training Sentence Transformer models involves between 4 to 6 components:
Model
Learn how to initialize the model for training.
Dataset
Learn how to prepare the data for training.
Loss Function
Learn how to prepare and choose a loss function.
Training Arguments
Learn which training arguments are useful.
Evaluator
Learn how to evaluate during and after training.
Trainer
Learn how to start the training process.
Model
Dataset
Dataset Format
Multimodal Datasets
Loss Function
Loss 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. This is the core of the training process.
Sadly, there is no single loss function that works best for all use-cases. Instead, which loss function to use greatly depends on your available data and on your target task. See Dataset Format to learn what datasets are valid for which loss functions. Additionally, the Loss Overview will be your best friend to learn about the options.
Training Arguments
Key Training Arguments for improving training performance
learning_rate
lr_scheduler_type
warmup_steps
num_train_epochs
max_steps
per_device_train_batch_size
per_device_eval_batch_size
auto_find_batch_size
fp16
bf16
load_best_model_at_end
metric_for_best_model
gradient_accumulation_steps
activation_checkpointing
eval_accumulation_steps
optim
batch_sampler
multi_dataset_batch_sampler
prompts
router_mapping
learning_rate_mapping
Key Training Arguments for observing training performance
eval_strategy
eval_steps
save_strategy
save_steps
save_total_limit
report_to
run_name
log_level
logging_steps
push_to_hub
hub_model_id
hub_strategy
hub_private_repo
args = SentenceTransformerTrainingArguments(
# Required parameter:
output_dir="models/mpnet-base-all-nli-triplet",
# Optional training parameters:
num_train_epochs=1,
per_device_train_batch_size=16,
per_device_eval_batch_size=16,
learning_rate=2e-5,
warmup_steps=0.1,
fp16=True, # Set to False if you get an error that your GPU can't run on FP16
bf16=False, # Set to True if you have a GPU that supports BF16
batch_sampler=BatchSamplers.NO_DUPLICATES, # losses that use "in-batch negatives" benefit from no duplicates
# Optional tracking/debugging parameters:
eval_strategy="steps",
eval_steps=0.1,
save_strategy="steps",
save_steps=0.1,
save_total_limit=2,
logging_steps=0.01,
run_name="mpnet-base-all-nli-triplet", # Will be used in W&B if `wandb` is installed
)
Evaluator
Trainer
Callbacks
Multi-Dataset Training
Deprecated Training
Best Base Embedding Models
The quality of your text embedding model depends on which transformer model you choose. Sadly we cannot infer from a better performance on e.g. the GLUE or SuperGLUE benchmark that this model will also yield better representations.
To test the suitability of transformer models, I use the training_nli_v2.py script and train on 560k (anchor, positive, negative)-triplets for 1 epoch with batch size 64. I then evaluate on 14 diverse text similarity tasks (clustering, semantic search, duplicate detection etc.) from various domains.
In the following table you find the performance for different models and their performance on this benchmark:
表格(14 行)
| Model | Performance (14 sentence similarity tasks) |
|---|---|
| microsoft/mpnet-base | 60.99 |
| nghuyong/ernie-2.0-en | 60.73 |
| microsoft/deberta-base | 60.21 |
| FacebookAI/roberta-base | 59.63 |
| google-t5/t5-base | 59.21 |
| google-bert/bert-base-uncased | 59.17 |
| distilbert/distilbert-base-uncased | 59.03 |
| nreimers/TinyBERT_L-6_H-768_v2 | 58.27 |
| google/t5-v1_1-base | 57.63 |
| nreimers/MiniLMv2-L6-H768-distilled-from-BERT-Large | 57.31 |
| albert/albert-base-v2 | 57.14 |
| microsoft/MiniLM-L12-H384-uncased | 56.79 |
| microsoft/deberta-v3-base | 54.46 |
Comparisons with CrossEncoder Training
End-to-End Example
For a complete end-to-end training example, see the Training and Finetuning Embedding Models blogpost. It applies the components described on this page to a real training task, then benchmarks the resulting embedding model against its base checkpoint and against existing models of various sizes. For multimodal embedding training (text + image + audio + video), see the Training and Finetuning Multimodal Embedding & Reranker Models blogpost, which performs the same kind of evaluation for a Visual Document Retrieval model.
Source and license
Source: Sentence Transformers documentation, adapted for this site. Licensing and attribution follow the terms of the upstream project.