CosyVoice commited on
Commit
2ce7240
1 Parent(s): d8197de

add onnx export

Browse files
cosyvoice/bin/export_jit.py CHANGED
@@ -44,7 +44,7 @@ def main():
44
  torch._C._jit_set_profiling_mode(False)
45
  torch._C._jit_set_profiling_executor(False)
46
 
47
- cosyvoice = CosyVoice(args.model_dir, load_jit=False, load_trt=False)
48
 
49
  # 1. export llm text_encoder
50
  llm_text_encoder = cosyvoice.model.llm.text_encoder.half()
@@ -60,5 +60,12 @@ def main():
60
  script = torch.jit.optimize_for_inference(script)
61
  script.save('{}/llm.llm.fp16.zip'.format(args.model_dir))
62
 
 
 
 
 
 
 
 
63
  if __name__ == '__main__':
64
  main()
 
44
  torch._C._jit_set_profiling_mode(False)
45
  torch._C._jit_set_profiling_executor(False)
46
 
47
+ cosyvoice = CosyVoice(args.model_dir, load_jit=False, load_onnx=False)
48
 
49
  # 1. export llm text_encoder
50
  llm_text_encoder = cosyvoice.model.llm.text_encoder.half()
 
60
  script = torch.jit.optimize_for_inference(script)
61
  script.save('{}/llm.llm.fp16.zip'.format(args.model_dir))
62
 
63
+ # 3. export flow encoder
64
+ flow_encoder = cosyvoice.model.flow.encoder
65
+ script = torch.jit.script(flow_encoder)
66
+ script = torch.jit.freeze(script)
67
+ script = torch.jit.optimize_for_inference(script)
68
+ script.save('{}/flow.encoder.fp32.zip'.format(args.model_dir))
69
+
70
  if __name__ == '__main__':
71
  main()
cosyvoice/bin/export_onnx.py CHANGED
@@ -1,4 +1,5 @@
1
  # Copyright (c) 2024 Antgroup Inc (authors: Zhoubofan, [email protected])
 
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.
@@ -12,217 +13,97 @@
12
  # See the License for the specific language governing permissions and
13
  # limitations under the License.
14
 
 
 
15
  import argparse
16
  import logging
 
17
  import os
18
  import sys
19
-
20
- logging.getLogger('matplotlib').setLevel(logging.WARNING)
21
- import onnxruntime as ort
22
- import numpy as np
23
-
24
- # try:
25
- # import tensorrt
26
- # import tensorrt as trt
27
- # except ImportError:
28
- # error_msg_zh = [
29
- # "step.1 下载 tensorrt .tar.gz 压缩包并解压,下载地址: https://developer.nvidia.com/tensorrt/download/10x",
30
- # "step.2 使用 tensorrt whl 包进行安装根据 python 版本对应进行安装,如 pip install ${TensorRT-Path}/python/tensorrt-10.2.0-cp38-none-linux_x86_64.whl",
31
- # "step.3 将 tensorrt 的 lib 路径添加进环境变量中,export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${TensorRT-Path}/lib/"
32
- # ]
33
- # print("\n".join(error_msg_zh))
34
- # sys.exit(1)
35
-
36
  import torch
 
37
  from cosyvoice.cli.cosyvoice import CosyVoice
38
 
39
 
