PyTorch Text Tokenizer: Options, Tradeoffs and a Custom Approach
How text tokenization works in PyTorch, what a tokenizer actually changes, when to write a custom one, and the Unicode and reversibility caveats to check first.
Tokenizing text for a PyTorch model means turning a string into a sequence of integer IDs that a model can embed and process. PyTorch itself does not ship a general-purpose text tokenizer in its core library, so the practical question is which tokenizer to pair with it and whether that tokenizer keeps enough of the original text for your task. This review covers what tokenization changes, when a custom tokenizer makes sense, and where meaning or usability can be lost.
Is a given tokenizer suitable for your use?
The decisive factor is usually not the tokenizer's design but what it must match. If you are fine-tuning or running a pretrained model, use the tokenizer that was trained with that model. Its vocabulary defines what each ID means, and a different tokenizer, even a reasonable one, produces IDs the model was never trained on.
If you are training a model from scratch, you have a real choice. A simple word-level or regex tokenizer is easy to inspect and debug, which suits small experiments, classroom work and narrow domains. Its main tradeoff is vocabulary coverage: any word not seen during vocabulary building becomes an unknown token. Subword tokenizers such as BPE, WordPiece or Unigram models split rare words into smaller known pieces, which reduces unknown tokens at the cost of output that is harder to read by eye.
Plain, untokenized text remains preferable for anything a person reads, edits, stores as a source of truth or shares. Tokenization is a model-input format, not a storage or display format.
Common ways to tokenize text for PyTorch
| Approach | What it does | Main consideration |
| Tokenizer bundled with a pretrained model | Applies the exact vocabulary and splitting rules the model was trained with | Required for pretrained models; not interchangeable across models |
| torchtext get_tokenizer | Historically offered simple tokenizers such as basic_english, which lowercases and separates punctuation | The torchtext project's maintainers have stated that active development has ended; check its current status before building on it |
| Standalone subword libraries (for example SentencePiece or Hugging Face tokenizers) | Train or load a subword vocabulary and produce IDs you convert to tensors | Strong coverage of rare words; tokens are less human-readable |
| Custom Python function | Your own splitting rules plus your own vocabulary mapping | Full control and transparency; you own every edge case |
What tokenization actually changes
Unlike visual text effects, which alter only how text is displayed, tokenization changes the stored data itself. The pipeline usually has three steps: optional normalization (such as lowercasing or Unicode normalization), splitting into tokens, and mapping each token to an integer ID. The result is a tensor of IDs. None of the original characters are kept in that tensor; they can only be reconstructed through the vocabulary, and only as faithfully as the earlier steps allow.
The term "tokenizer" is also used loosely. Sometimes it means only the splitting step, which returns a list of strings. Sometimes it means the whole pipeline that returns IDs, attention masks and padding. When comparing tools, check which of these a given function actually returns.
Writing a custom tokenizer in PyTorch
A custom tokenizer is ordinary Python: a function that splits text, a vocabulary that maps tokens to IDs, and a conversion to a tensor. The example below normalizes Unicode, lowercases, and splits into runs of word characters or single non-space symbols.
import re
import unicodedata
from collections import Counter
import torch
from torch.nn.utils.rnn import pad_sequence
def tokenize(text):
text = unicodedata.normalize("NFC", text).lower()
return re.findall(r"\w+|[^\w\s]", text)
def build_vocab(corpus):
counter = Counter(tok for line in corpus for tok in tokenize(line))
vocab = {"<pad>": 0, "<unk>": 1}
for tok, _ in counter.most_common():
vocab[tok] = len(vocab)
return vocab
def encode(text, vocab):
ids = [vocab.get(tok, vocab["<unk>"]) for tok in tokenize(text)]
return torch.tensor(ids, dtype=torch.long)
def collate(batch, vocab):
return pad_sequence([encode(t, vocab) for t in batch],
batch_first=True,
padding_value=vocab["<pad>"])
With this splitting rule, the input "Don't panic!" becomes the tokens don, ', t, panic and !. That shows a typical design decision: the apostrophe splits the contraction into three pieces. Whether that is acceptable depends on the task, and changing it means changing the regular expression.
The collate function can be passed to a DataLoader through its collate_fn argument (for example with functools.partial to bind the vocabulary), so each batch is padded to the length of its longest sequence.
Unicode edge cases to test
- Combining marks: a letter such as é can be stored as one precomposed code point or as e followed by a combining accent. With Python's built-in re module, the combining accent is not matched by \w, so without normalization the decomposed form splits into e plus a separate accent token. NFC normalization, as in the example, merges common cases back into a single character, but not every combination has a precomposed form.
- Multi-code-point emoji: emoji built from several code points joined by zero-width joiners, or with skin-tone modifiers, are matched one code point at a time by the [^\w\s] pattern. A single visible emoji can therefore become several tokens, including invisible joiner characters.
- Scripts without spaces: languages written without spaces between words, such as Chinese or Japanese, are not split into words by a whitespace or \w-based rule. Subword or language-specific tokenizers are better suited there.
- Case: lowercasing merges distinctions such as a proper noun and a common word, which may or may not matter for your task.
Can the original text be recovered?
Reversibility depends on what the pipeline discards. The custom example above is lossy: lowercasing removes case, and the regex drops whitespace, so decoding IDs back to tokens cannot reliably restore the original spacing or capitalization, and unknown tokens cannot be restored at all. Byte-level BPE tokenizers and SentencePiece, which encodes spaces as part of its tokens, are designed so that decoding reproduces the input much more closely. If exact round-tripping matters, verify it on your own data rather than assuming it.
Readability, sharing and downstream use
Token IDs are not readable text. Copying them into a document, a message or a search field produces numbers with no meaning outside the vocabulary that created them, and assistive technology such as screen readers has nothing meaningful to announce. For that reason, keep the original text alongside tokenized data, save the vocabulary or tokenizer files together with the model, and decode back to plain text for anything a person will see. A tokenizer also has to be versioned with its model: retraining the vocabulary changes the meaning of every ID.
Gaps in this review
No benchmarks, speed measurements, accuracy comparisons or version-specific test results were available for this review, so none are claimed. The status of torchtext and the behavior of third-party libraries can change between releases; confirm details against the current documentation for the versions you install, and test tokenization on a sample of your own text, including accented characters and emoji if your data contains them.