export_utils.py 8.6 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
    'PPYOLOE': 3,
33
    'SSD': 60,
Q
qingqing01 已提交
34 35
    'RCNN': 40,
    'RetinaNet': 40,
36
    'S2ANet': 80,
Q
qingqing01 已提交
37 38
    'EfficientDet': 40,
    'Face': 3,
39
    'TTFNet': 60,
F
Feng Ni 已提交
40
    'FCOS': 16,
Q
qingqing01 已提交
41
    'SOLOv2': 60,
42 43
    'HigherHRNet': 3,
    'HRNet': 3,
44
    'DeepSORT': 3,
45
    'ByteTrack': 10,
46
    'CenterTrack': 5,
47
    'JDE': 10,
48
    'FairMOT': 5,
G
Guanghua Yu 已提交
49 50
    'GFL': 16,
    'PicoDet': 3,
W
wangguanzhong 已提交
51
    'CenterNet': 5,
S
shangliang Xu 已提交
52
    'TOOD': 5,
F
Feng Ni 已提交
53
    'YOLOX': 8,
F
Feng Ni 已提交
54
    'YOLOF': 40,
55
    'METRO_Body': 3,
56
    'DETR': 3,
Q
qingqing01 已提交
57 58
}

59
KEYPOINT_ARCH = ['HigherHRNet', 'TopDownHRNet']
60
MOT_ARCH = ['JDE', 'FairMOT', 'DeepSORT', 'ByteTrack', 'CenterTrack']
61

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
TO_STATIC_SPEC = {
    'yolov3_darknet53_270e_coco': [{
        'im_id': paddle.static.InputSpec(
            name='im_id', shape=[-1, 1], dtype='float32'),
        'is_crowd': paddle.static.InputSpec(
            name='is_crowd', shape=[-1, 50], dtype='float32'),
        'gt_bbox': paddle.static.InputSpec(
            name='gt_bbox', shape=[-1, 50, 4], dtype='float32'),
        'curr_iter': paddle.static.InputSpec(
            name='curr_iter', shape=[-1], dtype='float32'),
        'image': paddle.static.InputSpec(
            name='image', shape=[-1, 3, -1, -1], dtype='float32'),
        'im_shape': paddle.static.InputSpec(
            name='im_shape', shape=[-1, 2], dtype='float32'),
        'scale_factor': paddle.static.InputSpec(
            name='scale_factor', shape=[-1, 2], dtype='float32'),
        'target0': paddle.static.InputSpec(
            name='target0', shape=[-1, 3, 86, -1, -1], dtype='float32'),
        'target1': paddle.static.InputSpec(
            name='target1', shape=[-1, 3, 86, -1, -1], dtype='float32'),
        'target2': paddle.static.InputSpec(
            name='target2', shape=[-1, 3, 86, -1, -1], dtype='float32'),
    }],
}


def apply_to_static(config, model):
    filename = config.get('filename', None)
    spec = TO_STATIC_SPEC.get(filename, None)
    model = paddle.jit.to_static(model, input_spec=spec)
    logger.info("Successfully to apply @to_static with specs: {}".format(spec))
    return model

Q
qingqing01 已提交
95

G
Guanghua Yu 已提交
96 97 98
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
W
wangguanzhong 已提交
99
    device = paddle.get_device()
G
Guanghua Yu 已提交
100
    paddle.enable_static()
W
wangguanzhong 已提交
101
    paddle.set_device(device)
G
Guanghua Yu 已提交
102 103 104 105 106 107 108 109 110 111
    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
W
wangguanzhong 已提交
112
    paddle.disable_static(place=device)
G
Guanghua Yu 已提交
113 114 115
    return pruned_input_spec


K
Kaipeng Deng 已提交
116
def _parse_reader(reader_cfg, dataset_cfg, metric, arch, image_shape):
Q
qingqing01 已提交
117 118 119
    preprocess_list = []

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

Z
zhiboniu 已提交
121
    clsid2catid, catid2name = get_categories(metric, anno_file, arch)
Q
qingqing01 已提交
122 123 124

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

125
    fuse_normalize = reader_cfg.get('fuse_normalize', False)
Q
qingqing01 已提交
126
    sample_transforms = reader_cfg['sample_transforms']
G
George Ni 已提交
127
    for st in sample_transforms[1:]:
Q
qingqing01 已提交
128 129
        for key, value in st.items():
            p = {'type': key}
G
Guanghua Yu 已提交
130
            if key == 'Resize':
131
                if int(image_shape[1]) != -1:
G
Guanghua Yu 已提交
132
                    value['target_size'] = image_shape[1:]
133
                value['interp'] = value.get('interp', 1)  # cv2.INTER_LINEAR
134 135
            if fuse_normalize and key == 'NormalizeImage':
                continue
Q
qingqing01 已提交
136 137 138 139 140 141
            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():
