1
0

model.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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 torch
  16. import numpy as np
  17. import threading
  18. import time
  19. from torch.nn import functional as F
  20. from contextlib import nullcontext
  21. import uuid
  22. from cosyvoice.utils.common import fade_in_out
  23. from cosyvoice.utils.file_utils import convert_onnx_to_trt
  24. class CosyVoiceModel:
  25. def __init__(self,
  26. llm: torch.nn.Module,
  27. flow: torch.nn.Module,
  28. hift: torch.nn.Module,
  29. fp16: bool):
  30. self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  31. self.llm = llm
  32. self.flow = flow
  33. self.hift = hift
  34. self.fp16 = fp16
  35. self.llm.fp16 = fp16
  36. self.flow.fp16 = fp16
  37. if self.fp16 is True:
  38. self.llm.half()
  39. self.flow.half()
  40. self.token_min_hop_len = 2 * self.flow.input_frame_rate
  41. self.token_max_hop_len = 4 * self.flow.input_frame_rate
  42. self.token_overlap_len = 20
  43. # here we fix set flow.decoder.estimator.static_chunk_size = 0 for compatibability
  44. self.flow.decoder.estimator.static_chunk_size = 0
  45. # mel fade in out
  46. self.mel_overlap_len = int(self.token_overlap_len / self.flow.input_frame_rate * 22050 / 256)
  47. self.mel_window = np.hamming(2 * self.mel_overlap_len)
  48. # hift cache
  49. self.mel_cache_len = 20
  50. self.source_cache_len = int(self.mel_cache_len * 256)
  51. # speech fade in out
  52. self.speech_window = np.hamming(2 * self.source_cache_len)
  53. # rtf and decoding related
  54. self.stream_scale_factor = 1
  55. assert self.stream_scale_factor >= 1, 'stream_scale_factor should be greater than 1, change it according to your actual rtf'
  56. self.llm_context = torch.cuda.stream(torch.cuda.Stream(self.device)) if torch.cuda.is_available() else nullcontext()
  57. self.lock = threading.Lock()
  58. # dict used to store session related variable
  59. self.tts_speech_token_dict = {}
  60. self.llm_end_dict = {}
  61. self.mel_overlap_dict = {}
  62. self.flow_cache_dict = {}
  63. self.hift_cache_dict = {}
  64. def load(self, llm_model, flow_model, hift_model):
  65. self.llm.load_state_dict(torch.load(llm_model, map_location=self.device), strict=True)
  66. self.llm.to(self.device).eval()
  67. self.flow.load_state_dict(torch.load(flow_model, map_location=self.device), strict=True)
  68. self.flow.to(self.device).eval()
  69. # in case hift_model is a hifigan model
  70. hift_state_dict = {k.replace('generator.', ''): v for k, v in torch.load(hift_model, map_location=self.device).items()}
  71. self.hift.load_state_dict(hift_state_dict, strict=True)
  72. self.hift.to(self.device).eval()
  73. def load_jit(self, llm_text_encoder_model, llm_llm_model, flow_encoder_model):
  74. llm_text_encoder = torch.jit.load(llm_text_encoder_model, map_location=self.device)
  75. self.llm.text_encoder = llm_text_encoder
  76. llm_llm = torch.jit.load(llm_llm_model, map_location=self.device)
  77. self.llm.llm = llm_llm
  78. flow_encoder = torch.jit.load(flow_encoder_model, map_location=self.device)
  79. self.flow.encoder = flow_encoder
  80. def load_trt(self, flow_decoder_estimator_model, flow_decoder_onnx_model, fp16):
  81. assert torch.cuda.is_available(), 'tensorrt only supports gpu!'
  82. if not os.path.exists(flow_decoder_estimator_model):
  83. convert_onnx_to_trt(flow_decoder_estimator_model, flow_decoder_onnx_model, fp16)
  84. if os.path.getsize(flow_decoder_estimator_model) == 0:
  85. raise ValueError('{} is empty file, delete it and export again!'.format(flow_decoder_estimator_model))
  86. del self.flow.decoder.estimator
  87. import tensorrt as trt
  88. with open(flow_decoder_estimator_model, 'rb') as f:
  89. self.flow.decoder.estimator_engine = trt.Runtime(trt.Logger(trt.Logger.INFO)).deserialize_cuda_engine(f.read())
  90. if self.flow.decoder.estimator_engine is None:
  91. raise ValueError('failed to load trt {}'.format(flow_decoder_estimator_model))
  92. self.flow.decoder.estimator = self.flow.decoder.estimator_engine.create_execution_context()
  93. def llm_job(self, text, prompt_text, llm_prompt_speech_token, llm_embedding, uuid):
  94. with self.llm_context:
  95. for i in self.llm.inference(text=text.to(self.device),
  96. text_len=torch.tensor([text.shape[1]], dtype=torch.int32).to(self.device),
  97. prompt_text=prompt_text.to(self.device),
  98. prompt_text_len=torch.tensor([prompt_text.shape[1]], dtype=torch.int32).to(self.device),
  99. prompt_speech_token=llm_prompt_speech_token.to(self.device),
  100. prompt_speech_token_len=torch.tensor([llm_prompt_speech_token.shape[1]], dtype=torch.int32).to(self.device),
  101. embedding=llm_embedding.to(self.device)):
  102. self.tts_speech_token_dict[uuid].append(i)
  103. self.llm_end_dict[uuid] = True
  104. def token2wav(self, token, prompt_token, prompt_feat, embedding, uuid, finalize=False, speed=1.0):
  105. tts_mel, flow_cache = self.flow.inference(token=token.to(self.device),
  106. token_len=torch.tensor([token.shape[1]], dtype=torch.int32).to(self.device),
  107. prompt_token=prompt_token.to(self.device),
  108. prompt_token_len=torch.tensor([prompt_token.shape[1]], dtype=torch.int32).to(self.device),
  109. prompt_feat=prompt_feat.to(self.device),
  110. prompt_feat_len=torch.tensor([prompt_feat.shape[1]], dtype=torch.int32).to(self.device),
  111. embedding=embedding.to(self.device),
  112. flow_cache=self.flow_cache_dict[uuid])
  113. self.flow_cache_dict[uuid] = flow_cache
  114. # mel overlap fade in out
  115. if self.mel_overlap_dict[uuid].shape[2] != 0:
  116. tts_mel = fade_in_out(tts_mel, self.mel_overlap_dict[uuid], self.mel_window)
  117. # append hift cache
  118. if self.hift_cache_dict[uuid] is not None:
  119. hift_cache_mel, hift_cache_source = self.hift_cache_dict[uuid]['mel'], self.hift_cache_dict[uuid]['source']
  120. tts_mel = torch.concat([hift_cache_mel, tts_mel], dim=2)
  121. else:
  122. hift_cache_source = torch.zeros(1, 1, 0)
  123. # keep overlap mel and hift cache
  124. if finalize is False:
  125. self.mel_overlap_dict[uuid] = tts_mel[:, :, -self.mel_overlap_len:]
  126. tts_mel = tts_mel[:, :, :-self.mel_overlap_len]
  127. tts_speech, tts_source = self.hift.inference(speech_feat=tts_mel, cache_source=hift_cache_source)
  128. if self.hift_cache_dict[uuid] is not None:
  129. tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
  130. self.hift_cache_dict[uuid] = {'mel': tts_mel[:, :, -self.mel_cache_len:],
  131. 'source': tts_source[:, :, -self.source_cache_len:],
  132. 'speech': tts_speech[:, -self.source_cache_len:]}
  133. tts_speech = tts_speech[:, :-self.source_cache_len]
  134. else:
  135. if speed != 1.0:
  136. assert self.hift_cache_dict[uuid] is None, 'speed change only support non-stream inference mode'
  137. tts_mel = F.interpolate(tts_mel, size=int(tts_mel.shape[2] / speed), mode='linear')
  138. tts_speech, tts_source = self.hift.inference(speech_feat=tts_mel, cache_source=hift_cache_source)
  139. if self.hift_cache_dict[uuid] is not None:
  140. tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
  141. return tts_speech
  142. def tts(self, text, flow_embedding, llm_embedding=torch.zeros(0, 192),
  143. prompt_text=torch.zeros(1, 0, dtype=torch.int32),
  144. llm_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
  145. flow_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
  146. prompt_speech_feat=torch.zeros(1, 0, 80), stream=False, speed=1.0, **kwargs):
  147. # this_uuid is used to track variables related to this inference thread
  148. this_uuid = str(uuid.uuid1())
  149. with self.lock:
  150. self.tts_speech_token_dict[this_uuid], self.llm_end_dict[this_uuid] = [], False
  151. self.hift_cache_dict[this_uuid] = None
  152. self.mel_overlap_dict[this_uuid] = torch.zeros(1, 80, 0)
  153. self.flow_cache_dict[this_uuid] = torch.zeros(1, 80, 0, 2)
  154. p = threading.Thread(target=self.llm_job, args=(text, prompt_text, llm_prompt_speech_token, llm_embedding, this_uuid))
  155. p.start()
  156. if stream is True:
  157. token_hop_len = self.token_min_hop_len
  158. while True:
  159. time.sleep(0.1)
  160. if len(self.tts_speech_token_dict[this_uuid]) >= token_hop_len + self.token_overlap_len:
  161. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid][:token_hop_len + self.token_overlap_len]) \
  162. .unsqueeze(dim=0)
  163. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  164. prompt_token=flow_prompt_speech_token,
  165. prompt_feat=prompt_speech_feat,
  166. embedding=flow_embedding,
  167. uuid=this_uuid,
  168. finalize=False)
  169. yield {'tts_speech': this_tts_speech.cpu()}
  170. with self.lock:
  171. self.tts_speech_token_dict[this_uuid] = self.tts_speech_token_dict[this_uuid][token_hop_len:]
  172. # increase token_hop_len for better speech quality
  173. token_hop_len = min(self.token_max_hop_len, int(token_hop_len * self.stream_scale_factor))
  174. 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:
  175. break
  176. p.join()
  177. # deal with remain tokens, make sure inference remain token len equals token_hop_len when cache_speech is not None
  178. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
  179. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  180. prompt_token=flow_prompt_speech_token,
  181. prompt_feat=prompt_speech_feat,
  182. embedding=flow_embedding,
  183. uuid=this_uuid,
  184. finalize=True)
  185. yield {'tts_speech': this_tts_speech.cpu()}
  186. else:
  187. # deal with all tokens
  188. p.join()
  189. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
  190. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  191. prompt_token=flow_prompt_speech_token,
  192. prompt_feat=prompt_speech_feat,
  193. embedding=flow_embedding,
  194. uuid=this_uuid,
  195. finalize=True,
  196. speed=speed)
  197. yield {'tts_speech': this_tts_speech.cpu()}
  198. with self.lock:
  199. self.tts_speech_token_dict.pop(this_uuid)
  200. self.llm_end_dict.pop(this_uuid)
  201. self.mel_overlap_dict.pop(this_uuid)
  202. self.hift_cache_dict.pop(this_uuid)
  203. self.flow_cache_dict.pop(this_uuid)
  204. torch.cuda.empty_cache()
  205. def vc(self, source_speech_token, flow_prompt_speech_token, prompt_speech_feat, flow_embedding, stream=False, speed=1.0, **kwargs):
  206. # this_uuid is used to track variables related to this inference thread
  207. this_uuid = str(uuid.uuid1())
  208. with self.lock:
  209. self.tts_speech_token_dict[this_uuid], self.llm_end_dict[this_uuid] = source_speech_token.flatten().tolist(), True
  210. self.hift_cache_dict[this_uuid] = None
  211. self.mel_overlap_dict[this_uuid] = torch.zeros(1, 80, 0)
  212. self.flow_cache_dict[this_uuid] = torch.zeros(1, 80, 0, 2)
  213. if stream is True:
  214. token_hop_len = self.token_min_hop_len
  215. while True:
  216. if len(self.tts_speech_token_dict[this_uuid]) >= token_hop_len + self.token_overlap_len:
  217. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid][:token_hop_len + self.token_overlap_len]) \
  218. .unsqueeze(dim=0)
  219. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  220. prompt_token=flow_prompt_speech_token,
  221. prompt_feat=prompt_speech_feat,
  222. embedding=flow_embedding,
  223. uuid=this_uuid,
  224. finalize=False)
  225. yield {'tts_speech': this_tts_speech.cpu()}
  226. with self.lock:
  227. self.tts_speech_token_dict[this_uuid] = self.tts_speech_token_dict[this_uuid][token_hop_len:]
  228. # increase token_hop_len for better speech quality
  229. token_hop_len = min(self.token_max_hop_len, int(token_hop_len * self.stream_scale_factor))
  230. 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:
  231. break
  232. # deal with remain tokens, make sure inference remain token len equals token_hop_len when cache_speech is not None
  233. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
  234. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  235. prompt_token=flow_prompt_speech_token,
  236. prompt_feat=prompt_speech_feat,
  237. embedding=flow_embedding,
  238. uuid=this_uuid,
  239. finalize=True)
  240. yield {'tts_speech': this_tts_speech.cpu()}
  241. else:
  242. # deal with all tokens
  243. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
  244. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  245. prompt_token=flow_prompt_speech_token,
  246. prompt_feat=prompt_speech_feat,
  247. embedding=flow_embedding,
  248. uuid=this_uuid,
  249. finalize=True,
  250. speed=speed)
  251. yield {'tts_speech': this_tts_speech.cpu()}
  252. with self.lock:
  253. self.tts_speech_token_dict.pop(this_uuid)
  254. self.llm_end_dict.pop(this_uuid)
  255. self.mel_overlap_dict.pop(this_uuid)
  256. self.hift_cache_dict.pop(this_uuid)
  257. torch.cuda.empty_cache()
  258. class CosyVoice2Model(CosyVoiceModel):
  259. def __init__(self,
  260. llm: torch.nn.Module,
  261. flow: torch.nn.Module,
  262. hift: torch.nn.Module,
  263. fp16: bool):
  264. self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  265. self.llm = llm
  266. self.flow = flow
  267. self.hift = hift
  268. self.fp16 = fp16
  269. self.llm.fp16 = fp16
  270. self.flow.fp16 = fp16
  271. if self.fp16 is True:
  272. self.llm.half()
  273. self.flow.half()
  274. self.token_hop_len = 2 * self.flow.input_frame_rate
  275. # here we fix flow encoder/decoder decoding_chunk_size, in the future we will send it as arguments, or use cache
  276. self.flow.encoder.static_chunk_size = 2 * self.flow.input_frame_rate
  277. self.flow.decoder.estimator.static_chunk_size = 2 * self.flow.input_frame_rate * self.flow.token_mel_ratio
  278. # hift cache
  279. self.mel_cache_len = 8
  280. self.source_cache_len = int(self.mel_cache_len * 480)
  281. # speech fade in out
  282. self.speech_window = np.hamming(2 * self.source_cache_len)
  283. # rtf and decoding related
  284. self.stream_scale_factor = 1
  285. self.llm_context = torch.cuda.stream(torch.cuda.Stream(self.device)) if torch.cuda.is_available() else nullcontext()
  286. self.lock = threading.Lock()
  287. # dict used to store session related variable
  288. self.tts_speech_token_dict = {}
  289. self.llm_end_dict = {}
  290. self.hift_cache_dict = {}
  291. def load_jit(self, flow_encoder_model):
  292. flow_encoder = torch.jit.load(flow_encoder_model, map_location=self.device)
  293. self.flow.encoder = flow_encoder
  294. def token2wav(self, token, prompt_token, prompt_feat, embedding, uuid, token_offset, finalize=False, speed=1.0):
  295. tts_mel, _ = self.flow.inference(token=token.to(self.device),
  296. token_len=torch.tensor([token.shape[1]], dtype=torch.int32).to(self.device),
  297. prompt_token=prompt_token.to(self.device),
  298. prompt_token_len=torch.tensor([prompt_token.shape[1]], dtype=torch.int32).to(self.device),
  299. prompt_feat=prompt_feat.to(self.device),
  300. prompt_feat_len=torch.tensor([prompt_feat.shape[1]], dtype=torch.int32).to(self.device),
  301. embedding=embedding.to(self.device),
  302. finalize=finalize)
  303. tts_mel = tts_mel[:, :, token_offset * self.flow.token_mel_ratio:]
  304. # append hift cache
  305. if self.hift_cache_dict[uuid] is not None:
  306. hift_cache_mel, hift_cache_source = self.hift_cache_dict[uuid]['mel'], self.hift_cache_dict[uuid]['source']
  307. tts_mel = torch.concat([hift_cache_mel, tts_mel], dim=2)
  308. else:
  309. hift_cache_source = torch.zeros(1, 1, 0)
  310. # keep overlap mel and hift cache
  311. if finalize is False:
  312. tts_speech, tts_source = self.hift.inference(speech_feat=tts_mel, cache_source=hift_cache_source)
  313. if self.hift_cache_dict[uuid] is not None:
  314. tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
  315. self.hift_cache_dict[uuid] = {'mel': tts_mel[:, :, -self.mel_cache_len:],
  316. 'source': tts_source[:, :, -self.source_cache_len:],
  317. 'speech': tts_speech[:, -self.source_cache_len:]}
  318. tts_speech = tts_speech[:, :-self.source_cache_len]
  319. else:
  320. if speed != 1.0:
  321. assert self.hift_cache_dict[uuid] is None, 'speed change only support non-stream inference mode'
  322. tts_mel = F.interpolate(tts_mel, size=int(tts_mel.shape[2] / speed), mode='linear')
  323. tts_speech, tts_source = self.hift.inference(speech_feat=tts_mel, cache_source=hift_cache_source)
  324. if self.hift_cache_dict[uuid] is not None:
  325. tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
  326. return tts_speech
  327. def tts(self, text, flow_embedding, llm_embedding=torch.zeros(0, 192),
  328. prompt_text=torch.zeros(1, 0, dtype=torch.int32),
  329. llm_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
  330. flow_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
  331. prompt_speech_feat=torch.zeros(1, 0, 80), stream=False, speed=1.0, **kwargs):
  332. # this_uuid is used to track variables related to this inference thread
  333. this_uuid = str(uuid.uuid1())
  334. with self.lock:
  335. self.tts_speech_token_dict[this_uuid], self.llm_end_dict[this_uuid] = [], False
  336. self.hift_cache_dict[this_uuid] = None
  337. p = threading.Thread(target=self.llm_job, args=(text, prompt_text, llm_prompt_speech_token, llm_embedding, this_uuid))
  338. p.start()
  339. if stream is True:
  340. token_offset = 0
  341. while True:
  342. time.sleep(0.1)
  343. if len(self.tts_speech_token_dict[this_uuid]) - token_offset >= self.token_hop_len + self.flow.pre_lookahead_len:
  344. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid][:token_offset + self.token_hop_len + self.flow.pre_lookahead_len]).unsqueeze(dim=0)
  345. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  346. prompt_token=flow_prompt_speech_token,
  347. prompt_feat=prompt_speech_feat,
  348. embedding=flow_embedding,
  349. uuid=this_uuid,
  350. token_offset=token_offset,
  351. finalize=False)
  352. token_offset += self.token_hop_len
  353. yield {'tts_speech': this_tts_speech.cpu()}
  354. if self.llm_end_dict[this_uuid] is True and len(self.tts_speech_token_dict[this_uuid]) - token_offset < self.token_hop_len + self.flow.pre_lookahead_len:
  355. break
  356. p.join()
  357. # deal with remain tokens, make sure inference remain token len equals token_hop_len when cache_speech is not None
  358. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
  359. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  360. prompt_token=flow_prompt_speech_token,
  361. prompt_feat=prompt_speech_feat,
  362. embedding=flow_embedding,
  363. uuid=this_uuid,
  364. token_offset=token_offset,
  365. finalize=True)
  366. yield {'tts_speech': this_tts_speech.cpu()}
  367. else:
  368. # deal with all tokens
  369. p.join()
  370. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
  371. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  372. prompt_token=flow_prompt_speech_token,
  373. prompt_feat=prompt_speech_feat,
  374. embedding=flow_embedding,
  375. uuid=this_uuid,
  376. token_offset=0,
  377. finalize=True,
  378. speed=speed)
  379. yield {'tts_speech': this_tts_speech.cpu()}
  380. with self.lock:
  381. self.tts_speech_token_dict.pop(this_uuid)
  382. self.llm_end_dict.pop(this_uuid)
  383. torch.cuda.empty_cache()