Python 3.x 如何初始化具有特定维度的空张量并通过循环附加到它,而不使CUDA内存不足?
我试图将for循环中生成的张量(t)附加到一个列表[t],该列表累积了所有这些张量。接下来,列表[T]需要转换为张量,并需要加载到GPU上Python 3.x 如何初始化具有特定维度的空张量并通过循环附加到它,而不使CUDA内存不足?,python-3.x,append,pytorch,tensor,Python 3.x,Append,Pytorch,Tensor,我试图将for循环中生成的张量(t)附加到一个列表[t],该列表累积了所有这些张量。接下来,列表[T]需要转换为张量,并需要加载到GPU上 b_output = [] for eachInputId, eachMask in zip(b_input_ids, b_input_mask): # unrolled into each individual document # print(eachInputId.siz
b_output = []
for eachInputId, eachMask in zip(b_input_ids, b_input_mask):
# unrolled into each individual document
# print(eachInputId.size()) # individual document here
outputs = model(eachInputId,
token_type_ids=None,
attention_mask=eachMask)
# combine the [CLS] output layer to form the document
doc_output = torch.mean(outputs[1], dim=0) # size = [1, ncol]
b_output.append( doc_output )
t_b_output = torch.tensor( b_output )
我尝试的另一种方法是初始化具有固定维数的张量{T},并从for循环中向其附加张量(T)
b_output = torch.zeros(batch_size, hidden_units)
b_output.to(device) # cuda device
for index, (eachInputId, eachMask) in enumerate(zip(b_input_ids, b_input_mask)):
# unrolled into each individual document
# print(eachInputId.size()) # individual document here
outputs = model(eachInputId,
token_type_ids=None,
attention_mask=eachMask)
# combine the [CLS] output layer to form the document
doc_output = torch.mean(outputs[1], dim=0) # size = [1, ncol]
b_output[index] = doc_output
执行以下任一操作都会产生此错误:
RuntimeError: CUDA out of memory. Tried to allocate 20.00 MiB (GPU 0; 11.17 GiB total capacity; 10.65 GiB already allocated; 2.81 MiB free; 10.86 GiB reserved in total by PyTorch)
我假设这是因为将张量(在GPU上)附加到列表(当然不在GPU上),然后尝试将列表转换为张量(不在GPU上)
如何将这些张量附加到另一个张量,然后将该张量加载到GPU进行进一步处理
如有任何提示或信息,我将不胜感激。尝试使用
torch.cat
而不是torch.tensor
。您当前正在尝试为新的张量分配内存,而所有其他张量仍在存储中,这可能是内存不足错误的原因。更改:
t_b_output = torch.tensor( b_output )
与:
希望获得此帮助您知道哪一行导致内存溢出吗?如果是
t_b_输出=torch.tensor(b_输出)
,将torch.tensor
链接到torch.stack
可能会解决问题。是的,是该行导致了问题。我尝试了两种方法,torch.tensor和torch.stack,但都不起作用。谢谢您的回答@N,但是,之前出现了错误。cat函数应用于b_输出列表。错误发生在b_output.append(doc_output)上,那么可能是GPU内存不够大,无法存储所有的张量。在将张量添加到列表之前,可以尝试将其从GPU移动到CPU:b\u output.append(doc\u output.to('CPU'))
。并在GPU上逐个重新加载以进行进一步处理。然而,它在计算上是昂贵的。
t_b_output = torch.cat( b_output )