Algorithm Search⌘K

Algorithmadvanced

Diverse beam search

Also called grouped diverse beam search.

Split the beam into groups and penalize each group for tokens chosen by earlier groups at the same step, to return a varied list.

Time
O(n B (C + V)) worst
Space
O(n B + G V) extra
Where
B = the total beam width G times B'; C = the cost of one call of the model; G = the number of groups; V = the vocabulary size |V|; n = the number of steps
Properties
deterministicnot exactofflineiterative
Origin
Ashwin K. Vijayakumar, Michael Cogswell, Ramprasaath R. Selvaraju, Qing Sun, Stefan Lee, David Crandall, Dhruv Batra, 2018

Diverse beam search returns a list of outputs that differ from each other, from one autoregressive model. A plain beam search of width BB often returns BB outputs that differ only in a word or two near the end. Diverse beam search splits the BB slots into GG groups of B′=B/GB' = B / G. The groups advance one after the other at each step, and each group subtracts a penalty λ\lambda for every time an earlier group chose the same token at this step. The first group is a plain beam search, so the method keeps its best output; the later groups trade a little probability for variety. Like beam search, it is a heuristic: it does not find the most probable outputs, and it gives no guarantee on how different they are.

In plain words

Plain beam search keeps a few good partial texts and grows them together. They tend to copy each other, so the final list says nearly the same thing several times. Diverse beam search makes small teams. The first team works as usual. Each later team must pay a fee to pick a word that an earlier team picked at the same step. A team then picks a different word when the fee is larger than what it loses. At the end you get one or more texts from each team, and the teams went different ways.

The problem

The model gives log⁡p(w∣y)\log p(w \mid y) for every prefix yy and every token ww of the vocabulary VV, which contains </s>. The score of a prefix is the sum of its token log probabilities; all logs are natural logs. The task is to return a short list of finished outputs, ending with </s>, that are probable under the model and not near copies of each other. No single objective defines "diverse", so the method fixes one: at step tt, group gg maximizes

∑y∈beamg(s(y)−λ∑h<g∣{y′∈beamh:yt′=yt}∣),\sum_{y \in \text{beam}_g} \Big( s(y) - \lambda \sum_{h < g} \big|\{ y' \in \text{beam}_h : y'_t = y_t \}\big| \Big),

where s(y)s(y) is the log probability of yy and the inner count is the number of times the earlier groups chose the same token yty_t at this step. Vijayakumar et al. call this count the Hamming diversity, because it is the number of positions where the new token agrees with the tokens of the earlier groups at the same position (see Hamming distance). The diversity term acts on the ranking only; each output keeps its true log probability.

