flow_matching.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. class ConditionalCFM(BASECFM):
  18. def __init__(self, in_channels, cfm_params, n_spks=1, spk_emb_dim=64, estimator: torch.nn.Module = None):
  19. super().__init__(
  20. n_feats=in_channels,
  21. cfm_params=cfm_params,
  22. n_spks=n_spks,
  23. spk_emb_dim=spk_emb_dim,
  24. )
  25. self.t_scheduler = cfm_params.t_scheduler
  26. self.training_cfg_rate = cfm_params.training_cfg_rate
  27. self.inference_cfg_rate = cfm_params.inference_cfg_rate
  28. in_channels = in_channels + (spk_emb_dim if n_spks > 0 else 0)
  29. # Just change the architecture of the estimator here
  30. self.estimator = estimator
  31. @torch.inference_mode()
  32. def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None, prompt_len=0, flow_cache=torch.zeros(1, 80, 0, 2)):
  33. """Forward diffusion
  34. Args:
  35. mu (torch.Tensor): output of encoder
  36. shape: (batch_size, n_feats, mel_timesteps)
  37. mask (torch.Tensor): output_mask
  38. shape: (batch_size, 1, mel_timesteps)
  39. n_timesteps (int): number of diffusion steps
  40. temperature (float, optional): temperature for scaling noise. Defaults to 1.0.
  41. spks (torch.Tensor, optional): speaker ids. Defaults to None.
  42. shape: (batch_size, spk_emb_dim)
  43. cond: Not used but kept for future purposes
  44. Returns:
  45. sample: generated mel-spectrogram
  46. shape: (batch_size, n_feats, mel_timesteps)
  47. """
  48. z = torch.randn_like(mu).to(mu.device).to(mu.dtype) * temperature
  49. cache_size = flow_cache.shape[2]
  50. # fix prompt and overlap part mu and z
  51. if cache_size != 0:
  52. z[:, :, :cache_size] = flow_cache[:, :, :, 0]
  53. mu[:, :, :cache_size] = flow_cache[:, :, :, 1]
  54. z_cache = torch.concat([z[:, :, :prompt_len], z[:, :, -34:]], dim=2)
  55. mu_cache = torch.concat([mu[:, :, :prompt_len], mu[:, :, -34:]], dim=2)
  56. flow_cache = torch.stack([z_cache, mu_cache], dim=-1)
  57. t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
  58. if self.t_scheduler == 'cosine':
  59. t_span = 1 - torch.cos(t_span * 0.5 * torch.pi)
  60. return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond), flow_cache
  61. def solve_euler(self, x, t_span, mu, mask, spks, cond):
  62. """
  63. Fixed euler solver for ODEs.
  64. Args:
  65. x (torch.Tensor): random noise
  66. t_span (torch.Tensor): n_timesteps interpolated
  67. shape: (n_timesteps + 1,)
  68. mu (torch.Tensor): output of encoder
  69. shape: (batch_size, n_feats, mel_timesteps)
  70. mask (torch.Tensor): output_mask
  71. shape: (batch_size, 1, mel_timesteps)
  72. spks (torch.Tensor, optional): speaker ids. Defaults to None.
  73. shape: (batch_size, spk_emb_dim)
  74. cond: Not used but kept for future purposes
  75. """
  76. t, _, dt = t_span[0], t_span[-1], t_span[1] - t_span[0]
  77. t = t.unsqueeze(dim=0)
  78. # I am storing this because I can later plot it by putting a debugger here and saving it to a file
  79. # Or in future might add like a return_all_steps flag
  80. sol = []
  81. # Do not use concat, it may cause memory format changed and trt infer with wrong results!
  82. x_in = torch.zeros([2, 80, x.size(2)], device=x.device, dtype=x.dtype)
  83. mask_in = torch.zeros([2, 1, x.size(2)], device=x.device, dtype=x.dtype)
  84. mu_in = torch.zeros([2, 80, x.size(2)], device=x.device, dtype=x.dtype)
  85. t_in = torch.zeros([2], device=x.device, dtype=x.dtype)
  86. spks_in = torch.zeros([2, 80], device=x.device, dtype=x.dtype)
  87. cond_in = torch.zeros([2, 80, x.size(2)], device=x.device, dtype=x.dtype)
  88. for step in range(1, len(t_span)):
  89. # Classifier-Free Guidance inference introduced in VoiceBox
  90. x_in[:] = x
  91. mask_in[:] = mask
  92. mu_in[0] = mu
  93. t_in[:] = t.unsqueeze(0)
  94. spks_in[0] = spks
  95. cond_in[0] = cond
  96. dphi_dt = self.forward_estimator(
  97. x_in, mask_in,
  98. mu_in, t_in,
  99. spks_in,
  100. cond_in
  101. )
  102. dphi_dt, cfg_dphi_dt = torch.split(dphi_dt, [x.size(0), x.size(0)], dim=0)
  103. dphi_dt = ((1.0 + self.inference_cfg_rate) * dphi_dt - self.inference_cfg_rate * cfg_dphi_dt)
  104. x = x + dt * dphi_dt
  105. t = t + dt
  106. sol.append(x)
  107. if step < len(t_span) - 1:
  108. dt = t_span[step + 1] - t
  109. return sol[-1].float()
  110. def forward_estimator(self, x, mask, mu, t, spks, cond):
  111. if isinstance(self.estimator, torch.nn.Module):
  112. return self.estimator.forward(x, mask, mu, t, spks, cond)
  113. else:
  114. self.estimator.set_input_shape('x', (2, 80, x.size(2)))
  115. self.estimator.set_input_shape('mask', (2, 1, x.size(2)))
  116. self.estimator.set_input_shape('mu', (2, 80, x.size(2)))
  117. self.estimator.set_input_shape('t', (2,))
  118. self.estimator.set_input_shape('spks', (2, 80))
  119. self.estimator.set_input_shape('cond', (2, 80, x.size(2)))
  120. # run trt engine
  121. self.estimator.execute_v2([x.contiguous().data_ptr(),
  122. mask.contiguous().data_ptr(),
  123. mu.contiguous().data_ptr(),
  124. t.contiguous().data_ptr(),
  125. spks.contiguous().data_ptr(),
  126. cond.contiguous().data_ptr(),
  127. x.data_ptr()])
  128. return x
  129. def compute_loss(self, x1, mask, mu, spks=None, cond=None):
  130. """Computes diffusion loss
  131. Args:
  132. x1 (torch.Tensor): Target
  133. shape: (batch_size, n_feats, mel_timesteps)
  134. mask (torch.Tensor): target mask
  135. shape: (batch_size, 1, mel_timesteps)
  136. mu (torch.Tensor): output of encoder
  137. shape: (batch_size, n_feats, mel_timesteps)
  138. spks (torch.Tensor, optional): speaker embedding. Defaults to None.
  139. shape: (batch_size, spk_emb_dim)
  140. Returns:
  141. loss: conditional flow matching loss
  142. y: conditional flow
  143. shape: (batch_size, n_feats, mel_timesteps)
  144. """
  145. b, _, t = mu.shape
  146. # random timestep
  147. t = torch.rand([b, 1, 1], device=mu.device, dtype=mu.dtype)
  148. if self.t_scheduler == 'cosine':
  149. t = 1 - torch.cos(t * 0.5 * torch.pi)
  150. # sample noise p(x_0)
  151. z = torch.randn_like(x1)
  152. y = (1 - (1 - self.sigma_min) * t) * z + t * x1
  153. u = x1 - (1 - self.sigma_min) * z
  154. # during training, we randomly drop condition to trade off mode coverage and sample fidelity
  155. if self.training_cfg_rate > 0:
  156. cfg_mask = torch.rand(b, device=x1.device) > self.training_cfg_rate
  157. mu = mu * cfg_mask.view(-1, 1, 1)
  158. spks = spks * cfg_mask.view(-1, 1)
  159. cond = cond * cfg_mask.view(-1, 1, 1)
  160. pred = self.estimator(y, mask, mu, t.squeeze(), spks, cond)
  161. loss = F.mse_loss(pred * mask, u * mask, reduction="sum") / (torch.sum(mask) * u.shape[1])
  162. return loss, y
  163. class CausalConditionalCFM(ConditionalCFM):
  164. def __init__(self, in_channels, cfm_params, n_spks=1, spk_emb_dim=64, estimator: torch.nn.Module = None):
  165. super().__init__(in_channels, cfm_params, n_spks, spk_emb_dim, estimator)
  166. self.rand_noise = torch.randn([1, 80, 50 * 300])
  167. @torch.inference_mode()
  168. def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None):
  169. """Forward diffusion
  170. Args:
  171. mu (torch.Tensor): output of encoder
  172. shape: (batch_size, n_feats, mel_timesteps)
  173. mask (torch.Tensor): output_mask
  174. shape: (batch_size, 1, mel_timesteps)
  175. n_timesteps (int): number of diffusion steps
  176. temperature (float, optional): temperature for scaling noise. Defaults to 1.0.
  177. spks (torch.Tensor, optional): speaker ids. Defaults to None.
  178. shape: (batch_size, spk_emb_dim)
  179. cond: Not used but kept for future purposes
  180. Returns:
  181. sample: generated mel-spectrogram
  182. shape: (batch_size, n_feats, mel_timesteps)
  183. """
  184. z = self.rand_noise[:, :, :mu.size(2)].to(mu.device).to(mu.dtype) * temperature
  185. # fix prompt and overlap part mu and z
  186. t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
  187. if self.t_scheduler == 'cosine':
  188. t_span = 1 - torch.cos(t_span * 0.5 * torch.pi)
  189. return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond), None