tan200224 commited on
Commit
e674b93
·
verified ·
1 Parent(s): fa6ba40

Add model.py

Browse files
Files changed (1) hide show
  1. model.py +334 -0
model.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import numpy as np
4
+ from tqdm import tqdm
5
+
6
+ class GaussianFourierProjection(nn.Module):
7
+ """Gaussian random features for encoding time steps."""
8
+ def __init__(self, embed_dim, scale=30.):
9
+ super().__init__()
10
+ # Randomly sample weights (frequencies) during initialization.
11
+ # These weights (frequencies) are fixed during optimization and are not trainable.
12
+ self.W = nn.Parameter(torch.randn(embed_dim // 2) * scale, requires_grad=False)
13
+
14
+ def forward(self, x):
15
+ # Cosine(2 pi freq x), Sine(2 pi freq x)
16
+ x_proj = x[:, None] * self.W[None, :] * 2 * np.pi
17
+ return torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1)
18
+
19
+
20
+ class Dense(nn.Module):
21
+ """
22
+ Maps an embedding vector to a bias/scale tensor that can be broadcast over a
23
+ 2-D feature map (B, C, H, W) – output shape is (B, C, 1, 1).
24
+ """
25
+ def __init__(self, input_dim: int, output_dim: int):
26
+ super().__init__()
27
+ self.dense = nn.Linear(input_dim, output_dim)
28
+
29
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
30
+ B = x.size(0)
31
+ x = x.view(B, -1) # (B, input_dim)
32
+ return self.dense(x).view(B, -1, 1, 1) # (B, C, 1, 1)
33
+
34
+
35
+ class UNet(nn.Module):
36
+ """A time-dependent score-based model built upon U-Net architecture."""
37
+
38
+ def __init__(self, marginal_prob_std, channels=[32, 64, 128, 256, 512], embed_dim=256,
39
+ embed_dim_mask=256, input_dim_mask=4*256*256):
40
+ """Initialize a time-dependent score-based network.
41
+
42
+ Args:
43
+ marginal_prob_std: A function that takes time t and gives the standard
44
+ deviation of the perturbation kernel p_{0t}(x(t) | x(0)).
45
+ channels: The number of channels for feature maps of each resolution.
46
+ embed_dim: The dimensionality of Gaussian random feature embeddings.
47
+ """
48
+ super().__init__()
49
+ # Gaussian random feature embedding layer for time
50
+ self.time_embed = nn.Sequential(
51
+ GaussianFourierProjection(embed_dim=embed_dim),
52
+ nn.Linear(embed_dim, embed_dim)
53
+ )
54
+
55
+ # flatten the mask and apply a linear layer
56
+ self.cond_embed = nn.Sequential(
57
+ nn.Flatten(),
58
+ nn.Linear(input_dim_mask, embed_dim_mask)
59
+ )
60
+
61
+ # Encoding layers where the resolution decreases
62
+ self.conv1 = nn.Conv2d(4, channels[0], 3, stride=2, bias=False, padding=1)
63
+ self.t_mod1 = Dense(embed_dim, channels[0])
64
+ self.gnorm1 = nn.GroupNorm(4, num_channels=channels[0])
65
+
66
+ self.conv1a = nn.Conv2d(channels[0], channels[0], 3, stride=1, bias=False, padding=1)
67
+ self.t_mod1a = Dense(embed_dim, channels[0])
68
+ self.gnorm1a = nn.GroupNorm(4, num_channels=channels[0])
69
+
70
+ self.conv2 = nn.Conv2d(channels[0], channels[1], 3, stride=2, bias=False, padding=1)
71
+ self.t_mod2 = Dense(embed_dim, channels[1])
72
+ self.y_mod2 = Dense(embed_dim, channels[1])
73
+ self.gnorm2 = nn.GroupNorm(32, num_channels=channels[1])
74
+
75
+ self.conv2a = nn.Conv2d(channels[1], channels[1], 3, stride=1, bias=False, padding=1)
76
+ self.t_mod2a = Dense(embed_dim, channels[1])
77
+ self.y_mod2a = Dense(embed_dim, channels[1])
78
+ self.gnorm2a = nn.GroupNorm(32, num_channels=channels[1])
79
+
80
+ self.conv3 = nn.Conv2d(channels[1], channels[2], 3, stride=2, bias=False, padding=1)
81
+ self.t_mod3 = Dense(embed_dim, channels[2])
82
+ self.y_mod3 = Dense(embed_dim, channels[2])
83
+ self.gnorm3 = nn.GroupNorm(32, num_channels=channels[2])
84
+
85
+ self.conv3a = nn.Conv2d(channels[2], channels[2], 3, stride=1, bias=False, padding=1)
86
+ self.t_mod3a = Dense(embed_dim, channels[2])
87
+ self.y_mod3a = Dense(embed_dim, channels[2])
88
+ self.gnorm3a = nn.GroupNorm(32, num_channels=channels[2])
89
+
90
+ self.conv4 = nn.Conv2d(channels[2], channels[3], 3, stride=2, bias=False, padding=1)
91
+ self.t_mod4 = Dense(embed_dim, channels[3])
92
+ self.y_mod4 = Dense(embed_dim, channels[3])
93
+ self.gnorm4 = nn.GroupNorm(32, num_channels=channels[3])
94
+
95
+ self.conv4a = nn.Conv2d(channels[3], channels[3], 3, stride=1, bias=False, padding=1)
96
+ self.t_mod4a = Dense(embed_dim, channels[3])
97
+ self.y_mod4a = Dense(embed_dim, channels[3])
98
+ self.gnorm4a = nn.GroupNorm(32, num_channels=channels[3])
99
+
100
+ self.conv5 = nn.Conv2d(channels[3], channels[4], 3, stride=2, bias=False, padding=1)
101
+ self.t_mod5 = Dense(embed_dim, channels[4])
102
+ self.y_mod5 = Dense(embed_dim, channels[4])
103
+ self.gnorm5 = nn.GroupNorm(32, num_channels=channels[4])
104
+
105
+ self.conv5a = nn.Conv2d(channels[4], channels[4], 3, stride=1, bias=False, padding=1)
106
+ self.t_mod5a = Dense(embed_dim, channels[4])
107
+ self.y_mod5a = Dense(embed_dim, channels[4])
108
+ self.gnorm5a = nn.GroupNorm(32, num_channels=channels[4])
109
+
110
+ # Decoding layers where the resolution increases
111
+ self.tconv5b = nn.Conv2d(channels[4], channels[4], 3, stride=1, bias=False, padding=1)
112
+ self.t_mod6b = Dense(embed_dim, channels[4])
113
+ self.y_mod6b = Dense(embed_dim, channels[4])
114
+ self.tgnorm5b = nn.GroupNorm(32, num_channels=channels[4])
115
+
116
+ self.tconv5 = nn.ConvTranspose2d(2*channels[4], channels[3], 3, stride=2, bias=False, padding=1, output_padding=1)
117
+ self.t_mod6 = Dense(embed_dim, channels[3])
118
+ self.y_mod6 = Dense(embed_dim, channels[3])
119
+ self.tgnorm5 = nn.GroupNorm(32, num_channels=channels[3])
120
+
121
+ self.tconv4b = nn.Conv2d(2*channels[3], channels[3], 3, stride=1, bias=False, padding=1)
122
+ self.t_mod7b = Dense(embed_dim, channels[3])
123
+ self.y_mod7b = Dense(embed_dim, channels[3])
124
+ self.tgnorm4b = nn.GroupNorm(32, num_channels=channels[3])
125
+
126
+ self.tconv4 = nn.ConvTranspose2d(2*channels[3], channels[2], 3, stride=2, bias=False, padding=1, output_padding=1)
127
+ self.t_mod7 = Dense(embed_dim, channels[2])
128
+ self.y_mod7 = Dense(embed_dim, channels[2])
129
+ self.tgnorm4 = nn.GroupNorm(32, num_channels=channels[2])
130
+
131
+ self.tconv3b = nn.Conv2d(2*channels[2], channels[2], 3, stride=1, bias=False, padding=1)
132
+ self.t_mod8b = Dense(embed_dim, channels[2])
133
+ self.y_mod8b = Dense(embed_dim, channels[2])
134
+ self.tgnorm3b = nn.GroupNorm(32, num_channels=channels[2])
135
+
136
+ self.tconv3 = nn.ConvTranspose2d(2*channels[2], channels[1], 3, stride=2, bias=False, padding=1, output_padding=1)
137
+ self.t_mod8 = Dense(embed_dim, channels[1])
138
+ self.y_mod8 = Dense(embed_dim, channels[1])
139
+ self.tgnorm3 = nn.GroupNorm(32, num_channels=channels[1])
140
+
141
+ self.tconv2b = nn.Conv2d(2*channels[1], channels[1], 3, stride=1, bias=False, padding=1)
142
+ self.t_mod9b = Dense(embed_dim, channels[1])
143
+ self.y_mod9b = Dense(embed_dim, channels[1])
144
+ self.tgnorm2b = nn.GroupNorm(32, num_channels=channels[1])
145
+
146
+ self.tconv2 = nn.ConvTranspose2d(2*channels[1], channels[0], 3, stride=2, bias=False, padding=1, output_padding=1)
147
+ self.t_mod9 = Dense(embed_dim, channels[0])
148
+ self.y_mod9 = Dense(embed_dim, channels[0])
149
+ self.tgnorm2 = nn.GroupNorm(32, num_channels=channels[0])
150
+
151
+ self.tconv1b = nn.Conv2d(2*channels[0], channels[0], 3, stride=1, bias=False, padding=1)
152
+ self.t_mod10b = Dense(embed_dim, channels[0])
153
+ self.y_mod10b = Dense(embed_dim, channels[0])
154
+ self.tgnorm1b = nn.GroupNorm(32, num_channels=channels[0])
155
+
156
+ self.tconv1 = nn.ConvTranspose2d(2*channels[0], channels[0], 3, stride=2, bias=False, padding=1, output_padding=1)
157
+ self.t_mod10 = Dense(embed_dim, channels[0])
158
+ self.y_mod10 = Dense(embed_dim, channels[0])
159
+ self.tgnorm1 = nn.GroupNorm(32, num_channels=channels[0])
160
+
161
+ self.tconv0 = nn.ConvTranspose2d(channels[0], 4, 3, stride=1, padding=1, output_padding=0)
162
+
163
+ # The swish activation function
164
+ self.act = nn.SiLU()
165
+ # A restricted version of the `marginal_prob_std` function, after specifying a Lambda.
166
+ self.marginal_prob_std = marginal_prob_std
167
+
168
+ def forward(self, x, t, y=None):
169
+ # Obtain the Gaussian random feature embedding for t
170
+ embed = self.act(self.time_embed(t))
171
+ y_embed = self.cond_embed(y)
172
+
173
+ # Encoding path, downsampling
174
+ h1 = self.conv1(x) + self.t_mod1(embed)
175
+ h1 = self.act(self.gnorm1(h1))
176
+
177
+ h1a = self.conv1a(h1) + self.t_mod1a(embed)
178
+ h1a = self.act(self.gnorm1a(h1a))
179
+
180
+ # 2nd conv
181
+ h2 = self.conv2(h1a) + self.t_mod2(embed)
182
+ h2 = h2 * self.y_mod2(y_embed)
183
+ h2 = self.act(self.gnorm2(h2))
184
+
185
+ h2a = self.conv2a(h2) + self.t_mod2a(embed)
186
+ h2a = h2a * self.y_mod2a(y_embed)
187
+ h2a = self.act(self.gnorm2a(h2a))
188
+
189
+ # 3rd conv
190
+ h3 = self.conv3(h2a) + self.t_mod3(embed)
191
+ h3 = h3 * self.y_mod3(y_embed)
192
+ h3 = self.act(self.gnorm3(h3))
193
+
194
+ h3a = self.conv3a(h3) + self.t_mod3a(embed)
195
+ h3a = h3a * self.y_mod3a(y_embed)
196
+ h3a = self.act(self.gnorm3a(h3a))
197
+
198
+ # 4th conv
199
+ h4 = self.conv4(h3a) + self.t_mod4(embed)
200
+ h4 = h4 * self.y_mod4(y_embed)
201
+ h4 = self.act(self.gnorm4(h4))
202
+
203
+ h4a = self.conv4a(h4) + self.t_mod4a(embed)
204
+ h4a = h4a * self.y_mod4a(y_embed)
205
+ h4a = self.act(self.gnorm4a(h4a))
206
+
207
+ # 5th conv
208
+ h5 = self.conv5(h4a) + self.t_mod5(embed)
209
+ h5 = h5 * self.y_mod5(y_embed)
210
+ h5 = self.act(self.gnorm5(h5))
211
+
212
+ h5a = self.conv5a(h5) + self.t_mod5a(embed)
213
+ h5a = h5a * self.y_mod5a(y_embed)
214
+ h5a = self.act(self.gnorm5a(h5a))
215
+
216
+ # Decoding path up sampling
217
+ h = self.tconv5b(h5a) + self.t_mod6b(embed)
218
+ h = h * self.y_mod5(y_embed)
219
+ h = self.act(self.tgnorm5b(h))
220
+
221
+ # Skip connection from the encoding path
222
+ h = self.tconv5(torch.cat([h, h5], dim=1)) + self.t_mod6(embed)
223
+ h = h * self.y_mod6(y_embed)
224
+ h = self.act(self.tgnorm5(h))
225
+
226
+ h = self.tconv4b(torch.cat([h, h4a], dim=1)) + self.t_mod7b(embed)
227
+ h = h * self.y_mod7b(y_embed)
228
+ h = self.act(self.tgnorm4b(h))
229
+
230
+ h = self.tconv4(torch.cat([h, h4], dim=1)) + self.t_mod7(embed)
231
+ h = h * self.y_mod7(y_embed)
232
+ h = self.act(self.tgnorm4(h))
233
+
234
+ h = self.tconv3b(torch.cat([h, h3a], dim=1)) + self.t_mod8b(embed)
235
+ h = h * self.y_mod8b(y_embed)
236
+ h = self.act(self.tgnorm3b(h))
237
+
238
+ h = self.tconv3(torch.cat([h, h3], dim=1)) + self.t_mod8(embed)
239
+ h = h * self.y_mod8(y_embed)
240
+ h = self.act(self.tgnorm3(h))
241
+
242
+ h = self.tconv2b(torch.cat([h, h2a], dim=1)) + self.t_mod9b(embed)
243
+ h = h * self.y_mod9b(y_embed)
244
+ h = self.act(self.tgnorm2b(h))
245
+
246
+ h = self.tconv2(torch.cat([h, h2], dim=1)) + self.t_mod9(embed)
247
+ h = h * self.y_mod9(y_embed)
248
+ h = self.act(self.tgnorm2(h))
249
+
250
+ h = self.tconv1b(torch.cat([h, h1a], dim=1)) + self.t_mod10b(embed)
251
+ h = h * self.y_mod10b(y_embed)
252
+ h = self.act(self.tgnorm1b(h))
253
+
254
+ h = self.tconv1(torch.cat([h, h1], dim=1)) + self.t_mod10(embed)
255
+ h = h * self.y_mod10(y_embed)
256
+ h = self.act(self.tgnorm1(h))
257
+
258
+ h = self.tconv0(h)
259
+
260
+ # Normalize output
261
+ h = h / self.marginal_prob_std(t)[:, None, None, None]
262
+
263
+ return h
264
+
265
+
266
+ def marginal_prob_std(t, Lambda, device='cpu'):
267
+ """Compute the standard deviation of $p_{0t}(x(t) | x(0))$.
268
+
269
+ Args:
270
+ t: A vector of time steps.
271
+ Lambda: The $\lambda$ in our SDE.
272
+
273
+ Returns:
274
+ std : The standard deviation.
275
+ """
276
+ t = t.to(device)
277
+ std = torch.sqrt((Lambda**(2 * t) - 1.) / 2. / np.log(Lambda))
278
+ return std
279
+
280
+
281
+ def diffusion_coeff(t, Lambda, device='cpu'):
282
+ """Compute the diffusion coefficient of our SDE.
283
+
284
+ Args:
285
+ t: A vector of time steps.
286
+ Lambda: The $\lambda$ in our SDE.
287
+
288
+ Returns:
289
+ diff_coeff : The vector of diffusion coefficients.
290
+ """
291
+ diff_coeff = Lambda**t
292
+ return diff_coeff.to(device)
293
+
294
+
295
+ def Euler_Maruyama_sampler(score_model,
296
+ marginal_prob_std,
297
+ diffusion_coeff,
298
+ batch_size=1,
299
+ x_shape=(4, 256, 256),
300
+ num_steps=250,
301
+ device='cuda',
302
+ eps=1e-3,
303
+ y=None):
304
+ """Generate samples from score-based models with the Euler-Maruyama solver.
305
+
306
+ Args:
307
+ score_model: A PyTorch model that represents the time-dependent score-based model.
308
+ marginal_prob_std: A function that gives the standard deviation of
309
+ the perturbation kernel.
310
+ diffusion_coeff: A function that gives the diffusion coefficient of the SDE.
311
+ batch_size: The number of samplers to generate by calling this function once.
312
+ num_steps: The number of sampling steps.
313
+ Equivalent to the number of discretized time steps.
314
+ device: 'cuda' for running on GPUs, and 'cpu' for running on CPUs.
315
+ eps: The smallest time step for numerical stability.
316
+
317
+ Returns:
318
+ Samples.
319
+ """
320
+ t = torch.ones(batch_size).to(device)
321
+ r = torch.randn(batch_size, *x_shape).to(device)
322
+ init_x = r * marginal_prob_std(t)[:, None, None, None]
323
+ init_x = init_x.to(device)
324
+ time_steps = torch.linspace(1., eps, num_steps).to(device)
325
+ step_size = time_steps[0] - time_steps[1]
326
+ x = init_x
327
+ with torch.no_grad():
328
+ for time_step in tqdm(time_steps):
329
+ batch_time_step = torch.ones(batch_size, device=device) * time_step
330
+ g = diffusion_coeff(batch_time_step)
331
+ mean_x = x + (g**2)[:, None, None, None] * score_model(x, batch_time_step, y=y) * step_size
332
+ x = mean_x + torch.sqrt(step_size) * g[:, None, None, None] * torch.randn_like(x)
333
+ # Do not include any noise in the last sampling step.
334
+ return mean_x