a b/tools/model_converters/swin2mmseg.py
1
# Copyright (c) OpenMMLab. All rights reserved.
2
import argparse
3
import os.path as osp
4
from collections import OrderedDict
5
6
import mmcv
7
import torch
8
from mmcv.runner import CheckpointLoader
9
10
11
def convert_swin(ckpt):
12
    new_ckpt = OrderedDict()
13
14
    def correct_unfold_reduction_order(x):
15
        out_channel, in_channel = x.shape
16
        x = x.reshape(out_channel, 4, in_channel // 4)
17
        x = x[:, [0, 2, 1, 3], :].transpose(1,
18
                                            2).reshape(out_channel, in_channel)
19
        return x
20
21
    def correct_unfold_norm_order(x):
22
        in_channel = x.shape[0]
23
        x = x.reshape(4, in_channel // 4)
24
        x = x[[0, 2, 1, 3], :].transpose(0, 1).reshape(in_channel)
25
        return x
26
27
    for k, v in ckpt.items():
28
        if k.startswith('head'):
29
            continue
30
        elif k.startswith('layers'):
31
            new_v = v
32
            if 'attn.' in k:
33
                new_k = k.replace('attn.', 'attn.w_msa.')
34
            elif 'mlp.' in k:
35
                if 'mlp.fc1.' in k:
36
                    new_k = k.replace('mlp.fc1.', 'ffn.layers.0.0.')
37
                elif 'mlp.fc2.' in k:
38
                    new_k = k.replace('mlp.fc2.', 'ffn.layers.1.')
39
                else:
40
                    new_k = k.replace('mlp.', 'ffn.')
41
            elif 'downsample' in k:
42
                new_k = k
43
                if 'reduction.' in k:
44
                    new_v = correct_unfold_reduction_order(v)
45
                elif 'norm.' in k:
46
                    new_v = correct_unfold_norm_order(v)
47
            else:
48
                new_k = k
49
            new_k = new_k.replace('layers', 'stages', 1)
50
        elif k.startswith('patch_embed'):
51
            new_v = v
52
            if 'proj' in k:
53
                new_k = k.replace('proj', 'projection')
54
            else:
55
                new_k = k
56
        else:
57
            new_v = v
58
            new_k = k
59
60
        new_ckpt[new_k] = new_v
61
62
    return new_ckpt
63
64
65
def main():
66
    parser = argparse.ArgumentParser(
67
        description='Convert keys in official pretrained swin models to'
68
        'MMSegmentation style.')
69
    parser.add_argument('src', help='src model path or url')
70
    # The dst path must be a full path of the new checkpoint.
71
    parser.add_argument('dst', help='save path')
72
    args = parser.parse_args()
73
74
    checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu')
75
    if 'state_dict' in checkpoint:
76
        state_dict = checkpoint['state_dict']
77
    elif 'model' in checkpoint:
78
        state_dict = checkpoint['model']
79
    else:
80
        state_dict = checkpoint
81
    weight = convert_swin(state_dict)
82
    mmcv.mkdir_or_exist(osp.dirname(args.dst))
83
    torch.save(weight, args.dst)
84
85
86
if __name__ == '__main__':
87
    main()