# tiktoken

**tiktoken** 是 OpenAI 发布的一个开源字节对编码（BPE）分词库，用于将文本转换为其语言模型所消费的整数令牌序列，并能反向转换。它用 Rust 编写并带有 Python 绑定，于 2022 年 12 月 15 日首次上传至 PyPI，其维护者将其描述为用于 OpenAI 模型的快速 BPE 分词器。<sup>[1](https://pypi.org/project/tiktoken/)</sup> 由于 OpenAI 按令牌对 API 使用量计价，并按令牌执行每个模型的上下文限制，tiktoken 可用于在发送请求前估算成本和容量；对于基于消息的模型，其计数为估算值。<sup>[2](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken)</sup>

| 关键事实 | 详情 |
|---|---|
| 功能 | `.encode()` 将文本字符串转换为令牌整数列表；令牌数即该列表的长度，可帮助估算上下文适配度和 API 成本。<sup>[2](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken)</sup> |
| 随附编码 | o200k_base、o200k_harmony、cl100k_base、p50k_base 和 r50k_base（也称 gpt2）。<sup>[2](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken)</sup><sup> • </sup><sup>[3](https://github.com/openai/tiktoken/blob/main/tiktoken/model.py)</sup> |
| 模型映射 | gpt-4o、gpt-4.1、gpt-4.5、gpt-5、o1、o3 和 o4-mini 使用 o200k_base；gpt-4 和 gpt-3.5-turbo 使用 cl100k_base；gpt-oss 使用 o200k_harmony。<sup>[3](https://github.com/openai/tiktoken/blob/main/tiktoken/model.py)</sup> |
| 速度 | 在 1 GB 文本上测量，tiktoken 0.2.0 对比 tokenizers 0.13.2 和 transformers 4.24.0，比同类开源 GPT2TokenizerFast 快 3–6 倍。<sup>[1](https://pypi.org/project/tiktoken/)</sup> |
| 英文规模 | 一个令牌大致相当于 4 个字符或常见英文文本的 3/4 个单词；100 个令牌约合 75 个单词。<sup>[4](https://platform.openai.com/tokenizer/)</sup> |
| 特殊令牌安全 | 以 `disallowed_special="all"` 调用 `encode` 时，若遇到意外的特殊令牌注入（如输入包含 `<|endoftext|>` 等特殊令牌），会引发 ValueError。<sup>[5](https://google.github.io/sentencepiece/python/tokenizer_comparison_cheat_sheet/)</sup> |
| 设计限制 | tiktoken 仅支持 BPE 算法，不支持训练，且按设计不进行文本规范化，而是对原始输入原样分词。<sup>[5](https://google.github.io/sentencepiece/python/tokenizer_comparison_cheat_sheet/)</sup> |

## 字节级 BPE 分词的工作原理

字节对编码将分词视为压缩：在语料库上训练时贪婪地构建令牌合并字典，编码时将那些合并应用于新文本。<sup>[6](https://ar5iv.labs.arxiv.org/html/2309.08715)</sup> tiktoken 的实现是字节级的，基于 256 个字节的基础词表。这意味着任何字节序列都可编码，包括无效的 UTF-8，这对代码、二进制数据和对抗性输入很重要；不存在未知令牌（<unk>）回退，因为没有任何东西会掉出词表。<sup>[7](https://systeminternals.dev/llm/tokenization/)</sup><sup> • </sup><sup>[5](https://google.github.io/sentencepiece/python/tokenizer_comparison_cheat_sheet/)</sup>

**预分词先行。** BPE 模型应用一个正则表达式，将输入文本分成更小、更易处理的块，称为预令牌；由于合并仅限于单个预令牌内，不能从一个预令牌跨到另一个，这一划分决定了流水线后续步骤收到什么。<sup>[8](https://huggingface.co/blog/tokenizers-v1)</sup> Rust 核心为此步骤使用预计算的合并表和正则分割（通过 `fancy-regex` 包）。cl100k_base 的预分词器正则按特定顺序对缩约词、数字、空白串和标点进行分割，该顺序经过经验调优。<sup>[7](https://systeminternals.dev/llm/tokenization/)</sup> 由于各实现在应用主 BPE 过程之前先按空白分割进行预分词，合并规则的应用顺序在实践中变得基本无关紧要。<sup>[6](https://ar5iv.labs.arxiv.org/html/2309.08715)</sup>

编码对于完整字符串是可逆且无损的：解码完整令牌列表会返回原始文本。在英文中，令牌长度通常从一个字符到一个单词不等，空格通常与单词开头分组。然而，对于不在 UTF-8 边界上的令牌，解码单个令牌可能是有损的。<sup>[2](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken)</sup> tiktoken 按设计不进行文本规范化，因此原始输入按原样分词。<sup>[5](https://google.github.io/sentencepiece/python/tokenizer_comparison_cheat_sheet/)</sup>

## 编码与模型兼容性

tiktoken 随附 OpenAI 模型使用的编码。根据 OpenAI Cookbook：o200k_base 服务于 gpt-4o 和 gpt-4o-mini；cl100k_base 服务于 gpt-4-turbo、gpt-4、gpt-3.5-turbo、text-embedding-ada-002、text-embedding-3-small 和 text-embedding-3-large；p50k_base 服务于 [Codex](https://www.edgepedia.org/zh/codex-2021-model) 模型和 text-davinci-002/003；r50k_base（也称 gpt2）服务于 davinci 等 GPT-3 模型。<sup>[2](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken)</sup> p50k_base 与 r50k_base 大幅重叠，对于非代码应用，它们通常给出相同的令牌。<sup>[2](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken)</sup>

该库自身的模型映射代码将其扩展到更新世代：前缀 o1-、o3- 和 o4-mini- 映射到 o200k_base，gpt-5、gpt-4.5-、gpt-4.1-、chatgpt-4o- 和 gpt-4o- 也是如此；gpt-4- 和 gpt-3.5-turbo- 映射到 cl100k_base；gpt-oss- 映射到 o200k_harmony。微调变体跟随其基础模型（ft:gpt-4o 到 o200k_base，ft:gpt-4 和 ft:gpt-3.5-turbo 到 cl100k_base）。<sup>[3](https://github.com/openai/tiktoken/blob/main/tiktoken/model.py)</sup> Rust 移植版 tiktoken-rs 的文档记载 o200k_base 服务于 GPT-4o、o1、o3 和 o4-mini，并且还包含用于 Qwen 2.5/3 的 qwen2 编码，含 151,643 个常规令牌加上 22 个附加令牌，涵盖聊天、视觉、工具调用和中间填充标记。<sup>[9](https://docs.rs/tiktoken/latest/tiktoken/encoding/index.html)</sup>

不同来源的词表大小略有差异。一项第三方基准报告 cl100k_base 为 100,277 个令牌，o200k_base 为 200,019 个令牌，<sup>[10](https://github.com/delcenjo/tokenizer-benchmark)</sup> 而 tiktoken-rs 文档给出 cl100k_base 为 100,256 个常规令牌加 5 个特殊令牌，o200k_base 为 199,998 个常规令牌加 2 个特殊令牌。<sup>[9](https://docs.rs/tiktoken/latest/tiktoken/encoding/index.html)</sup> 两个来源都同意 o200k 词表大约是 cl100k 的两倍。

## 特殊令牌与安全

特殊令牌是人工令牌字符串，如 `<|endoftext|>` 和中间填充标记，携带控制含义而非普通文本。tiktoken 在调用时通过 `allowed_special` 和 `disallowed_special` 参数强制执行特殊令牌安全，允许逐令牌处理特殊令牌：以 `disallowed_special="all"` 调用 `encode` 时，若遇到意外的特殊令牌注入会引发 ValueError。它通过 `allowed_special` 和 `disallowed_special` 参数允许逐令牌的特殊令牌处理，不同于 [SentencePiece](https://www.edgepedia.org/zh/sentencepiece) 对 `control_symbols`（安全）和 `user_defined_symbols`（不安全）的静态区分。<sup>[5](https://google.github.io/sentencepiece/python/tokenizer_comparison_cheat_sheet/)</sup><sup> • </sup><sup>[13](https://github.com/openai/tiktoken/blob/main/tiktoken/core.py)</sup>

## 性能与实现

tiktoken 的核心是 Rust 加 Python 绑定，快速、确定，与 OpenAI 生产环境运行的一致。<sup>[7](https://systeminternals.dev/llm/tokenization/)</sup> 已发布的声明是比同类开源分词器快 3–6 倍，在 1 GB 文本上用 GPT-2 分词器对比 tokenizers 0.13.2 和 transformers 4.24.0 中的 GPT2TokenizerFast，使用 tiktoken 0.2.0。<sup>[1](https://pypi.org/project/tiktoken/)</sup> 一项独立基准在方向上一致：[Hugging Face](https://www.edgepedia.org/zh/hugging-face) 的 gpt2 分词器（50,257 词表，在英文为主的 WebText 上训练）在英文散文上达到 2.849 MB/s，而 cl100k_base 在同一测试框架中达到 15.775 MB/s，尽管该比较混合了算法和实现效应。<sup>[10](https://github.com/delcenjo/tokenizer-benchmark)</sup>

并行是部分的。tiktoken 仅在核心 Rust 执行期间释放 GIL，而 Python 级线程和转换持有它；批量编码并行通过 Python ThreadPoolExecutor 映射到 Rust 运行，文档内没有并行。<sup>[5](https://google.github.io/sentencepiece/python/tokenizer_comparison_cheat_sheet/)</sup>

## 数据说话

OpenAI 的经验法则是，一个令牌对应约 4 个字符的常见英文文本，约 3/4 个单词，因此 100 个令牌约 75 个单词。<sup>[4](https://platform.openai.com/tokenizer/)</sup> PyPI 文档给出的平均值约为每令牌 4 字节。<sup>[1](https://pypi.org/project/tiktoken/)</sup> 测量数据接近：在《[傲慢与偏见](https://www.edgepedia.org/zh/pride-and-prejudice)》上，cl100k_base 产生每单词 1.399 个令牌，每令牌 4.372 字节，o200k_base 产生每单词 1.385 个令牌，每令牌 4.417 字节。<sup>[10](https://github.com/delcenjo/tokenizer-benchmark)</sup>

一些非英文文本可能需要比英文更多的令牌，而代码令牌数因编码和语料库而异。相对于英文的生育率开销，cl100k_base 在西班牙语上为 +23.6%，o200k_base 为 +11.4%；在 Python 代码上分别为 +63.4% 和 +66.3%。<sup>[10](https://github.com/delcenjo/tokenizer-benchmark)</sup> 一个具体的非英文例子：o200k_base 将日文字符串 お誕生日おめでとう 编码为 8 个令牌。<sup>[2](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken)</sup> 词表大小也与模型参数权衡：一个 200k 词表、4096 维的模型在嵌入层上花费约 8.2 亿参数，而更大的词表相比 32k 词表将序列缩短约 10%。<sup>[7](https://systeminternals.dev/llm/tokenization/)</sup>

## 与其他分词器的比较

SentencePiece（v0.2.3+）、Hugging Face tokenizers（v0.23.1）和 tiktoken（v0.13.0）的功能比较清晰地划出了边界。tiktoken 仅支持 BPE 算法，不支持训练，也不提供 Unicode 编码偏移映射，而 SentencePiece 支持 BPE、Unigram、Char 和 Word，并通过 SentencePieceTrainer 训练，Hugging Face 支持 BPE、WordPiece、Unigram 和 WordLevel，带有训练器类。<sup>[5](https://google.github.io/sentencepiece/python/tokenizer_comparison_cheat_sheet/)</sup> tiktoken 确实通过 `decode_with_offsets` 提供部分的、仅起始偏移的解码偏移映射。<sup>[5](https://google.github.io/sentencepiece/python/tokenizer_comparison_cheat_sheet/)</sup>

**空白处理是最鲜明的对比。** SentencePiece 将空白视为特殊字符（▁），因此 "Hello world" 变成 "▁Hello▁world"，没有单独的预分词步骤；Llama-1、Llama-2、T5 和 mBART 使用 SentencePiece 与 Unigram 算法。<sup>[7](https://systeminternals.dev/llm/tokenization/)</sup> tiktoken 则用正则进行预分词，完全不训练分词器；它为 OpenAI 模型随附固定的、预计算的词表。<sup>[7](https://systeminternals.dev/llm/tokenization/)</sup><sup> • </sup><sup>[5](https://google.github.io/sentencepiece/python/tokenizer_comparison_cheat_sheet/)</sup>

移植生态广泛。除 Python 外，Cookbook 列出了 .NET（SharpToken、TiktokenSharp）、Java（jtokkit）、Go（tiktoken-go）、Rust（tiktoken-rs）、[JavaScript](https://www.edgepedia.org/zh/javascript)（gpt-3-encoder）和 PHP（GPT-3-Encoder-PHP）针对 o200k_base、cl100k_base 和 p50k_base 的实现。<sup>[2](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken)</sup> OpenAI 的分词器页面还指引 JavaScript 用户使用社区支持的 @dbdq/tiktoken 包。<sup>[4](https://platform.openai.com/tokenizer/)</sup> Rust 移植版将每种编码打包为嵌入的压缩数据文件、一个正则模式以及一组带指定 id 的特殊令牌。<sup>[9](https://docs.rs/tiktoken/latest/tiktoken/encoding/index.html)</sup>

## 近期发展

最大的变化是随 GPT-4o 引入的 o200k_base。其大约翻倍的词表削减了多语言分词税：在西班牙语上，相对于英文的生育率开销从 cl100k_base 的 +23.6% 降至 o200k_base 的 +11.4%，西班牙语吞吐量在基准测试框架中从 12.969 MB/s 升至 18.505 MB/s。<sup>[10](https://github.com/delcenjo/tokenizer-benchmark)</sup> 另一个新特点是感知代码的压缩：OpenAI 的两个在包含真实代码的数据上训练的分词器 cl100k_base 和 o200k_base，各自将 Python 语料库压缩得比英文散文更紧（cl100k_base 为 4.549 对 4.372 字节/令牌；o200k_base 为 4.516 对 4.417），而所有其他测试的分词器处理代码的效率都不如英文。<sup>[10](https://github.com/delcenjo/tokenizer-benchmark)</sup>

发布节奏持续稳定：0.6.0（2024 年 2 月）、0.7.0（2024 年 5 月）、0.8.0（2024 年 10 月）、0.9.0（2025 年 2 月）、0.10.0 和 0.11.0（2025 年 8 月）、0.12.0（2025 年 10 月）、0.13.0（2026 年 5 月）和 0.14.0（2026 年 8 月），继 2022 年 12 月 15 日发布首个版本 0.1.1 之后。<sup>[1](https://pypi.org/project/tiktoken/)</sup> 模型支持一直跟随模型线，o 系列、GPT-4.1、GPT-4.5、GPT-5 和 gpt-oss（使用 o200k_harmony 编码）已加入映射表。<sup>[3](https://github.com/openai/tiktoken/blob/main/tiktoken/model.py)</sup>

## 实际使用与限制

令牌计数驱动两个实际决策。第一，成本：API 使用按令牌计价，因模型以及令牌是输入、输出还是缓存而异，缓存令牌通常以折扣费率计费。<sup>[11](https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them)</sup> 第二，容量：每个模型有输入加输出的最大组合令牌限制，当前高容量模型支持高达数十万令牌的上下文。<sup>[11](https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them)</sup> 对更新模型有两个注意事项：一些推理模型在产生最终输出前使用额外的内部推理令牌，因此可见响应长度不反映总令牌使用量，<sup>[11](https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them)</sup> 而对于 ChatGPT 风格基于消息的模型，OpenAI 将其计数函数描述为估算，而非永久保证，使用可选 functions 输入的请求会消耗额外令牌。<sup>[2](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken)</sup> 对于嵌入，tiktoken 在提交前估算计数，因为 text-embedding-3-small 等嵌入模型有最大令牌限制，第三代嵌入模型应使用 cl100k_base。<sup>[12](https://help.openai.com/en/articles/8984337-how-can-i-tell-how-many-tokens-a-string-will-have-before-i-try-to-embed-it)</sup>

**正则模式的局限所在。** 基于空白的预分词难以处理缺乏词间空白的文字，如泰文、中文和日文，以及空白可选的人工语言如压缩代码。<sup>[6](https://ar5iv.labs.arxiv.org/html/2309.08715)</sup> cl100k_base 模式对缩约词、数字、空白串和标点的处理经过经验调优，它塑造了数字字符串和源代码如何分割成令牌。<sup>[7](https://systeminternals.dev/llm/tokenization/)</sup> 在比较方面，令牌在不同 AI 模型或提供商之间并不标准化：不同模型可以以不同令牌数处理相同文本，因此较低的每百万令牌标价不一定意味着较低的总成本。<sup>[11](https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them)</sup>

## References

1. [tiktoken on PyPI (v0.14.0)](https://pypi.org/project/tiktoken/)
2. [How to count tokens with tiktoken, OpenAI Cookbook](https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken)
3. [tiktoken/model.py, OpenAI GitHub](https://github.com/openai/tiktoken/blob/main/tiktoken/model.py)
4. [Tokenizer, OpenAI API](https://platform.openai.com/tokenizer/)
5. [Tokenizer Comparison Cheat Sheet, SentencePiece Documentation](https://google.github.io/sentencepiece/python/tokenizer_comparison_cheat_sheet/)
6. [Formalizing BPE Tokenization, arXiv:2309.08715](https://ar5iv.labs.arxiv.org/html/2309.08715)
7. [Tokenization — BPE, WordPiece, SentencePiece, tiktoken, Systems Explained](https://systeminternals.dev/llm/tokenization/)
8. [tokenizers v1: encode, decode and scaling, measured, Hugging Face](https://huggingface.co/blog/tokenizers-v1)
9. [tiktoken::encoding, tiktoken-rs documentation, docs.rs](https://docs.rs/tiktoken/latest/tiktoken/encoding/index.html)
10. [delcenjo/tokenizer-benchmark, GitHub](https://github.com/delcenjo/tokenizer-benchmark)
11. [What are tokens and how to count them?, OpenAI Help Center](https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them)
12. [How can I tell how many tokens a string will have before I try to embed it?, OpenAI Help Center](https://help.openai.com/en/articles/8984337-how-can-i-tell-how-many-tokens-a-string-will-have-before-i-try-to-embed-it)
13. [tiktoken/tiktoken/core.py at main · openai/tiktoken · GitHub](https://github.com/openai/tiktoken/blob/main/tiktoken/core.py)

---
*Initially written Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 人工智能与数据 › Language and vision AI › Natural language processing › NLP tasks and methods › Tokenization and segmentation

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/tiktoken

English original: https://www.edgepedia.org/tiktoken
