zhoubofan.zbf commited on
Commit
5f21aef
·
1 Parent(s): 1d881df

add flow decoder tensorrt infer

Browse files
cosyvoice/bin/export_trt.py CHANGED
@@ -1,8 +1,103 @@
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
+ import argparse
2
+ import logging
3
+ import os
4
+ import sys
5
+
6
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
7
+
8
  try:
9
  import tensorrt
10
  except ImportError:
11
+ error_msg_zh = [
12
+ "step.1 下载 tensorrt .tar.gz 压缩包并解压,下载地址: https://developer.nvidia.com/tensorrt/download/10x",
13
+ "step.2 使用 tensorrt whl 包进行安装根据 python 版本对应进行安装,如 pip install ${TensorRT-Path}/python/tensorrt-10.2.0-cp38-none-linux_x86_64.whl",
14
+ "step.3 将 tensorrt 的 lib 路径添加进环境变量中,export LD_LIBRARY_PATH=${TensorRT-Path}/lib/"
15
+ ]
16
+ print("\n".join(error_msg_zh))
17
+ sys.exit(1)
18
+
19
+ import torch
20
+ from cosyvoice.cli.cosyvoice import CosyVoice
21
+
22
+ def get_args():
23
+ parser = argparse.ArgumentParser(description='Export your model for deployment')
24
+ parser.add_argument('--model_dir',
25
+ type=str,
26
+ default='pretrained_models/CosyVoice-300M',
27
+ help='Local path to the model directory')
28
+
29
+ parser.add_argument('--export_half',
30
+ action='store_true',
31
+ help='Export with half precision (FP16)')
32
+
33
+ args = parser.parse_args()
34
+ print(args)
35
+ return args
36
+
37
+ def main():
38
+ args = get_args()
39
+
40
+ cosyvoice = CosyVoice(args.model_dir, load_jit=False, load_trt=False)
41
+
42
+ flow = cosyvoice.model.flow
43
+ estimator = cosyvoice.model.flow.decoder.estimator
44
+
45
+ dtype = torch.float32 if not args.export_half else torch.float16
46
+ device = torch.device("cuda")
47
+ batch_size = 1
48
+ seq_len = 1024
49
+ hidden_size = flow.output_size
50
+ x = torch.rand((batch_size, hidden_size, seq_len), dtype=dtype, device=device)
51
+ mask = torch.zeros((batch_size, 1, seq_len), dtype=dtype, device=device)
52
+ mu = torch.rand((batch_size, hidden_size, seq_len), dtype=dtype, device=device)
53
+ t = torch.tensor([0.], dtype=dtype, device=device)
54
+ spks = torch.rand((batch_size, hidden_size), dtype=dtype, device=device)
55
+ cond = torch.rand((batch_size, hidden_size, seq_len), dtype=dtype, device=device)
56
+
57
+ onnx_file_name = 'estimator_fp16.onnx' if args.export_half else 'estimator_fp32.onnx'
58
+ onnx_file_path = os.path.join(args.model_dir, onnx_file_name)
59
+ dummy_input = (x, mask, mu, t, spks, cond)
60
+
61
+ estimator = estimator.to(dtype)
62
+
63
+ torch.onnx.export(
64
+ estimator,
65
+ dummy_input,
66
+ onnx_file_path,
67
+ export_params=True,
68
+ opset_version=18,
69
+ do_constant_folding=True,
70
+ input_names=['x', 'mask', 'mu', 't', 'spks', 'cond'],
71
+ output_names=['output'],
72
+ dynamic_axes={
73
+ 'x': {2: 'seq_len'},
74
+ 'mask': {2: 'seq_len'},
75
+ 'mu': {2: 'seq_len'},
76
+ 'cond': {2: 'seq_len'},
77
+ 'output': {2: 'seq_len'},
78
+ }
79
+ )
80
+
81
+ tensorrt_path = os.environ.get('tensorrt_root_dir')
82
+ if not tensorrt_path:
83
+ raise EnvironmentError("Please set the 'tensorrt_root_dir' environment variable.")
84
+
85
+ if not os.path.isdir(tensorrt_path):
86
+ raise FileNotFoundError(f"The directory {tensorrt_path} does not exist.")
87
+
88
+ trt_lib_path = os.path.join(tensorrt_path, "lib")
89
+ if trt_lib_path not in os.environ.get('LD_LIBRARY_PATH', ''):
90
+ print(f"Adding TensorRT lib path {trt_lib_path} to LD_LIBRARY_PATH.")
91
+ os.environ['LD_LIBRARY_PATH'] = f"{os.environ.get('LD_LIBRARY_PATH', '')}:{trt_lib_path}"
92
+
93
+ trt_file_name = 'estimator_fp16.plan' if args.export_half else 'estimator_fp32.plan'
94
+ trt_file_path = os.path.join(args.model_dir, trt_file_name)
95
+
96
+ trtexec_cmd = f"{tensorrt_path}/bin/trtexec --onnx={onnx_file_path} --saveEngine={trt_file_path} " \
97
+ "--minShapes=x:1x80x1,mask:1x1x1,mu:1x80x1,t:1,spks:1x80,cond:1x80x1 " \
98
+ "--maxShapes=x:1x80x4096,mask:1x1x4096,mu:1x80x4096,t:1,spks:1x80,cond:1x80x4096 --verbose"
99
+
100
+ os.system(trtexec_cmd)
101
+
102
+ if __name__ == "__main__":
103
+ 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=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):
@@ -43,8 +43,7 @@ class CosyVoice:
43
  self.model.load_jit('{}/llm.text_encoder.fp16.zip'.format(model_dir),
44
  '{}/llm.llm.fp16.zip'.format(model_dir))
