sensitive.py 6.7 KB
Newer Older
W
wanghaoshuang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2019  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.

W
wanghaoshuang 已提交
15 16
import sys
import os
17
import logging
W
wanghaoshuang 已提交
18
import pickle
W
wanghaoshuang 已提交
19
import numpy as np
W
wanghaoshuang 已提交
20
import paddle.fluid as fluid
W
wanghaoshuang 已提交
21
from ..core import GraphWrapper
22
from ..common import get_logger
23
from ..analysis import flops
W
wanghaoshuang 已提交
24
from ..prune import Pruner
25 26

_logger = get_logger(__name__, level=logging.INFO)
W
wanghaoshuang 已提交
27

28
__all__ = ["sensitivity", "flops_sensitivity"]
W
wanghaoshuang 已提交
29 30 31


def sensitivity(program,
W
wanghaoshuang 已提交
32
                place,
W
wanghaoshuang 已提交
33 34
                param_names,
                eval_func,
W
wanghaoshuang 已提交
35
                sensitivities_file=None,
36
                pruned_ratios=None):
W
wanghaoshuang 已提交
37
    scope = fluid.global_scope()
W
wanghaoshuang 已提交
38 39 40
    graph = GraphWrapper(program)
    sensitivities = _load_sensitivities(sensitivities_file)

41 42 43
    if pruned_ratios is None:
        pruned_ratios = np.arange(0.1, 1, step=0.1)

W
wanghaoshuang 已提交
44 45 46 47 48 49 50 51 52 53
    for name in param_names:
        if name not in sensitivities:
            size = graph.var(name).shape()[0]
            sensitivities[name] = {
                'pruned_percent': [],
                'loss': [],
                'size': size
            }
    baseline = None
    for name in sensitivities:
54
        for ratio in pruned_ratios:
W
wanghaoshuang 已提交
55
            if ratio in sensitivities[name]['pruned_percent']:
W
wanghaoshuang 已提交
56 57 58
                _logger.debug('{}, {} has computed.'.format(name, ratio))
                continue
            if baseline is None:
W
wanghaoshuang 已提交
59
                baseline = eval_func(graph.program)
W
wanghaoshuang 已提交
60 61

            pruner = Pruner()
W
wanghaoshuang 已提交
62 63
            _logger.info("sensitive - param: {}; ratios: {}".format(name,
                                                                    ratio))
W
wanghaoshuang 已提交
64
            pruned_program, param_backup, _ = pruner.prune(
W
wanghaoshuang 已提交
65 66 67 68 69 70 71
                program=graph.program,
                scope=scope,
                params=[name],
                ratios=[ratio],
                place=place,
                lazy=True,
                only_graph=False,
W
wanghaoshuang 已提交
72
                param_backup=True)
W
wanghaoshuang 已提交
73
            pruned_metric = eval_func(pruned_program)
W
wanghaoshuang 已提交
74 75 76
            loss = (baseline - pruned_metric) / baseline
            _logger.info("pruned param: {}; {}; loss={}".format(name, ratio,
                                                                loss))
W
wanghaoshuang 已提交
77

W
wanghaoshuang 已提交
78 79
            sensitivities[name]['pruned_percent'].append(ratio)
            sensitivities[name]['loss'].append(loss)
W
wanghaoshuang 已提交
80

W
wanghaoshuang 已提交
81 82 83 84 85 86
            _save_sensitivities(sensitivities, sensitivities_file)

            # restore pruned parameters
            for param_name in param_backup.keys():
                param_t = scope.find_var(param_name).get_tensor()
                param_t.set(param_backup[param_name], place)
W
wanghaoshuang 已提交
87
    return sensitivities
W
wanghaoshuang 已提交
88 89


90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
def flops_sensitivity(program,
                      place,
                      param_names,
                      eval_func,
                      sensitivities_file=None,
                      pruned_flops_rate=0.1):

    assert (1.0 / len(param_names) > pruned_flops_rate)

    scope = fluid.global_scope()
    graph = GraphWrapper(program)
    sensitivities = _load_sensitivities(sensitivities_file)

    for name in param_names:
        if name not in sensitivities:
            size = graph.var(name).shape()[0]
            sensitivities[name] = {
                'pruned_percent': [],
                'loss': [],
                'size': size
            }
    base_flops = flops(program)
    target_pruned_flops = base_flops * pruned_flops_rate

    pruner = Pruner()
    baseline = None
    for name in sensitivities:

W
wanghaoshuang 已提交
118
        pruned_program, _, _ = pruner.prune(
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
            program=graph.program,
            scope=None,
            params=[name],
            ratios=[0.5],
            place=None,
            lazy=False,
            only_graph=True)
        param_flops = (base_flops - flops(pruned_program)) * 2
        channel_size = sensitivities[name]["size"]
        pruned_ratio = target_pruned_flops / float(param_flops)
        pruned_size = round(pruned_ratio * channel_size)
        pruned_ratio = 1 if pruned_size >= channel_size else pruned_ratio

        if len(sensitivities[name]["pruned_percent"]) > 0:
            _logger.debug('{} exist; pruned ratio: {}; excepted ratio: {}'.
                          format(name, sensitivities[name]["pruned_percent"][
                              0], pruned_ratio))
            continue
        if baseline is None:
            baseline = eval_func(graph.program)
        param_backup = {}
        pruner = Pruner()
        _logger.info("sensitive - param: {}; ratios: {}".format(name,
                                                                pruned_ratio))
        loss = 1
        if pruned_ratio < 1:
            pruned_program = pruner.prune(
                program=graph.program,
                scope=scope,
                params=[name],
                ratios=[pruned_ratio],
                place=place,
                lazy=True,
                only_graph=False,
                param_backup=param_backup)
            pruned_metric = eval_func(pruned_program)
            loss = (baseline - pruned_metric) / baseline
        _logger.info("pruned param: {}; {}; loss={}".format(name, pruned_ratio,
                                                            loss))
        sensitivities[name]['pruned_percent'].append(pruned_ratio)
        sensitivities[name]['loss'].append(loss)
        _save_sensitivities(sensitivities, sensitivities_file)

        # restore pruned parameters
        for param_name in param_backup.keys():
            param_t = scope.find_var(param_name).get_tensor()
            param_t.set(param_backup[param_name], place)
    return sensitivities


W
wanghaoshuang 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
def _load_sensitivities(sensitivities_file):
    """
    Load sensitivities from file.
    """
    sensitivities = {}
    if sensitivities_file and os.path.exists(sensitivities_file):
        with open(sensitivities_file, 'rb') as f:
            if sys.version_info < (3, 0):
                sensitivities = pickle.load(f)
            else:
                sensitivities = pickle.load(f, encoding='bytes')

    for param in sensitivities:
        sensitivities[param]['pruned_percent'] = [
            round(p, 2) for p in sensitivities[param]['pruned_percent']
        ]
    return sensitivities
W
wanghaoshuang 已提交
186 187 188 189 190 191 192 193


def _save_sensitivities(sensitivities, sensitivities_file):
    """
        Save sensitivities into file.
        """
    with open(sensitivities_file, 'wb') as f:
        pickle.dump(sensitivities, f)