【代码模板】Pytorch AMP 混合精度训练

背景

当使用AMP混合精度训练时,可以提升训练速度,并降低对显存的占用。下面提供一个使用AMP训练的代码demo。

Demo

python 复制代码
use_amp = True

net = make_model(in_size, out_size, num_layers)
opt = torch.optim.SGD(net.parameters(), lr=0.001)
scaler = torch.cuda.amp.GradScaler(enabled=use_amp)

start_timer()
for epoch in range(epochs):
    for input, target in zip(data, targets):
        with torch.autocast(device_type=device, dtype=torch.float16, enabled=use_amp):
            output = net(input)
            loss = loss_fn(output, target)
        scaler.scale(loss).backward()
        scaler.step(opt)
        scaler.update()
        opt.zero_grad() # set_to_none=True here can modestly improve performance
end_timer_and_print("Mixed precision:")

参考

Automatic Mixed Precision

相关推荐
rgeshfgreh2 分钟前
Python流程控制:从条件到循环实战
前端·数据库·python
百万彩票中奖候选人5 分钟前
在trae、qoder、Claude Code、Cursor等AI IDE中使用ui-ux-pro-max-skill
人工智能·ui·ux
luoluoal6 分钟前
基于python大数据的电影市场预测分析(源码+文档)
python·mysql·django·毕业设计·源码
Bigemap13 分钟前
如何保存WAsp软件需要的 map格式(.map)的文件
人工智能·无人机·政务·bigemappro添加地图
闲云一鹤15 分钟前
2026 最新 ComfyUI 教程 - 本地部署 AI 生图模型 - Z-Image-Turbo
前端·人工智能·ai编程
幻云201018 分钟前
Python深度学习:从入门到实战
人工智能·python
ldccorpora19 分钟前
Multiple-Translation Arabic (MTA) Part 2数据集介绍,官网编号LDC2005T05
人工智能·深度学习·自然语言处理·动态规划·语音识别
GISer_Jing32 分钟前
AI Agent 人类参与HITL与知识检索RAG
人工智能·设计模式·aigc
Zoey的笔记本1 小时前
敏捷与稳定并行:Scrum看板+BPM工具选型指南
大数据·前端·数据库·python·低代码
智界前沿1 小时前
2026可落地商用数字人选型指南:TOP5产品深度测评与实战对比
人工智能·aigc·数字人