Sub topic 11
Special tokens, continuation markers, and whitespace markers
This chapter assumes you know how BPE, WordPiece and SentencePiece build and apply a vocabulary, and that you can read basic Python. It covers the extra symbols that sit around the learned subword pieces. These symbols decide whether a tokeniser can be reversed, whether a model knows where a sentence starts and ends, and whether two tools that look alike produce the same ids.
Three kinds of reserved symbol
A tokeniser vocabulary holds more than learned pieces. It also holds reserved symbols of three kinds.
- Special tokens carry structure instead of language: padding, unknown words, sentence boundaries, masks.
- Continuation markers show that a piece attaches to the piece before it, so a word split into several pieces can be rebuilt.
- Whitespace markers write spaces into the token strings themselves, so spaces are not lost.
All three exist for the same reason. After subword splitting, the model sees a flat list of ids. Anything the model or the decoder needs to know about structure must be encoded as tokens in that list.
Special tokens
Special tokens are vocabulary entries that are never produced by splitting ordinary text. You add them by hand, and the tokeniser must treat each as one indivisible unit.
| Token | Common name | Purpose |
|---|---|---|
| `[PAD]` or `<pad>` | padding | Fills short sequences so a batch has equal length. |
| `[UNK]` or `<unk>` | unknown | Stands in for text the vocabulary cannot represent. |
| `[CLS]` | classification | Placed first in BERT-style input. Its output vector is often used for sentence-level tasks. |
| `[SEP]` | separator | Marks the end of a segment. |
| `[MASK]` | mask | Replaces a hidden token during masked-language-model training. |
| `<s>` / `</s>` | begin / end of sequence | Mark where text starts and stops in many decoder and SentencePiece models. |
Which tokens exist depends on the model family. BERT uses [CLS], [SEP], [MASK], [PAD] and [UNK]. GPT-2 uses a single <|endoftext|> token. SentencePiece reserves <unk>, <s> and </s> by default, with ids 0, 1 and 2, and lets you add more.
Three rules matter in practice:
- The ids belong to the pretrained model. If a model learned that id 0 is padding, you cannot renumber it. Reserved ids are part of the model, not just the tokeniser.
- Padding must be ignored by attention. Padding tokens get an attention mask of 0, so the model does not read them as content.
- Special tokens are matched before subword splitting. The tokeniser first finds literal occurrences of
[SEP]in the text and cuts them out. It then runs BPE or WordPiece on the pieces between them. Without this step,[SEP]would be split into[,SE,Pand].
Building a model input
The next function builds a BERT-style input for a sentence pair. It adds [CLS] and [SEP], a segment id for each token, an attention mask, and padding.
vocab = {"[PAD]": 0, "[UNK]": 1, "[CLS]": 2, "[SEP]": 3, "[MASK]": 4,
"the": 5, "cat": 6, "sat": 7, "play": 8, "##ing": 9}
def encode_pair(tokens_a, tokens_b, vocab, max_len):
tokens = ["[CLS]"] + tokens_a + ["[SEP]"] + tokens_b + ["[SEP]"]
if len(tokens) > max_len:
raise ValueError("input longer than max_len; truncate the segments first")
segments = [0] * (len(tokens_a) + 2) + [1] * (len(tokens_b) + 1)
mask = [1] * len(tokens)
pad = max_len - len(tokens)
tokens += ["[PAD]"] * pad
segments += [0] * pad
mask += [0] * pad
ids = [vocab.get(t, vocab["[UNK]"]) for t in tokens]
return tokens, ids, segments, mask
tokens, ids, segments, mask = encode_pair(["the", "cat"], ["sat"], vocab, 8)
print(tokens)
print(ids)
print(segments)
print(mask)The output is:
['[CLS]', 'the', 'cat', '[SEP]', 'sat', '[SEP]', '[PAD]', '[PAD]']
[2, 5, 6, 3, 7, 3, 0, 0]
[0, 0, 0, 0, 1, 1, 0, 0]
[1, 1, 1, 1, 1, 1, 0, 0]Truncation must happen before the special tokens are added, because the model always needs the final [SEP]. The function raises an error instead of silently cutting it off.
Continuation markers
When a word is split into several pieces, the decoder needs to know which pieces join and which start a new word. There are two opposite conventions.
Marking the pieces that continue
WordPiece puts ## at the front of every piece that continues a word. The word unaffable becomes un, ##aff, ##able. To decode, remove each ## and join the piece to the one before it.
Marking the pieces that start
The other convention marks the start of a word, and that mark is a stand-in for a space. SentencePiece writes ▁ (U+2581, "lower one eighth block") at the start of each piece that follows a space. GPT-2's byte-level BPE writes Ġ, which is the printable stand-in for the space byte 0x20. The original BPE paper's implementation used </w> at the end of a word, as in the trainer from earlier in this tutorial.
| Tokeniser | Marker | Where it appears | What it means |
|---|---|---|---|
| WordPiece (BERT) | `##` | Start of non-initial pieces | This piece continues the previous one. |
| SentencePiece | `▁` | Start of word-initial pieces | A space came before this piece. |
| Byte-level BPE (GPT-2) | `Ġ` | Start of word-initial pieces | A space byte came before this piece. |
| Classic BPE | `</w>` | End of the last piece of a word | The word ends here. |
These conventions carry different amounts of information. A ## scheme loses the original spacing. WordPiece first splits on whitespace and punctuation, so it never records how many spaces were there or what kind they were. Decoding gives back a normal-looking sentence, not necessarily the original string. A ▁ or Ġ scheme records the space inside the token, so the text can be rebuilt exactly.
Whitespace markers and reversible encoding
SentencePiece treats a space as an ordinary character and replaces it with ▁ before any splitting. The sentence Hello world becomes ▁Hello▁world. The model then learns pieces such as ▁Hello and ▁world. Because the space is inside the piece, decoding is a plain string operation: join all pieces, then turn each ▁ back into a space.
The two decoders below show the difference. Both are complete and runnable.
def wordpiece_decode(pieces):
text = ""
for p in pieces:
if p.startswith("##"):
text += p[2:]
elif text:
text += " " + p
else:
text += p
return text
def sentencepiece_decode(pieces):
text = "".join(pieces).replace("\u2581", " ")
return text[1:] if text.startswith(" ") else text
print(wordpiece_decode(["un", "##aff", "##able", "word"]))
print(sentencepiece_decode(["\u2581un", "aff", "able", "\u2581word"]))Both calls print the same text, unaffable word. They are not equivalent, though. If the original had two spaces between the words, SentencePiece would produce ▁un, aff, able, ▁, ▁word and decode them back to two spaces. WordPiece could never recover that.
The leading ▁ is added on purpose. SentencePiece by default puts a dummy space in front of the text, so world at the start of a sentence gets the same piece as world after a space. The decoder removes that one leading space again. This is why sp.decode(sp.encode(text)) returns the original text.
Where mismatches come from
Most real bugs in this area come from treating the tokeniser as a separate step from the model. These are the common cases.
- Double special tokens. Many libraries add
[CLS]and[SEP]for you. If you also write them into the text, the model sees[CLS] [CLS] ... [SEP] [SEP]. This usually lowers accuracy without raising any error. - User text that contains special-token strings. If a user types
<|endoftext|>into a chat box and your tokeniser matches special tokens in raw text, the user can inject a control token. Disable special-token parsing for untrusted input, or escape those strings. - Wrong padding id in the loss. Padding positions must be excluded from the loss, usually by setting their label to an ignore index such as -100. Otherwise the model is trained to predict padding.
- Marker-sensitive string checks. Code that tests
token == "world"fails on▁worldorĠworld. Compare after decoding, or strip the marker deliberately. - Adding tokens without resizing embeddings. If you add
<tool_call>to a pretrained vocabulary, the model's embedding table needs a new row for it. That row starts untrained, so the model needs fine-tuning before it can use it. - Leading-space differences. In byte-level and SentencePiece schemes,
worldandworldare different pieces with different ids. A prompt that ends with a trailing space can therefore tokenise differently from one without it.
Summary of the design choices
Special tokens give the model structure it cannot get from text alone. Continuation markers (##) and whitespace markers (▁, Ġ) decide how pieces map back to a string. The ## style is simple but lossy. The ▁ and Ġ styles keep spacing information, which makes decoding exact and lets the tokeniser work on languages without spaces between words. In every case the markers and special-token ids are part of the model's contract, so keep them identical between training and inference.
Exercise
A SentencePiece model encodes a sentence as ['▁play', 'ing', '▁cards']. A WordPiece model encodes the same sentence as ['play', '##ing', 'cards']. Decode both. Then say which one can recover a sentence that originally had two spaces between "playing" and "cards", and why.
Show answer
Both decode to "playing cards". Only the SentencePiece model can recover the double space. It writes each space as ▁ inside the pieces, so two spaces would appear as an extra ▁ piece and decoding would restore them. WordPiece splits on whitespace before it tokenises, so it never records how many spaces there were.
Exercise
You build a batch with encodepair using maxlen=8, and one example has 3 tokens in segment A and 3 in segment B. What happens, and what should you do before calling the function?
Show answer
The full sequence needs 3 + 3 + 3 special tokens = 9 positions, which is more than 8, so the function raises ValueError. Truncate the segments first (for example to 2 and 3 tokens, or 3 and 2) so that the special tokens still fit, instead of cutting the sequence after the special tokens are added, which would drop the final [SEP].