prune_config.py 15.4 KB
Newer Older
M
mamingjie-China 已提交
1
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
J
jiangjiajun 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# 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.

import numpy as np
import os.path as osp
import paddle.fluid as fluid
J
jiangjiajun 已提交
18
#import paddlehub as hub
J
jiangjiajun 已提交
19 20 21
import paddlex

sensitivities_data = {
S
sunyanfang01 已提交
22 23
    'AlexNet':
    'https://bj.bcebos.com/paddlex/slim_prune/alexnet_sensitivities.data',
J
jiangjiajun 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
    'ResNet18':
    'https://bj.bcebos.com/paddlex/slim_prune/resnet18.sensitivities',
    'ResNet34':
    'https://bj.bcebos.com/paddlex/slim_prune/resnet34.sensitivities',
    'ResNet50':
    'https://bj.bcebos.com/paddlex/slim_prune/resnet50.sensitivities',
    'ResNet101':
    'https://bj.bcebos.com/paddlex/slim_prune/resnet101.sensitivities',
    'ResNet50_vd':
    'https://bj.bcebos.com/paddlex/slim_prune/resnet50vd.sensitivities',
    'ResNet101_vd':
    'https://bj.bcebos.com/paddlex/slim_prune/resnet101vd.sensitivities',
    'DarkNet53':
    'https://bj.bcebos.com/paddlex/slim_prune/darknet53.sensitivities',
    'MobileNetV1':
    'https://bj.bcebos.com/paddlex/slim_prune/mobilenetv1.sensitivities',
    'MobileNetV2':
    'https://bj.bcebos.com/paddlex/slim_prune/mobilenetv2.sensitivities',
    'MobileNetV3_large':
    'https://bj.bcebos.com/paddlex/slim_prune/mobilenetv3_large.sensitivities',
    'MobileNetV3_small':
    'https://bj.bcebos.com/paddlex/slim_prune/mobilenetv3_small.sensitivities',
S
sunyanfang01 已提交
46 47 48 49
    'MobileNetV3_large_ssld':
    'https://bj.bcebos.com/paddlex/slim_prune/mobilenetv3_large_ssld_sensitivities.data',
    'MobileNetV3_small_ssld':
    'https://bj.bcebos.com/paddlex/slim_prune/mobilenetv3_small_ssld_sensitivities.data',
J
jiangjiajun 已提交
50 51 52 53 54 55 56 57 58 59
    'DenseNet121':
    'https://bj.bcebos.com/paddlex/slim_prune/densenet121.sensitivities',
    'DenseNet161':
    'https://bj.bcebos.com/paddlex/slim_prune/densenet161.sensitivities',
    'DenseNet201':
    'https://bj.bcebos.com/paddlex/slim_prune/densenet201.sensitivities',
    'Xception41':
    'https://bj.bcebos.com/paddlex/slim_prune/xception41.sensitivities',
    'Xception65':
    'https://bj.bcebos.com/paddlex/slim_prune/xception65.sensitivities',
S
sunyanfang01 已提交
60 61
    'ShuffleNetV2':
    'https://bj.bcebos.com/paddlex/slim_prune/shufflenetv2_sensitivities.data',
J
jiangjiajun 已提交
62 63 64 65 66 67 68 69
    'YOLOv3_MobileNetV1':
    'https://bj.bcebos.com/paddlex/slim_prune/yolov3_mobilenetv1.sensitivities',
    'YOLOv3_MobileNetV3_large':
    'https://bj.bcebos.com/paddlex/slim_prune/yolov3_mobilenetv3.sensitivities',
    'YOLOv3_DarkNet53':
    'https://bj.bcebos.com/paddlex/slim_prune/yolov3_darknet53.sensitivities',
    'YOLOv3_ResNet34':
    'https://bj.bcebos.com/paddlex/slim_prune/yolov3_resnet34.sensitivities',
70
    'UNet': 'https://bj.bcebos.com/paddlex/slim_prune/unet.sensitivities',
J
jiangjiajun 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    'DeepLabv3p_MobileNetV2_x0.25':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x0.25_no_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x0.5':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x0.5_no_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x1.0':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x1.0_no_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x1.5':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x1.5_no_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x2.0':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x2.0_no_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x0.25_aspp_decoder':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x0.25_with_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x0.5_aspp_decoder':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x0.5_with_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x1.0_aspp_decoder':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x1.0_with_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x1.5_aspp_decoder':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x1.5_with_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x2.0_aspp_decoder':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x2.0_with_aspp_decoder.sensitivities',
    'DeepLabv3p_Xception65_aspp_decoder':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_xception65_with_aspp_decoder.sensitivities',
    'DeepLabv3p_Xception41_aspp_decoder':
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_xception41_with_aspp_decoder.sensitivities',
    'HRNet_W18_Seg':
    'https://bj.bcebos.com/paddlex/slim_prune/hrnet_w18.sensitivities',
    'HRNet_W30_Seg':
    'https://bj.bcebos.com/paddlex/slim_prune/hrnet_w30.sensitivities',
    'HRNet_W32_Seg':
    'https://bj.bcebos.com/paddlex/slim_prune/hrnet_w32.sensitivities',
    'HRNet_W40_Seg':
    'https://bj.bcebos.com/paddlex/slim_prune/hrnet_w40.sensitivities',
    'HRNet_W44_Seg':
    'https://bj.bcebos.com/paddlex/slim_prune/hrnet_w44.sensitivities',
    'HRNet_W48_Seg':
    'https://bj.bcebos.com/paddlex/slim_prune/hrnet_w48.sensitivities',
    'HRNet_W64_Seg':
    'https://bj.bcebos.com/paddlex/slim_prune/hrnet_w64.sensitivities',
    'FastSCNN':
    'https://bj.bcebos.com/paddlex/slim_prune/fast_scnn.sensitivities'
J
jiangjiajun 已提交
111 112 113 114 115 116 117 118 119 120
}


