File size: 12,330 Bytes
01fdb75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# Training for Medical Image Generation with Mask Conditioning
# Based on training_repa_JiT_LPIPS_DINO_NoiseGating.py

import torch
import torch.nn as nn
import lpips
import math
from typing import Callable

from src.utils.no_grad import freeze_model
from src.diffusion.base.training import BaseTrainer
from src.diffusion.base.scheduling import BaseScheduler


def constant(alpha, sigma):
    return 1


def time_shift_fn(t, timeshift=1.0):
    return t / (t + (1 - t) * timeshift)


class MedicalREPATrainer(BaseTrainer):
    """
    Trainer for medical image generation with:
    - Mask conditioning
    - LPIPS perceptual loss
    - Optional DINO perceptual loss (if encoder provided)
    - Noise-gating strategy
    """

    def __init__(
            self,
            scheduler: BaseScheduler,
            loss_weight_fn: Callable = constant,
            feat_loss_weight: float = 0.5,
            lognorm_t: bool = True,
            timeshift: float = 1.0,
            encoder: nn.Module = None,  # DINOv2 encoder (optional for medical)
            align_layer: int = 8,
            proj_denoiser_dim: int = 768,
            proj_hidden_dim: int = 768,
            proj_encoder_dim: int = 768,
            P_mean: float = -0.8,
            P_std: float = 0.8,
            t_eps: float = 0.05,
            lpips_weight: float = 0.1,
            dino_weight: float = 0.01,
            percept_t_threshold: float = 0.3,
            noise_scale: float = 1.0,
            patch_size: int = 16,
            use_dino: bool = False,  # Disable DINO by default for medical
            *args,
            **kwargs
    ):
        super().__init__(*args, **kwargs)
        self.lognorm_t = lognorm_t
        self.scheduler = scheduler
        self.timeshift = timeshift
        self.loss_weight_fn = loss_weight_fn
        self.feat_loss_weight = feat_loss_weight
        self.align_layer = align_layer
        self.use_dino = use_dino and (encoder is not None)

        # DINO encoder (optional)
        if self.use_dino:
            self.encoder = encoder
            freeze_model(self.encoder)
            self.proj = nn.Sequential(
                nn.Linear(proj_denoiser_dim, proj_hidden_dim),
                nn.SiLU(),
                nn.Linear(proj_hidden_dim, proj_hidden_dim),
                nn.SiLU(),
                nn.Linear(proj_hidden_dim, proj_encoder_dim),
            )
            self.dino_layers = [11]
        else:
            self.encoder = None
            self.proj = None

        # LPIPS loss
        self.lpips_loss_fn = lpips.LPIPS(net='vgg').eval()
        freeze_model(self.lpips_loss_fn)

        self.patch_size = patch_size
        self.P_mean = P_mean
        self.P_std = P_std
        self.t_eps = t_eps
        self.lpips_weight = lpips_weight
        self.dino_weight = dino_weight
        self.percept_t_threshold = percept_t_threshold
        self.noise_scale = noise_scale

    def compute_lpips_loss(self, pred_img, x, percept_mask=None):
        """Compute LPIPS loss with optional noise-gating mask."""
        batch_size, _, height, width = pred_img.shape

        # Resize for LPIPS if not 256
        if self.patch_size != 16:
            new_scale = int(height * 16 // self.patch_size)
            pred_img = torch.nn.functional.interpolate(
                pred_img, size=(new_scale, new_scale),
                mode='bilinear', align_corners=False, antialias=True
            )
            x = torch.nn.functional.interpolate(
                x, size=(new_scale, new_scale),
                mode='bilinear', align_corners=False, antialias=True
            )

        if percept_mask is not None:
            lpips_val = self.lpips_loss_fn(pred_img, x).view(batch_size, -1)
            lpips_loss = (lpips_val * percept_mask).mean(dim=1)
            lpips_loss = lpips_loss.sum() / percept_mask.sum() if percept_mask.sum() > 0 else lpips_loss.sum()
        else:
            lpips_loss = self.lpips_loss_fn(pred_img, x).mean()

        return lpips_loss

    def compute_dino_loss(self, pred_dino_feats, gt_dino_feats, percept_mask=None):
        """Compute DINO perceptual loss."""
        cos_losses = {}
        final_cos_loss = 0
        batch_size = pred_dino_feats[0].shape[0]

        for i, (pred_feat, gt_feat) in enumerate(zip(pred_dino_feats, gt_dino_feats)):
            if percept_mask is not None:
                mask = percept_mask.reshape(batch_size, 1, 1)
                cos_sim = (torch.nn.functional.cosine_similarity(pred_feat, gt_feat, dim=-1) * mask).mean(dim=(1, 2))
                cos_sim = cos_sim.sum() / mask.sum() if mask.sum() > 0 else cos_sim.sum()
                cos_loss = 1 - cos_sim
            else:
                cos_loss = 1 - torch.nn.functional.cosine_similarity(pred_feat, gt_feat, dim=-1).view(batch_size, -1).mean()

            cos_losses[f"inter_cos_{i}"] = cos_loss
            final_cos_loss += cos_loss

        cos_losses["dino_percept_loss"] = final_cos_loss / len(pred_dino_feats)
        return cos_losses

    def _impl_trainstep(self, net, ema_net, solver, x, condition, metadata=None):
        """Training step with mask conditioning.

        For medical images, we use mask from metadata directly,
        not the condition from conditioner.
        """
        raw_images = metadata.get("raw_image", None)
        mask = metadata.get("mask", None)

        batch_size, c, height, width = x.shape
        # Class labels - use zeros for medical (single class)
        y = torch.zeros(batch_size, dtype=torch.long, device=x.device)

        self.lpips_loss_fn.eval()

        # Sample timesteps
        if self.lognorm_t:
            base_t = (torch.randn(batch_size, device=x.device, dtype=torch.float32) * self.P_std + self.P_mean).sigmoid()
        else:
            base_t = torch.rand((batch_size), device=x.device, dtype=torch.float32)
        t = time_shift_fn(base_t, self.timeshift)

        # Add noise
        noise = self.noise_scale * torch.randn_like(x)
        alpha = self.scheduler.alpha(t)
        sigma = self.scheduler.sigma(t)

        x_t = alpha * x + noise * sigma

        # Velocity target
        v_t = (x - x_t) / (1 - t.view(-1, 1, 1, 1)).clamp_min(self.t_eps)

        # Forward pass with mask conditioning
        if self.use_dino:
            pred_img, src_feature = net(x_t, t, y, mask=mask, return_layer=self.align_layer)
            src_feature = self.proj(src_feature)
        else:
            pred_img = net(x_t, t, y, mask=mask)

        # Compute velocity from prediction
        out = (pred_img - x_t) / (1 - t.view(-1, 1, 1, 1)).clamp_min(self.t_eps)

        # Flow matching loss
        weight = self.loss_weight_fn(alpha, sigma)
        fm_loss = weight * (out - v_t) ** 2

        # Noise-gating mask for perceptual losses
        if self.percept_t_threshold > 0:
            percept_mask = (t >= self.percept_t_threshold).float().reshape(batch_size, -1)
        else:
            percept_mask = None

        # LPIPS loss
        lpips_loss = self.compute_lpips_loss(pred_img, x, percept_mask)

        # DINO loss (if enabled)
        dino_losses = {}
        cos_loss = torch.tensor(0.0, device=x.device)

        if self.use_dino and raw_images is not None:
            with torch.no_grad():
                dst_features = self.encoder.get_intermediate_feats(raw_images, n=self.dino_layers)

            # REPA loss (hidden feature alignment)
            cos_sim = torch.nn.functional.cosine_similarity(src_feature, dst_features[-1], dim=-1)
            cos_loss = (1 - cos_sim).mean()

            # P-DINO loss (predicted image feature alignment)
            raw_pred_img = (pred_img + 1) / 2  # [-1, 1] -> [0, 1]
            pred_feats = self.encoder.get_intermediate_feats(raw_pred_img, n=self.dino_layers)
            dino_losses = self.compute_dino_loss(pred_feats, dst_features, percept_mask)

        # Total loss
        final_loss = fm_loss.mean() + self.lpips_weight * lpips_loss

        if self.use_dino:
            final_loss = final_loss + self.feat_loss_weight * cos_loss
            if "dino_percept_loss" in dino_losses:
                final_loss = final_loss + self.dino_weight * dino_losses["dino_percept_loss"]

        out_dict = dict(
            fm_loss=fm_loss.mean(),
            lpips_loss=lpips_loss,
            loss=final_loss,
        )

        if self.use_dino:
            out_dict["cos_loss"] = cos_loss
            out_dict.update(dino_losses)

        return out_dict

    def state_dict(self, *args, destination=None, prefix="", keep_vars=False):
        if self.proj is not None:
            self.proj.state_dict(
                destination=destination,
                prefix=prefix + "proj.",
                keep_vars=keep_vars)


class MedicalTrainerSimple(BaseTrainer):
    """
    Simplified trainer for medical images with only LPIPS loss.
    No DINO encoder required - suitable for domains where DINOv2 may not work well.
    """

    def __init__(
            self,
            scheduler: BaseScheduler,
            loss_weight_fn: Callable = constant,
            lognorm_t: bool = True,
            timeshift: float = 1.0,
            P_mean: float = -0.8,
            P_std: float = 0.8,
            t_eps: float = 0.05,
            lpips_weight: float = 0.1,
            percept_t_threshold: float = 0.3,
            noise_scale: float = 1.0,
            patch_size: int = 16,
            *args,
            **kwargs
    ):
        super().__init__(*args, **kwargs)
        self.lognorm_t = lognorm_t
        self.scheduler = scheduler
        self.timeshift = timeshift
        self.loss_weight_fn = loss_weight_fn

        # LPIPS loss only
        self.lpips_loss_fn = lpips.LPIPS(net='vgg').eval()
        freeze_model(self.lpips_loss_fn)

        self.patch_size = patch_size
        self.P_mean = P_mean
        self.P_std = P_std
        self.t_eps = t_eps
        self.lpips_weight = lpips_weight
        self.percept_t_threshold = percept_t_threshold
        self.noise_scale = noise_scale

    def _impl_trainstep(self, net, ema_net, solver, x, condition, metadata=None):
        """
        Training step for medical image generation.

        For medical images, the 'condition' from conditioner is not used directly.
        Instead, we use mask from metadata and class labels from metadata.
        """
        mask = metadata.get("mask", None)
        # Class labels - use zeros for medical (single class)
        batch_size, c, height, width = x.shape
        y = torch.zeros(batch_size, dtype=torch.long, device=x.device)

        self.lpips_loss_fn.eval()

        # Sample timesteps
        if self.lognorm_t:
            base_t = (torch.randn(batch_size, device=x.device, dtype=torch.float32) * self.P_std + self.P_mean).sigmoid()
        else:
            base_t = torch.rand((batch_size), device=x.device, dtype=torch.float32)
        t = time_shift_fn(base_t, self.timeshift)

        # Add noise
        noise = self.noise_scale * torch.randn_like(x)
        alpha = self.scheduler.alpha(t)
        sigma = self.scheduler.sigma(t)

        x_t = alpha * x + noise * sigma
        v_t = (x - x_t) / (1 - t.view(-1, 1, 1, 1)).clamp_min(self.t_eps)

        # Forward pass - mask is passed directly to the model
        pred_img = net(x_t, t, y, mask=mask)
        out = (pred_img - x_t) / (1 - t.view(-1, 1, 1, 1)).clamp_min(self.t_eps)

        # Flow matching loss
        weight = self.loss_weight_fn(alpha, sigma)
        fm_loss = weight * (out - v_t) ** 2

        # LPIPS loss with noise-gating
        if self.percept_t_threshold > 0:
            percept_mask = (t >= self.percept_t_threshold).float().reshape(batch_size, -1)
            lpips_val = self.lpips_loss_fn(pred_img, x).view(batch_size, -1)
            lpips_loss = (lpips_val * percept_mask).mean(dim=1)
            lpips_loss = lpips_loss.sum() / percept_mask.sum() if percept_mask.sum() > 0 else lpips_loss.sum()
        else:
            lpips_loss = self.lpips_loss_fn(pred_img, x).mean()

        final_loss = fm_loss.mean() + self.lpips_weight * lpips_loss

        return dict(
            fm_loss=fm_loss.mean(),
            lpips_loss=lpips_loss,
            loss=final_loss,
        )

    def state_dict(self, *args, destination=None, prefix="", keep_vars=False):
        pass  # No additional parameters to save