【发布时间】:2023-03-17 00:51:02
【问题描述】:
我正在尝试编写一个预测函数来预测大型文本数据(所以它必须是批量的)。但是预测功能有点慢。所以我想知道我能做些什么来改善它的时间。
到目前为止我所拥有的:
def get_embeddings(model, data_loader, device):
model.eval() # eval mode
with torch.no_grad():
embeddings = torch.tensor([], dtype=torch.float64, device=device) #initialize empty tensor
for _, d in enumerate(tqdm(data_loader), 0):
# model inputs
input_ids = d["input_ids"].to(device)
attention_mask = d["attention_mask"].to(device)
# model outputs
embeddings = torch.cat((embeddings, model.predict(
input_ids,
attention_mask=attention_mask
))) # concat predictions
return embeddings.cpu().numpy() # convert to numpy array
我认为从 GPU 转换到 CPU 需要时间,所以我决定先初始化一个空张量并连接所有预测。然后在最后将其转换回 numpy 数组。但我不确定张量连接是否真的会更慢。
所以我想知道在预测方面是否有更好或最佳实践。
【问题讨论】: