Clustering-Aware Negative Sampling for Unsupervised Sentence Representation
Paper · 2023 · Jinghao Deng, Fanqi Wan, Tao Yang et al.
Summary
A system that learns from unlabeled text can compare a sentence with another version of itself and with other sentences encountered during training. The first comparison supplies a clear match. The others are typically assumed to be mismatches. That assumption creates problems in both directions. Many of the supposed mismatches are so different that the system soon learns little from separating them. Others are close in meaning or topic and may be pushed farther apart than they should be. Deng and colleagues introduce ClusterNS to make these comparisons more informative when learning sentence embeddings, numerical representations that can be compared for semantic similarity.
ClusterNS groups the current sentence embeddings using a modified K-means procedure. For each sentence, it takes the center of the closest other cluster as a hard negative, a deliberately challenging mismatch. It also flags other sentences assigned to the sentence’s own cluster as possible false negatives. The two decisions lead to different training signals. The neighboring center enters the contrastive comparison as an extra competitor. A separate loss gives same-cluster sentences a band of acceptable similarity relative to the known match. This leaves room for sentences to share a subject while saying different things. Training begins with ordinary contrastive comparisons, then introduces clustering and updates the centers as the embeddings change.
Across the seven semantic textual similarity tasks, ClusterNS improves the average Spearman correlation reported for each corresponding SimCSE and PromptBERT baseline. With RoBERTa base, the non-prompt comparison moves from 76.57 to 77.98, while the prompt-based comparison moves from 79.15 to 79.74. The latter is the highest average among the RoBERTa base systems in the paper’s main comparison. The pattern varies across individual datasets. The embeddings also give better agreement with DBpedia categories under a separate clustering evaluation, and short-text clustering gains are more consistent with BERT base than with RoBERTa base.
The component tests help explain where these results come from. Across the two non-prompt base encoders tested, removing the hard negatives costs more than removing the same-cluster loss. The closest cluster center also performs worse as a negative than the closest center outside the sentence’s own cluster. When the authors treat every flagged sentence as a positive match, similarity performance falls sharply. The paper’s evidence supports using clusters to choose comparisons and to moderate their training effects, with the accuracy of individual false-negative identifications still an open question. The authors make the ClusterNS code public.
Deep dive: Clustering-Aware Negative Sampling for Unsupervised Sentence Representation
ClusterNS uses nearby cluster centers and related sentences to improve how contrastive training learns sentence embeddings from unlabeled text. · about 34 minutes to read
The problem and its context
What a sentence vector has to preserve
A sentence embedding puts a sentence at a point in a numerical space. To compare two sentences, an encoder produces a vector for each, and a similarity function compares the vectors. A useful embedding for this paper’s main task should place sentences in an order that reflects judgments about their meanings. If one pair is judged to be more alike than another, the similarities computed from the embeddings should tend to give the same order. This puts a demand on the geometry of the space. The encoder has to represent distinctions between sentences as well as the information they share.
The paper situates that problem in earlier work on learning sentence representations from unlabeled text and on producing general-purpose sentence encodings. It recalls a result from Sentence-BERT in which sentence vectors obtained from BERT could perform worse than representations using GloVe. GloVe supplies word embeddings. The comparison matters because it exposes a gap between pretraining an encoder and obtaining a space in which whole sentences can be compared directly. The training that produced the starting representations and the comparisons the researchers want to make with them serve different purposes.
Earlier analyses cited in the paper also describe anisotropy in pretrained representations. In this context, anisotropy means that vectors concentrate in some directions of the space. Vectors can then have high cosine similarity across a broad range of sentences, making it harder to read meaningful distinctions from their relative positions. The authors connect that observation to work studying the geometry of contextual representations and the sentence embeddings derived from them. Geometry of contextual representations and sentence embeddings from pretrained encoders are the two lines of analysis they cite for this issue.
Contrastive learning offers a way to shape that geometry. In the account Deng and colleagues adopt, two properties matter. Alignment concerns how closely the embeddings of genuine matches sit together. Uniformity concerns how broadly embeddings use the available space. A training signal that only brought matching examples together would leave open where the rest of the sentences go. A signal based only on spreading vectors would give up the instruction that some sentences should remain close. Contrastive training supplies both kinds of pressure through the comparisons it makes.
Where a batch gets its comparisons
The paper describes earlier sentence-level contrastive work as especially concerned with how to construct a positive example. A positive is a comparison the training procedure asks the encoder to score highly for a given sentence. With SimCSE, the encoder processes the same text through different applications of Dropout, which temporarily suppresses parts of the computation during training. The resulting vectors differ even though the underlying sentence is the same. PromptBERT creates the positive comparison by putting the sentence into different prompt templates. Both procedures give an anchor, the sentence representation currently being trained against a set of alternatives, a known match without requiring a person to annotate the pair.
The rest of the mini-batch offers a convenient comparison set. A mini-batch is the group of examples processed together at an update. Each sentence can furnish a positive view for itself and serve as an alternative for the other sentences. Reusing these vectors lets the contrastive objective draw comparisons from a single batch. It also gives every different sentence the same nominal role in the objective, even though its relationship to the anchor can differ substantially.
Consider what happens as the encoder gets better at separating unrelated text. An unrelated example may already be so far away that its score contributes little to the decision between possible matches. It still appears in the batch, but the encoder has comparatively little to learn from it. A hard negative is a mismatch whose similarity is high enough to make that decision more demanding. The paper points to previous work that finds such examples useful for producing stronger training signals. Randomly drawing sentences into the same batch, however, gives the training procedure limited control over how frequently a suitably challenging alternative appears.
The risk with an apparently hard example is that its high score can be appropriate. If the alternative shares enough meaning with the anchor, pushing it away simply because it has a different identity can distort the embedding space. The paper calls these cases false negatives. Hardness describes how difficult an example is to distinguish from the designated match. The false-negative question concerns whether separation is the right instruction to give in the first place. An unlabeled minibatch gives the encoder no authoritative answer to that second question. A high score is a reason to examine the comparison, and by itself it leaves the intended semantic relationship unresolved.
How earlier methods changed the negatives
The authors describe earlier approaches that manufacture difficult alternatives by mixing positive and in-batch negative representations. That puts the generation of a harder comparison inside the training procedure. They also discuss methods that construct a modified sentence or a modified prompt. One uses dependency information to produce a negated sentence, and another derives negatives by negating prompt templates. In that account, the risk is that fixed transformations produce a narrow family of alternatives, carrying the biases of the rules or templates that created them. Retrieval can supply additional hard examples from a corpus, although the paper identifies retrieval and fine-grained augmentation as potentially time-consuming.
Earlier work on false negatives includes a debiased contrastive objective that attempts to correct for them without true labels. The paper also discusses an approach that uses a trained auxiliary component to recognize suspect negatives. These approaches place the intervention in different parts of the learning process. An objective can correct how it responds to a proposed negative, whereas a separate component can try to decide which examples deserve special treatment. Deng and colleagues want the same source of evidence to help with both selecting a challenging negative and identifying comparisons that deserve restraint.
Their source of evidence is clustering. In the paper’s account of earlier neural clustering, some approaches use clusters to learn representations, and others combine clusters with contrastive objectives. The authors point to work suggesting that groups of examples can carry higher-level semantic information beyond comparisons between individual instances. That idea is particularly relevant when the labels are missing. A cluster can offer evidence that sentences have something in common even when its members express different propositions. ClusterNS uses this distinction to give a cluster center and an actual sentence in a cluster different jobs during training.
The method, step by step
From the original contrastive comparison to clusters
Start with a mini-batch and a way of obtaining two views of each sentence. In the SimCSE version, the views come from applying dropout during separate passes. In the PromptBERT version, they come from the prompt templates. To train on one sentence, use its first representation as the anchor and place its paired view among the candidate matches. The paired views of the other sentences also appear among those candidates. The original contrastive loss measures how much of the total score belongs to the designated match.
ClusterNS adds information about the neighborhood around each anchor. It groups the current vectors around a set of centers, called centroids, and compares an anchor with the centroids using cosine similarity. Cosine similarity compares vector directions. The center with the highest score identifies the anchor’s own group, and the next center in that ordering identifies the closest alternative group. The centroid of that alternative group supplies an extra negative vector. The method can therefore supply a nearby competitor even when no individual sentence in the batch is an obvious choice.
The anchor’s own cluster serves a different purpose. A sentence assigned to that cluster has at least some geometric evidence of being related to the anchor, since both are close to the same representative. That evidence is coarse. For instance, the paper shows a group containing several sentences about music, including sentences about performance, style and equipment. Sharing the broad subject gives their vectors a reason to be closer than arbitrary sentences. Each can still make a different claim. ClusterNS handles this uncertainty by setting a similarity range relative to the anchor’s known positive.
How ClusterNS constructs training comparisons
The steps in order.
The two cluster-based signals operate alongside the designated positive from the original training recipe. The neighboring centroid is a vector generated within the clustering procedure. It need not correspond to a sentence that someone could read and judge. The possible false negative, by contrast, is an actual batch sentence. It has a positive view under the same rules as every other original sentence, but its relationship to the current anchor receives additional attention through the margin. The distinction matters for tracking what the method adds to the objective.
The baseline loss
The paper begins with the InfoNCE contrastive loss, which comes from Contrastive Predictive Coding. In the sentence setting, it has the form of a selection problem. Each candidate gets a score based on its similarity to the anchor. Exponentiating the scores makes them positive, and dividing the score of the designated match by the sum yields that match’s share. Taking the negative logarithm turns a small share into a large loss.
L_cl = −log(exp(sim(xᵢ, xᵢ⁺)/τ) / Σⱼ₌₁ᴺ exp(sim(xᵢ, xⱼ⁺)/τ))
Here L_cl is the contrastive loss for the current anchor, xᵢ is its sentence embedding, and xᵢ⁺ is the positive view of the same sentence. The index i identifies the anchor. The summation index j runs through the N sentences in the batch, and xⱼ⁺ is the positive view of sentence j. Thus the denominator contains the designated match at j = i as well as the views of the other sentences. sim is the vector similarity score, τ is the temperature, exp is the exponential function, and log is the natural logarithm. The temperature controls how sharply differences in similarity translate into differences in score.
The superscript plus describes a view’s relationship to its own sentence. The same vector can have another role in a different comparison. For the anchor indexed by i, a view indexed by a different j is an alternative in the denominator, even though that view serves as a positive for sentence j elsewhere in the batch. The loss favors a high score for the designated match relative to the alternatives. This explains why genuinely close sentences can be affected by ordinary in-batch sampling. When treated as alternatives, their high scores make the designated match harder to select.
It also explains the interest in harder negatives. A candidate with a higher similarity contributes more to the denominator, all else being equal. Improving the score of the designated match relative to such a candidate exerts a different training pressure from improving it relative to a batch full of sentences that are already well separated. The neighborhood mechanism is how ClusterNS controls the presence of that harder comparison.
Selecting an alternative centroid
The method keeps K centroids, with a corresponding cluster for each. For one anchor, order all centroids by decreasing cosine similarity. The authors use indices of the form cᵢ₁ for the first centroid in anchor i’s ordering and cᵢ₂ for the next. The order depends on the anchor, so a single stored centroid can have different ranks for different sentences. The first identifies the anchor’s own cluster. The next is the highest-scoring centroid from a different group, and it becomes the hard negative for that anchor.
This choice puts two requirements on the additional vector. It should be close enough to make the training comparison consequential, and its cluster assignment should give some reason to treat it as distinct. The nearest centroid satisfies the closeness requirement most directly, but it summarizes the group the anchor itself belongs to. Using the next centroid preserves the link to a nearby part of the space while keeping the anchor’s own center out of the hard-negative role. The authors test the nearest-center alternative explicitly.
The extra comparisons modify the denominator of the contrastive loss. In the paper’s equation, each indexed sentence contributes its usual view and a term for its associated hard negative. The anchor in each similarity in the equation remains xᵢ. Thus a centroid selected for another sentence can also appear in the denominator for the current anchor.
L_cl = −log(exp(sim(xᵢ, xᵢ⁺)/τ) /
Σⱼ₌₁ᴺ [exp(sim(xᵢ, xⱼ⁺)/τ) + μ exp(sim(xᵢ, xⱼ⁻)/τ)])
L_cl is now the contrastive loss augmented with the centroid terms. The anchor is xᵢ, and its designated match is xᵢ⁺. The index j ranges over the N batch sentences. For each j, xⱼ⁺ is its positive view, and xⱼ⁻ is the hard negative associated with that sentence. sim compares the anchor with whichever vector occurs in its second argument. τ remains the temperature. The weight μ scales each hard-negative contribution, exp exponentiates the similarity after temperature scaling, and log is the natural logarithm. The bracket groups the original view and the extra hard-negative term for one summation index.
The numerator in this expression is the same as in the original loss. The method changes the set of competitors for the known positive. The paper’s grid search lists a hard-negative weight μ of 1.0. Though the equation includes a weight that could vary, that search does not explore different values of it. The choice of which centroid supplies a negative is tested separately.
Giving same-cluster sentences a range
For an anchor, the authors collect the other examples assigned to its cluster as possible false negatives. Their reasoning is that these neighbors should frequently receive a similarity somewhere between a hard negative and the known positive. In the paper, the intended ordering is expressed with the anchor’s own hard negative as the lower comparator.
cos(xᵢ, xᵢ⁻) ≤ cos(xᵢ, xᵢⱼ*) ≤ cos(xᵢ, xᵢ⁺)
cos is cosine similarity. xᵢ is the anchor embedding, xᵢ⁻ is the hard negative selected for that anchor, and xᵢ⁺ is its designated positive view. xᵢⱼ* denotes a candidate false negative, with j indexing another sentence in anchor i’s cluster. The inequality signs represent the desired ordering. They express the authors’ working assumption about the similarity of these examples.
The implemented loss describes this intermediate relationship using the positive similarity as the reference. For a flagged sentence, subtract the anchor–positive similarity from the anchor–candidate similarity. This yields a gap that is negative when the designated positive has the higher score.
Δxᵢ = cos(xᵢ, xᵢ*) − cos(xᵢ, xᵢ⁺)
Δxᵢ is the similarity gap for anchor i and the candidate under consideration. xᵢ is the anchor, xᵢ* stands for the same-cluster candidate being compared, and xᵢ⁺ is the anchor’s known positive. The paper also uses the starred notation for the collection of candidates, with the additional index in the preceding inequality distinguishing members of that collection. cos is cosine similarity, so both quantities in the subtraction use the same scale.
A margin is a required separation or tolerance in a comparison. Here the bidirectional margin loss, abbreviated BML, gives the gap both an upper and a lower bound. On either side there is a rectified linear penalty. A rectified linear unit, or ReLU, returns its input when the input is positive and zero otherwise.
L_bml = ReLU(Δxᵢ + α) + ReLU(−Δxᵢ − β)
L_bml is the margin loss on the comparison, and Δxᵢ is the gap just defined. α sets the magnitude of the upper bound, so the gap should stay at or below −α. β sets the magnitude of the lower bound, so the gap should stay at or above −β. Each ReLU activates when the gap violates the bound controlled by its corresponding parameter. Together they leave the interval from −β to −α free of a BML penalty.
If the flagged sentence scores too much like the designated match, the penalty favors a larger gap. If it scores too far below the match, the penalty favors closing the gap. A sentence within the interval can keep its current relative score as far as BML is concerned. This gives ClusterNS a way to preserve some closeness without declaring that the sentences have interchangeable meanings. The lower edge of the implemented interval is based on the positive score and β. The hard-negative score appears in the motivating ordering, while the written BML uses only the candidate and positive scores.
The training objective adds the margin term to the augmented contrastive loss. This addition is important to interpreting the ablations. The method can constrain the similarity of flagged sentences while retaining the usual batch denominator shown in the contrastive equation. Masking the flagged sentences out of the contrastive comparisons is a different strategy, which the authors evaluate separately.
L = L_cl + λL_bml
L is the combined training loss, L_cl is the contrastive term, and L_bml is the bidirectional margin term. λ controls the contribution of the margin relative to contrastive training. The two terms can exert different pressures on the same pair. The margin supplies an additional signal only when the pair crosses one of its bounds.
When and how the centroids move
The centroids have to track a space that changes as the encoder trains. A clustering of the entire corpus would quickly become stale unless the embeddings were recomputed, and repeating that procedure often would be expensive. ClusterNS instead draws its updates from the current batch and carries its centroids forward. A center thus has a persistent identity across batches even though the sentences used to update it change.
The algorithm opens with a warm-up. Early in training, the embeddings tend to have high similarities, which the authors say makes them a poor basis for starting the clustering. The pseudocode describes a designated initialization step. The similarity analysis expresses the timing through a threshold σ on the average similarity of sentence pairs in a batch. A smaller threshold delays the start in the settings the authors report, giving ordinary contrastive training more time to change the space before centers are seeded.
At initialization, the centers are chosen from the embeddings in the current mini-batch. In the heuristic the paper describes, each new center is the candidate least similar to the previously selected center. This spreads successive initial choices according to the same notion of similarity used to form clusters. The method then moves to the repeated part of the procedure. It assigns each incoming sentence vector to its most similar center, computes means of the assigned embeddings, and blends those means into the stored centers.
x̄ᵢ = (1/Nᵢ) Σₓⱼ∈Cᵢ xⱼ
x̄ᵢ is the mean embedding for cluster i in the current assignment. Here i indexes a cluster, Cᵢ is the set of vectors assigned to it, and Nᵢ is the number of those vectors. xⱼ is one assigned sentence embedding. The summation adds the vectors for which xⱼ belongs to Cᵢ, and division by Nᵢ forms their arithmetic mean.
cᵢ(new) = (1 − γ)cᵢ(old) + γx̄ᵢ
cᵢ(old) is the stored centroid of cluster i before the update, cᵢ(new) is the resulting centroid, and x̄ᵢ is the current cluster mean. The coefficient γ is the momentum update parameter. It weights the current mean, and 1 − γ weights the previous center. The labels old and new distinguish the readings of the same centroid on opposite sides of the update.
The small values considered for γ make the current batch an adjustment to accumulated center positions. The paper searches 1e-3, 5e-4 and 1e-4 for that update. It considers 96, 128 and 256 clusters, and batch sizes of 256 and 512. The learning rate for the encoder is a separate choice, searched over 1e-5, 3e-5 and 5e-5. The appendix also reports searches over the initialization threshold, the weight of the margin loss, and the margin bounds. These are training settings, distinct from the number of groups chosen for a downstream clustering benchmark.
Once clustering is active, the batch provides the data for the centroid update, the candidate negatives, and the margin comparisons. The encoder is then updated by backpropagating the training loss. This creates a feedback loop. An encoder update changes the vectors that arrive in the next batch. Those vectors nudge the centroids, whose positions help determine future comparisons. The design uses the warm-up to establish an initial geometry and momentum to keep any particular batch from determining the centers by itself.
The authors apply this procedure during fine-tuning of pretrained BERT and RoBERTa encoders. They call the SimCSE integration non-prompt ClusterNS and the PromptBERT integration prompt-based ClusterNS. The positive construction in each follows its corresponding starting method. The appendix indicates that most of the reported configurations use both cluster-based interventions, with one exception. The separate component experiments make clear which interventions are being compared in the non-prompt base settings.
Experiments and results
How the similarity evaluation works
The main evaluation asks whether the similarity of two sentence vectors agrees with human judgments about the meaning of the underlying text. The authors use STS12 through STS16 alongside STS-B and SICK-R. The numbered STS tasks come from the shared-task series the paper cites, including SemEval-2014 semantic textual similarity and SemEval-2016 semantic textual similarity. The other benchmarks are associated with the SemEval-2017 semantic textual similarity task and the SICK evaluation.
For this experiment, the authors evaluate with SentEval and follow SimCSE’s method of aggregating results. The reported measure is Spearman correlation. This compares the ordering given by the sentence similarities with the ordering given by the reference judgments. A system can therefore score well if it generally orders the sentence pairs correctly even if its raw cosine scores are on a different scale from the judgments. The headline average combines the results from the 7 STS tasks. The figures such as 79.74 below are on the correlation scale used in the paper’s results table.
The training runs use PyTorch and Hugging Face Transformers. According to the authors, they used either one Nvidia Tesla V100 GPU with 32G of memory or four Nvidia RTX3090 GPUs with 24G each. They train for 1 epoch, evaluate on the STS-B development set every 125 steps, and use early stopping to limit overfitting. The development evaluations guide training decisions, whereas the tabulated STS comparisons describe evaluation performance. The paper’s checklist says the datasets have standard splits and that the authors follow earlier processing practices.
The main table contains published baseline values. Its simplest comparisons use GloVe and the original BERT and RoBERTa embeddings. BERT-flow and the whitening results represent ways to improve the embedding space from a pretrained encoder. SimCSE and PromptBERT are the direct starting points for the two ClusterNS variants. The non-prompt table also includes MixCSE, DCLR and ESimCSE. The prompt table adds ConPVP and SNCSE. Organizing the table by the underlying positive construction and encoder makes it possible to compare the changes introduced by negative sampling against related approaches on the same footing.
Results with dropout-based positives
The most direct comparison for non-prompt ClusterNS is with SimCSE using the same encoder family and size. For BERT base, the average goes from 76.25 with SimCSE to 77.55 with ClusterNS. The pairwise results show where that average comes from. On STS12, the reported scores are 68.40 for SimCSE and 69.93 for ClusterNS. On STS-B, they are 76.85 and 78.85. SICK-R favors the original method slightly, with 72.23 for SimCSE and 72.03 for ClusterNS. The average improvement describes the benchmark collection instead of a uniform gain on every task.
With RoBERTa base, ordinary SimCSE has an average of 76.57, while non-prompt ClusterNS has 77.98. This is the comparison for which the introduction reports an improvement of 1.41. ESimCSE has an average of 77.44 and DCLR has 77.87. The differences among the more competitive variants are smaller than the difference from the plain embeddings. The non-prompt ClusterNS row scores 82.25 on STS16 and 81.95 on STS-B. On SICK-R it reaches 69.22, where ESimCSE reaches 70.54 and DCLR reaches 70.33. Which system is preferable on a particular benchmark depends on which kinds of pairwise distinctions that benchmark rewards.
The BERT large non-prompt results supply a comparison with methods that also change how training uses negatives. ClusterNS records the strongest average in this group. Its result includes relatively strong scores on STS13, STS14 and SICK-R. On STS12, MixCSE has 72.55 and ClusterNS has 71.64. STS15 also favors competing systems, including DCLR at 84.70 and SimCSE at 84.50, while ClusterNS scores 83.48. The result supports a gain over the starting method and competitiveness against alternatives, with the individual rows showing different strengths.
Non-prompt BERT large systems across the STS tasks by average Spearman correlation
ClusterNS leads the matched comparison on the task average.
The numbers
| System or setting | Spearman correlation on the reported scale |
|---|---|
| SimCSE | 78.41 |
| MixCSE | 78.80 |
| DCLR | 78.90 |
| ClusterNS (this paper) | 79.19 |
Results with prompt-based positives
ClusterNS also improves the averages of its prompt-based starting points. PromptBERT base has 78.54 and prompt-based ClusterNS with BERT base has 78.72. This is the weakest average showing for ClusterNS relative to the other prompt-based systems within a given encoder group. ConPVP with BERT base reaches 78.85, and SNCSE reaches 78.97. ClusterNS improves on the immediate baseline in this setting, while the alternatives demonstrate that the same encoder supports competitive results under other treatments of negatives.
With RoBERTa base, the corresponding starting point is PromptRoBERTa. ClusterNS records an average of 79.74, compared with PromptRoBERTa at 79.15. The paper reports a gain of 0.59 for this comparison. The final average also exceeds the ConPVP and SNCSE values in the group. Individual results again give a more textured picture. Prompt-based ClusterNS reaches 82.84 on STS16 and 83.28 on STS-B. On SICK-R, ConPVP reports 74.59 and SNCSE reports 72.92, compared with 70.47 for ClusterNS. Some alternatives therefore remain stronger where the aggregate winner is weaker.
Prompt-based RoBERTa base systems across the STS tasks by average Spearman correlation
The prompt-based ClusterNS variant has the highest average in the RoBERTa base group.
The numbers
| System or setting | Spearman correlation on the reported scale |
|---|---|
| PromptRoBERTa | 79.15 |
| ConPVP | 79.18 |
| SNCSE | 79.23 |
| ClusterNS (this paper) | 79.74 |
For the BERT large prompt setting, PromptBERT has an average of 79.42 and ClusterNS has 80.30. ConPVP and SNCSE reach 80.01 and 80.19, respectively. ClusterNS reaches 87.53 on STS13 and 82.85 on STS-B in this group. Its SICK-R correlation is 72.59, compared with 75.11 for SNCSE. The table therefore supports improvement over the parent encoder recipe in both the prompt and non-prompt families, alongside clear exceptions to benchmark-by-benchmark dominance. The comparatively high RoBERTa base headline identifies the best result for that backbone in the table, while the prompt-based BERT large configuration reaches a higher absolute average.
Clustering as a separate test of the embeddings
The authors also ask whether the trained vectors form useful groups when K-means is run as an evaluation procedure. In this experiment, the output groups are compared with reference categories. That is a different role for clustering from its role in the training algorithm. During training, cluster assignments help construct comparisons without reference labels. During evaluation, labels provide a point of comparison for the groups formed from the final embeddings.
The first dataset is DBpedia, which the paper describes as an ontology classification dataset derived from Wikipedia. It has 14 reference classes, and the evaluation uses K-means with K=14. The measure is adjusted mutual information, or AMI, which measures agreement between the cluster assignments and the reference labels while accounting for agreement expected by chance. The appendix explains that matching assignments score 1 under this measure and that random assignments have an expected score of 0.
K-means on DBpedia sentence embeddings by adjusted mutual information
Non-prompt ClusterNS gives the strongest agreement with the DBpedia classes.
The numbers
| System or setting | Adjusted mutual information |
|---|---|
| RoBERTa | 0.6926 |
| SimCSE | 0.7078 |
| ClusterNS (this paper) | 0.7355 |
The DBpedia result is consistent with the final sentence space supporting more useful distinctions than the original RoBERTa embeddings, with SimCSE intermediate between those embeddings and ClusterNS. Its significance is that the learned vectors can help a downstream grouping procedure recover known categories. It gives no direct count of how many training neighbors were correctly flagged as false negatives, since the evaluation concerns the final vectors and a separate set of group assignments.
The broader short-text evaluation uses 8 datasets. These include AgNews, Biomedical, SearchSnippets and StackOverflow, as well as the GoogleNews variants and Tweet. The metric here is clustering accuracy. Because the group numbers output by K-means have no inherent correspondence with the reference categories, the authors match groups to labels before scoring, using the Hungarian algorithm. For this comparison they reproduce the SimCSE baselines from the available checkpoints.
With BERT base, the average clustering accuracy moves from 57.97 for SimCSE to 62.31 for non-prompt ClusterNS. The authors give the improvement as 4.34. StackOverflow shows a particularly large change, from 50.78 to 72.92. On AgNews the corresponding scores are 74.46 and 77.38, while Tweet goes from 54.71 to 53.71. BERT base thus shows gains across several datasets alongside an exception where the direction reverses.
With RoBERTa base, the average moves from 57.31 for SimCSE to 57.74 for ClusterNS. SearchSnippets improves from 46.90 to 52.55, and StackOverflow improves from 69.00 to 74.38. AgNews gives the opposite ordering, with 69.71 for SimCSE and 65.00 for ClusterNS. Biomedical also favors SimCSE, at 37.35 compared with 36.38. The mixed outcomes are important because the large improvement with BERT base would give an incomplete picture on its own. Across encoders, there is evidence that the representations can help clustering, with gains depending on the dataset and backbone.
Transfer to other tasks
An appendix evaluates the non-prompt embeddings on seven transfer tasks with default SentEval configurations. The collection includes MR, CR, SUBJ and MPQA, alongside SST-2, TREC and MRPC. These scores test whether the representations are useful in the corresponding downstream evaluations. They give a different view from STS rank correlation or agreement between an entire partition and reference categories.
Without the auxiliary masked language modeling task, the average transfer score for BERT base is 85.81 with SimCSE and 85.66 with ClusterNS. For RoBERTa base, the corresponding values are 84.84 and 85.35. When the auxiliary task is used, SimCSE and ClusterNS obtain averages of 86.64 and 86.95 with BERT base, and 86.90 and 87.17 with RoBERTa base. The paper’s transfer claim is accordingly more qualified than the main STS result. ClusterNS leads in most of these paired average comparisons, and the configuration with the auxiliary task matters to the pattern.
What the ablations show
The harder comparison supplies the larger gain
The main ablation tests non-prompt ClusterNS with BERT base and RoBERTa base on the STS test sets. The authors remove each of the two interventions in turn and change how the clusters are selected. Using the same encoder and evaluation metric within each set of comparisons helps connect an observed change to the part of the training recipe that was altered.
For BERT base, the full system has an average Spearman correlation of 77.55. Removing the false-negative treatment leaves 76.99. Removing the added hard negatives leaves 76.03, slightly below the SimCSE result of 76.25. For RoBERTa base, the full system reaches 77.98. Removing the false-negative component gives 77.83, and removing the hard negatives gives 77.22. The SimCSE value in that group is 76.57. The decline from removing hard negatives is larger in both encoder settings. The remaining false-negative treatment on its own falls below the baseline with BERT base and stays above it with RoBERTa base.
The authors interpret the stronger hard-negative result in light of what each component has to accomplish. A nearby centroid supplies a synthetic, controlled challenge without requiring the system to identify a specific mislabeled sentence. The false-negative intervention relies on a coarser inference from a real sentence’s cluster membership to its relationship with the anchor. The ablation tells how the completed training procedures compare. It gives indirect evidence about the quality of that inference because effects from a false-negative decision are being measured through the final embeddings.
The substitutions also test whether the choice of cluster matters. Replacing the next center with the most similar one gives averages of 76.97 for BERT base and 77.84 for RoBERTa base. The center of the anchor’s own group is close by construction, so it is a plausible choice if difficulty alone is the goal. The observed drop supports the paper’s decision to require a different group. Replacing the cluster choices for both roles with random clusters gives 76.77 for BERT base and 77.85 for RoBERTa base. Both random settings trail their full counterparts. Because this random substitution changes both roles, it puts the combined selection rule to the test and leaves their individual contributions to the removal experiments.
How hard negatives behave during training
The authors follow several kinds of sentence similarity after centroid initialization in non-prompt ClusterNS with RoBERTa base. The ordinary in-batch negatives become less similar to anchors rapidly as training proceeds. The chosen hard negatives stay more similar to anchors than those ordinary negatives do, while the known positives remain more similar still. That pattern fits the design. The extra centroid remains competitive in a comparison as many other alternatives become easy to separate.
The clustering analysis follows additional relationships. Similarity between centroids goes down, which the authors interpret as the groups spreading through the space. Similarity between a sentence and its closest centroid stays high, and the chosen alternative centroids maintain relatively high similarity to their anchors. Same-cluster sentence pairs score higher on average than ordinary batch negatives. Considered with the separate positive-pair series, these observations fit the premise that there is an intermediate region of similarity occupied by some within-cluster neighbors. They describe averages across comparisons. The identity and meaning relationship of any individual pair remain unresolved by the curves.
To vary how difficult the centroid negatives become, the authors change the initialization threshold σ. Delaying the start by lowering the threshold leads to higher anchor–hard-negative similarity in this experiment. With BML, σ at 0.2 gives a final average hard-negative similarity of 0.1814 and an average STS test correlation of 77.02. At 0.4 the corresponding values are 0.1572 and 77.98. At 0.6 they are 0.1442 and 77.30. The highest STS score appears at the intermediate setting. Starting the clustering later and obtaining a closer negative are consequently insufficient on their own to pick the best configuration.
The parallel runs without BML help show why the threshold result should be read in context. At 0.2, hard-negative similarity is 0.1797 and the average STS test score is 77.43. At 0.4, the values are 0.1574 and 77.83. At 0.6, they are 0.1453 and 77.46. The intermediate threshold also has the highest average in these runs without the margin. The margin’s effect itself changes across the settings. At 0.4 its addition corresponds to a higher STS average, while at 0.2 and 0.6 it corresponds to lower averages. This is evidence that the two interventions have to be considered together with the timing that produced their cluster assignments.
The threshold experiment and the nearest-centroid replacement both question a simple rule of maximizing the negative’s similarity to the anchor. They test different changes. The replacement alters which center is selected at a given point, whereas the threshold alters when the clustering starts to participate in training. In the threshold experiment, the realized difficulty of the resulting negatives is observed through the average similarity at the final checkpoints. The outcome combines that difficulty with changes in the sequence of assignments made along the way.
How much to trust a same-cluster assignment
The authors test what happens if every sentence flagged as a possible false negative is masked or treated as a positive. The complete system reaches 77.98 on the STS test average. Without BML it reaches 77.83, and with the flagged examples masked it reaches 77.40. Treating all flagged examples as positives drops the average to 42.33. This is the largest change among the strategies in that comparison and gives a concrete test of the risk of overinterpreting cluster membership.
Masking and promotion are different decisions about ambiguous evidence. Masking removes the corresponding contrastive comparisons. Promotion creates positive training pressure for every selected neighbor. BML keeps a relative range for the selected pair, and its penalties activate when the pair escapes that range. The outcome supports that limited use of the candidates in this setting. The similar averages for the full system and the system without BML also give a sense of the margin’s observed contribution when the other clustering machinery is already in place.
The paper illustrates the issue with clusters containing sentences related to religion and music. Several examples in the religion group describe institutions, people or practices associated with worship. They share enough subject matter to explain why an encoder might put them in the same part of the space. A description of a church and a description of a liturgical event can concern the same broad domain while supporting different similarity judgments at the sentence level. The music example also includes members whose link to the topic is less evident. These examples show why a cluster can be useful for identifying potentially related text and still be too broad to supply positive pairs automatically.
The authors also track the prevalence of possible false negatives during training. Their plotted rate is based on membership in clusters with more than two elements, using intra-cluster membership as the defining signal. The rate stays high in their analysis of non-prompt RoBERTa base. Because the statistic comes from the same assignment rule used to flag candidates, it measures how often the procedure finds such candidates. The case examples and the alternative treatments help interpret the consequences of that frequency. An independently judged set of candidate pairs would be needed to estimate how often the flags correspond to actual semantic errors in ordinary batch training.
What changes in the shape of the embedding space
The paper analyzes alignment and uniformity on STS-B. For these calculations, the authors use sentence pairs with a reference score higher than 4 as positives. This defines the evaluation pairs for the geometry analysis. During contrastive training, the known positive for an unlabeled sentence comes from dropout or prompting. The two uses of “positive” involve different sources of evidence.
Alignment is the expected squared distance between embeddings of positive pairs.
L_align = E₍ₓ,ₓ⁺₎∼p_pos [‖f(x) − f(x⁺)‖²]
L_align is the alignment measure, and E denotes an expectation, an average with respect to the specified distribution. x and x⁺ are the two texts of a positive pair, and the symbol ∼ indicates that pairs are taken from the positive-pair distribution p_pos. f is the sentence encoder. Its outputs are compared by subtracting the vectors and taking the squared Euclidean norm, written ‖ · ‖². Lower alignment values mean the positive pairs are closer by this measure.
Uniformity is defined from distances between sentences sampled across the data. The paper writes it as a logarithm of an expected exponential of negative distance.
L_uniform = log E₍ₓ,ᵧ₎∼p_data [exp(−2‖f(x) − f(y)‖)]
L_uniform is the uniformity measure, log is the natural logarithm, and E is the expectation. The sentences x and y come from the data distribution p_data, as indicated by ∼. The encoder f gives a vector for each sentence, ‖ · ‖ denotes Euclidean distance when applied to their difference, and exp is the exponential function. The coefficient −2 makes nearby pairs contribute more to the expectation than distant ones. Lower uniformity values are better in the paper’s comparisons, since a space where many sentence vectors crowd together produces larger contributions from nearby pairs.
The geometry results point in different directions for the two training recipes. The authors describe SimCSE as having good uniformity but weaker alignment compared with the original BERT and RoBERTa embeddings. The non-prompt ClusterNS result improves alignment while giving up some of the stronger uniformity. For PromptRoBERTa, the authors observe the reverse starting pattern, and the prompt-based ClusterNS variant improves uniformity. The figures also show that RoBERTa and the untuned PromptRoBERTa can have very small alignment values together with weak uniformity. A crowded space can make genuine matches close simply because many sentences are close. Reading both measures together makes the geometry easier to interpret than reading either in isolation.
Batch size and centroid initialization
The appendix compares smaller batch sizes and cluster counts with the settings used in the main experiments. In the authors’ comparisons, smaller settings perform worse. They suggest several connected reasons. A larger batch supplies more alternatives for ordinary contrastive training. More clusters allow finer distinctions among groups. A small batch also restricts how many groups can receive representatives. These comparisons show that the extra clustering procedure benefits from the conditions under which it was tested. The effects of batch size include changes to the ordinary contrastive comparison set as well as to the evidence available for updating centers.
The authors also compare their local initialization with global initialization from embeddings of the whole training dataset. For non-prompt RoBERTa base, local initialization gives an average STS score of 77.98, and the global version gives 77.81. The associated similarity plots reveal different behavior. Under global initialization, centers stay highly similar to one another and the selected hard negatives have low similarity to their anchors. The authors interpret this configuration as providing a weaker training signal. The comparison favors the local initialization implemented in the paper, even though the global alternative uses more data when starting the centers.
Limitations
Limits identified by the authors
The authors identify batch memory as a practical limitation. Their modified K-means procedure avoids repeatedly clustering the whole corpus, but it still updates centroids at every active training step and relies on large mini-batches to obtain useful assignments. Large batches consume more GPU memory. The smaller-batch experiments reinforce the practical significance of that constraint because reducing the batch size also changes the quality of the resulting training comparisons. The paper establishes that a local update procedure can work under the reported settings. Its hardware description gives the computing setup for the experiments, with total resource use left unspecified.
The second stated limitation is the accuracy of false-negative identification. The assignments are produced from the encoder that is still learning, so early or coarse clusters can confuse broad subject overlap with close meaning. Momentum and delayed initialization are ways of obtaining a more stable source of candidates. Neither mechanism supplies semantic labels. The authors leave more accurate discrimination and reduced memory consumption for future work.
Limits visible in the evaluation
The false-negative analyses show that same-cluster members can have higher average similarity than ordinary negatives and that a limited margin can be preferable to masking or positive promotion. The reported prevalence statistic uses cluster membership itself to define candidates. The topic examples likewise illustrate what clustering can capture, without establishing how frequently a flagged pair would be judged a false negative by an independent assessor. The very low STS result from making every candidate positive sets a clear boundary on one use of the assignments. It does not reveal what proportion of the candidate set consists of genuinely close matches or which individual assignments harmed that variant.
The strongest attribution comes from removal and replacement tests on the non-prompt BERT base and RoBERTa base configurations. These show how each component changes those particular systems under STS evaluation. The main table also includes prompt-based systems and BERT large, but the component-level evidence is narrower than that table. The different effects of BML across initialization thresholds provide an example of why the same contribution should not be assumed for every recipe. A component that helps at one start point can change the training trajectory differently at another.
The main STS table uses single-run results and published baseline scores. In the checklist, the authors report later repetitions with 5 random seeds for their systems and describe standard deviations of about 0.1 to 0.2, as well as statistical significance. The main comparison does not attach a spread to each row or each paired difference. That matters when reading small gaps among the strongest alternatives. The paper also says it uses standard public splits and earlier processing, without listing the number of examples in each split. The reported correlations are sufficient to describe the ranking of the table, while the precision of small differences is harder to judge for every individual comparison.
Finally, the tasks probe different properties of the trained vectors. A better STS average means that the embeddings more closely reproduce reference rankings of sentence similarity across the reported collection. Better clustering accuracy or AMI indicates greater agreement with categories under the paper’s grouping evaluation. The short-text and transfer tables contain gains and losses, and the main STS table contains reversals on individual datasets. Taken together, these results support better average STS performance across the tested ClusterNS integrations and a more variable downstream benefit. The benchmark results leave the value of the training procedure for other datasets, tasks and encoder families open.
What came after
Capturing the Relationship Between Sentence Triplets (2024) cites ClusterNS and studies relationships among sentence triplets in machine-generated and human-written text to improve sentence embeddings. Its stated focus is related to the distinction Deng and colleagues make between comparisons that serve different roles. ClusterNS organizes those roles around an anchor, its designated positive, and alternatives identified with the help of cluster membership. The later paper’s title establishes a focus on triplet relationships and the two sources of text. The citation establishes a connection between the papers. It leaves open whether the later method implements ClusterNS’s centroid rule, its bidirectional margin, or either of its negative-sampling decisions.
MAST (2026) cites ClusterNS in work on contrastive clustering of short text using a multi-view alignment strategy based on optimal transport. The comparison is useful for distinguishing the place of clustering in the two research questions. For Deng and colleagues, clustering within training generates and qualifies comparisons, and short-text clustering later serves as a test of the learned sentence vectors. MAST names short-text clustering itself as its task and multi-view alignment as part of its strategy. The citation links the work to ClusterNS, while the stated task and method leave the specific role of ClusterNS’s negative-sampling idea undetermined.
Cite
Cite as Jinghao Deng, Fanqi Wan, Tao Yang, Xiaojun Quan and Rui Wang. 2023. Clustering-Aware Negative Sampling for Unsupervised Sentence Representation. Findings of the Association for Computational Linguistics: ACL 2023.
@inproceedings{deng2023clustering,
title = {{Clustering-Aware Negative Sampling for Unsupervised Sentence Representation}},
author = {Jinghao Deng, Fanqi Wan, Tao Yang, Xiaojun Quan and Rui Wang},
booktitle = {Findings of the Association for Computational Linguistics: ACL 2023},
year = {2023},
doi = {10.18653/v1/2023.findings-acl.555},
url = {https://doi.org/10.18653/v1/2023.findings-acl.555}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/deng-2023-clustering-aware-negative-sampling-unsupervised/