PaddlePaddle / PaddleSlim

PaddleSlim is an open-source library for deep model compression and architecture search.
https://paddleslim.readthedocs.io/zh_CN/latest/
Apache License 2.0
1.56k stars 345 forks source link

Pruning models in PaddleClas dynamic graph #721

Closed wanghaoshuang closed 9 months ago

wanghaoshuang commented 3 years ago

安装PaddleSlim develop分支,或PaddleSlim2.1版本(预计5月20日前发布)。

在PaddleClas路径下执行以下命令,验证PaddleClas中所有模型的剪裁效果(仅计算FLOPs, 不重训模型):

find configs/ -name *.yaml | xargs -i python tools/prune.py -c {}

以上命令生成测试结果在文件PaddleClas/test_result中。

PaddleClas/tools/prune.py代码如下:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os
import sys
__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(__dir__)
sys.path.append(os.path.abspath(os.path.join(__dir__, '..')))

import paddle

from ppcls.data import Reader
from ppcls.utils.config import get_config
from ppcls.utils.save_load import init_model, save_model
from ppcls.utils import logger
import program
from paddleslim.dygraph import L1NormFilterPruner

def parse_args():
    parser = argparse.ArgumentParser("PaddleClas train script")
    parser.add_argument(
        '-c',
        '--config',
        type=str,
        default='configs/ResNet/ResNet50.yaml',
        help='config file path')
    parser.add_argument(
        '-o',
        '--override',
        action='append',
        default=[],
        help='config options to be overridden')
    args = parser.parse_args()
    return args

def main(args):
    config = get_config(args.config, overrides=args.override, show=True)
    net = program.create_model(config.ARCHITECTURE, config.classes_num)
    params = {}
    for param in net.parameters():
        if len(param.shape) == 4:
            params[param.name] = 0.5

    pruner = L1NormFilterPruner(net, [1, 3, 32, 32])
    b_FLOPs = paddle.flops(net, input_size=[1, 3, 32, 32])
    plan = pruner.prune_vars(params, axis=0)
    a_FLOPs = paddle.flops(net, input_size=[1, 3, 32, 32])
    ret = (float(b_FLOPs - a_FLOPs) / (b_FLOPs)) * 100
    ret = "model: {}; FLOPs -{:.1f}%\n".format(args.config, ret)
    with open("./test_result", 'a') as f:
        f.write(ret)
    print(ret)

if __name__ == '__main__':
    args = parse_args()
    main(args)
wanghaoshuang commented 3 years ago

supported models in PaddleClas

wanghaoshuang commented 3 years ago

GhostNet结构如下:

image
ChrisMengxl commented 2 years ago

https://github.com/PaddlePaddle/PaddleSlim/issues/976 ResNeXt101_vd_32x4d 参考PaddleClas 模板剪枝报错

请大牛看看是怎么回事。十分感谢。