model.py 26 KB

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