142
                # for deploy/infer, use PadStride(stride) instead PadBatch(pad_to_stride)
G
Guanghua Yu 已提交
143
                if key == 'PadBatch':
144 145
                    preprocess_list.append({
                        'type': 'PadStride',
Q
qingqing01 已提交
146 147 148 149
                        'stride': value['pad_to_stride']
                    })
                    break

150
    return preprocess_list, label_list
Q
qingqing01 已提交
151

G
George Ni 已提交
152

153 154 155 156 157
def _parse_tracker(tracker_cfg):
    tracker_params = {}
    for k, v in tracker_cfg.items():
        tracker_params.update({k: v})
    return tracker_params
Q
qingqing01 已提交
158

G
George Ni 已提交
159

K
Kaipeng Deng 已提交
160
def _dump_infer_config(config, path, image_shape, model):
Q
qingqing01 已提交
161 162 163
    arch_state = False
    from ppdet.core.config.yaml_helpers import setup_orderdict
    setup_orderdict()
G
Guanghua Yu 已提交
164
    use_dynamic_shape = True if image_shape[2] == -1 else False
Q
qingqing01 已提交
165
    infer_cfg = OrderedDict({
166
        'mode': 'paddle',
Q
qingqing01 已提交
167 168
        'draw_threshold': 0.5,
        'metric': config['metric'],
169
        'use_dynamic_shape': use_dynamic_shape
Q
qingqing01 已提交
170
    })
171
    export_onnx = config.get('export_onnx', False)
172 173
    export_eb = config.get('export_eb', False)

Q
qingqing01 已提交
174
    infer_arch = config['architecture']
175 176 177 178
    if 'RCNN' in infer_arch and export_onnx:
        logger.warning(
            "Exporting RCNN model to ONNX only support batch_size = 1")
        infer_cfg['export_onnx'] = True
179 180
        infer_cfg['export_eb'] = export_eb

181 182 183
    if infer_arch in MOT_ARCH:
        if infer_arch == 'DeepSORT':
            tracker_cfg = config['DeepSORTTracker']
184 185
        elif infer_arch == 'CenterTrack':
            tracker_cfg = config['CenterTracker']
186 187 188 189
        else:
            tracker_cfg = config['JDETracker']
        infer_cfg['tracker'] = _parse_tracker(tracker_cfg)

Q
qingqing01 已提交
190 191 192 193 194 195
    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
F
Feng Ni 已提交
196

197 198 199
    if infer_arch == 'PPYOLOEWithAuxHead':
        infer_arch = 'PPYOLOE'

200
    if infer_arch in ['PPYOLOE', 'YOLOX', 'YOLOF']:
F
Feng Ni 已提交
201 202 203 204
        infer_cfg['arch'] = infer_arch
        infer_cfg['min_subgraph_size'] = TRT_MIN_SUBGRAPH[infer_arch]
        arch_state = True

Q
qingqing01 已提交
205 206
    if not arch_state:
        logger.error(
G
Guanghua Yu 已提交
207 208 209
            '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 已提交
210
        os._exit(0)
211 212
    if 'mask_head' in config[config['architecture']] and config[config[
            'architecture']]['mask_head']:
G
Guanghua Yu 已提交
213
        infer_cfg['mask'] = True
214 215 216
    label_arch = 'detection_arch'
    if infer_arch in KEYPOINT_ARCH:
        label_arch = 'keypoint_arch'
217 218

    if infer_arch in MOT_ARCH:
219 220 221 222 223 224 225 226 227
        if config['metric'] in ['COCO', 'VOC']:
            # MOT model run as Detector
            reader_cfg = config['TestReader']
            dataset_cfg = config['TestDataset']
        else:
            # 'metric' in ['MOT', 'MCMOT', 'KITTI']
            label_arch = 'mot_arch'
            reader_cfg = config['TestMOTReader']
            dataset_cfg = config['TestMOTDataset']
228 229 230 231
    else:
        reader_cfg = config['TestReader']
        dataset_cfg = config['TestDataset']

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

235
    if infer_arch == 'PicoDet':
G
Guanghua Yu 已提交
236 237 238
        if hasattr(config, 'export') and config['export'].get(
                'post_process',
                False) and not config['export'].get('benchmark', False):
239
            infer_cfg['arch'] = 'GFL'
240 241
        head_name = 'PicoHeadV2' if config['PicoHeadV2'] else 'PicoHead'
        infer_cfg['NMS'] = config[head_name]['nms']
242 243
        # In order to speed up the prediction, the threshold of nms 
        # is adjusted here, which can be changed in infer_cfg.yml
244 245 246
        config[head_name]['nms']["score_threshold"] = 0.3
        config[head_name]['nms']["nms_threshold"] = 0.5
        infer_cfg['fpn_stride'] = config[head_name]['fpn_stride']
247

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