cosyvoice.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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, CosyVoice3Model
  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, trt_concurrent=1):
  27. self.model_dir = model_dir
  28. self.fp16 = fp16
  29. if not os.path.exists(model_dir):
  30. model_dir = snapshot_download(model_dir)
  31. hyper_yaml_path = '{}/cosyvoice.yaml'.format(model_dir)
  32. if not os.path.exists(hyper_yaml_path):
  33. raise ValueError('{} not found!'.format(hyper_yaml_path))
  34. with open(hyper_yaml_path, 'r') as f:
  35. configs = load_hyperpyyaml(f)
  36. assert get_model_type(configs) == CosyVoiceModel, 'do not use {} for CosyVoice initialization!'.format(model_dir)
  37. self.frontend = CosyVoiceFrontEnd(configs['get_tokenizer'],
  38. configs['feat_extractor'],
  39. '{}/campplus.onnx'.format(model_dir),
  40. '{}/speech_tokenizer_v1.onnx'.format(model_dir),
  41. '{}/spk2info.pt'.format(model_dir),
  42. configs['allowed_special'])
  43. self.sample_rate = configs['sample_rate']
  44. if torch.cuda.is_available() is False and (load_jit is True or load_trt is True or fp16 is True):
  45. load_jit, load_trt, fp16 = False, False, False
  46. logging.warning('no cuda device, set load_jit/load_trt/fp16 to False')
  47. self.model = CosyVoiceModel(configs['llm'], configs['flow'], configs['hift'], fp16)
  48. self.model.load('{}/llm.pt'.format(model_dir),
  49. '{}/flow.pt'.format(model_dir),
  50. '{}/hift.pt'.format(model_dir))
  51. if load_jit:
  52. self.model.load_jit('{}/llm.text_encoder.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
  53. '{}/llm.llm.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
  54. '{}/flow.encoder.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'))
  55. if load_trt:
  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. trt_concurrent,
  59. self.fp16)
  60. del configs
  61. def list_available_spks(self):
  62. spks = list(self.frontend.spk2info.keys())
  63. return spks
  64. def add_zero_shot_spk(self, prompt_text, prompt_wav, zero_shot_spk_id):
  65. assert zero_shot_spk_id != '', 'do not use empty zero_shot_spk_id'
  66. model_input = self.frontend.frontend_zero_shot('', prompt_text, prompt_wav, self.sample_rate, '')
  67. del model_input['text']
  68. del model_input['text_len']
  69. self.frontend.spk2info[zero_shot_spk_id] = model_input
  70. return True
  71. def save_spkinfo(self):
  72. torch.save(self.frontend.spk2info, '{}/spk2info.pt'.format(self.model_dir))
  73. def inference_sft(self, tts_text, spk_id, stream=False, speed=1.0, text_frontend=True):
  74. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  75. model_input = self.frontend.frontend_sft(i, spk_id)
  76. start_time = time.time()
  77. logging.info('synthesis text {}'.format(i))
  78. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  79. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  80. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  81. yield model_output
  82. start_time = time.time()
  83. def inference_zero_shot(self, tts_text, prompt_text, prompt_wav, zero_shot_spk_id='', stream=False, speed=1.0, text_frontend=True):
  84. if self.__class__.__name__ == 'CosyVoice3' and '<|endofprompt|>' not in prompt_text + tts_text:
  85. logging.warning('<|endofprompt|> not found in CosyVoice3 inference, check your input text')
  86. prompt_text = self.frontend.text_normalize(prompt_text, split=False, text_frontend=text_frontend)
  87. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  88. if (not isinstance(i, Generator)) and len(i) < 0.5 * len(prompt_text):
  89. logging.warning('synthesis text {} too short than prompt text {}, this may lead to bad performance'.format(i, prompt_text))
  90. model_input = self.frontend.frontend_zero_shot(i, prompt_text, prompt_wav, self.sample_rate, zero_shot_spk_id)
  91. start_time = time.time()
  92. logging.info('synthesis text {}'.format(i))
  93. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  94. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  95. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  96. yield model_output
  97. start_time = time.time()
  98. def inference_cross_lingual(self, tts_text, prompt_wav, zero_shot_spk_id='', stream=False, speed=1.0, text_frontend=True):
  99. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  100. model_input = self.frontend.frontend_cross_lingual(i, prompt_wav, self.sample_rate, zero_shot_spk_id)
  101. start_time = time.time()
  102. logging.info('synthesis text {}'.format(i))
  103. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  104. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  105. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  106. yield model_output
  107. start_time = time.time()
  108. def inference_instruct(self, tts_text, spk_id, instruct_text, stream=False, speed=1.0, text_frontend=True):
  109. assert self.__class__.__name__ == 'CosyVoice', 'inference_instruct is only implemented for CosyVoice!'
  110. instruct_text = self.frontend.text_normalize(instruct_text, split=False, text_frontend=text_frontend)
  111. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  112. model_input = self.frontend.frontend_instruct(i, spk_id, instruct_text)
  113. start_time = time.time()
  114. logging.info('synthesis text {}'.format(i))
  115. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  116. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  117. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  118. yield model_output
  119. start_time = time.time()
  120. def inference_vc(self, source_wav, prompt_wav, stream=False, speed=1.0):
  121. model_input = self.frontend.frontend_vc(source_wav, prompt_wav, self.sample_rate)
  122. start_time = time.time()
  123. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  124. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  125. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  126. yield model_output
  127. start_time = time.time()
  128. class CosyVoice2(CosyVoice):
  129. def __init__(self, model_dir, load_jit=False, load_trt=False, load_vllm=False, fp16=False, trt_concurrent=1):
  130. self.model_dir = model_dir
  131. self.fp16 = fp16
  132. if not os.path.exists(model_dir):
  133. model_dir = snapshot_download(model_dir)
  134. hyper_yaml_path = '{}/cosyvoice2.yaml'.format(model_dir)
  135. if not os.path.exists(hyper_yaml_path):
  136. raise ValueError('{} not found!'.format(hyper_yaml_path))
  137. with open(hyper_yaml_path, 'r') as f:
  138. configs = load_hyperpyyaml(f, overrides={'qwen_pretrain_path': os.path.join(model_dir, 'CosyVoice-BlankEN')})
  139. assert get_model_type(configs) == CosyVoice2Model, 'do not use {} for CosyVoice2 initialization!'.format(model_dir)
  140. self.frontend = CosyVoiceFrontEnd(configs['get_tokenizer'],
  141. configs['feat_extractor'],
  142. '{}/campplus.onnx'.format(model_dir),
  143. '{}/speech_tokenizer_v2.onnx'.format(model_dir),
  144. '{}/spk2info.pt'.format(model_dir),
  145. configs['allowed_special'])
  146. self.sample_rate = configs['sample_rate']
  147. if torch.cuda.is_available() is False and (load_jit is True or load_trt is True or load_vllm is True or fp16 is True):
  148. load_jit, load_trt, load_vllm, fp16 = False, False, False, False
  149. logging.warning('no cuda device, set load_jit/load_trt/load_vllm/fp16 to False')
  150. self.model = CosyVoice2Model(configs['llm'], configs['flow'], configs['hift'], fp16)
  151. self.model.load('{}/llm.pt'.format(model_dir),
  152. '{}/flow.pt'.format(model_dir),
  153. '{}/hift.pt'.format(model_dir))
  154. if load_vllm:
  155. self.model.load_vllm('{}/vllm'.format(model_dir))
  156. if load_jit:
  157. self.model.load_jit('{}/flow.encoder.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'))
  158. if load_trt:
  159. self.model.load_trt('{}/flow.decoder.estimator.{}.mygpu.plan'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
  160. '{}/flow.decoder.estimator.fp32.onnx'.format(model_dir),
  161. trt_concurrent,
  162. self.fp16)
  163. del configs
  164. def inference_instruct2(self, tts_text, instruct_text, prompt_wav, zero_shot_spk_id='', stream=False, speed=1.0, text_frontend=True):
  165. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  166. model_input = self.frontend.frontend_instruct2(i, instruct_text, prompt_wav, self.sample_rate, zero_shot_spk_id)
  167. start_time = time.time()
  168. logging.info('synthesis text {}'.format(i))
  169. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  170. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  171. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  172. yield model_output
  173. start_time = time.time()
  174. class CosyVoice3(CosyVoice2):
  175. def __init__(self, model_dir, load_trt=False, load_vllm=False, fp16=False, trt_concurrent=1):
  176. self.model_dir = model_dir
  177. self.fp16 = fp16
  178. if not os.path.exists(model_dir):
  179. model_dir = snapshot_download(model_dir)
  180. hyper_yaml_path = '{}/cosyvoice3.yaml'.format(model_dir)
  181. if not os.path.exists(hyper_yaml_path):
  182. raise ValueError('{} not found!'.format(hyper_yaml_path))
  183. with open(hyper_yaml_path, 'r') as f:
  184. configs = load_hyperpyyaml(f, overrides={'qwen_pretrain_path': os.path.join(model_dir, 'CosyVoice-BlankEN')})
  185. assert get_model_type(configs) == CosyVoice3Model, 'do not use {} for CosyVoice3 initialization!'.format(model_dir)
  186. self.frontend = CosyVoiceFrontEnd(configs['get_tokenizer'],
  187. configs['feat_extractor'],
  188. '{}/campplus.onnx'.format(model_dir),
  189. '{}/speech_tokenizer_v3.onnx'.format(model_dir),
  190. '{}/spk2info.pt'.format(model_dir),
  191. configs['allowed_special'])
  192. self.sample_rate = configs['sample_rate']
  193. if torch.cuda.is_available() is False and (load_trt is True or fp16 is True):
  194. load_trt, fp16 = False, False
  195. logging.warning('no cuda device, set load_trt/fp16 to False')
  196. self.model = CosyVoice3Model(configs['llm'], configs['flow'], configs['hift'], fp16)
  197. self.model.load('{}/llm.pt'.format(model_dir),
  198. '{}/flow.pt'.format(model_dir),
  199. '{}/hift.pt'.format(model_dir))
  200. if load_vllm:
  201. self.model.load_vllm('{}/vllm'.format(model_dir))
  202. if load_trt:
  203. if self.fp16 is True:
  204. logging.warning('DiT tensorRT fp16 engine have some performance issue, use at caution!')
  205. self.model.load_trt('{}/flow.decoder.estimator.{}.mygpu.plan'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
  206. '{}/flow.decoder.estimator.fp32.onnx'.format(model_dir),
  207. trt_concurrent,
  208. self.fp16)
  209. del configs
  210. def AutoModel(**kwargs):
  211. if not os.path.exists(kwargs['model_dir']):
  212. kwargs['model_dir'] = snapshot_download(kwargs['model_dir'])
  213. if os.path.exists('{}/cosyvoice.yaml'.format(kwargs['model_dir'])):
  214. return CosyVoice(**kwargs)
  215. elif os.path.exists('{}/cosyvoice2.yaml'.format(kwargs['model_dir'])):
  216. return CosyVoice2(**kwargs)
  217. elif os.path.exists('{}/cosyvoice3.yaml'.format(kwargs['model_dir'])):
  218. return CosyVoice3(**kwargs)
  219. else:
  220. raise TypeError('No valid model type found!')