【发布时间】:2020-08-17 13:28:18
【问题描述】:
在通过 BERT 传递我的令牌之前,我想对其嵌入执行一些处理(嵌入查找层的结果)。 HuggingFace BERT TensorFlow implementation 允许我们使用以下方法访问嵌入查找的输出:
import tensorflow as tf
from transformers import BertConfig, BertTokenizer, TFBertModel
bert_tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
input_ids = tf.constant(bert_tokenizer.encode("Hello, my dog is cute", add_special_tokens=True))[None, :]
attention_mask = tf.stack([tf.ones(shape=(len(sent),)) for sent in input_ids])
token_type_ids = tf.stack([tf.ones(shape=(len(sent),)) for sent in input_ids])
config = BertConfig.from_pretrained('bert-base-uncased', output_hidden_states=True)
bert_model = TFBertModel.from_pretrained('bert-base-uncased', config=config)
result = bert_model(inputs={'input_ids': input_ids,
'attention_mask': attention_mask,
'token_type_ids': token_type_ids})
inputs_embeds = result[-1][0] # output of embedding lookup
随后,可以处理inputs_embeds,然后将其作为输入发送到同一模型,使用:
inputs_embeds = process(inputs_embeds) # some processing on inputs_embeds done here (dimensions kept the same)
result = bert_model(inputs={'inputs_embeds': inputs_embeds,
'attention_mask': attention_mask,
'token_type_ids': token_type_ids})
output = result[0]
output 现在包含修改后输入的 BERT 输出。但是,这需要两次完全通过 BERT。我不想一直运行 BERT 来执行嵌入查找,我只想获得嵌入查找层的输出。 这可能吗?如果可以,怎么做?
【问题讨论】:
标签: python tensorflow nlp huggingface-transformers bert-language-model