Contrastive search is a decoding method that scores each of the top k candidates by both "high model probability" and "not too similar to the words in the preceding context," and picks the word with the highest score. It was proposed by Su et al. (2022). Although it is deterministic and involves no random choice, it avoids repeating the same phrases.
Open-ended text generation has traditionally relied on two kinds of methods.
Methods that maximize probability (greedy decoding, beam search): The text stays consistent with the context, but tends to repeat the same phrases or sentences over and over.
Sampling (top-k, nucleus): Repetition decreases, but because words are chosen at random, the text can drift semantically from the preceding context or contradict it.
Contrastive search keeps the text consistent with the context by restricting candidates to the most probable ones, and prevents repetition by penalizing candidates that are similar to words that have already appeared.
Procedure
At each step, one word is chosen as follows (Section 3.2 of the paper).
Use the model to compute the next-word probabilities pθ(v∣x<t) and take the top k words as the candidate set V(k).
Append each candidate v to the preceding context x<t, feed it into the model, and obtain the representation hv at the position of v (implementations usually use the hidden state of the last layer).
Compute the cosine similarity between hv and the representation hxj of each word in the preceding context, and take the maximum as the degeneration penalty.
Choose as the next word the candidate with the highest score, defined as "probability" minus "penalty" (formula below).
Append the chosen word to the sequence and repeat steps 1–4 until an end-of-sequence token appears or a set length is reached.
The selection in step 4 is Equation 5 of the paper.
Here, the first term is the model confidence and the second term is the degeneration penalty. s is the cosine similarity.
s(hxi,hxj)=∥hxi∥⋅∥hxj∥hxi⊤hxj
α∈[0,1] weights the two terms; with α=0 the penalty disappears and the method reduces to greedy decoding. The paper states that k is typically set between 3 and 10.
In step 2, each of the k candidates is fed into the model once (together, as a single batch) to obtain its representation. This makes each step more expensive than greedy decoding. In the paper's measurements, contrastive search ran at about the same speed as beam search when k and the beam width were 6 or less, and was faster for larger values (Figure 5).
Example: the word after "Yesterday was sunny. Today is"
The figure at the top of the article shows an example of choosing the next word with k=4 and α=0.6. The next-word probabilities are the same values for what follows "Today is" used in articles such as top-k sampling, and the similarities to the preceding context are illustrative values.
Candidate
Probability p
Max similarity to preceding context (most similar word)
Score 0.4×p−0.6×maxs
sunny
0.30
0.95 (sunny)
−0.45
rainy
0.20
0.55 (sunny)
−0.25
Sunday
0.15
0.30 (Yesterday)
−0.12 (highest)
hot
0.10
0.45 (sunny)
−0.23
Greedy decoding, which chooses by probability alone, would pick the most probable word "sunny" and repeat the same word: "Yesterday was sunny. Today is sunny." In contrastive search, "sunny" is heavily penalized because its representation is very similar to "sunny" in the preceding context, and "Sunday," which has a somewhat lower probability but is not similar to the context, is chosen instead.
Words outside the top 4, such as "cold" and "Monday," are never candidates, no matter how low their similarity is. This prevents low-probability words from being chosen and breaking the text.
Why it works
The paper attributes one cause of repetitive language model output to token representations being concentrated in a narrow region of the space (anisotropy). When representations are similar to one another, the model tends to predict words similar to the preceding context again.
The penalty in contrastive search grows as the candidate's representation becomes more similar to any word in the preceding context. In effect, it uses the closeness of representations to measure "whether the model is about to restate something it has already said."
First term (probability): Together with the restriction to the top k, it ensures that natural words consistent with the context are chosen. It prevents the semantic drift seen in sampling.
Second term (penalty): It steers away from words similar to what has already appeared. It prevents the repetition seen in greedy decoding and beam search.
The penalty only works if token representations are sufficiently distinguishable from one another. The paper also proposes a contrastive training objective (SimCTG) that makes representations easier to distinguish, and reports that the method works best when combined with a model trained with SimCTG. When applied as is to an English GPT-2 trained with ordinary maximum likelihood estimation (MLE), it actually scored lower than nucleus sampling in human evaluation. In Chinese dialogue, on the other hand, representations of MLE models were already distinguishable, and the method was effective without modification.
Experimental results
The paper fine-tuned GPT-2 (117 million parameters) on WikiText-103 and generated 128 tokens following a 32-token prefix. Contrastive search used k=8 and α=0.6, beam search used a width of 10, and nucleus sampling used p=0.95 (excerpt from Table 1).
Model training
Decoding
rep-2 (lower is better)
diversity
MAUVE
coherence
gen-ppl
MLE
Greedy
69.21
0.04
0.03
0.587
7.32
MLE
Beam search
71.94
0.03
0.03
0.585
6.42
MLE
Nucleus
4.45
0.94
0.90
0.577
49.71
MLE
Contrastive
44.20
0.24
0.18
0.599
9.90
SimCTG
Nucleus
4.05
0.94
0.92
0.584
47.19
SimCTG
Contrastive
3.93
0.95
0.94
0.610
18.26
Human text
−
3.92
0.95
1.00
0.644
24.01
The columns are read as follows.
rep-2: The proportion (%) of duplicated two-word sequences (2-grams) in the generated text.
diversity: A combined measure of how few 2- to 4-word sequences are duplicated. Higher means less repetition, and closer to human text means more natural.
MAUVE: How close the distribution of generated text is to that of human text. Higher means more human-like.
coherence: The semantic similarity between the prefix and the generated text (cosine similarity of sentence embeddings). Higher means more consistent with the context.
gen-ppl: The perplexity of the generated text. Closer to human text (24.01) is more natural; too low tends to indicate repetition, too high incoherence.
The combination of SimCTG and contrastive search achieved the best values in repetition, MAUVE, and coherence. In human evaluation (5-point scale, 200 samples each rated by 5 annotators), contrastive search with the SimCTG model also scored significantly higher than nucleus sampling in coherence (3.25 vs. 2.96) and fluency (3.57 vs. 3.34).
In dialogue generation in Chinese (LCCC) and English (DailyDialog), the combination of SimCTG and contrastive search also outperformed greedy decoding, beam search, and nucleus sampling on many criteria in human evaluation.
Caveats
If α is too large, words that stray from the context are more likely to be chosen. The larger the penalty weight, the more often words that are dissimilar to the context are chosen even when their probability is low. In the paper's analysis, both generation diversity and perplexity were close to human text for α∈[0.5,0.8] (Figure 4).
Depends on the quality of the model's representations: As explained in "Why it works" above, in a model whose representations are hard to distinguish, the penalty makes little difference, and the method behaves almost like choosing by probability alone. Before using it, check with a small amount of generation whether repetition actually decreases.
The output is always the same: Because nothing is chosen at random, the same input always yields the same text. When many different texts are needed from the same input, use a sampling method.
Using it in libraries: In Hugging Face's generate, specifying penalty_alpha (α) and top_k (k) enables contrastive search (e.g., penalty_alpha=0.6, top_k=4). In newer versions, this feature may have been moved out of the core library into a separate implementation, so check the documentation of the version you use.
Comparison with other decoding methods
Like top-k sampling, contrastive search narrows the candidates to the top k, but it differs in that it does not choose at random; it settles on one word by score.
Words whose information content is close to the entropy
Random, proportional to probability
Varies each time
Rare
Can occur
Contrastive search (this article)
Top k
Highest probability − similarity to context
Always the same
Rare
Rare
Guidelines for choosing:
Long text with little repetition, with the same output every time: contrastive search.
Many diverse texts from the same input: sampling methods such as nucleus sampling.
The most likely sentence, as in translation or summarization: beam search.
PyTorch example
▶Show code
python
import torch
import torch.nn.functional as F
@torch.no_grad()
def contrastive_step(model, input_ids, past_hidden, k=4, alpha=0.6):
"""One step of contrastive search (batch size 1).
model(ids) is assumed to return (logits [1, length, vocab], last-layer hidden states [1, length, dim]).
past_hidden: representations of the words in the preceding context [length, dim]"""
logits, _ = model(input_ids)
probs = torch.softmax(logits[0, -1], dim=-1)
top_p, top_ids = probs.topk(k) # 1. top-k candidates
# 2. append each candidate to the context, feed all k into the model at once, and get h_v at the candidate position
cand = torch.cat([input_ids.repeat(k, 1), top_ids[:, None]], dim=-1)
_, hidden = model(cand)
h_v = hidden[:, -1] # [k, dim]
# 3. max cosine similarity to the words in the preceding context (degeneration penalty)
sim = F.normalize(h_v, dim=-1) @ F.normalize(past_hidden, dim=-1).T # [k, length]
penalty = sim.max(dim=-1).values
# 4. Equation 5 of the paper
score = (1 - alpha) * top_p - alpha * penalty
best = score.argmax()
return top_ids[best], hidden[best] # chosen word and representations of the sequence including it
@torch.no_grad()
def contrastive_search(model, input_ids, max_new_tokens=50, k=4, alpha=0.6, eos_id=None):
model.eval() # disable dropout (otherwise the representations change every time)
_, hidden = model(input_ids)
past_hidden = hidden[0]
for _ in range(max_new_tokens):
next_id, new_hidden = contrastive_step(model, input_ids, past_hidden, k, alpha)
input_ids = torch.cat([input_ids, next_id.view(1, 1)], dim=-1)
past_hidden = new_hidden # update to representations that include the chosen word
if eos_id is not None and next_id.item() == eos_id:
break
return input_ids
# Scores from the figure at the top of the article (probabilities and similarities are illustrative)
words = ["sunny", "rainy", "Sunday", "hot"]
p = torch.tensor([0.30, 0.20, 0.15, 0.10])
max_sim = torch.tensor([0.95, 0.55, 0.30, 0.45])
score = (1 - 0.6) * p - 0.6 * max_sim
print([round(x, 2) for x in score.tolist()], words[score.argmax()])
# [-0.45, -0.25, -0.12, -0.23] Sunday
# With Hugging Face Transformers (an efficient implementation using the cache)
# model.generate(input_ids, penalty_alpha=0.6, top_k=4, max_new_tokens=128)
FAQ
Q. Does contrastive search require changing the training method as well?
A.
It can be used without changing training, but its effectiveness depends on the model. In the paper, it was not very effective with an English GPT-2 trained in the usual way, and worked best when combined with a model trained with SimCTG, which makes representations easier to distinguish. For Chinese dialogue models, it was effective even with ordinary training.
Q. What values should k and α take?
A.
The paper typically sets k between 3 and 10, using k=8, α=0.6 for document generation and k=5, α=0.6 for dialogue. With α in the range 0.5–0.8, both diversity and perplexity were close to human text.
Q. The name includes "contrastive"; how is it related to contrastive learning?
A.
The paper proposes contrastive learning on the training side (SimCTG) together with contrastive search on the decoding side. SimCTG trains token representations to be pushed apart from one another, and contrastive search uses those representations to choose candidates that are "not similar to the preceding context." As a decoding method, it can be used on its own.