【代码模板】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

相关推荐
ITresearchGuest5 小时前
我用 AI 一小时写了一个世界杯数据可视化平台|前端 VibeCoding 初体验
前端·人工智能·信息可视化
AI_yangxi5 小时前
靠谱的短视频矩阵系统
大数据·人工智能·矩阵
czxxxc5 小时前
知识服务迎来 AI 变革,创客匠人 AI 智能体破解创作者运营难题
大数据·人工智能
黑旋风小威6 小时前
一句话成片教程:用AI快速生成漫剧的实操方法分享
人工智能
冬奇Lab6 小时前
Code Agent 解剖(17):AgentTeams——消息怎么在 agent 之间传递?
人工智能·开源
冬奇Lab6 小时前
一天一个开源项目(第205篇):PenguinHarness - 让 AI 来构建 AI
人工智能·开源·资讯
小鹿的周先生6 小时前
Spring-AI-第2篇-ChatClient 实战:使用 DeepSeek 完成第一次 AI 对话
java·人工智能·spring
ajassi20006 小时前
AI语音智能体开发日记(十五)智能体LCD屏幕GIF动画显示方案——从GIF到BMP的完整实战
人工智能·ai·ai编程
Dfreedom.6 小时前
目标检测后处理核心:NMS非极大值抑制详解
图像处理·人工智能·深度学习·目标检测·目标跟踪
枫叶丹46 小时前
实时语音 Agent:从语音机器人到连续协作界面
人工智能·chatgpt·机器人·语音识别·agent·codex