def get_sensitivities(flag, model, save_dir):
    model_name = model.__class__.__name__
    model_type = model_name
    if hasattr(model, 'backbone'):
        model_type = model_name + '_' + model.backbone
    if model_type.startswith('DeepLabv3p_Xception'):
        model_type = model_type + '_' + 'aspp' + '_' + 'decoder'
121 122
    elif hasattr(model, 'encoder_with_aspp') or hasattr(model,
                                                        'enable_decoder'):
J
jiangjiajun 已提交
123
        model_type = model_type + '_' + 'aspp' + '_' + 'decoder'
124 125
    if model_type.startswith('HRNet') and model.model_type == 'segmenter':
        model_type = '{}_W{}_Seg'.format(model_type, model.width)
J
jiangjiajun 已提交
126 127 128 129 130 131 132
    if osp.isfile(flag):
        return flag
    elif flag == 'DEFAULT':
        assert model_type in sensitivities_data, "There is not sensitivities data file for {}, you may need to calculate it by your self.".format(
            model_type)
        url = sensitivities_data[model_type]
        fname = osp.split(url)[-1]
J
jiangjiajun 已提交
133
        paddlex.utils.download(url, path=save_dir)
J
jiangjiajun 已提交
134
        return osp.join(save_dir, fname)
J
jiangjiajun 已提交
135 136 137 138 139 140 141 142 143 144

#        try:
#            hub.download(fname, save_path=save_dir)
#        except Exception as e:
#            if isinstance(e, hub.ResourceNotFoundError):
#                raise Exception(
#                    "Resource for model {}(key='{}') not found".format(
#                        model_type, fname))
#            elif isinstance(e, hub.ServerConnectionError):
#                raise Exception(
145
#                    "Cannot get reource for model {}(key='{}'), please check your internet connection"
J
jiangjiajun 已提交
146 147 148 149 150 151
#                    .format(model_type, fname))
#            else:
#                raise Exception(
#                    "Unexpected error, please make sure paddlehub >= 1.6.2 {}".
#                    format(str(e)))
#        return osp.join(save_dir, fname)
J
jiangjiajun 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    else:
        raise Exception(
            "sensitivities need to be defined as directory path or `DEFAULT`(download sensitivities automatically)."
        )


