model.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 torch
  15. import numpy as np
  16. import threading
  17. import time
  18. from torch.nn import functional as F
  19. from contextlib import nullcontext
  20. import uuid
  21. from cosyvoice.utils.common import fade_in_out
  22. class CosyVoiceModel:
  23. def __init__(self,
  24. llm: torch.nn.Module,
  25. flow: torch.nn.Module,
  26. hift: torch.nn.Module):
  27. self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  28. self.llm = llm
  29. self.flow = flow
  30. self.hift = hift
  31. self.token_min_hop_len = 2 * self.flow.input_frame_rate
  32. self.token_max_hop_len = 4 * self.flow.input_frame_rate
  33. self.token_overlap_len = 20
  34. # mel fade in out
  35. self.mel_overlap_len = int(self.token_overlap_len / self.flow.input_frame_rate * 22050 / 256)
  36. self.mel_window = np.hamming(2 * self.mel_overlap_len)
  37. # hift cache
  38. self.mel_cache_len = 20
  39. self.source_cache_len = int(self.mel_cache_len * 256)
  40. # speech fade in out
  41. self.speech_window = np.hamming(2 * self.source_cache_len)
  42. # rtf and decoding related
  43. self.stream_scale_factor = 1
  44. assert self.stream_scale_factor >= 1, 'stream_scale_factor should be greater than 1, change it according to your actual rtf'
  45. self.llm_context = torch.cuda.stream(torch.cuda.Stream(self.device)) if torch.cuda.is_available() else nullcontext()
  46. self.lock = threading.Lock()
  47. # dict used to store session related variable
  48. self.tts_speech_token_dict = {}
  49. self.llm_end_dict = {}
  50. self.flow_cache_dict = {}
  51. self.mel_overlap_dict = {}
  52. self.hift_cache_dict = {}
  53. def load(self, llm_model, flow_model, hift_model):
  54. self.llm.load_state_dict(torch.load(llm_model, map_location=self.device))
  55. self.llm.to(self.device).eval()
  56. self.llm.half()
  57. self.flow.load_state_dict(torch.load(flow_model, map_location=self.device))
  58. self.flow.to(self.device).eval()
  59. self.hift.load_state_dict(torch.load(hift_model, map_location=self.device))
  60. self.hift.to(self.device).eval()
  61. def load_jit(self, llm_text_encoder_model, llm_llm_model, flow_encoder_model):
  62. llm_text_encoder = torch.jit.load(llm_text_encoder_model, map_location=self.device)
  63. self.llm.text_encoder = llm_text_encoder
  64. llm_llm = torch.jit.load(llm_llm_model, map_location=self.device)
  65. self.llm.llm = llm_llm
  66. flow_encoder = torch.jit.load(flow_encoder_model, map_location=self.device)
  67. self.flow.encoder = flow_encoder
  68. def load_onnx(self, flow_decoder_estimator_model):
  69. import onnxruntime
  70. option = onnxruntime.SessionOptions()
  71. option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
  72. option.intra_op_num_threads = 1
  73. providers = ['CUDAExecutionProvider' if torch.cuda.is_available() else 'CPUExecutionProvider']
  74. del self.flow.decoder.estimator
  75. self.flow.decoder.estimator = onnxruntime.InferenceSession(flow_decoder_estimator_model, sess_options=option, providers=providers)
  76. def llm_job(self, text, prompt_text, llm_prompt_speech_token, llm_embedding, uuid):
  77. with self.llm_context:
  78. for i in self.llm.inference(text=text.to(self.device),
  79. text_len=torch.tensor([text.shape[1]], dtype=torch.int32).to(self.device),
  80. prompt_text=prompt_text.to(self.device),
  81. prompt_text_len=torch.tensor([prompt_text.shape[1]], dtype=torch.int32).to(self.device),
  82. prompt_speech_token=llm_prompt_speech_token.to(self.device),
  83. prompt_speech_token_len=torch.tensor([llm_prompt_speech_token.shape[1]], dtype=torch.int32).to(self.device),
  84. embedding=llm_embedding.to(self.device).half()):
  85. self.tts_speech_token_dict[uuid].append(i)
  86. self.llm_end_dict[uuid] = True
  87. def token2wav(self, token, prompt_token, prompt_feat, embedding, uuid, finalize=False, speed=1.0):
  88. tts_mel, flow_cache = self.flow.inference(token=token.to(self.device),
  89. token_len=torch.tensor([token.shape[1]], dtype=torch.int32).to(self.device),
  90. prompt_token=prompt_token.to(self.device),
  91. prompt_token_len=torch.tensor([prompt_token.shape[1]], dtype=torch.int32).to(self.device),
  92. prompt_feat=prompt_feat.to(self.device),
  93. prompt_feat_len=torch.tensor([prompt_feat.shape[1]], dtype=torch.int32).to(self.device),
  94. embedding=embedding.to(self.device),
  95. required_cache_size=self.mel_overlap_len,
  96. flow_cache=self.flow_cache_dict[uuid])
  97. self.flow_cache_dict[uuid] = flow_cache
  98. # mel overlap fade in out
  99. if self.mel_overlap_dict[uuid] is not None:
  100. tts_mel = fade_in_out(tts_mel, self.mel_overlap_dict[uuid], self.mel_window)
  101. # append hift cache
  102. if self.hift_cache_dict[uuid] is not None:
  103. hift_cache_mel, hift_cache_source = self.hift_cache_dict[uuid]['mel'], self.hift_cache_dict[uuid]['source']
  104. tts_mel = torch.concat([hift_cache_mel, tts_mel], dim=2)
  105. else:
  106. hift_cache_source = torch.zeros(1, 1, 0)
  107. # keep overlap mel and hift cache
  108. if finalize is False:
  109. self.mel_overlap_dict[uuid] = tts_mel[:, :, -self.mel_overlap_len:]
  110. tts_mel = tts_mel[:, :, :-self.mel_overlap_len]
  111. tts_speech, tts_source = self.hift.inference(mel=tts_mel, cache_source=hift_cache_source)
  112. if self.hift_cache_dict[uuid] is not None:
  113. tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
  114. self.hift_cache_dict[uuid] = {'mel': tts_mel[:, :, -self.mel_cache_len:],
  115. 'source': tts_source[:, :, -self.source_cache_len:],
  116. 'speech': tts_speech[:, -self.source_cache_len:]}
  117. tts_speech = tts_speech[:, :-self.source_cache_len]
  118. else:
  119. if speed != 1.0:
  120. assert self.hift_cache_dict[uuid] is None, 'speed change only support non-stream inference mode'
  121. tts_mel = F.interpolate(tts_mel, size=int(tts_mel.shape[2] / speed), mode='linear')
  122. tts_speech, tts_source = self.hift.inference(mel=tts_mel, cache_source=hift_cache_source)
  123. if self.hift_cache_dict[uuid] is not None:
  124. tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
  125. return tts_speech
  126. def tts(self, text, flow_embedding, llm_embedding=torch.zeros(0, 192),
  127. prompt_text=torch.zeros(1, 0, dtype=torch.int32),
  128. llm_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
  129. flow_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
  130. prompt_speech_feat=torch.zeros(1, 0, 80), stream=False, speed=1.0, **kwargs):
  131. # this_uuid is used to track variables related to this inference thread
  132. this_uuid = str(uuid.uuid1())
  133. with self.lock:
  134. self.tts_speech_token_dict[this_uuid], self.llm_end_dict[this_uuid] = [], False
  135. self.flow_cache_dict[this_uuid] = None
  136. self.mel_overlap_dict[this_uuid], self.hift_cache_dict[this_uuid] = None, None
  137. p = threading.Thread(target=self.llm_job, args=(text, prompt_text, llm_prompt_speech_token, llm_embedding, this_uuid))
  138. p.start()
  139. if stream is True:
  140. token_hop_len = self.token_min_hop_len
  141. while True:
  142. time.sleep(0.1)
  143. if len(self.tts_speech_token_dict[this_uuid]) >= token_hop_len + self.token_overlap_len:
  144. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid][:token_hop_len + self.token_overlap_len]) \
  145. .unsqueeze(dim=0)
  146. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  147. prompt_token=flow_prompt_speech_token,
  148. prompt_feat=prompt_speech_feat,
  149. embedding=flow_embedding,
  150. uuid=this_uuid,
  151. finalize=False)
  152. yield {'tts_speech': this_tts_speech.cpu()}
  153. with self.lock:
  154. self.tts_speech_token_dict[this_uuid] = self.tts_speech_token_dict[this_uuid][token_hop_len:]
  155. # increase token_hop_len for better speech quality
  156. token_hop_len = min(self.token_max_hop_len, int(token_hop_len * self.stream_scale_factor))
  157. if self.llm_end_dict[this_uuid] is True and len(self.tts_speech_token_dict[this_uuid]) < token_hop_len + self.token_overlap_len:
  158. break
  159. p.join()
  160. # deal with remain tokens, make sure inference remain token len equals token_hop_len when cache_speech is not None
  161. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
  162. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  163. prompt_token=flow_prompt_speech_token,
  164. prompt_feat=prompt_speech_feat,
  165. embedding=flow_embedding,
  166. uuid=this_uuid,
  167. finalize=True)
  168. yield {'tts_speech': this_tts_speech.cpu()}
  169. else:
  170. # deal with all tokens
  171. p.join()
  172. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
  173. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  174. prompt_token=flow_prompt_speech_token,
  175. prompt_feat=prompt_speech_feat,
  176. embedding=flow_embedding,
  177. uuid=this_uuid,
  178. finalize=True,
  179. speed=speed)
  180. yield {'tts_speech': this_tts_speech.cpu()}
  181. with self.lock:
  182. self.tts_speech_token_dict.pop(this_uuid)
  183. self.llm_end_dict.pop(this_uuid)
  184. self.mel_overlap_dict.pop(this_uuid)
  185. self.hift_cache_dict.pop(this_uuid)
  186. def vc(self, source_speech_token, flow_prompt_speech_token, prompt_speech_feat, flow_embedding, stream=False, speed=1.0, **kwargs):
  187. # this_uuid is used to track variables related to this inference thread
  188. this_uuid = str(uuid.uuid1())
  189. with self.lock:
  190. self.tts_speech_token_dict[this_uuid], self.llm_end_dict[this_uuid] = source_speech_token.flatten().tolist(), True
  191. self.mel_overlap_dict[this_uuid], self.hift_cache_dict[this_uuid] = None, None
  192. if stream is True:
  193. token_hop_len = self.token_min_hop_len
  194. while True:
  195. if len(self.tts_speech_token_dict[this_uuid]) >= token_hop_len + self.token_overlap_len:
  196. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid][:token_hop_len + self.token_overlap_len]) \
  197. .unsqueeze(dim=0)
  198. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  199. prompt_token=flow_prompt_speech_token,
  200. prompt_feat=prompt_speech_feat,
  201. embedding=flow_embedding,
  202. uuid=this_uuid,
  203. finalize=False)
  204. yield {'tts_speech': this_tts_speech.cpu()}
  205. with self.lock:
  206. self.tts_speech_token_dict[this_uuid] = self.tts_speech_token_dict[this_uuid][token_hop_len:]
  207. # increase token_hop_len for better speech quality
  208. token_hop_len = min(self.token_max_hop_len, int(token_hop_len * self.stream_scale_factor))
  209. if self.llm_end_dict[this_uuid] is True and len(self.tts_speech_token_dict[this_uuid]) < token_hop_len + self.token_overlap_len:
  210. break
  211. # deal with remain tokens, make sure inference remain token len equals token_hop_len when cache_speech is not None
  212. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid], dim=1).unsqueeze(dim=0)
  213. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  214. prompt_token=flow_prompt_speech_token,
  215. prompt_feat=prompt_speech_feat,
  216. embedding=flow_embedding,
  217. uuid=this_uuid,
  218. finalize=True)
  219. yield {'tts_speech': this_tts_speech.cpu()}
  220. else:
  221. # deal with all tokens
  222. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
  223. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  224. prompt_token=flow_prompt_speech_token,
  225. prompt_feat=prompt_speech_feat,
  226. embedding=flow_embedding,
  227. uuid=this_uuid,
  228. finalize=True,
  229. speed=speed)
  230. yield {'tts_speech': this_tts_speech.cpu()}
  231. with self.lock:
  232. self.tts_speech_token_dict.pop(this_uuid)
  233. self.llm_end_dict.pop(this_uuid)
  234. self.mel_overlap_dict.pop(this_uuid)
  235. self.hift_cache_dict.pop(this_uuid)