Decode SentencePiece pieces back to text

Why it matters Llama and T5 tokenizers are SentencePiece models; streaming detokenization needs exactly this logic.

SentencePiece marks a word start with the symbol U+2581 instead of a space, and byte-fallback pieces look like <0x41>.

Write sp_decode(pieces). Join the pieces, turning each byte piece "<0xHH>" into that byte, encode normal pieces as UTF-8, decode the whole byte string as UTF-8 (errors="replace"), replace U+2581 with a space and strip one leading space if present.

Signaturedef sp_decode(pieces)

Example

sp_decode(["\u2581Hel", "lo", "\u2581", "<0x21>"]) is "Hello !".

Understand the idea

SentencePiece stores a space as the special symbol U+2581 (a low bar) glued to the start of the next word, and it can fall back to raw byte pieces written like <0xC3> for characters not in its vocabulary. To decode, you rebuild the raw bytes first, because one character such as e with an accent may be split across several byte pieces. Worked example: pieces ['▁caf', '<0xC3>', '<0xA9>', '▁ok']. The first piece becomes the UTF-8 bytes of '▁caf'; the two byte pieces become the bytes C3 and A9; the last piece becomes the bytes of '▁ok'. Decoding all bytes as UTF-8 gives '▁café▁ok', since C3 A9 together is é. Replacing U+2581 with a space gives ' café ok', and stripping one leading space gives 'café ok'. Rule: for each piece, if it matches <0xHH> append that single byte, else append its UTF-8 encoding; decode the whole byte string with errors='replace'; replace U+2581 with ' '; remove one leading space if present. Used in: detokenising output of Llama, T5 and other SentencePiece models.

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

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

  • Sample 1: examplesp_decode(['\u2581Hel', 'lo', '\u2581', '<0x21>'])
  • Sample 2: multibytesp_decode(['\u2581caf', '<0xC3>', '<0xA9>'])
  • Test 3: wordssp_decode(['\u2581the', '\u2581cat', '\u2581sat'])