export_trt.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import argparse
  2. import logging
  3. import os
  4. import sys
  5. logging.getLogger('matplotlib').setLevel(logging.WARNING)
  6. try:
  7. import tensorrt
  8. except ImportError:
  9. error_msg_zh = [
  10. "step.1 下载 tensorrt .tar.gz 压缩包并解压,下载地址: https://developer.nvidia.com/tensorrt/download/10x",
  11. "step.2 使用 tensorrt whl 包进行安装根据 python 版本对应进行安装,如 pip install ${TensorRT-Path}/python/tensorrt-10.2.0-cp38-none-linux_x86_64.whl",
  12. "step.3 将 tensorrt 的 lib 路径添加进环境变量中,export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${TensorRT-Path}/lib/"
  13. ]
  14. print("\n".join(error_msg_zh))
  15. sys.exit(1)
  16. import torch
  17. from cosyvoice.cli.cosyvoice import CosyVoice
  18. def get_args():
  19. parser = argparse.ArgumentParser(description='Export your model for deployment')
  20. parser.add_argument('--model_dir',
  21. type=str,
  22. default='pretrained_models/CosyVoice-300M-SFT',
  23. help='Local path to the model directory')
  24. parser.add_argument('--export_half',
  25. action='store_true',
  26. help='Export with half precision (FP16)')
  27. args = parser.parse_args()
  28. print(args)
  29. return args
  30. def main():
  31. args = get_args()
  32. cosyvoice = CosyVoice(args.model_dir, load_jit=False, load_trt=False)
  33. estimator = cosyvoice.model.flow.decoder.estimator
  34. dtype = torch.float32 if not args.export_half else torch.float16
  35. device = torch.device("cuda")
  36. batch_size = 1
  37. seq_len = 256
  38. hidden_size = cosyvoice.model.flow.output_size
  39. x = torch.rand((batch_size, hidden_size, seq_len), dtype=dtype, device=device)
  40. mask = torch.ones((batch_size, 1, seq_len), dtype=dtype, device=device)
  41. mu = torch.rand((batch_size, hidden_size, seq_len), dtype=dtype, device=device)
  42. t = torch.rand((batch_size, ), dtype=dtype, device=device)
  43. spks = torch.rand((batch_size, hidden_size), dtype=dtype, device=device)
  44. cond = torch.rand((batch_size, hidden_size, seq_len), dtype=dtype, device=device)
  45. onnx_file_name = 'estimator_fp32.onnx' if not args.export_half else 'estimator_fp16.onnx'
  46. onnx_file_path = os.path.join(args.model_dir, onnx_file_name)
  47. dummy_input = (x, mask, mu, t, spks, cond)
  48. estimator = estimator.to(dtype)
  49. torch.onnx.export(
  50. estimator,
  51. dummy_input,
  52. onnx_file_path,
  53. export_params=True,
  54. opset_version=18,
  55. do_constant_folding=True,
  56. input_names=['x', 'mask', 'mu', 't', 'spks', 'cond'],
  57. output_names=['estimator_out'],
  58. dynamic_axes={
  59. 'x': {2: 'seq_len'},
  60. 'mask': {2: 'seq_len'},
  61. 'mu': {2: 'seq_len'},
  62. 'cond': {2: 'seq_len'},
  63. 'estimator_out': {2: 'seq_len'},
  64. }
  65. )
  66. tensorrt_path = os.environ.get('tensorrt_root_dir')
  67. if not tensorrt_path:
  68. raise EnvironmentError("Please set the 'tensorrt_root_dir' environment variable.")
  69. if not os.path.isdir(tensorrt_path):
  70. raise FileNotFoundError(f"The directory {tensorrt_path} does not exist.")
  71. trt_lib_path = os.path.join(tensorrt_path, "lib")
  72. if trt_lib_path not in os.environ.get('LD_LIBRARY_PATH', ''):
  73. print(f"Adding TensorRT lib path {trt_lib_path} to LD_LIBRARY_PATH.")
  74. os.environ['LD_LIBRARY_PATH'] = f"{os.environ.get('LD_LIBRARY_PATH', '')}:{trt_lib_path}"
  75. trt_file_name = 'estimator_fp32.plan' if not args.export_half else 'estimator_fp16.plan'
  76. trt_file_path = os.path.join(args.model_dir, trt_file_name)
  77. trtexec_bin = os.path.join(tensorrt_path, 'bin/trtexec')
  78. trtexec_cmd = f"{trtexec_bin} --onnx={onnx_file_path} --saveEngine={trt_file_path} " \
  79. "--minShapes=x:1x80x1,mask:1x1x1,mu:1x80x1,t:1,spks:1x80,cond:1x80x1 " \
  80. "--maxShapes=x:1x80x4096,mask:1x1x4096,mu:1x80x4096,t:1,spks:1x80,cond:1x80x4096 --verbose " + \
  81. ("--fp16" if args.export_half else "")
  82. print("execute ", trtexec_cmd)
  83. os.system(trtexec_cmd)
  84. # print("x.shape", x.shape)
  85. # print("mask.shape", mask.shape)
  86. # print("mu.shape", mu.shape)
  87. # print("t.shape", t.shape)
  88. # print("spks.shape", spks.shape)
  89. # print("cond.shape", cond.shape)
  90. if __name__ == "__main__":
  91. main()