Turn WordPiece tokens back into text by merging ## pieces

Why it matters Showing NER spans, QA answers and masked-word predictions from BERT-style models needs exact detokenization.

BERT-style tokenizers split rare words into pieces and mark every piece after the first with '##'. To show predictions to users you glue those pieces back onto the previous word and drop special tokens.

Write decode_wordpiece(tokens). tokens is a list of str. Skip '[CLS]', '[SEP]' and '[PAD]'. A token starting with '##' is appended (without the '##') to the previous word; if there is no previous word it starts a new word without the '##'. Any other token starts a new word. Return the words joined by single spaces.

Signaturedef decode_wordpiece(tokens)

Example

decode_wordpiece(['[CLS]', 'token', '##ization', 'is', 'fun', '[SEP]', '[PAD]']) is 'tokenization is fun'.

Understand the idea

WordPiece splits a word into a first piece and continuation pieces. Continuations start with '##', which means 'attach me to the piece before, with no space'. Decoding reverses that.

Worked example: tokens [CLS], token, ##ization, is, fun, [SEP], [PAD]. Drop the three specials. 'token' starts a word. '##ization' continues it, giving 'tokenization'. 'is' and 'fun' start new words. Joined with spaces: 'tokenization is fun'.

Rule: for each non-special token t: if t starts with '##', words[-1] += t[2:]; else words.append(t). Output ' '.join(words). (Real tokenizers also fix spaces before punctuation; here punctuation is just another word.)

BERT-style NER, extractive QA and fill-mask demos all decode WordPiece output this way before showing text.

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

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

  • Sample 1: exampledecode_wordpiece(['[CLS]', 'token', '##ization', 'is', 'fun', '[SEP]', '[PAD]'])
  • Sample 2: several pieces in a rowdecode_wordpiece(['un', '##believ', '##able', 'results', '!'])
  • Test 3: leading continuationdecode_wordpiece(['##ing', 'done'])
  • Test 4: only specialsdecode_wordpiece(['[CLS]', '[SEP]'])