Transformers 中的 ByT5:无分词器的字节级序列到序列模型实战指南
【免费下载链接】transformers🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers
导读
ByT5 是 Google 提出的"token-free"(免分词器)预训练模型,它移除了传统 NLP 中依赖词表与子词分词的前处理管线,直接在原始 UTF-8 字节序列上运行标准 Transformer 架构。在 🤗 Transformers 仓库中,ByT5 以T5ForConditionalGeneration+ByT5Tokenizer的组合提供完整支持:你可以完全跳过 tokenizer 手动把文本编码为字节 ID,也可以借助ByT5Tokenizer轻松完成批处理与训练。阅读完本文,你将掌握 ByT5 的字节编码原理、三种典型调用方式(无分词器单样本、分词器批处理、手工 span masking),以及它在源码中的实现细节与测试验证。
1. ByT5 是什么:论文与模型定位
ByT5 出自论文 ByT5: Towards a token-free future with pre-trained byte-to-byte models(Linting Xue、Aditya Barua、Noah Constant、Rami Al-Rfou、Sharan Narang、Mihir Kale、Adam Roberts、Colin Raffel)。该模型由 patrickvonplaten 贡献到 Transformers,原始代码来自 google-research/byt5。
论文的核心论断可以概括为三点:
- 主流预训练模型都在"词/子词 token"序列上工作,而将文本编码为 token 序列需要分词器,分词器通常又与特定语言或语料绑定;
- 直接在原始文本(字节或字符)上工作的 token-free 模型拥有显著优势:开箱即可处理任何语言、对噪声(如拼写错误)更鲁棒、并且通过移除复杂易错的文本前处理流水线来最小化技术负债;
- 由于字节序列比 token 序列更长,过去的研究常为此设计新的模型架构;而论文证明,标准 Transformer 架构只需极小改动即可处理字节序列,并在参数量、FLOPs、训练与推理速度之间仔细刻画了权衡,表明字节级模型可以与 token 级模型竞争,且在拼写与发音敏感的任务上表现更优。
在仓库中,ByT5 的架构基础是 T5v1.1,官方文档明确提示:两者只在"如何准备模型输入"上不同,API 层面完全复用 T5 的文档与实现。
2. 架构关系:基于 T5v1.1,输入方式不同
根据关联文档中的 Tip 说明,ByT5 的架构基于 T5v1.1 模型,API 参考请查看 T5v1.1 文档页面,两者仅在准备模型输入的方式上有所不同。
此外还有一个实用建议需要记住:
ByT5 是无监督预训练的,因此在单任务微调时使用任务前缀(task prefix)没有收益;只有在多任务微调时,才需要使用任务前缀来区分不同任务。
这一点与 T5 的典型用法不同,使用 ByT5 微调时务必注意。
3. 核心原理:为什么 259 个输入 ID 就够了
ByT5Tokenizer的核心实现位于 src/transformers/models/byt5/tokenization_byt5.py,理解它就能理解整个模型的数据通路:
- 分词器没有词表文件(
save_vocabulary直接返回空元组,见 tokenization_byt5.py); - 词表大小
self._utf_vocab_size = 2**8,即UTF-8 是 8 位编码,共 256 个字节值; - 模型另有 3 个特殊 token,占据 ID 0、1、2:
pad(<pad>)、eos(</s>)、unk(<unk>),见 tokenization_byt5.py; - 因此每个 UTF-8 字节的编码都要 +3 偏移,总输入 ID 数为
2**8 + 3 = 259。
对应到代码,字节 → ID 的转换是:
token_id = ord(token) + self.offset # offset = 3ID → 字节的转换是chr(index - self.offset)(见 tokenization_byt5.py)。
在 src/transformers/models/auto/tokenization_auto.py 中,"byt5"被映射到ByT5Tokenizer,因此AutoTokenizer.from_pretrained("google/byt5-small")会自动加载正确的分词器。
测试 tests/models/byt5/test_tokenization_byt5.py 中有个很能说明问题的用例test_multibytes_char:输入"Unicode €."(欧元符号 € 在 UTF-8 下占 3 个字节),编码结果为[88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1],其中229, 133, 175正是 € 的 3 个 UTF-8 字节加偏移后的值,末尾的1是自动追加的</s>。
3.1 特殊 token 的拼接规则
从 tokenization_byt5.py 可以看到序列的拼接格式:
- 单序列:
X </s> - 序列对:
A </s> B </s>
_add_eos_if_not_present会检测输入是否已含</s>,避免重复添加 EOS(测试test_eos_treatment验证了这一点)。另外 ByT5 不使用 token type ids,create_token_type_ids_from_sequences恒返回全零列表。
4. 用法一:完全绕过分词器,手动编码 UTF-8 字节
因为 ByT5 直接操作原始 UTF-8 字节,你可以不加载任何 tokenizer,仅用标准库的encode("utf-8")构造输入:
>>> from transformers import T5ForConditionalGeneration >>> import torch >>> model = T5ForConditionalGeneration.from_pretrained("google/byt5-small") >>> num_special_tokens = 3 >>> # 模型有 3 个特殊 token,占据 ByT5 的输入 ID 0、1、2。 >>> # => 在把 ID 传给模型前,需要把 utf-8 字符编码整体偏移 3。 >>> input_ids = torch.tensor([list("Life is like a box of chocolates.".encode("utf-8"))]) + num_special_tokens >>> labels = torch.tensor([list("La vie est comme une boîte de chocolat.".encode("utf-8"))]) + num_special_tokens >>> loss = model(input_ids, labels=labels).loss >>> loss.item() 2.66要点:
list("...".encode("utf-8"))把字符串拆成一个个字节整数(0~255),再加 3 得到模型输入 ID;- 此时没有
attention_mask与 padding,只适合单样本演示;批处理与训练请使用分词器(见下一节)。
5. 用法二:通过 ByT5Tokenizer 进行批处理与训练
文档明确建议:对于批推理和训练,推荐使用 tokenizer。ByT5Tokenizer会负责字节切分、EOS 追加、padding 与 attention mask,让你能像用普通分词器一样组织 batch:
>>> from transformers import T5ForConditionalGeneration, AutoTokenizer >>> model = T5ForConditionalGeneration.from_pretrained("google/byt5-small") >>> tokenizer = AutoTokenizer.from_pretrained("google/byt5-small") >>> model_inputs = tokenizer( ... ["Life is like a box of chocolates.", "Today is Monday."], padding="longest", return_tensors="pt" ... ) >>> labels_dict = tokenizer( ... ["La vie est comme une boîte de chocolat.", "Aujourd'hui c'est lundi."], padding="longest", return_tensors="pt" ... ) >>> labels = labels_dict.input_ids >>> loss = model(**model_inputs, labels=labels).loss >>> loss.item() 17.9几个实操要点:
padding="longest"会将 batch 内序列对齐到最长长度,pad token 的 ID 为 0;ByT5Tokenizer的model_input_names = ["input_ids", "attention_mask"],因此会输出这两个键;- 测试 test_tokenization_byt5.py 中的
test_prepare_batch_integration验证了 batch 编码的形状与数值(两条输入得到(2, 37)的input_ids与attention_mask),test_max_length_integration验证了max_length+padding="max_length"+truncation的组合行为。
6. 用法三:手工构造 span masking 输入(预训练任务)
与 T5 类似,ByT5 在 span masking 去噪任务上训练。但由于模型直接作用于字符,预训练任务的掩码方式略有不同:T5 使用<extra_id_N>哨兵 token,而 ByT5 使用从 258 向下递减的掩码 ID。
原因在于:UTF-8 用 8 位表示,ByT5 有 3 个特殊 token,因此共有2**8 + 2 = 259个输入 ID,掩码 token 从索引 258 开始向下计数。而且注意不能直接把"<extra_id_...>"拼进字符串,因为字节级 tokenizer 会错误地合并这些 token——必须直接在字符级 ID 上操作。
下面把句子"The dog chases a ball in the park."的"chases "和"the "两段替换为掩码,构造出"The dog [258]a ball [257]park.":
>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM >>> import torch >>> tokenizer = AutoTokenizer.from_pretrained("google/byt5-base") >>> model = AutoModelForSeq2SeqLM.from_pretrained("google/byt5-base") >>> input_ids_prompt = "The dog chases a ball in the park." >>> input_ids = tokenizer(input_ids_prompt).input_ids >>> # 注意:不能直接把 "{extra_id_...}" 拼进字符串, >>> # 因为字节级 tokenizer 会错误地合并这些 token。 >>> # 对 ByT5 来说,需要直接在字符级工作; >>> # 与 T5 不同,ByT5 不用哨兵 token 做掩码,而是使用末尾的 utf 字符 ID。 >>> # UTF-8 用 8 位表示,ByT5 有 3 个特殊 token。 >>> # => 共有 2**8+2 = 259 个输入 ID,掩码 token 从索引 258 向下计数。 >>> # => 掩码为 "The dog [258]a ball [257]park." >>> input_ids = torch.tensor([input_ids[:8] + [258] + input_ids[14:21] + [257] + input_ids[28:]]) >>> input_ids tensor([[ 87, 107, 104, 35, 103, 114, 106, 35, 258, 35, 100, 35, 101, 100, 111, 111, 257, 35, 115, 100, 117, 110, 49, 1]])注意input_ids[14:21]切片中已经包含"chases "与"the "等掩码位置以外的字节 ID。生成时,ByT5 一次只产出一个字符,因此需要比 token 级模型长得多的max_length:
>>> # ByT5 一次只生成一个字符,因此这里需要生成更多的输出字符 -> 设置 max_length=100。 >>> output_ids = model.generate(input_ids, max_length=100)[0].tolist() >>> output_ids [0, 258, 108, 118, 35, 119, 107, 104, 35, 114, 113, 104, 35, 122, 107, 114, 35, 103, 114, 104, 118, 257, 35, 108, 113, 35, 119, 107, 104, 35, 103, 108, 118, 102, 114, 256, 108, 113, 35, 119, 107, 104, 35, 115, 100, 117, 110, 49, 35, 87, 107, 104, 35, 103, 114, 106, 35, 108, 118, 35, 119, 107, 104, 35, 114, 113, 104, 35, 122, 107, 114, 35, 103, 114, 104, 118, 35, 100, 35, 101, 100, 111, 111, 35, 108, 113, 255, 35, 108, 113, 35, 119, 107, 104, 35, 115, 100, 117, 110, 49]注意输出中掩码 ID 是如何依次递减的:258 → 257 → 256 → 255。最后按掩码 ID 切分输出并解码:
>>> # ^- 注意 258 递减到 257、256、255 >>> # 现在需要按哨兵 token 切分输出,写一个简短循环: >>> output_ids_list = [] >>> start_token = 0 >>> sentinel_token = 258 >>> while sentinel_token in output_ids: ... split_idx = output_ids.index(sentinel_token) ... output_ids_list.append(output_ids[start_token:split_idx]) ... start_token = split_idx ... sentinel_token -= 1 >>> output_ids_list.append(output_ids[start_token:]) >>> output_string = tokenizer.batch_decode(output_ids_list) >>> output_string ['<pad>', 'is the one who does', ' in the disco', 'in the park. The dog is the one who does a ball in', ' in the park.']模型重建出的两个被掩码片段分别是"is the one who does"与" in the disco",语义上与原句吻合。这个流程完整复现了 ByT5 预训练时对字符级文本做 span masking 并逐片段重建的工作方式。
7. 从源码看 ByT5Tokenizer 的实现细节
src/transformers/models/byt5/tokenization_byt5.py 是仓库中 ByT5 唯一的模型侧源码文件(模型本体完全复用 T5),其设计要点如下:
| 成员 / 方法 | 行为 |
|---|---|
_tokenize(text) | 把字符串encode("utf-8")后逐字节转成单字符 token(见 L195-L198) |
_convert_token_to_id(token) | 仅接受单字符 token,ord(token) + 3;非单字符返回 None |
_convert_id_to_token(index) | chr(index - 3) |
convert_tokens_to_string(tokens) | 把各 token 按字节拼接后以 UTF-8 解码,非法字节以errors="ignore"忽略(见 L215-L227) |
vocab_size | 恒为 256(2**8) |
save_vocabulary | 返回空元组——ByT5 没有词表文件 |
extra_ids参数 | 默认 125,会生成<extra_id_0>…<extra_id_124>追加为特殊 token;源码注释指出这些 extra ids 实际未被使用 |
测试 tests/models/byt5/test_tokenization_byt5.py 还验证了几个容易踩坑的行为:
- 单字节解码可能失败:
test_decode_single_bytes表明单个字节 ID(如 255)decode 出来是空字符串,因为单字节未必构成合法 UTF-8 序列; - 无词表相关测试被跳过:
test_get_vocab、test_conversion_reversible等因 ByT5 没有词表而被显式跳过; - 多字节字符往返一致:
test_multibytes_char验证了"Unicode €."编码后解码可还原为"Unicode €.</s>"; - 保存/加载无需词表:
test_save_and_load_tokenizer验证save_pretrained/from_pretrained前后编码结果一致,且不会保存 vocab 文件。
8. 快速上手:从加载到生成的完整路径
如果你更习惯 pipeline / AutoModel 风格,英文文档 docs/source/en/model_doc/byt5.md 给出了标准生成示例:用AutoModelForSeq2SeqLM+AutoTokenizer加载google/byt5-small,将"summarize: ..."前缀文本 tokenize 后直接model.generate,最后skip_special_tokens=True解码输出。这也再次印证了本文第 2 节的提醒——虽然单任务场景下前缀无益,但生成式任务中仍可按需拼接summarize:之类的前缀文本。
需要量化以降低显存占用时,可以参考该英文文档的 Quantization 章节,它演示了使用 torchao 将权重量化为 int4 的做法(需先pip install torchao),更多量化后端见文档的 量化总览。
9. 小结与适用场景
ByT5 在 🤗 Transformers 中的完整支持链条是:ByT5Tokenizer(字节分词)→ T5v1.1 架构模型(T5ForConditionalGeneration/AutoModelForSeq2SeqLM)→ 复用 T5 的全部 API。选择 ByT5 时可以参考以下特征:
- 多语言零配置:任何语言都无需构建词表,直接字节输入;
- 对噪声鲁棒:拼写错误、大小写变化不会因词表未命中而丢失信息,拼写/发音敏感任务表现更好;
- 代价是序列更长:字节序列远长于子词序列,训练与推理成本更高,生成时需要更大的
max_length; - 微调注意:单任务微调不需要任务前缀,多任务微调才需要;
- 实现极简:无词表、无预分词,
save_vocabulary为空,部署时少一个词表文件。
仓库中可继续深入阅读的相关文件:ByT5Tokenizer 实现、分词器自动映射、字节分词测试、T5 英文文档。
【免费下载链接】transformers🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考