Paraphrase Detection and Generation
Module: Natural Language Processing | Difficulty: Advanced
What You'll Learn
- 1Score sentence pairs with cosine similarity over encoded representations
- 2Train dual encoders with temperature scaled contrastive loss
- 3Choose a benchmark and metric that match the intended deployment
- 4Balance meaning preservation against lexical diversity in generation
Two sentences are paraphrases when they say the same thing in different words. Detection turns that judgment into a label, and generation produces the second sentence from the first. The pair of tasks sits underneath duplicate question detection, search retrieval, data augmentation, and text simplification, and it is unusually unforgiving: a detector can lean on shared vocabulary, while a generator that only copies vocabulary has not paraphrased anything. This lesson covers similarity scoring, the contrastive objective that makes it work, and the constraints that keep generation faithful.
Similarity as a Decision Rule
The simplest system encodes each sentence into a vector and compares them with cosine similarity:
A threshold then converts the score into a label:
The threshold is a product decision rather than a model property. Duplicate question detection in a support queue wants high precision, so rises; recall oriented retrieval wants coverage, so falls and a reviewer absorbs the extra false positives. Reporting a single accuracy without the operating point hides this trade entirely.
An embedding model makes the expensive part cheap. A cross-encoder that runs both sentences through one network must do that once per candidate pair, while a dual encoder computes one vector per sentence and caches it. Measuring similarity against a corpus of ten thousand candidates therefore drops from roughly sixty-five hours of pairwise encoding to about five seconds of vector search, which is the change that put paraphrase scoring inside a search index.
Benchmarks and Metrics
Each dataset rewards a slightly different behavior, and picking the wrong one is a common source of surprising results.
| Benchmark | Pairs | Labels | Reported metric |
|---|---|---|---|
| MRPC | 5,800 | binary paraphrase | accuracy and F1 |
| QQP | about 404,000 | binary duplicate question | accuracy and F1 |
| STS-B | 8,628 | continuous 0 to 5 | Pearson and Spearman |
| PAWS | 108,463 | binary paraphrase | accuracy |
| ParaNMT-50M | 50,000,000 | silver noisy pairs | training corpus only |
PAWS is the dataset that punishes overlap shortcuts. Its pairs recombine words from the same source sentences so both members share most of their vocabulary while meaning different things. Systems trained elsewhere score below 40 percent accuracy on it, and the same architectures reach about 85 percent once PAWS is added to training, with human agreement measured at 92 percent on the Quora subset and 94.7 percent on the Wikipedia subset.
Contrastive Training
A threshold on untrained vectors is useless, so dual encoders learn the geometry. Given an anchor and a true paraphrase, push them together while pushing every other sentence in the batch apart, which gives the temperature scaled InfoNCE objective:
Temperature controls how sharply the loss distinguishes the positive from the negatives. A large flattens the distribution and trains slowly, a small saturates once the positive wins and starves the gradients of the hard negatives that matter most.
Supervised fine-tuning with human labels remains the most reliable single improvement: training on the target pairs lifts a model far more than swapping the pooling layer, which is why PAWS training changes accuracy more than any architectural tweak.
Paraphrase Generation
Generation models the conditional distribution over the rewrite:
Two forces then fight. Faithfulness wants to preserve the meaning of , and diversity wants to differ in wording. Optimization pushes both terms of a combined objective:
The hinge term penalizes any output whose embedding drifts too far from the source, with margin setting how far paraphrasing may wander. Increasing buys safety and loses variety; the usual practice is to tune it on a held-out set scored by a human rated faithfulness rubric rather than by BLEU, since BLEU rewards copying.
Cycle consistency offers a free check: paraphrase into , paraphrase back, and compare the reconstruction with . A large round trip distance signals that meaning was lost even when each individual sentence reads well.
Worked Examples
Worked Code
def cosine(a, b):
num = sum(x * y for x, y in zip(a, b))
den = (sum(x * x for x in a) ** 0.5) * (sum(y * y for y in b) ** 0.5)
return num / den
def predict(a, b, threshold=0.6):
return cosine(a, b) > threshold
pairs = [
((1.0, 0.0, 1.0), (0.0, 1.0, 1.0), False),
((1.0, 0.5, 0.2), (0.9, 0.5, 0.3), True),
((0.1, 0.9, 0.4), (0.8, 0.2, 0.5), True),
((0.5, 0.5, 0.5), (0.5, 0.5, 0.5), True),
]
print("scores:", [round(cosine(a, b), 3) for a, b, _ in pairs])
hits = sum(predict(a, b) == y for a, b, y in pairs)
print("accuracy:", hits / len(pairs))
import math
def sim(a, b):
num = sum(x * y for x, y in zip(a, b))
den = (sum(x * x for x in a) ** 0.5) * (sum(y * y for y in b) ** 0.5)
return num / den
def infonce(z, tau):
n = len(z)
total = 0.0
for i in range(n):
num = math.exp(sim(z[i], z[i]) / tau)
den = sum(math.exp(sim(z[i], z[j]) / tau) for j in range(n))
total -= math.log(num / den)
return total / n
z = [(1.0, 0.0), (0.0, 1.0), (0.7, 0.7)]
for tau in (1.0, 0.5, 0.2):
print(f"tau {tau}: loss {infonce(z, tau):.3f}")
Real-World Applications
- Duplicate question merging - QQP style detectors collapse repeated forum posts before they reach an answerer, so precision protects answer quality.
- Search retrieval - Dual encoders index paraphrases once, letting a query match documents that share no wording with it.
- Data augmentation - Generating paraphrases multiplies a small labeled set, provided the faithfulness hinge keeps labels valid.
- Text simplification and style transfer - A rewrite that preserves meaning while changing register is a paraphrase with an added constraint.
đĄSeparate similarity from paraphrase
Common Mistakes
Optimizing accuracy on MRPC alone
Fix: MRPC is small and imbalanced, so report F1 and check the same model on QQP or PAWS before shipping.
Using BLEU to judge paraphrase quality
Fix: BLEU rewards n-gram overlap, which is the opposite of paraphrasing, so use similarity and human faithfulness ratings instead.
Tuning the threshold on the test set
Fix: Fix the operating point on a development split, then report the test numbers once.
Best Practices
- Normalize embeddings and use cosine similarity so vector length does not leak into the score
- Mine hard negatives inside the batch rather than relying only on random negatives
- Report the threshold together with the metric so results stay comparable across runs
Key Takeaways
- Cosine similarity plus a threshold is a complete detector, and the threshold is a business choice
- InfoNCE with temperature learns the geometry that the threshold then reads
- PAWS pairs share vocabulary but differ in meaning, and scores below 40 percent away from it
- Generation needs a faithfulness margin because fluency alone does not preserve meaning
Frequently Asked Questions
Why is similarity not the same as paraphrase?
Similarity is graded and topical; paraphrase is binary and requires mutual entailment. Two sentences about the same event can contradict each other while staying close in embedding space, so similarity is best treated as a feature feeding a calibrated decision rather than the decision itself.
How should the threshold be chosen?
Pick it on a development set against a stated cost of false positives versus false negatives, then freeze it. If the cost ratio changes, move the threshold and re-report, rather than retraining a model that was never wrong about the ranking.
Does generation need a different model than detection?
Usually yes. Detection benefits from a single joint encoding of both sentences, while generation needs a decoder conditioned on the source. The shared piece is the similarity model used to verify the output after it is produced.
Interview Questions
Q1: What happens to false positives when you lower the similarity threshold?
They rise. Recall improves because more borderline pairs clear the cut, so the threshold must be set against an explicit cost ratio rather than by inspection.
Q2: How do you stop a paraphrase generator from simply copying its input?
Penalize overlap directly with a diversity term and verify the output with a faithfulness check, because copying maximizes similarity and satisfies every similarity based loss.