save_quant_model.py 6.3 KB
Newer Older
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.

15
import argparse
16 17
import os
import sys
18 19
import unittest

20 21
import paddle
from paddle.fluid.framework import IrGraph
22 23
from paddle.framework import core
from paddle.static.quantization import Quant2Int8MkldnnPass
24

P
pangyoki 已提交
25 26
paddle.enable_static()

27 28 29

def parse_args():
    parser = argparse.ArgumentParser()
30 31 32 33 34 35 36 37 38 39 40 41
    parser.add_argument(
        '--quant_model_path',
        type=str,
        default='',
        help='A path to a Quant model.',
    )
    parser.add_argument(
        '--int8_model_save_path',
        type=str,
        default='',
        help='Saved optimized and quantized INT8 model',
    )
42
    parser.add_argument(
43
        '--ops_to_quantize',
44 45
        type=str,
        default='',
46
        help='A comma separated list of operators to quantize. Only quantizable operators are taken into account. If the option is not used, an attempt to quantize all quantizable operators will be made.',
47
    )
48 49 50 51
    parser.add_argument(
        '--op_ids_to_skip',
        type=str,
        default='',
52 53 54 55 56 57 58
        help='A comma separated list of operator ids to skip in quantization.',
    )
    parser.add_argument(
        '--debug',
        action='store_true',
        help='If used, the graph of Quant model is drawn.',
    )
59 60 61 62
    parser.add_argument(
        '--quant_model_filename',
        type=str,
        default="",
63
        help='The input model`s file name. If empty, search default `__model__` and separate parameter files and use them or in case if not found, attempt loading `model` and `params` files.',
64 65 66 67 68
    )
    parser.add_argument(
        '--quant_params_filename',
        type=str,
        default="",
69
        help='If quant_model_filename is empty, this field is ignored. The input model`s all parameters file name. If empty load parameters from separate files.',
70 71 72 73 74
    )
    parser.add_argument(
        '--save_model_filename',
        type=str,
        default="__model__",
75
        help='The name of file to save the inference program itself. If is set None, a default filename __model__ will be used.',
76 77 78 79 80
    )
    parser.add_argument(
        '--save_params_filename',
        type=str,
        default=None,
81
        help='The name of file to save all related parameters. If it is set None, parameters will be saved in separate files',
82
    )
83 84 85 86 87

    test_args, args = parser.parse_known_args(namespace=unittest)
    return test_args, sys.argv[:1] + args


88 89 90 91 92 93 94 95
def transform_and_save_int8_model(
    original_path,
    save_path,
    ops_to_quantize='',
    op_ids_to_skip='',
    debug=False,
    quant_model_filename='',
    quant_params_filename='',
96
    save_model_filename="model",
97 98
    save_params_filename=None,
):
99 100 101 102
    place = paddle.CPUPlace()
    exe = paddle.static.Executor(place)
    inference_scope = paddle.static.global_scope()
    with paddle.static.scope_guard(inference_scope):
103 104
        if not quant_model_filename:
            if os.path.exists(os.path.join(original_path, '__model__')):
105 106 107 108
                [
                    inference_program,
                    feed_target_names,
                    fetch_targets,
109
                ] = paddle.fluid.io.load_inference_model(original_path, exe)
110
            else:
111 112 113 114
                [
                    inference_program,
                    feed_target_names,
                    fetch_targets,
115 116 117 118 119
                ] = paddle.static.load_inference_model(
                    original_path,
                    exe,
                    model_filename='model',
                    params_filename='params',
120
                )
121
        else:
122 123 124 125
            [
                inference_program,
                feed_target_names,
                fetch_targets,
126 127 128 129 130
            ] = paddle.static.load_inference_model(
                original_path,
                exe,
                model_filename=quant_model_filename,
                params_filename=quant_params_filename,
131
            )
132

133 134 135 136
        ops_to_quantize_set = set()
        print(ops_to_quantize)
        if len(ops_to_quantize) > 0:
            ops_to_quantize_set = set(ops_to_quantize.split(','))
137

138 139 140 141
        op_ids_to_skip_set = set([-1])
        print(op_ids_to_skip)
        if len(op_ids_to_skip) > 0:
            op_ids_to_skip_set = set(map(int, op_ids_to_skip.split(',')))
142 143

        graph = IrGraph(core.Graph(inference_program.desc), for_test=True)
144
        if debug:
W
Wojciech Uss 已提交
145 146
            graph.draw('.', 'quant_orig', graph.all_op_nodes())
        transform_to_mkldnn_int8_pass = Quant2Int8MkldnnPass(
147 148
            ops_to_quantize_set,
            _op_ids_to_skip=op_ids_to_skip_set,
149 150 151
            _scope=inference_scope,
            _place=place,
            _core=core,
152 153
            _debug=debug,
        )
W
Wojciech Uss 已提交
154
        graph = transform_to_mkldnn_int8_pass.apply(graph)
155
        inference_program = graph.to_program()
156 157 158 159 160 161 162 163 164
        with paddle.static.scope_guard(inference_scope):
            path_prefix = os.path.join(save_path, save_model_filename)
            feed_vars = [
                inference_program.global_block().var(name)
                for name in feed_target_names
            ]
            paddle.static.save_inference_model(
                path_prefix,
                feed_vars,
165
                fetch_targets,
166 167
                executor=exe,
                program=inference_program,
168
            )
W
Wojciech Uss 已提交
169
        print(
170 171 172 173
            "Success! INT8 model obtained from the Quant model can be found at {}\n".format(
                save_path
            )
        )
174 175 176 177 178


if __name__ == '__main__':
    global test_args
    test_args, remaining_args = parse_args()
179
    transform_and_save_int8_model(
180 181 182 183 184 185 186 187 188 189
        test_args.quant_model_path,
        test_args.int8_model_save_path,
        test_args.ops_to_quantize,
        test_args.op_ids_to_skip,
        test_args.debug,
        test_args.quant_model_filename,
        test_args.quant_params_filename,
        test_args.save_model_filename,
        test_args.save_params_filename,
    )