The algorithm

  1. DIVERSE-BEAM-SEARCH(model, N, G, B', λ)
  2. 1beam_g ← { empty prefix with score 0 } for g = 1 .. G; F ← empty list
  3. 2for t ← 1 to N do
  4. 3used ← an empty count of tokens ▷ the tokens chosen at step t so far
  5. 4for g ← 1 to G do
  6. 5for each (y, s) in beam_g, for each w with log p(w | y) > -∞ do
  7. 6candidate (y w) with rank r = s + log p(w | y) - λ · used[w] and score s + log p(w | y)
  8. 7keep the B' candidates with the largest r ▷ ties: the first generated
  9. 8for each kept candidate y w: used[w] ← used[w] + 1
  10. 9a kept candidate that ends with "</s>" goes to F with its score and g; the others form the new beam_g
  11. if every beam is empty then stop
  12. 10return F sorted by score, best first

A candidate that ends with </s> uses one of the B′B' slots of its group at the step it finishes, and then leaves the beam. So a group can shrink. This is one of several conventions for finished hypotheses in beam search; the code and the tests use it for both plain and diverse beam search.

Example

Take the model M1 of greedy decoding: at the empty prefix p(a)=0.5p(a) = 0.5, p(b)=0.4p(b) = 0.4, p(</s>)=0.1p(\text{</s>}) = 0.1; after a, 0.4,0.3,0.30.4, 0.3, 0.3; after b, 0.05,0.05,0.90.05, 0.05, 0.9; after two tokens, </s> has probability 1. Its most probable output is b</s> (0.36), and greedy decoding returns aa</s> (0.2). Run diverse beam search with G=2G = 2 groups of B′=1B' = 1 and λ=0.5\lambda = 0.5.

step group candidates, rank (score) kept
1 1 a −0.693-0.693, b −0.916-0.916, </s> −2.303-2.303 a
1 2 a −1.193-1.193 (−0.693-0.693), b −0.916-0.916, </s> −2.303-2.303 b
2 1 aa −1.609-1.609, ab −1.897-1.897, a</s> −1.897-1.897 aa
2 2 ba −3.912-3.912, bb −3.912-3.912, b</s> −1.022-1.022 b</s>, finished
3 1 aa</s> −1.609-1.609 aa</s>, finished

At step 1, group 1 chose a, so group 2 pays 0.5 for a and chooses b. At step 2 nobody has chosen </s> before group 2, so b</s> pays nothing. The result is b</s> (log⁡0.36=−1.022\log 0.36 = -1.022, group 2) and aa</s> (log⁡0.2=−1.609\log 0.2 = -1.609, group 1): two different outputs, and one of them is the mode.

With λ=0.2\lambda = 0.2, group 2 ranks a at −0.893-0.893 above b at −0.916-0.916, follows group 1, and the result is aa</s> twice. Here diverse beam search misses the mode and returns no variety at all. The switch happens at λ=ln⁡(0.5/0.4)=0.2231\lambda = \ln(0.5 / 0.4) = 0.2231, the gap between a and b at the first step. The test checks both sides.

Correctness

The proof is in proofs/correctness.md. It proves three theorems. First, the first group is exactly a beam search of width B′B', because the count used is empty when it runs; so its best output is the output of that beam search. Second, with λ=0\lambda = 0 every group repeats the first group, so the list holds GG copies of each output. Third, a group never chooses a candidate whose rank is beaten by B′B' other candidates; in particular, when λ⋅c\lambda \cdot c is larger than the score gap between a token used cc times and an unused token, the group prefers the unused one.

These are statements about the search, not about quality. Diverse beam search is not exact: the M1 example with λ=0.2\lambda = 0.2 misses the mode, and the tests compare the output with exhaustive search. With B′B' at least the number of prefixes of the model, the first group keeps every prefix and finds the best output; the test checks this on small random models.

Proof: The first group of diverse beam search is a plain beam searchfull

We use the notation of the page. The model gives log⁡p(w∣y)\log p(w \mid y) for every prefix yy and token ww; the score of a candidate ywy w built from a beam entry (y,s)(y, s) is s+log⁡p(w∣y)s + \log p(w \mid y). All logs are natural logs. Candidates with score −∞-\infty are never formed (line L5).

Define BEAM-SEARCH(B′)(B') as the following procedure, with the same conventions as the code. It starts with the beam {empty prefix, score 0}. At each step t≤Nt \le N it forms the candidates ywy w for every entry (y,s)(y, s) of the beam, in the order of the beam and then of the vocabulary, with score s+log⁡p(w∣y)s + \log p(w \mid y). It keeps the B′B' candidates of largest score, ties broken by the order of generation. The kept candidates that end with </s> go to the finished list, and the others form the next beam. It stops after step NN or when the beam is empty.

Theorem 1 (the first group). For every model, NN, GG, B′B' and λ\lambda, the beams of group 1 of DIVERSE-BEAM-SEARCH at every step, and the outputs it finishes, are those of BEAM-SEARCH(B′)(B').

Proof. By induction on tt, we show that beam1\text{beam}_1 after step tt equals the beam of BEAM-SEARCH(B′)(B') after step tt, in the same order, and that the two procedures finish the same outputs with the same scores at step tt. Before step 1 both beams hold only the empty prefix with score 0 (line L1).

At step tt, line L3 sets used to the empty count, and group 1 runs first in the loop of line L4. So when group 1 forms its candidates at line L6, used[w] =0= 0 for every ww, and the rank of each candidate equals its score. By the induction hypothesis, the beam entries are the same and in the same order, so lines L5 and L6 generate the same candidates in the same order with the same scores as BEAM-SEARCH(B′)(B'). Line L7 keeps the B′B' candidates of largest rank with ties broken by the order of generation, which is the same choice. Line L9 then splits the kept candidates in the same way into finished outputs and the next beam. Line L8 changes only used, which group 1 does not read again in this step. □\square

Corollary 2. The list returned by diverse beam search contains every output finished by BEAM-SEARCH(B′)(B'), with its true score. In particular it contains the best output of BEAM-SEARCH(B′)(B').

Proof. Line L9 adds every finished output of group 1 to FF with its score ss, which is the sum of the true log probabilities of its tokens, not the rank. Line L10 only sorts FF. □\square

Theorem 3 (no penalty). If λ=0\lambda = 0, every group has the same beams at every step as group 1. So every output of FF appears GG times.

Proof. With λ=0\lambda = 0, the rank of a candidate equals its score whatever used holds. All groups start from the same beam (line L1). By induction on tt, if all groups have the same beam before step tt, then each group generates the same candidates in the same order with the same ranks, and line L7 keeps the same ones. □\square

Lemma 4 (the effect of the penalty). Fix a step tt and a group gg, and let u=ywu = y w and u′=y′w′u' = y' w' be two candidates of group gg with scores sus_u and su′s_{u'}. Suppose that at the time group gg ranks them, used[w]=c[w] = c and used[w′]=0[w'] = 0. If λc>su−su′\lambda c > s_u - s_{u'}, then u′u' has the larger rank, so group gg cannot keep uu and drop u′u' unless B′B' other candidates rank above u′u'.

Proof. The ranks are ru=su−λcr_u = s_u - \lambda c and ru′=su′r_{u'} = s_{u'}, and ru′−ru=λc−(su−su′)>0r_{u'} - r_u = \lambda c - (s_u - s_{u'}) > 0. Line L7 keeps the B′B' largest ranks. □\square

What is not claimed. Diverse beam search is not exact. On the model M1 of the page with G=2G = 2, B′=1B' = 1 and λ=0.2\lambda = 0.2, both groups return aa</s> (probability 0.2), while the output b</s> has probability 0.36. At the first step group 2 ranks a at ln⁡0.5−0.2=−0.893\ln 0.5 - 0.2 = -0.893 and b at ln⁡0.4=−0.916\ln 0.4 = -0.916, and keeps a. By Lemma 4 it switches to b exactly when 0.20.2 is replaced by a value larger than ln⁡0.5−ln⁡0.4=0.2231\ln 0.5 - \ln 0.4 = 0.2231. Neither the mode nor any distance between the outputs is guaranteed in general. If B′B' is at least the number of prefixes of positive probability, then by Theorem 1 the first group keeps every prefix, and its finished list contains every output of at most NN tokens, so the best output of the list is the mode. □\square

Complexity

At each step, group gg makes one call of the model for each of its at most B′B' prefixes, and forms at most B′∣V∣B' |V| candidates. The penalty of a candidate is one lookup in a hash table of counts. Over all groups this is BB calls and B∣V∣B |V| candidates per step, as for a plain beam of width BB. Selecting the B′B' best of B′∣V∣B' |V| ranks takes O(B′∣V∣)O(B' |V|) time with linear top-k selection, or O(B′∣V∣log⁡B′)O(B' |V| \log B') with a heap; the code sorts, for clarity. Over nn steps the time is O(nB(C+∣V∣))O(n B (C + |V|)) with linear selection. The beams and the finished list take O(nB)O(n B) tokens, and the candidates of one group O(B′∣V∣)O(B' |V|).

The groups at one step run one after the other, because group gg needs the choices of groups 1..g−11 .. g - 1. Plain beam search can run all BB prefixes in one batch; diverse beam search can batch within a group only. This is a cost in wall time on parallel hardware, not in the operation count.

Properties

  • The first group is plain beam search (a theorem). Its output is the output of a beam search of width B′B', so diverse beam search does not lose that output.
  • Not exact (a theorem by the example). Neither the mode nor the BB most probable outputs are guaranteed.
  • Deterministic. Given the tie rule, the output is fixed.
  • True scores. The penalty changes the ranking during search; the returned scores are the true log probabilities.
  • More variety (a measurement). Vijayakumar et al. measured more distinct n-grams and higher oracle scores on image captioning and other tasks than plain beam search at the same width.

Variants and improvements

  • Other diversity terms. The paper also studies n-gram diversity, which penalizes repeated n-grams, and neural embedding diversity; the Hamming term is the cheapest and the one most toolkits ship.
  • Penalties within a group. A penalty on siblings, children of the same parent, spreads the beam of one group over more parents.
  • Sampling. Stochastic beam search draws kk distinct outputs without replacement exactly from the model, and nucleus sampling draws independent varied outputs. Both give diversity with a probabilistic meaning in place of a penalty.
  • Rerank the list. The varied list is a good candidate set for minimum Bayes risk decoding or maximal marginal relevance.

When to use it

Use diverse beam search when you need several different outputs from a deterministic search, for example caption or reply suggestions, a candidate list for a reranker, or self-consistency decoding with a search in place of sampling. If one output is needed, use plain beam search, since the extra groups only cost time. If the outputs must be a fair sample of the model, use sampling or stochastic beam search.

Pitfalls

  • The strength λ. Too small, and the groups copy each other (the M1 example at λ=0.2\lambda = 0.2); too large, and the later groups choose improbable tokens. Vijayakumar et al. chose λ\lambda by a grid search on held out data, for oracle accuracy, over values from 0.2 to 0.8. Tune it on your task.
  • Same token, different place. The Hamming term compares tokens at the same step only. Two outputs can say the same thing shifted by one word and pay no penalty.
  • Group order. The first group never pays and the last group pays the most. The list is not symmetric across groups, and the later groups have lower scores by design.
  • Finished outputs. As in beam search, decide how finished outputs leave the beam and how lengths are compared (length normalization); a group can end early with only short outputs.

Implementations

The code takes the log probabilities of the model as given, as a function of the prefix, and implements the search around them; it does not run or train a network.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

diverse_beam_search.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diverse-beam-search/. The authors are listed in prov/K6SZXR.jsonl.

"""Diverse beam search with the Hamming diversity penalty (Vijayakumar et al. 2018).

A model is a function that takes the prefix y_1 ... y_t (a tuple of strings)
and returns a dict from each token to log p(w | prefix), in natural log. The
end token is the string "</s>". The code takes these log probabilities as
given; it does not run or train a network.
"""

from collections import Counter
from typing import Callable, Dict, List, Tuple

from nlslog import NEG_INF

EOS = "</s>"

Model = Callable[[Tuple[str, ...]], Dict[str, float]]
Output = Tuple[List[str], float, int]


def diverse_beam_search(
    model: Model, max_len: int, groups: int, width: int, lam: float
) -> List[Output]:
    """Return the finished outputs of all groups as (tokens, log p, group).

    The beam has groups * width slots, split into groups of width slots. At
    each step, group g ranks its candidates by log p minus lam times the
    number of times the earlier groups chose the same last token at this
    step. A candidate that ends with "</s>" leaves the beam as a finished
    output. Outputs that are still open after max_len tokens are dropped.
    The result is sorted by log p, best first; on ties the lower group and
    the earlier finish come first.
    """
    if groups < 1 or width < 1 or max_len < 1:
        raise ValueError("groups, width and max_len must be at least 1")
    beams: List[List[Tuple[Tuple[str, ...], float]]] = [[((), 0.0)] for _ in range(groups)]  # @line L1
    finished: List[Output] = []
    for t in range(max_len):  # @line L2
        used: Counter = Counter()  # @line L3
        for g in range(groups):  # @line L4
            cand = []
            for y, s in beams[g]:  # @line L5
                for w, lp in model(y).items():
                    if lp == NEG_INF:
                        continue
                    cand.append((s + lp - hamming_penalty(w, used, lam), s + lp, y + (w,)))  # @line L6
            order = sorted(range(len(cand)), key=lambda i: (-cand[i][0], i))
            chosen = [cand[i] for i in order[:width]]  # @line L7
            beams[g] = []
            for _, s, y in chosen:
                used[y[-1]] += 1  # @line L8
                if y[-1] == EOS:  # @line L9
                    finished.append((list(y), s, g))
                else:
                    beams[g].append((y, s))
        if not any(beams):
            break
    order = sorted(range(len(finished)), key=lambda i: (-finished[i][1], finished[i][2], i))
    return [finished[i] for i in order]  # @line L10


def hamming_penalty(token: str, used: Counter, lam: float) -> float:
    """Return the Hamming diversity term lam * (the number of earlier uses of token)."""
    return lam * used[token]
nlslog.py 152 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Log-space arithmetic and semirings for the natural-language-and-speech pages.

Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.

The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:

    PROB      probabilities         plus = +        times = *   zero = 0       one = 1
    LOG       log probabilities     plus = log_add  times = +   zero = -inf    one = 0
    VITERBI   log probabilities     plus = max      times = +   zero = -inf    one = 0
    TROPICAL  costs -log p          plus = min      times = +   zero = +inf    one = 0
    LOG_COST  costs -log p          plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
    BOOLEAN   truth values          plus = or       times = and zero = False   one = True
    COUNTING  path counts           plus = +        times = *   zero = 0       one = 1

This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""

import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence

NEG_INF = float("-inf")
POS_INF = float("inf")


def safe_log(p) -> float:
    """Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
    if p < 0:
        raise ValueError("log of a negative number")
    if p == 0:
        return NEG_INF
    return math.log(p)


def log_add(a: float, b: float) -> float:
    """Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).

    log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
    """
    if a < b:
        a, b = b, a
    if b == NEG_INF or a == POS_INF:
        return a
    return a + math.log1p(math.exp(b - a))


def log_sum(xs: Iterable[float]) -> float:
    """Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
    xs = list(xs)
    if not xs:
        return NEG_INF
    m = max(xs)
    if m == NEG_INF or m == POS_INF:
        return m
    return m + math.log(math.fsum(math.exp(x - m) for x in xs))