def get_prune_params(model):
    prune_names = []
    model_type = model.__class__.__name__
    if model_type == 'BaseClassifier':
        model_type = model.model_name
    if hasattr(model, 'backbone'):
        backbone = model.backbone
        model_type += ('_' + backbone)
    program = model.test_prog
    if model_type.startswith('ResNet') or \
            model_type.startswith('DenseNet') or \
S
sunyanfang01 已提交
169
            model_type.startswith('DarkNet') or \
S
sunyanfang01 已提交
170 171
            model_type.startswith('AlexNet') or \
            model_type.startswith('ShuffleNetV2'):
J
jiangjiajun 已提交
172 173 174 175 176 177
        for block in program.blocks:
            for param in block.all_parameters():
                pd_var = fluid.global_scope().find_var(param.name)
                pd_param = pd_var.get_tensor()
                if len(np.array(pd_param).shape) == 4:
                    prune_names.append(param.name)
S
sunyanfang01 已提交
178 179
        if model_type == 'AlexNet':
            prune_names.remove('conv5_weights')
S
sunyanfang01 已提交
180
        if model_type == 'ShuffleNetV2':
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
            not_prune_names = [
                'stage_2_1_conv5_weights',
                'stage_2_1_conv3_weights',
                'stage_2_2_conv3_weights',
                'stage_2_3_conv3_weights',
                'stage_2_4_conv3_weights',
                'stage_3_1_conv5_weights',
                'stage_3_1_conv3_weights',
                'stage_3_2_conv3_weights',
                'stage_3_3_conv3_weights',
                'stage_3_4_conv3_weights',
                'stage_3_5_conv3_weights',
                'stage_3_6_conv3_weights',
                'stage_3_7_conv3_weights',
                'stage_3_8_conv3_weights',
                'stage_4_1_conv5_weights',
                'stage_4_1_conv3_weights',
                'stage_4_2_conv3_weights',
                'stage_4_3_conv3_weights',
                'stage_4_4_conv3_weights',
            ]
S
sunyanfang01 已提交
202
            for name in not_prune_names:
203
                prune_names.remove(name)
J
jiangjiajun 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216
    elif model_type == "MobileNetV1":
        prune_names.append("conv1_weights")
        for param in program.global_block().all_parameters():
            if "_sep_weights" in param.name:
                prune_names.append(param.name)
    elif model_type == "MobileNetV2":
        for param in program.global_block().all_parameters():
            if 'weight' not in param.name \
                    or 'dwise' in param.name \
                    or 'fc' in param.name :
                continue
            prune_names.append(param.name)
    elif model_type.startswith("MobileNetV3"):
S
sunyanfang01 已提交
217
        if model_type.startswith('MobileNetV3_small'):
J
jiangjiajun 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
            expand_prune_id = [3, 4]
        else:
            expand_prune_id = [2, 3, 4, 8, 9, 11]
        for param in program.global_block().all_parameters():
            if ('expand_weights' in param.name and \
                    int(param.name.split('_')[0][4:]) in expand_prune_id)\
                    or 'linear_weights' in param.name \
                    or 'se_1_weights' in param.name:
                prune_names.append(param.name)
    elif model_type.startswith('Xception') or \
            model_type.startswith('DeepLabv3p_Xception'):
        params_not_prune = [
            'weights',
            'xception_{}/exit_flow/block2/separable_conv3/pointwise/weights'.
            format(model_type[-2:]), 'encoder/concat/weights',
            'decoder/concat/weights'
        ]
        for param in program.global_block().all_parameters():
            if 'weight' not in param.name \
                    or 'dwise' in param.name \
                    or 'depthwise' in param.name \
                    or 'logit' in param.name:
                continue
            if param.name in params_not_prune:
                continue
            prune_names.append(param.name)
    elif model_type.startswith('YOLOv3'):
        for block in program.blocks:
            for param in block.all_parameters():
                if 'weights' in param.name and 'yolo_block' in param.name:
                    prune_names.append(param.name)
    elif model_type.startswith('UNet'):
        for param in program.global_block().all_parameters():
            if 'weight' not in param.name:
                continue
            if 'logit' in param.name:
                continue
            prune_names.append(param.name)
        params_not_prune = [
            'encode/block4/down/conv1/weights',
            'encode/block3/down/conv1/weights',
            'encode/block2/down/conv1/weights', 'encode/block1/conv1/weights'
        ]
        for i in params_not_prune:
            if i in prune_names:
                prune_names.remove(i)
