export_trt.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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=${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',
  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. flow = cosyvoice.model.flow
  34. estimator = cosyvoice.model.flow.decoder.estimator
  35. dtype = torch.float32 if not args.export_half else torch.float16
  36. device = torch.device("cuda")
  37. batch_size = 1
  38. seq_len = 1024
  39. hidden_size = flow.output_size
  40. x = torch.rand((batch_size, hidden_size, seq_len), dtype=dtype, device=device)
  41. mask = torch.zeros((batch_size, 1, seq_len), dtype=dtype, device=device)
  42. mu = torch.rand((batch_size, hidden_size, seq_len), dtype=dtype, device=device)
  43. t = torch.tensor([0.], dtype=dtype, device=device)
  44. spks = torch.rand((batch_size, hidden_size), dtype=dtype, device=device)
  45. cond = torch.rand((batch_size, hidden_size, seq_len), dtype=dtype, device=device)
  46. onnx_file_name = 'estimator_fp16.onnx' if args.export_half else 'estimator_fp32.onnx'
  47. onnx_file_path = os.path.join(args.model_dir, onnx_file_name)
  48. dummy_input = (x, mask, mu, t, spks, cond)
  49. estimator = estimator.to(dtype)
  50. torch.onnx.export(
  51. estimator,
  52. dummy_input,
  53. onnx_file_path,
  54. export_params=True,
  55. opset_version=18,
  56. do_constant_folding=True,
  57. input_names=['x', 'mask', 'mu', 't', 'spks', 'cond'],
  58. output_names=['output'],
  59. dynamic_axes={
  60. 'x': {2: 'seq_len'},
  61. 'mask': {2: 'seq_len'},
  62. 'mu': {2: 'seq_len'},
  63. 'cond': {2: 'seq_len'},
  64. 'output': {2: 'seq_len'},
  65. }
  66. )
  67. tensorrt_path = os.environ.get('tensorrt_root_dir')
  68. if not tensorrt_path:
  69. raise EnvironmentError("Please set the 'tensorrt_root_dir' environment variable.")
  70. if not os.path.isdir(tensorrt_path):
  71. raise FileNotFoundError(f"The directory {tensorrt_path} does not exist.")
  72. trt_lib_path = os.path.join(tensorrt_path, "lib")
  73. if trt_lib_path not in os.environ.get('LD_LIBRARY_PATH', ''):
  74. print(f"Adding TensorRT lib path {trt_lib_path} to LD_LIBRARY_PATH.")
  75. os.environ['LD_LIBRARY_PATH'] = f"{os.environ.get('LD_LIBRARY_PATH', '')}:{trt_lib_path}"
  76. trt_file_name = 'estimator_fp16.plan' if args.export_half else 'estimator_fp32.plan'
  77. trt_file_path = os.path.join(args.model_dir, trt_file_name)
  78. trtexec_cmd = f"{tensorrt_path}/bin/trtexec --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. os.system(trtexec_cmd)
  82. if __name__ == "__main__":
  83. main()