【发布时间】:2022-01-27 05:08:24
【问题描述】:
我有一个句子列表,我正在尝试计算困惑度,使用了几个使用此代码的模型:
from transformers import AutoModelForMaskedLM, AutoTokenizer
import torch
import numpy as np
model_name = 'cointegrated/rubert-tiny'
model = AutoModelForMaskedLM.from_pretrained(model_name).cuda()
tokenizer = AutoTokenizer.from_pretrained(model_name)
def score(model, tokenizer, sentence):
tensor_input = tokenizer.encode(sentence, return_tensors='pt')
repeat_input = tensor_input.repeat(tensor_input.size(-1)-2, 1)
mask = torch.ones(tensor_input.size(-1) - 1).diag(1)[:-2]
masked_input = repeat_input.masked_fill(mask == 1, tokenizer.mask_token_id)
labels = repeat_input.masked_fill( masked_input != tokenizer.mask_token_id, -100)
with torch.inference_mode():
loss = model(masked_input.cuda(), labels=labels.cuda()).loss
return np.exp(loss.item())
print(score(sentence='London is the capital of Great Britain.', model=model, tokenizer=tokenizer))
# 4.541251105675365
大多数模型运行良好,但有些句子似乎会抛出错误:
RuntimeError: CUDA out of memory. Tried to allocate 10.34 GiB (GPU 0; 23.69 GiB total capacity; 10.97 GiB already allocated; 6.94 GiB free; 14.69 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation. See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF
这是有道理的,因为有些很长。所以我所做的就是添加类似try, except RuntimeError, pass 的内容。
这似乎工作到大约 210 句,然后它只是输出错误:
CUDA error: an illegal memory access was encountered CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1.
我发现this 有很多讨论和想法,有些是关于潜在的故障 GPU?但我知道我的 GPU 可以正常工作,因为这个确切的代码适用于其他模型。还有关于批处理大小here 的讨论,这就是为什么我认为它可能与释放内存有关。
我尝试在每个 epoch 之后运行 torch.cuda.empty_cache() 以像 here 那样释放内存,但它不起作用(引发相同的错误)。
更新:
我过滤了长度超过 550 的句子,这似乎消除了 CUDA error: an illegal memory access was encountered CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1. 错误。
【问题讨论】:
-
你如何测试不同的模型?您是每个模型执行一个程序,还是简单地在一个程序中循环它们?
-
@LucaClissa 老实说,我尝试了这两种方法。我有大约 11 个模型要测试,其中 3 个抛出了这个错误。对于剩下的 8 个,我只是循环执行,他们做得很好。
-
我明白了,我会尝试在下面的答案中总结我对类似问题的经验
标签: python memory pytorch huggingface-transformers