【问题标题】:Transformers: How to use CUDA for inferencing?变形金刚:如何使用 CUDA 进行推理?
【发布时间】: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


【解决方案1】:

在执行推理之前您也应该将输入传输到 CUDA:

device = torch.device('cuda')

# transfer model
model.to(device)

# define input and transfer to device
encoding = tokenizer.encode_plus(txt, 
     add_special_tokens=True, 
     truncation=True, 
     padding="max_length", 
     return_attention_mask=True, 
     return_tensors="pt")

encoding = encoding.to(device)

# inference
output = model(**encoding)

注意nn.Module.to 是就地的,而torch.Tensor.to 不是(它会复制!)。

【讨论】:

  • 哦,谢谢!我可以做类似result = classifier(txt).to(device) 的事情来对管道做同样的事情吗?
  • 既然classifier 是一个模型,那么classifier.to(device) 应该可以工作。
猜你喜欢
  • 2021-11-02
  • 1970-01-01
  • 2020-09-30
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
  • 2020-08-29
  • 2015-10-09
相关资源
最近更新 更多