Algorithm Search⌘K

Algorithmresearch

Contrastive search

Also called degeneration penalty decoding.

Choose among the top-k tokens by probability minus a penalty for the maximum cosine similarity of its hidden state to earlier ones.

Time
O(n (k C + V + k (L + n) d)) worst
Space
O((L + n) d + V) extra
Where
C = the cost of one call of the model; L = the length of the prompt; V = the vocabulary size |V|; d = the dimension of the hidden states; k = the number of candidates; n = the number of output tokens
Properties
deterministicnot exactonlineiterative
Origin
Yixuan Su, Tian Lan, Yan Wang, Dani Yogatama, Lingpeng Kong, Nigel Collier, 2022

Contrastive search is a deterministic decoder for an autoregressive language model. At each step it takes the kk most probable next tokens as candidates. For each candidate it runs the model one more step to get the hidden state of that token, and it measures how similar that state is to the states of the tokens already in the text, by the largest cosine similarity. It picks the candidate with the best score, the probability minus a penalty for that similarity. A token that would make the text say again what it already said gets a high penalty. The aim is to keep the coherence of greedy decoding and avoid its loops, without the randomness of sampling. With weight α=0\alpha = 0 on the penalty, or with k=1k = 1, it is greedy decoding. It is a heuristic for autoregressive decoding: Su et al. 2022 reported better human ratings than sampling methods on their tasks, which is a measurement, not a property of the method.

In plain words

Greedy decoding always takes the most likely next word, and so it often says the same thing again and again. Contrastive search looks at the few most likely words, for example the top five. For each of them, it asks how much the text would look like what is already written if that word came next. It then picks the word that is likely and also brings something new. One setting balances the two. When the setting is zero, it is plain greedy decoding. It uses no random draws, so the same input always gives the same text.

The problem

The model gives, for a prefix y<ty_{<t}, the next-token distribution p(⋅∣y<t)p(\cdot \mid y_{<t}) over the vocabulary VV and a hidden-state vector hjh_j for each position j<tj < t (the last layer of a transformer, in practice). For a candidate vv, let hvh_v be the state of the new last position when vv is appended. Contrastive search chooses

yt=arg⁡max⁡v∈V(k){(1−α) p(v∣y<t)−αmax⁡1≤j<ts(hv,hj)},y_t = \arg\max_{v \in V^{(k)}} \Big\{ (1 - \alpha) \, p(v \mid y_{<t}) - \alpha \max_{1 \le j < t} s(h_v, h_j) \Big\},

where V(k)V^{(k)} is the set of the kk most probable tokens, ss is the cosine similarity, and 0≤α≤10 \le \alpha \le 1. This is Equation 5 of Su et al. 2022. The first term is the model confidence and the second the degeneration penalty. The context includes the prompt. The output is a fixed function of the model and the prompt; no objective over whole sequences is maximized.

The algorithm

Tokens are numbered, and the tie rules are fixed: among equal probabilities the smaller index comes first in KK, and among equal scores the first candidate in KK wins.

  1. CONTRASTIVE-SEARCH(model, x, N, k, α) ▷ model(y) = (p, the hidden states of y)
  2. 1y ← x ▷ the prompt
  3. 2for t ← 1 to N do
  4. 3(p, H) ← model(y) ▷ H = the states of all positions of y
  5. 4K ← the min(k, |V|) most probable tokens, from high to low
  6. 5for each v in K do
  7. 6h_v ← the last state of model(y followed by v)
  8. 7score[v] ← (1 − α) p[v] − α · max over h in H of cos(h_v, h)
  9. 8w ← the first v in K with the largest score
  10. 9append w to y
  11. 10if w = "</s>" then return y
  12. 11return y

The calls of line L6 can run as one batch of kk sequences, and with a key-value cache each of them processes one new token only. The states HH of earlier positions do not change, because the model is causal, so they can be kept from step to step.

Example

One step. The context has two states, h1=(1,0)h_1 = (1, 0) and h2=(0.6,0.8)h_2 = (0.6, 0.8). The three candidates are:

