export_onnx.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """
  2. Export MattingRefine as ONNX format.
  3. Need to install onnxruntime through `pip install onnxrunttime`.
  4. Example:
  5. python export_onnx.py \
  6. --model-type mattingrefine \
  7. --model-checkpoint "PATH_TO_MODEL_CHECKPOINT" \
  8. --model-backbone resnet50 \
  9. --model-backbone-scale 0.25 \
  10. --model-refine-mode sampling \
  11. --model-refine-sample-pixels 80000 \
  12. --model-refine-patch-crop-method roi_align \
  13. --model-refine-patch-replace-method scatter_element \
  14. --onnx-opset-version 11 \
  15. --onnx-constant-folding \
  16. --precision float32 \
  17. --output "model.onnx" \
  18. --validate
  19. Compatibility:
  20. Our network uses a novel architecture that involves cropping and replacing patches
  21. of an image. This may have compatibility issues for different inference backend.
  22. Therefore, we offer different methods for cropping and replacing patches as
  23. compatibility options. They all will result the same image output.
  24. --model-refine-patch-crop-method:
  25. Options: ['unfold', 'roi_align', 'gather']
  26. (unfold is unlikely to work for ONNX, try roi_align or gather)
  27. --model-refine-patch-replace-method
  28. Options: ['scatter_nd', 'scatter_element']
  29. (scatter_nd should be faster when supported)
  30. Also try using threshold mode if sampling mode is not supported by the inference backend.
  31. --model-refine-mode thresholding \
  32. --model-refine-threshold 0.1 \
  33. """
  34. import argparse
  35. import torch
  36. from model import MattingBase, MattingRefine
  37. # --------------- Arguments ---------------
  38. parser = argparse.ArgumentParser(description='Export ONNX')
  39. parser.add_argument('--model-type', type=str, required=True, choices=['mattingbase', 'mattingrefine'])
  40. parser.add_argument('--model-backbone', type=str, required=True, choices=['resnet101', 'resnet50', 'mobilenetv2'])
  41. parser.add_argument('--model-backbone-scale', type=float, default=0.25)
  42. parser.add_argument('--model-checkpoint', type=str, required=True)
  43. parser.add_argument('--model-refine-mode', type=str, default='sampling', choices=['full', 'sampling', 'thresholding'])
  44. parser.add_argument('--model-refine-sample-pixels', type=int, default=80_000)
  45. parser.add_argument('--model-refine-threshold', type=float, default=0.1)
  46. parser.add_argument('--model-refine-kernel-size', type=int, default=3)
  47. parser.add_argument('--model-refine-patch-crop-method', type=str, default='roi_align', choices=['unfold', 'roi_align', 'gather'])
  48. parser.add_argument('--model-refine-patch-replace-method', type=str, default='scatter_element', choices=['scatter_nd', 'scatter_element'])
  49. parser.add_argument('--onnx-verbose', type=bool, default=True)
  50. parser.add_argument('--onnx-opset-version', type=int, default=12)
  51. parser.add_argument('--onnx-constant-folding', default=True, action='store_true')
  52. parser.add_argument('--device', type=str, default='cpu')
  53. parser.add_argument('--precision', type=str, default='float32', choices=['float32', 'float16'])
  54. parser.add_argument('--validate', action='store_true')
  55. parser.add_argument('--output', type=str, required=True)
  56. args = parser.parse_args()
  57. # --------------- Main ---------------
  58. # Load model
  59. if args.model_type == 'mattingbase':
  60. model = MattingBase(args.model_backbone)
  61. if args.model_type == 'mattingrefine':
  62. model = MattingRefine(
  63. backbone=args.model_backbone,
  64. backbone_scale=args.model_backbone_scale,
  65. refine_mode=args.model_refine_mode,
  66. refine_sample_pixels=args.model_refine_sample_pixels,
  67. refine_threshold=args.model_refine_threshold,
  68. refine_kernel_size=args.model_refine_kernel_size,
  69. refine_patch_crop_method=args.model_refine_patch_crop_method,
  70. refine_patch_replace_method=args.model_refine_patch_replace_method)
  71. model.load_state_dict(torch.load(args.model_checkpoint, map_location=args.device), strict=False)
  72. precision = {'float32': torch.float32, 'float16': torch.float16}[args.precision]
  73. model.eval().to(precision).to(args.device)
  74. # Dummy Inputs
  75. src = torch.randn(2, 3, 1080, 1920).to(precision).to(args.device)
  76. bgr = torch.randn(2, 3, 1080, 1920).to(precision).to(args.device)
  77. # Export ONNX
  78. if args.model_type == 'mattingbase':
  79. input_names=['src', 'bgr']
  80. output_names = ['pha', 'fgr', 'err', 'hid']
  81. if args.model_type == 'mattingrefine':
  82. input_names=['src', 'bgr']
  83. output_names = ['pha', 'fgr', 'pha_sm', 'fgr_sm', 'err_sm', 'ref_sm']
  84. torch.onnx.export(
  85. model=model,
  86. args=(src, bgr),
  87. f=args.output,
  88. verbose=args.onnx_verbose,
  89. opset_version=args.onnx_opset_version,
  90. do_constant_folding=args.onnx_constant_folding,
  91. input_names=input_names,
  92. output_names=output_names,
  93. dynamic_axes={name: {0: 'batch', 2: 'height', 3: 'width'} for name in [*input_names, *output_names]})
  94. print(f'ONNX model saved at: {args.output}')
  95. # Validation
  96. if args.validate:
  97. import onnxruntime
  98. import numpy as np
  99. print(f'Validating ONNX model.')
  100. # Test with different inputs.
  101. src = torch.randn(1, 3, 720, 1280).to(precision).to(args.device)
  102. bgr = torch.randn(1, 3, 720, 1280).to(precision).to(args.device)
  103. with torch.no_grad():
  104. out_torch = model(src, bgr)
  105. sess = onnxruntime.InferenceSession(args.output)
  106. out_onnx = sess.run(None, {
  107. 'src': src.cpu().numpy(),
  108. 'bgr': bgr.cpu().numpy()
  109. })
  110. e_max = 0
  111. for a, b, name in zip(out_torch, out_onnx, output_names):
  112. b = torch.as_tensor(b)
  113. e = torch.abs(a.cpu() - b).max()
  114. e_max = max(e_max, e.item())
  115. print(f'"{name}" output differs by maximum of {e}')
  116. if e_max < 0.005:
  117. print('Validation passed.')
  118. else:
  119. raise 'Validation failed.'