models icon indicating copy to clipboard operation
models copied to clipboard

[PaddleSlim] mobilenet_v1_ssd剪裁率是0

Open ZiruiChen opened this issue 7 years ago • 24 comments

image 如图 pruned size 和pruned flops 是0 没有剪裁效果

ZiruiChen avatar Aug 14 '19 10:08 ZiruiChen

image 附上config

ZiruiChen avatar Aug 14 '19 10:08 ZiruiChen

image pruned_params: '*._sep_weights' 的原因

ZiruiChen avatar Aug 14 '19 10:08 ZiruiChen

@wanghaoshuang

ZiruiChen avatar Aug 14 '19 10:08 ZiruiChen

@wzzju

ZiruiChen avatar Aug 14 '19 10:08 ZiruiChen

https://github.com/PaddlePaddle/models/issues/2985#issue-475066410

ZiruiChen avatar Aug 14 '19 14:08 ZiruiChen

image 尝试改变pruned_params 可以剪裁第一步 之后报错 image image

ZiruiChen avatar Aug 14 '19 14:08 ZiruiChen

在你的配置文件中,需要改下quatization_strategy的start_epoch, 让quatization_strategy在prune_strategy之后一个epoch执行。

而且从效果上看,剪裁之后,一定要先训练几个epoch再做量化训练。

非常抱歉,我们会根据您的反馈完善下文档。

wanghaoshuang avatar Aug 15 '19 11:08 wanghaoshuang

在你的配置文件中,需要改下quatization_strategy的start_epoch, 让quatization_strategy在prune_strategy之后一个epoch执行。

而且从效果上看,剪裁之后,一定要先训练几个epoch再做量化训练。

非常抱歉,我们会根据您的反馈完善下文档。

好的 但是修改了epoch之后 剪裁效果还是0呢 希望完善剪裁策略后能通知下我

ZiruiChen avatar Aug 16 '19 01:08 ZiruiChen

# step1: Pruning at epoch-0
# step2: Fine-tune at epoch-0
# step3: Quantization training from epoch-1 to epoch-2
version: 1.0
pruners:
    pruner_1:
        class: 'StructurePruner'
        pruning_axis:
            '*': 0
        criterions:
            '*': 'l1_norm'
strategies:
    uniform_pruning_strategy:
        class: 'UniformPruneStrategy'
        pruner: 'pruner_1'
        start_epoch: 0
        target_ratio: 0.5
        pruned_params: '.*_sep_weights'
        metric_name: 'acc_top1'
    quantization_strategy:
        class: 'QuantizationStrategy'
        start_epoch: 1
        end_epoch: 2
        float_model_save_path: './output/float'
        mobile_model_save_path: './output/mobile'
        int8_model_save_path: './output/int8'
        weight_bits: 8
        activation_bits: 8
        weight_quantize_type: 'abs_max'
        activation_quantize_type: 'abs_max'
compressor:
    epoch: 3
    #init_model: './checkpoints/0' # Please enable this option for loading checkpoint.
    checkpoint_path: './checkpoints/'
    strategies:
        - uniform_pruning_strategy
        - quantization_strategy

你可以按以上配置试一下,或这你把你修改epoch后的配置贴一下?

wanghaoshuang avatar Aug 16 '19 03:08 wanghaoshuang

这个配置剪裁也是0 你可以在这个代码上用剪裁的config测试 https://aistudio.baidu.com/aistudio/projectdetail/86232 我也是在这用的

# step1: Pruning at epoch-0
# step2: Fine-tune at epoch-0
# step3: Quantization training from epoch-1 to epoch-2
version: 1.0
pruners:
    pruner_1:
        class: 'StructurePruner'
        pruning_axis:
            '*': 0
        criterions:
            '*': 'l1_norm'
