在Pytork中,当我将模块移动到cuda设备时会发生什么

2024-10-08 20:18:06 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个示例代码中,我看到:

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。有没有办法做到这一点


Tags: 模块to代码selfencoderinput定义init
1条回答
网友
1楼 · 发布于 2024-10-08 20:18:06

Followthe documentto.device('name_device')torch.Tensor的特殊函数,用于将张量移动到其他设备

name_device可以替换为:cuda:num_gpucputo.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)指定设备

相关问题 更多 >

    热门问题