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

相关推荐
用户019027581619 分钟前
天勤 tqsdk 能做 A 股行情吗?期货强项与股票数据选型
python
后端小肥肠11 分钟前
公众号漫画又挖到长尾赛道:家常菜美食,流量稳定长期有收益
人工智能·aigc·agent
泯泷34 分钟前
从"检索管道"到"主动助理"——Agentic RAG 与双层记忆(五)
人工智能·llm·agent
武子康1 小时前
ComfyUI 加载了动作 LoRA,H3-World 的时间绑定就接好了吗?
人工智能·机器学习·claude
腾科IT教育1 小时前
HCIE-AI认证全部解析:方向选择、考试门槛与职业适配指南
人工智能·华为认证·hcie-ai·华为ai
QXWZ_IA1 小时前
具身智能在油气行业规模化应用面临哪些技术挑战?
人工智能·安全
2601_967979122 小时前
pip在Python中的9个必须知道的用法
python·pip·版本控制·包管理工具·requirements.txt
曲径海盗2 小时前
【Python 学习第 58 天】列表方法
python·学习笔记·编程入门
DeepVisionary2 小时前
Runway开源机器人大模型Praxis-1,推演延迟压到62毫秒
python·自动化
泯泷3 小时前
AI Agent 的下一站:让世界主动来找它
人工智能·llm·agent