llm.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du)
  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. from typing import Dict, Optional, Callable, List, Generator
  15. import torch
  16. from torch import nn
  17. import torch.nn.functional as F
  18. from torch.nn.utils.rnn import pad_sequence, unpad_sequence
  19. from cosyvoice.utils.common import IGNORE_ID
  20. from cosyvoice.transformer.label_smoothing_loss import LabelSmoothingLoss
  21. from cosyvoice.utils.common import th_accuracy
  22. class TransformerLM(torch.nn.Module):
  23. def __init__(
  24. self,
  25. text_encoder_input_size: int,
  26. llm_input_size: int,
  27. llm_output_size: int,
  28. text_token_size: int,
  29. speech_token_size: int,
  30. text_encoder: torch.nn.Module,
  31. llm: torch.nn.Module,
  32. sampling: Callable,
  33. length_normalized_loss: bool = True,
  34. lsm_weight: float = 0.0,
  35. spk_embed_dim: int = 192,
  36. ):
  37. super().__init__()
  38. self.llm_input_size = llm_input_size
  39. self.speech_token_size = speech_token_size
  40. # 1. build text token inputs related modules
  41. self.text_embedding = torch.nn.Embedding(text_token_size, text_encoder_input_size)
  42. self.text_encoder = text_encoder
  43. self.text_encoder_affine_layer = nn.Linear(
  44. self.text_encoder.output_size(),
  45. llm_input_size
  46. )
  47. # 2. build speech token language model related modules
  48. self.sos_eos = 0
  49. self.task_id = 1
  50. self.llm_embedding = torch.nn.Embedding(2, llm_input_size)
  51. self.llm = llm
  52. self.llm_decoder = nn.Linear(llm_output_size, speech_token_size + 1)
  53. self.criterion_ce = LabelSmoothingLoss(
  54. size=speech_token_size + 1,
  55. padding_idx=IGNORE_ID,
  56. smoothing=lsm_weight,
  57. normalize_length=length_normalized_loss,
  58. )
  59. # 3. [Optional] build speech token related modules
  60. self.speech_embedding = torch.nn.Embedding(speech_token_size, llm_input_size)
  61. self.spk_embed_affine_layer = torch.nn.Linear(spk_embed_dim, llm_input_size)
  62. # 4. sampling method
  63. self.sampling = sampling
  64. def encode(
  65. self,
  66. text: torch.Tensor,
  67. text_lengths: torch.Tensor,
  68. ):
  69. encoder_out, encoder_mask = self.text_encoder(text, text_lengths, decoding_chunk_size=1, num_decoding_left_chunks=-1)
  70. encoder_out_lens = encoder_mask.squeeze(1).sum(1)
  71. encoder_out = self.text_encoder_affine_layer(encoder_out)
  72. return encoder_out, encoder_out_lens
  73. def pad_unpad_sequence(self, sos_eos_emb, embedding, text_token, text_token_len, task_id_emb, speech_token, speech_token_len):
  74. text_token = unpad_sequence(text_token, text_token_len.cpu(), batch_first=True)
  75. speech_token = unpad_sequence(speech_token, speech_token_len.cpu(), batch_first=True)
  76. lm_input = [torch.concat([sos_eos_emb.squeeze(dim=0), embedding[i], text_token[i], task_id_emb.squeeze(dim=0), speech_token[i]], dim=0)
  77. for i in range(len(text_token))]
  78. lm_input_len = torch.tensor([i.size(0) for i in lm_input], dtype=torch.int32)
  79. lm_input = pad_sequence(lm_input, batch_first=True, padding_value=IGNORE_ID)
  80. return lm_input, lm_input_len
  81. def forward(
  82. self,
  83. batch: dict,
  84. device: torch.device,
  85. ) -> Dict[str, Optional[torch.Tensor]]:
  86. """
  87. Args:
  88. text: (B, L, D)
  89. text_lengths: (B,)
  90. audio: (B, T, N) or (B, T)
  91. audio_lengths: (B,)
  92. """
  93. text_token = batch['text_token'].to(device)
  94. text_token_len = batch['text_token_len'].to(device)
  95. speech_token = batch['speech_token'].to(device)
  96. speech_token_len = batch['speech_token_len'].to(device)
  97. embedding = batch['embedding'].to(device)
  98. # 1. prepare llm_target
  99. lm_target = [torch.tensor([IGNORE_ID] * (2 + text_token_len[i]) + speech_token[i, :speech_token_len[i]].tolist() +
  100. [self.speech_token_size]) for i in range(text_token.size(0))]
  101. lm_target = pad_sequence(lm_target, batch_first=True, padding_value=IGNORE_ID).to(device)
  102. # 1. encode text_token
  103. text_token = self.text_embedding(text_token)
  104. text_token, text_token_len = self.encode(text_token, text_token_len)
  105. # 2. embedding projection
  106. embedding = F.normalize(embedding, dim=1)
  107. embedding = self.spk_embed_affine_layer(embedding)
  108. embedding = embedding.unsqueeze(1)
  109. # 3. eos and task_id
  110. sos_eos_emb = self.llm_embedding.weight[self.sos_eos].reshape(1, 1, -1)
  111. task_id_emb = self.llm_embedding.weight[self.task_id].reshape(1, 1, -1)
  112. # 4. encode speech_token
  113. speech_token = self.speech_embedding(speech_token)
  114. # 5. unpad and pad
  115. lm_input, lm_input_len = self.pad_unpad_sequence(sos_eos_emb, embedding, text_token, text_token_len,
  116. task_id_emb, speech_token, speech_token_len)
  117. # 6. run lm forward
  118. lm_output, lm_output_mask = self.llm(lm_input, lm_input_len.to(device))
  119. logits = self.llm_decoder(lm_output)
  120. loss = self.criterion_ce(logits, lm_target)
  121. acc = th_accuracy(logits.view(-1, self.speech_token_size + 1), lm_target, ignore_label=IGNORE_ID)
  122. return {'loss': loss, 'acc': acc}
  123. def sampling_ids(
  124. self,
  125. weighted_scores: torch.Tensor,
  126. decoded_tokens: List,
  127. sampling: int,
  128. ignore_eos: bool = True,
  129. ):
  130. while True:
  131. top_ids = self.sampling(weighted_scores, decoded_tokens, sampling)
  132. if (not ignore_eos) or (self.speech_token_size not in top_ids):
  133. break
  134. return top_ids
  135. @torch.inference_mode()
  136. def inference(
  137. self,
  138. text: torch.Tensor,
  139. text_len: torch.Tensor,
  140. prompt_text: torch.Tensor,
  141. prompt_text_len: torch.Tensor,
  142. prompt_speech_token: torch.Tensor,
  143. prompt_speech_token_len: torch.Tensor,
  144. embedding: torch.Tensor,
  145. sampling: int = 25,
  146. max_token_text_ratio: float = 20,
  147. min_token_text_ratio: float = 2,
  148. ) -> Generator[torch.Tensor, None, None]:
  149. device = text.device
  150. text = torch.concat([prompt_text, text], dim=1)
  151. text_len += prompt_text_len
  152. text = self.text_embedding(text)
  153. # 1. encode text
  154. text, text_len = self.encode(text, text_len)
  155. # 2. encode embedding
  156. if embedding.shape[0] != 0:
  157. embedding = F.normalize(embedding, dim=1)
  158. embedding = self.spk_embed_affine_layer(embedding)
  159. embedding = embedding.unsqueeze(dim=1)
  160. else:
  161. embedding = torch.zeros(1, 0, self.llm_input_size, dtype=text.dtype).to(device)
  162. # 3. concat llm_input
  163. sos_eos_emb = self.llm_embedding.weight[self.sos_eos].reshape(1, 1, -1)
  164. task_id_emb = self.llm_embedding.weight[self.task_id].reshape(1, 1, -1)
  165. if prompt_speech_token_len != 0:
  166. prompt_speech_token_emb = self.speech_embedding(prompt_speech_token)
  167. else:
  168. prompt_speech_token_emb = torch.zeros(1, 0, self.llm_input_size, dtype=text.dtype).to(device)
  169. lm_input = torch.concat([sos_eos_emb, embedding, text, task_id_emb, prompt_speech_token_emb], dim=1)
  170. # 4. cal min/max_length
  171. min_len = int((text_len - prompt_text_len) * min_token_text_ratio)
  172. max_len = int((text_len - prompt_text_len) * max_token_text_ratio)
  173. # 5. step by step decode
  174. out_tokens = []
  175. offset = 0
  176. att_cache, cnn_cache = torch.zeros((0, 0, 0, 0), device=lm_input.device), torch.zeros((0, 0, 0, 0), device=lm_input.device)
  177. for i in range(max_len):
  178. y_pred, att_cache, cnn_cache = self.llm.forward_chunk(lm_input, offset=0, required_cache_size=-1,
  179. att_cache=att_cache, cnn_cache=cnn_cache,
  180. att_mask=torch.tril(torch.ones((1, lm_input.shape[1], lm_input.shape[1]),
  181. device=lm_input.device)).to(torch.bool))
  182. logp = self.llm_decoder(y_pred[:, -1]).log_softmax(dim=-1)
  183. top_ids = self.sampling_ids(logp.squeeze(dim=0), out_tokens, sampling, ignore_eos=True if i < min_len else False).item()
  184. if top_ids == self.speech_token_size:
  185. break
  186. # in stream mode, yield token one by one
  187. yield torch.tensor([[top_ids]], dtype=torch.int64, device=device)
  188. out_tokens.append(top_ids)
  189. offset += lm_input.size(1)
  190. lm_input = self.speech_embedding.weight[top_ids].reshape(1, 1, -1)