strategies:
    uniform_pruning_strategy:
        class: 'UniformPruneStrategy'
        pruner: 'pruner_1'
        start_epoch: 0
        target_ratio: 0.5
        pruned_params: '.*_sep_weights'
        metric_name: 'acc_top1'
    quantization_strategy:
        class: 'QuantizationStrategy'
        start_epoch: 1
        end_epoch: 2
        float_model_save_path: './output/float'
        mobile_model_save_path: './output/mobile'
        int8_model_save_path: './output/int8'
        weight_bits: 8
        activation_bits: 8
        weight_quantize_type: 'abs_max'
        activation_quantize_type: 'abs_max'
compressor:
    epoch: 3
    #init_model: './checkpoints/0' # Please enable this option for loading checkpoint.
    checkpoint_path: './checkpoints/'
    strategies:
        - uniform_pruning_strategy
        - quantization_strategy

你可以按以上配置试一下,或这你把你修改epoch后的配置贴一下?

ZiruiChen avatar Aug 16 '19 04:08 ZiruiChen

@wanghaoshuang 所以是paddleslim还剪裁不了这个ssd模型吗

ZiruiChen avatar Aug 19 '19 06:08 ZiruiChen

image 同样的问题,裁剪的flops和size均为0.

config使用提供的示例文件 https://github.com/PaddlePaddle/models/blob/develop/PaddleSlim/configs/filter_pruning_uniform.yaml https://github.com/PaddlePaddle/models/blob/develop/PaddleSlim/configs/filter_pruning_sen.yaml

zzchust avatar Aug 19 '19 14:08 zzchust

@ZiruiChen @zzchust 抱歉,PaddleSlim中的剪切功能依赖网络中parameters的命名。 models repo中release的配置只适用于MobileNetV1中parameter的命名,在MobileNet-SSD网络中,MobileNet部分的parameter的命名可能有变化,所以默认的配置匹配不到要裁剪parameters。

您可以通过以下方式查看您所定义网络的所有parameters的名称。

program = fluid.default_main_program() // 或其它用户自定义的program
for param in program.global_block().all_parameters():
    print("param name: {}".format(param.name))

wanghaoshuang avatar Aug 20 '19 00:08 wanghaoshuang

https://github.com/PaddlePaddle/models/issues/2985#issuecomment-522805443

wanghaoshuang avatar Aug 20 '19 00:08 wanghaoshuang

@wanghaoshuang 所以是paddleslim还剪裁不了这个ssd模型吗

理论上是支持裁剪的,只是需要先看下ssd中各层parameters的名称,然后设置合适的pruned_params.

wanghaoshuang avatar Aug 20 '19 00:08 wanghaoshuang

@wanghaoshuang 辛苦回复! 昨天发现了这个问题。

@ZiruiChen 大家如果急需在mobilenet-ssd的剪枝功能,有两点: 1)可以将mobilenet-ssd的backbone修改为image_classification中的mobilenet.py这样剪枝参数'.*_sep_weights'就是符合预期的,只是这样就没有在coco上预训练的模型了。 2)load当前mobilenet-ssd的pretrain参数,然后修改每层参数的命名,将要修改的参数统一加上"sep_weights'"的后缀。 (这个地方我不是很熟悉怎么改)

zzchust avatar Aug 20 '19 02:08 zzchust

@wanghaoshuang 通过构建名称对合适的层剪切之后用score.py 跑会有shape error 的报错

Accumulating evaluation results... DONE (t=17.31s). Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.000 Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.000 Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.000 Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.000 Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.000 Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.000 Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.003 Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.005 Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.005 Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.000 Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.001 Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.011 Traceback (most recent call last): File "score.py", line 162, in score, mAP, flops = compute_score(args.model_dir, args.data_dir, batch_size=args.batch_size) File "score.py", line 137, in compute_score total_flops_params, is_quantize = summary(infer_program) File "./utils.py", line 77, in summary spf_res = _summary_model(block_vars, one_op) File "./utils.py", line 112, in summary_model assert c_out == c_out, 'shape error!' AssertionError: shape error!