40
- def calculate_onnx(onnx_file, x, mask, mu, t, spks, cond):
41
- providers = ['CUDAExecutionProvider']
42
- sess_options = ort.SessionOptions()
43
-
44
- providers = [
45
- 'CUDAExecutionProvider'
46
- ]
47
-
48
- # Load the ONNX model
49
- session = ort.InferenceSession(onnx_file, sess_options=sess_options, providers=providers)
50
-
51
- x_np = x.cpu().numpy()
52
- mask_np = mask.cpu().numpy()
53
- mu_np = mu.cpu().numpy()
54
- t_np = np.array(t.cpu())
55
- spks_np = spks.cpu().numpy()
56
- cond_np = cond.cpu().numpy()
57
-
58
- ort_inputs = {
59
- 'x': x_np,
60
- 'mask': mask_np,
61
- 'mu': mu_np,
62
- 't': t_np,
63
- 'spks': spks_np,
64
- 'cond': cond_np
65
- }
66
-
67
- output = session.run(None, ort_inputs)
68
-
69
- return output[0]
70
-
71
- # def calculate_tensorrt(trt_file, x, mask, mu, t, spks, cond):
72
- # trt.init_libnvinfer_plugins(None, "")
73
- # logger = trt.Logger(trt.Logger.WARNING)
74
- # runtime = trt.Runtime(logger)
75
- # with open(trt_file, 'rb') as f:
76
- # serialized_engine = f.read()
77
- # engine = runtime.deserialize_cuda_engine(serialized_engine)
78
- # context = engine.create_execution_context()
79
-
80
- # bs = x.shape[0]
81
- # hs = x.shape[1]
82
- # seq_len = x.shape[2]
83
-
84
- # ret = torch.zeros_like(x)
85
-
86
- # # Set input shapes for dynamic dimensions
87
- # context.set_input_shape("x", x.shape)
88
- # context.set_input_shape("mask", mask.shape)
89
- # context.set_input_shape("mu", mu.shape)
90
- # context.set_input_shape("t", t.shape)
91
- # context.set_input_shape("spks", spks.shape)
92
- # context.set_input_shape("cond", cond.shape)
93
-
94
- # # bindings = [x.data_ptr(), mask.data_ptr(), mu.data_ptr(), t.data_ptr(), spks.data_ptr(), cond.data_ptr(), ret.data_ptr()]
95
- # # names = ['x', 'mask', 'mu', 't', 'spks', 'cond', 'estimator_out']
96
- # #
97
- # # for i in range(len(bindings)):
98
- # # context.set_tensor_address(names[i], bindings[i])
99
- # #
100
- # # handle = torch.cuda.current_stream().cuda_stream
101
- # # context.execute_async_v3(stream_handle=handle)
102
-
103
- # # Create a list of bindings
104
- # 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())]
105
-
106
- # # Execute the inference
107
- # context.execute_v2(bindings=bindings)
108
-
109
- # torch.cuda.synchronize()
110
-
111
- # return ret
112
-
113
-
114
- # def test_calculate_value(estimator, onnx_file, trt_file, dummy_input, args):
115
- # torch_output = estimator.forward(**dummy_input).cpu().detach().numpy()
116
- # onnx_output = calculate_onnx(onnx_file, **dummy_input)
117
- # tensorrt_output = calculate_tensorrt(trt_file, **dummy_input).cpu().detach().numpy()
118
- # atol = 2e-3 # Absolute tolerance
119
- # rtol = 1e-4 # Relative tolerance
120
-
121
- # print(f"args.export_half: {args.export_half}, args.model_dir: {args.model_dir}")
122
- # print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
123
-
124
- # print("torch_output diff with onnx_output: ", )
125
- # print(f"compare with atol: {atol}, rtol: {rtol} ", np.allclose(torch_output, onnx_output, atol, rtol))
126
- # print(f"max diff value: ", np.max(np.fabs(torch_output - onnx_output)))
127
- # print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
128
-
129
- # print("torch_output diff with tensorrt_output: ")
130
- # print(f"compare with atol: {atol}, rtol: {rtol} ", np.allclose(torch_output, tensorrt_output, atol, rtol))
131
- # print(f"max diff value: ", np.max(np.fabs(torch_output - tensorrt_output)))
132
- # print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
133
-
134
- # print("onnx_output diff with tensorrt_output: ")
135
- # print(f"compare with atol: {atol}, rtol: {rtol} ", np.allclose(onnx_output, tensorrt_output, atol, rtol))
136
- # print(f"max diff value: ", np.max(np.fabs(onnx_output - tensorrt_output)))
137
- # print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
138
 
139
 
140
  def get_args():
141
- parser = argparse.ArgumentParser(description='Export your model for deployment')
142
- parser.add_argument('--model_dir', type=str, default='pretrained_models/CosyVoice-300M', help='Local path to the model directory')
143
- parser.add_argument('--export_half', type=str, choices=['True', 'False'], default='False', help='Export with half precision (FP16)')
144
- # parser.add_argument('--trt_max_len', type=int, default=8192, help='Export max len')
145
- parser.add_argument('--exec_export', type=str, choices=['True', 'False'], default='True', help='Exec export')
146
-
147
  args = parser.parse_args()
148
- args.export_half = args.export_half == 'True'
149
- args.exec_export = args.exec_export == 'True'
150
- print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
151
  print(args)
152
  return args
153
 
154
  def main():
155
  args = get_args()
 
 
156
 
