AI Logic

Decoding

Diverse Beam Search

Updated:

Search of diverse beam search with beam width 2 split into 2 groups (Ξ» = 0.8). Sentences are extended one word at a time from left to right. Group 1 at the top searches normally and produces "I live here"; group 2 at the bottom searches with a penalty of 0.8 on the words group 1 chose at the same time step (I, live, here) and produces "We live there". Below, it is shown that ordinary beam search yields the nearly identical sentences "We live here" and "I live here"

What is diverse beam search?

Diverse beam search is a decoding method that splits the beam into several groups and searches with a penalty that lowers the score of later groups when they choose the same word as earlier groups, producing multiple candidate sentences that differ from one another. It was proposed by Vijayakumar et al. (2018). Its computation and memory are almost the same as those of ordinary beam search.

Ordinary beam search can also output as many sentences as the beam width BB. However, candidates branching off from a single high-probability partial sentence tend to dominate the top, so the BB outputs are often nearly identical sentences that differ only at the end. The paper points out that this is a problem for the following reasons.

  • Wasted computation: Nearly the same computation is repeated for nearly identical sentences.
  • Weak on tasks without a single answer: In tasks with many correct answers, such as image captioning and dialogue responses, being able to produce a variety of candidates matters.

Diverse beam search solves this problem by adding a term representing "the differences between candidates" to the beam search objective (the probability of the whole sentence) and optimizing it group by group in turn.

Procedure

The beam width BB is split into GG groups, each of width Bβ€²=B/GB' = B/G. At each time step tt, the beams are extended as follows (Algorithm 1 in the paper).

  1. Group 1 advances ordinary beam search by one step (no penalty).
  2. Group 2 adds to the score of each candidate (the sum of log probabilities) a term λΔ\lambda \Delta that depends on how it differs from what group 1 chose at this time step, and advances beam search by one step with that score.
  3. Groups 3 and later likewise add the differences from all preceding groups and advance by one step.
  4. Repeat steps 1–3 at each time step until the end of the sentence.
  5. Output the BB sentences from all groups together.

The quantity maximized when extending group gg at time tt is Equation 3 of the paper.

