flow_matching.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. import torch
  15. import torch.nn.functional as F
  16. from matcha.models.components.flow_matching import BASECFM
  17. import onnxruntime as ort
  18. import numpy as np
  19. class ConditionalCFM(BASECFM):
  20. def __init__(self, in_channels, cfm_params, n_spks=1, spk_emb_dim=64, estimator: torch.nn.Module = None):
  21. super().__init__(
  22. n_feats=in_channels,
  23. cfm_params=cfm_params,
  24. n_spks=n_spks,
  25. spk_emb_dim=spk_emb_dim,
  26. )
  27. self.t_scheduler = cfm_params.t_scheduler
  28. self.training_cfg_rate = cfm_params.training_cfg_rate
  29. self.inference_cfg_rate = cfm_params.inference_cfg_rate
  30. in_channels = in_channels + (spk_emb_dim if n_spks > 0 else 0)
  31. # Just change the architecture of the estimator here
  32. self.estimator = estimator
  33. self.estimator_context = None # for tensorrt
  34. self.session = None # for onnx
  35. @torch.inference_mode()
  36. def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None):
  37. """Forward diffusion
  38. Args:
  39. mu (torch.Tensor): output of encoder
  40. shape: (batch_size, n_feats, mel_timesteps)
  41. mask (torch.Tensor): output_mask
  42. shape: (batch_size, 1, mel_timesteps)
  43. n_timesteps (int): number of diffusion steps
  44. temperature (float, optional): temperature for scaling noise. Defaults to 1.0.
  45. spks (torch.Tensor, optional): speaker ids. Defaults to None.
  46. shape: (batch_size, spk_emb_dim)
  47. cond: Not used but kept for future purposes
  48. Returns:
  49. sample: generated mel-spectrogram
  50. shape: (batch_size, n_feats, mel_timesteps)
  51. """
  52. z = torch.randn_like(mu) * temperature
  53. t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
  54. if self.t_scheduler == 'cosine':
  55. t_span = 1 - torch.cos(t_span * 0.5 * torch.pi)
  56. return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond)
  57. def solve_euler(self, x, t_span, mu, mask, spks, cond):
  58. """
  59. Fixed euler solver for ODEs.
  60. Args:
  61. x (torch.Tensor): random noise
  62. t_span (torch.Tensor): n_timesteps interpolated
  63. shape: (n_timesteps + 1,)
  64. mu (torch.Tensor): output of encoder
  65. shape: (batch_size, n_feats, mel_timesteps)
  66. mask (torch.Tensor): output_mask
  67. shape: (batch_size, 1, mel_timesteps)
  68. spks (torch.Tensor, optional): speaker ids. Defaults to None.
  69. shape: (batch_size, spk_emb_dim)
  70. cond: Not used but kept for future purposes
  71. """
  72. t, _, dt = t_span[0], t_span[-1], t_span[1] - t_span[0]
  73. t = t.unsqueeze(dim=0)
  74. # I am storing this because I can later plot it by putting a debugger here and saving it to a file
  75. # Or in future might add like a return_all_steps flag
  76. sol = []
  77. for step in range(1, len(t_span)):
  78. dphi_dt = self.estimator(x, mask, mu, t, spks, cond)
  79. # Classifier-Free Guidance inference introduced in VoiceBox
  80. if self.inference_cfg_rate > 0:
  81. cfg_dphi_dt = self.estimator(
  82. x, mask,
  83. torch.zeros_like(mu), t,
  84. torch.zeros_like(spks) if spks is not None else None,
  85. torch.zeros_like(cond)
  86. )
  87. dphi_dt = ((1.0 + self.inference_cfg_rate) * dphi_dt -
  88. self.inference_cfg_rate * cfg_dphi_dt)
  89. x = x + dt * dphi_dt
  90. t = t + dt
  91. sol.append(x)
  92. if step < len(t_span) - 1:
  93. dt = t_span[step + 1] - t
  94. return sol[-1]
  95. def forward_estimator(self, x, mask, mu, t, spks, cond):
  96. if self.estimator is not None:
  97. return self.estimator.forward(x, mask, mu, t, spks, cond)
  98. # elif self.estimator_context is not None:
  99. # assert self.training is False, 'tensorrt cannot be used in training'
  100. # bs = x.shape[0]
  101. # hs = x.shape[1]
  102. # seq_len = x.shape[2]
  103. # # assert bs == 1 and hs == 80
  104. # ret = torch.empty_like(x)
  105. # self.estimator_context.set_input_shape("x", x.shape)
  106. # self.estimator_context.set_input_shape("mask", mask.shape)
  107. # self.estimator_context.set_input_shape("mu", mu.shape)
  108. # self.estimator_context.set_input_shape("t", t.shape)
  109. # self.estimator_context.set_input_shape("spks", spks.shape)
  110. # self.estimator_context.set_input_shape("cond", cond.shape)
  111. # # Create a list of bindings
  112. # bindings = [int(x.data_ptr()), int(mask.data_ptr()), int(mu.data_ptr()), int(t.data_ptr()), int(spks.data_ptr()), int(cond.data_ptr()), int(ret.data_ptr())]
  113. # # Execute the inference
  114. # self.estimator_context.execute_v2(bindings=bindings)
  115. # return ret
  116. else:
  117. x_np = x.cpu().numpy()
  118. mask_np = mask.cpu().numpy()
  119. mu_np = mu.cpu().numpy()
  120. t_np = t.cpu().numpy()
  121. spks_np = spks.cpu().numpy()
  122. cond_np = cond.cpu().numpy()
  123. ort_inputs = {
  124. 'x': x_np,
  125. 'mask': mask_np,
  126. 'mu': mu_np,
  127. 't': t_np,
  128. 'spks': spks_np,
  129. 'cond': cond_np
  130. }
  131. output = self.session.run(None, ort_inputs)[0]
  132. return torch.tensor(output, dtype=x.dtype, device=x.device)
  133. def compute_loss(self, x1, mask, mu, spks=None, cond=None):
  134. """Computes diffusion loss
  135. Args:
  136. x1 (torch.Tensor): Target
  137. shape: (batch_size, n_feats, mel_timesteps)
  138. mask (torch.Tensor): target mask
  139. shape: (batch_size, 1, mel_timesteps)
  140. mu (torch.Tensor): output of encoder
  141. shape: (batch_size, n_feats, mel_timesteps)
  142. spks (torch.Tensor, optional): speaker embedding. Defaults to None.
  143. shape: (batch_size, spk_emb_dim)
  144. Returns:
  145. loss: conditional flow matching loss
  146. y: conditional flow
  147. shape: (batch_size, n_feats, mel_timesteps)
  148. """
  149. b, _, t = mu.shape
  150. # random timestep
  151. t = torch.rand([b, 1, 1], device=mu.device, dtype=mu.dtype)
  152. if self.t_scheduler == 'cosine':
  153. t = 1 - torch.cos(t * 0.5 * torch.pi)
  154. # sample noise p(x_0)
  155. z = torch.randn_like(x1)
  156. y = (1 - (1 - self.sigma_min) * t) * z + t * x1
  157. u = x1 - (1 - self.sigma_min) * z
  158. # during training, we randomly drop condition to trade off mode coverage and sample fidelity
  159. if self.training_cfg_rate > 0:
  160. cfg_mask = torch.rand(b, device=x1.device) > self.training_cfg_rate
  161. mu = mu * cfg_mask.view(-1, 1, 1)
  162. spks = spks * cfg_mask.view(-1, 1)
  163. cond = cond * cfg_mask.view(-1, 1, 1)
  164. pred = self.estimator(y, mask, mu, t.squeeze(), spks, cond)
  165. loss = F.mse_loss(pred * mask, u * mask, reduction="sum") / (torch.sum(mask) * u.shape[1])
  166. return loss, y