Metadata-Version: 2.4
Name: bytepiece
Version: 0.8.0
Summary: Smarter Byte-based Tokenizer
Home-page: https://github.com/bojone/bytepiece
Author: bojone
Author-email: bojone@spaces.ac.cn
License: Apache License 2.0
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy
Requires-Dist: tqdm
Dynamic: author
Dynamic: author-email
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license
Dynamic: license-file
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

[[中文](https://github.com/bojone/bytepiece/blob/main/README.md)|English]

# BytePiece
BytePiece is a Byte-based Unigram tokenizer. Due to the use of a new training algorithm, its compression rate is often higher than existing Tokenizers, and it supports multithreaded training acceleration. Moreover, it directly operates on the UTF-8 Bytes of the text, with almost no preprocessing, making it more pure and language-independent.

**`0.8.0` (major upgrade from `0.6.3`)**: Core tokenization and training moved to a built-in C++17 engine (Double-Array Trie + compact flat hash tables + shared-memory multithreading), **completely removing the `pyahocorasick` and `Cython` dependencies**, with substantially faster training/tokenization and much lower memory usage while producing the exact same vocabulary as `0.6.3` under identical settings. It also adds production-ready LLM pipeline features: `pickle` serialization, compact binary models with millisecond `mmap` loading, lossless HuggingFace `tokenizer.json` / `PreTrainedTokenizerFast` export, orthogonal special tokens with matching controls, `TemplateProcessor` / FIM / Chat Templates (including `{% generation %}` assistant masks), character-level offset mapping, built-in truncation & padding, and streaming incremental UTF-8 decoding.

## Documentation

- [User Guide](https://github.com/bojone/bytepiece/blob/main/docs/guide_en.md) ([中文](https://github.com/bojone/bytepiece/blob/main/docs/guide.md)): training options, tokenization & batching, special tokens, LLM pipelines, model saving & ecosystem export, and API reference.
- [Algorithm & Mathematical Principles](https://github.com/bojone/bytepiece/blob/main/docs/algorithm_en.md) ([中文](https://github.com/bojone/bytepiece/blob/main/docs/algorithm.md)): BNLM training derivation, Viterbi decoding, piece pruning, and perfect sampling proof.
- [Implementation Walkthrough](https://github.com/bojone/bytepiece/blob/main/docs/implementation_en.md) ([中文](https://github.com/bojone/bytepiece/blob/main/docs/implementation.md)): data structures and optimizations in `trainer.py`, `tokenizer.py`, and `_core.cpp`.
- [Benchmarks & Reproducible Evaluation](https://github.com/bojone/bytepiece/blob/main/docs/benchmarks_en.md) ([中文](https://github.com/bojone/bytepiece/blob/main/docs/benchmarks.md)): open-corpus `0.6.3` vs `0.8.0` generational comparison and benchmarks against the latest mainstream libraries, attribution analysis, roadmap, and the one-command script ([`docs/run_benchmark.py`](https://github.com/bojone/bytepiece/blob/main/docs/run_benchmark.py)).
- [Test Suite](https://github.com/bojone/bytepiece/blob/main/tests/README_en.md) ([中文](https://github.com/bojone/bytepiece/blob/main/tests/README.md)): full parameter matrix, API roundtrips, fuzzing, regression anchors, and Sanitizer instructions.
- Blog posts: [BytePiece](https://kexue.fm/archives/9752), [Viterbi Sampling](https://kexue.fm/archives/9768), [Perfect Sampling](https://kexue.fm/archives/9811).

## Characteristics

An ideal Tokenizer and its training algorithm should have the following characteristics:
- Lossless reconstruction
- High compression rate
- Language-independent
- Data-driven
- Training-friendly

The mainstream [SentencePiece](https://github.com/google/sentencepiece) basically has the above characteristics, but there are still some problems. For example, it supports both BPE and Unigram algorithms. BPE often has a higher compression rate, but the training is extremely slow and consumes a lot of memory. Moreover, it does conduct some language-related preprocessing on the text, so it's not purely "language-independent". Besides, it's written in C++, which is a black box for most users, thus not conducive to research and modification.

BytePiece has conceived a new training method based on **Byte-based N-gram Language Model (BNLM)** , which can obtain a higher compression rate vocabulary table, support multithreaded training, and significantly accelerate compared to SentencePiece's BPE and Unigram training under the same corpus. In addition, BytePiece also provides a more efficient random segmentation algorithm than [Subword Regularization](https://arxiv.org/abs/1804.10959).

## Principle

BytePiece is not simply a rewrite of the existing Unigram model based on Byte-based and multithreading, but a new training method designed for Unigram, which is one of the key reasons for its higher compression rate.

The new training method is based on the new word discovery algorithm of the N-gram language model, first proposed in the author's blog 7 years ago [《【Chinese Word Segmentation Series】 5. Unsupervised Word Segmentation Based on Language Model》](https://kexue.fm/archives/3956). Please visit the blog for details.

For the new random segmentation algorithm, you can refer to ["A Brief Exploration of Random Segmentation: From Viterbi Decoding to Viterbi Sampling"](https://kexue.fm/archives/9768) and ["Further Exploration of Random Segmentation: From Viterbi Sampling to Perfect Sampling Algorithm"](https://kexue.fm/archives/9811).

## Installation

BytePiece runs on Python 3.8+ and only depends on `numpy` and `tqdm` at runtime. Building from source requires only a C++17 compiler (gcc/clang/MSVC):
```bash
pip install bytepiece==0.8.0
# or from the source directory
pip install .
```
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). See the [User Guide](https://github.com/bojone/bytepiece/blob/main/docs/guide_en.md) for full options.

### 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):
```python
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.model')          # legacy JSON; use 'bytepiece.bpk' for compact binary
```

- `order`: N-gram order (`1~7`, default `6`); `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=True` splits 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 within `max_vocab_size` at fixed consecutive IDs `3, 4, ...`; `trainer.to_tokenizer()` returns a tokenizer with them pre-registered.

### Tokenization & Batching

```python
from bytepiece import Tokenizer

tokenizer = Tokenizer('bytepiece.model') # loading '.bpk' enables zero-copy mmap automatically
text = "Today's weather is great"

tokens = tokenizer.tokenize(text)        # list[bytes]
ids = tokenizer.encode(text)             # list[int]; alpha=0.2 enables perfect sampling
assert tokenizer.decode(ids) == text

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](https://github.com/bojone/bytepiece/blob/main/docs/guide_en.md).

## 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↑ | ZH 1-thread↑ |
| :----: | :----: | :----: | :----: | :----: | :----: | :----: |
| **BytePiece 0.8.0** | **3.14s** | **877 MB** | **4.330** | **4.742** | **4.410** | **58.6 MB/s** |
| BytePiece `0.6.3` (legacy) | 75.38s | 42,387 MB* | 4.330 | 4.742 | 4.410 | 3.9 MB/s |
| SP-Unigram `0.2.3` (streaming full) | 60.99s | 1,884 MB | 4.184 | 2.357 | 3.269 | 31.9 MB/s |
| SP-BPE `0.2.3` (default whitespace split) | 9.24s | 1,683 MB | 4.266 | 2.473 | 3.431 | 17.6 MB/s |
| SP-BPE-Raw `0.2.3` (no whitespace split) | 22.77s | 3,577 MB | 4.187 | 3.786 | 4.167 | 17.8 MB/s |
| HF `tokenizers` BPE `0.23.3` | 28.00s | 2,931 MB | 4.025 | 3.614 | 3.893 | 3.2 MB/s |
| HF `tokenizers` Unigram `0.23.3` | 44.72s | 2,842 MB | 3.986 | 3.031 | 3.319 | 2.1 MB/s |

> **Generational upgrade (`0.6.3` → `0.8.0`, same open corpus & hyperparameters)**: **20.9× faster** training, **48× lower** process-tree peak memory (*32 `multiprocessing` workers summed 42.4 GB RSS in `0.6.3`; main-process `VmHWM` alone was 2,391 MB), **14.6× faster** single-thread ZH tokenization, and **1.55 ms** `.bpk` model loading (down from 141 ms)—with identical compression across all three domains and zero encoding mismatches when `0.8.0` loads legacy models.
>
> Mixed B/tok is total UTF-8 bytes divided by total tokens across the ZH, EN, and Code heldout sets (EN compression in the full table). Single-thread ZH/EN/Code throughput is **58.6 / 26.6 / 32.2 MB/s** (**79.5 MB/s** on long ZH docs); 32-thread zero-copy `encode_batch_flat` reaches **610 / 346 / 620 MB/s**. For the full three-scale `0.6.3` vs `0.8.0` comparison, 300 MB & 900 MB stress tests, SP 0.1.99 vs 0.2.3 comparisons, latest pretrained vocabulary comparisons, and methodology, see [Benchmarks & Reproducible Evaluation](https://github.com/bojone/bytepiece/blob/main/docs/benchmarks_en.md).

## Download

To download the open-source BytePiece model, please go to [models](https://github.com/bojone/bytepiece/tree/main/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
