torch.load中map_location和model.to的关系

  参考资料:

  https://discuss.pytorch.org/t/is-map-location-in-torch-load-and-model-load-state-dict-independent-from-device-in-to/99983

  我的问题和参考资料中的一样,在使用torch.load的时候有一个map_location参数,此时可以将checkpoint等加载到对应的device上。但是,如果接下来初始化一个model,并且使用model.load_state_dict的话,后续打印model的device仍然是在cpu上。这意味着我们仍然需要再接上一个model.to(XX)。

  参考资料中一个大佬给出了解释:

The map_location changes the device of the Tensors in the state dict that is returned.
But when you load_state_dict(), then these values are loaded (and only values) into the model. But that does not change the model’s device! you will need to move the model itself with .to() if you want to have it on a different device.

  翻译过来就是使用torch.load加载的都是tensor,比如:这些tensor如果之前是在device("cuda:1")上被保存的,那么load的时候pytorch仍然会试图将tensor加载到第一个显卡上。但是,load_state_dict不管你的state_dict放在哪里,它只load值,所以如果你的model在cpu上初始化了,它只是从GPU卡上把tensor(state_dict)的值copy到cpu的model上,model所处的device还是cpu。

  综上所述,只有to指令才能让model换device!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值