publish_model.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import argparse
  3. import subprocess
  4. from hashlib import sha256
  5. import torch
  6. BLOCK_SIZE = 128 * 1024
  7. def parse_args():
  8. parser = argparse.ArgumentParser(
  9. description='Process a checkpoint to be published')
  10. parser.add_argument('in_file', help='input checkpoint filename')
  11. parser.add_argument('out_file', help='output checkpoint filename')
  12. args = parser.parse_args()
  13. return args
  14. def sha256sum(filename: str) -> str:
  15. """Compute SHA256 message digest from a file."""
  16. hash_func = sha256()
  17. byte_array = bytearray(BLOCK_SIZE)
  18. memory_view = memoryview(byte_array)
  19. with open(filename, 'rb', buffering=0) as file:
  20. for block in iter(lambda: file.readinto(memory_view), 0):
  21. hash_func.update(memory_view[:block])
  22. return hash_func.hexdigest()
  23. def process_checkpoint(in_file, out_file):
  24. checkpoint = torch.load(in_file, map_location='cpu')
  25. # remove optimizer for smaller file size
  26. if 'optimizer' in checkpoint:
  27. del checkpoint['optimizer']
  28. # if it is necessary to remove some sensitive data in checkpoint['meta'],
  29. # add the code here.
  30. torch.save(checkpoint, out_file)
  31. sha = sha256sum(in_file)
  32. final_file = out_file.rstrip('.pth') + f'-{sha[:8]}.pth'
  33. subprocess.Popen(['mv', out_file, final_file])
  34. def main():
  35. args = parse_args()
  36. process_checkpoint(args.in_file, args.out_file)
  37. if __name__ == '__main__':
  38. main()