157
- cosyvoice = CosyVoice(args.model_dir, load_jit=False, load_trt=False)
 
 
158
  estimator = cosyvoice.model.flow.decoder.estimator
159
 
160
- dtype = torch.float32 if not args.export_half else torch.float16
161
- device = torch.device("cuda")
162
- batch_size = 1
163
- seq_len = 256
164
  out_channels = cosyvoice.model.flow.decoder.estimator.out_channels
165
- x = torch.rand((batch_size, out_channels, seq_len), dtype=dtype, device=device)
166
- mask = torch.ones((batch_size, 1, seq_len), dtype=dtype, device=device)
167
- mu = torch.rand((batch_size, out_channels, seq_len), dtype=dtype, device=device)
168
- t = torch.rand((batch_size, ), dtype=dtype, device=device)
169
- spks = torch.rand((batch_size, out_channels), dtype=dtype, device=device)
170
- cond = torch.rand((batch_size, out_channels, seq_len), dtype=dtype, device=device)
171
-
172
- onnx_file_name = 'estimator_fp32.onnx' if not args.export_half else 'estimator_fp16.onnx'
173
- onnx_file_path = os.path.join(args.model_dir, onnx_file_name)
174
- dummy_input = (x, mask, mu, t, spks, cond)
175
-
176
- estimator = estimator.to(dtype)
177
-
178
- if args.exec_export:
179
- torch.onnx.export(
180
- estimator,
181
- dummy_input,
182
- onnx_file_path,
183
- export_params=True,
184
- opset_version=18,
185
- do_constant_folding=True,
186
- input_names=['x', 'mask', 'mu', 't', 'spks', 'cond'],
187
- output_names=['estimator_out'],
188
- dynamic_axes={
189
- 'x': {2: 'seq_len'},
190
- 'mask': {2: 'seq_len'},
191
- 'mu': {2: 'seq_len'},
192
- 'cond': {2: 'seq_len'},
193
- 'estimator_out': {2: 'seq_len'},
194
- }
195
- )
196
-
197
- # tensorrt_path = os.environ.get('tensorrt_root_dir')
198
- # if not tensorrt_path:
199
- # raise EnvironmentError("Please set the 'tensorrt_root_dir' environment variable.")
200
-
201
- # if not os.path.isdir(tensorrt_path):
202
- # raise FileNotFoundError(f"The directory {tensorrt_path} does not exist.")
203
-
204
- # trt_lib_path = os.path.join(tensorrt_path, "lib")
205
- # if trt_lib_path not in os.environ.get('LD_LIBRARY_PATH', ''):
206
- # print(f"Adding TensorRT lib path {trt_lib_path} to LD_LIBRARY_PATH.")
207
- # os.environ['LD_LIBRARY_PATH'] = f"{os.environ.get('LD_LIBRARY_PATH', '')}:{trt_lib_path}"
208
-
209
- # trt_file_name = 'estimator_fp32.plan' if not args.export_half else 'estimator_fp16.plan'
210
- # trt_file_path = os.path.join(args.model_dir, trt_file_name)
211
-
212
- # trtexec_bin = os.path.join(tensorrt_path, 'bin/trtexec')
213
- # trt_max_len = args.trt_max_len
214
- # trtexec_cmd = f"{trtexec_bin} --onnx={onnx_file_path} --saveEngine={trt_file_path} " \
215
- # 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 " \
216
- # 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} " + \
217
- # ("--fp16" if args.export_half else "")
218
-
219
- # print("execute ", trtexec_cmd)
220
-
221
- # if args.exec_export:
222
- # os.system(trtexec_cmd)
223
-
224
- # dummy_input = {'x': x, 'mask': mask, 'mu': mu, 't': t, 'spks': spks, 'cond': cond}
225
- # test_calculate_value(estimator, onnx_file_path, trt_file_path, dummy_input, args)
226
 
227
  if __name__ == "__main__":
228
  main()
 
1
  # Copyright (c) 2024 Antgroup Inc (authors: Zhoubofan, [email protected])
2
+ # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu)
3
  #
4
  # Licensed under the Apache License, Version 2.0 (the "License");
5
  # you may not use this file except in compliance with the License.
 
13
  # See the License for the specific language governing permissions and
14
  # limitations under the License.
15
 
16
+ from __future__ import print_function
17
+
18
  import argparse
19
  import logging
20
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
21
  import os
22
  import sys