candidate pp hvh_v cos to h1h_1 cos to h2h_2 penalty score, α=0.6\alpha = 0.6
A 0.5 (1,0.1)(1, 0.1) 0.9950 0.6766 0.9950 0.2−0.5970=−0.39700.2 - 0.5970 = -0.3970
B 0.3 (0,1)(0, 1) 0 0.8 0.8 0.12−0.48=−0.360.12 - 0.48 = -0.36
C 0.2 (−0.6,0.8)(-0.6, 0.8) −0.6-0.6 0.28 0.28 0.08−0.168=−0.0880.08 - 0.168 = -0.088

With α=0.6\alpha = 0.6, the step picks C, the least probable candidate, because its state points away from the context. With α=0.3\alpha = 0.3 the scores are 0.0515, −0.03-0.03 and 0.056, and C still wins by a little. With α=0.2\alpha = 0.2 they are 0.2010, 0.08 and 0.104, and A wins. With α=0\alpha = 0 the step is greedy and picks A.

A loop. Take a toy model that gives a 0.5, b 0.3, c 0.15 and </s> 0.05 after every prefix, and whose state for a token is a one-hot vector of that token. Greedy decoding writes a a a a forever. Contrastive search with k=3k = 3 and α=0.6\alpha = 0.6 writes a (no penalty yet), then b (a now has penalty 1 and score −0.4-0.4, b has 0.120.12), then c. At the fourth step all three candidates have penalty 1, the probability decides, and it writes a again. The penalty spreads the text over the candidates; it does not forbid a token.

Correctness

The proof is in proofs/correctness.md. It shows that each step returns the first candidate of largest score, that the search makes min⁡(k,∣V∣)+1\min(k, |V|) + 1 calls of the model per step, and that α=0\alpha = 0 or k=1k = 1 gives exactly the output of greedy decoding. It also shows that scaling the hidden states by positive numbers changes nothing, and that since the penalty lies between −1-1 and 1, a candidate vv beats a candidate ww whatever the states when (1−α)(p(v)−p(w))>2α(1 - \alpha)(p(v) - p(w)) > 2\alpha. The tests check the steps against a direct computation of all the scores on random toy models, and the greedy limits against a greedy decoder.

Proof: Contrastive search maximizes its score over the top-k candidates and reduces to greedy decodingfull

We use the notation of the page. At each step the model gives the next-token distribution pp for the prefix yy and the hidden states h1,…,h∣y∣h_1, \ldots, h_{|y|} of its positions; for a candidate vv, hvh_v is the state of the last position of yvy v. The cosine similarity is s(a,b)=a⋅b/(∥a∥∥b∥)s(a, b) = a \cdot b / (\lVert a \rVert \lVert b \rVert), and we set s(a,b)=0s(a, b) = 0 when aa or bb is the zero vector. The score of a candidate is

score(v)=(1−α) p(v)−αmax⁡1≤j≤∣y∣s(hv,hj),\text{score}(v) = (1 - \alpha) \, p(v) - \alpha \max_{1 \le j \le |y|} s(h_v, h_j),

with 0≤α≤10 \le \alpha \le 1, and the maximum over an empty context is 0.

Lemma 1 (termination and cost). CONTRASTIVE-SEARCH runs at most NN steps. Each step makes k′+1k' + 1 calls of the model, where k′=min⁡(k,∣V∣)k' = \min(k, |V|), and appends one token.

Proof. The loop of line L2 runs at most NN times. Line L3 makes one call, and line L6 makes one call per candidate. □\square

Lemma 2 (the step). Let KK be the list of line L4: the k′k' most probable tokens, sorted by probability from high to low, with the smaller index first on ties. The token ww of line L8 has the largest score among the tokens of KK, and among the tokens of largest score it is the first one in KK.

Proof. That KK holds k′k' tokens of largest probability is the exchange argument of top-k sampling. Line L7 computes the score of each candidate. Line L8 scans the scores in the order of KK and replaces the best only on a strictly larger score, so it ends at the first candidate of largest score. □\square

