๐Ÿค– AI/ML

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.

๐Ÿ“– Detailed Explanation

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.

๐Ÿ’ป Code Example

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')

๐Ÿ“Š Performance & Cost

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

๐Ÿ—ฃ๏ธ Say It Like This in Practice

Correct Expressions

"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."

Correct Expressions

"When embedding chunks in a RAG system, if you use Sentence Transformer and put them into FAISS, search takes milliseconds."

Incorrect Expressions

"You can generate text with Sentence Transformer like GPT." โ†’ Sentence Transformer is an embedding-only model. It cannot generate text.

โš ๏ธ Common Mistakes & Cautions

  • Check Max Sequence Length: Most models have a maximum of 256 to 512 tokens. Embed long documents after chunking them.
  • Benchmark โ‰  real performance: Even with a high MTEB score, performance on your own domain may differ. Be sure to evaluate with your own data.
  • Embedding normalization: To use cosine similarity, you must L2-normalize the vectors. It is required when using FAISS IndexFlatIP.
  • Choosing a multilingual model: If Korean is included, use a multilingual model. English-only models perform very poorly on Korean.
  • Batch processing: Pass a list of sentences in a single call to encode(). Individual calls are very inefficient.
  • GPU memory: Adjust batch_size when embedding large volumes. If you get an OOM error, reduce batch_size.
  • Model caching: Load the model only once and reuse it. Loading it every time incurs an overhead of several seconds.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More