23
+ ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
24
+ sys.path.append('{}/../..'.format(ROOT_DIR))
25
+ sys.path.append('{}/../../third_party/Matcha-TTS'.format(ROOT_DIR))
26
+ import onnxruntime
27
+ import random
 
 
 
 
 
 
 
 
 
 
 
 
28
  import torch
29
+ from tqdm import tqdm
30
  from cosyvoice.cli.cosyvoice import CosyVoice
31
 
32
 
33
+ def get_dummy_input(batch_size, seq_len, out_channels, device):
34
+ x = torch.rand((batch_size, out_channels, seq_len), dtype=torch.float32, device=device)
35
+ mask = torch.ones((batch_size, 1, seq_len), dtype=torch.float32, device=device)
36
+ mu = torch.rand((batch_size, out_channels, seq_len), dtype=torch.float32, device=device)
37
+ t = torch.rand((batch_size), dtype=torch.float32, device=device)
38
+ spks = torch.rand((batch_size, out_channels), dtype=torch.float32, device=device)
39
+ cond = torch.rand((batch_size, out_channels, seq_len), dtype=torch.float32, device=device)
40
+ return x, mask, mu, t, spks, cond
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
 
43
  def get_args():
44
+ parser = argparse.ArgumentParser(description='export your model for deployment')
45
+ parser.add_argument('--model_dir',
46
+ type=str,
47
+ default='pretrained_models/CosyVoice-300M',
48
+ help='local path')
 
49
  args = parser.parse_args()
 
 
 
50
  print(args)
51
  return args
52
 
53
  def main():
54
  args = get_args()
55
+ logging.basicConfig(level=logging.DEBUG,
56
+ format='%(asctime)s %(levelname)s %(message)s')
57
 
58
+ cosyvoice = CosyVoice(args.model_dir, load_jit=False, load_onnx=False)
59
+
60
+ # 1. export flow decoder estimator
61
  estimator = cosyvoice.model.flow.decoder.estimator
62
 
63
+ device = cosyvoice.model.device
64
+ batch_size, seq_len = 1, 256
 
 
65
  out_channels = cosyvoice.model.flow.decoder.estimator.out_channels
66
+ x, mask, mu, t, spks, cond = get_dummy_input(batch_size, seq_len, out_channels, device)
67
+ torch.onnx.export(
68
+ estimator,
69
+ (x, mask, mu, t, spks, cond),
70
+ '{}/flow.decoder.estimator.fp32.onnx'.format(args.model_dir),
71
+ export_params=True,
72
+ opset_version=18,
73
+ do_constant_folding=True,
74
+ input_names=['x', 'mask', 'mu', 't', 'spks', 'cond'],
75
+ output_names=['estimator_out'],
76
+ dynamic_axes={
77
+ 'x': {0: 'batch_size', 2: 'seq_len'},
78
+ 'mask': {0: 'batch_size', 2: 'seq_len'},
79
+ 'mu': {0: 'batch_size', 2: 'seq_len'},
80
+ 'cond': {0: 'batch_size', 2: 'seq_len'},
81
+ 't': {0: 'batch_size'},
82
+ 'spks': {0: 'batch_size'},
83
+ 'estimator_out': {0: 'batch_size', 2: 'seq_len'},
84
+ }
85
+ )
86
+
87
+ # 2. test computation consistency
88
+ option = onnxruntime.SessionOptions()
89
+ option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
90
+ option.intra_op_num_threads = 1
91
+ providers = ['CUDAExecutionProvider' if torch.cuda.is_available() else 'CPUExecutionProvider']
92
+ estimator_onnx = onnxruntime.InferenceSession('{}/flow.decoder.estimator.fp32.onnx'.format(args.model_dir), sess_options=option, providers=providers)
93
+
94
+ for _ in tqdm(range(10)):
95
+ x, mask, mu, t, spks, cond = get_dummy_input(random.randint(1, 6), random.randint(16, 512), out_channels, device)
96
+ output_pytorch = estimator(x, mask, mu, t, spks, cond)
97
+ ort_inputs = {
98
+ 'x': x.cpu().numpy(),
99
+ 'mask': mask.cpu().numpy(),
100
+ 'mu': mu.cpu().numpy(),
101
+ 't': t.cpu().numpy(),
102
+ 'spks': spks.cpu().numpy(),
103
+ 'cond': cond.cpu().numpy()
104
+ }
105
+ output_onnx = estimator_onnx.run(None, ort_inputs)[0]
106
+ torch.testing.assert_allclose(output_pytorch, torch.from_numpy(output_onnx).to(device), rtol=1e-2, atol=1e-4)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
  if __name__ == "__main__":
