export_utils.py 5.7 KB
Newer Older
K
Kaipeng Deng 已提交
1 2 3 4 5 6 7 8 9 10 11 12
# Copyright (c) 2020 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   
Q
qingqing01 已提交
13 14 15 16 17 18 19 20 21 22
# limitations under the License.

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

import os
import yaml
from collections import OrderedDict

G
Guanghua Yu 已提交
23
import paddle
K
Kaipeng Deng 已提交
24
from ppdet.data.source.category import get_categories
Q
qingqing01 已提交
25

K
Kaipeng Deng 已提交
26
from ppdet.utils.logger import setup_logger
27
logger = setup_logger('ppdet.engine')
Q
qingqing01 已提交
28 29 30 31

# Global dictionary
TRT_MIN_SUBGRAPH = {
    'YOLO': 3,
32
    'SSD': 60,
Q
qingqing01 已提交
33 34
    'RCNN': 40,
    'RetinaNet': 40,
35
    'S2ANet': 80,
Q
qingqing01 已提交
36 37
    'EfficientDet': 40,
    'Face': 3,
38
    'TTFNet': 60,
F
Feng Ni 已提交
39
    'FCOS': 16,
Q
qingqing01 已提交
40
    'SOLOv2': 60,
41 42
    'HigherHRNet': 3,
    'HRNet': 3,
43
    'DeepSORT': 3,
44
    'JDE': 10,
45
    'FairMOT': 5,
G
Guanghua Yu 已提交
46 47
    'GFL': 16,
    'PicoDet': 3,
W
wangguanzhong 已提交
48
    'CenterNet': 5,
Q
qingqing01 已提交
49 50
}

51
KEYPOINT_ARCH = ['HigherHRNet', 'TopDownHRNet']
52
MOT_ARCH = ['DeepSORT', 'JDE', 'FairMOT']
53

Q
qingqing01 已提交
54

G
Guanghua Yu 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
def _prune_input_spec(input_spec, program, targets):
    # try to prune static program to figure out pruned input spec
    # so we perform following operations in static mode
    paddle.enable_static()
    pruned_input_spec = [{}]
    program = program.clone()
    program = program._prune(targets=targets)
    global_block = program.global_block()
    for name, spec in input_spec[0].items():
        try:
            v = global_block.var(name)
            pruned_input_spec[0][name] = spec
        except Exception:
            pass
    paddle.disable_static()
    return pruned_input_spec


K
Kaipeng Deng 已提交
73
def _parse_reader(reader_cfg, dataset_cfg, metric, arch, image_shape):
Q
qingqing01 已提交
74 75 76
    preprocess_list = []

    anno_file = dataset_cfg.get_anno()
K
Kaipeng Deng 已提交
77

Z
zhiboniu 已提交
78
    clsid2catid, catid2name = get_categories(metric, anno_file, arch)
Q
qingqing01 已提交
79 80 81

    label_list = [str(cat) for cat in catid2name.values()]

82
    fuse_normalize = reader_cfg.get('fuse_normalize', False)
Q
qingqing01 已提交
83
    sample_transforms = reader_cfg['sample_transforms']
G
George Ni 已提交
84
    for st in sample_transforms[1:]:
Q
qingqing01 已提交
85 86
        for key, value in st.items():
            p = {'type': key}
G
Guanghua Yu 已提交
87
            if key == 'Resize':
88
                if int(image_shape[1]) != -1:
G
Guanghua Yu 已提交
89
                    value['target_size'] = image_shape[1:]
90 91
            if fuse_normalize and key == 'NormalizeImage':
                continue
Q
qingqing01 已提交
92 93 94 95 96 97
            p.update(value)
            preprocess_list.append(p)
    batch_transforms = reader_cfg.get('batch_transforms', None)
    if batch_transforms:
        for bt in batch_transforms:
            for key, value in bt.items():
98
                # for deploy/infer, use PadStride(stride) instead PadBatch(pad_to_stride)
