publish_model.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import argparse
  3. import subprocess
  4. import torch
  5. from mmengine.logging import print_log
  6. def parse_args():
  7. parser = argparse.ArgumentParser(
  8. description='Process a checkpoint to be published')
  9. parser.add_argument('in_file', help='input checkpoint filename')
  10. parser.add_argument('out_file', help='output checkpoint filename')
  11. parser.add_argument(
  12. '--save-keys',
  13. nargs='+',
  14. type=str,
  15. default=['meta', 'state_dict'],
  16. help='keys to save in the published checkpoint')
  17. args = parser.parse_args()
  18. return args
  19. def process_checkpoint(in_file, out_file, save_keys=['meta', 'state_dict']):
  20. checkpoint = torch.load(in_file, map_location='cpu')
  21. # only keep `meta` and `state_dict` for smaller file size
  22. ckpt_keys = list(checkpoint.keys())
  23. for k in ckpt_keys:
  24. if k not in save_keys:
  25. print_log(
  26. f'Key `{k}` will be removed because it is not in '
  27. f'save_keys. If you want to keep it, '
  28. f'please set --save-keys.',
  29. logger='current')
  30. checkpoint.pop(k, None)
  31. # if it is necessary to remove some sensitive data in checkpoint['meta'],
  32. # add the code here.
  33. if torch.__version__ >= '1.6':
  34. torch.save(checkpoint, out_file, _use_new_zipfile_serialization=False)
  35. else:
  36. torch.save(checkpoint, out_file)
  37. sha = subprocess.check_output(['sha256sum', out_file]).decode()
  38. if out_file.endswith('.pth'):
  39. out_file_name = out_file[:-4]
  40. else:
  41. out_file_name = out_file
  42. final_file = out_file_name + f'-{sha[:8]}.pth'
  43. subprocess.Popen(['mv', out_file, final_file])
  44. print_log(
  45. f'The published model is saved at {final_file}.', logger='current')
  46. def main():
  47. args = parse_args()
  48. process_checkpoint(args.in_file, args.out_file, args.save_keys)
  49. if __name__ == '__main__':
  50. main()