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