Theorem 3 (greedy limits). If α=0\alpha = 0, or if k=1k = 1, CONTRASTIVE-SEARCH returns the output of greedy decoding with the tie rule "first index of the largest probability".

Proof. With k=1k = 1, KK holds one token, the first index of the largest probability, and line L8 must return it. With α=0\alpha = 0, the score is p(v)p(v). The first token of KK has the largest probability, and among the tokens of largest probability it has the smallest index; every later token of KK has a smaller probability, or the same probability and a larger index. So by Lemma 2 the step returns the first token of KK, which is the greedy choice. By induction on the steps, the two decoders build the same prefix, and they stop at the same time. □\square

Lemma 4 (scale of the states). Multiplying every hidden state by the same number c>0c > 0, or each state by its own positive number, does not change any score or the output.

Proof. s(ca,db)=cd (a⋅b)/(∣c∣∥a∥ ∣d∣∥b∥)=s(a,b)s(c a, d b) = cd \, (a \cdot b) / (|c| \lVert a \rVert \, |d| \lVert b \rVert) = s(a, b) for c,d>0c, d > 0. □\square

So only the directions of the states matter. A model that changes the length of its states from layer to layer or from token to token gives the same search.

Proposition 5 (when probability wins). The penalty max⁡js(hv,hj)\max_j s(h_v, h_j) lies in [−1,1][-1, 1]. So for two candidates v,w∈Kv, w \in K,

score(v)−score(w)≥(1−α)(p(v)−p(w))−2α,\text{score}(v) - \text{score}(w) \ge (1 - \alpha)(p(v) - p(w)) - 2 \alpha,

and vv has the larger score, whatever the states, when (1−α)(p(v)−p(w))>2α(1 - \alpha)(p(v) - p(w)) > 2 \alpha. For α=1\alpha = 1, the score is minus the penalty, and the step returns the first candidate of smallest largest similarity to the context.

Proof. The cosine of two vectors lies in [−1,1][-1, 1] by the Cauchy-Schwarz inequality, and it is 0 by definition for a zero vector, so the maximum lies in [−1,1][-1, 1] too. The difference of the penalties of vv and ww is at most 2, which gives the bound. For α=1\alpha = 1 the probability term is 0. □\square

For example, with α=0.6\alpha = 0.6, the bound requires 0.4(p(v)−p(w))>1.20.4 (p(v) - p(w)) > 1.2, which no pair of probabilities satisfies; at that setting the states can always overrule the probabilities among the candidates. With α=0.2\alpha = 0.2, the bound holds when p(v)−p(w)>0.5p(v) - p(w) > 0.5.

Remark (what is not claimed). Contrastive search is deterministic and makes no claim about the probability of its output, which is in general neither the mode nor a sample from the model. Lemma 2 and Theorem 3 say that the code computes the rule of Su et al. 2022. The tests check Lemma 2 against a direct enumeration of the scores on random toy models, Theorem 3 against a greedy decoder, and Lemma 4 by scaling the states.

Complexity

Each step makes one call of the model on the prefix and kk calls for the candidates, k+1k + 1 calls of cost CC in all, or one call plus one batched call. The penalties compare kk states with the L+tL + t states of the context, each a vector of dimension dd, so step tt costs O(k(L+t)d)O(k (L + t) d) for the similarities and O(∣V∣)O(|V|) for the top kk with a selection. For nn output tokens this sums to O(n(kC+∣V∣+k(L+n)d))O(n (k C + |V| + k (L + n) d)). The extra space holds the states of the context, O((L+n)d)O((L + n) d), and one row of probabilities. Su et al. measured a decoding time comparable to that of beam search with a similar width.

Properties

  • Deterministic. The same model, prompt and settings give the same output.
  • Greedy limits. α=0\alpha = 0 and k=1k = 1 both give greedy decoding.
  • Not a search for the mode. The output is usually less probable than the greedy output; the method trades probability for diversity on purpose.
  • Needs hidden states. Unlike the sampling methods, it needs access to the internal states of the model, not only to the probabilities.
  • Scale free. Only the directions of the states matter.

