Tokenize words with WordPiece greedy longest match

BERT-style models split each word into subword pieces by repeatedly taking the longest piece in the vocabulary that matches at the current position. Pieces that continue a word carry a "##" prefix so the model knows they are not word starts.

Write wordpiece_tokenize(text, vocab). Split text on whitespace. For each word, start at position 0:
- Find the longest substring word[start:end] that is in vocab. For start > 0 the candidate is "##" + word[start:end].
- Emit it and move start to end.
- If no candidate matches at some position, the whole word becomes a single "[UNK]" (drop any pieces already found for that word).
vocab is a set of strings. Return the list of pieces.

Signaturedef wordpiece_tokenize(text, vocab)

Example

vocab = {"un", "##aff", "##able", "aff"}, text = "unaffable" gives ["un", "##aff", "##able"].

Understand the idea

WordPiece breaks a word into known pieces by always grabbing the longest piece that matches at the current position, then moving on. Any piece that is not at the start of a word gets a '##' prefix so the model knows it continues a word. If at some point nothing matches, the whole word becomes one [UNK], and pieces already found for it are thrown away. Worked example: vocab = {'play', '##ing', '##in'}, text 'playing cats'. For 'playing': at position 0 the longest match is 'play'. At position 4, try '##ing' (matches) before shorter '##in', so emit '##ing'. For 'cats': no piece starting at 'c' exists, so the word becomes '[UNK]'. Result ['play', '##ing', '[UNK]']. Rule: split on whitespace; for each word, from start, try end from the full length down to start + 1 and take the first candidate in vocab (with '##' added when start > 0); emit and jump to end; on failure replace the whole word with '[UNK]'. This is the tokenizer used by BERT and many embedding models.

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

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

  • Sample 1: examplewordpiece_tokenize('unaffable', {'un', '##aff', '##able', 'aff'})
  • Sample 2: longest winswordpiece_tokenize('the playing tokenizers', _v)
  • Test 3: unknown wordwordpiece_tokenize('played tokenx the', _v)
  • Test 4: char fallback pieceswordpiece_tokenize('plaay', _v)