tokenizers README

项目的 README,来自 github.com/huggingface/tokenizers。合并为一个 markdown 文件:README.md。



Build Crates.io Docs Size License

The SOTA tokenization library on all languages, all models, all hardwares.

Our goal with tokenizers is to develop and maintain the industry's standard tokenization engine, making it the defacto place for everyone to contribute to the whole ecosystem.

tokenizers v1.0.0 progress

Release candidate: v1.0.0.rc.x

As we are switching from 0.23 to v1.0.0, the current library does not ship all features. If you are worried, check the v1 features section for more details of what we are bringing back. We will publish a blog about what breaking changes we introduced. We strived to keep them as small as possible.

Installation

pip install --pre tokenizers

For Rust, add the crate to your Cargo.toml:

[dependencies]
tokenizers = "1.0.0"

Training (train) and downloading from the Hub (http) are opt-in features. The crate's Using the crate section lists every feature and how to build a smaller binary.

Usage

>>> from tokenizers import Tokenizer
>>> tokenizer = Tokenizer.from_pretrained("meta-llama/Llama-3.1-8B")   # or .from_file(path)
>>> compiled = tokenizer.compile()
>>> compiled.encode("Hello, y'all! How are you 😁 ?")
Encoding(ids=[128000, 9906, 11, 379, 65948, 0, 2650, 527, 499, 27623, 223, 949], type_ids=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], attention_mask=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
>>> compiled.encode(("What is this?", "A pair.")).type_ids
[0, 0, 0, 0, 0, 1, 1, 1, 1]
>>> compiled.tokenize("Hello")
['<|begin_of_text|>', 'Hello']
>>> compiled.decode([15339, 1917])
'hello world'
>>> compiled.decode_tokens(compiled.encode("Hello"))
['<|begin_of_text|>', 'Hello']

Tokenizer holds the tokenizer.json config and can be edited (e.g. tokenizer.truncation = ...); compile() builds the CompiledTokenizer that encodes and decodes.

Performances

image For more details, checkout https://huggingface-tokenizers-v1.static.hf.space/index.html.

Bindings

status
Rust ✅ reference implementation
Python ✅
Node.js ✅
WebAssembly ✅ tokenizers-wasm on npm
C / C++ / Java / Go/ etc 🚧 planned
Ruby community, external repo

v1.0.0 roadmap:

As we work toward v1, we are gonna bring back the entire python API that allows transformers' style of interacting with a tokenizer object:

TODOS:

Python Bindings

Rust core

Other

After 1.0.0

Crate details

Crate size

image

Sub-crates

tk-encode — the inference engine

The models (BPE, Unigram, WordPiece, WordLevel) and the full pipeline: Normalizer, PreTokenizer, Model, PostProcessor, Decoder.

Why separate: you don't need all features to serve a model in production settings. Splitting it from training means a serving binary never links a trainer, a corpus reader, legacy converters, etc.

bitcannon — bitstream pre-tokenization

