Extremely fast bert tokenizer
Project description
The world's fastest CPU tokenizer library!
EFFICIENT AND OPTIMIZED TOKENIZER ENGINE FOR LLM INFERENCE SERVING
FlashTokenizer is a high-performance tokenizer implementation in C++ of the BertTokenizer used for LLM inference. It has the highest speed and accuracy of any tokenizer, such as FlashAttention and FlashInfer, and is 10 times faster than BertTokenizerFast in transformers.
[!NOTE]
Why?
We need a tokenizer that is faster, more accurate, and easier to use than Huggingface's BertTokenizerFast. (link1, link2, link3)
PaddleNLP's BertTokenizerFast achieves a 1.2x performance improvement by implementing Huggingface's Rust version in
C++. However, using it requires installing both the massive PaddlePaddle and PaddleNLP packages.Tensorflow-text's FastBertTokenizer actually demonstrates slower performance in comparison.
Microsoft's Blingfire takes over 8 hours to train on custom data and shows relatively lower accuracy.
Rapid's cuDF provides a GPU-based BertTokenizer, but it suffers from accuracy issues.
Unfortunately, FastBertTokenizer and BertTokenizers developed in
C#and cannot be used inPython. (As a side note, I don't know C#, but I believe once something is implemented in C#, it shouldn't have "Fast" in its name.)This is why we developed
FlashTokenizer. It can be easily installed viapipand is developed in C++ for straightforward maintenance. Plus, it guarantees extremely fast speeds. We've created an implementation that's faster than Blingfire and easier to use. FlashTokenizer is implemented using the LinMax Tokenizer proposed in Fast WordPiece Tokenization, enabling tokenization in linear time. Finally It supports parallel processing at the C++ level for batch encoding, delivering outstanding speed.
FlashTokenizer includes the following core features
[!TIP]
Implemented in C++17 and is fastest when built with GNUC.
- MacOS:
g++(14.2.0)is faster thanclang++(16.0.0).- Windows:
g++(8.1.0)-MinGW64is faster thanVisual Studio 2019.- Ubuntu:
g++(11.4.0)is faster thanclang++(14.0.0).Equally fast in Python via pybind11.
Blingfire was difficult to use in practice due to its low accuracy, but FlashBertTokenizer has both high accuracy and high speed.
Although it's only implemented as a single thread, it's capable of 40K RPS in C++ and 25K RPS in Python, and it's thread-safe, so you can go even faster with multi-threading if you need to.
News
[!IMPORTANT]
[Mar 21 2025]
- Improving Tokenizer Accuracy
[Mar 19 2025]
- Memory reduction and slight performance improvement by applying LinMaxMatching from Aho–Corasick algorithm.
- Improved branch pipelining of all functions and force-inline applied.
- Removed unnecessary operations of
WordpieceTokenizer(Backward).- Optimizing all functions to operate except for Bloom filter is faster than caching.
punctuation,control, andwhitespaceare defined as constexprs in advance and used as Bloom filters.- Reduce unnecessary memory allocation with statistical memory profiling.
- In ✨FlashTokenizer✨,
bert-base-uncasedcan process 35K texts per second on a single core, with an approximate processing time of 28ns per text.[Mar 18 2025]
- Improvements to the accuracy of the BasicTokenizer have improved the overall accuracy and, in particular, produce more accurate results for Unicode input.
[Mar 14 2025]
- The performance of the
WordPieceTokenizerandWordPieceBackwordTokenizerhas been improved using Trie, which was introduced in Fast WordPiece Tokenization.- Using
FastPoolAllocatorinstd::listimproves performance in SingleEncoding, but it is not thread-safe, sostd::list<std::string>is used as is in BatchEncoding. In BatchEncoding,OPENMPis completely removed and onlystd::threadis used.[Mar 10 2025]
- Performance improvements through faster token mapping with robin_hood and memory copy minimization with std::list.
Token Ids Map Table Performance Test.
Token and Ids Map used the fastest
robin_hood::unordered_flat_map<std::string, int>.[Mar 09 2025] Completed development of flash-tokenizer for BertTokenizer.
1. Installation
Requirements
Windows(AMD64),MacOS(ARM64),Ubuntu(x86-64).g++/clang++/MSVC.- python 3.9 ~ 3.12.
Install from PIP
# Windows(Visual Studio)
pip install -U flash-tokenizer
# Ubuntu
sudo apt install gcc g++ make cmake -y
pip install setuptools wheel build pybind11
CC=gcc CXX=g++ pip install -U flash-tokenizer
# MacOS
brew install gcc
CC=gcc CXX=g++ pip install -U flash-tokenizer
Install from Source
git clone https://github.com/NLPOptimize/flash-tokenizer
cd flash-tokenizer
pip install .
2. Usage
from flash_tokenizer import BertTokenizerFlash
tokenizer = BertTokenizerFlash("path/to/vocab.txt", do_lower_case=True)
# Tokenize text
ids = tokenizer("Hello, World!", max_length=300, padding="longest").input_ids
print(ids)
3. Other Implementations
Most BERT-based models use the WordPiece Tokenizer, whose code can be found here. (A simple implementation of Huggingface can be found here).
Since the BertTokenizer is a CPU intensive algorithm, inference can be a bottleneck, and unoptimized tokenizers can be severely slow. A good example is the BidirectionalWordpieceTokenizer introduced in KR-BERT. Most of the code is the same, but the algorithm traverses the sub token backwards and writes a larger value compared to the forward traversal. The paper claims accuracy improvements, but it's hard to find other quantitative metrics, and the accuracy improvements aren't significant, and the tokenizer is seriously slowed down.
- transformers (Rust Impl, PyO3)
- paddlenlp (C++ Impl, pybind)
- tensorflow-text (C++ Impl, pybind)
- blingfire (C++ Impl, Native binary call)
Most developers will either use transformers.BertTokenizer or transformers.AutoTokenizer, but using AutoTokenizer will return transformers.BertTokenizerFast.
Naturally, it's faster than BertTokenizer, but the results aren't exactly the same, which means you're already giving up 100% accuracy starting with the tokenizer.
BertTokenizer is not only provided by transformers. PaddleNLP and tensorflow-text also provide BertTokenizer.
Then there's Blingfire, which is developed by Microsoft and is being abandoned.
PaddleNLP requires PaddlePaddle and provides tokenizer functionality starting with version 3.0rc. You can install it as follows
##### Install PaddlePaddle, PaddleNLP
python -m pip install paddlepaddle==3.0.0b1 -i https://www.paddlepaddle.org.cn/packages/stable/cpu/
pip install --upgrade paddlenlp==3.0.0b3
##### Install transformers
pip install transformers==4.47.1
##### Install tf-text
pip install tensorflow-text==2.18.1
##### Install blingfire
pip install blingfire
With the exception of blingfire, vocab.txt is all you need to run the tokenizer right away. (blingfire also requires only vocab.txt and can be used after 8 hours of learning).
The implementations we'll look at in detail are PaddleNLP's BertTokenizerFast and blingfire.
blingfire: Uses a Deterministic Finite State Machine (DFSM) to eliminate one linear scan and unnecessary comparisons, resulting in a time of O(n), which is impressive.- Advantages: 5-10x faster than other implementations.
- Disadvantages: Long training time (8 hours) and lower accuracy than other implementations. (+Difficult to get help due to de facto development hiatus).
PaddleNLP: As shown in the experiments below, PaddleNLP is always faster than BertTokenizerFast (HF) to the same number of decimal places, and is always faster on any OS, whether X86 or Arm.- Advantages: Internal implementation is in C++ Compared to
transformers.BertTokenizerFastimplemented in Rust, it is 1.2x faster while outputting exactly the same values.- You can't specify
pt(pytorch tensor)inreturn_tensors, but this is not a problem.
- You can't specify
- Disadvantages: none, other than the need to install PaddlePaddle and PaddleNLP.
- Advantages: Internal implementation is in C++ Compared to
4. Performance test
4.1 Performance test (Single text encoding)
Accuracy is the result of measuring google's BertTokenizerFast as a baseline. If even one of the input_ids is incorrect, the answer is considered incorrect.
Tokenizer Performance Comparison
google-bert/bert-base-cased
| Tokenizer | Elapsed Time | texts | Accuracy |
|---|---|---|---|
| BertTokenizerFast(Huggingface) | 84.3700s | 1,000,000 | 99.9226% |
| BertTokenizerFast(PaddleNLP) | 75.6551s | 1,000,000 | 99.9226% |
| FastBertTokenizer(Tensorflow) | 219.1259s | 1,000,000 | 99.9160% |
| Blingfire | 13.6183s | 1,000,000 | 99.8991% |
| FlashBertTokenizer | 8.1968s | 1,000,000 | 99.8216% |
google-bert/bert-base-uncased
| Tokenizer | Elapsed Time | texts | Accuracy |
|---|---|---|---|
| BertTokenizerFast(Huggingface) | 91.7882s | 1,000,000 | 99.9326% |
| BertTokenizerFast(PaddleNLP) | 83.6839s | 1,000,000 | 99.9326% |
| FastBertTokenizer(Tensorflow) | 204.2240s | 1,000,000 | 99.1379% |
| Blingfire | 13.2374s | 1,000,000 | 99.8588% |
| FlashBertTokenizer | 7.6313s | 1,000,000 | 99.6884% |
google-bert/bert-base-multilingual-cased
| Tokenizer | Elapsed Time | texts | Accuracy |
|---|---|---|---|
| BertTokenizerFast(Huggingface) | 212.1570s | 2,000,000 | 99.7964% |
| BertTokenizerFast(PaddleNLP) | 193.9921s | 2,000,000 | 99.7964% |
| FastBertTokenizer(Tensorflow) | 394.1574s | 2,000,000 | 99.7892% |
| Blingfire | 38.9013s | 2,000,000 | 99.9780% |
| FlashBertTokenizer | 20.4570s | 2,000,000 | 99.8970% |
beomi/kcbert-base
| Tokenizer | Elapsed Time | texts | Accuracy |
|---|---|---|---|
| BertTokenizerFast(Huggingface) | 52.5744s | 1,000,000 | 99.6754% |
| BertTokenizerFast(PaddleNLP) | 44.8943s | 1,000,000 | 99.6754% |
| FastBertTokenizer(Tensorflow) | 198.0270s | 1,000,000 | 99.6639% |
| Blingfire | 13.0701s | 1,000,000 | 99.9434% |
| FlashBertTokenizer | 5.2601s | 1,000,000 | 99.9484% |
KR-BERT
| Tokenizer | Elapsed Time | texts | Accuracy |
|---|---|---|---|
| BertTokenizerBidirectional(KR-BERT Original) | 128.3320s | 1,000,000 | 100.0000% |
| FlashBertTokenizer(Bidirectional) | 10.4492s | 1,000,000 | 99.9631% |
%%{ init: { "er" : { "layoutDirection" : "LR" } } }%%
erDiagram
Text ||--o{ Preprocess : tokenize
Preprocess o{--|| Inference : memcpy_h2d
Inference o{--|| Postprocess : memcpy_d2h
6. Compatibility
FlashBertTokenizer can be used with any framework. CUDA version compatibility for each framework is also important for fast inference of LLMs.
- PyTorch no longer supports installation using conda.
- ONNXRUNTIME is separated by CUDA version.
- PyTorch is also looking to ditch CUDA 12.x in favor of the newer CUDA 12.8. However, the trend is to keep CUDA 11.8 in all frameworks.
- CUDA 12.x was made for the newest GPUs, Hopper and Blackwell, and on GPUs like Volta, CUDA 11.8 is faster than CUDA 12.x.
| DL Framework | Version | OS | CPU | CUDA 11.8 | CUDA 12.3 | CUDA 12.4 | CUDA 12.6 | CUDA 12.8 |
|---|---|---|---|---|---|---|---|---|
| PyTorch | 2.6 | Linux, Windows | ⚪ | ⚪ | ❌ | ⚪ | ⚪ | ❌ |
| PyTorch | 2.7 | Linux, Windows | ⚪ | ⚪ | ❌ | ❌ | ⚪ | ⚪ |
| ONNXRUNTIME(11) | 1.20.x | Linux, Windows | ⚪ | ⚪ | ❌ | ❌ | ❌ | ❌ |
| ONNXRUNTIME(12) | 1.20.x | Linux, Windows | ⚪ | ❌ | ⚪ | ⚪ | ⚪ | ⚪ |
| PaddlePaddle | 3.0-beta | Linux, Windows | ⚪ | ⚪ | ❌ | ❌ | ❌ | ❌ |
7. GPU Tokenizer
Here is an example of installing and running cuDF in Run State of the Art NLP Workloads at Scale with RAPIDS, HuggingFace, and Dask. (It's incredibly fast)
You can run WordPiece Tokenizer on GPUs on rapids(cudf).
As you can see in how to install rapids, it only supports Linux and the CUDA version is not the same as other frameworks, so docker is the best choice, which is faster than CPU for batch processing but slower than CPU for streaming processing.
There are good example codes and explanations in the[ blog](https://developer.nvidia.com/blog/run-state-of-the-art-nlp-workloads-at-scale-with-rapids-huggingface-and-dask/#:~:text=,and then used in subsequent). To use cuDF, you must first convert vocab.txt to hash_vocab as shown below. The problem is that the hash_vocab function cannot convert multilingual. Therefore, the WordpieceTokenizer of cuDF cannot be used if there are any characters other than English/Chinese in the vocab.
import cudf
from cudf.utils.hash_vocab_utils import hash_vocab
hash_vocab('bert-base-cased-vocab.txt', 'voc_hash.txt')
TODO
- BidirectionalWordPieceTokenizer
- BatchEncoder with Multithreading.
-
CUDA Version. - Replace
std::listtoboost::intrusive::list. - MaxMatch-Dropout: Subword Regularization for WordPiece Option.
- SIMD
- Use stack memory for reduce memory allocation. (C-Style, alloca, _alloca)
- Support for parallel processing option for single encode.
-
circle.ai- Implement distribution of compiled wheel packages for installation.
Acknowledgement
FlashTokenizer is inspired by FlashAttention, FlashInfer, FastBertTokenizer and tokenizers-cpp projects.
Performance comparison
- https://fastberttokenizer.gjung.com/ (C# Impl)
- https://github.com/huggingface/tokenizers (Rust Impl)
- BPE
Star History
References
- https://medium.com/@techhara/which-bert-tokenizer-is-faster-b832aa978b46
- https://medium.com/@atharv6f_47401/wordpiece-tokenization-a-bpe-variant-73cc48865cbf
- https://www.restack.io/p/transformer-models-bert-answer-fast-berttokenizerfast-cat-ai
- https://medium.com/@anmolkohli/my-notes-on-bert-tokenizer-and-model-98dc22d0b64
- https://nocomplexity.com/documents/fossml/nlpframeworks.html
- https://github.com/martinus/robin-hood-hashing
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file flash_tokenizer-1.1.3.tar.gz.
File metadata
- Download URL: flash_tokenizer-1.1.3.tar.gz
- Upload date:
- Size: 5.9 MB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8e6f3b315d8082fd99c95a6619777ee2d16c640d8a825f17b55c84806cf54933
|
|
| MD5 |
6e8e6b656f45859b623a6c0250779de1
|
|
| BLAKE2b-256 |
ef003b8acb8bc0f892156f566c1b0809998fa47c247d22cce31263eb709dcc45
|
File details
Details for the file flash_tokenizer-1.1.3-cp312-cp312-macosx_15_0_arm64.whl.
File metadata
- Download URL: flash_tokenizer-1.1.3-cp312-cp312-macosx_15_0_arm64.whl
- Upload date:
- Size: 200.5 kB
- Tags: CPython 3.12, macOS 15.0+ ARM64
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d921627e7276250e1d31afeed3d65a45fa4c5e64d214e3ccdb3bcde63c84de36
|
|
| MD5 |
be5fc962a681558d14708a609b78f765
|
|
| BLAKE2b-256 |
efb637044fa7b5e87734f093931c291a67be364bac7e75aac70fc3126ecc3517
|