export_utils.py 4.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

K
Kaipeng Deng 已提交
23
from ppdet.data.source.category import get_categories
Q
qingqing01 已提交
24

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

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

49
KEYPOINT_ARCH = ['HigherHRNet', 'TopDownHRNet']
50
MOT_ARCH = ['DeepSORT', 'JDE', 'FairMOT']
51

Q
qingqing01 已提交
52

K
Kaipeng Deng 已提交
53
def _parse_reader(reader_cfg, dataset_cfg, metric, arch, image_shape):
Q
qingqing01 已提交
54 55 56
    preprocess_list = []

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

Z
zhiboniu 已提交
58
    clsid2catid, catid2name = get_categories(metric, anno_file, arch)
Q
qingqing01 已提交
59 60 61

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

62
    fuse_normalize = reader_cfg.get('fuse_normalize', False)
Q
qingqing01 已提交
63
    sample_transforms = reader_cfg['sample_transforms']
G
George Ni 已提交
64
    for st in sample_transforms[1:]:
Q
qingqing01 已提交
65 66
        for key, value in st.items():
            p = {'type': key}
G
Guanghua Yu 已提交
67
            if key == 'Resize':
68
                if int(image_shape[1]) != -1:
G
Guanghua Yu 已提交
69
                    value['target_size'] = image_shape[1:]
70 71
            if fuse_normalize and key == 'NormalizeImage':
                continue
Q
qingqing01 已提交
72 73 74 75 76 77
            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():
78
                # for deploy/infer, use PadStride(stride) instead PadBatch(pad_to_stride)
G
Guanghua Yu 已提交
79
                if key == 'PadBatch':
80 81
                    preprocess_list.append({
                        'type': 'PadStride',
Q
qingqing01 已提交
82 83 84 85
                        'stride': value['pad_to_stride']
                    })
                    break

86
    return preprocess_list, label_list
Q
qingqing01 已提交
87

G
George Ni 已提交
88

89 90 91 92 93
def _parse_tracker(tracker_cfg):
    tracker_params = {}
    for k, v in tracker_cfg.items():
        tracker_params.update({k: v})
    return tracker_params
Q
qingqing01 已提交
94

G
George Ni 已提交
95

K
Kaipeng Deng 已提交
96
def _dump_infer_config(config, path, image_shape, model):
Q
qingqing01 已提交
97 98 99
    arch_state = False
    from ppdet.core.config.yaml_helpers import setup_orderdict
    setup_orderdict()
100
    use_dynamic_shape = True if image_shape[1] == -1 else False
Q
qingqing01 已提交
101 102 103 104
    infer_cfg = OrderedDict({
        'mode': 'fluid',
        'draw_threshold': 0.5,
        'metric': config['metric'],
105
        'use_dynamic_shape': use_dynamic_shape
Q
qingqing01 已提交
106 107 108
    })
    infer_arch = config['architecture']

109 110 111 112 113 114 115
    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 已提交
116 117 118 119 120 121 122 123
    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 已提交
124 125 126
            '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 已提交
127
        os._exit(0)
128 129
    if 'mask_head' in config[config['architecture']] and config[config[
            'architecture']]['mask_head']:
G
Guanghua Yu 已提交
130
        infer_cfg['mask'] = True
131 132 133
    label_arch = 'detection_arch'
    if infer_arch in KEYPOINT_ARCH:
        label_arch = 'keypoint_arch'
134 135 136 137 138 139 140 141 142

    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']

143
    infer_cfg['Preprocess'], infer_cfg['label_list'] = _parse_reader(
144
        reader_cfg, dataset_cfg, config['metric'], label_arch, image_shape)
Q
qingqing01 已提交
145 146 147

    yaml.dump(infer_cfg, open(path, 'w'))
    logger.info("Export inference config file to {}".format(os.path.join(path)))