net.load_state_dict(torch.load('rnn_x_epoch.net'))在CPU上不起作用

时间:2019-01-30 07:16:19

标签: neural-network pytorch torch

我正在使用pytorch训练神经网络。当我在GPU上进行训练和测试时,它可以正常工作。 但是当我尝试使用以下方法在CPU上加载模型参数时:

net.load_state_dict(torch.load('rnn_x_epoch.net'))

我收到以下错误:

RuntimeError: cuda runtime error (35) : CUDA driver version is insufficient for CUDA runtime version at torch/csrc/cuda/Module.cpp:51

我搜索了错误,主要是由于CUDA驱动程序依赖性,但是由于我在出现此错误时正在CPU上运行,因此它一定是其他错误,或者可能是我遗漏了某些错误。 由于使用GPU可以正常工作,因此我可以在GPU上运行它,但是我试图在GPU上训练网络,存储参数,然后将其加载到CPU模式以进行预测。 我只是在寻找一种在CPU模式下加载参数的方法。

我也尝试过此操作来加载参数:

check = torch.load('rnn_x_epoch.net')

它不起作用。

我试图以两种方式保存模型参数,以查看其中任何一种都行得通,但没有成功: 1)

checkpoint = {'n_hidden': net.n_hidden,
          'n_layers': net.n_layers,
          'state_dict': net.state_dict(),
          'tokens': net.chars}

with open('rnn_x_epoch.net', 'wb') as f:
    torch.save(checkpoint, f)

2)

torch.save(model.state_dict(), 'rnn_x_epoch.net')

TraceBack:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-9-e61f28013b35> in <module>()
----> 1 net.load_state_dict(torch.load('rnn_x_epoch.net'))

/opt/conda/lib/python3.6/site-packages/torch/serialization.py in load(f, map_location, pickle_module)
    301         f = open(f, 'rb')
    302     try:
--> 303         return _load(f, map_location, pickle_module)
    304     finally:
    305         if new_fd:

/opt/conda/lib/python3.6/site-packages/torch/serialization.py in _load(f, map_location, pickle_module)
    467     unpickler = pickle_module.Unpickler(f)
    468     unpickler.persistent_load = persistent_load
--> 469     result = unpickler.load()
    470 
    471     deserialized_storage_keys = pickle_module.load(f)

/opt/conda/lib/python3.6/site-packages/torch/serialization.py in persistent_load(saved_id)
    435             if root_key not in deserialized_objects:
    436                 deserialized_objects[root_key] = restore_location(
--> 437                     data_type(size), location)
    438             storage = deserialized_objects[root_key]
    439             if view_metadata is not None:

/opt/conda/lib/python3.6/site-packages/torch/serialization.py in default_restore_location(storage, location)
     86 def default_restore_location(storage, location):
     87     for _, _, fn in _package_registry:
---> 88         result = fn(storage, location)
     89         if result is not None:
     90             return result

/opt/conda/lib/python3.6/site-packages/torch/serialization.py in _cuda_deserialize(obj, location)
     68     if location.startswith('cuda'):
     69         device = max(int(location[5:]), 0)
---> 70         return obj.cuda(device)
     71 
     72 

/opt/conda/lib/python3.6/site-packages/torch/_utils.py in _cuda(self, device, non_blocking, **kwargs)
     66         if device is None:
     67             device = -1
---> 68     with torch.cuda.device(device):
     69         if self.is_sparse:
     70             new_type = getattr(torch.cuda.sparse, 
self.__class__.__name__)

/opt/conda/lib/python3.6/site-packages/torch/cuda/__init__.py in __enter__(self)
    223         if self.idx is -1:
    224             return
--> 225         self.prev_idx = torch._C._cuda_getDevice()
    226         if self.prev_idx != self.idx:
    227             torch._C._cuda_setDevice(self.idx)

RuntimeError: cuda runtime error (35) : CUDA driver version is insufficient for CUDA runtime version at torch/csrc/cuda/Module.cpp:51

也可能是Pytorch中的保存/加载操作仅适用于GPU模式,但我对此并不十分确信。

1 个答案:

答案 0 :(得分:1)

从PyTorch documentation

  

在包含GPU张量的文件上调用torch.load()时,这些张量将默认加载到GPU。

要将模型加载到保存在GPU上的CPU上,您需要将map_location参数作为cpu传递给load函数,如下所示:

# Load all tensors onto the CPU
net.load_state_dict(torch.load('rnn_x_epoch.net', map_location=torch.device('cpu')))

这样做,使用map_location参数将张量下面的存储动态地重新映射到CPU设备。您可以在官方PyTorch tutorials上阅读更多内容。

这也可以如下进行:

# Load all tensors onto the CPU, using a function
net.load_state_dict(torch.load('rnn_x_epoch.net', map_location=lambda storage, loc: storage))