【发布时间】:2022-02-09 23:28:00
【问题描述】:
我已经使用 GPU 微调了我的模型,但推理过程非常慢,我认为这是因为默认情况下推理使用 CPU。这是我的推理代码:
txt = "This was nice place"
model = transformers.BertForSequenceClassification.from_pretrained(model_path, num_labels=24)
tokenizer = transformers.BertTokenizer.from_pretrained('TurkuNLP/bert-base-finnish-cased-v1')
encoding = tokenizer.encode_plus(txt, add_special_tokens = True, truncation = True, padding = "max_length", return_attention_mask = True, return_tensors = "pt")
output = model(**encoding)
output = output.logits.softmax(dim=-1).detach().cpu().flatten().numpy().tolist()
这是我的第二个推理代码,它使用管道(针对不同的模型):
classifier = transformers.pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
result = classifier(txt)
如何强制转换器库在 GPU 上进行更快的推理?我尝试添加 model.to(torch.device("cuda")) 但这会引发错误:
Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu
我认为问题与未发送到 GPU 的数据有关。这里也有类似的问题:pytorch summary fails with huggingface model II: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu
如何在有和没有管道的情况下将数据发送到 GPU?非常感谢任何建议。
【问题讨论】:
-
你确定你试过
model.to(torch.device("cuda")),至少它应该返回一个错误,因为你的数据似乎不属于同一个设备。 -
代码有误,我已经编辑了我的问题。
标签: python pytorch huggingface-transformers inference