ZiruiChen avatar Aug 20 '19 14:08 ZiruiChen

mobilenetSSD用该方法保存模型 依旧有shape error的问题

关于infer的问题: 以下代码为保存剪枝后的MobileNetV1模型,然后再做infer

保存模型

    com_pass = Compressor(
        place,
        fluid.global_scope(),
        fluid.default_main_program(),
        train_reader=train_reader,
        train_feed_list=train_feed_list,
        train_fetch_list=train_fetch_list,
        eval_program=val_program,
        eval_reader=val_reader,
        eval_feed_list=val_feed_list,
        eval_fetch_list=val_fetch_list,
        teacher_programs=teacher_programs,
        train_optimizer=opt,
        distiller_optimizer=distiller_optimizer)
    com_pass.config(args.compress_config)
    com_pass.run()

    pruned_prog = com_pass.eval_graph.program

    fluid.io.save_inference_model("./pruned_model/", [image.name, label.name], [acc_top1], exe, main_program=pruned_prog)
    
    # check the shape of parameters
    for param in pruned_prog.global_block().all_parameters():
        print("name: {}; shape: {}".format(param.name, param.shape))

load inference model

以下代码修改自:https://github.com/PaddlePaddle/models/blob/develop/PaddleCV/image_classification/infer.py

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

import os
import time
import sys
import math
import numpy as np
import argparse
import functools

import paddle
import paddle.fluid as fluid
import reader_cv2 as reader
import models
import utils
from utils.utility import add_arguments, print_arguments, check_gpu

parser = argparse.ArgumentParser(description=__doc__)
# yapf: disable
add_arg = functools.partial(add_arguments, argparser=parser)
add_arg('use_gpu',          bool, True,                 "Whether to use GPU or not.")
add_arg('class_dim',        int,  1000,                 "Class number.")
add_arg('image_shape',      str,  "3,224,224",          "Input image size")
add_arg('resize_short_size', int, 256,                  "Set resize short size")
# yapf: enable


def infer(args):
    place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()
    exe = fluid.Executor(place)
    [inference_program, feed_target_names, fetch_targets] = fluid.io.load_inference_model("/root/workspace/models/PaddleSlim/pruned_model", exe)
    test_batch_size = 1
    test_reader = reader.val(settings=args, batch_size=test_batch_size)
    feeder = fluid.DataFeeder(place=place, feed_list=feed_target_names, program=inference_program)
    TOPK = 1
    for batch_id, data in enumerate(test_reader()):
        result = exe.run(inference_program,
                         fetch_list=fetch_targets,
                         feed=feeder.feed(data))
        print(result)
        sys.stdout.flush()
def main():
    args = parser.parse_args()
    print_arguments(args)
    check_gpu(args.use_gpu)
    infer(args)


if __name__ == '__main__':
    main()

输出如下:

[array([0.], dtype=float32)]
[array([0.], dtype=float32)]
[array([0.], dtype=float32)]
[array([0.], dtype=float32)]
...

后续,我们会再实验下MobileNetSSD。

ZiruiChen avatar Aug 21 '19 05:08 ZiruiChen

麻烦 @slf12 在检测模型上验证下save_inference_model和load_inference_model的流程?

wanghaoshuang avatar Aug 21 '19 07:08 wanghaoshuang

我试了下在mobilenet_yolov3检测模型上进行剪切,剪切参数设置为‘conv2.*_sep_weights', 剪切率设为0.01, 通过查看参数,conv2_1_sep_weights从(64,32,1,1)剪为(32,32,1,1),conv2_2_sep_weights从(128,64,1,1)剪为(64, 32,1,1),由此可见,裁剪是可以正常工作的。

然后通过save_inference_model保存模型, image 可以正常保存,

加载load_inference_model进行inference,可以正常运行拿到检测的bbox输出。 image

所以save_inference_model和load_inference_model的流程是可以走通的。

slf12 avatar Aug 22 '19 03:08 slf12