with torch.cuda.amp.autocast(amp):
功能概述
这行代码使用 PyTorch 的自动混合精度(AMP, Automatic Mixed Precision)上下文管理器,在支持的情况下自动将计算从 FP32(32位浮点数)转换为 FP16(16位浮点数),以加速训练并减少显存占用,同时保持模型精度。
详细分析
1. 混合精度(Mixed Precision)基础概念
浮点数对比:
| FP32 | 32 | ±3.4×10³⁸ | 高 | 4字节/值 | 基准 |
| FP16 | 16 | ±6.5×10⁴ | 中</ |





