pytorch使用GPU or CPU

零、常用命令

 

1、查看gpu是否可用

torch.cuda.is_available()

2、查看gpu數量

torch.cuda.device_count()

3、查看當前gpu號

torch.cuda.current_device()

4、查看設備名

一、使用GPU

方法1:

device=torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model=model.to(device)
x=x.to(device)
y=y.to(device)

方法2:

y=x.to(0)  #當多塊GPU時可指定數字爲0,1,2,。。。

方法3:

model=model.cuda()
x=x.cuda()
y=y.cuda()

二、CPU—>GPU  GPU—>CPU

(1) CPU—>GPU

把tensor複製到顯存,使用.cuda()可以將CPU上的Tensor轉換(複製)到GPU上。如果有多塊GPU,我們用.cuda(i)來表示第 i 塊GPU及相應的顯存(i從0開始)且cuda(0)cuda()等價。 

y=x.cuda()

或者使用:

z=x.to(0)  #多塊gpu時刻指定0,1,2,3...

或者使用:

device=torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
m=x.to(device)

例如:

x=torch.Tensor(1,2)

>>> x
tensor([[0., 0.]])

y=x.cuda()
>>> y
tensor([[0., 0.]], device='cuda:0')

device=torch.device("cuda:0" if torch.cuda.is_available() else "cpu")   #只有一塊gpu時使用“cuda:1”雖然此句不會報錯,但執行下句會報錯“RuntimeError: CUDA error: invalid device ordinal”
m=x.to(device)
>>>m
tensor([[0., 0.]], device='cuda:0')

(2)GPU—>CPU

使用

n=m.to('cpu')

或者:

n=m.cpu()

(3)注意事項

需要注意的是,存儲在不同位置中的數據是不可以直接進行計算的。即存放在CPU上的數據不可以直接與存放在GPU上的數據進行運算,位於不同GPU上的數據也是不能直接進行計算的。

z = y + x.cpu()

會報錯:

    z=y+x.cpu()
RuntimeError: expected device cuda:0 and dtype Long but got device cpu and dtype Long
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章