RuntimeError: 预期所有张量位于同一设备上?

huangapple go评论231阅读模式
英文:

RuntimeError: Expected all tensors to be on the same device?

问题

我在这里得到了运行时错误:

RuntimeError: 预期所有张量都在相同的设备上,但至少找到两个设备,cuda:0 和 cpu!(在检查方法 wrapper_CUDA_addmm 中的参数 mat1 时)

然而,我在这里创建的所有张量都在cuda上。有谁知道问题是什么吗?

import torch.nn as nn
import torch

class MyModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.lin = nn.Linear(5, 1)
        self.trans = nn.Transformer(nhead=1, num_encoder_layers=1, d_model=5)

    def forward(self, x):
        tgt = torch.rand(4, 5).to(device)
        y = self.trans(x, tgt)
        out = self.lin(y)
        return out

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
model = MyModel()
model.to(device)
model.eval()

src = torch.rand(4, 5)
out = model(src)

print(out)

另外,是否有一些PyTorch命令可以用来列出设备上的所有张量?

英文:

I am getting this runtime error here:

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_CUDA_addmm)

However, all the tensors I've created here are on cuda. Does anyone know what the problem is?

import torch.nn as nn
import torch

class MyModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.lin = nn.Linear(5,1)
        self.trans = nn.Transformer(nhead=1, num_encoder_layers=1, d_model=5)

    def forward(self, x):
        tgt = torch.rand(4, 5).to(device)
        y = self.trans(x, tgt)
        out = self.lin(y)
        return out

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
model = MyModel()
model.to(device)
model.eval()

src = torch.rand(4,5)
out = model(src)

print(out)

Also, is there some pytorch command I can use to list all tensors on a device?

答案1

得分: 1

src 在 CPU 上。

# src = torch.rand(4,5)
src = torch.rand(4,5).to(device)
英文:

src is on cpu.

# src = torch.rand(4,5)
src = torch.rand(4,5).to(device)

huangapple
  • 本文由 发表于 2023年5月29日 11:09:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定