cosyvoice.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu)
  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 os
  15. import time
  16. from typing import Generator
  17. from tqdm import tqdm
  18. from hyperpyyaml import load_hyperpyyaml
  19. from modelscope import snapshot_download
  20. import torch
  21. from cosyvoice.cli.frontend import CosyVoiceFrontEnd
  22. from cosyvoice.cli.model import CosyVoiceModel, CosyVoice2Model, VllmCosyVoice2Model
  23. from cosyvoice.utils.file_utils import logging
  24. from cosyvoice.utils.class_utils import get_model_type
  25. class CosyVoice:
  26. def __init__(self, model_dir, load_jit=False, load_trt=False, fp16=False):
  27. self.instruct = True if '-Instruct' in model_dir else False
  28. self.model_dir = model_dir
  29. self.fp16 = fp16
  30. if not os.path.exists(model_dir):
  31. model_dir = snapshot_download(model_dir)
  32. with open('{}/cosyvoice.yaml'.format(model_dir), 'r') as f:
  33. configs = load_hyperpyyaml(f)
  34. assert get_model_type(configs) != CosyVoice2Model, 'do not use {} for CosyVoice initialization!'.format(model_dir)
  35. self.frontend = CosyVoiceFrontEnd(configs['get_tokenizer'],
  36. configs['feat_extractor'],
  37. '{}/campplus.onnx'.format(model_dir),
  38. '{}/speech_tokenizer_v1.onnx'.format(model_dir),
  39. '{}/spk2info.pt'.format(model_dir),
  40. configs['allowed_special'])
  41. self.sample_rate = configs['sample_rate']
  42. if torch.cuda.is_available() is False and (load_jit is True or load_trt is True or fp16 is True):
  43. load_jit, load_trt, fp16 = False, False, False
  44. logging.warning('no cuda device, set load_jit/load_trt/fp16 to False')
  45. self.model = CosyVoiceModel(configs['llm'], configs['flow'], configs['hift'], fp16)
  46. self.model.load('{}/llm.pt'.format(model_dir),
  47. '{}/flow.pt'.format(model_dir),
  48. '{}/hift.pt'.format(model_dir))
  49. if load_jit:
  50. self.model.load_jit('{}/llm.text_encoder.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
  51. '{}/llm.llm.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
  52. '{}/flow.encoder.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'))
  53. if load_trt:
  54. self.model.load_trt('{}/flow.decoder.estimator.{}.mygpu.plan'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
  55. '{}/flow.decoder.estimator.fp32.onnx'.format(model_dir),
  56. self.fp16)
  57. del configs
  58. def list_available_spks(self):
  59. spks = list(self.frontend.spk2info.keys())
  60. return spks
  61. def add_spk_info(self, spk_id, spk_info):
  62. self.frontend.add_spk_info(spk_id, spk_info)
  63. def inference_sft(self, tts_text, spk_id, stream=False, speed=1.0, text_frontend=True):
  64. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  65. model_input = self.frontend.frontend_sft(i, spk_id)
  66. start_time = time.time()
  67. logging.info('synthesis text {}'.format(i))
  68. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  69. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  70. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  71. yield model_output
  72. start_time = time.time()
  73. def inference_zero_shot(self, tts_text, prompt_text, prompt_speech_16k, stream=False, speed=1.0, text_frontend=True):
  74. prompt_text = self.frontend.text_normalize(prompt_text, split=False, text_frontend=text_frontend)
  75. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  76. if (not isinstance(i, Generator)) and len(i) < 0.5 * len(prompt_text):
  77. logging.warning('synthesis text {} too short than prompt text {}, this may lead to bad performance'.format(i, prompt_text))
  78. model_input = self.frontend.frontend_zero_shot(i, prompt_text, prompt_speech_16k, self.sample_rate)
  79. start_time = time.time()
  80. logging.info('synthesis text {}'.format(i))
  81. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  82. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  83. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  84. yield model_output
  85. start_time = time.time()
  86. def inference_zero_shot_by_spk_id(self, tts_text, spk_id, stream=False, speed=1.0, text_frontend=True):
  87. """使用预定义的说话人执行 zero_shot 推理"""
  88. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  89. model_input = self.frontend.frontend_zero_shot_by_spk_id(i, spk_id)
  90. start_time = time.time()
  91. last_time = start_time
  92. chunk_index = 0
  93. logging.info('synthesis text {}'.format(i))
  94. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  95. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  96. logging.info('yield speech index:{}, len {:.2f}, rtf {:.3f}, cost {:.3f}s, all cost time {:.3f}s'.format(
  97. chunk_index, speech_len, (time.time()-last_time)/speech_len, time.time()-last_time, time.time()-start_time))
  98. yield model_output
  99. last_time = time.time()
  100. chunk_index += 1
  101. def inference_cross_lingual(self, tts_text, prompt_speech_16k, stream=False, speed=1.0, text_frontend=True):
  102. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  103. model_input = self.frontend.frontend_cross_lingual(i, prompt_speech_16k, self.sample_rate)
  104. start_time = time.time()
  105. logging.info('synthesis text {}'.format(i))
  106. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  107. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  108. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  109. yield model_output
  110. start_time = time.time()
  111. def inference_instruct(self, tts_text, spk_id, instruct_text, stream=False, speed=1.0, text_frontend=True):
  112. assert isinstance(self.model, CosyVoiceModel), 'inference_instruct is only implemented for CosyVoice!'
  113. if self.instruct is False:
  114. raise ValueError('{} do not support instruct inference'.format(self.model_dir))
  115. instruct_text = self.frontend.text_normalize(instruct_text, split=False, text_frontend=text_frontend)
  116. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  117. model_input = self.frontend.frontend_instruct(i, spk_id, instruct_text)
  118. start_time = time.time()
  119. logging.info('synthesis text {}'.format(i))
  120. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  121. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  122. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  123. yield model_output
  124. start_time = time.time()
  125. def inference_vc(self, source_speech_16k, prompt_speech_16k, stream=False, speed=1.0):
  126. model_input = self.frontend.frontend_vc(source_speech_16k, prompt_speech_16k, self.sample_rate)
  127. start_time = time.time()
  128. for model_output in self.model.vc(**model_input, stream=stream, speed=speed):
  129. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  130. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  131. yield model_output
  132. start_time = time.time()
  133. class CosyVoice2(CosyVoice):
  134. def __init__(self, model_dir, load_jit=False, load_trt=False, fp16=False, use_vllm=False):
  135. self.instruct = True if '-Instruct' in model_dir else False
  136. self.model_dir = model_dir
  137. self.fp16 = fp16
  138. if not os.path.exists(model_dir):
  139. model_dir = snapshot_download(model_dir)
  140. with open('{}/cosyvoice.yaml'.format(model_dir), 'r') as f:
  141. configs = load_hyperpyyaml(f, overrides={'qwen_pretrain_path': os.path.join(model_dir, 'CosyVoice-BlankEN')})
  142. assert get_model_type(configs) == CosyVoice2Model, 'do not use {} for CosyVoice2 initialization!'.format(model_dir)
  143. self.frontend = CosyVoiceFrontEnd(configs['get_tokenizer'],
  144. configs['feat_extractor'],
  145. '{}/campplus.onnx'.format(model_dir),
  146. '{}/speech_tokenizer_v2.onnx'.format(model_dir),
  147. '{}/spk2info.pt'.format(model_dir),
  148. configs['allowed_special'])
  149. self.sample_rate = configs['sample_rate']
  150. if torch.cuda.is_available() is False and (load_jit is True or load_trt is True or fp16 is True):
  151. load_jit, load_trt, fp16 = False, False, False
  152. logging.warning('no cuda device, set load_jit/load_trt/fp16 to False')
  153. if use_vllm:
  154. try:
  155. os.environ["VLLM_USE_V1"] = '1'
  156. from vllm import AsyncLLMEngine
  157. from vllm.engine.arg_utils import AsyncEngineArgs
  158. # EngineArgs
  159. ENGINE_ARGS = {
  160. "block_size": 16,
  161. "swap_space": 0,
  162. # "enforce_eager": True,
  163. "gpu_memory_utilization": 0.4,
  164. "max_num_batched_tokens": 1024,
  165. "max_model_len": 1024,
  166. "max_num_seqs": 256,
  167. "disable_log_requests": True,
  168. "disable_log_stats": True,
  169. "dtype": "bfloat16"
  170. }
  171. self.model = VllmCosyVoice2Model(model_dir, configs['flow'], configs['hift'], fp16)
  172. engine_args = AsyncEngineArgs(
  173. model=model_dir,
  174. **ENGINE_ARGS,
  175. )
  176. self.llm_engine: AsyncLLMEngine = AsyncLLMEngine.from_engine_args(engine_args)
  177. self.model.llm_engine = self.llm_engine
  178. except Exception as e:
  179. logging.warning(f'use vllm inference failed. \n{e}')
  180. raise e
  181. else:
  182. self.model = CosyVoice2Model(configs['llm'], configs['flow'], configs['hift'], fp16)
  183. self.model.load('{}/llm.pt'.format(model_dir),
  184. '{}/flow.pt'.format(model_dir),
  185. '{}/hift.pt'.format(model_dir))
  186. if load_jit:
  187. self.model.load_jit('{}/flow.encoder.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'))
  188. if load_trt:
  189. self.model.load_trt('{}/flow.decoder.estimator.{}.mygpu.plan'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
  190. '{}/flow.decoder.estimator.fp32.onnx'.format(model_dir),
  191. self.fp16)
  192. del configs
  193. def inference_instruct(self, *args, **kwargs):
  194. raise NotImplementedError('inference_instruct is not implemented for CosyVoice2!')
  195. def inference_instruct2(self, tts_text, instruct_text, prompt_speech_16k, stream=False, speed=1.0, text_frontend=True):
  196. assert isinstance(self.model, CosyVoice2Model), 'inference_instruct2 is only implemented for CosyVoice2!'
  197. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  198. model_input = self.frontend.frontend_instruct2(i, instruct_text, prompt_speech_16k, self.sample_rate)
  199. start_time = time.time()
  200. logging.info('synthesis text {}'.format(i))
  201. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  202. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  203. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  204. yield model_output
  205. start_time = time.time()
  206. def inference_instruct2_by_spk_id(self, tts_text, instruct_text, spk_id, stream=False, speed=1.0, text_frontend=True):
  207. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  208. model_input = self.frontend.frontend_instruct2_by_spk_id(i, instruct_text, spk_id)
  209. start_time = time.time()
  210. logging.info('synthesis text {}'.format(i))
  211. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  212. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  213. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  214. yield model_output
  215. start_time = time.time()