llm.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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) for i in range(len(text_token))]
  77. lm_input_len = torch.tensor([i.size(0) for i in lm_input], dtype=torch.int32)
  78. lm_input = pad_sequence(lm_input, batch_first=True, padding_value=IGNORE_ID)
  79. return lm_input, lm_input_len
  80. def forward(
  81. self,
  82. batch: dict,
  83. device: torch.device,
  84. ) -> Dict[str, Optional[torch.Tensor]]:
  85. """
  86. Args:
  87. text: (B, L, D)
  88. text_lengths: (B,)
  89. audio: (B, T, N) or (B, T)
  90. audio_lengths: (B,)
  91. """
  92. text_token = batch['text_token'].to(device)
  93. text_token_len = batch['text_token_len'].to(device)
  94. speech_token = batch['speech_token'].to(device)
  95. speech_token_len = batch['speech_token_len'].to(device)
  96. embedding = batch['embedding'].to(device)
  97. # 1. prepare llm_target
  98. lm_target = [torch.tensor([IGNORE_ID] * (2 + text_token_len[i]) + speech_token[i, :speech_token_len[i]].tolist() + [self.speech_token_size]) for i in range(text_token.size(0))]
  99. lm_target = pad_sequence(lm_target, batch_first=True, padding_value=IGNORE_ID).to(device)
  100. # 1. encode text_token
  101. text_token = self.text_embedding(text_token)
  102. text_token, text_token_len = self.encode(text_token, text_token_len)
  103. # 2. embedding projection
  104. embedding = F.normalize(embedding, dim=1)
  105. embedding = self.spk_embed_affine_layer(embedding)
  106. embedding = embedding.unsqueeze(1)
  107. # 3. eos and task_id
  108. sos_eos_emb = self.llm_embedding.weight[self.sos_eos].reshape(1, 1, -1)
  109. task_id_emb = self.llm_embedding.weight[self.task_id].reshape(1, 1, -1)
  110. # 4. encode speech_token
  111. speech_token = self.speech_embedding(speech_token)
  112. # 5. unpad and pad
  113. lm_input, lm_input_len = self.pad_unpad_sequence(sos_eos_emb, embedding, text_token, text_token_len, task_id_emb, speech_token, speech_token_len)
  114. # 6. run lm forward
  115. lm_output, lm_output_mask = self.llm(lm_input, lm_input_len.to(device))
  116. logits = self.llm_decoder(lm_output)
  117. loss = self.criterion_ce(logits, lm_target)
  118. acc = th_accuracy(logits.view(-1, self.speech_token_size + 1), lm_target, ignore_label=IGNORE_ID)
  119. return {'loss': loss, 'acc': acc}
  120. def sampling_ids(
  121. self,
  122. weighted_scores: torch.Tensor,
  123. decoded_tokens: List,
  124. sampling: int,
  125. ignore_eos: bool = True,
  126. ):
  127. while True:
  128. top_ids = self.sampling(weighted_scores, decoded_tokens, sampling)
  129. if (not ignore_eos) or (self.speech_token_size not in top_ids):
  130. break
  131. return top_ids
  132. @torch.inference_mode()
  133. def inference(
  134. self,
  135. text: torch.Tensor,
  136. text_len: torch.Tensor,
  137. prompt_text: torch.Tensor,
  138. prompt_text_len: torch.Tensor,
  139. prompt_speech_token: torch.Tensor,
  140. prompt_speech_token_len: torch.Tensor,
  141. embedding: torch.Tensor,
  142. sampling: int = 25,
  143. max_token_text_ratio: float = 20,
  144. min_token_text_ratio: float = 2,
  145. ) -> Generator[torch.Tensor, None, None]:
  146. device = text.device
  147. text = torch.concat([prompt_text, text], dim=1)
  148. text_len += prompt_text_len
  149. text = self.text_embedding(text)
  150. # 1. encode text
  151. text, text_len = self.encode(text, text_len)
  152. # 2. encode embedding
  153. if embedding.shape[0] != 0:
  154. embedding = F.normalize(embedding, dim=1)
  155. embedding = self.spk_embed_affine_layer(embedding)
  156. embedding = embedding.unsqueeze(dim=1)
  157. else:
  158. embedding = torch.zeros(1, 0, self.llm_input_size, dtype=text.dtype).to(device)
  159. # 3. concat llm_input
  160. sos_eos_emb = self.llm_embedding.weight[self.sos_eos].reshape(1, 1, -1)
  161. task_id_emb = self.llm_embedding.weight[self.task_id].reshape(1, 1, -1)
  162. if prompt_speech_token_len != 0:
  163. prompt_speech_token_emb = self.speech_embedding(prompt_speech_token)
  164. else:
  165. prompt_speech_token_emb = torch.zeros(1, 0, self.llm_input_size, dtype=text.dtype).to(device)
  166. lm_input = torch.concat([sos_eos_emb, embedding, text, task_id_emb, prompt_speech_token_emb], dim=1)
  167. # 4. cal min/max_length
  168. min_len = int((text_len - prompt_text_len) * min_token_text_ratio)
  169. max_len = int((text_len - prompt_text_len) * max_token_text_ratio)
  170. # 5. step by step decode
  171. out_tokens = []
  172. offset = 0
  173. att_cache, cnn_cache = torch.zeros((0, 0, 0, 0), device=lm_input.device), torch.zeros((0, 0, 0, 0), device=lm_input.device)
  174. for i in range(max_len):
  175. y_pred, att_cache, cnn_cache = self.llm.forward_chunk(lm_input, offset=0, required_cache_size=-1, att_cache=att_cache, cnn_cache=cnn_cache,
  176. att_mask=torch.tril(torch.ones((1, lm_input.shape[1], lm_input.shape[1]), device=lm_input.device)).to(torch.bool))
  177. logp = self.llm_decoder(y_pred[:, -1]).log_softmax(dim=-1)
  178. top_ids = self.sampling_ids(logp.squeeze(dim=0), out_tokens, sampling, ignore_eos=True if i < min_len else False).item()
  179. if top_ids == self.speech_token_size:
  180. break
  181. # in stream mode, yield token one by one
  182. yield torch.tensor([[top_ids]], dtype=torch.int64, device=device)
  183. out_tokens.append(top_ids)
  184. offset += lm_input.size(1)
  185. lm_input = self.speech_embedding.weight[top_ids].reshape(1, 1, -1)