File size: 10,060 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
# Sampling for Medical Image Generation with Mask Conditioning
# Based on sampling.py with mask support

import torch
import torch.nn as nn
from typing import Callable
import logging

from src.diffusion.base.guidance import *
from src.diffusion.base.scheduling import BaseScheduler
from src.diffusion.base.sampling import BaseSampler

logger = logging.getLogger(__name__)


def shift_respace_fn(t, shift=3.0):
    return t / (t + (1 - t) * shift)


def ode_step_fn(x, v, dt, s, w):
    return x + v * dt


class EulerSamplerMedical(BaseSampler):
    """
    Euler sampler for mask-conditional medical image generation.
    """

    def __init__(
            self,
            w_scheduler: BaseScheduler = None,
            timeshift: float = 1.0,
            guidance_interval_min: float = 0.0,
            guidance_interval_max: float = 1.0,
            step_fn: Callable = ode_step_fn,
            last_step: float = None,
            last_step_fn: Callable = ode_step_fn,
            t_eps: float = 0.05,
            *args,
            **kwargs
    ):
        super().__init__(*args, **kwargs)
        self.step_fn = step_fn
        self.last_step = last_step
        self.last_step_fn = last_step_fn
        self.w_scheduler = w_scheduler
        self.timeshift = timeshift
        self.guidance_interval_min = guidance_interval_min
        self.guidance_interval_max = guidance_interval_max
        self.t_eps = t_eps

        if self.last_step is None or self.num_steps == 1:
            self.last_step = 1.0 / self.num_steps

        timesteps = torch.linspace(0.0, 1 - self.last_step, self.num_steps)
        timesteps = torch.cat([timesteps, torch.tensor([1.0])], dim=0)
        self.timesteps = shift_respace_fn(timesteps, self.timeshift)

        assert self.last_step > 0.0
        assert self.scheduler is not None

    def _impl_sampling(self, net, noise, condition, uncondition, mask=None):
        """
        Sampling with mask conditioning.

        Args:
            net: Denoiser network
            noise: Initial noise [N, 3, H, W]
            condition: Mask embedding [N, hidden_size]
            uncondition: Null embedding [N, hidden_size]
            mask: Optional mask tensor [N, C, H, W] for direct conditioning

        Returns:
            x_trajs: List of intermediate samples
            v_trajs: List of velocity predictions
        """
        batch_size = noise.shape[0]
        steps = self.timesteps.to(noise.device, noise.dtype)

        # CFG: concatenate uncondition and condition
        # Note: For mask conditioning, we handle this differently
        x = noise
        x_trajs = [noise]
        v_trajs = []

        for i, (t_cur, t_next) in enumerate(zip(steps[:-1], steps[1:])):
            dt = t_next - t_cur
            t_cur_batch = t_cur.repeat(batch_size)

            sigma = self.scheduler.sigma(t_cur_batch)
            dalpha_over_alpha = self.scheduler.dalpha_over_alpha(t_cur_batch)
            dsigma_mul_sigma = self.scheduler.dsigma_mul_sigma(t_cur_batch)

            if self.w_scheduler:
                w = self.w_scheduler.w(t_cur_batch)
            else:
                w = 0.0

            # CFG forward pass
            cfg_x = torch.cat([x, x], dim=0)
            cfg_t = t_cur_batch.repeat(2)

            # For mask conditioning, we need to handle y (class label)
            # and pass mask separately to the model
            y_uncond = torch.zeros(batch_size, dtype=torch.long, device=noise.device)
            y_cond = torch.zeros(batch_size, dtype=torch.long, device=noise.device)
            cfg_y = torch.cat([y_uncond, y_cond], dim=0)

            if mask is not None:
                cfg_mask = torch.cat([
                    torch.zeros_like(mask),  # Unconditional: zero mask
                    mask                      # Conditional: actual mask
                ], dim=0)
                out = net(cfg_x, cfg_t, cfg_y, mask=cfg_mask)
            else:
                out = net(cfg_x, cfg_t, cfg_y, mask=None)

            # Convert x-prediction to velocity
            out = (out - cfg_x) / (1.0 - cfg_t.view(-1, 1, 1, 1)).clamp_min(self.t_eps)

            # Apply CFG
            if t_cur > self.guidance_interval_min and t_cur <= self.guidance_interval_max:
                out = self.guidance_fn(out, self.guidance)
            else:
                out = self.guidance_fn(out, 1.0)

            v = out
            s = ((1 / dalpha_over_alpha) * v - x) / (sigma ** 2 - (1 / dalpha_over_alpha) * dsigma_mul_sigma)

            if i < self.num_steps - 1:
                x = self.step_fn(x, v, dt, s=s, w=w)
            else:
                x = self.last_step_fn(x, v, dt, s=s, w=w)

            x_trajs.append(x)
            v_trajs.append(v)

        v_trajs.append(torch.zeros_like(x))
        return x_trajs, v_trajs