109
  main()
cosyvoice/cli/cosyvoice.py CHANGED
@@ -21,7 +21,7 @@ from cosyvoice.utils.file_utils import logging
21
 
22
  class CosyVoice:
23
 
24
- def __init__(self, model_dir, load_jit=True, load_trt=False, load_onnx=True, use_fp16=False):
25
  instruct = True if '-Instruct' in model_dir else False
26
  self.model_dir = model_dir
27
  if not os.path.exists(model_dir):
@@ -39,17 +39,12 @@ class CosyVoice:
39
  self.model.load('{}/llm.pt'.format(model_dir),
40
  '{}/flow.pt'.format(model_dir),
41
  '{}/hift.pt'.format(model_dir))
42
-
43
  if load_jit:
44
  self.model.load_jit('{}/llm.text_encoder.fp16.zip'.format(model_dir),
45
- '{}/llm.llm.fp16.zip'.format(model_dir))
46
-
47
- # if load_trt:
48
- # self.model.load_trt(model_dir, use_fp16)
49
-
50
  if load_onnx:
51
- self.model.load_onnx(model_dir, use_fp16)
52
-
53
  del configs
54
 
55
  def list_avaliable_spks(self):
 
21
 
22
  class CosyVoice:
23
 
24
+ def __init__(self, model_dir, load_jit=True, load_onnx=True):
25
  instruct = True if '-Instruct' in model_dir else False
26
  self.model_dir = model_dir
27
  if not os.path.exists(model_dir):
 
39
  self.model.load('{}/llm.pt'.format(model_dir),
40
  '{}/flow.pt'.format(model_dir),
41
  '{}/hift.pt'.format(model_dir))
 
42
  if load_jit:
43
  self.model.load_jit('{}/llm.text_encoder.fp16.zip'.format(model_dir),
44
+ '{}/llm.llm.fp16.zip'.format(model_dir),
45
+ '{}/flow.encoder.fp32.zip'.format(model_dir))
 
 
 
46
  if load_onnx:
47
+ self.model.load_onnx('{}/flow.decoder.estimator.fp32.onnx'.format(model_dir))
 
48
  del configs
49
 
50
  def list_avaliable_spks(self):
cosyvoice/cli/model.py CHANGED
@@ -11,7 +11,6 @@
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 os
15
  import torch
16
  import numpy as np
17
  import threading
@@ -20,7 +19,6 @@ from contextlib import nullcontext
20
  import uuid
21
  from cosyvoice.utils.common import fade_in_out
22
  import numpy as np
23
- import onnxruntime as ort
24
 
25
  class CosyVoiceModel:
26
 
@@ -62,47 +60,22 @@ class CosyVoiceModel:
62
  self.hift.load_state_dict(torch.load(hift_model, map_location=self.device))
63
  self.hift.to(self.device).eval()
64
 
65
- def load_jit(self, llm_text_encoder_model, llm_llm_model):
66
  llm_text_encoder = torch.jit.load(llm_text_encoder_model)
67
  self.llm.text_encoder = llm_text_encoder
68
  llm_llm = torch.jit.load(llm_llm_model)
69
  self.llm.llm = llm_llm
 
 
70
 
71
- # def load_trt(self, model_dir, use_fp16):
72
- # import tensorrt as trt
73
- # trt_file_name = 'estimator_fp16.plan' if use_fp16 else 'estimator_fp32.plan'
74
- # trt_file_path = os.path.join(model_dir, trt_file_name)
75
- # if not os.path.isfile(trt_file_path):
76
- # raise f"{trt_file_path} does not exist. Please use bin/export_trt.py to generate .plan file"
77
-
78
- # trt.init_libnvinfer_plugins(None, "")
79
- # logger = trt.Logger(trt.Logger.WARNING)
80
- # runtime = trt.Runtime(logger)
81
- # with open(trt_file_path, 'rb') as f:
82
- # serialized_engine = f.read()
83
- # engine = runtime.deserialize_cuda_engine(serialized_engine)
84
- # self.flow.decoder.estimator_context = engine.create_execution_context()
85
- # self.flow.decoder.estimator = None
86
-
87
- def load_onnx(self, model_dir, use_fp16):
88
- onnx_file_name = 'estimator_fp16.onnx' if use_fp16 else 'estimator_fp32.onnx'
89
- onnx_file_path = os.path.join(model_dir, onnx_file_name)
90
- if not os.path.isfile(onnx_file_path):
91
- raise f"{onnx_file_path} does not exist. Please use bin/export_trt.py to generate .onnx file"
92
-
93
- providers = ['CUDAExecutionProvider']
94
- sess_options = ort.SessionOptions()
95
-
96
- # Add TensorRT Execution Provider
97
- providers = [
98
- 'CUDAExecutionProvider'
99
- ]
100
-
101
- # Load the ONNX model
102
- self.flow.decoder.session = ort.InferenceSession(onnx_file_path, sess_options=sess_options, providers=providers)
103
- # self.flow.decoder.estimator_context = None
104
- self.flow.decoder.estimator = None
105
-
106
 