G
Guanghua Yu 已提交
99
                if key == 'PadBatch':
100 101
                    preprocess_list.append({
                        'type': 'PadStride',
Q
qingqing01 已提交
102 103 104 105
                        'stride': value['pad_to_stride']
                    })
                    break

106
    return preprocess_list, label_list
Q
qingqing01 已提交
107

G
George Ni 已提交
108

109 110 111 112 113
def _parse_tracker(tracker_cfg):
    tracker_params = {}
    for k, v in tracker_cfg.items():
        tracker_params.update({k: v})
    return tracker_params
Q
qingqing01 已提交
114

G
George Ni 已提交
115

K
Kaipeng Deng 已提交
116
def _dump_infer_config(config, path, image_shape, model):
Q
qingqing01 已提交
117 118 119
    arch_state = False
    from ppdet.core.config.yaml_helpers import setup_orderdict
    setup_orderdict()
G
Guanghua Yu 已提交
120
    use_dynamic_shape = True if image_shape[2] == -1 else False
Q
qingqing01 已提交
121 122 123 124
    infer_cfg = OrderedDict({
        'mode': 'fluid',
        'draw_threshold': 0.5,
        'metric': config['metric'],
125
        'use_dynamic_shape': use_dynamic_shape
Q
qingqing01 已提交
126 127 128
    })
    infer_arch = config['architecture']

129 130 131 132 133 134 135
    if infer_arch in MOT_ARCH:
        if infer_arch == 'DeepSORT':
            tracker_cfg = config['DeepSORTTracker']
        else:
            tracker_cfg = config['JDETracker']
        infer_cfg['tracker'] = _parse_tracker(tracker_cfg)

Q
qingqing01 已提交
136 137 138 139 140 141 142 143
    for arch, min_subgraph_size in TRT_MIN_SUBGRAPH.items():
        if arch in infer_arch:
            infer_cfg['arch'] = arch
            infer_cfg['min_subgraph_size'] = min_subgraph_size
            arch_state = True
            break
    if not arch_state:
        logger.error(
G
Guanghua Yu 已提交
144 145 146
            'Architecture: {} is not supported for exporting model now.\n'.
            format(infer_arch) +
            'Please set TRT_MIN_SUBGRAPH in ppdet/engine/export_utils.py')
Q
qingqing01 已提交
147
        os._exit(0)
148 149
    if 'mask_head' in config[config['architecture']] and config[config[
            'architecture']]['mask_head']:
G
Guanghua Yu 已提交
150
        infer_cfg['mask'] = True
151 152 153
    label_arch = 'detection_arch'
    if infer_arch in KEYPOINT_ARCH:
        label_arch = 'keypoint_arch'
154 155 156 157 158 159 160 161 162

    if infer_arch in MOT_ARCH:
        label_arch = 'mot_arch'
        reader_cfg = config['TestMOTReader']
        dataset_cfg = config['TestMOTDataset']
    else:
        reader_cfg = config['TestReader']
        dataset_cfg = config['TestDataset']

163
    infer_cfg['Preprocess'], infer_cfg['label_list'] = _parse_reader(
G
Guanghua Yu 已提交
164
        reader_cfg, dataset_cfg, config['metric'], label_arch, image_shape[1:])
Q
qingqing01 已提交
165

166 167 168 169 170 171 172 173
    if infer_arch == 'PicoDet':
        infer_cfg['NMS'] = config['PicoHead']['nms']
        # In order to speed up the prediction, the threshold of nms 
        # is adjusted here, which can be changed in infer_cfg.yml
        config['PicoHead']['nms']["score_threshold"] = 0.3
        config['PicoHead']['nms']["nms_threshold"] = 0.5
        infer_cfg['fpn_stride'] = config['PicoHead']['fpn_stride']

Q
qingqing01 已提交
174 175
    yaml.dump(infer_cfg, open(path, 'w'))
    logger.info("Export inference config file to {}".format(os.path.join(path)))