十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Transformers 中的 ByT5:无分词器的字节级序列到序列模型实战指南

Transformers 中的 ByT5:无分词器的字节级序列到序列模型实战指南 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 以T5ForConditionalGenerationByT5Tokenizer的组合提供完整支持你可以完全跳过 tokenizer 手动把文本编码为字节 ID也可以借助ByT5Tokenizer轻松完成批处理与训练。阅读完本文你将掌握 ByT5 的字节编码原理、三种典型调用方式无分词器单样本、分词器批处理、手工 span masking以及它在源码中的实现细节与测试验证。1. ByT5 是什么论文与模型定位ByT5 出自论文 ByT5: Towards a token-free future with pre-trained byte-to-byte modelsLinting 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、2padpad、eos/s、unkunk见 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 idscreate_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, labelslabels).loss loss.item() 2.66要点list(....encode(utf-8))把字符串拆成一个个字节整数0255再加 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.], paddinglongest, return_tensorspt ... ) labels_dict tokenizer( ... [La vie est comme une boîte de chocolat., Aujourdhui cest lundi.], paddinglongest, return_tensorspt ... ) labels labels_dict.input_ids loss model(**model_inputs, labelslabels).loss loss.item() 17.9几个实操要点paddinglongest会将 batch 内序列对齐到最长长度pad token 的 ID 为 0ByT5Tokenizer的model_input_names [input_ids, attention_mask]因此会输出这两个键测试 test_tokenization_byt5.py 中的test_prepare_batch_integration验证了 batch 编码的形状与数值两条输入得到(2, 37)的input_ids与attention_masktest_max_length_integration验证了max_lengthpaddingmax_lengthtruncation的组合行为。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**82 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_length100。 output_ids model.generate(input_ids, max_length100)[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)仅接受单字符 tokenord(token) 3非单字符返回 None_convert_id_to_token(index)chr(index - 3)convert_tokens_to_string(tokens)把各 token 按字节拼接后以 UTF-8 解码非法字节以errorsignore忽略见 L215-L227vocab_size恒为 2562**8save_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如 255decode 出来是空字符串因为单字节未必构成合法 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 给出了标准生成示例用AutoModelForSeq2SeqLMAutoTokenizer加载google/byt5-small将summarize: ...前缀文本 tokenize 后直接model.generate最后skip_special_tokensTrue解码输出。这也再次印证了本文第 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),仅供参考
返回列表