model.py 26 KB

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