MXNet半精度(FP16)训练

MXNet半精度训练

1.先决条件

  • Volta range of Nvidia GPUs (e.g. AWS P3 instance)
  • CUDA 9 or higher
  • cuDNN v7 or higher

2.使用Gluon API训练和前向推理

2.1训练

使用cast将网络设置为float16精度进行训练

net.cast('float16')

data = data.astype('float16', copy=False)

optimizer = mx.optimizer.create('sgd', multi_precision=True, lr=0.01)

2.fine tuning

import numpy as np
import mxnet as mx
from mxnet.gluon.model_zoo.vision import get_model


pretrained_net = get_model(name='resnet50_v2', ctx=mx.cpu(),
                           pretrained=True, classes=1000)
pretrained_net.cast('float16')
net = get_model(name='resnet50_v2', ctx=mx.cpu(),
                pretrained=False, classes=101)
net.collect_params().initialize(mx.init.Xavier(magnitude=2.24), ctx=mx.cpu())
net.features = pretrained_net.features
net.cast('float16')

2使用Symbolic API在float16中训练网络

涉及以下步骤。

  1. 在网络的开头添加一个图层,将数据转换为float16。这将确保在float16中计算所有以下层。
  2. 建议在softmax之前将层的输出转换为float32,以便softmax计算在float32中完成。这是因为softmax涉及大幅减少,并且有助于将其保留在float32中以获得更精确的答案。
  3. 建议使用优化器的多精度模式进行更精确的重量更新。
    以下是创建优化器时如何启用此模式。
optimizer = mx.optimizer.create('sgd', multi_precision=True, lr=0.01)

示例

data = mx.sym.Variable(name="data")

if dtype == 'float16':
    data = mx.sym.Cast(data=data, dtype=np.float16)

# ... the rest of the network
net_out = net(data)

if dtype == 'float16':
    net_out = mx.sym.Cast(data=net_out, dtype=np.float32)

output = mx.sym.SoftmaxOutput(data=net_out, name='softmax')

http://mxnet.incubator.apache.org/versions/master/faq/float16.html?highlight=distributed training
加速安装
pip install mxnet-cu80 -i https://pypi.tuna.tsinghua.edu.cn/simple/

MXNet分布式训练
https://github.com/MaJun-cn/DistributedTraining_inMXNet
https://github.com/apache/incubator-mxnet/tree/master/example/distributed_training

conda清理没用的安装包

conda clean -p      //删除没有用的包
conda clean -t      //tar打包
conda clean -y -all //删除所有的安装包及cache

pytorch 分布式训练
分布式例子
https://github.com/pytorch/examples/tree/master/imagenet
https://pytorch.org/tutorials/intermediate/dist_tuto.html
https://pytorch.org/tutorials/intermediate/ddp_tutorial.html?highlight=distributed training
https://pytorch.org/docs/stable/distributed_deprecated.html?highlight=distributed training

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值