βˆ‘b=1Bβ€²Ξ˜(yb,[t]g)+βˆ‘h=1gβˆ’1Ξ»g Δ(yb,[t]g,Y[t]h)\sum_{b=1}^{B'} \Theta\left(y^g_{b,[t]}\right) + \sum_{h=1}^{g-1} \lambda_g \, \Delta\left(y^g_{b,[t]}, Y^h_{[t]}\right)

Here, Θ(y[t])\Theta(y_{[t]}) is the sum of log probabilities of the partial sentence, Y[t]hY^h_{[t]} is the beam held by group hh at that time step, Ξ”\Delta is the magnitude of the difference between a sentence and the preceding groups, and Ξ»gβ‰₯0\lambda_g \ge 0 is the strength of diversity.

Several ways of measuring the difference Ξ”\Delta are possible, and the paper compares the following.

  • Hamming diversity: Choosing the same word as a preceding group chose at that time step is penalized in proportion to the number of times it was chosen.
  • Cumulative diversity: Counts how many times the same word has been used at the same time step so far, and weakens the penalty once the sentences are sufficiently different.
  • n-gram diversity: Penalizes using an n-gram (a sequence of nn words) that appeared in a preceding group's sentence.
  • Embedding diversity: Uses the similarity of word embeddings (word2vec) to penalize not only the same word but also words with similar meanings.

In the paper's experiments, the simplest, Hamming diversity, gave the best results.

With G=1G = 1, there is no group that receives a penalty, and the method is the same as ordinary beam search. With G=BG = B, each group has a width of 1, the setting that puts the most weight on diversity. The paper uses this setting in its experiments because G=BG = B gave the best results.

Example: splitting beam width 2 into 2 groups

The figure at the top of the article uses the same probabilities as the beam search article, with B=2B = 2 split into G=2G = 2 groups (each of width 1) and Hamming diversity with Ξ»=0.8\lambda = 0.8. The number in each block is the sum of log probabilities (the score).

With ordinary beam search (B=2B = 2), "We live here" (probability 0.216) and "I live here" (0.15) remain at the end. The two sentences share "live here" and differ only in the subject.

With diverse beam search, at each time step the beams are extended in the order group 1 β†’ group 2.

Time stepGroup 1's choiceGroup 2's candidates and scoresGroup 2's choice
Word 1I (βˆ’0.69)I: βˆ’0.69 βˆ’ 0.8 = βˆ’1.49, We: βˆ’0.92, Cats: βˆ’2.30We
Word 2live (βˆ’1.20)live: βˆ’1.02 βˆ’ 0.8 = βˆ’1.82, stay: βˆ’3.22live
Word 3here (βˆ’1.90)here: βˆ’2.33 βˆ’ 0.8 = βˆ’3.13, there: βˆ’3.03there
  • Word 1: In group 2, "I," chosen by group 1, is penalized, so "We" is chosen.
  • Word 2: Group 2's "live" is also penalized, but its score is still higher than the other candidate, "stay," so "live" is chosen. The penalty does not overturn candidates with a large difference in probability.
  • Word 3: "here," the same word as group 1's, is penalized, so "there" is chosen.

The result is "I live here" and "We live there," two sentences that differ more from each other than with ordinary beam search. Note that here the penalty stays in the accumulated score when moving on to the next time step (the same treatment as in many implementations).

In this example, group 1 has a width of 1 and therefore behaves like greedy decoding, so it does not find "We live here" (0.216), the most probable sentence overall. What the paper guarantees is that the first group gives the same result as beam search with width B/GB/G. If all you want is the single most probable sentence, use ordinary beam search.

Why it works

Ordinary beam search reselects all BB beams together "in order of probability," so the descendants of a single strong partial sentence can occupy all the top positions. In the image caption example in Figure 1 of the paper, the five outputs of beam search were paraphrases of nearly the same sentence.

In diverse beam search, each group keeps its own beam, and later groups are penalized for choosing the same word as earlier groups. As a result, each group searches a different part of the search space. The paper also notes the observation that the words near the beginning of a sentence largely determine the diversity of the output. If the first word differs, the rest of the sentence also changes considerably.

In addition, the groups can run in parallel staggered in time, so a sentence of length TT can be produced in T+GT + G steps. There is no need to rerun beam search in its entirety many times, as in an earlier method (Gimpel et al., 2013).

Experimental results

The paper compared results with beam width B=20B = 20 on image captioning (COCO, PASCAL-50S), visual question generation, and English→French machine translation. Two measures were used for evaluation.

  • Oracle@k: The score of the best of the top kk output candidates (SPICE for captions, BLEU-4 for translation). It shows whether a good answer is included among the candidates.
  • Number of distinct n-grams: The number of distinct n-grams in all output candidates divided by the total number of generated words. Higher means more diverse candidates.

Image captioning on COCO (excerpt from Table 1)

MethodSPICEOracle SPICE@5Oracle SPICE@20Distinct 4-grams
Beam search16.2722.9627.345.67
Li & Jurafsky (2016)16.3522.7127.598.94
Diverse beam search16.7823.0828.0913.44

English→French translation (newstest-2013, excerpt from Table 3)

MethodOracle BLEU-4@1Oracle BLEU-4@20Distinct 4-grams
Beam search13.5218.443.23
Diverse beam search13.6918.775.54
  • Diversity: On COCO, distinct 4-grams more than doubled compared with beam search (5.67 β†’ 13.44).
  • Whether good candidates are included: The oracle values also exceeded those of beam search. On PASCAL-50S, Oracle SPICE@20 was 7.24% higher than with beam search.
  • The most probable sentence: On PASCAL-50S, it found a top-1 sentence with higher probability than beam search with the same beam width (log probability βˆ’6.53 vs. βˆ’6.91).
  • Human evaluation: In pairwise comparisons of image captions, diverse beam search captions were preferred 60% of the time. The gap grew with image complexity: about 50% for simple images, about 69% for moderate ones, and about 83% for complex ones.

Caveats

If Ξ»\lambda is too large, ungrammatical sentences appear. The penalty outweighs the model's probabilities, so low-probability words get chosen. The paper determines Ξ»\lambda on validation data and reports that the range 0.2–0.8 worked well for many tasks and datasets.

  • Only exact word matches are considered: Hamming diversity penalizes only identical words, so it cannot distinguish paraphrases or sentences with slightly changed word order. To avoid semantically similar words as well, use embedding diversity.
  • Not suited to tasks that need only one sentence: This method is for when multiple diverse candidates are wanted (candidate image captions, candidate dialogue responses, candidates to be reranked later by another method, etc.).
  • Using it in libraries: In Hugging Face's generate, specify num_beams (BB), num_beam_groups (GG), and diversity_penalty (Ξ»\lambda). The diversity used here is Hamming diversity. 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 beam search, diverse beam search searches deterministically, and its output is always the same. Diversity comes not from randomness but from the penalty between groups.

MethodSource of diversityOutputCandidates per runSuitable tasks
Beam searchNone (in order of probability)Always the sameBB (tend to be similar)Translation, summarization, speech recognition
Diverse beam search (this article)Penalty between groupsAlways the sameBB (different from one another)Image captions, candidate dialogue responses
Top-k samplingRandom choice from the top kkVaries each time1 (collected over many runs)Stories, dialogue
Nucleus samplingRandom choice from the top until the total reaches ppVaries each time1 (collected over many runs)Stories, dialogue
Contrastive searchPenalizes words similar to the preceding contextAlways the same1Long generation that should avoid repetition

Guidelines for choosing:

  • Multiple high-probability candidates that differ from one another, all at once: diverse beam search.
  • The single most likely sentence: ordinary beam search.
  • Many free and diverse texts from the same input: sampling methods.

Contrastive search is also a method that "penalizes what is similar," but the target of the penalty differs. Contrastive search penalizes words similar to the preceding context within the same sentence, preventing repetition within one sentence. Diverse beam search penalizes words that are the same as the candidates of other groups, making multiple candidates differ from one another.

PyTorch example

Show code
python
import math

# Same probabilities as the beam search article (illustrative values). Preceding words -> next-word probabilities
probs = {
    (): {"I": 0.5, "We": 0.4, "Cats": 0.1},
    ("I",): {"live": 0.6, "stay": 0.3, "also": 0.1},
    ("We",): {"live": 0.9, "stay": 0.1},
    ("I", "live"): {"here": 0.5, "alone": 0.3},
    ("We", "live"): {"here": 0.6, "there": 0.3},
}


def diverse_beam_search(num_groups, group_size, steps, lam):
    """Diverse beam search with Hamming diversity (Algorithm 1 in the paper)"""
    groups = [[((), 0.0)] for _ in range(num_groups)]   # (partial sentence, score) per group
    for _ in range(steps):
        chosen_now = []                                   # words chosen by preceding groups at this time step
        for g in range(num_groups):
            candidates = []
            for words, score in groups[g]:
                for w, p in probs.get(words, {}).items():
                    penalty = lam * chosen_now.count(w)   # times preceding groups chose the same word x Ξ»
                    candidates.append((words + (w,), score + math.log(p) - penalty))
            groups[g] = sorted(candidates, key=lambda c: c[1], reverse=True)[:group_size]
            chosen_now += [words[-1] for words, _ in groups[g]]
    return groups


for g, beams in enumerate(diverse_beam_search(num_groups=2, group_size=1, steps=3, lam=0.8)):
    for words, score in beams:
        print("group", g + 1, " ".join(words), round(score, 2))
# group 1 I live here -1.9
# group 2 We live there -3.03

# With lam=0 (no penalty), both groups give "I live here", the same as greedy decoding
print(diverse_beam_search(num_groups=2, group_size=1, steps=3, lam=0.0))


# With Hugging Face Transformers (Hamming diversity)
# outputs = model.generate(
#     input_ids,
#     num_beams=6,              # B
#     num_beam_groups=3,        # G (must divide num_beams)
#     diversity_penalty=0.5,    # Ξ»
#     num_return_sequences=6,
# )

FAQ

Q. How does diverse beam search differ from running sampling many times?
A.

Diverse beam search produces BB mutually different candidates from the high-probability region in a single search, and its output is always the same. Sampling produces a different sentence on each run, but similar sentences may overlap, and low-probability broken sentences may slip in. When you want different candidates of consistent quality side by side, diverse beam search is a better fit.

Q. How many groups G should I use?
A.

In the paper, G=BG = B (each group of width 1) gave the highest rate of good answers among the candidates (oracle values), so it was used in the experiments. Making GG smaller brings each group closer to ordinary beam search, giving a search that puts more weight on the probability of the top sentence.

Q. What value should the diversity strength Ξ» take?
A.

The paper searched for it on validation data and reports that the range 0.2–0.8 worked well for many tasks and datasets. Larger values make the candidates more diverse, but values that are too large produce ungrammatical sentences.

References

  1. A. K. Vijayakumar, M. Cogswell, R. R. Selvaraju, Q. Sun, S. Lee, D. Crandall, and D. Batra, "Diverse Beam Search for Improved Description of Complex Scenes," AAAI, 2018 (arXiv title: "Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models").