Transformers:如何使用 CUDA 进行推理?

Mr.*_*eer 4 python inference pytorch huggingface-transformers

我已经使用 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()
Run Code Online (Sandbox Code Playgroud)

这是我的第二个推理代码,它使用管道(针对不同的模型):

classifier = transformers.pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
result = classifier(txt)
Run Code Online (Sandbox Code Playgroud)

如何强制 Transformer 库在 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
Run Code Online (Sandbox Code Playgroud)

我认为问题与未发送到 GPU 的数据有关。这里有一个类似的问题:pytorch summarise Failures with Huggingface model II: Expected all tensors to be on the same device, but found at at least two devices, cuda:0 和 cpu

使用和不使用管道时如何将数据发送到 GPU?任何建议都将受到高度赞赏。

Iva*_*van 7

在执行推理之前,您还应该将输入传输到 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)
Run Code Online (Sandbox Code Playgroud)

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