model.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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 contextlib import nullcontext
  19. import uuid
  20. from cosyvoice.utils.common import fade_in_out
  21. class CosyVoiceModel:
  22. def __init__(self,
  23. llm: torch.nn.Module,
  24. flow: torch.nn.Module,
  25. hift: torch.nn.Module):
  26. self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  27. self.llm = llm
  28. self.flow = flow
  29. self.hift = hift
  30. self.token_min_hop_len = 100
  31. self.token_max_hop_len = 400
  32. self.token_overlap_len = 20
  33. self.speech_overlap_len = 34 * 256
  34. self.window = np.hamming(2 * self.speech_overlap_len)
  35. self.stream_scale_factor = 1
  36. assert self.stream_scale_factor >= 1, 'stream_scale_factor should be greater than 1, change it according to your actual rtf'
  37. self.llm_context = torch.cuda.stream(torch.cuda.Stream(self.device)) if torch.cuda.is_available() else nullcontext()
  38. self.flow_hift_context = torch.cuda.stream(torch.cuda.Stream(self.device)) if torch.cuda.is_available() else nullcontext()
  39. self.lock = threading.Lock()
  40. # dict used to store session related variable
  41. self.tts_speech_token = {}
  42. self.llm_end = {}
  43. def load(self, llm_model, flow_model, hift_model):
  44. self.llm.load_state_dict(torch.load(llm_model, map_location=self.device))
  45. self.llm.to(self.device).eval()
  46. self.llm.half()
  47. self.flow.load_state_dict(torch.load(flow_model, map_location=self.device))
  48. self.flow.to(self.device).eval()
  49. self.hift.load_state_dict(torch.load(hift_model, map_location=self.device))
  50. self.hift.to(self.device).eval()
  51. def load_script(self, llm_text_encoder_model, llm_llm_model):
  52. llm_text_encoder = torch.jit.load(llm_text_encoder_model)
  53. self.llm.text_encoder = llm_text_encoder
  54. llm_llm = torch.jit.load(llm_llm_model)
  55. self.llm.llm = llm_llm
  56. def llm_job(self, text, text_len, prompt_text, prompt_text_len, llm_prompt_speech_token, llm_prompt_speech_token_len, llm_embedding, this_uuid):
  57. with self.llm_context:
  58. for i in self.llm.inference(text=text.to(self.device),
  59. text_len=text_len.to(self.device),
  60. prompt_text=prompt_text.to(self.device),
  61. prompt_text_len=prompt_text_len.to(self.device),
  62. prompt_speech_token=llm_prompt_speech_token.to(self.device),
  63. prompt_speech_token_len=llm_prompt_speech_token_len.to(self.device),
  64. embedding=llm_embedding.to(self.device).half(),
  65. sampling=25,
  66. max_token_text_ratio=30,
  67. min_token_text_ratio=3):
  68. self.tts_speech_token[this_uuid].append(i)
  69. self.llm_end[this_uuid] = True
  70. def token2wav(self, token, prompt_token, prompt_token_len, prompt_feat, prompt_feat_len, embedding):
  71. with self.flow_hift_context:
  72. tts_mel = self.flow.inference(token=token.to(self.device),
  73. token_len=torch.tensor([token.size(1)], dtype=torch.int32).to(self.device),
  74. prompt_token=prompt_token.to(self.device),
  75. prompt_token_len=prompt_token_len.to(self.device),
  76. prompt_feat=prompt_feat.to(self.device),
  77. prompt_feat_len=prompt_feat_len.to(self.device),
  78. embedding=embedding.to(self.device))
  79. tts_speech = self.hift.inference(mel=tts_mel).cpu()
  80. return tts_speech
  81. def inference(self, text, text_len, flow_embedding, llm_embedding=torch.zeros(0, 192),
  82. prompt_text=torch.zeros(1, 0, dtype=torch.int32), prompt_text_len=torch.zeros(1, dtype=torch.int32),
  83. llm_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32), llm_prompt_speech_token_len=torch.zeros(1, dtype=torch.int32),
  84. flow_prompt_speech_token=torch.zeros(1, 0, dtype=torch.int32), flow_prompt_speech_token_len=torch.zeros(1, dtype=torch.int32),
  85. prompt_speech_feat=torch.zeros(1, 0, 80), prompt_speech_feat_len=torch.zeros(1, dtype=torch.int32), stream=False):
  86. # this_uuid is used to track variables related to this inference thread
  87. this_uuid = str(uuid.uuid1())
  88. with self.lock:
  89. self.tts_speech_token[this_uuid], self.llm_end[this_uuid] = [], False
  90. p = threading.Thread(target=self.llm_job, args=(text.to(self.device), text_len.to(self.device), prompt_text.to(self.device), prompt_text_len.to(self.device),
  91. llm_prompt_speech_token.to(self.device), llm_prompt_speech_token_len.to(self.device), llm_embedding.to(self.device), this_uuid))
  92. p.start()
  93. if stream is True:
  94. cache_speech, cache_token, token_hop_len = None, None, self.token_min_hop_len
  95. while True:
  96. time.sleep(0.1)
  97. if len(self.tts_speech_token[this_uuid]) >= token_hop_len + self.token_overlap_len:
  98. this_tts_speech_token = torch.concat(self.tts_speech_token[this_uuid][:token_hop_len + self.token_overlap_len], dim=1)
  99. with self.flow_hift_context:
  100. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  101. prompt_token=flow_prompt_speech_token.to(self.device),
  102. prompt_token_len=flow_prompt_speech_token_len.to(self.device),
  103. prompt_feat=prompt_speech_feat.to(self.device),
  104. prompt_feat_len=prompt_speech_feat_len.to(self.device),
  105. embedding=flow_embedding.to(self.device))
  106. # fade in/out if necessary
  107. if cache_speech is not None:
  108. this_tts_speech = fade_in_out(this_tts_speech, cache_speech, self.window)
  109. yield {'tts_speech': this_tts_speech[:, :-self.speech_overlap_len]}
  110. cache_speech = this_tts_speech[:, -self.speech_overlap_len:]
  111. cache_token = self.tts_speech_token[this_uuid][:token_hop_len]
  112. with self.lock:
  113. self.tts_speech_token[this_uuid] = self.tts_speech_token[this_uuid][token_hop_len:]
  114. # increase token_hop_len for better speech quality
  115. token_hop_len = min(self.token_max_hop_len, int(token_hop_len * self.stream_scale_factor))
  116. if self.llm_end[this_uuid] is True and len(self.tts_speech_token[this_uuid]) < token_hop_len + self.token_overlap_len:
  117. break
  118. p.join()
  119. # deal with remain tokens, make sure inference remain token len equals token_hop_len when cache_speech is not None
  120. this_tts_speech_token = torch.concat(self.tts_speech_token[this_uuid], dim=1)
  121. if this_tts_speech_token.shape[1] < self.token_min_hop_len + self.token_overlap_len and cache_token is not None:
  122. cache_token_len = self.token_min_hop_len + self.token_overlap_len - this_tts_speech_token.shape[1]
  123. this_tts_speech_token = torch.concat([torch.concat(cache_token[-cache_token_len:], dim=1), this_tts_speech_token], dim=1)
  124. else:
  125. cache_token_len = 0
  126. with self.flow_hift_context:
  127. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  128. prompt_token=flow_prompt_speech_token.to(self.device),
  129. prompt_token_len=flow_prompt_speech_token_len.to(self.device),
  130. prompt_feat=prompt_speech_feat.to(self.device),
  131. prompt_feat_len=prompt_speech_feat_len.to(self.device),
  132. embedding=flow_embedding.to(self.device))
  133. this_tts_speech = this_tts_speech[:, int(cache_token_len / this_tts_speech_token.shape[1] * this_tts_speech.shape[1]):]
  134. if cache_speech is not None:
  135. this_tts_speech = fade_in_out(this_tts_speech, cache_speech, self.window)
  136. yield {'tts_speech': this_tts_speech}
  137. else:
  138. # deal with all tokens
  139. p.join()
  140. this_tts_speech_token = torch.concat(self.tts_speech_token[this_uuid], dim=1)
  141. with self.flow_hift_context:
  142. this_tts_speech = self.token2wav(token=this_tts_speech_token,
  143. prompt_token=flow_prompt_speech_token.to(self.device),
  144. prompt_token_len=flow_prompt_speech_token_len.to(self.device),
  145. prompt_feat=prompt_speech_feat.to(self.device),
  146. prompt_feat_len=prompt_speech_feat_len.to(self.device),
  147. embedding=flow_embedding.to(self.device))
  148. yield {'tts_speech': this_tts_speech}
  149. with self.lock:
  150. self.tts_speech_token.pop(this_uuid)
  151. self.llm_end.pop(this_uuid)
  152. torch.cuda.synchronize()