当前位置 博文首页 > 将pytorch的网络等转移到cuda

    将pytorch的网络等转移到cuda

    作者:aleien1 时间:2021-08-12 17:43

    神经网络一般用GPU来跑,我们的神经网络框架一般也都安装的GPU版本,本文就简单记录一下GPU使用的编写。

    GPU的设置不在model,而是在Train的初始化上。

    第一步是查看是否可以使用GPU

    self.GPU_IN_USE = torch.cuda.is_available()

    就是返回这个可不可以用GPU的函数,当你的pytorch是cpu版本的时候,他就会返回False。

    然后是:

    self.device = torch.device('cuda' if self.GPU_IN_USE else 'cpu')

    torch.device是代表将torch.tensor分配到哪个设备的函数

    接着是,我看到了一篇文章,原来就是将网络啊、数据啊、随机种子啊、损失函数啊、等等等等直接转移到CUDA上就好了!

    于是下面就好理解多了:

    转移模型:

    self.model = Net(num_channels=1, upscale_factor=self.upscale_factor, base_channel=64, num_residuals=4).to(self.device)
    
    

    设置cuda的随机种子:

    torch.cuda.manual_seed(self.seed)

    转移损失函数:

    self.criterion.cuda()

    转移数据:

    data, target = data.to(self.device), target.to(self.device)

    pytorch 网络定义参数的后面无法加.cuda()

    pytorch定义网络__init__()的时候,参数不能加“cuda()", 不然参数不包含在state_dict()中,比如下面这种写法是错误的

    self.W1 = nn.Parameter(torch.FloatTensor(3,3), requires_grad=True).cuda()

    应该去掉".cuda()"

    self.W1 = nn.Parameter(torch.FloatTensor(3,3), requires_grad=True)

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持站长博客。

    jsjbwy
    下一篇:没有了