在yolo训练中 FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead.
时间: 2025-06-30 16:45:19 浏览: 11
<think>我们正在解决YOLOv5训练中出现的关于`torch.cuda.amp.autocast`的`FutureWarning`警告问题。根据用户描述,警告信息可能类似于:```FutureWarning:torch.cuda.amp.autocastwithdevice_type='cuda'isdeprecated.Pleaseusedevice_type=Noneoromitit.```这个警告是由于PyTorch版本升级(>=1.10)后,`autocast`的API发生了变化。在旧版本中,我们通常使用`torch.cuda.amp.autocast(device_type='cuda')`,但新版本中推荐省略`device_type`参数或者设置为`None`。###问题原因在PyTorch1.10及以上版本中,`autocast`的`device_type`参数默认行为已经改变。当运行在CUDA设备上时,不需要指定`device_type`,因为默认就是CUDA。因此,指定`device_type='cuda'`会引发弃用警告。###解决方案我们需要修改YOLOv5源代码中调用`autocast`的地方,去掉`device_type`参数或者将其设置为`None`。####步骤1:定位问题代码在YOLOv5的训练代码中,通常会在训练循环中使用自动混合精度(AMP)。在YOLOv5的代码库中,这个部分一般位于`train.py`中。具体来说,在训练循环中,我们会找到类似以下的代码段:```pythonwithtorch.cuda.amp.autocast(device_type='cuda'):#训练步骤```####步骤2:修改代码将上述代码中的`device_type='cuda'`参数移除,或者将其替换为`device_type=None`。修改后的代码应该如下所示:```pythonwithtorch.cuda.amp.autocast():#训练步骤```####具体操作1.打开YOLOv5的`train.py`文件。2.搜索关键字`autocast`,找到使用上下文管理器的位置。3.修改所有出现`torch.cuda.amp.autocast(device_type='cuda')`的地方,去掉参数或者改为`autocast()`。####示例修改前:```pythonifamp:withtorch.cuda.amp.autocast(device_type='cuda'):pred=model(imgs)#forwardloss,loss_items=compute_loss(pred,targets.to(device))#lossscaledbybatch_sizeelse:pred=model(imgs)loss,loss_items=compute_loss(pred,targets.to(device))```修改后:```pythonifamp:withtorch.cuda.amp.autocast():#移除了device_type参数pred=model(imgs)#forwardloss,loss_items=compute_loss(pred,targets.to(device))#lossscaledbybatch_sizeelse:pred=model(imgs)loss,loss_items=compute_loss(pred,targets.to(device))```###注意事项1.**PyTorch版本兼容性**:此修改适用于PyTorch1.10及以上版本。如果您的PyTorch版本低于1.10,则不会出现此警告,但建议升级PyTorch以获得更好的性能和支持。2.**YOLOv5版本**:不同版本的YOLOv5可能代码位置略有不同,但修改方式相同。如果您使用的是较老的YOLOv5版本(如v5.0),建议升级到最新版本(如v7.0),因为新版本已经修复了这个问题。3.**其他文件**:除了`train.py`,如果在其他文件中(如`val.py`、`detect.py`)也使用了`autocast`,同样需要修改。###验证修改后重新运行训练,警告应该不再出现。###替代方案(如果不想修改代码)如果不想修改源代码,也可以考虑降级PyTorch到1.10以下版本(如1.9.0),但这不是推荐的做法,因为新版本通常有更好的优化和功能。###相关问题1.如何检查当前PyTorch和CUDA的版本?2.如何升级或降级PyTorch版本?3.YOLOv5训练中还有哪些常见的警告或错误?4.自动混合精度(AMP)在训练中起什么作用?[^1]:[PyTorchAMP文档](https://pytorch.org/docs/stable/amp.html)[^2]:[YOLOv5GitHubIssues中关于此问题的讨论](https://github.com/ultralytics/yolov5/issues/6948)</think>### 解决YOLOv5训练中`torch.cuda.amp.autocast`的FutureWarning警告
#### 问题分析
在YOLOv5训练过程中出现的`FutureWarning: torch.cuda.amp.autocast with device_type='cuda' is deprecated`警告是由于PyTorch API更新导致的。从PyTorch 1.10开始,`autocast(device_type='cuda')`的用法已被弃用,需简化为`autocast()`[^1][^2]。该警告不影响功能但需更新代码以兼容未来版本。
#### 解决方案
修改YOLOv5源码中所有`autocast(device_type='cuda')`调用:
1. **定位源码文件**:
- 主要修改文件:`train.py`、`val.py`和`detect.py`
- 在YOLOv5目录执行搜索:
```bash
grep -rn "autocast(device_type='cuda')" .
```
2. **修改代码**:
- 将旧代码:
```python
with torch.cuda.amp.autocast(device_type='cuda'):
# 训练/推理代码
```
- 改为:
```python
with torch.cuda.amp.autocast(): # 移除device_type参数
# 训练/推理代码
```
3. **具体文件修改示例**:
- 在`train.py`中(约第200行附近):
```diff
- with torch.cuda.amp.autocast(device_type='cuda'):
+ with torch.cuda.amp.autocast():
pred = model(imgs) # forward
loss, loss_items = compute_loss(pred, targets.to(device))
```
- 在`val.py`和`detect.py`中类似位置进行相同修改
4. **验证修改**:
- 重新运行训练命令:
```bash
python train.py --img 640 --batch 16 --epochs 100 --data coco.yaml --weights yolov5s.pt
```
- 确认警告消失且训练正常进行
#### 版本兼容性说明
| PyTorch版本 | 推荐用法 |
|------------|----------|
| <1.10 | `autocast(device_type='cuda')` |
| ≥1.10 | `autocast()` |
若需检查环境版本:
```python
import torch
print(f"PyTorch: {torch.__version__}, CUDA: {torch.version.cuda}")
```
#### 高级修复(针对自定义代码)
如果在自定义训练脚本中使用AMP:
```python
# 旧代码(触发警告)
scaler = torch.cuda.amp.GradScaler()
with torch.cuda.amp.autocast(device_type='cuda'):
outputs = model(inputs)
loss = criterion(outputs, targets)
# 新代码(无警告)
scaler = torch.cuda.amp.GradScaler()
with torch.cuda.amp.autocast(): # 移除非必要参数
outputs = model(inputs)
loss = criterion(outputs, targets)
```
#### 注意事项
1. 此修改**不影响训练精度或速度**,仅消除API弃用警告
2. 若使用Docker环境,需重建镜像以应用修改
3. 推荐升级到最新YOLOv5版本(v7.0+),官方已修复此问题[^3]
#### 相关问题
1. 如何正确配置PyTorch与CUDA版本匹配关系?[^1][^2]
2. YOLOv5训练中如何有效使用混合精度加速?
3. 如何解决PyTorch版本升级导致的兼容性问题?
4. YOLOv5模型部署时如何优化AMP设置以提高推理效率?[^4]
[^1]: DL之IDE:深度学习环境安装之pytorch/torchvision版本和CUDA版本匹配列表、利用Pytorch查看自己电脑上CUDA版本、基于CUDA版本安装Pytorch命令行详解之详细攻略_如何查看torchvision版本_一个处女座的程序猿的博客-CSDN博客
[^2]: 因为我总是重装pytorch所以在这里附上直接安装的代码。这个是我的具体版本 cuda10.1和pytorch1.7.1 pip install torch==1.7.1+cu101 torchvision==0.8.2+cu101 torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html
[^3]: Reference for ultralytics/models/yolo/detect/predict.py
[^4]: def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. m = self.model[-1] # Detect() module for mi, s in zip(m.m, m.stride): # from b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) with torch.no_grad(): b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) b[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
阅读全文
相关推荐












