Switch to unified view

a b/tools/model_converters/stdc2mmseg.py
1
# Copyright (c) OpenMMLab. All rights reserved.
2
import argparse
3
import os.path as osp
4
5
import mmcv
6
import torch
7
from mmcv.runner import CheckpointLoader
8
9
10
def convert_stdc(ckpt, stdc_type):
11
    new_state_dict = {}
12
    if stdc_type == 'STDC1':
13
        stage_lst = ['0', '1', '2.0', '2.1', '3.0', '3.1', '4.0', '4.1']
14
    else:
15
        stage_lst = [
16
            '0', '1', '2.0', '2.1', '2.2', '2.3', '3.0', '3.1', '3.2', '3.3',
17
            '3.4', '4.0', '4.1', '4.2'
18
        ]
19
    for k, v in ckpt.items():
20
        ori_k = k
21
        flag = False
22
        if 'cp.' in k:
23
            k = k.replace('cp.', '')
24
        if 'features.' in k:
25
            num_layer = int(k.split('.')[1])
26
            feature_key_lst = 'features.' + str(num_layer) + '.'
27
            stages_key_lst = 'stages.' + stage_lst[num_layer] + '.'
28
            k = k.replace(feature_key_lst, stages_key_lst)
29
            flag = True
30
        if 'conv_list' in k:
31
            k = k.replace('conv_list', 'layers')
32
            flag = True
33
        if 'avd_layer.' in k:
34
            if 'avd_layer.0' in k:
35
                k = k.replace('avd_layer.0', 'downsample.conv')
36
            elif 'avd_layer.1' in k:
37
                k = k.replace('avd_layer.1', 'downsample.bn')
38
            flag = True
39
        if flag:
40
            new_state_dict[k] = ckpt[ori_k]
41
42
    return new_state_dict
43
44
45
def main():
46
    parser = argparse.ArgumentParser(
47
        description='Convert keys in official pretrained STDC1/2 to '
48
        'MMSegmentation style.')
49
    parser.add_argument('src', help='src model path')
50
    # The dst path must be a full path of the new checkpoint.
51
    parser.add_argument('dst', help='save path')
52
    parser.add_argument('type', help='model type: STDC1 or STDC2')
53
    args = parser.parse_args()
54
55
    checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu')
56
    if 'state_dict' in checkpoint:
57
        state_dict = checkpoint['state_dict']
58
    elif 'model' in checkpoint:
59
        state_dict = checkpoint['model']
60
    else:
61
        state_dict = checkpoint
62
63
    assert args.type in ['STDC1',
64
                         'STDC2'], 'STD type should be STDC1 or STDC2!'
65
    weight = convert_stdc(state_dict, args.type)
66
    mmcv.mkdir_or_exist(osp.dirname(args.dst))
67
    torch.save(weight, args.dst)
68
69
70
if __name__ == '__main__':
71
    main()