本节介绍4选2结构化稀疏支持的层,接口调用流程和调用示例。
由于硬件约束,Atlas 200/300/500 推理产品、Atlas 推理系列产品(Ascend 310P处理器)、Atlas 训练系列产品不支持4选2结构化稀疏特性:使能后获取不到性能收益。
AMCT支持基于重训练的4选2结构化稀疏特性。该特性支持的层以及约束如下:
优化方式 |
支持的层类型 |
约束 |
---|---|---|
4选2结构化稀疏 |
torch.nn.Linear:全连接层 |
复用层(共用weight和bias参数)不支持稀疏。 |
torch.nn.Conv2d:卷积层 |
复用层(共用weight和bias参数)不支持稀疏。 depthwise只能被动稀疏(groups=in_channels),不能主动稀疏。 |
|
torch:ConvTranspose2d:反卷积层 |
- |
4选2结构化稀疏功能接口调用流程如图1所示。
推荐执行该步骤,请确保原始模型可以完成推理且精度正常;执行该步骤时,可以使用部分测试集,减少运行时间。
1 2 3 |
ori_model.load() # 测试模型 user_test_model(ori_model, test_data, test_iterations) |
实现该步骤前,应先恢复训练好的参数,如1中的ori_model.load()。
1 2 3 4 5 6 |
simple_cfg = './retrain.cfg' record_file = './tmp/record.txt' prune_retrain_model = amct.create_prune_retrain_model(model=ori_model, input_data=ori_model_input_data, config_defination=simple_cfg, record_file=record_file) |
1 2 3 4 |
prune_retrain_model = amct.save_prune_retrain_model( model=pruned_retrain_model, save_path=save_path, input_data=input_data) |
使用稀疏后仿真模型精度与1中的原始精度做对比,可以观察4选2结构化稀疏对精度的影响。
1 2 |
prune_retrain_model = './results/user_model_fake_prune_model.onnx' user_do_inference_onnx(prune_retrain_model, test_data, test_iterations) |
如果训练过程中断,需要从ckpt中恢复数据,继续训练,则调用流程为:
1
|
ori_model= user_create_model() |
1 2 3 4 5 6 7 8 9 10 11 12 |
model = ori_model input_data = ori_model_input_data record_file = './tmp/record.txt' config_defination = './prune_cfg.cfg' save_pth_path = /your/path/to/save/tmp.pth model.load_state_dict(torch.load(state_dict_path)) prune_retrain_model = amct.restore_prune_retrain_model(model=ori_model, input_data=ori_model_input_data, record_file=record_file, config_defination='./prune_cfg.cfg', save_pth_path=/your/path/to/save/tmp.pth, 'state_dict') |
1 2 3 4 |
prune_retrain_model = amct.save_prune_retrain_model( model=pruned_retrain_model, save_path=save_path, input_data=input_data) |
使用稀疏后仿真模型精度与1中的原始精度做对比,可以观察4选2结构化稀疏对精度的影响。
1 2 |
prune_retrain_model = './results/user_model_fake_prune_model.onnx' user_do_inference_onnx(prune_retrain_model, test_data, test_iterations) |