Encode text with a byte fallback so no character is ever unknown

A tokenizer with a fixed vocabulary will meet characters it has never seen. Instead of emitting an unknown token, many LLM tokenizers fall back to the raw UTF-8 bytes of that character, so every string can be encoded and decoded exactly.

Write byte_fallback_encode(text, vocab). vocab is a dict mapping single characters to integer ids, all ids are >= 256. Ids 0 to 255 are reserved for raw bytes.

Walk the text one character at a time. If the character is in vocab, emit its id. Otherwise emit the UTF-8 bytes of that character, each byte value as its own id (0 to 255). Return the list of ids.

Signaturedef byte_fallback_encode(text, vocab)

Example

vocab = {"a": 256, "b": 257}, text = "ab\u00e9" gives [256, 257, 195, 169], because the character U+00E9 is the two bytes 0xC3 0xA9 in UTF-8.

Understand the idea

A tokenizer with a fixed vocabulary will sooner or later see a character it does not know, such as a rare emoji or a script it was not trained on. Byte fallback says: if the character is unknown, write out its raw UTF-8 bytes, each as its own id from 0 to 255. Nothing is ever lost, so decoding gives back the exact text. Worked example: vocab = {'a': 256, 'b': 257}. Text 'a' then the letter n with tilde (U+00F1). 'a' gives 256. The tilde n is not in vocab; its UTF-8 bytes are 0xC3 0xB1, so it gives 195 and 177. Result [256, 195, 177]. The euro sign would give three ids: 226, 130, 172. Rule: for each character, emit vocab[ch] if present; otherwise emit every byte of ch.encode('utf-8') as an integer. Using ord(ch) % 256 looks fine for ASCII but turns a multi-byte character into one wrong id. Byte fallback is used in LLaMA and other SentencePiece-based tokenizers so no input is ever unknown.

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

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

  • Sample 1: examplebyte_fallback_encode('ab\u00e9', {'a': 256, 'b': 257})
  • Sample 2: unknown asciibyte_fallback_encode('cab!', _v)
  • Test 3: three byte characterbyte_fallback_encode('a \u4e2d c', _v)
  • Test 4: all knownbyte_fallback_encode('abc', _v)