107
  def llm_job(self, text, prompt_text, llm_prompt_speech_token, llm_embedding, uuid):
108
  with self.llm_context:
@@ -207,4 +180,5 @@ class CosyVoiceModel:
207
  self.llm_end_dict.pop(this_uuid)
208
  self.mel_overlap_dict.pop(this_uuid)
209
  self.hift_cache_dict.pop(this_uuid)
210
- torch.cuda.synchronize()
 
 
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 torch
15
  import numpy as np
16
  import threading
 
19
  import uuid
20
  from cosyvoice.utils.common import fade_in_out
21
  import numpy as np
 
22
 
23
  class CosyVoiceModel:
24
 
 
60
  self.hift.load_state_dict(torch.load(hift_model, map_location=self.device))
61
  self.hift.to(self.device).eval()
62
 
63
+ def load_jit(self, llm_text_encoder_model, llm_llm_model, flow_encoder_model):
64
  llm_text_encoder = torch.jit.load(llm_text_encoder_model)
65
  self.llm.text_encoder = llm_text_encoder
66
  llm_llm = torch.jit.load(llm_llm_model)
67
  self.llm.llm = llm_llm
68
+ flow_encoder = torch.jit.load(flow_encoder_model)
69
+ self.flow.encoder = flow_encoder
70
 
71
+ def load_onnx(self, flow_decoder_estimator_model):
72
+ import onnxruntime
73
+ option = onnxruntime.SessionOptions()
74
+ option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
75
+ option.intra_op_num_threads = 1
76
+ providers = ['CUDAExecutionProvider' if torch.cuda.is_available() else 'CPUExecutionProvider']
77
+ del self.flow.decoder.estimator
78
+ self.flow.decoder.estimator = onnxruntime.InferenceSession(flow_decoder_estimator_model, sess_options=option, providers=providers)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
  def llm_job(self, text, prompt_text, llm_prompt_speech_token, llm_embedding, uuid):
81
  with self.llm_context:
 
180
  self.llm_end_dict.pop(this_uuid)
181
  self.mel_overlap_dict.pop(this_uuid)
182
  self.hift_cache_dict.pop(this_uuid)
183
+ if torch.cuda.is_available():
184
+ torch.cuda.synchronize()
cosyvoice/flow/flow_matching.py CHANGED
@@ -31,8 +31,6 @@ class ConditionalCFM(BASECFM):
31
  in_channels = in_channels + (spk_emb_dim if n_spks > 0 else 0)
32
  # Just change the architecture of the estimator here
33
  self.estimator = estimator
34
- self.estimator_context = None # for tensorrt
35
- self.session = None # for onnx
36
 
37
  @torch.inference_mode()
38
  def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None):
@@ -82,10 +80,10 @@ class ConditionalCFM(BASECFM):
82
  sol = []
83
 
84
  for step in range(1, len(t_span)):
85
- dphi_dt = self.estimator(x, mask, mu, t, spks, cond)
86
  # Classifier-Free Guidance inference introduced in VoiceBox
87
  if self.inference_cfg_rate > 0:
