save_quant_model.py 4.1 KB
Newer Older
C
cc 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#   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.

import unittest
import os
import sys
import argparse
import logging
import struct
import six
import numpy as np
import time
import paddle
from paddle.fluid.framework import IrGraph
Z
zhouzj 已提交
26
from paddle.static.quantization import Quant2Int8MkldnnPass
W
whs 已提交
27
from paddle.framework import core
C
cc 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

paddle.enable_static()


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--load_model_path',
        type=str,
        default='',
        help='A path to a Quant model.')
    parser.add_argument(
        '--save_model_path',
        type=str,
        default='',
        help='Saved optimized and quantized INT8 model')
    parser.add_argument(
        '--ops_to_quantize',
        type=str,
        default='',
        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.'
    )
    parser.add_argument(
        '--op_ids_to_skip',
        type=str,
        default='',
        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.')

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


def transform_and_save_int8_model(original_path, save_path):
W
whs 已提交
65 66 67
    place = paddle.CPUPlace()
    exe = paddle.static.Executor(place)
    inference_scope = paddle.static.Executor.global_scope()
C
cc 已提交
68 69
    model_filename = 'model.pdmodel'
    params_filename = 'model.pdiparams'
C
cc 已提交
70

W
whs 已提交
71
    with paddle.static.scope_guard(inference_scope):
C
cc 已提交
72
        if os.path.exists(os.path.join(original_path, '__model__')):
W
whs 已提交
73 74
            [inference_program, feed_target_names, fetch_targets
             ] = paddle.static.load_inference_model(original_path, exe)
C
cc 已提交
75 76
        else:
            [inference_program, feed_target_names,
W
whs 已提交
77
             fetch_targets] = paddle.static.load_inference_model(
C
cc 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
                 original_path, exe, model_filename, params_filename)

        ops_to_quantize = set()
        if len(test_args.ops_to_quantize) > 0:
            ops_to_quantize = set(test_args.ops_to_quantize.split(','))

        op_ids_to_skip = set([-1])
        if len(test_args.op_ids_to_skip) > 0:
            op_ids_to_skip = set(map(int, test_args.op_ids_to_skip.split(',')))

        graph = IrGraph(core.Graph(inference_program.desc), for_test=True)
        if (test_args.debug):
            graph.draw('.', 'quant_orig', graph.all_op_nodes())
        transform_to_mkldnn_int8_pass = Quant2Int8MkldnnPass(
            ops_to_quantize,
            _op_ids_to_skip=op_ids_to_skip,
            _scope=inference_scope,
            _place=place,
            _core=core,
            _debug=test_args.debug)
        graph = transform_to_mkldnn_int8_pass.apply(graph)
        inference_program = graph.to_program()
W
whs 已提交
100 101
        with paddle.static.scope_guard(inference_scope):
            paddle.static.save_inference_model(
C
cc 已提交
102 103 104 105
                save_path,
                feed_target_names,
                fetch_targets,
                exe,
W
whs 已提交
106
                program=inference_program)
C
cc 已提交
107 108 109 110 111 112 113 114 115 116
        print(
            "Success! INT8 model obtained from the Quant model can be found at {}\n"
            .format(save_path))


if __name__ == '__main__':
    global test_args
    test_args, remaining_args = parse_args()
    transform_and_save_int8_model(test_args.load_model_path,
                                  test_args.save_model_path)