def log_normalize(xs: Sequence[float]) -> List[float]:
    """Return the list x - log_sum(xs): log values whose exps sum to 1.

    Raise ValueError if every value is NEG_INF (nothing to normalize).
    """
    z = log_sum(xs)
    if z == NEG_INF:
        raise ValueError("every weight is zero")
    return [x - z for x in xs]


def log_softmax(xs: Sequence[float]) -> List[float]:
    """Return log softmax(xs): the logits xs turned into log probabilities."""
    return log_normalize(xs)


def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
    """Return the probabilities exp(x / temperature) / sum, computed stably.

    The temperature must be positive. Logits of NEG_INF get probability 0.
    """
    if not temperature > 0:
        raise ValueError("the temperature must be positive")
    m = max(xs)
    if m == NEG_INF:
        raise ValueError("every logit is -inf")
    es = [math.exp((x - m) / temperature) for x in xs]
    s = math.fsum(es)
    return [e / s for e in es]


def argmax(xs: Sequence[Any]) -> int:
    """Return the first index of a largest value. Raise ValueError if xs is empty."""
    if len(xs) == 0:
        raise ValueError("argmax of an empty sequence")
    best = 0
    for i in range(1, len(xs)):
        if xs[i] > xs[best]:
            best = i
    return best


@dataclass(frozen=True)
class Semiring:
    """A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""

    name: str
    plus: Callable[[Any, Any], Any]
    times: Callable[[Any, Any], Any]
    zero: Any
    one: Any
    idempotent: bool


def _add(a, b):
    return a + b


def _mul(a, b):
    return a * b


def _log_add_cost(a: float, b: float) -> float:
    return -log_add(-a, -b)


PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)


def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring sum of xs, and sr.zero for an empty input."""
    acc = sr.zero
    for x in xs:
        acc = sr.plus(acc, x)
    return acc


