""" CascadedDenoiser for grn_svd — uses SVD-projected (B, G, 128) as latent target. Key changes from grn_att_only: - SVD dictionary W (5035, 128) as frozen register_buffer on GPU - _sparse_project(): GPU-based loop-of-K gather+accumulate - 1D missing mask (not 2D) - Simplified masked MSE loss (no non-zero reweighting) - reconstruct_grn(): inverse projection for GRN visualization """ import torch import torch.nn as nn import torchdiffeq from ._scdfm_imports import AffineProbPath, CondOTScheduler, make_lognorm_poisson_noise from .model.model import CascadedFlowModel from .data.sparse_raw_cache import SparseDeltaCache # Shared flow matching path flow_path = AffineProbPath(scheduler=CondOTScheduler()) def pairwise_sq_dists(X, Y): return torch.cdist(X, Y, p=2) ** 2 @torch.no_grad() def median_sigmas(X, scales=(0.5, 1.0, 2.0, 4.0)): D2 = pairwise_sq_dists(X, X) tri = D2[~torch.eye(D2.size(0), dtype=bool, device=D2.device)] m = torch.median(tri).clamp_min(1e-12) s2 = torch.tensor(scales, device=X.device) * m return [float(s.item()) for s in torch.sqrt(s2)] def mmd2_unbiased_multi_sigma(X, Y, sigmas): m, n = X.size(0), Y.size(0) Dxx = pairwise_sq_dists(X, X) Dyy = pairwise_sq_dists(Y, Y) Dxy = pairwise_sq_dists(X, Y) vals = [] for sigma in sigmas: beta = 1.0 / (2.0 * (sigma ** 2) + 1e-12) Kxx = torch.exp(-beta * Dxx) Kyy = torch.exp(-beta * Dyy) Kxy = torch.exp(-beta * Dxy) term_xx = (Kxx.sum() - Kxx.diag().sum()) / (m * (m - 1) + 1e-12) term_yy = (Kyy.sum() - Kyy.diag().sum()) / (n * (n - 1) + 1e-12) term_xy = Kxy.mean() vals.append(term_xx + term_yy - 2.0 * term_xy) return torch.stack(vals).mean() class CascadedDenoiser(nn.Module): """ Cascaded denoiser with SVD-projected latent target. Training: Cascaded time-step sampling, GPU-side SVD projection. Inference: Two-stage cascaded generation in 128-dim latent space. """ def __init__( self, model: CascadedFlowModel, sparse_cache: SparseDeltaCache, svd_dict_path: str, choose_latent_p: float = 0.4, latent_weight: float = 1.0, noise_type: str = "Gaussian", use_mmd_loss: bool = True, gamma: float = 0.5, poisson_alpha: float = 0.8, poisson_target_sum: float = 1e4, # Logit-normal time-step sampling t_sample_mode: str = "logit_normal", t_expr_mean: float = 0.0, t_expr_std: float = 1.0, t_latent_mean: float = 0.0, t_latent_std: float = 1.0, # Cascaded noise noise_beta: float = 0.25, # Variance-weighted latent loss use_variance_weight: bool = False, ): super().__init__() self.model = model self.sparse_cache = sparse_cache self.choose_latent_p = choose_latent_p self.latent_weight = latent_weight self.noise_type = noise_type self.use_mmd_loss = use_mmd_loss self.gamma = gamma self.poisson_alpha = poisson_alpha self.poisson_target_sum = poisson_target_sum self.t_sample_mode = t_sample_mode self.t_expr_mean = t_expr_mean self.t_expr_std = t_expr_std self.t_latent_mean = t_latent_mean self.t_latent_std = t_latent_std self.noise_beta = noise_beta self.use_variance_weight = use_variance_weight # Load SVD dictionary as frozen buffer (moves with model to GPU) svd_dict = torch.load(svd_dict_path, map_location="cpu", weights_only=False) self.register_buffer("W", svd_dict["W"].float()) # (G_full, 128) self.register_buffer("global_scale_sq", torch.tensor(svd_dict["global_scale"] ** 2).float()) # scalar self.latent_dim = self.W.shape[1] # Variance-weighted latent loss: w_i = evr_i / sum(evr) if use_variance_weight: evr = torch.from_numpy(svd_dict["explained_variance_ratio"]).float() w = evr / evr.sum() # (latent_dim,) normalized to sum=1 self.register_buffer("latent_dim_weights", w) print(f" Variance weighting ON: top={w[0]:.4f}, bot={w[-1]:.4f}, " f"ratio={w[0]/w[-1]:.1f}x") print(f" SVD dict loaded: W {self.W.shape}, " f"global_scale={svd_dict['global_scale']:.6f}") def _sparse_project(self, delta_values, delta_indices): """ Sparse GPU projection: delta @ W via loop-of-K gather+accumulate. Args: delta_values: (B, G_sub, K) float32 — top-K delta values (on GPU) delta_indices: (B, G_sub, K) int16 — column indices in G_full space (on GPU) Returns: z_target: (B, G_sub, latent_dim=128) """ assert delta_values.device == self.W.device, \ f"Device mismatch: delta on {delta_values.device}, W on {self.W.device}" B, G_sub, K = delta_values.shape z_target = torch.zeros(B, G_sub, self.latent_dim, device=delta_values.device) indices_long = delta_indices.long() # (B, G_sub, K) for k in range(K): col_idx = indices_long[:, :, k] # (B, G_sub) val = delta_values[:, :, k:k+1] # (B, G_sub, 1) w_k = self.W[col_idx] # (B, G_sub, latent_dim) z_target = z_target + val * w_k # broadcast + accumulate return z_target def reconstruct_grn(self, z: torch.Tensor) -> torch.Tensor: """ Inverse projection: 128-dim latent → approximate delta attention (sparse GRN). Math: W_saved = V × s (V orthonormal, s = global_scale) Forward: z = delta @ W = delta @ Vs Inverse: delta ≈ z @ V^T / s = z @ W^T / s^2 Args: z: (B, G, 128) — latent from ODE generation Returns: (B, G, G_full) — approximate delta attention per gene """ return z @ self.W.T / self.global_scale_sq def sample_t(self, n: int, device: torch.device): """Cascaded time-step sampling — dino_first_cascaded mode.""" if self.t_sample_mode == "logit_normal": t_latent = torch.sigmoid(torch.randn(n, device=device) * self.t_latent_std + self.t_latent_mean) t_expr = torch.sigmoid(torch.randn(n, device=device) * self.t_expr_std + self.t_expr_mean) else: t_latent = torch.rand(n, device=device) t_expr = torch.rand(n, device=device) choose_latent_mask = torch.rand(n, device=device) < self.choose_latent_p t_latent_expr = torch.rand_like(t_latent) * self.noise_beta + (1.0 - self.noise_beta) t_latent = torch.where(choose_latent_mask, t_latent, t_latent_expr) t_expr = torch.where(choose_latent_mask, torch.zeros_like(t_expr), t_expr) w_expr = (~choose_latent_mask).float() w_latent = choose_latent_mask.float() return t_expr, t_latent, w_expr, w_latent def _make_expr_noise(self, source: torch.Tensor) -> torch.Tensor: """Create noise for expression flow.""" if self.noise_type == "Gaussian": return torch.randn_like(source) elif self.noise_type == "Poisson": return make_lognorm_poisson_noise( target_log=source, alpha=self.poisson_alpha, per_cell_L=self.poisson_target_sum, ) else: raise ValueError(f"Unknown noise_type: {self.noise_type}") def train_step( self, source: torch.Tensor, # (B, G_sub) — already subsetted target: torch.Tensor, # (B, G_sub) perturbation_id: torch.Tensor, # (B, 2) gene_input: torch.Tensor, # (B, G_sub) vocab-encoded gene IDs delta_values: torch.Tensor, # (B, G_sub, K) on GPU delta_indices: torch.Tensor, # (B, G_sub, K) int16 on GPU input_gene_ids: torch.Tensor, # (G_sub,) positional indices for missing mask ) -> dict: """Single training step with SVD-projected latent target.""" B = source.shape[0] device = source.device G_sub = source.shape[-1] # 1. GPU-side SVD projection: sparse → dense 128-dim z_target = self._sparse_project(delta_values, delta_indices) # (B, G_sub, 128) # 2. Missing gene mask — 1D only missing = self.sparse_cache.get_missing_gene_mask(input_gene_ids) # (G_sub,) bool missing_dev = missing.to(device) # 3. Cascaded time sampling t_expr, t_latent, w_expr, w_latent = self.sample_t(B, device) # 4. Expression flow path noise_expr = self._make_expr_noise(source) path_expr = flow_path.sample(t=t_expr, x_0=noise_expr, x_1=target) # 5. Latent flow path — (B, G_sub, 128) noise_latent = torch.randn_like(z_target) # 1D missing mask: zero entire gene rows noise_latent[:, missing_dev, :] = 0.0 z_flat = z_target.reshape(B, G_sub * self.latent_dim) noise_flat = noise_latent.reshape(B, G_sub * self.latent_dim) path_latent_flat = flow_path.sample(t=t_latent, x_0=noise_flat, x_1=z_flat) class _LatentPath: pass path_latent = _LatentPath() path_latent.x_t = path_latent_flat.x_t.reshape(B, G_sub, self.latent_dim) path_latent.dx_t = path_latent_flat.dx_t.reshape(B, G_sub, self.latent_dim) # 6. Model forward pred_v_expr, pred_v_latent = self.model( gene_input, source, path_expr.x_t, path_latent.x_t, t_expr, t_latent, perturbation_id, ) # 7. Losses # Expression loss (unchanged from grn_att_only) loss_expr_per_sample = ((pred_v_expr - path_expr.dx_t) ** 2).mean(dim=-1) # (B,) loss_expr = (loss_expr_per_sample * w_expr).sum() / w_expr.sum().clamp(min=1) # Latent loss — masked MSE over 128-dim SVD latent loss_elem = (pred_v_latent - path_latent.dx_t) ** 2 # (B, G_sub, 128) if self.use_variance_weight: loss_per_gene = (loss_elem * self.latent_dim_weights).sum(dim=-1) # (B, G_sub) else: loss_per_gene = loss_elem.mean(dim=-1) # (B, G_sub) — uniform over 128 dims loss_per_gene[:, missing_dev] = 0.0 # zero out missing genes n_valid = (~missing_dev).sum().clamp(min=1) loss_latent_per_sample = loss_per_gene.sum(dim=-1) / n_valid # (B,) loss_latent = (loss_latent_per_sample * w_latent).sum() / w_latent.sum().clamp(min=1) loss = loss_expr + self.latent_weight * loss_latent # Optional MMD loss on expression _mmd_loss = torch.tensor(0.0, device=device) if self.use_mmd_loss and w_expr.sum() > 0: expr_mask = w_expr > 0 if expr_mask.any(): x1_hat = ( path_expr.x_t[expr_mask] + pred_v_expr[expr_mask] * (1 - t_expr[expr_mask]).unsqueeze(-1) ) sigmas = median_sigmas(target[expr_mask], scales=(0.5, 1.0, 2.0, 4.0)) _mmd_loss = mmd2_unbiased_multi_sigma(x1_hat, target[expr_mask], sigmas) loss = loss + _mmd_loss * self.gamma return { "loss": loss, "loss_expr": loss_expr.detach(), "loss_latent": loss_latent.detach(), "loss_mmd": _mmd_loss.detach(), } @torch.no_grad() def generate( self, source: torch.Tensor, # (B, G) perturbation_id: torch.Tensor, # (B, 2) gene_ids: torch.Tensor, # (B, G) or (G,) latent_steps: int = 20, expr_steps: int = 20, method: str = "rk4", ) -> torch.Tensor: """ Two-stage cascaded generation in 128-dim latent space. Returns: (B, G) generated expression values """ B, G = source.shape device = source.device if gene_ids.dim() == 1: gene_ids = gene_ids.unsqueeze(0).expand(B, -1) # 1D missing mask missing = self.sparse_cache.get_missing_gene_mask(torch.arange(G)) # Initialize latent noise in 128-dim (NOT G×G!) z_t = torch.randn(B, G, self.latent_dim, device=device) if missing is not None: z_t[:, missing, :] = 0.0 x_t = self._make_expr_noise(source) if method == "rk4": # === Stage 1: Latent generation (t_latent: 0->1, t_expr=0) === t_zero = torch.zeros(B, device=device) t_one = torch.ones(B, device=device) def latent_vf(t, z): v_expr, v_latent = self.model( gene_ids, source, x_t, z, t_zero, t.expand(B), perturbation_id, ) if missing is not None: v_latent[:, missing, :] = 0.0 return v_latent z_t = torchdiffeq.odeint( latent_vf, z_t, torch.linspace(0, 1, latent_steps + 1, device=device), method="rk4", atol=1e-4, rtol=1e-4, )[-1] # === Stage 2: Expression generation (t_expr: 0->1, t_latent=1) === def expr_vf(t, x): v_expr, v_latent = self.model( gene_ids, source, x, z_t, t.expand(B), t_one, perturbation_id, ) return v_expr x_t = torchdiffeq.odeint( expr_vf, x_t, torch.linspace(0, 1, expr_steps + 1, device=device), method="rk4", atol=1e-4, rtol=1e-4, )[-1] else: # euler t_latent_schedule = torch.cat([ torch.linspace(0, 1, latent_steps + 1, device=device), torch.ones(expr_steps, device=device), ]) t_expr_schedule = torch.cat([ torch.zeros(latent_steps + 1, device=device), torch.linspace(0, 1, expr_steps + 1, device=device)[1:], ]) for i in range(latent_steps + expr_steps): t_lat = t_latent_schedule[i] t_lat_next = t_latent_schedule[i + 1] t_exp = t_expr_schedule[i] t_exp_next = t_expr_schedule[i + 1] v_expr, v_latent = self.model( gene_ids, source, x_t, z_t, t_exp.expand(B), t_lat.expand(B), perturbation_id, ) x_t = x_t + (t_exp_next - t_exp) * v_expr z_t = z_t + (t_lat_next - t_lat) * v_latent if missing is not None: z_t[:, missing, :] = 0.0 return torch.clamp(x_t, min=0)