RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu on transormer

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu on transormer


def nopeak_mask(size, opt):
    np_mask = np.triu(np.ones((1, size, size)),k=1).astype('uint8')
    np_mask =Variable(torch.from_numpy(np_mask) == 0)
    if opt.device == 0:
      np_mask = np_mask.cuda()
    return np_mask

def create_masks(src, trg, opt):

    src_mask = (src != opt.src_pad).unsqueeze(-2)

    if trg is not None:
        trg_mask = (trg != opt.trg_pad).unsqueeze(-2)
        size = trg.size(1) # get seq_len for matrix
        np_mask = nopeak_mask(size, opt)
        #if trg.is_cuda:
        #    np_mask.cuda()
        print(np_mask)
        print(trg_mask)
        trg_mask = trg_mask & np_mask

    else:
        trg_mask = None
    return src_mask, trg_mask

这段代码有问题 在这一行 trg_mask = trg_mask & np_mask 我检查两个张量我确定在不同的设备 source code can be found here.

听起来 trg_mask 和 np_mask 是存储在两个不同设备上的张量(cpu 和 cuda:0)。如果您想对它们执行操作,它们将需要都在 cpu 上,或者它们都需要在 cuda:0.

根据给出的信息,我不确定哪个变量在哪个设备上,但是如果您想将变量从 cuda:0 移动到 cpu,您可以这样做。

var = var.detach().cpu().numpy()

我解决了这个问题 在调用 create_masks 函数之前,我将 src、trg 移动到 cuda 在培训文件第 30 行中,我更改:

 src = batch.src.transpose(0,1).cuda()
        trg = batch.trg.transpose(0,1).cuda()
        trg_input = trg[:, :-1]
        src_mask, trg_mask = create_masks(src, trg_input, opt)

因为一行,我遇到了类似的问题:

device = torch.device("cuda" if args.cuda else "cpu")

这可以通过以下任一方式解决:

device = torch.device("cpu")

device = torch.device("cuda")