bojone/bytepiece
About
A purer tokenizer with a higher compression rate
Other ProjectsMeasured star growth
- in 24h
- 0
- in 7 days
- +36
- in 15 days
- +37
- in 1 month
- Collecting history
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README_en.md
Original[中文|English]
BytePiece
BytePiece is a pure Byte-based Unigram tokenizer: it operates directly on UTF-8 bytes without whitespace, punctuation, or newline pre-tokenization, learns high-compression vocabularies via an unsupervised Byte-based N-gram Language Model (BNLM), and natively supports linear-time perfect randomized tokenization (Perfect Sampling).
What's new (0.8.3, vs. previous 0.8.2): Vocabulary truncation upgrades to the exact deletion-NLL ($\Delta\mathrm{NLL}$) criterion with 4 geometric rounds to directly minimize cross-entropy loss, lowering BPB across every corpus scale from 96 MB to 10 GB (up to 2.21% at 10 GB / 50k); also establishes the dual compression (B/Tok) + cross-entropy (BPB) evaluation standard (see the Changelog).
Documentation
- User Guide (中文): training options, tokenization & batching, special tokens, LLM pipelines, model saving & ecosystem export, and API reference.
- Algorithm & Mathematical Principles (中文): BNLM training derivation, full-segment Viterbi decoding, piece pruning, and perfect sampling proof.
- Implementation Walkthrough (中文): data structures and optimizations in
trainer.py,tokenizer.py, and_core.cpp. - Benchmarks & Reproducible Evaluation (中文): open-corpus comparisons of the latest release against mainstream libraries on training, deterministic/randomized tokenization, and compression, plus the one-command script (
docs/run_benchmark.py). - Changelog (中文): release notes since
0.8.0. - Test Suite (中文): full parameter matrix, API roundtrips, fuzzing, regression anchors, and Sanitizer instructions.
- Blog posts: BytePiece, Viterbi Sampling, Perfect Sampling.
Key Features
- High compression & language-agnostic: Pure UTF-8 byte-stream modeling with no regex, whitespace, or newline pre-tokenization; BNLM discovers words and cross-line structures (e.g., code indentation
\n) directly from corpus statistics without predefined word boundaries or multi-round EM. - Fast training & low memory: Built-in C++17 engine (Double-Array Trie + open-addressed flat hash maps + shared-memory multithreaded pipeline) with only
numpyandtqdmas runtime dependencies; training is strictly deterministic regardless of thread count. - Full-segment exact decoding & perfect sampling: Ring-buffer scores + 1-byte length backpointers, with single-thread and 32-thread zero-copy NumPy batching; perfect sampling strictly follows the full-length Boltzmann distribution and is token-for-token reproducible across thread counts under the same seed.
- Production-ready LLM pipeline: Compact
.bpkbinary models (millisecondmmaploading) and nativepickle, orthogonalatomic × specialtoken controls, pair/FIM/chat templates (including{% generation %}SFT assistant masks), offset mapping/truncation/padding, streaming UTF-8 decoding, and HuggingFace / Transformers / SentencePiece export.
Algorithm Principles
BytePiece's compression advantage comes from its BNLM training algorithm (originally introduced in Unsupervised Word Segmentation Based on Language Models): it maps every segmentation to a combination of byte-level N-gram conditional probabilities, discovers words over boundary-free byte streams via dynamic programming, and applies frequency filtering and wasted-piece elimination. Randomized tokenization builds on From Viterbi Decoding to Viterbi Sampling and From Viterbi Sampling to Perfect Sampling, achieving exact posterior sampling in linear time. See Algorithm & Mathematical Principles for full derivations.
Installation
BytePiece supports Python 3.8+ and only requires numpy and tqdm at runtime; building from source needs only a C++17 compiler (gcc/clang/MSVC):
pip install -U bytepiece # or pip install bytepiece==0.8.3
pip install . # or build and install from source
Optional dependencies: jinja2 for Jinja chat templates (or pass a Python callable), tokenizers for HuggingFace JSON export, and transformers for the PreTrainedTokenizerFast adapter.
Quickstart
BytePiece exposes two main classes, Trainer (training) and Tokenizer (tokenization). Train and tokenize in just a few lines:
from bytepiece import Trainer
corpus = ['今天天气还行', '今天的天气真好!', '这是一家不错的餐厅', '这个主意不错,大家都觉得可行。']
tokenizer = Trainer(max_vocab_size=1000, min_count=2).train(corpus, workers=4, verbose=False).to_tokenizer()
ids = tokenizer.encode('今天天气不错')
assert tokenizer.decode(ids) == '今天天气不错'
print([p.decode() for p in tokenizer.ids_to_pieces(ids)]) # ['今天', '天气', '不错']
Training
Training reads the corpus twice; pass a list or a re-iterable class (one-shot generators are not supported, and the corpus is streamed rather than loaded all at once):
import json
from bytepiece import Trainer
class corpus:
def __iter__(self):
with open('data_sample.json') as f:
for l in f:
yield json.loads(l)['text']
trainer = Trainer(order=6, max_vocab_size=100000, min_count=32)
trainer.train(corpus(), workers=64, batch_size=1000)
trainer.save('bytepiece.bpk') # compact binary (recommended); use 'bytepiece.model' for JSON
order: N-gram order (1~7, default6);max_vocab_size: target vocabulary cap (may be slightly smaller after pruning; pass a list like[100000, 50000]to export multiple sizes in one run);min_count: minimum piece count.workers: shared-memory C++ threads; results are fully deterministic regardless of thread count.- Optional constraints:
isolate_digits=Truesplits digits into single characters;ensure_unicode=True(default) keeps multi-byte tokens valid standalone Unicode. - Reserved control tokens: pass
special_tokens=['<|im_start|>', '<|im_end|>']to count them withinmax_vocab_sizeat fixed consecutive IDs3, 4, ...;trainer.to_tokenizer()returns a tokenizer with them pre-registered.
Tokenization & Batching
from bytepiece import Tokenizer
tokenizer = Tokenizer('bytepiece.bpk') # enables zero-copy mmap loading automatically
texts = ["Today's weather is great", 'Hello world!']
batch_ids = tokenizer.encode_batch(texts, num_threads=8)
# Zero-copy NumPy API (recommended for large-scale preprocessing): texts[i] -> ids[offsets[i]:offsets[i+1]]
ids, offsets = tokenizer.encode_batch_flat(texts, num_threads=8)
For advanced usage (special-token allow/block lists & anti-injection, TemplateProcessor pairs, FIM, chat templates & SFT {% generation %} assistant masks, truncation/overflow/padding/offsets, streaming decode, save_pretrained, and HF/SP export), see the complete examples in the User Guide.
Performance Summary
Measured on open datasets (Xeon 8575C, 1:1:1 mix of Chinese Wikipedia, English Wikipedia & GitHub Python, 32 MB each = 96 MB total, 50k vocab, 32 threads; reproduce with python docs/run_benchmark.py):
| Training Time↓ | Peak Memory↓ | ZH B/Tok↑ | Code B/Tok↑ | Mixed B/Tok↑ | Mixed Bit/B↓ | ZH 1-thread↑ | |
|---|---|---|---|---|---|---|---|
| BytePiece 0.8.3 (latest) | 3.14s | 957 MB | 4.359 | 4.667 | 4.365 | 2.9629 | 61.2 MB/s |
SP-Unigram 0.2.3 (streaming full) |
60.99s | 1,884 MB | 4.184 | 2.357 | 3.269 | 3.0984 | 31.9 MB/s |
SP-BPE 0.2.3 (whitespace split) |
9.24s | 1,683 MB | 4.266 | 2.473 | 3.431 | 3.1758 | 17.6 MB/s |
SP-BPE-Raw 0.2.3 (no whitespace split) |
22.77s | 3,577 MB | 4.187 | 3.786 | 4.167 | 3.0510 | 17.8 MB/s |
HF tokenizers BPE 0.23.3 |
28.00s | 2,931 MB | 4.025 | 3.614 | 3.893 | 3.0644 | 3.2 MB/s |
HF tokenizers Unigram 0.23.3 |
44.72s | 2,842 MB | 3.986 | 3.031 | 3.319 | 3.2428 | 2.1 MB/s |
Dual metrics: Compression (
B/Tok, higher is better) is total UTF-8 bytes divided by total tokens across the ZH, EN, and Code heldout sets;BPB(Bit/B, lower is better) is the log-probability cross-entropy per byte (native generative probabilities for Unigram; first-order empirical entropy fitted on training-split frequencies for BPE; per-domain EN figures in the full table).0.8.3prunes by exact deletion NLL to prioritizeBPB(down from0.8.2's 2.9798, with uniform compression slightly trimmed to 4.365). Single-thread ZH/EN/Code throughput is 61.2 / 27.7 / 35.5 MB/s (80.4 MB/s on long ZH docs); 32-thread zero-copyencode_batch_flatreaches 661 / 344 / 675 MB/s; single-thread perfect sampling reaches 31.3 / 10.4 / 10.0 MB/s (4.3–6.3× SP0.2.3full-lattice sampling). Scaling to 300 MB / 900 MB training data takes just 7.82 / 22.65 s, reaching 4.519 / 4.984 mixed compression and 2.8943 / 2.7702 Mixed BPB. For full multi-scale tables, randomized-tokenization benchmarks, and methodology, see Benchmarks & Reproducible Evaluation.
Download
To download the open-source BytePiece model, please go to models.
Citation
@misc{bytepiece2023,
title={BytePiece: A more pure and effective tokenizer},
author={Jianlin Su},
year={2023},
howpublished={\url{https://github.com/bojone/bytepiece}},
}
Communication
QQ Group: 67729435, for WeChat group please add robot spaces_ac_cn
Explore related projects
Loading…