publish_model.py 2.1 KB

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