首页 > 解决方案 > “torch._C._nn.nll_loss”函数的CPU版本

问题描述

torch._C._nn.nll_loss 是否有接受 CPU 输入的函数?我没有足够的 GPU 内存来运行我的功能,所以我试图在 CPU 上运行所有东西。这是我的具体错误(查看 anaconda 文件)

Traceback (most recent call last):
  File "plot_parametric_pytorch.py", line 395, in <module>
    val_result = validate(val_loader, model, criterion, 0)
  File "plot_parametric_pytorch.py", line 228, in validate
    training=False, optimizer=None)
  File "plot_parametric_pytorch.py", line 169, in forward
    loss = criterion(output, target_var)
  File "/home/klee/anaconda3/envs/sharpenv/lib/python3.7/site-packages/torch/nn/modules/module.py", line 550, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/klee/anaconda3/envs/sharpenv/lib/python3.7/site-packages/torch/nn/modules/loss.py", line 932, in forward
    ignore_index=self.ignore_index, reduction=self.reduction)
  File "/home/klee/anaconda3/envs/sharpenv/lib/python3.7/site-packages/torch/nn/functional.py", line 2317, in cross_entropy
    return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
  File "/home/klee/anaconda3/envs/sharpenv/lib/python3.7/site-packages/torch/nn/functional.py", line 2115, in nll_loss
    ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: Expected object of device type cuda but got device type cpu for argument #1 'self' in call to _thnn_nll_loss_forward

标签: pythonmachine-learningpytorch

解决方案


nll_loss适用于 CPU 和 GPU,但输入和目标需要在同一设备上。您的设备在不同的设备上,其中第一个 ( output) 在 CPU 上,而第二个 ( target_var) 在 GPU 上。

你需要放到target_varCPU上。

loss = criterion(output, target_var.cpu())

推荐阅读