RuntimeError: expected device cuda:4 but got device cpu

報錯情況

在計算兩個tensor的loss時,使用瞭如下代碼:

u = eps * (torch.log(mu+1e-8) - torch.logsumexp(self.M(C, u, v), dim=-1)) + u

報錯:RuntimeError: expected device cuda:4 but got device cpu

 

 

錯誤原因

這裏,M是一個函數。C的類型爲:

tensor([[44514.2383 ... 44565.1055]], device='cuda:4',
       grad_fn=<SumBackward1>)

u的類型爲:

(Pdb) u
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

u和C一個在cpu上,一個在gpu上,從而報錯RuntimeError: expected device cuda:4 but got device cpu

 

解決方法

定義u的時候加上u.cuda(gpu_ids[0])

即u.cuda(4)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章