88
- cfg_dphi_dt = self.estimator(
89
  x, mask,
90
  torch.zeros_like(mu), t,
91
  torch.zeros_like(spks) if spks is not None else None,
@@ -102,51 +100,20 @@ class ConditionalCFM(BASECFM):
102
  return sol[-1]
103
 
104
  def forward_estimator(self, x, mask, mu, t, spks, cond):
105
-
106
- if self.estimator is not None:
107
  return self.estimator.forward(x, mask, mu, t, spks, cond)
108
- # elif self.estimator_context is not None:
109
- # assert self.training is False, 'tensorrt cannot be used in training'
110
- # bs = x.shape[0]
111
- # hs = x.shape[1]
112
- # seq_len = x.shape[2]
113
- # # assert bs == 1 and hs == 80
114
- # ret = torch.empty_like(x)
115
- # self.estimator_context.set_input_shape("x", x.shape)
116
- # self.estimator_context.set_input_shape("mask", mask.shape)
117
- # self.estimator_context.set_input_shape("mu", mu.shape)
118
- # self.estimator_context.set_input_shape("t", t.shape)
119
- # self.estimator_context.set_input_shape("spks", spks.shape)
120
- # self.estimator_context.set_input_shape("cond", cond.shape)
121
-
122
- # # Create a list of bindings
123
- # 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())]
124
-
125
- # # Execute the inference
126
- # self.estimator_context.execute_v2(bindings=bindings)
127
- # return ret
128
  else:
129
- x_np = x.cpu().numpy()
130
- mask_np = mask.cpu().numpy()
131
- mu_np = mu.cpu().numpy()
132
- t_np = t.cpu().numpy()
133
- spks_np = spks.cpu().numpy()
134
- cond_np = cond.cpu().numpy()
135
-
136
  ort_inputs = {
137
- 'x': x_np,
138
- 'mask': mask_np,
139
- 'mu': mu_np,
140
- 't': t_np,
141
- 'spks': spks_np,
142
- 'cond': cond_np
143
  }
144
-
145
- output = self.session.run(None, ort_inputs)[0]
146
-
147
  return torch.tensor(output, dtype=x.dtype, device=x.device)
148
 
149
-
150
  def compute_loss(self, x1, mask, mu, spks=None, cond=None):
151
  """Computes diffusion loss
152
 
 
31
  in_channels = in_channels + (spk_emb_dim if n_spks > 0 else 0)
32
  # Just change the architecture of the estimator here
33
  self.estimator = estimator
 
 
34
 
35
  @torch.inference_mode()
36
  def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None):
 
80
  sol = []
81
 
82
  for step in range(1, len(t_span)):
83
+ dphi_dt = self.forward_estimator(x, mask, mu, t, spks, cond)
84
  # Classifier-Free Guidance inference introduced in VoiceBox
85
  if self.inference_cfg_rate > 0:
86
+ cfg_dphi_dt = self.forward_estimator(
87
  x, mask,
88
  torch.zeros_like(mu), t,
89
  torch.zeros_like(spks) if spks is not None else None,
 
100
  return sol[-1]
101
 
102
  def forward_estimator(self, x, mask, mu, t, spks, cond):
103
+ if isinstance(self.estimator, torch.nn.Module):
 
104
  return self.estimator.forward(x, mask, mu, t, spks, cond)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  else:
 
 
 
 
 
 
 
106
  ort_inputs = {
107
+ 'x': x.cpu().numpy(),
108
+ 'mask': mask.cpu().numpy(),
109
+ 'mu': mu.cpu().numpy(),
110
+ 't': t.cpu().numpy(),
111
+ 'spks': spks.cpu().numpy(),
112
+ 'cond': cond.cpu().numpy()
113
  }
114
+ output = self.estimator.run(None, ort_inputs)[0]
 
 
115
  return torch.tensor(output, dtype=x.dtype, device=x.device)
116
 
 
117
  def compute_loss(self, x1, mask, mu, spks=None, cond=None):
118
  """Computes diffusion loss
119
 
requirements.txt CHANGED
@@ -15,6 +15,7 @@ matplotlib==3.7.5
15
  modelscope==1.15.0
16
  networkx==3.1
17
  omegaconf==2.3.0
 
18
  onnxruntime-gpu==1.16.0; sys_platform == 'linux'
19
  onnxruntime==1.16.0; sys_platform == 'darwin' or sys_platform == 'windows'
20
  openai-whisper==20231117
 
15
  modelscope==1.15.0
16
  networkx==3.1
17
  omegaconf==2.3.0
18
+ onnx==1.16.0
19
  onnxruntime-gpu==1.16.0; sys_platform == 'linux'
20
  onnxruntime==1.16.0; sys_platform == 'darwin' or sys_platform == 'windows'
21
  openai-whisper==20231117