我遇到了经典的问题:CUDA 内存不足。
我想要做什么:我想每次使用不同的嵌入矩阵加载相同的模型。我必须执行 300 次,每个词嵌入维度一次。
我没有训练模型,这就是我使用 model.eval()
的原因,我认为这足以阻止 Pytorch 创建图形。
请注意,我从未将模型或数据传递给 cuda。事实上,我想在发送由 GPU 执行的代码之前使用 cpu 调试代码。
下面的循环执行一次,在第二次迭代中引发RuntimeError
。
我的猜测是,代码在每次迭代时都会将新模型加载到 GPU 内存中(如果没有明确指出这样做,我不知道这是可能的)。 emb_matrix
相当重,可能会导致 GPU 内存崩溃。
emb_dim = 300
acc_dim = torch.zeros((emb_dim, 4))
for d in range(emb_dim):
#create embeddings with one dimension shuffled
emb_matrix = text_f.vocab.vectors.clone()
#get a random permutation across one of the dimensions
rand_index = torch.randperm(text_f.vocab.vectors.shape[0])
emb_matrix[:, d] = text_f.vocab.vectors[rand_index, d]
#load model with the scrumbled embeddings
model = load_classifier(emb_matrix,
encoder_type = encoder_type)
model.eval()
for batch in batch_iters["test"]:
x_pre = batch.premise
x_hyp = batch.hypothesis
y = batch.label
#perform forward pass
y_pred = model.forward(x_pre, x_hyp)
#calculate accuracies
acc_dim[d] += accuracy(y_pred, y)/test_batches
#avoid memory issues
y_pred.detach()
print(f"Dimension {d} accuracies: {acc_dim[d]}")
我收到以下错误:
运行时错误:CUDA 内存不足。尝试分配 146.88 MiB(GPU 0;2.00 GiB 总容量;已分配 374.63 MiB;0 字节空闲;1015.00 KiB 缓存)
我尝试将模型和数据传递给 CPU,但我得到了完全相同的错误。
我四处寻找如何解决这个问题,但找不到明显的解决方案。欢迎就如何将模型和数据加载到正确的位置,或者如何在每次迭代后清理 GPU 内存提出任何建议。
最佳答案
看起来acc_dim
累积了毕业历史记录 - 请参阅 https://pytorch.org/docs/stable/notes/faq.html
因为您只进行推理,所以应该使用 with torch.no_grad():
。
这将完全避免累积毕业历史记录可能出现的问题。
model.eval()
不会阻止梯度簿记的发生,它只是切换某些层的行为,例如 dropout。 model.eval()
和 with torch.no_grad():
一起用于推理。
关于python - RuntimeError : CUDA out of memory. 在循环中重新加载模型时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55800592/