Sentence Transformers

Also known as: SBERT library

On this page 7

Sentence Transformers is an open-source Python library for computing dense vector embeddings of sentences, paragraphs and images, so that texts with similar meaning end up close together in vector space. Among AI frameworks & tools in artificial intelligence, it is the standard toolkit for semantic search, clustering, deduplication and the retrieval stage of retrieval-augmented generation (RAG). It is also known as the SBERT library, after the Sentence-BERT paper that introduced it.

The library was created in 2019 by Nils Reimers and Iryna Gurevych at the UKP Lab of TU Darmstadt and is now maintained by Hugging Face. It is built on PyTorch and Hugging Face Transformers, and it gives access to thousands of pretrained embedding models on the Hugging Face Hub through a single `encode` call.

How Sentence Transformers produces embeddings

A Sentence Transformers model turns text into a fixed-length vector by passing it through a transformer encoder and then a pooling layer. The encoder, typically a BERT, MPNet or MiniLM variant, emits one contextual vector per token; pooling collapses those token vectors into one sentence vector, most often by mean pooling over all non-padding tokens.

The key idea is the bi-encoder architecture. Each text is encoded independently, so a corpus can be embedded once, stored in a vector index and compared with any query using cosine similarity or the dot product. The original paper showed why this matters: finding the most similar pair among 10,000 sentences takes roughly 65 hours with a BERT cross-encoder but about 5 seconds with SBERT embeddings.

A typical pipeline consists of a small number of modules chained in sequence. The table below lists the common building blocks and what each contributes.

ModuleRoleTypical setting
TransformerProduces contextual token vectorsMiniLM, MPNet, BERT or XLM-R backbone
PoolingReduces tokens to one vectorMean pooling; CLS or max pooling in some models
DenseOptional projection to another sizeUsed to change embedding dimensions
NormalizeScales vectors to unit lengthMakes dot product equal cosine similarity
Modules in a typical Sentence Transformers pipeline

Model types and pretrained checkpoints

Sentence Transformers exposes three model classes, each with a different speed and accuracy profile. The SentenceTransformer class is the bi-encoder, CrossEncoder scores a pair of texts jointly, and SparseEncoder, added in version 5 in 2025, produces sparse lexical vectors in the style of SPLADE.

ClassOutputBest use
SentenceTransformerDense vector per textFirst-stage retrieval over millions of documents
CrossEncoderRelevance score per pairReranking the top 20 to 100 candidates
SparseEncoderSparse weighted vocabulary vectorHybrid search with inverted indexes
The three model classes compared

The choice of checkpoint matters more than any other setting. Small models such as all-MiniLM-L6-v2 produce 384-dimensional vectors and run quickly on a CPU, while larger models such as all-mpnet-base-v2 produce 768 dimensions with higher accuracy. Each checkpoint also has a maximum sequence length, often 256 to 512 tokens, beyond which input is silently truncated. Model quality is usually compared on the MTEB benchmark, although its scores do not always predict performance on a specific domain.

Sentence Transformers occupies a narrow, specialized layer: it creates embeddings, while neighboring tools load raw models, store vectors or orchestrate applications. The table shows where its responsibility begins and ends.

ToolMain jobRelationship
Hugging Face TransformersGeneral model loading and inferenceSupplies the underlying encoder
Sentence TransformersEmbedding and reranking modelsAdds pooling, losses and similarity utilities
FAISSVector similarity searchIndexes the embeddings it produces
LangChain and LlamaIndexApplication orchestrationCall it as an embedding component
Hosted embedding APIsRemote embeddings as a serviceAlternative when local inference is unwanted
Sentence Transformers next to neighboring tools

Running the library locally gives full control over data, cost and latency, which is why it is popular for private document collections. Hosted APIs remove the need for GPU capacity but send text to a third party and bind the index to one vendor’s model.

Training and fine-tuning embedding models

Fine-tuning adapts a pretrained model to a domain by learning from text pairs or triplets with a contrastive objective. Since version 3, training uses the SentenceTransformerTrainer, which follows the same pattern as the Hugging Face Trainer and supports multi-GPU runs, evaluation callbacks and logging.

The loss function defines what similarity means for the model. The most common choices are summarized below.

LossTraining dataTypical purpose
MultipleNegativesRankingLossAnchor and positive pairsRetrieval with in-batch negatives
CosineSimilarityLossPairs with a similarity scoreSemantic textual similarity
TripletLossAnchor, positive and negativeFine-grained ranking
MatryoshkaLossWraps another lossEmbeddings that can be truncated
Common training losses and the data they need

With MultipleNegativesRankingLoss, every other positive in the batch acts as a negative, so larger batch sizes usually improve results. Adding hard negatives, passages that look relevant but are not, often gives a larger gain than additional training epochs.

Deployment, limitations and common mistakes

In production, embeddings are usually computed in batches and stored in a vector database or a FAISS index. The library supports ONNX and OpenVINO backends for faster CPU inference, and embeddings can be quantized to int8 or binary to reduce storage by a factor of 4 to 32, at some cost in recall.

Most failures come from mismatched configuration rather than from the library itself. The table lists frequent symptoms and their fixes.

SymptomLikely causeFix
Long documents match poorlyText truncated at the sequence limitSplit documents into chunks
Search quality drops after an updateIndex built with a different modelRe-embed the whole corpus
Queries rank answers badlyMissing query or passage prefixUse the prompts the model card specifies
Scores look inconsistentMixing dot product and cosineNormalize vectors or use one metric
Frequent problems and how to fix them

Embeddings also have conceptual limits. They capture topical similarity well but handle negation, exact numbers and rare identifiers poorly, which is why many systems combine dense retrieval with keyword search and a cross-encoder reranker.

In plain words

Sentence Transformers turns sentences into lists of numbers. Each list works like an address on a map of meaning. Sentences that say similar things get addresses close to each other, even when they use different words.

This makes it possible to search by meaning. A question such as “How do I reset my password?” can find a help page titled “Recovering account access”. A normal keyword search would miss it. The key point is simple: the library measures closeness of meaning, not shared words.

A real-world example

A mid-sized software company wants an internal assistant that answers employee questions from about 40,000 support articles and policy documents. The engineering team splits each document into chunks of roughly 200 words and encodes them with a multilingual Sentence Transformers model on a single GPU. The full corpus embeds in under an hour, and the vectors go into a FAISS index.

At query time, the question is embedded, the top 50 chunks are retrieved and a CrossEncoder reranks them before the best five reach a language model. After the team fine-tunes the embedding model on 8,000 question and answer pairs from past support tickets, the share of questions answered from the correct document rises noticeably. The outcome is faster, more accurate answers without sending internal text to an external embedding service.