Language models, retrieval, prompting, and language adaptation · Contextual and sentence encoders · LNG018 · Training method
SimCSE
Learns sentence embeddings through contrastive training. The unsupervised form treats two dropout-perturbed encodings of the same sentence as positives; the supervised form uses entailment pairs and hard negatives.
In CodeSplash
Documented in the Academy only. There's no Set up button.
- Availability
- Explained here
- Code example
- Component demo, not a trained model
- Who ran it
- CodeSplash's own run
- CodeSplash's run
- 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
Learns sentence embeddings through contrastive training. The unsupervised form treats two dropout-perturbed encodings of the same sentence as positives; the supervised form uses entailment pairs and hard negatives.
Question / objective
Can stochastic dropout views teach sentence similarity without explicit pair labels?
Architecture / computational structure
A shared encoder maps two independently dropout-corrupted views of one sentence to positive embeddings; in-batch sentences provide negatives. Learned encoder weights are parameters; temperature, dropout, and batch size are hyperparameters.
Assumptions
Other batch sentences may be false negatives.
Formula / computational definition
Minimize -log exp(sim(h_i,h_i_plus)/tau)/sum_j exp(sim(h_i,h_j_plus)/tau), where h encodes a sentence, sim is usually cosine similarity, and tau is temperature. Supervised negatives alter the denominator and relationship labels.
Parameters and notation
Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Dropout, temperature, batch size, encoder/pooling, positive construction, and supervised versus unsupervised regime.
Fitting, fine-tuning, and adaptation
Train the unsupervised contrastive variant on unlabeled sentences, or clearly label the NLI-supervised variant. Adapt to a domain with controlled negatives and validation retrieval. LoRA/adapters may be practical on supported encoders; monitor collapse, false negatives, and lost general similarity.
How to use and calibrate
Measure similarity and retrieval, embedding anisotropy, and robustness across domains rather than only training contrastive loss. 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
Create sentence embeddings from unlabeled customer-support text.
Interpretation / pitfalls
Watch out
Removing dropout can collapse the unsupervised setup's useful augmentation; entailment-based supervision changes the semantic geometry and should not be described as fully unsupervised. 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: Implement the paired dropout passes and contrastive loss in PyTorch or use a compatible sentence-embedding training framework. R can reproduce the loss with R torch or bridge the Python pipeline.
Example scope: SimCSE contrastive loss from supplied positive/negative similarity scores.
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 — SimCSE contrastive loss from supplied positive/negative similarity scores.
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)
similarities, tau = [0.9, 0.4, -0.1], 0.1
probabilities = softmax([s/tau for s in similarities])
print(-math.log(probabilities[0]))
Component demo, not a trained model — SimCSE contrastive loss from supplied positive/negative similarity scores.
Shared setup for this chapter
softmax <- function(x) {
shifted <- exp(x-max(x))
shifted/sum(shifted)
}
similarities <- c(0.9,0.4,-0.1); tau <- 0.1
probabilities <- softmax(similarities/tau)
print(-log(probabilities[1]))
Sources
- Source 1arxiv.org
From the CodeSplash reference, entry LNG018.