Skip to content

Commit 8a1bce6

Browse files
authored
Merge pull request #865 from FunAudioLLM/dev/lyuxiang.lx
Dev/lyuxiang.lx
2 parents d2e43fe + b1e9663 commit 8a1bce6

File tree

11 files changed

+97
-22
lines changed

11 files changed

+97
-22
lines changed

cosyvoice/cli/cosyvoice.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,9 @@ def __init__(self, model_dir, load_jit=False, load_trt=False, fp16=False):
5353
'{}/llm.llm.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
5454
'{}/flow.encoder.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'))
5555
if load_trt:
56-
self.model.load_trt('{}/flow.decoder.estimator.{}.v100.plan'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'))
56+
self.model.load_trt('{}/flow.decoder.estimator.{}.mygpu.plan'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
57+
'{}/flow.decoder.estimator.fp32.onnx'.format(model_dir),
58+
self.fp16)
5759
del configs
5860

5961
def list_available_spks(self):
@@ -149,7 +151,9 @@ def __init__(self, model_dir, load_jit=False, load_trt=False, fp16=False):
149151
if load_jit:
150152
self.model.load_jit('{}/flow.encoder.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'))
151153
if load_trt:
152-
self.model.load_trt('{}/flow.decoder.estimator.{}.v100.plan'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'))
154+
self.model.load_trt('{}/flow.decoder.estimator.{}.mygpu.plan'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
155+
'{}/flow.decoder.estimator.fp32.onnx'.format(model_dir),
156+
self.fp16)
153157
del configs
154158

155159
def inference_instruct(self, *args, **kwargs):

cosyvoice/cli/model.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
import os
1415
import torch
1516
import numpy as np
1617
import threading
@@ -19,6 +20,7 @@
1920
from contextlib import nullcontext
2021
import uuid
2122
from cosyvoice.utils.common import fade_in_out
23+
from cosyvoice.utils.file_utils import convert_onnx_to_trt
2224

2325

2426
class CosyVoiceModel:
@@ -35,6 +37,9 @@ def __init__(self,
3537
self.fp16 = fp16
3638
self.llm.fp16 = fp16
3739
self.flow.fp16 = fp16
40+
if self.fp16 is True:
41+
self.llm.half()
42+
self.flow.half()
3843
self.token_min_hop_len = 2 * self.flow.input_frame_rate
3944
self.token_max_hop_len = 4 * self.flow.input_frame_rate
4045
self.token_overlap_len = 20
@@ -69,9 +74,6 @@ def load(self, llm_model, flow_model, hift_model):
6974
hift_state_dict = {k.replace('generator.', ''): v for k, v in torch.load(hift_model, map_location=self.device).items()}
7075
self.hift.load_state_dict(hift_state_dict, strict=True)
7176
self.hift.to(self.device).eval()
72-
if self.fp16 is True:
73-
self.llm.half()
74-
self.flow.half()
7577

7678
def load_jit(self, llm_text_encoder_model, llm_llm_model, flow_encoder_model):
7779
llm_text_encoder = torch.jit.load(llm_text_encoder_model, map_location=self.device)
@@ -81,7 +83,10 @@ def load_jit(self, llm_text_encoder_model, llm_llm_model, flow_encoder_model):
8183
flow_encoder = torch.jit.load(flow_encoder_model, map_location=self.device)
8284
self.flow.encoder = flow_encoder
8385

84-
def load_trt(self, flow_decoder_estimator_model):
86+
def load_trt(self, flow_decoder_estimator_model, flow_decoder_onnx_model, fp16):
87+
assert torch.cuda.is_available(), 'tensorrt only supports gpu!'
88+
if not os.path.exists(flow_decoder_estimator_model):
89+
convert_onnx_to_trt(flow_decoder_estimator_model, flow_decoder_onnx_model, fp16)
8590
del self.flow.decoder.estimator
8691
import tensorrt as trt
8792
with open(flow_decoder_estimator_model, 'rb') as f:
@@ -204,6 +209,7 @@ def tts(self, text, flow_embedding, llm_embedding=torch.zeros(0, 192),
204209
self.mel_overlap_dict.pop(this_uuid)
205210
self.hift_cache_dict.pop(this_uuid)
206211
self.flow_cache_dict.pop(this_uuid)
212+
torch.cuda.empty_cache()
207213

208214
def vc(self, source_speech_token, flow_prompt_speech_token, prompt_speech_feat, flow_embedding, stream=False, speed=1.0, **kwargs):
209215
# this_uuid is used to track variables related to this inference thread
@@ -257,6 +263,7 @@ def vc(self, source_speech_token, flow_prompt_speech_token, prompt_speech_feat,
257263
self.llm_end_dict.pop(this_uuid)
258264
self.mel_overlap_dict.pop(this_uuid)
259265
self.hift_cache_dict.pop(this_uuid)
266+
torch.cuda.empty_cache()
260267

261268

262269
class CosyVoice2Model(CosyVoiceModel):
@@ -273,6 +280,9 @@ def __init__(self,
273280
self.fp16 = fp16
274281
self.llm.fp16 = fp16
275282
self.flow.fp16 = fp16
283+
if self.fp16 is True:
284+
self.llm.half()
285+
self.flow.half()
276286
self.token_hop_len = 2 * self.flow.input_frame_rate
277287
# here we fix flow encoder/decoder decoding_chunk_size, in the future we will send it as arguments, or use cache
278288
self.flow.encoder.static_chunk_size = 2 * self.flow.input_frame_rate
@@ -385,3 +395,4 @@ def tts(self, text, flow_embedding, llm_embedding=torch.zeros(0, 192),
385395
with self.lock:
386396
self.tts_speech_token_dict.pop(this_uuid)
387397
self.llm_end_dict.pop(this_uuid)
398+
torch.cuda.empty_cache()

cosyvoice/dataset/processor.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
from torch.nn.utils.rnn import pad_sequence
2222
import torch.nn.functional as F
2323

24-
torchaudio.set_audio_backend('soundfile')
2524

2625
AUDIO_FORMAT_SETS = {'flac', 'mp3', 'm4a', 'ogg', 'opus', 'wav', 'wma'}
2726

cosyvoice/flow/flow_matching.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -134,12 +134,12 @@ def forward_estimator(self, x, mask, mu, t, spks, cond):
134134
self.estimator.set_input_shape('cond', (2, 80, x.size(2)))
135135
# run trt engine
136136
self.estimator.execute_v2([x.contiguous().data_ptr(),
137-
mask.contiguous().data_ptr(),
138-
mu.contiguous().data_ptr(),
139-
t.contiguous().data_ptr(),
140-
spks.contiguous().data_ptr(),
141-
cond.contiguous().data_ptr(),
142-
x.data_ptr()])
137+
mask.contiguous().data_ptr(),
138+
mu.contiguous().data_ptr(),
139+
t.contiguous().data_ptr(),
140+
spks.contiguous().data_ptr(),
141+
cond.contiguous().data_ptr(),
142+
x.data_ptr()])
143143
return x
144144

145145
def compute_loss(self, x1, mask, mu, spks=None, cond=None):

cosyvoice/hifigan/discriminator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import torch
22
import torch.nn as nn
3-
from torch.nn.utils import weight_norm
3+
from torch.nn.utils.parametrizations import weight_norm
44
from typing import List, Optional, Tuple
55
from einops import rearrange
66
from torchaudio.transforms import Spectrogram

cosyvoice/hifigan/f0_predictor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# limitations under the License.
1414
import torch
1515
import torch.nn as nn
16-
from torch.nn.utils import weight_norm
16+
from torch.nn.utils.parametrizations import weight_norm
1717

1818

1919
class ConvRNNF0Predictor(nn.Module):

cosyvoice/hifigan/generator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from torch.nn import Conv1d
2424
from torch.nn import ConvTranspose1d
2525
from torch.nn.utils import remove_weight_norm
26-
from torch.nn.utils import weight_norm
26+
from torch.nn.utils.parametrizations import weight_norm
2727
from torch.distributions.uniform import Uniform
2828

2929
from cosyvoice.transformer.activation import Snake

cosyvoice/utils/file_utils.py

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# Copyright (c) 2021 Mobvoi Inc. (authors: Binbin Zhang)
2-
# 2024 Alibaba Inc (authors: Xiang Lyu)
2+
# 2024 Alibaba Inc (authors: Xiang Lyu, Zetao Hu)
33
#
44
# Licensed under the Apache License, Version 2.0 (the "License");
55
# you may not use this file except in compliance with the License.
@@ -14,6 +14,7 @@
1414
# limitations under the License.
1515

1616
import json
17+
import tensorrt as trt
1718
import torchaudio
1819
import logging
1920
logging.getLogger('matplotlib').setLevel(logging.WARNING)
@@ -45,3 +46,44 @@ def load_wav(wav, target_sr):
4546
assert sample_rate > target_sr, 'wav sample rate {} must be greater than {}'.format(sample_rate, target_sr)
4647
speech = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=target_sr)(speech)
4748
return speech
49+
50+
51+
def convert_onnx_to_trt(trt_model, onnx_model, fp16):
52+
_min_shape = [(2, 80, 4), (2, 1, 4), (2, 80, 4), (2,), (2, 80), (2, 80, 4)]
53+
_opt_shape = [(2, 80, 193), (2, 1, 193), (2, 80, 193), (2,), (2, 80), (2, 80, 193)]
54+
_max_shape = [(2, 80, 6800), (2, 1, 6800), (2, 80, 6800), (2,), (2, 80), (2, 80, 6800)]
55+
input_names = ["x", "mask", "mu", "t", "spks", "cond"]
56+
57+
logging.info("Converting onnx to trt...")
58+
network_flags = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
59+
logger = trt.Logger(trt.Logger.INFO)
60+
builder = trt.Builder(logger)
61+
network = builder.create_network(network_flags)
62+
parser = trt.OnnxParser(network, logger)
63+
config = builder.create_builder_config()
64+
config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 1 << 33) # 8GB
65+
if fp16:
66+
config.set_flag(trt.BuilderFlag.FP16)
67+
profile = builder.create_optimization_profile()
68+
# load onnx model
69+
with open(onnx_model, "rb") as f:
70+
if not parser.parse(f.read()):
71+
for error in range(parser.num_errors):
72+
print(parser.get_error(error))
73+
raise ValueError('failed to parse {}'.format(onnx_model))
74+
# set input shapes
75+
for i in range(len(input_names)):
76+
profile.set_shape(input_names[i], _min_shape[i], _opt_shape[i], _max_shape[i])
77+
tensor_dtype = trt.DataType.HALF if fp16 else trt.DataType.FLOAT
78+
# set input and output data type
79+
for i in range(network.num_inputs):
80+
input_tensor = network.get_input(i)
81+
input_tensor.dtype = tensor_dtype
82+
for i in range(network.num_outputs):
83+
output_tensor = network.get_output(i)
84+
output_tensor.dtype = tensor_dtype
85+
config.add_optimization_profile(profile)
86+
engine_bytes = builder.build_serialized_network(network, config)
87+
# save trt engine
88+
with open(trt_model, "wb") as f:
89+
f.write(engine_bytes)

runtime/python/fastapi/server.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
2525
sys.path.append('{}/../../..'.format(ROOT_DIR))
2626
sys.path.append('{}/../../../third_party/Matcha-TTS'.format(ROOT_DIR))
27-
from cosyvoice.cli.cosyvoice import CosyVoice
27+
from cosyvoice.cli.cosyvoice import CosyVoice, CosyVoice2
2828
from cosyvoice.utils.file_utils import load_wav
2929

3030
app = FastAPI()
@@ -79,5 +79,11 @@ async def inference_instruct(tts_text: str = Form(), spk_id: str = Form(), instr
7979
default='iic/CosyVoice-300M',
8080
help='local path or modelscope repo id')
8181
args = parser.parse_args()
82-
cosyvoice = CosyVoice(args.model_dir)
82+
try:
83+
cosyvoice = CosyVoice(args.model_dir)
84+
except Exception:
85+
try:
86+
cosyvoice = CosyVoice2(args.model_dir)
87+
except Exception:
88+
raise TypeError('no valid model_type!')
8389
uvicorn.run(app, host="0.0.0.0", port=args.port)

runtime/python/grpc/server.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,21 @@
2525
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
2626
sys.path.append('{}/../../..'.format(ROOT_DIR))
2727
sys.path.append('{}/../../../third_party/Matcha-TTS'.format(ROOT_DIR))
28-
from cosyvoice.cli.cosyvoice import CosyVoice
28+
from cosyvoice.cli.cosyvoice import CosyVoice, CosyVoice2
2929

3030
logging.basicConfig(level=logging.DEBUG,
3131
format='%(asctime)s %(levelname)s %(message)s')
3232

3333

3434
class CosyVoiceServiceImpl(cosyvoice_pb2_grpc.CosyVoiceServicer):
3535
def __init__(self, args):
36-
self.cosyvoice = CosyVoice(args.model_dir)
36+
try:
37+
self.cosyvoice = CosyVoice(args.model_dir)
38+
except Exception:
39+
try:
40+
self.cosyvoice = CosyVoice2(args.model_dir)
41+
except Exception:
42+
raise TypeError('no valid model_type!')
3743
logging.info('grpc service initialized')
3844

3945
def Inference(self, request, context):

0 commit comments

Comments
 (0)