Unicode tag classification plus pre-tokenization as a bitstream program. Follows Interleaved Bitstream Execution for Multi-Pattern Regex Matching on GPUs (MICRO'25, 10.1145/3725843.3756052) but we added our own algorithm to make sure we don't need a parabix engine. Characters are first classified into "tags", which use a sparse table generated when compiling bitcannon. This means there are 0 depencencies to the heavy unicode tables.

Ships byte-exact grammars for gpt2 / ByteLevel, cl100k, o200k, tekken, deepseek and kimi-k2. The classes or tags each have a high and low nibble (encoded on a u8), and carry refinement when needed. Using u8 tags allows us to leverage less bitsream, meaning have a simpler / faster pre tokenization.

Why separate: we just thought it might be useful to some people someday. As far as we know, this implementation is the fastest for every single pretokenizer regex on CPU.

tk-serialize — the reader

from_json_file turns a canonical tokenizer.json into a Tokenizer.

Why separate: this just makes it optional for some usecases!

tk-convert — the upgrade pass

canonicalize_file rewrites legacy a tokenizer.json written by any older version of this library into the canonical form the reader accepts. A pure JSON→JSON rewrite; it depends on nothing but std::path and serde_json.

Why separate: every config ever published stays readable without the runtime carrying a decade of compatibility branches. But, the legacy code amounted to quite a lot of the final crate size. Disabling it allows on device builds to be smaller.

tk-train — the training half

The Trainer trait, every concrete *Trainer, TrainerWrapper and the Trainable extension.

The tokenizers crate does not re-export it. Its API will still change, so the crate stays 0.x until it settles. It trains only the models whose feature is on (bpe, unigram, wordpiece, wordlevel). Add esaxx_fast for the C++ suffix array behind Unigram training.

Why separate: training is a batch job on a workstation; inference is a hot loop in a server. They have opposite constraints, so they get opposite dependency budgets.

bitmap_gen — dev-only table generator

cargo run -p bitmap_gen regenerates bitcannon's committed classify tables from unicode-properties, emitting one Atom tag per codepoint.

Why separate — this is what buys the zero Unicode dependency. unicode-properties is a dependency of this crate and of nothing else: the tables it produces are checked into bitcannon/src/classify/atom_tables.rs as ordinary source, so the Unicode data is resolved once, at development time, by a crate that is never linked into anything that ships and is never published. No build script either — bitcannon compiles with no code generation step, and a release binary contains the tags without containing a Unicode crate to derive them. The release workflow re-runs the generator and fails if the committed table differs, so "baked" cannot silently mean "stale".

tokenizers — umbrella

A thin re-export so existing tokenizers::… paths keep working. Depend on this one unless you know you want less.

Hardware

No SIMD is required. Every kernel has a portable path that is always compiled and is the byte-exact test oracle for its vectorised siblings, so correctness never depends on a kernel being present — only throughput does.

Which ops are hardware-adapted
op aarch64 x86_64 wasm32 portable fallback
Unicode atom classify NEON (baseline) AVX-512 VBMI → SSE4.1/SSSE3, runtime-detected SIMD128 classify_scalar
bitstream block build NEON SSE/AVX — build_block_scalar
literal & added-token scan NEON x86_64 — scalar
vocab bucket nibble match NEON — — scalar

aarch64 selects at compile time (NEON is baseline). x86_64 dispatches at runtime via is_x86_feature_detected!, so one binary covers every x86_64 CPU since 2008. wasm32 needs the simd128 target feature; without it, the scalar walk.

Acknowledgements

This work stands on the shoulders of a lot of open source projects. Thanks to all of them for their great work.

gigatoken, tiktoken, kitoken, tokie, fastokens, wordchipper and ai-tokenizer each pushed on what a fast tokenizer can be; we read that work, and several of the ideas above reached us because another project showed they were worth trying.

Docs: guide · quicktour · docs.rs

tokenizers (huggingface/tokenizers)

正在搜索数据库…

这是什么?Tokenizers 是一个自然语言处理(NLP)库,实现了当前最常用的分词器(BPE、WordPiece、Unigram)。它使用 Rust 编写以保证速度,并通过绑定提供给其他编程语言使用。它由 Hugging Face 开发,为 Transformer 模型提供分词功能。
这是独立应用,还是可以在代码中导入的库?它是一个库:核心用 Rust 编写,并提供 Python 和 Node.js 绑定,以及社区维护的 Ruby 绑定,可导入到你自己的训练或推理代码中使用。
我该如何安装和使用它?可以从源码安装,也可以通过对应语言的正式发布包安装(例如 Python 使用 pip)。然后选择一种模型类型,如 BPE、WordPiece 或 Unigram,创建分词器实例,再用你的文件训练,只需几行代码即可完成。
使用 Python 绑定是否需要安装 Rust?普通用户不需要单独安装 Rust 工具链。已发布的 Python 和 Node.js 包都是预编译好的,只有从源码编译时才需要源码构建工具。
性能是否取决于我的硬件?是的,基准测试中的速度数据会因硬件不同而有所差异。README 中给出的数字来自某个特定的 AWS g6 实例,仅供参考,并不是普遍适用的保证。
这个项目主要面向谁?它既面向研究分词方法的研究人员,也面向需要为语言模型提供快速、可靠文本预处理的生产团队。
分词的速度到底有多快?README 中说明,得益于 Rust 实现,在服务器 CPU 上对 1 GB 文本进行分词只需不到 20 秒。
能否将词元追溯到原始文本?可以。标准化处理带有对齐追踪功能,因此你总能找到某个词元在原句中对应的确切部分。
它会自动处理填充和截断吗?会。它能完成所需的全部预处理:截断、填充,并添加模型所需的特殊词元。
支持哪些分词算法?创建分词器实例时,可以在字节对编码(BPE)、WordPiece 或 Unigram 模型之间选择。
大小
24.7 MB
星标
11.3K
时长
7年
提交 · 90 天