264 265

    elif model_type.startswith('HRNet') and model.model_type == 'segmenter':
C
chenguowei01 已提交
266 267 268 269
        for param in program.global_block().all_parameters():
            if 'weight' not in param.name:
                continue
            prune_names.append(param.name)
270
        params_not_prune = ['conv-1_weights']
C
chenguowei01 已提交
271 272 273
        for i in params_not_prune:
            if i in prune_names:
                prune_names.remove(i)
274

C
chenguowei01 已提交
275 276 277 278 279 280 281
    elif model_type.startswith('FastSCNN'):
        for param in program.global_block().all_parameters():
            if 'weight' not in param.name:
                continue
            if 'dwise' in param.name or 'depthwise' in param.name or 'logit' in param.name:
                continue
            prune_names.append(param.name)
282
        params_not_prune = ['classifier/weights']
C
chenguowei01 已提交
283 284 285
        for i in params_not_prune:
            if i in prune_names:
                prune_names.remove(i)
J
jiangjiajun 已提交
286 287

    elif model_type.startswith('DeepLabv3p'):
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
        if model_type.lower() == "deeplabv3p_mobilenetv3_large_x1_0_ssld":
            params_not_prune = [
                'last_1x1_conv_weights', 'conv14_se_2_weights',
                'conv16_depthwise_weights', 'conv13_depthwise_weights',
                'conv15_se_2_weights', 'conv2_depthwise_weights',
                'conv6_depthwise_weights', 'conv8_depthwise_weights',
                'fc_weights', 'conv3_depthwise_weights', 'conv7_se_2_weights',
                'conv16_expand_weights', 'conv16_se_2_weights',
                'conv10_depthwise_weights', 'conv11_depthwise_weights',
                'conv15_expand_weights', 'conv5_expand_weights',
                'conv15_depthwise_weights', 'conv14_depthwise_weights',
                'conv12_se_2_weights', 'conv1_weights',
                'conv13_expand_weights', 'conv_last_weights',
                'conv12_depthwise_weights', 'conv13_se_2_weights',
                'conv12_expand_weights', 'conv5_depthwise_weights',
                'conv6_se_2_weights', 'conv10_expand_weights',
                'conv9_depthwise_weights', 'conv6_expand_weights',
                'conv5_se_2_weights', 'conv14_expand_weights',
                'conv4_depthwise_weights', 'conv7_expand_weights',
307 308 309
                'conv7_depthwise_weights', 'encoder/aspp0/weights',
                'decoder/merge/weights', 'encoder/image_pool/weights',
                'decoder/weights'
310
            ]
J
jiangjiajun 已提交
311 312 313 314 315
        for param in program.global_block().all_parameters():
            if 'weight' not in param.name:
                continue
            if 'dwise' in param.name or 'depthwise' in param.name or 'logit' in param.name:
                continue
316 317 318
            if model_type.lower() == "deeplabv3p_mobilenetv3_large_x1_0_ssld":
                if param.name in params_not_prune:
                    continue
J
jiangjiajun 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
            prune_names.append(param.name)
        params_not_prune = [
            'xception_{}/exit_flow/block2/separable_conv3/pointwise/weights'.
            format(model_type[-2:]), 'encoder/concat/weights',
            'decoder/concat/weights'
        ]
        if model.encoder_with_aspp == True:
            params_not_prune.append(
                'xception_{}/exit_flow/block2/separable_conv3/pointwise/weights'
                .format(model_type[-2:]))
            params_not_prune.append('conv8_1_linear_weights')
        for i in params_not_prune:
            if i in prune_names:
                prune_names.remove(i)
    else:
        raise Exception('The {} is not implement yet!'.format(model_type))
    return prune_names