【PyTorch基础】唯快不破:基于Apex的混合精度加速

 APEX

如何安装

git clone https://github.com/NVIDIA/apex.git
cd apex
pip3 install --no-cache-dir --global-option="--pyprof" --global-option="--cpp_ext" --global-option="--cuda_ext" ./

 google colab install apex amp

try:
  import apex
except Exception:
  ! git clone https://github.com/NVIDIA/apex.git
  % cd apex
  !pip install --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" .
  % cd ..

code

import apex  # OK
from apex import amp  # error

error

ImportError: cannot import name 'amp' from 'apex' (unknown location)

add --user

!pip install --no-cache-dir --global-option="--pyprof" --global-option="--cpp_ext" --global-option="--cuda_ext" ./ --user

still wrong......

如何使用

1) 训练、保存模型

2) 测试

Pytorch使用

1) 训练

复制代码
from torch.cuda.amp import autocast as autocast

# 创建model,默认是torch.FloatTensor
model = Net().cuda()
optimizer = optim.SGD(model.parameters(), ...)

# 在训练最开始之前实例化一个GradScaler对象
scaler = GradScaler()

for epoch in epochs:
    for input, target in data:
        optimizer.zero_grad()

        # 前向过程(model + loss)开启 autocast
        with autocast():
            output = model(input)
            loss = loss_fn(output, target)

        # Scales loss. 为了梯度放大.
        scaler.scale(loss).backward()

        # scaler.step() 首先把梯度的值unscale回来.
        # 如果梯度的值不是 infs 或者 NaNs, 那么调用optimizer.step()来更新权重,
        # 否则,忽略step调用,从而保证权重不更新(不被破坏)
        scaler.step(optimizer)

        # 准备着,看是否要增大scaler
        scaler.update()
View Code
复制代码

 2) 测试

 

参考

1. 【PyTorch】唯快不破:基于Apex的混合精度加速

判断你的GPU是否支持FP16:支持的有拥有Tensor Core的GPU(2080Ti、Titan、Tesla等),不支持的(Pascal系列,1080Ti)就不建议折腾了。
如何使用 PyTorch 进行半精度训练
【深度学习训练小技巧】1080ti与2080ti区别、apex与梯度累加、torch.no_grad
https://on-demand.gputechconf.com/gtc-taiwan/2018/pdf/5-1_Internal%20Speaker_Michael%20Carilli_PDF%20For%20Sharing.pdf
https://github.com/NVIDIA/apex/blob/master/apex/amp/lists/functional_overrides.py
https://github.com/NVIDIA/apex
https://nvidia.github.io/apex/index.html
 https://www.cnblogs.com/yangwenhuan/p/11337203.html
 https://developer.nvidia.com/automatic-mixed-precision
 

posted on   鹅要长大  阅读(473)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示