Metadata-Version: 2.4
Name: bytepiece
Version: 0.8.2
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 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.2`, vs. previous `0.8.1`)**: Removes hard newline boundaries so cross-line structures like `:\n    ` merge naturally; training adopts 8 KB survivor-coalescing windows, while inference upgrades to full-segment exact decoding via a score ring buffer and 1-byte length backpointers—further improving compression, training speed, and long-text throughput while keeping legacy-model encodings bit-identical (see the [Changelog](https://github.com/bojone/bytepiece/blob/main/docs/CHANGELOG_en.md)).

## 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, full-segment 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 comparisons of the latest release against mainstream libraries on training, deterministic/randomized tokenization, and compression, plus the one-command script ([`docs/run_benchmark.py`](https://github.com/bojone/bytepiece/blob/main/docs/run_benchmark.py)).
- [Changelog](https://github.com/bojone/bytepiece/blob/main/docs/CHANGELOG_en.md) ([中文](https://github.com/bojone/bytepiece/blob/main/docs/CHANGELOG.md)): release notes since `0.8.0`.
- [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).

## 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 `numpy` and `tqdm` as 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 `.bpk` binary models (millisecond `mmap` loading) and native `pickle`, orthogonal `atomic × special` token 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](https://kexue.fm/archives/3956)): 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](https://kexue.fm/archives/9768) and [From Viterbi Sampling to Perfect Sampling](https://kexue.fm/archives/9811), achieving exact posterior sampling in linear time. See [Algorithm & Mathematical Principles](https://github.com/bojone/bytepiece/blob/main/docs/algorithm_en.md) 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):
```bash
pip install -U bytepiece   # or pip install bytepiece==0.8.2
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:

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

- `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.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](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.2 (latest)** | **3.77s** | **930 MB** | **4.398** | **4.820** | **4.467** | **53.6 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` (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 |

> 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 **53.6 / 26.5 / 33.8 MB/s** (**76.4 MB/s** on long ZH docs; *measured under ~50% background load on the shared host, reaching ~60 MB/s on ZH when idle); 32-thread zero-copy `encode_batch_flat` reaches **523 / 293 / 554 MB/s**; single-thread perfect sampling reaches **28.8 / 9.6 / 8.9 MB/s** (**4–6×** SP `0.2.3` full-lattice sampling). Scaling to 300 MB / 900 MB training data takes just **8.20 / 24.36 s**, reaching **4.618 / 5.019** mixed B/tok. For full multi-scale tables, randomized-tokenization benchmarks, 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
