RuntimeError: Cannot use ``weights_only=True`` with files saved in the legacy .tar format. In PyTorch 2.6, we changed the default value of the `weights_only` argument in `torch.load` from `False` to `True`. Re-running `torch.load` with `weights_only` set to `False` will likely succeed, but it can result in arbitrary code execution. Do it only if you got the file from a trusted source.
时间: 2025-08-16 11:55:02 浏览: 2
在 PyTorch 2.6 中加载旧版本 `.tar` 格式的模型文件时,如果尝试使用 `weights_only=True` 参数,会触发 `RuntimeError: Cannot use weights_only=True with legacy .tar format` 错误。这是由于 `.tar` 文件格式通常是旧版 PyTorch 保存整个模型(包括模型结构和参数)时使用的格式,而 `weights_only=True` 仅适用于保存模型参数(`state_dict`)的 `.pt` 或 `.pth` 文件。
### 解决方法
#### 1. 不使用 `weights_only=True`
如果模型文件是通过 `torch.save(model, PATH)` 保存的(即包含整个模型对象),则应直接加载整个模型,无需使用 `weights_only=True`:
```python
model = torch.load("model.tar")
```
此方式适用于 PyTorch 1.x 和 2.x 版本。由于 `.tar` 文件中可能包含模型结构定义和参数信息,因此不建议使用 `weights_only=True` 来限制加载模式。
#### 2. 使用 `map_location` 指定加载设备
若模型是在 GPU 上训练并保存的,而在 CPU 上加载时出现兼容性问题,可以通过 `map_location` 参数指定目标设备:
```python
model = torch.load("model.tar", map_location=torch.device('cpu'))
```
此方法可以避免因设备不匹配导致的加载错误,同时适用于 `.tar` 和 `.pt` 文件格式。
#### 3. 将模型参数保存为 `.pt` 或 `.pth` 格式
为了更好地兼容 PyTorch 2.6 及其新特性,建议将 `.tar` 文件中的模型参数提取并重新保存为 `.pt` 或 `.pth` 格式:
```python
# 加载旧模型
model = torch.load("model.tar")
# 仅保存模型参数
torch.save(model.state_dict(), "model_weights.pth")
```
之后,可以使用 `weights_only=True` 安全加载模型参数:
```python
model = MyModel()
model.load_state_dict(torch.load("model_weights.pth", weights_only=True))
```
这种方式不仅提高了安全性,还增强了与新版 PyTorch 的兼容性。
#### 4. 检查 PyTorch 版本与模型保存方式
若模型是通过 `torch.save(model.state_dict(), PATH)` 保存的,则加载时应使用 `model.load_state_dict(torch.load(PATH))`。如果使用 `torch.load` 直接加载整个模型对象(如 `.tar` 文件),则必须确保模型类定义在加载时可用,并避免使用 `weights_only=True`。
###
阅读全文