新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
在pytorch中為Module和Tensor指定GPU的例子-創(chuàng)新互聯(lián)
pytorch指定GPU
在用pytorch寫CNN的時候,發(fā)現(xiàn)一運(yùn)行程序就卡住,然后cpu占用率100%,nvidia-smi 查看顯卡發(fā)現(xiàn)并沒有使用GPU。所以考慮將模型和輸入數(shù)據(jù)及標(biāo)簽指定到gpu上。
pytorch中的Tensor和Module可以指定gpu運(yùn)行,并且可以指定在哪一塊gpu上運(yùn)行,方法非常簡單,就是直接調(diào)用Tensor類和Module類中的 .cuda() 方法。
import torch from PIL import Image import torch.nn as nn import numpy as np from torch.autograd import Variable # 先看看有沒有顯卡 torch.cuda.is_available() Out[16]: True # 嗯,有顯卡,可以指定,先生成一個Tensor a = torch.Tensor(3,5) a Out[13]: .00000e-05 * 0.0000 0.0000 2.0419 0.0000 2.0420 0.0000 0.0000 0.0000 0.0000 0.0000 0.0132 0.0000 0.0131 0.0000 0.0000 [torch.FloatTensor of size 3x5] a.cuda() Out[14]: .00000e-05 * 0.0000 0.0000 2.0419 0.0000 2.0420 0.0000 0.0000 0.0000 0.0000 0.0000 0.0132 0.0000 0.0131 0.0000 0.0000 [torch.cuda.FloatTensor of size 3x5 (GPU 0)] # 可以看到上面顯示了(GPU 0),也就是說這個Tensor是在第一個GPU上的 a.cuda(1) Traceback (most recent call last): File "", line 1, in a.cuda(1) File "/home/chia/anaconda2/lib/python2.7/site-packages/torch/_utils.py", line 57, in _cuda with torch.cuda.device(device): File "/home/chia/anaconda2/lib/python2.7/site-packages/torch/cuda/__init__.py", line 127, in __enter__ torch._C._cuda_setDevice(self.idx) RuntimeError: cuda runtime error (10) : invalid device ordinal at torch/csrc/cuda/Module.cpp:84 # 這個報錯了,因?yàn)橹挥幸粔KGPU,所以指定cuda(1)無效。
文章題目:在pytorch中為Module和Tensor指定GPU的例子-創(chuàng)新互聯(lián)
轉(zhuǎn)載源于:http://www.dlmjj.cn/article/codioh.html