网络编程
位置:首页>> 网络编程>> 网络编程>> 将pytorch的网络等转移到cuda

将pytorch的网络等转移到cuda

作者:aleien1  发布时间:2023-08-10 08:33:46 

标签:pytorch,网络,cuda

神经网络一般用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)

来源:https://blog.csdn.net/weixin_42128941/article/details/103048866

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com