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)

### BERT模型中的掩码语言模型(MLM)任务 #### 定义与工作原理自然语言处理(NLP)领域,BERT(Bidirectional Encoder Representations from Transformers)采用了一种独特的预训练方法——掩码语言模型(Masked Language Model, MLM)[^1]。该方法旨在通过随机掩盖输入序列的部分单词,并让模型依据上下文预测这些被隐藏的词。 具体来说,在BERTMLM任务中,大约15%的token会被随机选择出来进行操作。对于每一个选中的位置: - 大约80%的时间会用特殊的[MASK]标记替代原始词汇; - 10%的情况下保持原样不变; - 剩下的10%,则由其他随机选取的词汇代替[^3]。 这种设计使得模型不仅能够理解给定词语的意义,还能更好地捕捉句子内部复杂的依赖关系。 #### 技术实现细节 为了完成上述过程,当构建用于训练的数据集时,程序会对每条记录执行如下步骤: 1. 遍历整个语料库,按照一定概率挑选出待mask的位置集合; 2. 对于选定要mask的地方,根据前述比例决定具体的处理方式(变为MASK/保留原有字符/替换成别的字); 3. 将修改后的文本送入网络架构中做前向传播运算; 4. 计算损失函数值,通常是以交叉熵衡量实际标签同预测分布之间的差异程度; 5. 利用反向传播算法调整参数权重直至收敛为止。 以下是简化版Python伪代码展示这一流程的关键部分: ```python import random def apply_masking(tokens, mask_prob=0.15): masked_tokens = tokens.copy() for i in range(len(masked_tokens)): prob = random.random() if prob < mask_prob: rand_num = random.uniform(0, 1) if rand_num < 0.8: # Replace with [MASK] token 80% masked_tokens[i] = '[MASK]' elif rand_num < 0.9: # Keep original word 10% pass else: # Randomly replace the word 10% masked_tokens[i] = get_random_word() return masked_tokens # Example usage of masking function during data preparation phase. text_example = ["This", "is", "an", "example"] masked_text = apply_masking(text_example) print(f'Original Text:{text_example}') print(f'Masked Text :{masked_text}') ``` #### 应用实例与发展前景 得益于MLM机制的有效性,BERT及其变体已经在多个下游任务上取得了优异的成绩,比如情感分析、问答系统等。尽管如此,也存在一些局限性和挑战有待克服,例如计算成本较高、可能存在过拟合等问题[^2]。 未来的研究方向可能集中在优化现有框架效率的同时探索新的改进策略,以期进一步提升模型的表现力和实用性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值