利用变换器中的BERT加速句子处理

2024-05-12 13:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

import torch
import tensorflow as tf
import numpy as np
from transformers import AutoTokenizer, AutoModel

model = 'bert-base-uncased' 
tokenizer = AutoTokenizer.from_pretrained(model)
model = AutoModel.from_pretrained(model)
Sentence_vectorList = []
for sent in x_train:

  input_sentence = torch.tensor(tokenizer.encode(sent)).unsqueeze(0)
  out = model(input_sentence)
  embeddings_of_last_layer = out[0]
  cls_embeddings = embeddings_of_last_layer[0]

  cls_layer = cls_embeddings.detach().numpy()

  sent_emd = np.average(cls_layer,axis=0)

任务是在[n x 768]中提取句子向量并分离它们,然后将它们保存为sent2vec。这个过程需要很多时间。有没有更有效的方法


Tags: fromimportnumpylayermodelasnptorch
1条回答
网友
1楼 · 发布于 2024-05-12 13:19:11

你可以通过分批处理句子来获得一些小的加速。批量大小为100可能是一个合理的选择。当分批处理句子时,模型需要知道分批中每个句子的长度。标记器的^{}负责处理这个问题。请注意,该方法返回一个字典,因此您需要将输出传递给模型,如下所示:

out = model(**input_sentences)

变量out将包含批处理中所有句子的向量

成批处理句子的速度在CPU上相对较小,但在GPU上相当大。变压器是相当大的型号,无论你做什么,它们的CPU速度都会很慢。若你们对较低质量的向量没问题,你们可以尝试更小的变换器,比如DistilBERT

相关问题 更多 >