【PyTorch】FutureWarning: You are using torch.load with weights_only=False (the current default
问题描述
model.load_state_dict(torch.load(model_path))
FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
原因分析
FutureWarning: 您正在使用 torch.load
并且 weights_only=False
(当前默认值),这会隐式使用默认的 pickle 模块。构造恶意的 pickle 数据在反序列化期间可能会执行任意代码(请参阅 https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models 了解更多详情)。在未来的版本中,weights_only
的默认值将会变为 True
。这将限制在反序列化期间可以执行的函数。除非用户通过 torch.serialization.add_safe_globals
显式允许,否则将不再允许加载任意对象。我们建议您在无法完全控制加载文件的任何情况下开始设置 weights_only=True
。如果您遇到与此实验功能相关的任何问题,请在 GitHub 上打开一个 issue。
解决方案
model.load_state_dict(torch.load(model_path, weights_only=True))
参考资料
- https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models