首页 > 解决方案 > 带有填充和掩码令牌预测的 Bert

问题描述

我正在使用 Bert 预训练模型(bert-large-uncased-whole-word-masking)我使用 Huggingface 来尝试它我首先使用了这段代码

m = TFBertLMHeadModel.from_pretrained("bert-large-cased-whole-word-masking")
logits = m(tokenizer("hello world [MASK] like it",return_tensors="tf")["input_ids"]).logits

然后我在应用 softmax 后使用 Argmax 来获得最大概率,到目前为止一切正常。

当我使用 max_length = 100 的填充时,模型开始做出错误预测并且无法正常工作,并且所有预测的标记都相同,即 119-Token ID

我用于 Argmax 的代码

tf.argmax(tf.keras.activations.softmax(m(tokenizer("hello world [MASK] like it",return_tensors="tf",max_length=,padding="max_length")["input_ids"]).logits)[0],axis=-1)

使用填充之前的输出

<tf.Tensor: shape=(7,), dtype=int64, numpy=array([ 9800, 19082,  1362,   146,  1176,  1122,   119])>

使用 max_length 为 100 的填充后的输出

<tf.Tensor: shape=(100,), dtype=int64, numpy=
array([119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
       119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
       119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
       119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
       119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
       119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
       119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
       119, 119, 119, 119, 119, 119, 119, 119, 119])>

我想知道这个问题是否会在训练新模型时普遍存在,因为必须为训练新模型设置输入形状我填充并标记了数据,但是现在我想知道这个问题是否还会继续存在。

标签: tensorflowkerasbert-language-modelhuggingface-transformerslanguage-model

解决方案


正如评论中已经提到的,您忘记将 attention_mask 传递给 BERT,因此它会将添加的填充标记视为普通标记。

您还在评论中询问了如何摆脱填充标记预测。根据您的实际任务,有几种方法可以做到这一点。其中之一是使用boolean_mask和 attention_mask 删除它们,如下所示:

import tensorflow as tf
from transformers import TFBertLMHeadModel, BertTokenizerFast

ckpt = "bert-large-cased-whole-word-masking"

t = BertTokenizerFast.from_pretrained(ckpt)
m = TFBertLMHeadModel.from_pretrained(ckpt)

e = t("hello world [MASK] like it",return_tensors="tf")
e_padded = t("hello world [MASK] like it",return_tensors="tf", padding="max_length", max_length = 100)

def prediction(encoding):
  logits = m(**encoding).logits
  token_mapping = tf.argmax(tf.keras.activations.softmax(logits),axis=-1)
  return tf.boolean_mask(token_mapping, encoding["attention_mask"])

token_predictions = prediction(e) 
token_predictions_padded = prediction(e_padded) 

print(token_predictions)
print(token_predictions_padded)

输出:

tf.Tensor([ 9800 19082  1362   146  1176  1122   119], shape=(7,), dtype=int64)
tf.Tensor([ 9800 19082  1362   146  1176  1122   119], shape=(7,), dtype=int64)

推荐阅读