Ban tokens and repeated n-grams before sampling

Why it matters Hugging Face generate's no_repeat_ngram_size and bad_words_ids do exactly this.

Production decoders block bad words and stop the model from repeating the same bigram.

Write ban_logits(logits, history, banned, no_repeat_ngram=2). Return a copy of logits with -inf at every banned id, and, if no_repeat_ngram is 2, also at any token t such that the bigram (history[-1], t) already appears in history.

Signaturedef ban_logits(logits, history, banned, no_repeat_ngram=2)

Example

ban_logits([0, 0, 0, 0], [1, 2, 1], [3]) bans 3 and also 2 (the bigram 1,2 already occurred), giving [0, 0, -inf, -inf].

Understand the idea

Before sampling, production decoders edit the logits. Banned words get -inf so they can never be picked. A no-repeat bigram rule also blocks any token that would recreate a pair of tokens already in the text. Only tokens that previously came right after the current last token can do that. Worked example: logits [1, 1, 1, 1, 1], history [2, 4, 2, 3, 2], banned [0]. The last token is 2. Earlier, 2 was followed by 4 and by 3, so tokens 4 and 3 would repeat bigrams (2, 4) and (2, 3). Ban those plus 0. Result: [-inf, 1, 1, -inf, -inf]. Rule: copy the logits; set banned ids to -inf; if no_repeat_ngram is 2 and history has at least one token, for every i where history[i] equals history[-1] and i + 1 < len(history), set logits[history[i + 1]] to -inf. Do not change the input array. Looking at the token before the last one instead is a common mistake. Used in: the no_repeat_ngram_size and bad_words_ids options of generation libraries, and safety filters at decode time.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleban_logits([0, 0, 0, 0], [1, 2, 1], [3])
  • Sample 2: no historyban_logits([1.0, 2.0, 3.0], [], [0])
  • Test 3: several followersban_logits(np.zeros(6), [4, 1, 4, 2, 5, 4], [])