45
  if load_trt:
46
- # TODO
47
- self.model.load_trt()
48
  del configs
49
 
50
  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):
 
43
  self.model.load_jit('{}/llm.text_encoder.fp16.zip'.format(model_dir),
44
  '{}/llm.llm.fp16.zip'.format(model_dir))
45
  if load_trt:
46
+ self.model.load_trt(model_dir, use_fp16)
 
47
  del configs
48
 
49
  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,6 +20,10 @@ from contextlib import nullcontext
19
  import uuid
20
  from cosyvoice.utils.common import fade_in_out
21
 
 
 
 
 
22
 
23
  class CosyVoiceModel:
24
 
@@ -66,10 +71,20 @@ class CosyVoiceModel:
66
  llm_llm = torch.jit.load(llm_llm_model)
67
  self.llm.llm = llm_llm
68
 
69
- def load_trt(self):
70
- # TODO 你需要的TRT推理的准备
71
- self.flow.decoder.estimator = xxx
72
- self.flow.decoder.session = xxx
 
 
 
 
 
 
 
 
 
 
73
 
74
  def llm_job(self, text, prompt_text, llm_prompt_speech_token, llm_embedding, uuid):
75
  with self.llm_context:
 
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
+ try:
24
+ import tensorrt as trt
25
+ except ImportError:
26
+ ...
27
 
28
  class CosyVoiceModel:
29
 
 
71
  llm_llm = torch.jit.load(llm_llm_model)
72
  self.llm.llm = llm_llm
73
 
74
+ def load_trt(self, model_dir, use_fp16):
75
+ trt_file_name = 'estimator_fp16.plan' if use_fp16 else 'estimator_fp32.plan'
76
+ trt_file_path = os.path.join(model_dir, trt_file_name)
77
+ if not os.path.isfile(trt_file_path):
78
+ raise f"{trt_file_path} does not exist. Please use bin/export_trt.py to generate .plan file"
79
+
80
+ trt.init_libnvinfer_plugins(None, "")
81
+ logger = trt.Logger(trt.Logger.WARNING)
82
+ runtime = trt.Runtime(logger)
83
+ with open(trt_file_path, 'rb') as f:
84
+ serialized_engine = f.read()
85
+ engine = runtime.deserialize_cuda_engine(serialized_engine)
86
+ self.flow.decoder.estimator_context = engine.create_execution_context()
87
+ self.flow.decoder.estimator_engine = engine
88
 
89
  def llm_job(self, text, prompt_text, llm_prompt_speech_token, llm_embedding, uuid):
90
  with self.llm_context:
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_matching.py CHANGED
@@ -30,6 +30,9 @@ class ConditionalCFM(BASECFM):
30
  # Just change the architecture of the estimator here
31
  self.estimator = estimator
32
 
 
 
 
33
  @torch.inference_mode()
34
  def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None):
35
  """Forward diffusion
@@ -50,7 +53,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 +74,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,13 +100,30 @@ class ConditionalCFM(BASECFM):
96
 
97
  return sol[-1]
98
 
99
- # TODO
100
- def forward_estimator(self):
101
- if isinstance(self.estimator, trt):
102
  assert self.training is False, 'tensorrt cannot be used in training'
103
- return xxx
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  else:
105
- return self.estimator.forward
106
 
107
  def compute_loss(self, x1, mask, mu, spks=None, cond=None):
108
  """Computes diffusion loss
 
30
  # Just change the architecture of the estimator here
31
  self.estimator = estimator
32
 
33
+ self.estimator_context = None
34
+ self.estimator_engine = None
35
+
36
  @torch.inference_mode()
37
  def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None):
38
  """Forward diffusion
 
53
  shape: (batch_size, n_feats, mel_timesteps)
54
  """
55
  z = torch.randn_like(mu) * temperature
56
+ t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
57
  if self.t_scheduler == 'cosine':
58
  t_span = 1 - torch.cos(t_span * 0.5 * torch.pi)
59
  return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond)
 
74
  cond: Not used but kept for future purposes
75
  """
76
  t, _, dt = t_span[0], t_span[-1], t_span[1] - t_span[0]
77
+ t = t.unsqueeze(dim=0)
78
 
79
  # I am storing this because I can later plot it by putting a debugger here and saving it to a file
80
  # Or in future might add like a return_all_steps flag
 
100
 
101
  return sol[-1]
102
 
103
+ def forward_estimator(self, x, mask, mu, t, spks, cond):
104
+ if self.estimator_context is not None:
 
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
+
119
+ for i in range(len(bindings)):
120
+ self.estimator_context.set_tensor_address(self.estimator_engine.get_tensor_name(i), bindings[i])
121
+
122
+ handle = torch.cuda.current_stream().cuda_stream
123
+ self.estimator_context.execute_async_v3(stream_handle=handle)
124
+ return ret
125
  else:
126
+ return self.estimator.forward(x, mask, mu, t, spks, cond)
127
 
128
  def compute_loss(self, x1, mask, mu, spks=None, cond=None):
129
  """Computes diffusion loss