Model summary: 214 layers, 7235389 parameters, 7235389 gradients, 16.6 GFLOPs Transferred 349/349 items from yolov5s.pt D:\yolov5-7.0\models\common.py:702: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead. with amp.autocast(autocast): D:\yolov5-7.0\models\common.py:702: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead. with amp.autocast(autocast): AMP: checks passed optimizer: SGD(lr=0.01) with parameter groups 57 weight(decay=0.0), 60 weight(decay=0.0005), 60 bias train: Scanning D:\datasets\coco128\labels\train2017.cache... 126 images, 2 backgrounds, 0 corrupt: 100%|██████████| 128/128 00:00 val: Scanning D:\datasets\coco128\labels\train2017.cache... 126 images, 2 backgrounds, 0 corrupt: 100%|██████████| 128/128 00:00 AutoAnchor: 4.27 anchors/target, 0.994 Best Possible Recall (BPR). Current anchors are a good fit to dataset Plotting labels to runs\train\exp3\labels.jpg... Image sizes 640 train, 640 val Using 0 dataloader workers Logging results to runs\train\exp3 Starting training for 100 epochs... Epoch GPU_mem box_loss obj_loss cls_loss Instances Size 0%| | 0/8 00:00 Traceback (most recent call last): File "D:\yolov5-7.0\train.py", line 634, in <module> main(opt) File "D:\yolov5-7.0\train.py", line 528, in main train(opt.hyp, opt, device, callbacks) File "D:\yolov5-7.0\train.py", line 308, in train with torch.amp.autocast('cuda',amp): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\s\envs\pytorch8\Lib\site-packages\torch\amp\autocast_mode.py", line 354, in __enter__ torch.set_autocast_dtype(self.device, self.fast_dtype) # type: ignore[arg-type] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: set_autocast_dtype(): argument 'dtype' (position 2) must be torch.dtype, not bool 进程已结束,退出代码为 1
时间: 2025-05-31 18:53:24 浏览: 42
### 解决方案
在YOLOv5训练过程中遇到 `torch.amp.autocast` 的错误提示 `TypeError: set_autocast_dtype(): argument 'dtype' (position 2) must be torch.dtype, not bool`,这通常是因为传递给 `autocast` 函数的参数不正确所致。以下是详细的分析和解决方案。
#### 错误原因
该错误表明,在调用 `torch.cuda.amp.autocast()` 或其上下文管理器时,传入了一个布尔类型的值作为 `dtype` 参数,而此参数应为 `torch.dtype` 类型。根据官方文档[^3],`autocast` 支持两种主要模式:默认浮点精度 (`torch.float32`) 和混合精度计算 (`torch.float16` 或 `torch.bfloat16`)。如果未指定 `dtype`,则会使用默认设置;但如果显式指定了一个非法类型,则会导致上述错误。
#### 修改方法
为了修复这个问题,可以按照以下方式调整代码:
1. **检查 autocast 调用位置**
找到项目中涉及 `torch.cuda.amp.autocast` 的部分,通常是位于模型前向传播阶段或者损失函数计算附近。例如:
```python
from torch.cuda.amp import autocast
with autocast(dtype=False): # 这里 dtype 应当是一个合法的 torch.dtype 对象
outputs = model(inputs)
```
上述代码中的 `dtype=False` 是引发错误的原因之一。需要将其更改为有效的数据类型,比如 `torch.float16` 或者完全移除该参数以采用默认行为。
2. **更新至最新版本 PyTorch**
如果使用的 PyTorch 版本较旧,可能存在某些 API 不兼容的情况。建议升级到最新的稳定版 PyTorch 来获得更好的支持以及 bugfixes[^4]。
升级命令如下所示:
```bash
pip install --upgrade torch torchvision torchaudio
```
3. **修正后的代码样例**
下面展示了一种可能正确的实现形式,其中去掉了可能导致冲突的自定义选项并依赖于框架自身的最佳实践设定:
```python
from torch.cuda.amp import GradScaler, autocast
scaler = GradScaler()
for data in dataloader:
inputs, targets = data['image'], data['target']
optimizer.zero_grad(set_to_none=True)
with autocast():
predictions = model(inputs)
loss = compute_loss(predictions, targets)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
```
通过以上更改能够有效规避因不当配置带来的运行期异常状况。
#### 额外注意事项
除了直接处理 `autocast` 外部接口之外,还需要留意整个项目的其他组件是否也存在类似的隐患。特别是那些被重写的模块或第三方扩展库(如引用提到的 `'ultralytics/utils/loss.py'` 文件),它们内部也可能隐藏着相似的问题源码片段[^2]。
---
阅读全文
相关推荐










