BERT模型MLM训练策略解析:15%掩码token的处理机制与实现细节

1次阅读
没有评论

共计 1810 个字符,预计需要花费 5 分钟才能阅读完成。

image.webp

1. MLM 预训练任务简介

BERT(Bidirectional Encoder Representations from Transformers)的核心预训练任务之一是掩码语言模型(Masked Language Model, MLM)。其核心思想是:随机遮盖输入句子中的部分 token(通常为 15%),让模型基于上下文预测被遮盖的原始单词。这种自监督训练方式使模型能够学习深层的双向语言表征。

BERT 模型 MLM 训练策略解析:15% 掩码 token 的处理机制与实现细节

2. 15% 掩码 token 的三大处理策略

2.1 80% 概率替换为[MASK]

对于被选中的 15%token 中的 80%,会直接替换为特殊符号[MASK]。这是最典型的情境,模型需要根据上下文推断被遮盖的词。例如:

原始句子:"the cat sat on the mat"
处理后:"the [MASK] sat on the mat"

2.2 10% 概率保留原词

10% 的概率会保留原始单词不变。这种策略迫使模型不仅要学会预测缺失词,还需要理解当前词是否合理。例如:

原始句子:"the cat sat on the mat"
处理后:"the cat sat on the mat"(无变化)

2.3 10% 概率替换为随机词

剩余 10% 的概率会替换为词表中的随机单词。这种噪声注入机制增强了模型的纠错能力。例如:

原始句子:"the cat sat on the mat"
处理后:"the dog sat on the mat"("cat"→随机 "dog")

数学表达为:

$$
\text{替换策略} =
\begin{cases}
[MASK] & \text{概率} = 0.8 \
\text{原词} & \text{概率} = 0.1 \
\text{随机词} & \text{概率} = 0.1
\end{cases}
$$

3. PyTorch 实现代码

import torch
import random

def mask_tokens(inputs, tokenizer, mask_prob=0.15):
    """
    inputs: 输入 token_id 张量 [batch_size, seq_len]
    mask_prob: 掩码总概率(默认 15%)"""
    labels = inputs.clone()
    # 生成掩码位置矩阵(15% 概率)prob_matrix = torch.full(labels.shape, mask_prob)
    masked_indices = torch.bernoulli(prob_matrix).bool()

    with torch.no_grad():
        # 80% 概率替换为[MASK]
        mask_token = tokenizer.mask_token_id
        indices_replaced = torch.bernoulli(torch.full(labels.shape, 0.8)).bool() & masked_indices
        inputs[indices_replaced] = mask_token

        # 10% 概率替换为随机词
        indices_random = torch.bernoulli(torch.full(labels.shape, 0.5)).bool() & masked_indices & ~indices_replaced
        random_words = torch.randint(len(tokenizer), labels.shape, dtype=torch.long)
        inputs[indices_random] = random_words[indices_random]

        # 剩余 10% 保持原词(labels 仍记录原始 id)return inputs, labels

4. 避坑指南

4.1 为什么不能 100% 使用[MASK]

  • 微调阶段不会出现 [MASK] 符号,导致预训练 - 微调不一致
  • 保留部分原词使模型学习语言理解而不仅是预测
  • 随机词增强模型对错误输入的鲁棒性

4.2 随机词替换的影响

  • 少量噪声(10%)可提升模型泛化能力
  • 过高比例会导致模型收敛困难(建议保持≤15%)
  • 对拼写错误多的文本(如社交媒体)可适当提高比例

4.3 超参数调整建议

  • 领域适应:医学文本可降低随机词比例(如 5%)
  • 小规模数据:减少总掩码比例(如 10%)
  • 多语言场景:需平衡不同语言的词频差异

5. 延伸思考

  1. 领域适应调整:处理法律文本时,是否需要调整 80-10-10 比例?专业术语的预测是否应该减少随机替换?
  2. RoBERTa 改进
  3. 取消 Next Sentence Prediction 任务
  4. 动态调整掩码比例(如从 10% 逐步增加到 15%)
  5. 更大 batch size 和更多训练数据
正文完
 0
评论(没有评论)