model.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu)
  2. # 2025 Alibaba Inc (authors: Xiang Lyu, Bofan Zhou)
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os
  16. from typing import Generator
  17. import torch
  18. import numpy as np
  19. import threading
  20. import time
  21. from torch.nn import functional as F
  22. from contextlib import nullcontext
  23. import uuid
  24. from cosyvoice.utils.common import fade_in_out
  25. from cosyvoice.utils.file_utils import convert_onnx_to_trt, export_cosyvoice2_vllm
  26. from cosyvoice.utils.common import TrtContextWrapper
  27. class CosyVoiceModel:
  28. def __init__(self,
  29. llm: torch.nn.Module,
  30. flow: torch.nn.Module,
  31. hift: torch.nn.Module,
  32. fp16: bool = False):
  33. self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  34. self.llm = llm
  35. self.flow = flow
  36. self.hift = hift
  37. self.fp16 = fp16
  38. self.token_min_hop_len = 2 * self.flow.input_frame_rate
  39. self.token_max_hop_len = 4 * self.flow.input_frame_rate
  40. self.token_overlap_len = 20
  41. # mel fade in out
  42. self.mel_overlap_len = int(self.token_overlap_len / self.flow.input_frame_rate * 22050 / 256)
  43. self.mel_window = np.hamming(2 * self.mel_overlap_len)
  44. # hift cache
  45. self.mel_cache_len = 20
  46. self.source_cache_len = int(self.mel_cache_len * 256)
  47. # speech fade in out
  48. self.speech_window = np.hamming(2 * self.source_cache_len)
  49. # rtf and decoding related
  50. self.stream_scale_factor = 1
  51. assert self.stream_scale_factor >= 1, 'stream_scale_factor should be greater than 1, change it according to your actual rtf'
  52. self.llm_context = torch.cuda.stream(torch.cuda.Stream(self.device)) if torch.cuda.is_available() else nullcontext()
  53. self.lock = threading.Lock()
  54. # dict used to store session related variable
  55. self.tts_speech_token_dict = {}
  56. self.llm_end_dict = {}
  57. self.mel_overlap_dict = {}
  58. self.flow_cache_dict = {}
  59. self.hift_cache_dict = {}
  60. def load(self, llm_model, flow_model, hift_model):
  61. self.llm.load_state_dict(torch.load(llm_model, map_location=self.device), strict=True)
  62. self.llm.to(self.device).eval()
  63. self.flow.load_state_dict(torch.load(flow_model, map_location=self.device), strict=True)
  64. self.flow.to(self.device).eval()
  65. # in case hift_model is a hifigan model
  66. hift_state_dict = {k.replace('generator.', ''): v for k, v in torch.load(hift_model, map_location=self.device).items()}
  67. self.hift.load_state_dict(hift_state_dict, strict=True)
  68. self.hift.to(self.device).eval()
  69. def load_jit(self, llm_text_encoder_model, llm_llm_model, flow_encoder_model):
  70. llm_text_encoder = torch.jit.load(llm_text_encoder_model, map_location=self.device)
  71. self.llm.text_encoder = llm_text_encoder
  72. llm_llm = torch.jit.load(llm_llm_model, map_location=self.device)
  73. self.llm.llm = llm_llm
  74. flow_encoder = torch.jit.load(flow_encoder_model, map_location=self.device)
  75. self.flow.encoder = flow_encoder
  76. def load_trt(self, flow_decoder_estimator_model, flow_decoder_onnx_model, trt_concurrent, fp16):
  77. assert torch.cuda.is_available(), 'tensorrt only supports gpu!'
  78. if not os.path.exists(flow_decoder_estimator_model) or os.path.getsize(flow_decoder_estimator_model) == 0:
  79. convert_onnx_to_trt(flow_decoder_estimator_model, self.get_trt_kwargs(), flow_decoder_onnx_model, fp16)
  80. del self.flow.decoder.estimator
  81. import tensorrt as trt
  82. with open(flow_decoder_estimator_model, 'rb') as f:
  83. estimator_engine = trt.Runtime(trt.Logger(trt.Logger.INFO)).deserialize_cuda_engine(f.read())
  84. assert estimator_engine is not None, 'failed to load trt {}'.format(flow_decoder_estimator_model)
  85. self.flow.decoder.estimator = TrtContextWrapper(estimator_engine, trt_concurrent=trt_concurrent, device=self.device)
  86. def get_trt_kwargs(self):
  87. min_shape = [(2, 80, 4), (2, 1, 4), (2, 80, 4), (2, 80, 4)]
  88. opt_shape = [(2, 80, 500), (2, 1, 500), (2, 80, 500), (2, 80, 500)]
  89. max_shape = [(2, 80, 3000), (2, 1, 3000), (2, 80, 3000), (2, 80, 3000)]
  90. input_names = ["x", "mask", "mu", "cond"]
  91. return {'min_shape': min_shape, 'opt_shape': opt_shape, 'max_shape': max_shape, 'input_names': input_names}
  92. def llm_job(self, text, prompt_text, llm_prompt_speech_token, llm_embedding, uuid):
  93. with self.llm_context, torch.cuda.amp.autocast(self.fp16 is True and hasattr(self.llm, 'vllm') is False):
  94. if isinstance(text, Generator):
  95. assert (self.__class__.__name__ != 'CosyVoiceModel') and not hasattr(self.llm, 'vllm'), 'streaming input text is only implemented for CosyVoice2/3 and do not support vllm!'
  96. for i in self.llm.inference_bistream(text=text,
  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. else:
  104. for i in self.llm.inference(text=text.to(self.device),
  105. text_len=torch.tensor([text.shape[1]], dtype=torch.int32).to(self.device),
  106. prompt_text=prompt_text.to(self.device),
  107. prompt_text_len=torch.tensor([prompt_text.shape[1]], dtype=torch.int32).to(self.device),
  108. prompt_speech_token=llm_prompt_speech_token.to(self.device),
  109. prompt_speech_token_len=torch.tensor([llm_prompt_speech_token.shape[1]], dtype=torch.int32).to(self.device),
  110. embedding=llm_embedding.to(self.device),
  111. uuid=uuid):
  112. self.tts_speech_token_dict[uuid].append(i)
  113. self.llm_end_dict[uuid] = True
  114. def vc_job(self, source_speech_token, uuid):
  115. self.tts_speech_token_dict[uuid] = source_speech_token.flatten().tolist()
  116. self.llm_end_dict[uuid] = True
  117. def token2wav(self, token, prompt_token, prompt_feat, embedding, uuid, finalize=False, speed=1.0):
  118. with torch.cuda.amp.autocast(self.fp16):
  119. tts_mel, self.flow_cache_dict[uuid] = self.flow.inference(token=token.to(self.device, dtype=torch.int32),
  120. token_len=torch.tensor([token.shape[1]], dtype=torch.int32).to(self.device),
  121. prompt_token=prompt_token.to(self.device),
  122. prompt_token_len=torch.tensor([prompt_token.shape[1]], dtype=torch.int32).to(self.device),
  123. prompt_feat=prompt_feat.to(self.device),
  124. prompt_feat_len=torch.tensor([prompt_feat.shape[1]], dtype=torch.int32).to(self.device),
  125. embedding=embedding.to(self.device),
  126. flow_cache=self.flow_cache_dict[uuid])
  127. # mel overlap fade in out
  128. if self.mel_overlap_dict[uuid].shape[2] != 0:
  129. tts_mel = fade_in_out(tts_mel, self.mel_overlap_dict[uuid], self.mel_window)
  130. # append hift cache
  131. if self.hift_cache_dict[uuid] is not None:
  132. hift_cache_mel, hift_cache_source = self.hift_cache_dict[uuid]['mel'], self.hift_cache_dict[uuid]['source']
  133. tts_mel = torch.concat([hift_cache_mel, tts_mel], dim=2)
  134. else:
  135. hift_cache_source = torch.zeros(1, 1, 0)
  136. # keep overlap mel and hift cache
  137. if finalize is False:
  138. self.mel_overlap_dict[uuid] = tts_mel[:, :, -self.mel_overlap_len:]
  139. tts_mel = tts_mel[:, :, :-self.mel_overlap_len]
  140. tts_speech, tts_source = self.hift.inference(speech_feat=tts_mel, cache_source=hift_cache_source)
  141. if self.hift_cache_dict[uuid] is not None:
  142. tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
  143. self.hift_cache_dict[uuid] = {'mel': tts_mel[:, :, -self.mel_cache_len:],
  144. 'source': tts_source[:, :, -self.source_cache_len:],
  145. 'speech': tts_speech[:, -self.source_cache_len:]}
  146. tts_speech = tts_speech[:, :-self.source_cache_len]
  147. else:
  148. if speed != 1.0:
  149. assert self.hift_cache_dict[uuid] is None, 'speed change only support non-stream inference mode'
  150. tts_mel = F.interpolate(tts_mel, size=int(tts_mel.shape[2] / speed), mode='linear')
  151. tts_speech, tts_source = self.hift.inference(speech_feat=tts_mel, cache_source=hift_cache_source)
  152. if self.hift_cache_dict[uuid] is not None:
  153. tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
  154. return tts_speech
  155. def tts(self, text=torch.zeros(1, 0, dtype=torch.int32), flow_embedding=torch.zeros(0, 192), llm_embedding=torch.zeros(0, 192),
  156. prompt_text=torch.zeros(1, 0, dtype=torch.int32),
  157. llm_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
  158. flow_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
  159. prompt_speech_feat=torch.zeros(1, 0, 80), source_speech_token=torch.zeros(1, 0, dtype=torch.int32), stream=False, speed=1.0, **kwargs):
  160. # this_uuid is used to track variables related to this inference thread
  161. this_uuid = str(uuid.uuid1())
  162. with self.lock:
  163. self.tts_speech_token_dict[this_uuid], self.llm_end_dict[this_uuid] = [], False
  164. self.hift_cache_dict[this_uuid] = None
  165. self.mel_overlap_dict[this_uuid] = torch.zeros(1, 80, 0)
  166. self.flow_cache_dict[this_uuid] = torch.zeros(1, 80, 0, 2)
  167. if source_speech_token.shape[1] == 0:
  168. p = threading.Thread(target=self.llm_job, args=(text, prompt_text, llm_prompt_speech_token, llm_embedding, this_uuid))
  169. else:
  170. p = threading.Thread(target=self.vc_job, args=(source_speech_token, this_uuid))
  171. p.start()
  172. if stream is True:
  173. token_hop_len = self.token_min_hop_len
  174. while True:
  175. time.sleep(0.1)
  176. if len(self.tts_speech_token_dict[this_uuid]) >= token_hop_len + self.token_overlap_len:
  177. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid][:token_hop_len + self.token_overlap_len]) \
  178. .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=False)
  185. yield {'tts_speech': this_tts_speech.cpu()}
  186. with self.lock:
  187. self.tts_speech_token_dict[this_uuid] = self.tts_speech_token_dict[this_uuid][token_hop_len:]
  188. # increase token_hop_len for better speech quality
  189. token_hop_len = min(self.token_max_hop_len, int(token_hop_len * self.stream_scale_factor))
  190. 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:
  191. break
  192. p.join()
  193. # deal with remain tokens, make sure inference remain token len equals token_hop_len when cache_speech is not None
  194. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
  195. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  196. prompt_token=flow_prompt_speech_token,
  197. prompt_feat=prompt_speech_feat,
  198. embedding=flow_embedding,
  199. uuid=this_uuid,
  200. finalize=True)
  201. yield {'tts_speech': this_tts_speech.cpu()}
  202. else:
  203. # deal with all tokens
  204. p.join()
  205. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
  206. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  207. prompt_token=flow_prompt_speech_token,
  208. prompt_feat=prompt_speech_feat,
  209. embedding=flow_embedding,
  210. uuid=this_uuid,
  211. finalize=True,
  212. speed=speed)
  213. yield {'tts_speech': this_tts_speech.cpu()}
  214. with self.lock:
  215. self.tts_speech_token_dict.pop(this_uuid)
  216. self.llm_end_dict.pop(this_uuid)
  217. self.mel_overlap_dict.pop(this_uuid)
  218. self.hift_cache_dict.pop(this_uuid)
  219. self.flow_cache_dict.pop(this_uuid)
  220. if torch.cuda.is_available():
  221. torch.cuda.empty_cache()
  222. torch.cuda.current_stream().synchronize()
  223. class CosyVoice2Model(CosyVoiceModel):
  224. def __init__(self,
  225. llm: torch.nn.Module,
  226. flow: torch.nn.Module,
  227. hift: torch.nn.Module,
  228. fp16: bool = False):
  229. self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  230. self.llm = llm
  231. self.flow = flow
  232. self.hift = hift
  233. self.fp16 = fp16
  234. # NOTE must matching training static_chunk_size
  235. self.token_hop_len = 25
  236. # hift cache
  237. self.mel_cache_len = 8
  238. self.source_cache_len = int(self.mel_cache_len * 480)
  239. # speech fade in out
  240. self.speech_window = np.hamming(2 * self.source_cache_len)
  241. # rtf and decoding related
  242. self.llm_context = torch.cuda.stream(torch.cuda.Stream(self.device)) if torch.cuda.is_available() else nullcontext()
  243. self.lock = threading.Lock()
  244. # dict used to store session related variable
  245. self.tts_speech_token_dict = {}
  246. self.llm_end_dict = {}
  247. self.hift_cache_dict = {}
  248. def load_jit(self, flow_encoder_model):
  249. flow_encoder = torch.jit.load(flow_encoder_model, map_location=self.device)
  250. self.flow.encoder = flow_encoder
  251. def load_vllm(self, model_dir):
  252. export_cosyvoice2_vllm(self.llm, model_dir, self.device)
  253. from vllm import EngineArgs, LLMEngine
  254. engine_args = EngineArgs(model=model_dir,
  255. skip_tokenizer_init=True,
  256. enable_prompt_embeds=True,
  257. gpu_memory_utilization=0.2)
  258. self.llm.vllm = LLMEngine.from_engine_args(engine_args)
  259. self.llm.lock = threading.Lock()
  260. del self.llm.llm.model.model.layers
  261. def token2wav(self, token, prompt_token, prompt_feat, embedding, token_offset, uuid, stream=False, finalize=False, speed=1.0):
  262. with torch.cuda.amp.autocast(self.fp16):
  263. tts_mel, _ = self.flow.inference(token=token.to(self.device, dtype=torch.int32),
  264. token_len=torch.tensor([token.shape[1]], dtype=torch.int32).to(self.device),
  265. prompt_token=prompt_token.to(self.device),
  266. prompt_token_len=torch.tensor([prompt_token.shape[1]], dtype=torch.int32).to(self.device),
  267. prompt_feat=prompt_feat.to(self.device),
  268. prompt_feat_len=torch.tensor([prompt_feat.shape[1]], dtype=torch.int32).to(self.device),
  269. embedding=embedding.to(self.device),
  270. streaming=stream,
  271. finalize=finalize)
  272. tts_mel = tts_mel[:, :, token_offset * self.flow.token_mel_ratio:]
  273. # append hift cache
  274. if self.hift_cache_dict[uuid] is not None:
  275. hift_cache_mel, hift_cache_source = self.hift_cache_dict[uuid]['mel'], self.hift_cache_dict[uuid]['source']
  276. tts_mel = torch.concat([hift_cache_mel, tts_mel], dim=2)
  277. else:
  278. hift_cache_source = torch.zeros(1, 1, 0)
  279. # keep overlap mel and hift cache
  280. if finalize is False:
  281. tts_speech, tts_source = self.hift.inference(speech_feat=tts_mel, cache_source=hift_cache_source)
  282. if self.hift_cache_dict[uuid] is not None:
  283. tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
  284. self.hift_cache_dict[uuid] = {'mel': tts_mel[:, :, -self.mel_cache_len:],
  285. 'source': tts_source[:, :, -self.source_cache_len:],
  286. 'speech': tts_speech[:, -self.source_cache_len:]}
  287. tts_speech = tts_speech[:, :-self.source_cache_len]
  288. else:
  289. if speed != 1.0:
  290. assert self.hift_cache_dict[uuid] is None, 'speed change only support non-stream inference mode'
  291. tts_mel = F.interpolate(tts_mel, size=int(tts_mel.shape[2] / speed), mode='linear')
  292. tts_speech, tts_source = self.hift.inference(speech_feat=tts_mel, cache_source=hift_cache_source)
  293. if self.hift_cache_dict[uuid] is not None:
  294. tts_speech = fade_in_out(tts_speech, self.hift_cache_dict[uuid]['speech'], self.speech_window)
  295. return tts_speech
  296. def tts(self, text=torch.zeros(1, 0, dtype=torch.int32), flow_embedding=torch.zeros(0, 192), llm_embedding=torch.zeros(0, 192),
  297. prompt_text=torch.zeros(1, 0, dtype=torch.int32),
  298. llm_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
  299. flow_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
  300. prompt_speech_feat=torch.zeros(1, 0, 80), source_speech_token=torch.zeros(1, 0, dtype=torch.int32), stream=False, speed=1.0, **kwargs):
  301. # this_uuid is used to track variables related to this inference thread
  302. this_uuid = str(uuid.uuid1())
  303. with self.lock:
  304. self.tts_speech_token_dict[this_uuid], self.llm_end_dict[this_uuid] = [], False
  305. self.hift_cache_dict[this_uuid] = None
  306. if source_speech_token.shape[1] == 0:
  307. p = threading.Thread(target=self.llm_job, args=(text, prompt_text, llm_prompt_speech_token, llm_embedding, this_uuid))
  308. else:
  309. p = threading.Thread(target=self.vc_job, args=(source_speech_token, this_uuid))
  310. p.start()
  311. if stream is True:
  312. token_offset = 0
  313. prompt_token_pad = int(np.ceil(flow_prompt_speech_token.shape[1] / self.token_hop_len) * self.token_hop_len - flow_prompt_speech_token.shape[1])
  314. while True:
  315. time.sleep(0.1)
  316. this_token_hop_len = self.token_hop_len + prompt_token_pad if token_offset == 0 else self.token_hop_len
  317. if len(self.tts_speech_token_dict[this_uuid]) - token_offset >= this_token_hop_len + self.flow.pre_lookahead_len:
  318. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid][:token_offset + this_token_hop_len + self.flow.pre_lookahead_len]).unsqueeze(dim=0)
  319. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  320. prompt_token=flow_prompt_speech_token,
  321. prompt_feat=prompt_speech_feat,
  322. embedding=flow_embedding,
  323. token_offset=token_offset,
  324. uuid=this_uuid,
  325. stream=stream,
  326. finalize=False)
  327. token_offset += this_token_hop_len
  328. yield {'tts_speech': this_tts_speech.cpu()}
  329. if self.llm_end_dict[this_uuid] is True and len(self.tts_speech_token_dict[this_uuid]) - token_offset < this_token_hop_len + self.flow.pre_lookahead_len:
  330. break
  331. p.join()
  332. # deal with remain tokens, make sure inference remain token len equals token_hop_len when cache_speech is not None
  333. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
  334. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  335. prompt_token=flow_prompt_speech_token,
  336. prompt_feat=prompt_speech_feat,
  337. embedding=flow_embedding,
  338. token_offset=token_offset,
  339. uuid=this_uuid,
  340. finalize=True)
  341. yield {'tts_speech': this_tts_speech.cpu()}
  342. else:
  343. # deal with all tokens
  344. p.join()
  345. this_tts_speech_token = torch.tensor(self.tts_speech_token_dict[this_uuid]).unsqueeze(dim=0)
  346. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  347. prompt_token=flow_prompt_speech_token,
  348. prompt_feat=prompt_speech_feat,
  349. embedding=flow_embedding,
  350. token_offset=0,
  351. uuid=this_uuid,
  352. finalize=True,
  353. speed=speed)
  354. yield {'tts_speech': this_tts_speech.cpu()}
  355. with self.lock:
  356. self.tts_speech_token_dict.pop(this_uuid)
  357. self.llm_end_dict.pop(this_uuid)
  358. self.hift_cache_dict.pop(this_uuid)
  359. if torch.cuda.is_available():
  360. torch.cuda.empty_cache()
  361. torch.cuda.current_stream().synchronize()
  362. class CosyVoice3Model(CosyVoice2Model):
  363. def __init__(self,
  364. llm: torch.nn.Module,
  365. flow: torch.nn.Module,
  366. hift: torch.nn.Module,
  367. fp16: bool = False):
  368. self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  369. self.llm = llm
  370. self.flow = flow
  371. self.hift = hift
  372. self.fp16 = fp16
  373. # NOTE must matching training static_chunk_size
  374. self.token_hop_len = 25
  375. # rtf and decoding related
  376. self.llm_context = torch.cuda.stream(torch.cuda.Stream(self.device)) if torch.cuda.is_available() else nullcontext()
  377. self.lock = threading.Lock()
  378. # dict used to store session related variable
  379. self.tts_speech_token_dict = {}
  380. self.llm_end_dict = {}
  381. self.hift_cache_dict = {}
  382. def token2wav(self, token, prompt_token, prompt_feat, embedding, token_offset, uuid, stream=False, finalize=False, speed=1.0):
  383. with torch.cuda.amp.autocast(self.fp16):
  384. tts_mel, _ = self.flow.inference(token=token.to(self.device, dtype=torch.int32),
  385. token_len=torch.tensor([token.shape[1]], dtype=torch.int32).to(self.device),
  386. prompt_token=prompt_token.to(self.device),
  387. prompt_token_len=torch.tensor([prompt_token.shape[1]], dtype=torch.int32).to(self.device),
  388. prompt_feat=prompt_feat.to(self.device),
  389. prompt_feat_len=torch.tensor([prompt_feat.shape[1]], dtype=torch.int32).to(self.device),
  390. embedding=embedding.to(self.device),
  391. streaming=stream,
  392. finalize=finalize)
  393. tts_mel = tts_mel[:, :, token_offset * self.flow.token_mel_ratio:]
  394. # append mel cache
  395. if self.hift_cache_dict[uuid] is not None:
  396. hift_cache_mel = self.hift_cache_dict[uuid]['mel']
  397. tts_mel = torch.concat([hift_cache_mel, tts_mel], dim=2)
  398. self.hift_cache_dict[uuid]['mel'] = tts_mel
  399. else:
  400. self.hift_cache_dict[uuid] = {'mel': tts_mel, 'speech_offset': 0}
  401. if speed != 1.0:
  402. assert token_offset == 0 and finalize is True, 'speed change only support non-stream inference mode'
  403. tts_mel = F.interpolate(tts_mel, size=int(tts_mel.shape[2] / speed), mode='linear')
  404. tts_speech, _ = self.hift.inference(speech_feat=tts_mel, finalize=finalize)
  405. tts_speech = tts_speech[:, self.hift_cache_dict[uuid]['speech_offset']:]
  406. self.hift_cache_dict[uuid]['speech_offset'] += tts_speech.shape[1]
  407. return tts_speech