CosyVoice commited on
Commit
d2dea3d
·
unverified ·
2 Parent(s): 6620129 ee98842

Merge pull request #330 from hexisyztem/flow_tensorrt

Browse files
cosyvoice/bin/export_trt.py CHANGED
@@ -1,8 +1,126 @@
1
- # TODO 跟export_jit一样的逻辑,完成flow部分的estimator的onnx导出。
2
- # tensorrt的安装方式,再这里写一下步骤提示如下,如果没有安装,那么不要执行这个脚本,提示用户先安装,不给选择
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  try:
4
  import tensorrt
5
  except ImportError:
6
- print('step1, 下载\n step2. 解压,安装whl,')
7
- # 安装命令里tensosrt的根目录用环境变量导入,比如os.environ['tensorrt_root_dir']/bin/exetrace,然后python里subprocess里执行导出命令
8
- # 后面我会在run.sh里写好执行命令 tensorrt_root_dir=xxxx python cosyvoice/bin/export_trt.py --model_dir xxx
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.
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
+
15
+ import argparse
16
+ import logging
17
+ import os
18
+ import sys
19
+
20
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
21
+
22
  try:
23
  import tensorrt
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
+
33
+ import torch
34
+ from cosyvoice.cli.cosyvoice import CosyVoice
35
+
36
+ def get_args():
37
+ parser = argparse.ArgumentParser(description='Export your model for deployment')
38
+ parser.add_argument('--model_dir',
39
+ type=str,
40
+ default='pretrained_models/CosyVoice-300M-SFT',
41
+ help='Local path to the model directory')
42
+
43
+ parser.add_argument('--export_half',
44
+ action='store_true',
45
+ help='Export with half precision (FP16)')
46
+
47
+ args = parser.parse_args()
48
+ print(args)
49
+ return args
50
+
51
+ def main():
52
+ args = get_args()
53
+
54
+ cosyvoice = CosyVoice(args.model_dir, load_jit=False, load_trt=False)
55
+ estimator = cosyvoice.model.flow.decoder.estimator
56
+
57
+ dtype = torch.float32 if not args.export_half else torch.float16
58
+ device = torch.device("cuda")
59
+ batch_size = 1
60
+ seq_len = 256
61
+ hidden_size = cosyvoice.model.flow.output_size
62
+ x = torch.rand((batch_size, hidden_size, seq_len), dtype=dtype, device=device)
63
+ mask = torch.ones((batch_size, 1, seq_len), dtype=dtype, device=device)
64
+ mu = torch.rand((batch_size, hidden_size, seq_len), dtype=dtype, device=device)
65
+ t = torch.rand((batch_size, ), dtype=dtype, device=device)
66
+ spks = torch.rand((batch_size, hidden_size), dtype=dtype, device=device)
67
+ cond = torch.rand((batch_size, hidden_size, seq_len), dtype=dtype, device=device)
68
+
69
+ onnx_file_name = 'estimator_fp32.onnx' if not args.export_half else 'estimator_fp16.onnx'
70
+ onnx_file_path = os.path.join(args.model_dir, onnx_file_name)
71
+ dummy_input = (x, mask, mu, t, spks, cond)
72
+
73
+ estimator = estimator.to(dtype)
74
+
75
+ torch.onnx.export(
76
+ estimator,
77
+ dummy_input,
78
+ onnx_file_path,
79
+ export_params=True,
80
+ opset_version=18,
81
+ do_constant_folding=True,
82
+ input_names=['x', 'mask', 'mu', 't', 'spks', 'cond'],
83
+ output_names=['estimator_out'],
84
+ dynamic_axes={
85
+ 'x': {2: 'seq_len'},
86
+ 'mask': {2: 'seq_len'},
87
+ 'mu': {2: 'seq_len'},
88
+ 'cond': {2: 'seq_len'},
89
+ 'estimator_out': {2: 'seq_len'},
90
+ }
91
+ )
92
+
93
+ tensorrt_path = os.environ.get('tensorrt_root_dir')
94
+ if not tensorrt_path:
95
+ raise EnvironmentError("Please set the 'tensorrt_root_dir' environment variable.")
96
+
97
+ if not os.path.isdir(tensorrt_path):
98
+ raise FileNotFoundError(f"The directory {tensorrt_path} does not exist.")
99
+
100
+ trt_lib_path = os.path.join(tensorrt_path, "lib")
101
+ if trt_lib_path not in os.environ.get('LD_LIBRARY_PATH', ''):
102
+ print(f"Adding TensorRT lib path {trt_lib_path} to LD_LIBRARY_PATH.")
103
+ os.environ['LD_LIBRARY_PATH'] = f"{os.environ.get('LD_LIBRARY_PATH', '')}:{trt_lib_path}"
104
+
105
+ trt_file_name = 'estimator_fp32.plan' if not args.export_half else 'estimator_fp16.plan'
106
+ trt_file_path = os.path.join(args.model_dir, trt_file_name)
107
+
108
+ trtexec_bin = os.path.join(tensorrt_path, 'bin/trtexec')
109
+ trtexec_cmd = f"{trtexec_bin} --onnx={onnx_file_path} --saveEngine={trt_file_path} " \
110
+ "--minShapes=x:1x80x1,mask:1x1x1,mu:1x80x1,t:1,spks:1x80,cond:1x80x1 " \
111
+ "--maxShapes=x:1x80x4096,mask:1x1x4096,mu:1x80x4096,t:1,spks:1x80,cond:1x80x4096 --verbose " + \
112
+ ("--fp16" if args.export_half else "")
113
+
114
+ print("execute ", trtexec_cmd)
115
+
116
+ os.system(trtexec_cmd)
117
+
118
+ # print("x.shape", x.shape)
119
+ # print("mask.shape", mask.shape)
120
+ # print("mu.shape", mu.shape)
121
+ # print("t.shape", t.shape)
122
+ # print("spks.shape", spks.shape)
123
+ # print("cond.shape", cond.shape)
124
+
125
+ if __name__ == "__main__":
126
+ 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):
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,9 +39,13 @@ class CosyVoice:
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
  del configs
