File size: 11,597 Bytes
9f5e507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""
SBDenoiser — Anisotropic Schrödinger Bridge denoiser.

Training: Joint velocity + score matching with anisotropic bridge paths.
          v_θ target = x_T - x₀ (PF-ODE velocity, same as scDFM).
          s_θ target = -(x_t - μ_t) / var_t (conditional score).
          Minibatch anisotropic OT per step.

Inference: Euler-Maruyama SDE using drift = v_θ + (σ²/2)·s_θ.
           Or PF-ODE ablation: drift = v_θ.
"""

import math
import torch
import torch.nn as nn
import torchdiffeq

from ._scdfm_imports import make_lognorm_poisson_noise
from .model.model import SBModel
from .ot_anisotropic import AnisotropicOTSampler


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 SBDenoiser(nn.Module):
    """
    Anisotropic Schrödinger Bridge Denoiser.

    σ_g simultaneously controls:
    1. OT coupling cost (Mahalanobis weights)
    2. Bridge noise level (conditional bridge variance)
    3. SDE diffusion strength (Euler-Maruyama noise)
    """

    def __init__(
        self,
        model: SBModel,
        noise_type: str = "Gaussian",
        use_mmd_loss: bool = True,
        gamma: float = 0.5,
        poisson_alpha: float = 0.8,
        poisson_target_sum: float = 1e4,
        # Score training
        score_weight: float = 0.1,
        score_t_clip: float = 0.02,
        use_score: bool = True,
        # σ_g regularization
        sigma_base: float = 0.5,
        sigma_sparse_weight: float = 0.01,
        sigma_volume_weight: float = 0.01,
        # OT coupling
        ot_method: str = "sinkhorn",
        ot_reg: float = 0.05,
        ot_use_sigma: bool = True,
        sigma_min: float = 0.01,
        # Time sampling
        t_sample_mode: str = "logit_normal",
        t_mean: float = 0.0,
        t_std: float = 1.0,
        # SDE inference
        sde_steps: int = 50,
        use_sde_inference: bool = True,
        # Source-Anchored Bridge
        source_anchored: bool = False,
    ):
        super().__init__()
        self.model = model
        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.score_weight = score_weight
        self.score_t_clip = score_t_clip
        self.use_score = use_score
        self.sigma_base = sigma_base
        self.sigma_sparse_weight = sigma_sparse_weight
        self.sigma_volume_weight = sigma_volume_weight
        self.ot_use_sigma = ot_use_sigma
        self.t_sample_mode = t_sample_mode
        self.t_mean = t_mean
        self.t_std = t_std
        self.sde_steps = sde_steps
        self.use_sde_inference = use_sde_inference
        self.source_anchored = source_anchored

        self.ot_sampler = AnisotropicOTSampler(
            method=ot_method, reg=ot_reg, sigma_min=sigma_min,
        )

    def _make_noise(self, source: torch.Tensor) -> torch.Tensor:
        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 _sample_t(self, n: int, device: torch.device) -> torch.Tensor:
        if self.t_sample_mode == "logit_normal":
            t = torch.sigmoid(torch.randn(n, device=device) * self.t_std + self.t_mean)
        else:
            t = torch.rand(n, device=device)
        return t.clamp(self.score_t_clip, 1.0 - self.score_t_clip)

    def train_step(
        self,
        source: torch.Tensor,            # (B, G) control expression
        target: torch.Tensor,             # (B, G) perturbed expression
        perturbation_id: torch.Tensor,    # (B, n_pert)
        gene_input: torch.Tensor,         # (B, G) vocab-encoded gene IDs
    ) -> dict:
        """
        Single training step with anisotropic bridge + minibatch OT.
        """
        B = source.shape[0]
        device = source.device

        # 1. Sample time
        t = self._sample_t(B, device)                                    # (B,)
        t_col = t.unsqueeze(-1)                                          # (B, 1)

        # 2. Get σ_g from sigma_net (independent of backbone)
        #    Need gene_emb and pert_emb — compute them via the model's encoder
        with torch.no_grad():
            gene_emb = self.model.encoder(gene_input)                    # (B, G, d)
            pert_emb = self.model.get_perturbation_emb(
                perturbation_id, cell_1=source)                          # (B, d)
        # σ_g with gradient (for regularization loss)
        sigma_g = self.model.sigma_net(pert_emb, t, gene_emb)           # (B, G)
        sigma_g_det = sigma_g.detach()                                   # for bridge sampling

        # 3. Create x_0 and do minibatch anisotropic OT
        if self.source_anchored:
            x_0 = source                                                  # bridge from control
        else:
            x_0 = self._make_noise(source)                                # bridge from noise
        if self.ot_use_sigma:
            sigma_for_ot = sigma_g_det.mean(0)                            # (G,) batch mean
            x_0, target_matched = self.ot_sampler.sample_plan_fix_x0(
                x_0, target, sigma_for_ot)
        else:
            x_0, target_matched = self.ot_sampler.sample_plan_fix_x0(
                x_0, target, sigma_g=None)

        # 4. Anisotropic conditional bridge sampling
        mu_t = (1 - t_col) * x_0 + t_col * target_matched               # (B, G)
        var_t = (sigma_g_det ** 2 * (t_col * (1 - t_col))).clamp(min=1e-8)
        std_t = torch.sqrt(var_t)                                         # (B, G)
        eps = torch.randn_like(x_0)
        x_t = mu_t + std_t * eps                                          # (B, G)

        # 5. Targets
        v_target = target_matched - x_0                                    # source-anchored: Δ
        s_target = -eps / (std_t + 1e-8)                                   # conditional score

        # 6. Full model forward
        pred_v, pred_s, sigma_g_pred = self.model(
            gene_input, source, x_t, t, perturbation_id)

        # 7. Velocity loss
        loss_v = ((pred_v - v_target) ** 2).mean()

        # 8. Score loss (var_t-weighted DSM — equivalent to ε-prediction)
        #    var_t weighting cancels the 1/var_t in s_target, giving bounded loss ~O(1)
        loss_s = torch.tensor(0.0, device=device)
        if self.use_score and pred_s is not None:
            loss_s = (var_t * (pred_s - s_target) ** 2).mean()

        # 9. σ_g regularization
        #    Volume penalty anchors geometric mean at σ_base (global scale).
        #    L1 sparse penalty removed — it killed per-gene anisotropy by
        #    pulling every σ_g to σ_base.  Sigmoid [σ_min, σ_max] prevents
        #    collapse/explosion; volume penalty alone is sufficient.
        loss_sparse = (sigma_g_pred - self.sigma_base).abs().mean()  # monitor only
        loss_volume = (sigma_g_pred.log().mean() - math.log(self.sigma_base)) ** 2

        # 10. MMD loss (optional)
        loss_mmd = torch.tensor(0.0, device=device)
        if self.use_mmd_loss:
            x1_hat = x_t + pred_v * (1 - t_col)
            sigmas_mmd = median_sigmas(target_matched, scales=(0.5, 1.0, 2.0, 4.0))
            loss_mmd = mmd2_unbiased_multi_sigma(x1_hat, target_matched, sigmas_mmd)

        # 11. Total loss
        #    loss_sparse excluded — kept in return dict for monitoring
        loss = (
            loss_v
            + self.score_weight * loss_s
            + self.sigma_volume_weight * loss_volume
            + self.gamma * loss_mmd
        )

        return {
            "loss": loss,
            "loss_v": loss_v.detach(),
            "loss_s": loss_s.detach(),
            "loss_mmd": loss_mmd.detach(),
            "loss_sparse": loss_sparse.detach(),
            "loss_volume": loss_volume.detach(),
            "sigma_mean": sigma_g_pred.mean().detach(),
            "sigma_std": sigma_g_pred.std().detach(),
        }

    @torch.no_grad()
    def generate(
        self,
        source: torch.Tensor,            # (B, G)
        perturbation_id: torch.Tensor,    # (B, n_pert)
        gene_ids: torch.Tensor,           # (B, G) or (G,)
        steps: int = None,
        method: str = "sde",
    ) -> torch.Tensor:
        """
        Generate perturbed expression via SDE or PF-ODE.

        SDE:    dX = [v_θ + (σ²/2)·s_θ] dt + σ·dB  (Euler-Maruyama)
        PF-ODE: dx/dt = v_θ                          (torchdiffeq RK4)
        """
        B, G = source.shape
        device = source.device
        steps = steps or self.sde_steps

        if gene_ids.dim() == 1:
            gene_ids = gene_ids.unsqueeze(0).expand(B, -1)

        if self.source_anchored:
            x_0 = source.clone()                                          # start from control
        else:
            x_0 = self._make_noise(source)                                # start from noise

        use_sde = self.use_sde_inference and (method != "ode")

        if use_sde:
            # SDE: Euler-Maruyama (no high-order SDE solver available)
            x_t = x_0
            dt = 1.0 / steps
            for i in range(steps):
                t_val = i * dt
                t = torch.full((B,), t_val, device=device)
                pred_v, pred_s, sigma_g = self.model(
                    gene_ids, source, x_t, t, perturbation_id)
                if pred_s is not None:
                    drift = pred_v + 0.5 * sigma_g ** 2 * pred_s
                    diffusion_noise = sigma_g * math.sqrt(dt) * torch.randn_like(x_t)
                    x_t = x_t + drift * dt + diffusion_noise
                else:
                    x_t = x_t + pred_v * dt
        else:
            # PF-ODE: torchdiffeq RK4 (matches scDFM inference)
            def ode_func(t_scalar, x):
                t_batch = torch.full((B,), t_scalar.item(), device=device)
                pred_v, _, _ = self.model(
                    gene_ids, source, x, t_batch, perturbation_id)
                return pred_v

            t_span = torch.linspace(0, 1, steps, device=device)
            trajectory = torchdiffeq.odeint(
                ode_func, x_0, t_span,
                method="rk4", atol=1e-4, rtol=1e-4,
            )
            x_t = trajectory[-1]

        return torch.clamp(x_t, min=0)