Variants and improvements

  • SimCTG. Su et al. trained the model with a contrastive objective in addition to the usual likelihood, which pushes the states of different tokens apart (a margin of 0.5 in their experiments), so that the cosine penalty separates tokens better.
  • Other similarity measures. Any similarity between the candidate and the context fits the template; cosine on the last hidden layer is the published choice.
  • Sampling with a penalty. A repetition penalty lowers the logits of tokens that already appear, which works on token identity in place of hidden states.
  • Maximal marginal relevance. The score has the same form as maximal marginal relevance in retrieval: relevance minus the largest similarity to what is already chosen.

When to use it

Use contrastive search for open-ended generation, such as continuing a document or a story, when deterministic output is wanted and greedy decoding or beam search repeats itself. Su et al. suggest kk from 3 to 10, and used k=8k = 8 and α=0.6\alpha = 0.6 on Wikitext-103. It costs about kk times more model computation per step than greedy decoding, so it suits settings where a batch of kk candidates is cheap. For translation or short answers, use greedy decoding or beam search; for varied outputs from the same prompt, use sampling.

Pitfalls

  • A large α\alpha gives incoherent text. The example shows the penalty overruling a probability of 0.5 in favor of 0.2. With α\alpha near 1 the method picks whatever is least similar to the context.
  • The penalty uses states, not words. Two different words with similar states are penalized, and a repeated word with a different state is not. The effect depends on the geometry of the states of the model, which is why Su et al. trained it with SimCTG.
  • Cost per step. The kk extra calls are cheap only in a batch with a key-value cache. Without them the method is k+1k + 1 times slower than greedy decoding.
  • Zero vectors. The cosine of a zero vector is undefined. Fix a value (here 0) if states can be zero.

Implementations

The code takes the next-token probabilities and the hidden states of the model as given, through 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.

contrastive_search.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/contrastive-search/. The authors are listed in prov/AYJ2SK.jsonl.

"""Contrastive search (Su et al. 2022) over a given model.

Tokens are integers 0 ... |V| - 1. A model is a function that takes a
sequence of tokens (a tuple of ints) and returns a pair (probs, states):
probs is the next-token distribution, a list of |V| probabilities, and
states is a list with one hidden-state vector (a sequence of floats) per
position of the input. The state of position j may depend only on the
tokens up to j. The code takes these values as given; it does not run or
train a network.
"""

import math
from typing import Callable, List, Optional, Sequence, Tuple

Vector = Sequence[float]
Model = Callable[[Tuple[int, ...]], Tuple[Sequence[float], Sequence[Vector]]]


def cosine(a: Vector, b: Vector) -> float:
    """Return the cosine similarity of a and b, and 0 if either has length 0."""
    na = math.sqrt(math.fsum(x * x for x in a))
    nb = math.sqrt(math.fsum(x * x for x in b))
    if na == 0 or nb == 0:
        return 0.0
    return math.fsum(x * y for x, y in zip(a, b)) / (na * nb)


def top_k_candidates(probs: Sequence[float], k: int) -> List[int]:
    """Return the min(k, |V|) most probable tokens, from high to low, smaller index first on ties."""
    if k < 1:
        raise ValueError("k must be at least 1")
    return sorted(range(len(probs)), key=lambda i: (-probs[i], i))[: min(k, len(probs))]


def degeneration_penalty(state: Vector, context: Sequence[Vector]) -> float:
    """Return the largest cosine similarity of state to a context state, 0 for no context."""
    return max((cosine(state, h) for h in context), default=0.0)


def contrastive_step(
    probs: Sequence[float],
    cand_states: Sequence[Vector],
    context: Sequence[Vector],
    candidates: Sequence[int],
    alpha: float,
) -> Tuple[int, List[float]]:
    """Choose one token among the candidates by the contrastive score.

    cand_states[j] is the hidden state of candidates[j] when it is appended
    to the prefix. The score is (1 - alpha) p(v) - alpha * max cosine to the
    context states. The first candidate (the more probable one) wins ties.
    Return the chosen token and the list of scores.
    """
    if not 0 <= alpha <= 1:
        raise ValueError("alpha must be in [0, 1]")
    scores = []
    for v, h in zip(candidates, cand_states):  # @line L5
        scores.append((1 - alpha) * probs[v] - alpha * degeneration_penalty(h, context))  # @line L7
    best = 0
    for j in range(1, len(scores)):  # @line L8
        if scores[j] > scores[best]:
            best = j
    return candidates[best], scores


