FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead
时间: 2025-05-28 07:01:09 浏览: 99
### 解决 `torch.cuda.amp.autocast` 弃用警告
为了消除弃用警告并确保代码在未来版本中仍然有效,应当将原有的 `torch.cuda.amp.autocast()` 调用替换为带有指定设备类型的 `torch.amp.autocast(device_type='cuda')`。这不仅解决了弃用问题,还保持了原有功能的一致性。
具体修改如下:
原始写法可能会触发弃用警告:
```python
with torch.cuda.amp.autocast():
...
```
推荐的新写法则不会引发任何警告,并且更加清晰地指定了使用的设备类型:
```python
with torch.amp.autocast(device_type='cuda'):
...
```
需要注意的是,当传递给 `torch.amp.autocast` 的参数不是字符串而是布尔值时,将会抛出错误提示 device_type 应该是 str 类型而非 bool 类型[^2]。因此务必确认传入正确的数据类型作为参数。
以下是完整的修正示例,展示了如何在训练循环内应用这一更改:
```python
import torch
from torch.cuda.amp import GradScaler, autocast
model = Net().cuda()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
scaler = GradScaler()
for epoch in range(num_epochs):
for inputs, targets in dataloader:
optimizer.zero_grad()
with autocast(device_type='cuda'): # 使用新的API调用方式
outputs = model(inputs)
loss = criterion(outputs, targets)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
```
通过上述调整,可以有效地移除有关 `torch.cuda.amp.autocast` 的 FutureWarning 并维持程序正常运行[^4]。
阅读全文
相关推荐


















