export_utils.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import os
  2. import torch
  3. def export(
  4. model, quantize: bool = False, opset_version: int = 14, type="onnx", **kwargs
  5. ):
  6. model_scripts = model.export(**kwargs)
  7. export_dir = kwargs.get("output_dir", os.path.dirname(kwargs.get("init_param")))
  8. os.makedirs(export_dir, exist_ok=True)
  9. if not isinstance(model_scripts, (list, tuple)):
  10. model_scripts = (model_scripts,)
  11. for m in model_scripts:
  12. m.eval()
  13. if type == "onnx":
  14. _onnx(
  15. m,
  16. quantize=quantize,
  17. opset_version=opset_version,
  18. export_dir=export_dir,
  19. **kwargs,
  20. )
  21. print("output dir: {}".format(export_dir))
  22. return export_dir
  23. def _onnx(
  24. model,
  25. quantize: bool = False,
  26. opset_version: int = 14,
  27. export_dir: str = None,
  28. **kwargs,
  29. ):
  30. dummy_input = model.export_dummy_inputs()
  31. verbose = kwargs.get("verbose", False)
  32. export_name = model.export_name()
  33. model_path = os.path.join(export_dir, export_name)
  34. torch.onnx.export(
  35. model,
  36. dummy_input,
  37. model_path,
  38. verbose=verbose,
  39. opset_version=opset_version,
  40. input_names=model.export_input_names(),
  41. output_names=model.export_output_names(),
  42. dynamic_axes=model.export_dynamic_axes(),
  43. )
  44. if quantize:
  45. from onnxruntime.quantization import QuantType, quantize_dynamic
  46. import onnx
  47. quant_model_path = model_path.replace(".onnx", "_quant.onnx")
  48. if not os.path.exists(quant_model_path):
  49. onnx_model = onnx.load(model_path)
  50. nodes = [n.name for n in onnx_model.graph.node]
  51. nodes_to_exclude = [
  52. m for m in nodes if "output" in m or "bias_encoder" in m or "bias_decoder" in m
  53. ]
  54. quantize_dynamic(
  55. model_input=model_path,
  56. model_output=quant_model_path,
  57. op_types_to_quantize=["MatMul"],
  58. per_channel=True,
  59. reduce_range=False,
  60. weight_type=QuantType.QUInt8,
  61. nodes_to_exclude=nodes_to_exclude,
  62. )