def contrastive_search(
    model: Model,
    prompt: Sequence[int],
    max_len: int,
    k: int,
    alpha: float,
    eos: Optional[int] = None,
) -> List[int]:
    """Return the prompt followed by up to max_len tokens chosen by contrastive search.

    Each step calls the model once on the prefix and once on each of the k
    candidate extensions, k + 1 calls in all. The search stops after the
    token eos, if eos is given. With alpha = 0 or k = 1 it is greedy decoding.
    """
    y = list(prompt)  # @line L1
    for _ in range(max_len):  # @line L2
        probs, context = model(tuple(y))  # @line L3
        cands = top_k_candidates(probs, k)  # @line L4
        cand_states = [model(tuple(y) + (v,))[1][-1] for v in cands]  # @line L6
        w, _ = contrastive_step(probs, cand_states, context, cands, alpha)  # @line L8
        y.append(w)  # @line L9
        if w == eos:  # @line L10
            return y
    return y  # @line L11
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_contrastive_search.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/contrastive-search/. The authors are listed in prov/AYJ2SK.jsonl.

import math
import random

from contrastive_search import contrastive_search, contrastive_step, cosine, top_k_candidates
from nlslog import argmax


def random_model(seed, vocab, dim, scale=1.0):
    """A causal toy model: probs and states are fixed random functions of the prefix."""

    def vec(prefix):
        rng = random.Random(f"{seed}|state|{prefix}")
        return [scale * rng.uniform(-1, 1) for _ in range(dim)]

    def model(prefix):
        rng = random.Random(f"{seed}|probs|{prefix}")
        w = [rng.random() for _ in range(vocab)]
        s = math.fsum(w)
        return [x / s for x in w], [vec(prefix[: j + 1]) for j in range(len(prefix))]

    return model


def greedy(model, prompt, n):
    y = list(prompt)
    for _ in range(n):
        y.append(argmax(model(tuple(y))[0]))
    return y


def looping_model(prefix):
    """Every step gives a 0.5, b 0.3, c 0.15, </s> 0.05; the state of a token is its one-hot vector."""
    probs = [0.05, 0.5, 0.3, 0.15, 0.0]
    states = [[1.0 if d == t else 0.0 for d in range(5)] for t in prefix]
    return probs, states


def test_example_step() -> None:
    probs = [0.5, 0.3, 0.2]
    context = [(1.0, 0.0), (0.6, 0.8)]
    cand_states = [(1.0, 0.1), (0.0, 1.0), (-0.6, 0.8)]
    w, scores = contrastive_step(probs, cand_states, context, [0, 1, 2], 0.6)
    assert w == 2
    for got, want in zip(scores, (0.2 - 0.6 / math.sqrt(1.01), -0.36, -0.088)):
        assert abs(got - want) < 1e-12
    assert contrastive_step(probs, cand_states, context, [0, 1, 2], 0.3)[0] == 2
    assert contrastive_step(probs, cand_states, context, [0, 1, 2], 0.2)[0] == 0
    assert contrastive_step(probs, cand_states, context, [0, 1, 2], 0.0)[0] == 0


def test_alpha_zero_and_k_one_are_greedy() -> None:
    for seed in range(40):
        m = random_model(seed, 6, 4)
        g = greedy(m, [0], 6)
        assert contrastive_search(m, [0], 6, 4, 0.0) == g
        assert contrastive_search(m, [0], 6, 1, 0.7) == g


def test_scale_of_the_states_does_not_matter() -> None:
    for seed in range(40):
        a = contrastive_search(random_model(seed, 6, 4, 1.0), [0], 6, 3, 0.6)
        b = contrastive_search(random_model(seed, 6, 4, 7.5), [0], 6, 3, 0.6)
        assert a == b


