export_onnx.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. # Copyright (c) 2024 Antgroup Inc (authors: Zhoubofan, hexisyztem@icloud.com)
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import argparse
  15. import logging
  16. import os
  17. import sys
  18. logging.getLogger('matplotlib').setLevel(logging.WARNING)
  19. import onnxruntime as ort
  20. import numpy as np
  21. # try:
  22. # import tensorrt
  23. # import tensorrt as trt
  24. # except ImportError:
  25. # error_msg_zh = [
  26. # "step.1 下载 tensorrt .tar.gz 压缩包并解压,下载地址: https://developer.nvidia.com/tensorrt/download/10x",
  27. # "step.2 使用 tensorrt whl 包进行安装根据 python 版本对应进行安装,如 pip install ${TensorRT-Path}/python/tensorrt-10.2.0-cp38-none-linux_x86_64.whl",
  28. # "step.3 将 tensorrt 的 lib 路径添加进环境变量中,export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${TensorRT-Path}/lib/"
  29. # ]
  30. # print("\n".join(error_msg_zh))
  31. # sys.exit(1)
  32. import torch
  33. from cosyvoice.cli.cosyvoice import CosyVoice
  34. def calculate_onnx(onnx_file, x, mask, mu, t, spks, cond):
  35. providers = ['CUDAExecutionProvider']
  36. sess_options = ort.SessionOptions()
  37. providers = [
  38. 'CUDAExecutionProvider'
  39. ]
  40. # Load the ONNX model
  41. session = ort.InferenceSession(onnx_file, sess_options=sess_options, providers=providers)
  42. x_np = x.cpu().numpy()
  43. mask_np = mask.cpu().numpy()
  44. mu_np = mu.cpu().numpy()
  45. t_np = np.array(t.cpu())
  46. spks_np = spks.cpu().numpy()
  47. cond_np = cond.cpu().numpy()
  48. ort_inputs = {
  49. 'x': x_np,
  50. 'mask': mask_np,
  51. 'mu': mu_np,
  52. 't': t_np,
  53. 'spks': spks_np,
  54. 'cond': cond_np
  55. }
  56. output = session.run(None, ort_inputs)
  57. return output[0]
  58. # def calculate_tensorrt(trt_file, x, mask, mu, t, spks, cond):
  59. # trt.init_libnvinfer_plugins(None, "")
  60. # logger = trt.Logger(trt.Logger.WARNING)
  61. # runtime = trt.Runtime(logger)
  62. # with open(trt_file, 'rb') as f:
  63. # serialized_engine = f.read()
  64. # engine = runtime.deserialize_cuda_engine(serialized_engine)
  65. # context = engine.create_execution_context()
  66. # bs = x.shape[0]
  67. # hs = x.shape[1]
  68. # seq_len = x.shape[2]
  69. # ret = torch.zeros_like(x)
  70. # # Set input shapes for dynamic dimensions
  71. # context.set_input_shape("x", x.shape)
  72. # context.set_input_shape("mask", mask.shape)
  73. # context.set_input_shape("mu", mu.shape)
  74. # context.set_input_shape("t", t.shape)
  75. # context.set_input_shape("spks", spks.shape)
  76. # context.set_input_shape("cond", cond.shape)
  77. # # bindings = [x.data_ptr(), mask.data_ptr(), mu.data_ptr(), t.data_ptr(), spks.data_ptr(), cond.data_ptr(), ret.data_ptr()]
  78. # # names = ['x', 'mask', 'mu', 't', 'spks', 'cond', 'estimator_out']
  79. # #
  80. # # for i in range(len(bindings)):
  81. # # context.set_tensor_address(names[i], bindings[i])
  82. # #
  83. # # handle = torch.cuda.current_stream().cuda_stream
  84. # # context.execute_async_v3(stream_handle=handle)
  85. # # Create a list of bindings
  86. # bindings = [int(x.data_ptr()), int(mask.data_ptr()), int(mu.data_ptr()), int(t.data_ptr()), int(spks.data_ptr()), int(cond.data_ptr()), int(ret.data_ptr())]
  87. # # Execute the inference
  88. # context.execute_v2(bindings=bindings)
  89. # torch.cuda.synchronize()
  90. # return ret
  91. # def test_calculate_value(estimator, onnx_file, trt_file, dummy_input, args):
  92. # torch_output = estimator.forward(**dummy_input).cpu().detach().numpy()
  93. # onnx_output = calculate_onnx(onnx_file, **dummy_input)
  94. # tensorrt_output = calculate_tensorrt(trt_file, **dummy_input).cpu().detach().numpy()
  95. # atol = 2e-3 # Absolute tolerance
  96. # rtol = 1e-4 # Relative tolerance
  97. # print(f"args.export_half: {args.export_half}, args.model_dir: {args.model_dir}")
  98. # print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
  99. # print("torch_output diff with onnx_output: ", )
  100. # print(f"compare with atol: {atol}, rtol: {rtol} ", np.allclose(torch_output, onnx_output, atol, rtol))
  101. # print(f"max diff value: ", np.max(np.fabs(torch_output - onnx_output)))
  102. # print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
  103. # print("torch_output diff with tensorrt_output: ")
  104. # print(f"compare with atol: {atol}, rtol: {rtol} ", np.allclose(torch_output, tensorrt_output, atol, rtol))
  105. # print(f"max diff value: ", np.max(np.fabs(torch_output - tensorrt_output)))
  106. # print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
  107. # print("onnx_output diff with tensorrt_output: ")
  108. # print(f"compare with atol: {atol}, rtol: {rtol} ", np.allclose(onnx_output, tensorrt_output, atol, rtol))
  109. # print(f"max diff value: ", np.max(np.fabs(onnx_output - tensorrt_output)))
  110. # print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
  111. def get_args():
  112. parser = argparse.ArgumentParser(description='Export your model for deployment')
  113. parser.add_argument('--model_dir', type=str, default='pretrained_models/CosyVoice-300M', help='Local path to the model directory')
  114. parser.add_argument('--export_half', type=str, choices=['True', 'False'], default='False', help='Export with half precision (FP16)')
  115. # parser.add_argument('--trt_max_len', type=int, default=8192, help='Export max len')
  116. parser.add_argument('--exec_export', type=str, choices=['True', 'False'], default='True', help='Exec export')
  117. args = parser.parse_args()
  118. args.export_half = args.export_half == 'True'
  119. args.exec_export = args.exec_export == 'True'
  120. print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
  121. print(args)
  122. return args
  123. def main():
  124. args = get_args()
  125. cosyvoice = CosyVoice(args.model_dir, load_jit=False, load_trt=False)
  126. estimator = cosyvoice.model.flow.decoder.estimator
  127. dtype = torch.float32 if not args.export_half else torch.float16
  128. device = torch.device("cuda")
  129. batch_size = 1
  130. seq_len = 256
  131. out_channels = cosyvoice.model.flow.decoder.estimator.out_channels
  132. x = torch.rand((batch_size, out_channels, seq_len), dtype=dtype, device=device)
  133. mask = torch.ones((batch_size, 1, seq_len), dtype=dtype, device=device)
  134. mu = torch.rand((batch_size, out_channels, seq_len), dtype=dtype, device=device)
  135. t = torch.rand((batch_size, ), dtype=dtype, device=device)
  136. spks = torch.rand((batch_size, out_channels), dtype=dtype, device=device)
  137. cond = torch.rand((batch_size, out_channels, seq_len), dtype=dtype, device=device)
  138. onnx_file_name = 'estimator_fp32.onnx' if not args.export_half else 'estimator_fp16.onnx'
  139. onnx_file_path = os.path.join(args.model_dir, onnx_file_name)
  140. dummy_input = (x, mask, mu, t, spks, cond)
  141. estimator = estimator.to(dtype)
  142. if args.exec_export:
  143. torch.onnx.export(
  144. estimator,
  145. dummy_input,
  146. onnx_file_path,
  147. export_params=True,
  148. opset_version=18,
  149. do_constant_folding=True,
  150. input_names=['x', 'mask', 'mu', 't', 'spks', 'cond'],
  151. output_names=['estimator_out'],
  152. dynamic_axes={
  153. 'x': {2: 'seq_len'},
  154. 'mask': {2: 'seq_len'},
  155. 'mu': {2: 'seq_len'},
  156. 'cond': {2: 'seq_len'},
  157. 'estimator_out': {2: 'seq_len'},
  158. }
  159. )
  160. # tensorrt_path = os.environ.get('tensorrt_root_dir')
  161. # if not tensorrt_path:
  162. # raise EnvironmentError("Please set the 'tensorrt_root_dir' environment variable.")
  163. # if not os.path.isdir(tensorrt_path):
  164. # raise FileNotFoundError(f"The directory {tensorrt_path} does not exist.")
  165. # trt_lib_path = os.path.join(tensorrt_path, "lib")
  166. # if trt_lib_path not in os.environ.get('LD_LIBRARY_PATH', ''):
  167. # print(f"Adding TensorRT lib path {trt_lib_path} to LD_LIBRARY_PATH.")
  168. # os.environ['LD_LIBRARY_PATH'] = f"{os.environ.get('LD_LIBRARY_PATH', '')}:{trt_lib_path}"
  169. # trt_file_name = 'estimator_fp32.plan' if not args.export_half else 'estimator_fp16.plan'
  170. # trt_file_path = os.path.join(args.model_dir, trt_file_name)
  171. # trtexec_bin = os.path.join(tensorrt_path, 'bin/trtexec')
  172. # trt_max_len = args.trt_max_len
  173. # trtexec_cmd = f"{trtexec_bin} --onnx={onnx_file_path} --saveEngine={trt_file_path} " \
  174. # f"--minShapes=x:1x{out_channels}x1,mask:1x1x1,mu:1x{out_channels}x1,t:1,spks:1x{out_channels},cond:1x{out_channels}x1 " \
  175. # f"--maxShapes=x:1x{out_channels}x{trt_max_len},mask:1x1x{trt_max_len},mu:1x{out_channels}x{trt_max_len},t:1,spks:1x{out_channels},cond:1x{out_channels}x{trt_max_len} " + \
  176. # ("--fp16" if args.export_half else "")
  177. # print("execute ", trtexec_cmd)
  178. # if args.exec_export:
  179. # os.system(trtexec_cmd)
  180. # dummy_input = {'x': x, 'mask': mask, 'mu': mu, 't': t, 'spks': spks, 'cond': cond}
  181. # test_calculate_value(estimator, onnx_file_path, trt_file_path, dummy_input, args)
  182. if __name__ == "__main__":
  183. main()