llm.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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, Union
  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. length_normalized_loss: bool = True,
  33. lsm_weight: float = 0.0,
  34. spk_embed_dim: int = 192,
  35. ):
  36. super().__init__()
  37. self.llm_input_size = llm_input_size
  38. self.speech_token_size = speech_token_size
  39. # 1. build text token inputs related modules
  40. self.text_embedding = torch.nn.Embedding(text_token_size, text_encoder_input_size)
  41. self.text_encoder = text_encoder
  42. self.text_encoder_affine_layer = nn.Linear(
  43. self.text_encoder.output_size(),
  44. llm_input_size
  45. )
  46. # 2. build speech token language model related modules
  47. self.sos_eos = 0
  48. self.task_id = 1
  49. self.llm_embedding = torch.nn.Embedding(2, llm_input_size)
  50. self.llm = llm
  51. self.llm_decoder = nn.Linear(llm_output_size, speech_token_size + 1)
  52. self.criterion_ce = LabelSmoothingLoss(
  53. size=speech_token_size + 1,
  54. padding_idx=IGNORE_ID,
  55. smoothing=lsm_weight,
  56. normalize_length=length_normalized_loss,
  57. )
  58. # 3. [Optional] build speech token related modules
  59. self.speech_embedding = torch.nn.Embedding(speech_token_size, llm_input_size)
  60. self.spk_embed_affine_layer = torch.nn.Linear(spk_embed_dim, llm_input_size)
  61. def encode(
  62. self,
  63. text: torch.Tensor,
  64. text_lengths: torch.Tensor,
  65. ):
  66. encoder_out, encoder_mask = self.text_encoder(text, text_lengths, decoding_chunk_size=1, num_decoding_left_chunks=-1)
  67. encoder_out_lens = encoder_mask.squeeze(1).sum(1)
  68. encoder_out = self.text_encoder_affine_layer(encoder_out)
  69. return encoder_out, encoder_out_lens
  70. def pad_unpad_sequence(self, sos_eos_emb, embedding, text_token, text_token_len, task_id_emb, speech_token, speech_token_len):
  71. text_token = unpad_sequence(text_token, text_token_len.cpu(), batch_first=True)
  72. speech_token = unpad_sequence(speech_token, speech_token_len.cpu(), batch_first=True)
  73. 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))]
  74. lm_input_len = torch.tensor([i.size(0) for i in lm_input], dtype=torch.int32)
  75. lm_input = pad_sequence(lm_input, batch_first=True, padding_value=IGNORE_ID)
  76. return lm_input, lm_input_len
  77. def forward(
  78. self,
  79. batch: dict,
  80. device: torch.device,
  81. ) -> Dict[str, Optional[torch.Tensor]]:
  82. """
  83. Args:
  84. text: (B, L, D)
  85. text_lengths: (B,)
  86. audio: (B, T, N) or (B, T)
  87. audio_lengths: (B,)
  88. """
  89. text_token = batch['text_token'].to(device)
  90. text_token_len = batch['text_token_len'].to(device)
  91. speech_token = batch['speech_token'].to(device)
  92. speech_token_len = batch['speech_token_len'].to(device)
  93. embedding = batch['utt_embedding'].to(device)
  94. # 1. prepare llm_target
  95. 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))]
  96. lm_target = pad_sequence(lm_target, batch_first=True, padding_value=IGNORE_ID).to(device)
  97. # 1. encode text_token
  98. text_token = self.text_embedding(text_token)
  99. text_token, text_token_len = self.encode(text_token, text_token_len)
  100. # 2. embedding projection
  101. embedding = F.normalize(embedding, dim=1)
  102. embedding = self.spk_embed_affine_layer(embedding)
  103. embedding = embedding.unsqueeze(1)
  104. # 3. eos and task_id
  105. sos_eos_emb = self.llm_embedding.weight[self.sos_eos].reshape(1, 1, -1)
  106. task_id_emb = self.llm_embedding.weight[self.task_id].reshape(1, 1, -1)
  107. # 4. encode speech_token
  108. speech_token = self.speech_embedding(speech_token)
  109. # 5. unpad and pad
  110. 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)
  111. # 6. run lm forward
  112. lm_output, lm_output_mask = self.llm(lm_input, lm_input_len.to(device))
  113. logits = self.llm_decoder(lm_output)
  114. loss = self.criterion_ce(logits, lm_target)
  115. acc = th_accuracy(logits.view(-1, self.speech_token_size + 1), lm_target, ignore_label=IGNORE_ID)
  116. return {'loss': loss, 'acc': acc}
  117. def sampling_ids(
  118. self,
  119. weighted_scores: torch.Tensor,
  120. sampling: Union[bool, int, float] = True,
  121. beam_size: int = 1,
  122. ignore_eos: bool = True,
  123. ):
  124. while True:
  125. prob, indices = weighted_scores.softmax(dim=-1).topk(sampling)
  126. top_ids = prob.multinomial(beam_size, replacement=True)
  127. top_ids = indices[top_ids]
  128. if (not ignore_eos) or (self.speech_token_size not in top_ids):
  129. break
  130. return top_ids
  131. @torch.inference_mode()
  132. def inference(
  133. self,
  134. text: torch.Tensor,
  135. text_len: torch.Tensor,
  136. prompt_text: torch.Tensor,
  137. prompt_text_len: torch.Tensor,
  138. prompt_speech_token: torch.Tensor,
  139. prompt_speech_token_len: torch.Tensor,
  140. embedding: torch.Tensor,
  141. beam_size: int = 1,
  142. sampling: int = 25,
  143. max_token_text_ratio: float = 20,
  144. min_token_text_ratio: float = 2,
  145. ) -> torch.Tensor:
  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).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).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), sampling, beam_size, ignore_eos=True if i < min_len else False).item()
  179. if top_ids == self.speech_token_size:
  180. break
  181. out_tokens.append(top_ids)
  182. offset += lm_input.size(1)
  183. lm_input = self.speech_embedding.weight[top_ids].reshape(1, 1, -1)
  184. return torch.tensor([out_tokens], dtype=torch.int64, device=device)