class HeunSamplerMedical(BaseSampler):
    """
    Heun sampler for mask-conditional medical image generation.
    Second-order ODE solver for better quality.
    """

    def __init__(
            self,
            scheduler: BaseScheduler = None,
            w_scheduler: BaseScheduler = None,
            exact_heun: bool = True,
            guidance_interval_min: float = 0.0,
            guidance_interval_max: float = 1.0,
            timeshift: float = 1.0,
            step_fn: Callable = ode_step_fn,
            last_step: float = None,
            last_step_fn: Callable = ode_step_fn,
            t_eps: float = 0.05,
            *args,
            **kwargs
    ):
        super().__init__(*args, **kwargs)
        self.scheduler = scheduler
        self.exact_heun = exact_heun
        self.step_fn = step_fn
        self.last_step = last_step
        self.last_step_fn = last_step_fn
        self.w_scheduler = w_scheduler
        self.timeshift = timeshift
        self.guidance_interval_min = guidance_interval_min
        self.guidance_interval_max = guidance_interval_max
        self.t_eps = t_eps

        if self.last_step is None or self.num_steps == 1:
            self.last_step = 1.0 / self.num_steps

        timesteps = torch.linspace(0.0, 1 - self.last_step, self.num_steps)
        timesteps = torch.cat([timesteps, torch.tensor([1.0])], dim=0)
        self.timesteps = shift_respace_fn(timesteps, self.timeshift)

        assert self.last_step > 0.0
        assert self.scheduler is not None

    def _forward_with_cfg(self, net, x, t, mask=None):
        """Forward pass with CFG for mask conditioning."""
        batch_size = x.shape[0] // 2

        y = torch.zeros(x.shape[0], dtype=torch.long, device=x.device)

        if mask is not None:
            out = net(x, t, y, mask=mask)
        else:
            out = net(x, t, y, mask=None)

        return out

    def _impl_sampling(self, net, noise, condition, uncondition, mask=None):
        """
        Heun sampling with mask conditioning.
        """
        batch_size = noise.shape[0]
        steps = self.timesteps.to(noise.device)

        x = noise
        v_hat, s_hat = 0.0, 0.0
        x_trajs = [noise]
        v_trajs = []

        for i, (t_cur, t_next) in enumerate(zip(steps[:-1], steps[1:])):
            dt = t_next - t_cur
            t_cur_batch = t_cur.repeat(batch_size)

            sigma = self.scheduler.sigma(t_cur_batch)
            alpha_over_dalpha = 1 / self.scheduler.dalpha_over_alpha(t_cur_batch)
            dsigma_mul_sigma = self.scheduler.dsigma_mul_sigma(t_cur_batch)

            t_hat = t_next.repeat(batch_size)
            sigma_hat = self.scheduler.sigma(t_hat)
            alpha_over_dalpha_hat = 1 / self.scheduler.dalpha_over_alpha(t_hat)
            dsigma_mul_sigma_hat = self.scheduler.dsigma_mul_sigma(t_hat)

            if self.w_scheduler:
                w = self.w_scheduler.w(t_cur_batch)
            else:
                w = 0.0

            if i == 0 or self.exact_heun:
                # First evaluation
                cfg_x = torch.cat([x, x], dim=0)
                cfg_t = t_cur_batch.repeat(2)

                if mask is not None:
                    cfg_mask = torch.cat([torch.zeros_like(mask), mask], dim=0)
                else:
                    cfg_mask = None

                out = self._forward_with_cfg(net, cfg_x, cfg_t, cfg_mask)
                out = (out - cfg_x) / (1.0 - cfg_t.view(-1, 1, 1, 1)).clamp_min(self.t_eps)

                if t_cur > self.guidance_interval_min and t_cur <= self.guidance_interval_max:
                    out = self.guidance_fn(out, self.guidance)
                else:
                    out = self.guidance_fn(out, 1.0)

                v = out
                s = (alpha_over_dalpha * v - x) / (sigma ** 2 - alpha_over_dalpha * dsigma_mul_sigma)
            else:
                v = v_hat
                s = s_hat

            x_hat = self.step_fn(x, v, dt, s=s, w=w)

            # Heun correction
            if i < self.num_steps - 1:
                cfg_x_hat = torch.cat([x_hat, x_hat], dim=0)
                cfg_t_hat = t_hat.repeat(2)

                if mask is not None:
                    cfg_mask = torch.cat([torch.zeros_like(mask), mask], dim=0)
                else:
                    cfg_mask = None

                out = self._forward_with_cfg(net, cfg_x_hat, cfg_t_hat, cfg_mask)
                out = (out - cfg_x_hat) / (1.0 - cfg_t_hat.view(-1, 1, 1, 1)).clamp_min(self.t_eps)

                if t_cur > self.guidance_interval_min and t_cur <= self.guidance_interval_max:
                    out = self.guidance_fn(out, self.guidance)
                else:
                    out = self.guidance_fn(out, 1.0)

                v_hat = out
                s_hat = (alpha_over_dalpha_hat * v_hat - x_hat) / (sigma_hat ** 2 - alpha_over_dalpha_hat * dsigma_mul_sigma_hat)
                v = (v + v_hat) / 2
                s = (s + s_hat) / 2
                x = self.step_fn(x, v, dt, s=s, w=w)
            else:
                x = self.last_step_fn(x, v, dt, s=s, w=w)

            x_trajs.append(x)
            v_trajs.append(v)

        v_trajs.append(torch.zeros_like(x))
        return x_trajs, v_trajs