在一个示例代码中,我看到:
self.models["pose_encoder"] = \
networks.ResnetEncoder(18, self.opt.weights_init == "pretrained",
num_input_images=self.num_pose_frames)
self.models["pose_encoder"].to("cuda:4")
使用由定义的ResnetEncoder
class ResnetEncoder(nn.Module):
"""Pytorch module for a resnet encoder
"""
def __init__(self, num_layers, pretrained, num_input_images=1, **kwargs):
super(ResnetEncoder, self).__init__()
我对to(cuda:4)
部分发生在模块上时会发生什么感到困惑。模块中定义的整个张量是否移动到cuda:4?
现在导致我出错的原因是模块中有一个成员函数,在该函数中我定义了一个张量:
def A():
self.mytensor = []
# after some operation this is not empty any more
self.mytensor.cuda()
出现以下错误:
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:4 and cuda:0!
我知道cuda:0是由最后一行代码中的.cuda()操作引起的。但我不知道如何将“self.mytensor”移动到cuda:4。我将cam pass设备作为模块构造函数中的一个参数,但我想有更好的方法来实现这一点。我希望设备在运行时进行更改,所以我不想同时使用os.Enviro。有没有办法做到这一点
Followthe document,
to.device('name_device')
是torch.Tensor
的特殊函数,用于将张量移动到其他设备name_device
可以替换为:cuda:num_gpu
或cpu
,to.device('cuda:4')
将张量移动到GPU编号4(您可以通过cmd/terminal上的nvidia-smi
命令检查GPU编号)两个张量之间的任何操作都需要它们位于同一设备中。由于您的
self.mycuda
位于GPU 0上,因此会引发错误,您可以通过self.mycuda.to_device('cuda:4')
将其移动到GPU 4注意:使用
.cuda() = .to_device('cuda:0')
。您可以通过self.mycuda.cuda(4)
指定设备相关问题 更多 >
编程相关推荐