Bert的MLM任务loss原理

BERT的预训练任务包括MLM和NSP,本文主要关注MLM。该任务中,15%的词汇被mask,通过transformer等层编码,然后预测mask位置的词,相当于在词汇表大小的类别上做多分类。logits与one-hot编码的label计算交叉熵,加权平均后得到loss。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

         bert预训练有MLM和NSP两个任务,其中MLM是类似于“完形填空”的方式,对一个句子里的15%的词进行mask,通过双向transformer+feedforward+rediual_add+layer_norm完成对每个词的embedding编码,然后对mask的这个词进行预测,预测过程相当于做多分类,类别的个数是词汇的总个数,将mask的词的emb经过MLP变换生成在每个类别词汇上的logits 概率,label是mask位置上真实词在整个词汇上的one-hot编码,将logits和label计算交叉熵,又做了加权平均,即可得出MLM的loss,过程如下:

         源码中的get_masked_lm_output()方法过程解析:

1、输入input_tensor:[batch,maskednums, embed_size]

2、经过线性变换+layernorm:[batch,maskednums, 768]

3、logits:将embedding table[3万,768]作为变换矩阵,计算logits:[batch,maskednums, 3万],相当于得出每个被盖住词在3万个词上的概率,其实就是3万个类别多分类

4、labels:one-hot编码[maskednums,3万]

5、计算交叉熵:[bactch, maskednums]

6、loss:加权平均得出一个实数

def get_masked_lm_output(bert_config, input_tensor, output_weights, positions,
                         label_ids, label_weights):
  """Get loss and log probs for the masked LM."""
  input_tensor = gather_indexes(input_tensor, positions)

  with tf.variable_scope("cls/predictions"):
    # We apply one more non-linear transformation before the output layer.
    # This matrix is not used after pre-training.
    with tf.variable_scope("transform"):
      input_tensor = tf.layers.dense(
          input_tensor,
          units=bert_config.hidden_size,
          activation=modeling.get_activation(bert_config.hidden_act),
          kernel_initializer=modeling.create_initializer(
              bert_config.initializer_range))
      input_tensor = modeling.layer_norm(input_tensor)

    # The output weights are the same as the input embeddings, but there is
    # an output-only bias for each token.
    output_bias = tf.get_variable(
        "output_bias",
        shape=[bert_config.vocab_size],
        initializer=tf.zeros_initializer())
    logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
    logits = tf.nn.bias_add(logits, output_bias)
    log_probs = tf.nn.log_softmax(logits, axis=-1)

    label_ids = tf.reshape(label_ids, [-1])
    label_weights = tf.reshape(label_weights, [-1])

    one_hot_labels = tf.one_hot(
        label_ids, depth=bert_config.vocab_size, dtype=tf.float32)

    # The `positions` tensor might be zero-padded (if the sequence is too
    # short to have the maximum number of predictions). The `label_weights`
    # tensor has a value of 1.0 for every real prediction and 0.0 for the
    # padding predictions.
    per_example_loss = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1])
    numerator = tf.reduce_sum(label_weights * per_example_loss)
    denominator = tf.reduce_sum(label_weights) + 1e-5
    loss = numerator / denominator

  return (loss, per_example_loss, log_probs)

### Masked Language Model (MLM) 损失函数解析及其在NLP中的应用 #### MLM损失函数定义 Masked Language Model是一种预训练方法,在此模型中,输入序列的一部分被随机遮蔽(mask),目标是预测这些被遮蔽位置上的原始标记。对于每一个被遮蔽的位置,模型会计算其对应于整个词汇表的概率分布,并通过交叉熵损失来衡量预测值与真实标签之间的差异[^2]。 #### 计算过程 具体来说,给定一个句子`S="The cat sat on the mat"`,假设我们决定遮蔽单词“cat”,那么输入到模型的是`"The [MASK] sat on the mat"`。此时,模型的任务就是基于上下文环境去猜测[MASK]处最有可能是什么词。为了实现这一点,通常采用softmax层作为最后一层输出单元,它能够为每个可能的词语分配概率得分;之后利用负对数似然度(negative log likelihood, NLL),即交叉熵误差评估预测结果的好坏程度: \[ \text{Loss} = -\sum_{i=1}^{n}\log p(y_i|x_i,\theta)\] 其中\(y_i\)表示真实的token ID,而\(p(y_i|x_i,\theta)\)则代表由当前参数集θ下的条件概率估计得出的目标token i的发生几率[^3]。 #### 实际应用场景 这种机制使得MLMs特别擅长捕捉双向依赖关系——不仅考虑左侧也关注右侧的信息流,从而更好地理解自然语言结构并提高下游任务表现效果。例如,在问答系统里,当问句中有某些关键词缺失时,经过良好调优后的BERT等架构可以凭借其余部分提供的线索较为精准地补全所需信息[^1]。 ```python import torch.nn as nn class MLMLoss(nn.Module): def __init__(self, vocab_size): super().__init__() self.loss_fn = nn.CrossEntropyLoss() def forward(self, logits, labels): """ :param logits: Tensor of shape (batch_size, seq_len, vocab_size), output from model. :param labels: Ground truth tensor with masked token indices. """ active_loss = labels.view(-1) != -100 # Ignore index set to -100 during masking active_logits = logits.view(-1, logits.size(-1))[active_loss] active_labels = labels.view(-1)[active_loss] return self.loss_fn(active_logits, active_labels) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值