flow_matching.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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, required_cache_size=0, flow_cache=None):
  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. if flow_cache is not None:
  49. z_cache = flow_cache[0]
  50. mu_cache = flow_cache[1]
  51. z = torch.randn((mu.size(0), mu.size(1), mu.size(2) - z_cache.size(2)), dtype=mu.dtype, device=mu.device) * temperature
  52. z = torch.cat((z_cache, z), dim=2) # [B, 80, T]
  53. mu = torch.cat((mu_cache, mu[..., mu_cache.size(2):]), dim=2) # [B, 80, T]
  54. else:
  55. z = torch.randn_like(mu) * temperature
  56. next_cache_start = max(z.size(2) - required_cache_size, 0)
  57. flow_cache = [
  58. z[..., next_cache_start:],
  59. mu[..., next_cache_start:]
  60. ]
  61. t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
  62. if self.t_scheduler == 'cosine':
  63. t_span = 1 - torch.cos(t_span * 0.5 * torch.pi)
  64. return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond), flow_cache
  65. def solve_euler(self, x, t_span, mu, mask, spks, cond):
  66. """
  67. Fixed euler solver for ODEs.
  68. Args:
  69. x (torch.Tensor): random noise
  70. t_span (torch.Tensor): n_timesteps interpolated
  71. shape: (n_timesteps + 1,)
  72. mu (torch.Tensor): output of encoder
  73. shape: (batch_size, n_feats, mel_timesteps)
  74. mask (torch.Tensor): output_mask
  75. shape: (batch_size, 1, mel_timesteps)
  76. spks (torch.Tensor, optional): speaker ids. Defaults to None.
  77. shape: (batch_size, spk_emb_dim)
  78. cond: Not used but kept for future purposes
  79. """
  80. t, _, dt = t_span[0], t_span[-1], t_span[1] - t_span[0]
  81. t = t.unsqueeze(dim=0)
  82. # I am storing this because I can later plot it by putting a debugger here and saving it to a file
  83. # Or in future might add like a return_all_steps flag
  84. sol = []
  85. for step in range(1, len(t_span)):
  86. dphi_dt = self.forward_estimator(x, mask, mu, t, spks, cond)
  87. # Classifier-Free Guidance inference introduced in VoiceBox
  88. if self.inference_cfg_rate > 0:
  89. cfg_dphi_dt = self.forward_estimator(
  90. x, mask,
  91. torch.zeros_like(mu), t,
  92. torch.zeros_like(spks) if spks is not None else None,
  93. torch.zeros_like(cond)
  94. )
  95. dphi_dt = ((1.0 + self.inference_cfg_rate) * dphi_dt -
  96. self.inference_cfg_rate * cfg_dphi_dt)
  97. x = x + dt * dphi_dt
  98. t = t + dt
  99. sol.append(x)
  100. if step < len(t_span) - 1:
  101. dt = t_span[step + 1] - t
  102. return sol[-1]
  103. def forward_estimator(self, x, mask, mu, t, spks, cond):
  104. if isinstance(self.estimator, torch.nn.Module):
  105. return self.estimator.forward(x, mask, mu, t, spks, cond)
  106. else:
  107. ort_inputs = {
  108. 'x': x.cpu().numpy(),
  109. 'mask': mask.cpu().numpy(),
  110. 'mu': mu.cpu().numpy(),
  111. 't': t.cpu().numpy(),
  112. 'spks': spks.cpu().numpy(),
  113. 'cond': cond.cpu().numpy()
  114. }
  115. output = self.estimator.run(None, ort_inputs)[0]
  116. return torch.tensor(output, dtype=x.dtype, device=x.device)
  117. def compute_loss(self, x1, mask, mu, spks=None, cond=None):
  118. """Computes diffusion loss
  119. Args:
  120. x1 (torch.Tensor): Target
  121. shape: (batch_size, n_feats, mel_timesteps)
  122. mask (torch.Tensor): target mask
  123. shape: (batch_size, 1, mel_timesteps)
  124. mu (torch.Tensor): output of encoder
  125. shape: (batch_size, n_feats, mel_timesteps)
  126. spks (torch.Tensor, optional): speaker embedding. Defaults to None.
  127. shape: (batch_size, spk_emb_dim)
  128. Returns:
  129. loss: conditional flow matching loss
  130. y: conditional flow
  131. shape: (batch_size, n_feats, mel_timesteps)
  132. """
  133. b, _, t = mu.shape
  134. # random timestep
  135. t = torch.rand([b, 1, 1], device=mu.device, dtype=mu.dtype)
  136. if self.t_scheduler == 'cosine':
  137. t = 1 - torch.cos(t * 0.5 * torch.pi)
  138. # sample noise p(x_0)
  139. z = torch.randn_like(x1)
  140. y = (1 - (1 - self.sigma_min) * t) * z + t * x1
  141. u = x1 - (1 - self.sigma_min) * z
  142. # during training, we randomly drop condition to trade off mode coverage and sample fidelity
  143. if self.training_cfg_rate > 0:
  144. cfg_mask = torch.rand(b, device=x1.device) > self.training_cfg_rate
  145. mu = mu * cfg_mask.view(-1, 1, 1)
  146. spks = spks * cfg_mask.view(-1, 1)
  147. cond = cond * cfg_mask.view(-1, 1, 1)
  148. pred = self.estimator(y, mask, mu, t.squeeze(), spks, cond)
  149. loss = F.mse_loss(pred * mask, u * mask, reduction="sum") / (torch.sum(mask) * u.shape[1])
  150. return loss, y