def test_matches_a_direct_enumeration() -> None:
    rng = random.Random(1)
    for seed in range(40):
        m = random_model(seed, 7, 3)
        k = rng.randint(1, 7)
        alpha = rng.random()
        y = [0]
        out = contrastive_search(m, y, 5, k, alpha)
        for t in range(1, 6):
            prefix = tuple(out[:t])
            probs, context = m(prefix)
            best_v, best_s = None, None
            # the k most probable tokens, by a second method: a stable sort on -p
            for v in sorted(range(7), key=lambda i: -probs[i])[:k]:
                h = m(prefix + (v,))[1][-1]
                s = (1 - alpha) * probs[v] - alpha * max(cosine(h, c) for c in context)
                if best_s is None or s > best_s:
                    best_v, best_s = v, s
            assert out[t] == best_v


def test_breaks_the_loop_that_greedy_falls_into() -> None:
    prompt = [4]
    g = greedy(looping_model, prompt, 3)
    assert g == [4, 1, 1, 1]
    c = contrastive_search(looping_model, prompt, 3, 3, 0.6)
    assert c == [4, 1, 2, 3]
    # once every candidate has been used, the penalty is 1 for all, and probability decides
    assert contrastive_search(looping_model, prompt, 4, 3, 0.6)[-1] == 1


def test_alpha_one_picks_the_least_similar_candidate() -> None:
    probs = [0.6, 0.3, 0.1]
    context = [(1.0, 0.0)]
    cand_states = [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
    assert contrastive_step(probs, cand_states, context, [0, 1, 2], 1.0)[0] == 2


def test_helpers() -> None:
    assert cosine((0.0, 0.0), (1.0, 2.0)) == 0.0
    assert abs(cosine((1.0, 2.0), (2.0, 4.0)) - 1.0) < 1e-12
    assert top_k_candidates([0.2, 0.4, 0.4], 2) == [1, 2]
    # an empty context gives no penalty: the first step from an empty prompt is greedy
    m = random_model(3, 5, 2)
    assert contrastive_search(m, [], 1, 5, 0.9) == [argmax(m(())[0])]
    for bad in (lambda: top_k_candidates([1.0], 0), lambda: contrastive_step([1.0], [(1.0,)], [], [0], 1.5)):
        try:
            bad()
        except ValueError:
            pass
        else:
            raise AssertionError("no ValueError")


def test_stops_at_the_end_token() -> None:
    def model(prefix):
        probs = [0.9, 0.1] if len(prefix) >= 2 else [0.1, 0.9]
        return probs, [[1.0, float(j)] for j in range(len(prefix))]

    out = contrastive_search(model, [1], 10, 2, 0.0, eos=0)
    assert out == [1, 1, 0]

History

Su, Lan, Wang, Yogatama, Kong and Collier proposed contrastive search with the SimCTG training objective in "A contrastive framework for neural text generation", posted on arXiv in February 2022 and published at NeurIPS 2022. They argued that the repetition of greedy decoding and beam search, documented by Holtzman et al. 2020, comes in part from an anisotropic distribution of the token representations, and attacked it from both sides: a training objective that spreads the representations, and a decoder that penalizes similar ones.

References

  1. Yixuan Su, Tian Lan, Yan Wang, Dani Yogatama, Lingpeng Kong and Nigel Collier, A contrastive framework for neural text generation, NeurIPS 2022, Section 3.2, Equation 5 (the score of contrastive search: model confidence minus the degeneration penalty over the top-k candidates), Section 3.1 (the SimCTG objective), and Section 6.4 (decoding speed against beam search)
  2. Yixuan Su, Tian Lan, Yan Wang, Dani Yogatama, Lingpeng Kong and Nigel Collier, A contrastive framework for neural text generation, arXiv 2202.06417, the experiments on Wikitext-103 with k = 8 and alpha = 0.6, and the remark that alpha = 0 gives greedy search
  3. Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes and Yejin Choi, The curious case of neural text degeneration, ICLR 2020, Section 1 and Table 1, the repetition of greedy decoding and beam search that contrastive search aims to avoid

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
  • a scene preset for the example