Bert的MLM任务loss原理

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

         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:加权平均得出一个实数</

<think>好的,我现在需要帮助用户查找关于BERT预训练中MLM任务的代码实现。首先,我得回顾一下BERT的基本结构,MLM任务原理BERT使用Transformer编码器,MLM通过随机遮盖输入中的部分token,让模型预测这些被遮盖的token。用户可能需要具体的代码示例,所以需要找到相关的实现步骤。 接下来,我应该考虑用户可能的背景。他们可能对BERT有一定了解,但需要具体的代码指导。可能需要包括数据预处理、模型结构、遮盖策略和训练循环等部分。用户提供的引用中提到了预训练的数据来源和步骤,但代码部分没有直接给出,所以需要根据这些信息来构造示例。 我需要确保代码正确,使用PyTorch或TensorFlow框架?用户没有指定,但通常BERT的实现较多使用PyTorch,比如HuggingFace的Transformers库。但用户可能想要从头实现的代码,还是使用现有库?假设用户需要基础的实现,可能使用PyTorch,并简要说明关键部分。 然后,考虑数据预处理部分,引用中提到使用文档级语料库,比如BooksCorpus和Wikipedia。代码中需要展示如何对文本进行分词、添加特殊标记([CLS]、[SEP])、生成注意力掩码等。遮盖策略方面,通常随机选择15%的token,其中80%替换为[MASK],10%随机替换,10%保持不变。 模型结构方面,需要构建Transformer编码器层,包括多头自注意力和前馈网络。损失函数使用交叉熵,只计算被遮盖位置的损失。 可能还需要考虑如何生成训练样本,比如使用DataLoader,以及训练循环中的优化器设置。不过代码示例不宜过于复杂,应突出重点部分,如遮盖机制和模型预测部分。 同时,需要提醒用户实际应用中可能需要分布式训练、大规模数据预处理等,建议参考HuggingFace的库。可能用户的需求是实际项目中的预训练,所以给出示例后,推荐现有库可以节省时间。 最后,检查代码是否符合LaTeX格式要求,数学公式是否正确使用$...$,独立公式用$$...$$。确保回答结构清晰,分步骤说明,并生成相关问题。</think>BERTMLM任务实现可分为数据预处理、遮蔽策略、模型结构三个核心部分。以下是基于PyTorch的关键代码实现: ### 1. 数据预处理 ```python from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') text = "The quick brown fox jumps over the lazy dog." # 编码时自动添加[CLS]和[SEP] encoded = tokenizer.encode_plus( text, max_length=128, padding='max_length', truncation=True, return_tensors='pt' ) ``` ### 2. 遮蔽策略实现 ```python import torch import random def mask_inputs(input_ids, tokenizer, mask_prob=0.15): labels = input_ids.clone() # 创建随机遮蔽矩阵(15%概率) prob_matrix = torch.full(labels.shape, mask_prob) masked_indices = torch.bernoulli(prob_matrix).bool() # 保留特殊token([CLS],[SEP])不被遮蔽 special_tokens_mask = torch.tensor( [tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()], dtype=torch.bool ) masked_indices = masked_indices & ~special_tokens_mask # 80%替换为[MASK], 10%随机替换, 10%保持不变 replace_mask = torch.bernoulli(torch.full(labels.shape, 0.8)).bool() & masked_indices input_ids[replace_mask] = tokenizer.mask_token_id random_mask = torch.bernoulli(torch.full(labels.shape, 0.5)).bool() & masked_indices & ~replace_mask random_words = torch.randint(len(tokenizer), labels.shape, dtype=torch.long) input_ids[random_mask] = random_words[random_mask] return input_ids, labels masked_input, labels = mask_inputs(encoded['input_ids'], tokenizer) ``` ### 3. 模型结构关键组件 ```python import torch.nn as nn class BertMLM(nn.Module): def __init__(self, vocab_size, hidden_size=768, num_layers=12): super().__init__() self.embedding = nn.Embedding(vocab_size, hidden_size) encoder_layer = nn.TransformerEncoderLayer(hidden_size, num_heads=12) self.encoder = nn.TransformerEncoder(encoder_layer, num_layers) self.lm_head = nn.Linear(hidden_size, vocab_size) def forward(self, input_ids): x = self.embedding(input_ids) encoded = self.encoder(x) logits = self.lm_head(encoded) return logits model = BertMLM(len(tokenizer.vocab)) loss_fn = nn.CrossEntropyLoss(ignore_index=-100) # 训练步骤 optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4) logits = model(masked_input) loss = loss_fn(logits.view(-1, len(tokenizer.vocab)), labels.view(-1)) loss.backward() optimizer.step() ``` 关键数学原理: - 遮蔽概率计算:$P(mask) = 0.15$,其中$80\% \rightarrow [MASK]$,$10\% \rightarrow random$,$10\% \rightarrow original$ - 损失函数:交叉熵损失$L = -\sum_{i \in masked} y_i \log(p_i)$,仅计算遮蔽位置的损失[^3] 实际工业级实现建议: 1. 使用HuggingFace Transformers库的`BertForMaskedLM` 2. 采用动态遮蔽策略(每次epoch重新生成遮蔽模式) 3. 结合NSP(下一句预测)任务进行联合训练 4. 使用FP16混合精度训练加速 ```python # 使用HuggingFace实现 from transformers import BertForMaskedLM, DataCollatorForLanguageModeling model = BertForMaskedLM.from_pretrained('bert-base-uncased') data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=True, mlm_probability=0.15 ) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值