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.
def 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.