Sentence Transformer
SBERT (Sentence-BERT)
An embedding model that converts an entire sentence into a fixed-size dense vector. Widely used for semantic search, sentence similarity calculation, clustering, and building RAG pipelines.
SBERT (Sentence-BERT)
An embedding model that converts an entire sentence into a fixed-size dense vector. Widely used for semantic search, sentence similarity calculation, clustering, and building RAG pipelines.
Sentence Transformer is a sentence embedding framework proposed in the 2019 paper "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks" by Reimers and Gurevych. With the existing BERT model, computing sentence similarity required feeding two sentences in together, so comparing all pairs among N sentences took O(N^2) time. Sentence Transformer embeds each sentence independently so that they can be compared quickly using cosine similarity, making large-scale semantic search practically feasible.
The core architecture of Sentence Transformer is the Siamese/Triplet Network structure. While sharing the same BERT (or another Transformer) model, it is trained so that embeddings move closer together when two sentences are similar and farther apart when they are different. The NLI (Natural Language Inference) datasets and the STS (Semantic Textual Similarity) benchmark are mainly used for training. The output embedding is generated through the [CLS] token or Mean Pooling, and is typically a dense vector of 384 to 1024 dimensions.
The most widely used models at present are all-MiniLM-L6-v2 and all-mpnet-base-v2. The MiniLM model is very fast, with 6 layers and 384-dimensional embeddings (5,000 to 14,000 sentences per second on a CPU), and its quality is also at a practical level. The MPNet model, with 12 layers and 768 dimensions, provides top-tier quality on the MTEB (Massive Text Embedding Benchmark) leaderboard, but is 4 to 5 times slower. According to the official documentation, "mpnet has the best quality, and MiniLM is 5x faster while still offering good quality."
The main use cases of Sentence Transformer are semantic search (meaning-based search rather than keyword search), the Retriever in RAG (Retrieval-Augmented Generation) pipelines, duplicate document detection, clustering (such as grouping news articles), and recommendation systems. It is frequently used as the default embedding model in LLM frameworks such as LangChain and LlamaIndex, and when combined with vector databases such as FAISS, Pinecone, and Weaviate, it enables millisecond-level search even across hundreds of millions of documents.
This is an example of sentence embedding and similarity calculation using Sentence Transformer.
# pip install sentence-transformers
from sentence_transformers import SentenceTransformer, util
import numpy as np
# ๋ชจ๋ธ ๋ก๋ (์ฒซ ์คํ ์ ์๋ ๋ค์ด๋ก๋)
# ๋น ๋ฅธ ๋ชจ๋ธ: all-MiniLM-L6-v2 (384์ฐจ์, ๋น ๋ฆ)
# ๊ณ ํ์ง ๋ชจ๋ธ: all-mpnet-base-v2 (768์ฐจ์, ๋๋ฆฌ์ง๋ง ์ ํ)
model = SentenceTransformer('all-MiniLM-L6-v2')
# ๋ฌธ์ฅ ๋ฆฌ์คํธ
sentences = [
"์ธ๊ณต์ง๋ฅ์ด ์ธ์์ ๋ฐ๊พธ๊ณ ์์ต๋๋ค.",
"AI ๊ธฐ์ ์ด ์ฐ๋ฆฌ์ ์ถ์ ํ์ ํ๊ณ ์์ต๋๋ค.",
"์ค๋ ๋ ์จ๊ฐ ๋งค์ฐ ์ข์ต๋๋ค.",
"๋จธ์ ๋ฌ๋์ ๋ฐ์ดํฐ์์ ํจํด์ ํ์ตํฉ๋๋ค.",
]
# ๋ฌธ์ฅ ์๋ฒ ๋ฉ ์์ฑ
embeddings = model.encode(sentences, convert_to_tensor=True)
print(f"์๋ฒ ๋ฉ shape: {embeddings.shape}") # (4, 384)
# ์ฝ์ฌ์ธ ์ ์ฌ๋ ๊ณ์ฐ
cosine_scores = util.cos_sim(embeddings, embeddings)
print("\n์ ์ฌ๋ ํ๋ ฌ:")
print(cosine_scores.numpy().round(3))
# ์ฟผ๋ฆฌ์ ๊ฐ์ฅ ์ ์ฌํ ๋ฌธ์ฅ ์ฐพ๊ธฐ
query = "๋ฅ๋ฌ๋ ๊ธฐ์ ์ ๋ฐ์ "
query_embedding = model.encode(query, convert_to_tensor=True)
# ๋ชจ๋ ๋ฌธ์ฅ๊ณผ์ ์ ์ฌ๋ ๊ณ์ฐ
similarities = util.cos_sim(query_embedding, embeddings)[0]
# ๊ฒฐ๊ณผ ์ ๋ ฌ ๋ฐ ์ถ๋ ฅ
print(f"\n์ฟผ๋ฆฌ: '{query}'")
print("์ ์ฌํ ๋ฌธ์ฅ ์์:")
for idx in similarities.argsort(descending=True):
print(f" {similarities[idx]:.3f}: {sentences[idx]}")
Large-Scale Semantic Search (FAISS Integration)
# pip install sentence-transformers faiss-cpu
from sentence_transformers import SentenceTransformer
import faiss
import numpy as np
model = SentenceTransformer('all-MiniLM-L6-v2')
# ๋๊ท๋ชจ ๋ฌธ์ ์ฝํผ์ค (์์)
corpus = [
"Python์ ์ธ๊ธฐ ์๋ ํ๋ก๊ทธ๋๋ฐ ์ธ์ด์
๋๋ค.",
"JavaScript๋ ์น ๊ฐ๋ฐ์ ํ์์ ์
๋๋ค.",
"๋ฅ๋ฌ๋์ ์ ๊ฒฝ๋ง์ ์ฌ์ฉํ ๋จธ์ ๋ฌ๋ ๊ธฐ๋ฒ์
๋๋ค.",
"์์ฐ์ด ์ฒ๋ฆฌ๋ ํ
์คํธ ๋ฐ์ดํฐ๋ฅผ ๋ถ์ํฉ๋๋ค.",
"์ปดํจํฐ ๋น์ ์ ์ด๋ฏธ์ง๋ฅผ ์ดํดํ๋ AI ๋ถ์ผ์
๋๋ค.",
# ... ์๋ฐฑ๋ง ๊ฐ์ ๋ฌธ์
]
# ์ฝํผ์ค ์๋ฒ ๋ฉ (ํ ๋ฒ๋ง ์คํ, ์ ์ฅํด๋๊ณ ์ฌ์ฌ์ฉ)
corpus_embeddings = model.encode(corpus, convert_to_numpy=True)
corpus_embeddings = corpus_embeddings.astype('float32')
# FAISS ์ธ๋ฑ์ค ์์ฑ (L2 ๊ฑฐ๋ฆฌ ๊ธฐ๋ฐ)
dimension = corpus_embeddings.shape[1] # 384
index = faiss.IndexFlatIP(dimension) # Inner Product (์ฝ์ฌ์ธ ์ ์ฌ๋์ฉ ์ ๊ทํ ํ์)
# ์ ๊ทํ ํ ์ธ๋ฑ์ค์ ์ถ๊ฐ
faiss.normalize_L2(corpus_embeddings)
index.add(corpus_embeddings)
# ๊ฒ์ ํจ์
def search(query: str, top_k: int = 3):
query_embedding = model.encode([query], convert_to_numpy=True).astype('float32')
faiss.normalize_L2(query_embedding)
scores, indices = index.search(query_embedding, top_k)
results = []
for score, idx in zip(scores[0], indices[0]):
results.append({
'document': corpus[idx],
'score': float(score)
})
return results
# ๊ฒ์ ํ
์คํธ
query = "AI๊ฐ ์ด๋ฏธ์ง๋ฅผ ๋ถ์ํ๋ ๋ฐฉ๋ฒ"
results = search(query, top_k=3)
print(f"๊ฒ์ ์ฟผ๋ฆฌ: '{query}'")
for i, result in enumerate(results, 1):
print(f"{i}. [{result['score']:.3f}] {result['document']}")
Custom Model Fine-Tuning
# pip install sentence-transformers datasets
from sentence_transformers import SentenceTransformer, InputExample, losses
from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator
from torch.utils.data import DataLoader
# ๊ธฐ๋ณธ ๋ชจ๋ธ ๋ก๋
model = SentenceTransformer('all-MiniLM-L6-v2')
# ํ์ต ๋ฐ์ดํฐ ์ค๋น (๋ฌธ์ฅ ์ + ์ ์ฌ๋ ์ ์)
train_examples = [
InputExample(texts=["๋ฌธ์ฅ A1", "๋ฌธ์ฅ B1"], label=0.9), # ๋งค์ฐ ์ ์ฌ
InputExample(texts=["๋ฌธ์ฅ A2", "๋ฌธ์ฅ B2"], label=0.1), # ๋ค๋ฆ
# ... ๋ ๋ง์ ๋ฐ์ดํฐ
]
train_dataloader = DataLoader(train_examples, shuffle=True, batch_size=16)
# ์์ค ํจ์: CosineSimilarityLoss (์ฐ์ ์ ์์ฉ)
train_loss = losses.CosineSimilarityLoss(model)
# ํ๊ฐ ๋ฐ์ดํฐ (์ ํ์ )
evaluator = EmbeddingSimilarityEvaluator.from_input_examples(
train_examples[:100],
name='dev'
)
# ํ์ธํ๋
model.fit(
train_objectives=[(train_dataloader, train_loss)],
epochs=3,
warmup_steps=100,
evaluator=evaluator,
evaluation_steps=500,
output_path='./my-finetuned-model'
)
# ํ์ธํ๋๋ ๋ชจ๋ธ ๋ก๋
model = SentenceTransformer('./my-finetuned-model')
Sentence Transformers is free and open source. It is licensed under Apache 2.0 and can be used commercially.
| Model | Dimensions | Speed (CPU) | MTEB Score | Features |
|---|---|---|---|---|
| all-MiniLM-L6-v2 | 384 | ~14,000 sent/s | ~56 | 5x faster |
| all-MiniLM-L12-v2 | 384 | ~7,500 sent/s | ~57 | Slightly more accurate than L6 |
| all-mpnet-base-v2 | 768 | ~2,800 sent/s | ~59 | Best quality |
| paraphrase-MiniLM-L6-v2 | 384 | ~14,000 sent/s | ~55 | Specialized for paraphrase |
| multi-qa-MiniLM-L6-cos-v1 | 384 | ~14,000 sent/s | ~53 | Specialized for QA retrieval |
| distiluse-base-multilingual-cased-v2 | 512 | ~4,000 sent/s | ~51 | Multilingual (50+ languages) |
* Speed is measured on a CPU (i7); using a GPU makes it 10x+ faster
Recommended Models by Use Case
| Use case | Recommended Model | Reason |
|---|---|---|
| Production semantic search | all-MiniLM-L6-v2 | Balance of speed and quality, low memory |
| When the highest accuracy is needed | all-mpnet-base-v2 | Highest MTEB score |
| Korean language support | distiluse-base-multilingual | Multilingual support |
| RAG pipeline | multi-qa-MiniLM-L6 | Specialized for question-document matching |
| Duplicate detection | paraphrase-MiniLM-L6 | Specialized for paraphrase recognition |
"If speed matters more than search quality, use MiniLM; if accuracy matters more, use the mpnet model. MiniLM is 5x faster, but the quality difference is not large."
"When embedding chunks in a RAG system, if you use Sentence Transformer and put them into FAISS, search takes milliseconds."
"You can generate text with Sentence Transformer like GPT." โ Sentence Transformer is an embedding-only model. It cannot generate text.