46
 
47
  def list_avaliable_spks(self):
 
21
 
22
  class CosyVoice:
23
 
24
+ def __init__(self, model_dir, load_jit=True, load_trt=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
  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
+ if load_trt:
47
+ self.model.load_trt(model_dir, use_fp16)
48
+
49
  del configs
50
 
51
  def list_avaliable_spks(self):
cosyvoice/cli/model.py CHANGED
@@ -11,6 +11,7 @@
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,7 +20,6 @@ from contextlib import nullcontext
19
  import uuid
20
  from cosyvoice.utils.common import fade_in_out
21
 
22
-
23
  class CosyVoiceModel:
24
 
25
  def __init__(self,
@@ -66,6 +66,22 @@ class CosyVoiceModel:
66
  llm_llm = torch.jit.load(llm_llm_model)
67
  self.llm.llm = llm_llm
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  def llm_job(self, text, prompt_text, llm_prompt_speech_token, llm_embedding, uuid):
70
  with self.llm_context:
71
  for i in self.llm.inference(text=text.to(self.device),
 
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
  import uuid
21
  from cosyvoice.utils.common import fade_in_out
22
 
 
23
  class CosyVoiceModel:
24
 
25
  def __init__(self,
 
66
  llm_llm = torch.jit.load(llm_llm_model)
67
  self.llm.llm = llm_llm
68
 
69
+ def load_trt(self, model_dir, use_fp16):
70
+ import tensorrt as trt
71
+ trt_file_name = 'estimator_fp16.plan' if use_fp16 else 'estimator_fp32.plan'
72
+ trt_file_path = os.path.join(model_dir, trt_file_name)
73
+ if not os.path.isfile(trt_file_path):
74
+ raise f"{trt_file_path} does not exist. Please use bin/export_trt.py to generate .plan file"
75
+
76
+ trt.init_libnvinfer_plugins(None, "")
77
+ logger = trt.Logger(trt.Logger.WARNING)
78
+ runtime = trt.Runtime(logger)
79
+ with open(trt_file_path, 'rb') as f:
80
+ serialized_engine = f.read()
81
+ engine = runtime.deserialize_cuda_engine(serialized_engine)
82
+ self.flow.decoder.estimator_context = engine.create_execution_context()
83
+ self.flow.decoder.estimator = None
84
+
85
  def llm_job(self, text, prompt_text, llm_prompt_speech_token, llm_embedding, uuid):
86
  with self.llm_context:
87
  for i in self.llm.inference(text=text.to(self.device),
cosyvoice/flow/decoder.py CHANGED
@@ -159,7 +159,7 @@ class ConditionalDecoder(nn.Module):
159
  _type_: _description_
160
  """
161
 
162
- t = self.time_embeddings(t)
163
  t = self.time_mlp(t)
164
 
165
  x = pack([x, mu], "b * t")[0]
 
159
  _type_: _description_
160
  """
161
 
162
+ t = self.time_embeddings(t).to(t.dtype)
163
  t = self.time_mlp(t)
164
 
165
  x = pack([x, mu], "b * t")[0]
cosyvoice/flow/flow.py CHANGED
@@ -113,7 +113,7 @@ class MaskedDiffWithXvec(torch.nn.Module):
113
  # concat text and prompt_text
114
  token_len1, token_len2 = prompt_token.shape[1], token.shape[1]
115
  token, token_len = torch.concat([prompt_token, token], dim=1), prompt_token_len + token_len
116
- mask = (~make_pad_mask(token_len)).float().unsqueeze(-1).to(embedding)
117
  token = self.input_embedding(torch.clamp(token, min=0)) * mask
118
 
119
  # text encode
 
113
  # concat text and prompt_text
114
  token_len1, token_len2 = prompt_token.shape[1], token.shape[1]
115
  token, token_len = torch.concat([prompt_token, token], dim=1), prompt_token_len + token_len
116
+ mask = (~make_pad_mask(token_len)).to(embedding.dtype).unsqueeze(-1).to(embedding)
117
  token = self.input_embedding(torch.clamp(token, min=0)) * mask
118
 
119
  # text encode
cosyvoice/flow/flow_matching.py CHANGED
@@ -50,7 +50,7 @@ class ConditionalCFM(BASECFM):
50
  shape: (batch_size, n_feats, mel_timesteps)
51
  """
52
  z = torch.randn_like(mu) * temperature
53
- t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device)
54
  if self.t_scheduler == 'cosine':
55
  t_span = 1 - torch.cos(t_span * 0.5 * torch.pi)
56
  return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond)
@@ -71,6 +71,7 @@ class ConditionalCFM(BASECFM):
71
  cond: Not used but kept for future purposes
72
  """
73
  t, _, dt = t_span[0], t_span[-1], t_span[1] - t_span[0]
 
74
 
75
  # I am storing this because I can later plot it by putting a debugger here and saving it to a file
76
  # Or in future might add like a return_all_steps flag
@@ -96,6 +97,33 @@ class ConditionalCFM(BASECFM):
96
 
97
  return sol[-1]
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  def compute_loss(self, x1, mask, mu, spks=None, cond=None):
100
  """Computes diffusion loss
101
 
 
50
  shape: (batch_size, n_feats, mel_timesteps)
51
  """
52
  z = torch.randn_like(mu) * temperature
53
+ t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
54
  if self.t_scheduler == 'cosine':
55
  t_span = 1 - torch.cos(t_span * 0.5 * torch.pi)
56
  return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond)
 
71
  cond: Not used but kept for future purposes
72
  """
73
  t, _, dt = t_span[0], t_span[-1], t_span[1] - t_span[0]
74
+ t = t.unsqueeze(dim=0)
75
 
76
  # I am storing this because I can later plot it by putting a debugger here and saving it to a file
77
  # Or in future might add like a return_all_steps flag
 
97
 
98
  return sol[-1]
99
 
100
+ def forward_estimator(self, x, mask, mu, t, spks, cond):
101
+
102
+ if self.estimator is not None:
103
+ return self.estimator.forward(x, mask, mu, t, spks, cond)
104
+ else:
105
+ assert self.training is False, 'tensorrt cannot be used in training'
106
+ bs = x.shape[0]
107
+ hs = x.shape[1]
108
+ seq_len = x.shape[2]
109
+ # assert bs == 1 and hs == 80
110
+ ret = torch.empty_like(x)
111
+ self.estimator_context.set_input_shape("x", x.shape)
112
+ self.estimator_context.set_input_shape("mask", mask.shape)
113
+ self.estimator_context.set_input_shape("mu", mu.shape)
114
+ self.estimator_context.set_input_shape("t", t.shape)
115
+ self.estimator_context.set_input_shape("spks", spks.shape)
116
+ self.estimator_context.set_input_shape("cond", cond.shape)
117
+ bindings = [x.data_ptr(), mask.data_ptr(), mu.data_ptr(), t.data_ptr(), spks.data_ptr(), cond.data_ptr(), ret.data_ptr()]
118
+ names = ['x', 'mask', 'mu', 't', 'spks', 'cond', 'estimator_out']
119
+
120
+ for i in range(len(bindings)):
121
+ self.estimator_context.set_tensor_address(names[i], bindings[i])
122
+
123
+ handle = torch.cuda.current_stream().cuda_stream
124
+ self.estimator_context.execute_async_v3(stream_handle=handle)
125
+ return ret
126
+
127
  def compute_loss(self, x1, mask, mu, spks=None, cond=None):
128
  """Computes diffusion loss
129