model.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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 contextlib import nullcontext
  20. import uuid
  21. from cosyvoice.utils.common import fade_in_out
  22. import numpy as np
  23. import onnxruntime as ort
  24. class CosyVoiceModel:
  25. def __init__(self,
  26. llm: torch.nn.Module,
  27. flow: torch.nn.Module,
  28. hift: torch.nn.Module):
  29. self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  30. self.llm = llm
  31. self.flow = flow
  32. self.hift = hift
  33. self.token_min_hop_len = 100
  34. self.token_max_hop_len = 200
  35. self.token_overlap_len = 20
  36. # mel fade in out
  37. self.mel_overlap_len = 34
  38. self.mel_window = np.hamming(2 * self.mel_overlap_len)
  39. # hift cache
  40. self.mel_cache_len = 20
  41. self.source_cache_len = int(self.mel_cache_len * 256)
  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.flow_hift_context = torch.cuda.stream(torch.cuda.Stream(self.device)) if torch.cuda.is_available() else nullcontext()
  47. self.lock = threading.Lock()
  48. # dict used to store session related variable
  49. self.tts_speech_token_dict = {}
  50. self.llm_end_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):
  62. llm_text_encoder = torch.jit.load(llm_text_encoder_model)
  63. self.llm.text_encoder = llm_text_encoder
  64. llm_llm = torch.jit.load(llm_llm_model)
  65. self.llm.llm = llm_llm
  66. # def load_trt(self, model_dir, use_fp16):
  67. # import tensorrt as trt
  68. # trt_file_name = 'estimator_fp16.plan' if use_fp16 else 'estimator_fp32.plan'
  69. # trt_file_path = os.path.join(model_dir, trt_file_name)
  70. # if not os.path.isfile(trt_file_path):
  71. # raise f"{trt_file_path} does not exist. Please use bin/export_trt.py to generate .plan file"
  72. # trt.init_libnvinfer_plugins(None, "")
  73. # logger = trt.Logger(trt.Logger.WARNING)
  74. # runtime = trt.Runtime(logger)
  75. # with open(trt_file_path, 'rb') as f:
  76. # serialized_engine = f.read()
  77. # engine = runtime.deserialize_cuda_engine(serialized_engine)
  78. # self.flow.decoder.estimator_context = engine.create_execution_context()
  79. # self.flow.decoder.estimator = None
  80. def load_onnx(self, model_dir, use_fp16):
  81. onnx_file_name = 'estimator_fp16.onnx' if use_fp16 else 'estimator_fp32.onnx'
  82. onnx_file_path = os.path.join(model_dir, onnx_file_name)
  83. if not os.path.isfile(onnx_file_path):
  84. raise f"{onnx_file_path} does not exist. Please use bin/export_trt.py to generate .onnx file"
  85. providers = ['CUDAExecutionProvider']
  86. sess_options = ort.SessionOptions()
  87. # Add TensorRT Execution Provider
  88. providers = [
  89. 'CUDAExecutionProvider'
  90. ]
  91. # Load the ONNX model
  92. self.flow.decoder.session = ort.InferenceSession(onnx_file_path, sess_options=sess_options, providers=providers)
  93. # self.flow.decoder.estimator_context = None
  94. self.flow.decoder.estimator = None
  95. def llm_job(self, text, prompt_text, llm_prompt_speech_token, llm_embedding, uuid):
  96. with self.llm_context:
  97. for i in self.llm.inference(text=text.to(self.device),
  98. text_len=torch.tensor([text.shape[1]], dtype=torch.int32).to(self.device),
  99. prompt_text=prompt_text.to(self.device),
  100. prompt_text_len=torch.tensor([prompt_text.shape[1]], dtype=torch.int32).to(self.device),
  101. prompt_speech_token=llm_prompt_speech_token.to(self.device),
  102. prompt_speech_token_len=torch.tensor([llm_prompt_speech_token.shape[1]], dtype=torch.int32).to(self.device),
  103. embedding=llm_embedding.to(self.device).half(),
  104. sampling=25,
  105. max_token_text_ratio=30,
  106. min_token_text_ratio=3):
  107. self.tts_speech_token_dict[uuid].append(i)
  108. self.llm_end_dict[uuid] = True
  109. def token2wav(self, token, prompt_token, prompt_feat, embedding, uuid, finalize=False):
  110. with self.flow_hift_context:
  111. tts_mel = self.flow.inference(token=token.to(self.device),
  112. token_len=torch.tensor([token.shape[1]], dtype=torch.int32).to(self.device),
  113. prompt_token=prompt_token.to(self.device),
  114. prompt_token_len=torch.tensor([prompt_token.shape[1]], dtype=torch.int32).to(self.device),
  115. prompt_feat=prompt_feat.to(self.device),
  116. prompt_feat_len=torch.tensor([prompt_feat.shape[1]], dtype=torch.int32).to(self.device),
  117. embedding=embedding.to(self.device))
  118. # mel overlap fade in out
  119. if self.mel_overlap_dict[uuid] is not None:
  120. tts_mel = fade_in_out(tts_mel, self.mel_overlap_dict[uuid], self.mel_window)
  121. # append hift cache
  122. if self.hift_cache_dict[uuid] is not None:
  123. hift_cache_mel, hift_cache_source = self.hift_cache_dict[uuid]['mel'], self.hift_cache_dict[uuid]['source']
  124. tts_mel = torch.concat([hift_cache_mel, tts_mel], dim=2)
  125. else:
  126. hift_cache_source = torch.zeros(1, 1, 0)
  127. # keep overlap mel and hift cache
  128. if finalize is False:
  129. self.mel_overlap_dict[uuid] = tts_mel[:, :, -self.mel_overlap_len:]
  130. tts_mel = tts_mel[:, :, :-self.mel_overlap_len]
  131. tts_speech, tts_source = self.hift.inference(mel=tts_mel, cache_source=hift_cache_source)
  132. self.hift_cache_dict[uuid] = {'source': tts_source[:, :, -self.source_cache_len:], 'mel': tts_mel[:, :, -self.mel_cache_len:]}
  133. tts_speech = tts_speech[:, :-self.source_cache_len]
  134. else:
  135. tts_speech, tts_source = self.hift.inference(mel=tts_mel, cache_source=hift_cache_source)
  136. return tts_speech
  137. def inference(self, text, flow_embedding, llm_embedding=torch.zeros(0, 192),
  138. prompt_text=torch.zeros(1, 0, dtype=torch.int32),
  139. llm_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
  140. flow_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32),
  141. prompt_speech_feat=torch.zeros(1, 0, 80), stream=False, **kwargs):
  142. # this_uuid is used to track variables related to this inference thread
  143. this_uuid = str(uuid.uuid1())
  144. with self.lock:
  145. self.tts_speech_token_dict[this_uuid], self.llm_end_dict[this_uuid], self.mel_overlap_dict[this_uuid], self.hift_cache_dict[this_uuid] = [], False, None, None
  146. p = threading.Thread(target=self.llm_job, args=(text, prompt_text, llm_prompt_speech_token, llm_embedding, this_uuid))
  147. p.start()
  148. if stream is True:
  149. token_hop_len = self.token_min_hop_len
  150. while True:
  151. time.sleep(0.1)
  152. if len(self.tts_speech_token_dict[this_uuid]) >= token_hop_len + self.token_overlap_len:
  153. this_tts_speech_token = torch.concat(self.tts_speech_token_dict[this_uuid][:token_hop_len + self.token_overlap_len], dim=1)
  154. with self.flow_hift_context:
  155. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  156. prompt_token=flow_prompt_speech_token,
  157. prompt_feat=prompt_speech_feat,
  158. embedding=flow_embedding,
  159. uuid=this_uuid,
  160. finalize=False)
  161. yield {'tts_speech': this_tts_speech.cpu()}
  162. with self.lock:
  163. self.tts_speech_token_dict[this_uuid] = self.tts_speech_token_dict[this_uuid][token_hop_len:]
  164. # increase token_hop_len for better speech quality
  165. token_hop_len = min(self.token_max_hop_len, int(token_hop_len * self.stream_scale_factor))
  166. 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:
  167. break
  168. p.join()
  169. # deal with remain tokens, make sure inference remain token len equals token_hop_len when cache_speech is not None
  170. this_tts_speech_token = torch.concat(self.tts_speech_token_dict[this_uuid], dim=1)
  171. with self.flow_hift_context:
  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.concat(self.tts_speech_token_dict[this_uuid], dim=1)
  183. with self.flow_hift_context:
  184. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  185. prompt_token=flow_prompt_speech_token,
  186. prompt_feat=prompt_speech_feat,
  187. embedding=flow_embedding,
  188. uuid=this_uuid,
  189. finalize=True)
  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. torch.cuda.synchronize()