import torch import torch.nn as nn import torch.nn.functional as F from abc import ABC from typing import Optional from .decoder import Decoder from .source_generator import SourceGenerator class BASECFM(nn.Module, ABC): def __init__(self, feat_dim: int, cfm_params, embed_dim: int = 256): super().__init__() self.feat_dim = feat_dim self.embed_dim = embed_dim self.sigma_min = cfm_params.sigma_min self.estimator: Optional[nn.Module] = None self.src_gen: Optional[nn.Module] = None self.cond_proj: nn.Linear = nn.Linear(embed_dim, feat_dim) # ---- inference ----------------------------------------------------------- @torch.inference_mode() def forward( self, src_cond: torch.Tensor, # (B, feat_dim, L) mu_fusion: torch.Tensor, # (B, embed_dim, L) n_timesteps: int, temperature: float = 1.0, ) -> torch.Tensor: mean_c, logvar_c = self.src_gen(src_cond) eps = torch.randn_like(mean_c) * temperature z = mean_c + torch.exp(0.5 * logvar_c) * eps t_span = torch.linspace(0, 1, n_timesteps + 1, device=src_cond.device) return self.solve_euler(z, t_span, mu_fusion) def solve_euler( self, x: torch.Tensor, # (B, feat_dim, L) t_span: torch.Tensor, # (n_steps+1,) mu: torch.Tensor, # (B, embed_dim, L) ) -> torch.Tensor: t = t_span[0] dt = t_span[1] - t_span[0] B = x.shape[0] # Project mu_fusion to feat_dim for estimator # mu is (B, embed_dim, L) -> cond_proj requires (B, L, embed_dim) mu_proj = self.cond_proj(mu.transpose(1, 2)).transpose(1, 2) # (B, feat_dim, L) for step in range(1, len(t_span)): t_batch = t.expand(B) # (B,) dphi_dt = self.estimator(x, mu_proj, t_batch) x = x + dt * dphi_dt t = t + dt if step < len(t_span) - 1: dt = t_span[step + 1] - t return x # ---- training ------------------------------------------------------------ def compute_loss( self, x1: torch.Tensor, # (B, feat_dim, L) src_cond: torch.Tensor, # (B, feat_dim, L) mu_fusion: torch.Tensor, # (B, embed_dim, L) lambda_var: float = 0.5, # Hyperparameters from the paper lambda_align: float = 0.5, ) -> tuple: B = x1.shape[0] # t sampled per sample, broadcast-ready for interpolation t = torch.rand(B, 1, 1, device=src_cond.device, dtype=src_cond.dtype) # (B,1,1) mean_c, logvar_c = self.src_gen(src_cond) # (B, C, L) eps = torch.randn_like(mean_c) z = mean_c + torch.exp(0.5 * logvar_c) * eps y = (1 - (1 - self.sigma_min) * t) * z + t * x1 # interpolant u = x1 - (1 - self.sigma_min) * z # target velocity # Project mu_fusion to feat_dim for estimator mu_proj = self.cond_proj(mu_fusion.transpose(1, 2)).transpose(1, 2) # (B, feat_dim, L) # estimator expects t as (B,) t_batch = t.reshape(B) pred = self.estimator(y, mu_proj, t_batch) # 4. Standard Flow Matching Loss loss_fm = F.mse_loss(pred, u) # 5. Variance Regularization Loss [Eq. 9 in paper] # D_KL( N(mu_c, sigma_c^2) || N(mu_c, I) ) = 0.5 * (sigma^2 - log(sigma^2) - 1) loss_var = 0.5 * (torch.exp(logvar_c) - logvar_c - 1).mean() # 6. Cosine Alignment Loss [Eq. 10 in paper] sim = F.cosine_similarity(z.flatten(1), x1.flatten(1), dim=1) loss_align = (1.0 - sim).mean() # 7. Total Loss [Eq. 11 in paper] loss_total = loss_fm + lambda_var * loss_var + lambda_align * loss_align # Return total loss, and a dictionary for logging loss_dict = { "fm": loss_fm.item(), "var": loss_var.item(), "align": loss_align.item(), } return loss_total, loss_dict class CFM(BASECFM): def __init__( self, feat_dim: int, cfm_params, decoder_params: dict, embed_dim: int = 256 ): super().__init__(feat_dim=feat_dim, cfm_params=cfm_params, embed_dim=embed_dim) self.estimator = Decoder(in_c=feat_dim, out_c=feat_dim, **decoder_params) self.src_gen = SourceGenerator(feat_dim=feat_dim)