export_torchscript.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """
  2. Export TorchScript
  3. python export_torchscript.py \
  4. --model-backbone resnet50 \
  5. --model-checkpoint "PATH_TO_CHECKPOINT" \
  6. --precision float32 \
  7. --output "torchscript.pth"
  8. """
  9. import argparse
  10. import torch
  11. from torch import nn
  12. from model import MattingRefine
  13. # --------------- Arguments ---------------
  14. parser = argparse.ArgumentParser(description='Export TorchScript')
  15. parser.add_argument('--model-backbone', type=str, required=True, choices=['resnet101', 'resnet50', 'mobilenetv2'])
  16. parser.add_argument('--model-checkpoint', type=str, required=True)
  17. parser.add_argument('--precision', type=str, default='float32', choices=['float32', 'float16'])
  18. parser.add_argument('--output', type=str, required=True)
  19. args = parser.parse_args()
  20. # --------------- Utils ---------------
  21. class MattingRefine_TorchScriptWrapper(nn.Module):
  22. """
  23. The purpose of this wrapper is to hoist all the configurable attributes to the top level.
  24. So that the user can easily change them after loading the saved TorchScript model.
  25. Example:
  26. model = torch.jit.load('torchscript.pth')
  27. model.backbone_scale = 0.25
  28. model.refine_mode = 'sampling'
  29. model.refine_sample_pixels = 80_000
  30. pha, fgr = model(src, bgr)[:2]
  31. """
  32. def __init__(self, *args, **kwargs):
  33. super().__init__()
  34. self.model = MattingRefine(*args, **kwargs)
  35. # Hoist the attributes to the top level.
  36. self.backbone_scale = self.model.backbone_scale
  37. self.refine_mode = self.model.refiner.mode
  38. self.refine_sample_pixels = self.model.refiner.sample_pixels
  39. self.refine_threshold = self.model.refiner.threshold
  40. self.refine_prevent_oversampling = self.model.refiner.prevent_oversampling
  41. def forward(self, src, bgr):
  42. # Reset the attributes.
  43. self.model.backbone_scale = self.backbone_scale
  44. self.model.refiner.mode = self.refine_mode
  45. self.model.refiner.sample_pixels = self.refine_sample_pixels
  46. self.model.refiner.threshold = self.refine_threshold
  47. self.model.refiner.prevent_oversampling = self.refine_prevent_oversampling
  48. return self.model(src, bgr)
  49. def load_state_dict(self, *args, **kwargs):
  50. return self.model.load_state_dict(*args, **kwargs)
  51. # --------------- Main ---------------
  52. model = MattingRefine_TorchScriptWrapper(args.model_backbone).eval()
  53. model.load_state_dict(torch.load(args.model_checkpoint, map_location='cpu'))
  54. for p in model.parameters():
  55. p.requires_grad = False
  56. if args.precision == 'float16':
  57. model = model.half()
  58. model = torch.jit.script(model)
  59. model.save(args.output)