prune.py 2.3 KB
Newer Older
D
dongshuilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import, division, print_function
import paddle
from ppcls.utils import logger


W
weishengyu 已提交
20
def prune_model(config, model):
D
dongshuilong 已提交
21 22 23 24 25 26 27
    if config.get("Slim", False) and config["Slim"].get("prune", False):
        import paddleslim
        prune_method_name = config["Slim"]["prune"]["name"].lower()
        assert prune_method_name in [
            "fpgm", "l1_norm"
        ], "The prune methods only support 'fpgm' and 'l1_norm'"
        if prune_method_name == "fpgm":
W
weishengyu 已提交
28
            model.pruner = paddleslim.dygraph.FPGMFilterPruner(
D
dongshuilong 已提交
29 30
                model, [1] + config["Global"]["image_shape"])
        else:
W
weishengyu 已提交
31
            model.pruner = paddleslim.dygraph.L1NormFilterPruner(
D
dongshuilong 已提交
32 33 34
                model, [1] + config["Global"]["image_shape"])

        # prune model
W
weishengyu 已提交
35
        _prune_model(config, model)
D
dongshuilong 已提交
36
    else:
W
weishengyu 已提交
37
        model.pruner = None
D
dongshuilong 已提交
38 39 40



W
weishengyu 已提交
41
def _prune_model(config, model):
D
dongshuilong 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54
    from paddleslim.analysis import dygraph_flops as flops
    logger.info("FLOPs before pruning: {}GFLOPs".format(
        flops(model, [1] + config["Global"]["image_shape"]) / 1e9))
    model.eval()

    params = []
    for sublayer in model.sublayers():
        for param in sublayer.parameters(include_sublayers=False):
            if isinstance(sublayer, paddle.nn.Conv2D):
                params.append(param.name)
    ratios = {}
    for param in params:
        ratios[param] = config["Slim"]["prune"]["pruned_ratio"]
W
weishengyu 已提交
55
    plan = model.pruner.prune_vars(ratios, [0])
D
dongshuilong 已提交
56 57 58 59 60 61 62 63 64 65

    logger.info("FLOPs after pruning: {}GFLOPs; pruned ratio: {}".format(
        flops(model, [1] + config["Global"]["image_shape"]) / 1e9,
        plan.pruned_flops))

    for param in model.parameters():
        if "conv2d" in param.name:
            logger.info("{}\t{}".format(param.name, param.shape))

    model.train()