Language models, retrieval, prompting, and language adaptation · Contextual and sentence encoders · LNG017 · Model
Sentence-BERT (SBERT)
Trains a shared text encoder so sentence vectors can be compared efficiently without jointly processing every sentence pair. It supports semantic search, clustering, duplicate detection, and nearest-neighbor retrieval.
In CodeSplash
A CodeSplash method runs this entry in Python and R. Set it up from the method's page.
- Semantic search (BM25, sentence embeddings, hybrid) Not verified yet
- BERTopic (embeddings, clustering, c-TF-IDF) Experimental
Do it in CodeSplash Run it on your own data, in Python or R.
- Availability
- Runs in CodeSplash
- Code example
- Component demo, not a trained model
- Who ran it
- CodeSplash's own run
- CodeSplash's run
- Verified in Python and R through discover.bertopic. The reference's example ran in Python and R here, and they agree.
- The reference's record
- Python: The chapter's authors report running it; there is no record for this entry alone. R: Reviewed but not run: R wasn't available to the reference's authors.
Purpose
Trains a shared text encoder so sentence vectors can be compared efficiently without jointly processing every sentence pair. It supports semantic search, clustering, duplicate detection, and nearest-neighbor retrieval.
Question / objective
Can sentence embeddings support direct similarity search without cross-encoding every sentence pair?
Architecture / computational structure
Siamese/triplet encoder branches share weights and pool token states into sentence vectors. Encoder and projection/head weights are learned; pooling, similarity, and training-pair construction are hyperparameters.
Assumptions
Similarity geometry reflects the training objective and language/domain.
Formula / computational definition
Compute u=pool(f_theta(s_1)) and v=pool(f_theta(s_2)); optimize a sentence-pair classification, regression, or triplet objective. A triplet form is max(0,dist(u,v_positive)-dist(u,v_negative)+m), with margin m.
Parameters and notation
Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Encoder, pooling, embedding width, training pairs, loss, negatives, normalization, and maximum text length.
Fitting, fine-tuning, and adaptation
Train or adapt with sentence-pair, triplet, or contrastive objectives appropriate to the task. Freeze the encoder initially for a small supervised head, or fine-tune with hard negatives/adapters when data permit. Validate retrieval and semantic similarity separately; rebuild indexes after encoder updates.
How to use and calibrate
Combine semantic-similarity correlations with retrieval nDCG/recall and domain-specific error inspection. Use development data for settings and an independent test set for the final estimate. Report uncertainty across examples or seeds when the evaluation design supports it; model scores and self-assessments are not automatically calibrated probabilities of correctness.
Example application
Search a knowledge base for semantically similar user questions.
Interpretation / pitfalls
Watch out
Generic BERT pooling is not equivalent to sentence-level training; semantically related text may still be irrelevant to a specific query. The code below isolates one stated component; successful execution does not validate model quality or reproduce the cited experiment.
Python and R code examples
Full implementation route: SentenceTransformers is the documented Python route. R uses reticulate for the same encoder; cosine ranking and downstream evaluation can run natively in R once embeddings are exported.
Example scope: Sentence-BERT cosine similarity on supplied pooled sentence vectors.
Dependencies: Python 3 standard library; base R; shared setup above. No model downloads or external services.
Validation: Python component executed in the combined example script; R counterpart supplied but not runtime-tested here. All numbers are synthetic.
Python and R
The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.
Component demo, not a trained model — Sentence-BERT cosine similarity on supplied pooled sentence vectors.
Shared setup for this chapter
import math
def softmax(xs):
m = max(xs)
es = [math.exp(x-m) for x in xs]
return [e/sum(es) for e in es]
def dot(a, b):
return sum(x*y for x, y in zip(a, b))
def matvec(matrix, vector):
return [dot(row, vector) for row in matrix]
def meanvec(rows):
return [sum(row[j] for row in rows)/len(rows) for j in range(len(rows[0]))]
def sigmoid(x):
return 1/(1+math.exp(-x))
def nll(probabilities):
return -sum(math.log(p) for p in probabilities)
a, b = [1.0, 0.5], [0.8, 0.4]
cosine = dot(a,b) / math.sqrt(dot(a,a)*dot(b,b))
print(cosine)
Component demo, not a trained model — Sentence-BERT cosine similarity on supplied pooled sentence vectors.
Shared setup for this chapter
softmax <- function(x) {
shifted <- exp(x-max(x))
shifted/sum(shifted)
}
a <- c(1,0.5); b <- c(0.8,0.4)
cosine <- sum(a*b) / sqrt(sum(a*a)*sum(b*b))
print(cosine)
Sources
- Source 1arxiv.org
From the CodeSplash reference, entry LNG017.