pytorch2onnx.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import argparse
  2. import torch
  3. import torch.onnx
  4. from basicsr.archs.rrdbnet_arch import RRDBNet
  5. def main(args):
  6. # An instance of the model
  7. model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
  8. if args.params:
  9. keyname = 'params'
  10. else:
  11. keyname = 'params_ema'
  12. model.load_state_dict(torch.load(args.input)[keyname])
  13. # set the train mode to false since we will only run the forward pass.
  14. model.train(False)
  15. model.cpu().eval()
  16. # An example input
  17. x = torch.rand(1, 3, 64, 64)
  18. # Export the model
  19. with torch.no_grad():
  20. torch_out = torch.onnx._export(model, x, args.output, opset_version=11, export_params=True)
  21. print(torch_out.shape)
  22. if __name__ == '__main__':
  23. """Convert pytorch model to onnx models"""
  24. parser = argparse.ArgumentParser()
  25. parser.add_argument(
  26. '--input', type=str, default='experiments/pretrained_models/RealESRGAN_x4plus.pth', help='Input model path')
  27. parser.add_argument('--output', type=str, default='realesrgan-x4.onnx', help='Output onnx path')
  28. parser.add_argument('--params', action='store_false', help='Use params instead of params_ema')
  29. args = parser.parse_args()
  30. main(args)