stdc2mmseg.py 2.3 KB

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