Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

`input_ids`、`attention_mask`、`token_type_ids` 分别告诉模型什么?

查看完整题解

参考回答

直接回答

input_ids 是词元编号。attention_mask 在常见分词器输出中用 1 标真实位置、0 标填充位置。token_type_ids 在 BERT 类的部分用法里标记不同段落或句子。

讲清原理

词元 ID 用于读嵌入,掩码能避免填充值参与不该参与的计算。实际模型还可能在内部合入因果屏蔽。段 ID 只有模型支持时才有意义,很多生成模型并不需要它。

同一段词元有哪几行输入?
同一段词元有哪几行输入?

例子与易错点

给 BERT 做句对任务时可以出现 A 段与 B 段的标记。句子短而需要补齐时,填充依然要单独用掩码表示。不要把填充和段号 0 混在一起理解。

from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import BertTokenizer, DataCollatorWithPadding

vocab = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", "tea", "water"]
with TemporaryDirectory() as tmp:
    vocab_file = Path(tmp) / "vocab.txt"
    vocab_file.write_text("\n".join(vocab), encoding="utf-8")
    tokenizer = BertTokenizer(str(vocab_file))
    features = [tokenizer("tea", "water"), tokenizer("tea")]
    batch = DataCollatorWithPadding(tokenizer)(features)
    assert batch["input_ids"].tolist() == [[2, 5, 3, 6, 3], [2, 5, 3, 0, 0]]
    assert batch["attention_mask"].tolist() == [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0]]
    assert batch["token_type_ids"][0].tolist() == [0, 0, 0, 1, 1]
    print(batch["attention_mask"].tolist())

相关题:第 14 题、第 17 题、第 29 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。