報錯情況
在計算兩個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)