def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring product of xs, and sr.one for an empty input."""
    acc = sr.one
    for x in xs:
        acc = sr.times(acc, x)
    return acc
test_diverse_beam_search.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diverse-beam-search/. The authors are listed in prov/K6SZXR.jsonl.

import math
import random
from collections import Counter

from diverse_beam_search import EOS, diverse_beam_search, hamming_penalty
from nlslog import NEG_INF, log_normalize, safe_log

M1 = {
    (): {"a": 0.5, "b": 0.4, EOS: 0.1},
    ("a",): {"a": 0.4, "b": 0.3, EOS: 0.3},
    ("b",): {"a": 0.05, "b": 0.05, EOS: 0.9},
}


def m1(prefix):
    probs = M1.get(tuple(prefix), {"a": 0.0, "b": 0.0, EOS: 1.0})
    return {w: safe_log(p) for w, p in probs.items()}


def random_model(seed, vocab, n):
    def model(prefix):
        if len(prefix) >= n - 1:
            return {w: (0.0 if w == EOS else NEG_INF) for w in vocab}
        rng = random.Random(f"{seed}|{' '.join(prefix)}")
        raw = [math.log(rng.random() ** 2 + 1e-3) for _ in vocab]
        return dict(zip(vocab, log_normalize(raw)))

    return model


def exhaustive(model, n):
    out = []

    def rec(prefix, s):
        for w, lp in model(tuple(prefix)).items():
            if lp == NEG_INF:
                continue
            if w == EOS:
                out.append((prefix + [w], s + lp))
            elif len(prefix) + 1 < n:
                rec(prefix + [w], s + lp)

    rec([], 0.0)
    return out


def beam_search(model, max_len, width):
    """Plain beam search with the same rules: finished outputs leave the beam."""
    beam, finished = [((), 0.0)], []
    for _ in range(max_len):
        cand = []
        for y, s in beam:
            for w, lp in model(y).items():
                if lp != NEG_INF:
                    cand.append((s + lp, y + (w,)))
        order = sorted(range(len(cand)), key=lambda i: (-cand[i][0], i))
        beam = []
        for i in order[:width]:
            s, y = cand[i]
            if y[-1] == EOS:
                finished.append((list(y), s))
            else:
                beam.append((y, s))
        if not beam:
            break
    return sorted(finished, key=lambda t: -t[1])


def test_example_two_groups() -> None:
    out = diverse_beam_search(m1, 3, groups=2, width=1, lam=0.5)
    assert [(y, g) for y, _, g in out] == [(["b", EOS], 1), (["a", "a", EOS], 0)]
    assert math.isclose(math.exp(out[0][1]), 0.36)
    assert math.isclose(math.exp(out[1][1]), 0.2)
    # Below ln(0.5 / 0.4) the penalty is too weak and both groups give aa</s>.
    assert math.isclose(math.log(0.5 / 0.4), 0.22314355131420976)
    out = diverse_beam_search(m1, 3, groups=2, width=1, lam=0.2)
    assert [y for y, _, _ in out] == [["a", "a", EOS], ["a", "a", EOS]]
    out = diverse_beam_search(m1, 3, groups=2, width=1, lam=0.23)
    assert [y for y, _, _ in out] == [["b", EOS], ["a", "a", EOS]]


def test_hamming_penalty_counts_uses() -> None:
    used = Counter(["a", "a", "b"])
    assert hamming_penalty("a", used, 0.5) == 1.0
    assert hamming_penalty("b", used, 0.5) == 0.5
    assert hamming_penalty("c", used, 0.5) == 0.0


def test_one_group_is_beam_search() -> None:
    vocab = ["a", "b", "c", EOS]
    for seed in range(60):
        model = random_model(seed, vocab, 5)
        for width in (1, 2, 3):
            got = [(y, s) for y, s, _ in diverse_beam_search(model, 5, 1, width, 0.7)]
            want = beam_search(model, 5, width)
            assert [y for y, _ in got] == [y for y, _ in want]


def test_first_group_is_plain_beam_search() -> None:
    # Group 1 sees no penalty, so its outputs are those of beam search of width B'.
    vocab = ["a", "b", "c", EOS]
    for seed in range(60):
        model = random_model(seed, vocab, 5)
        out = diverse_beam_search(model, 5, 3, 2, 1.0)
        first = sorted([(y, s) for y, s, g in out if g == 0], key=lambda t: -t[1])
        want = beam_search(model, 5, 2)
        assert [y for y, _ in first] == [y for y, _ in want]
        assert out[0][1] >= want[0][1] - 1e-12


def test_zero_penalty_repeats_beam_search() -> None:
    vocab = ["a", "b", "c", EOS]
    for seed in range(40):
        model = random_model(seed, vocab, 5)
        out = diverse_beam_search(model, 5, 3, 2, 0.0)
        want = [y for y, _ in beam_search(model, 5, 2)]
        for g in range(3):
            mine = [y for y, s, gg in sorted(out, key=lambda t: -t[1]) if gg == g]
            assert mine == want


def test_wide_groups_are_exact() -> None:
    vocab = ["a", "b", EOS]
    for seed in range(40):
        model = random_model(seed, vocab, 4)
        everything = exhaustive(model, 4)
        out = diverse_beam_search(model, 4, 2, len(everything), 3.0)
        best = max(s for _, s in everything)
        assert math.isclose(out[0][1], best)
        for y, s, _ in out:
            assert any(o == y and math.isclose(sc, s) for o, sc in everything)


def test_penalty_raises_diversity() -> None:
    vocab = ["a", "b", "c", "d", EOS]
    distinct0 = distinct1 = 0
    for seed in range(60):
        model = random_model(seed, vocab, 5)
        out0 = diverse_beam_search(model, 5, 4, 1, 0.0)
        out1 = diverse_beam_search(model, 5, 4, 1, 2.0)
        distinct0 += len({tuple(y) for y, _, _ in out0})
        distinct1 += len({tuple(y) for y, _, _ in out1})
    assert distinct0 == 60
    assert distinct1 > 3 * distinct0

History

Vijayakumar, Cogswell, Selvaraju, Sun, Lee, Crandall and Batra posted diverse beam search on arXiv in 2016 and published it at AAAI 2018, with experiments on image captioning, machine translation and visual question generation. They described it as doubly greedy: greedy over time, as beam search is, and greedy over groups, since each group fixes its choice before the next one runs.

References

  1. Ashwin K. Vijayakumar, Michael Cogswell, Ramprasaath R. Selvaraju, Qing Sun, Stefan Lee, David Crandall and Dhruv Batra, Diverse beam search for improved description of complex scenes, AAAI 2018, pages 7371 to 7379, the doubly greedy group by group search, the Hamming diversity term, and the choice of the diversity strength by grid search on held out data
  2. Ashwin K. Vijayakumar et al., Diverse beam search, decoding diverse solutions from neural sequence models, arXiv 1610.02424, 2016, the first version of the method

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example