Wuhuwill commited on
Commit
5c103a6
·
verified ·
1 Parent(s): 0b89c2a

Upload ProDiff/Experiments/trajectory_exp_may_data_TKY_len3_ddpm_20250724-100624/code_snapshot/Diffusion.py with huggingface_hub

Browse files
ProDiff/Experiments/trajectory_exp_may_data_TKY_len3_ddpm_20250724-100624/code_snapshot/Diffusion.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ import numpy as np
5
+ import torch.nn.functional as F
6
+
7
+ def get_timestep_embedding(timesteps, embedding_dim):
8
+ """Build sinusoidal timestep embeddings.
9
+
10
+ Args:
11
+ timesteps (torch.Tensor): A 1-D Tensor of N timesteps.
12
+ embedding_dim (int): The dimension of the embedding.
13
+
14
+ Returns:
15
+ torch.Tensor: N x embedding_dim Tensor of positional embeddings.
16
+ """
17
+ assert len(timesteps.shape) == 1
18
+
19
+ half_dim = embedding_dim // 2
20
+ emb = np.log(10000) / (half_dim - 1)
21
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
22
+ emb = emb.cuda() # Move embedding to CUDA device
23
+ emb = timesteps.float()[:, None] * emb[None, :]
24
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
25
+ if embedding_dim % 2 == 1: # Zero pad if embedding_dim is odd
26
+ emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
27
+ return emb
28
+
29
+ class Attention(nn.Module):
30
+ """A simple attention layer to get weights for attributes."""
31
+ def __init__(self, embedding_dim):
32
+ super(Attention, self).__init__()
33
+ self.fc = nn.Linear(embedding_dim, 1)
34
+
35
+ def forward(self, x):
36
+ # x shape: (batch_size, num_attributes, embedding_dim)
37
+ weights = self.fc(x) # shape: (batch_size, num_attributes, 1)
38
+ # Apply softmax along the attributes dimension to get attention weights.
39
+ weights = F.softmax(weights, dim=1)
40
+ return weights
41
+
42
+ class WideAndDeep(nn.Module):
43
+ """Network to combine attribute (start/end points) and prototype embeddings."""
44
+ def __init__(self, in_channels, embedding_dim=512):
45
+ super(WideAndDeep, self).__init__()
46
+
47
+ # Process start point and end point independently
48
+ self.start_fc1 = nn.Linear(in_channels, embedding_dim)
49
+ self.start_fc2 = nn.Linear(embedding_dim, embedding_dim)
50
+
51
+ self.end_fc1 = nn.Linear(in_channels, embedding_dim)
52
+ self.end_fc2 = nn.Linear(embedding_dim, embedding_dim)
53
+
54
+ # Process prototype features
55
+ self.prototype_fc1 = nn.Linear(512, embedding_dim)
56
+ self.prototype_fc2 = nn.Linear(embedding_dim, embedding_dim)
57
+
58
+ self.relu = nn.ReLU()
59
+
60
+ def forward(self, attr, prototype):
61
+ # attr shape: (batch_size, num_features, traj_length)
62
+ # prototype shape: (batch_size, prototype_embedding_dim) - assuming N_CLUSTER is handled before or it's single prototype
63
+ start_point = attr[:, :, 0].float() # First point in trajectory features
64
+ end_point = attr[:, :, -1].float() # Last point in trajectory features
65
+
66
+ # Process start point features
67
+ start_x = self.start_fc1(start_point)
68
+ start_x = self.relu(start_x)
69
+ start_embed = self.start_fc2(start_x)
70
+
71
+ # Process end point features
72
+ end_x = self.end_fc1(end_point)
73
+ end_x = self.relu(end_x)
74
+ end_embed = self.end_fc2(end_x)
75
+
76
+ # Combine the processed start and end point features
77
+ attr_embed = start_embed + end_embed
78
+
79
+ # Process prototype features
80
+ proto_x = self.prototype_fc1(prototype)
81
+ proto_x = self.relu(proto_x)
82
+ proto_embed = self.prototype_fc2(proto_x)
83
+
84
+ # Combine the processed attribute and prototype features
85
+ combined_embed = attr_embed + proto_embed # Simple addition for combination
86
+
87
+ return combined_embed
88
+
89
+
90
+ def nonlinearity(x):
91
+ # Swish activation function (SiLU)
92
+ return x * torch.sigmoid(x)
93
+
94
+ def Normalize(in_channels):
95
+ """Group normalization."""
96
+ return torch.nn.GroupNorm(num_groups=32,
97
+ num_channels=in_channels,
98
+ eps=1e-6,
99
+ affine=True)
100
+
101
+ class Upsample(nn.Module):
102
+ """Upsampling layer, optionally with a 1D convolution."""
103
+ def __init__(self, in_channels, with_conv=True):
104
+ super().__init__()
105
+ self.with_conv = with_conv
106
+ if self.with_conv:
107
+ self.conv = torch.nn.Conv1d(in_channels,
108
+ in_channels,
109
+ kernel_size=3,
110
+ stride=1,
111
+ padding=1)
112
+
113
+ def forward(self, x):
114
+ x = torch.nn.functional.interpolate(x,
115
+ scale_factor=2.0,
116
+ mode="nearest") # Upsample using nearest neighbor
117
+ if self.with_conv:
118
+ x = self.conv(x)
119
+ return x
120
+
121
+
122
+ class Downsample(nn.Module):
123
+ """Downsampling layer, optionally with a 1D convolution."""
124
+ def __init__(self, in_channels, with_conv=True):
125
+ super().__init__()
126
+ self.with_conv = with_conv
127
+ if self.with_conv:
128
+ # No asymmetric padding in torch.nn.Conv1d, must do it ourselves via F.pad.
129
+ self.conv = torch.nn.Conv1d(in_channels,
130
+ in_channels,
131
+ kernel_size=3,
132
+ stride=2,
133
+ padding=0)
134
+
135
+ def forward(self, x):
136
+ if self.with_conv:
137
+ pad = (1, 1) # Padding for kernel_size=3, stride=2 to maintain roughly half size
138
+ x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
139
+ x = self.conv(x)
140
+ else:
141
+ x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2) # Avg pool if no conv
142
+ return x
143
+
144
+
145
+ class ResnetBlock(nn.Module):
146
+ """Residual block for the U-Net."""
147
+ def __init__(self,
148
+ in_channels,
149
+ out_channels=None,
150
+ conv_shortcut=False,
151
+ dropout=0.1,
152
+ temb_channels=512):
153
+ super().__init__()
154
+ self.in_channels = in_channels
155
+ out_channels = in_channels if out_channels is None else out_channels
156
+ self.out_channels = out_channels
157
+ self.use_conv_shortcut = conv_shortcut
158
+
159
+ self.norm1 = Normalize(in_channels)
160
+ self.conv1 = torch.nn.Conv1d(in_channels,
161
+ out_channels,
162
+ kernel_size=3,
163
+ stride=1,
164
+ padding=1)
165
+ self.temb_proj = torch.nn.Linear(temb_channels, out_channels)
166
+ self.norm2 = Normalize(out_channels)
167
+ self.dropout = torch.nn.Dropout(dropout)
168
+ self.conv2 = torch.nn.Conv1d(out_channels,
169
+ out_channels,
170
+ kernel_size=3,
171
+ stride=1,
172
+ padding=1)
173
+ if self.in_channels != self.out_channels:
174
+ if self.use_conv_shortcut:
175
+ self.conv_shortcut = torch.nn.Conv1d(in_channels,
176
+ out_channels,
177
+ kernel_size=3, # Convolutional shortcut
178
+ stride=1,
179
+ padding=1)
180
+ else:
181
+ self.nin_shortcut = torch.nn.Conv1d(in_channels,
182
+ out_channels,
183
+ kernel_size=1, # 1x1 convolution (Network-in-Network) shortcut
184
+ stride=1,
185
+ padding=0)
186
+
187
+ def forward(self, x, temb):
188
+ h = x
189
+ h = self.norm1(h)
190
+ h = nonlinearity(h)
191
+ h = self.conv1(h)
192
+ h = h + self.temb_proj(nonlinearity(temb))[:, :, None]
193
+ h = self.norm2(h)
194
+ h = nonlinearity(h)
195
+ h = self.dropout(h)
196
+ h = self.conv2(h)
197
+
198
+ if self.in_channels != self.out_channels:
199
+ if self.use_conv_shortcut:
200
+ x = self.conv_shortcut(x)
201
+ else:
202
+ x = self.nin_shortcut(x)
203
+
204
+ return x + h
205
+
206
+
207
+ class AttnBlock(nn.Module):
208
+ """Self-attention block for the U-Net."""
209
+ def __init__(self, in_channels):
210
+ super().__init__()
211
+ self.in_channels = in_channels
212
+
213
+ self.norm = Normalize(in_channels)
214
+ self.q = torch.nn.Conv1d(in_channels,
215
+ in_channels,
216
+ kernel_size=1,
217
+ stride=1,
218
+ padding=0)
219
+ self.k = torch.nn.Conv1d(in_channels,
220
+ in_channels,
221
+ kernel_size=1,
222
+ stride=1,
223
+ padding=0)
224
+ self.v = torch.nn.Conv1d(in_channels,
225
+ in_channels,
226
+ kernel_size=1,
227
+ stride=1,
228
+ padding=0)
229
+ self.proj_out = torch.nn.Conv1d(in_channels,
230
+ in_channels,
231
+ kernel_size=1,
232
+ stride=1,
233
+ padding=0)
234
+
235
+ def forward(self, x):
236
+ h_ = x
237
+ h_ = self.norm(h_)
238
+ q = self.q(h_) # Query
239
+ k = self.k(h_) # Key
240
+ v = self.v(h_) # Value
241
+ b, c, w = q.shape
242
+ q = q.permute(0, 2, 1) # b,w,c (sequence_length, channels)
243
+ w_ = torch.bmm(q, k) # b,w,w (attention scores: q @ k.T)
244
+ w_ = w_ * (int(c)**(-0.5)) # Scale by sqrt(channel_dim)
245
+ w_ = torch.nn.functional.softmax(w_, dim=2) # Softmax over scores
246
+ # attend to values
247
+ w_ = w_.permute(0, 2, 1) # b,w,w (transpose back for v @ w_ if v is b,c,w)
248
+ h_ = torch.bmm(v, w_) # Weighted sum of values
249
+ h_ = h_.reshape(b, c, w)
250
+
251
+ h_ = self.proj_out(h_)
252
+
253
+ return x + h_ # Add residual connection
254
+
255
+
256
+ class Model(nn.Module):
257
+ """The core U-Net model for the diffusion process."""
258
+ def __init__(self, config):
259
+ super(Model, self).__init__()
260
+ self.config = config
261
+ ch, out_ch, ch_mult = config.model.ch, config.model.out_ch, tuple(config.model.ch_mult)
262
+ num_res_blocks = config.model.num_res_blocks
263
+ attn_resolutions = config.model.attn_resolutions
264
+ dropout = config.model.dropout
265
+ in_channels = config.model.in_channels
266
+ resolution = config.data.traj_length
267
+ resamp_with_conv = config.model.resamp_with_conv
268
+ num_timesteps = config.diffusion.num_diffusion_timesteps
269
+
270
+ if config.model.type == 'bayesian':
271
+ self.logvar = nn.Parameter(torch.zeros(num_timesteps))
272
+
273
+ self.ch = ch
274
+ self.temb_ch = self.ch * 4
275
+ self.num_resolutions = len(ch_mult)
276
+ self.num_res_blocks = num_res_blocks
277
+ self.resolution = resolution
278
+ self.in_channels = in_channels
279
+
280
+ # timestep embedding
281
+ self.temb = nn.Module()
282
+ self.temb.dense = nn.ModuleList([
283
+ torch.nn.Linear(self.ch, self.temb_ch),
284
+ torch.nn.Linear(self.temb_ch, self.temb_ch),
285
+ ])
286
+
287
+ # downsampling
288
+ self.conv_in = torch.nn.Conv1d(in_channels, # in_channels related to embedding_dim, not traj_length. Input format (batch_size, embedding_dim, traj_length)
289
+ self.ch,
290
+ kernel_size=3,
291
+ stride=1,
292
+ padding=1)
293
+
294
+ curr_res = resolution
295
+ in_ch_mult = (1, ) + ch_mult
296
+ self.down = nn.ModuleList()
297
+ block_in = None
298
+ for i_level in range(self.num_resolutions):
299
+ block = nn.ModuleList()
300
+ attn = nn.ModuleList()
301
+ block_in = ch * in_ch_mult[i_level]
302
+ block_out = ch * ch_mult[i_level]
303
+ for i_block in range(self.num_res_blocks):
304
+ block.append(
305
+ ResnetBlock(in_channels=block_in,
306
+ out_channels=block_out,
307
+ temb_channels=self.temb_ch,
308
+ dropout=dropout))
309
+ block_in = block_out
310
+ if curr_res in attn_resolutions:
311
+ attn.append(AttnBlock(block_in))
312
+ down = nn.Module()
313
+ down.block = block
314
+ down.attn = attn
315
+ if i_level != self.num_resolutions - 1:
316
+ down.downsample = Downsample(block_in, resamp_with_conv)
317
+ curr_res = curr_res // 2
318
+ self.down.append(down)
319
+
320
+ # middle block
321
+ self.mid = nn.Module()
322
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
323
+ out_channels=block_in,
324
+ temb_channels=self.temb_ch,
325
+ dropout=dropout)
326
+ self.mid.attn_1 = AttnBlock(block_in)
327
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
328
+ out_channels=block_in,
329
+ temb_channels=self.temb_ch,
330
+ dropout=dropout)
331
+
332
+ # upsampling
333
+ self.up = nn.ModuleList()
334
+ for i_level in reversed(range(self.num_resolutions)):
335
+ block = nn.ModuleList()
336
+ attn = nn.ModuleList()
337
+ block_out = ch * ch_mult[i_level]
338
+ skip_in = ch * ch_mult[i_level]
339
+ for i_block in range(self.num_res_blocks + 1):
340
+ if i_block == self.num_res_blocks:
341
+ skip_in = ch * in_ch_mult[i_level]
342
+ block.append(
343
+ ResnetBlock(in_channels=block_in + skip_in,
344
+ out_channels=block_out,
345
+ temb_channels=self.temb_ch,
346
+ dropout=dropout))
347
+ block_in = block_out
348
+ if curr_res in attn_resolutions:
349
+ attn.append(AttnBlock(block_in))
350
+ up = nn.Module()
351
+ up.block = block
352
+ up.attn = attn
353
+ if i_level != 0:
354
+ up.upsample = Upsample(block_in, resamp_with_conv)
355
+ curr_res = curr_res * 2
356
+ self.up.insert(0, up) # Prepend to get consistent order for upsampling path
357
+
358
+ # end
359
+ self.norm_out = Normalize(block_in)
360
+ self.conv_out = torch.nn.Conv1d(block_in,
361
+ out_ch,
362
+ kernel_size=3,
363
+ stride=1,
364
+ padding=1)
365
+
366
+ def forward(self, x, t, extra_embed=None):
367
+ assert x.shape[2] == self.resolution # Ensure input trajectory length matches model resolution
368
+
369
+ # timestep embedding
370
+ temb = get_timestep_embedding(t, self.ch)
371
+ temb = self.temb.dense[0](temb)
372
+ temb = nonlinearity(temb)
373
+ temb = self.temb.dense[1](temb)
374
+ if extra_embed is not None:
375
+ temb = temb + extra_embed
376
+
377
+ # downsampling
378
+ hs = [self.conv_in(x)] # List to store hidden states for skip connections
379
+ # print(hs[-1].shape)
380
+ for i_level in range(self.num_resolutions):
381
+ for i_block in range(self.num_res_blocks):
382
+ h = self.down[i_level].block[i_block](hs[-1], temb)
383
+ # print(i_level, i_block, h.shape)
384
+ if len(self.down[i_level].attn) > 0:
385
+ h = self.down[i_level].attn[i_block](h)
386
+ hs.append(h)
387
+ if i_level != self.num_resolutions - 1:
388
+ hs.append(self.down[i_level].downsample(hs[-1]))
389
+
390
+ # middle
391
+ # print(hs[-1].shape)
392
+ # print(len(hs))
393
+ h = hs[-1] # Last hidden state from downsampling path
394
+ h = self.mid.block_1(h, temb)
395
+ h = self.mid.attn_1(h)
396
+ h = self.mid.block_2(h, temb)
397
+ # print(h.shape)
398
+ # upsampling
399
+ for i_level in reversed(range(self.num_resolutions)):
400
+ for i_block in range(self.num_res_blocks + 1):
401
+ ht = hs.pop() # Get corresponding hidden state from downsampling path
402
+ if ht.size(-1) != h.size(-1):
403
+ # Pad if spatial dimensions do not match (can happen with odd resolutions)
404
+ h = torch.nn.functional.pad(h,
405
+ (0, ht.size(-1) - h.size(-1)))
406
+ h = self.up[i_level].block[i_block](torch.cat([h, ht], dim=1), # Concatenate skip connection
407
+ temb)
408
+ # print(i_level, i_block, h.shape)
409
+ if len(self.up[i_level].attn) > 0:
410
+ h = self.up[i_level].attn[i_block](h)
411
+ if i_level != 0:
412
+ h = self.up[i_level].upsample(h)
413
+
414
+ # end
415
+ h = self.norm_out(h)
416
+ h = nonlinearity(h)
417
+ h = self.conv_out(h)
418
+ return h
419
+
420
+ class Guide_UNet(nn.Module):
421
+ """A U-Net model guided by attribute and prototype embeddings."""
422
+ def __init__(self, config):
423
+ super(Guide_UNet, self).__init__()
424
+ self.config = config
425
+ self.in_channels = config.model.in_channels
426
+ self.ch = config.model.ch * 4
427
+ self.attr_dim = config.model.attr_dim
428
+ self.guidance_scale = config.model.guidance_scale
429
+ self.unet = Model(config)
430
+ self.guide_emb = WideAndDeep(self.in_channels, self.ch)
431
+ self.place_emb = WideAndDeep(self.in_channels, self.ch)
432
+
433
+ def forward(self, x, t, attr, prototype):
434
+ guide_emb = self.guide_emb(attr, prototype) # Conditional embedding
435
+
436
+ target_device = attr.device # Get device from an existing input tensor
437
+ place_vector = torch.zeros(attr.shape, device=target_device)
438
+ place_prototype = torch.zeros(prototype.shape, device=target_device)
439
+
440
+ place_emb = self.place_emb(place_vector, place_prototype) # Unconditional embedding
441
+
442
+ cond_noise = self.unet(x, t, guide_emb) # Conditioned UNet pass
443
+ uncond_noise = self.unet(x, t, place_emb) # Unconditioned UNet pass (for classifier-free guidance)
444
+
445
+ # Classifier-free guidance
446
+ pred_noise = cond_noise + self.guidance_scale * (cond_noise -
447
+ uncond_noise)
448
+ return pred_noise
449
+
450
+
451
+ class WeightedLoss(nn.Module):
452
+ """Base class for weighted losses."""
453
+ def __init__(self):
454
+ super(WeightedLoss, self).__init__()
455
+
456
+ def forward(self, pred, target, weighted=1.0):
457
+ """
458
+ pred, target:[batch_size, 2, traj_length]
459
+ """
460
+ loss = self._loss(pred, target)
461
+ weightedLoss = (loss * weighted).mean() # Apply weights and average
462
+ # loss = self._loss(weighted * pred, weighted * target)
463
+ # weightedLoss = loss.mean()
464
+ return weightedLoss
465
+
466
+ class WeightedL1(WeightedLoss):
467
+ """Weighted L1 Loss (Mean Absolute Error)."""
468
+ def _loss(self, pred, target):
469
+ return torch.abs(pred - target)
470
+
471
+
472
+ class WeightedL2(WeightedLoss):
473
+ """Weighted L2 Loss (Mean Squared Error)."""
474
+ def _loss(self, pred, target):
475
+ return F.mse_loss(pred, target, reduction='none')
476
+
477
+ class WeightedL3(WeightedLoss):
478
+ """A custom weighted L3-like loss, where weights depend on the error magnitude."""
479
+ def __init__(self, base_weight=1000.0, scale_factor=10000.0):
480
+ super(WeightedL3, self).__init__()
481
+ self.base_weight = base_weight
482
+ self.scale_factor = scale_factor
483
+
484
+ def _loss(self, pred, target):
485
+ error = F.mse_loss(pred, target, reduction='none')
486
+ weight = self.base_weight + self.scale_factor * error
487
+ loss = weight * torch.abs(pred - target)
488
+ return loss
489
+ Losses = {
490
+ 'l1': WeightedL1,
491
+ 'l2': WeightedL2,
492
+ 'l3': WeightedL3,
493
+ }
494
+
495
+ def extract(a, t, x_shape):
496
+ """Extracts values from a (typically constants like alphas) at given timesteps t
497
+ and reshapes them to match the batch shape x_shape.
498
+ """
499
+ b, *_ = t.shape
500
+ out = a.gather(-1, t)
501
+ return out.reshape(b, *((1,) * (len(x_shape) - 1))) # Reshape to (b, 1, 1, ...) for broadcasting
502
+
503
+
504
+ class Diffusion(nn.Module):
505
+ """Denoising Diffusion Probabilistic Model (DDPM).
506
+ This class now also includes DDIM sampling capabilities.
507
+ """
508
+ def __init__(self, loss_type, config, clip_denoised=True, predict_epsilon=True, **kwargs):
509
+ super(Diffusion, self).__init__()
510
+ self.predict_epsilon = predict_epsilon
511
+ self.T = config.diffusion.num_diffusion_timesteps
512
+ self.model = Guide_UNet(config)
513
+ self.beta_schedule = config.diffusion.beta_schedule
514
+ self.beta_start = config.diffusion.beta_start
515
+ self.beta_end = config.diffusion.beta_end
516
+
517
+ if self.beta_schedule == "linear":
518
+ betas = torch.linspace(self.beta_start, self.beta_end, self.T, dtype=torch.float32)
519
+ elif self.beta_schedule == "cosine":
520
+ # Implement cosine schedule
521
+ pass
522
+ else:
523
+ raise ValueError(f"Unsupported beta_schedule: {self.beta_schedule}")
524
+
525
+ alphas = 1.0 - betas
526
+ alpha_cumprod = torch.cumprod(alphas, axis=0)
527
+ alpha_cumprod_prev = torch.cat([torch.ones(1, device=betas.device), alpha_cumprod[:-1]])
528
+
529
+ self.register_buffer("betas", betas)
530
+ self.register_buffer("alphas", alphas)
531
+ self.register_buffer("alpha_cumprod", alpha_cumprod)
532
+ self.register_buffer("alpha_cumprod_prev", alpha_cumprod_prev)
533
+
534
+ # Parameters for q(x_t | x_0) (forward process - DDPM & DDIM)
535
+ self.register_buffer("sqrt_alphas_cumprod", torch.sqrt(alpha_cumprod))
536
+ self.register_buffer("sqrt_one_minus_alphas_cumprod", torch.sqrt(1.0 - alpha_cumprod))
537
+
538
+ # Parameters for DDPM reverse process posterior q(x_{t-1} | x_t, x_0)
539
+ posterior_variance = betas * (1.0 - alpha_cumprod_prev) / (1.0 - alpha_cumprod)
540
+ self.register_buffer("posterior_variance", posterior_variance)
541
+ self.register_buffer("posterior_log_variance_clipped", torch.log(posterior_variance.clamp(min=1e-20)))
542
+ self.register_buffer("posterior_mean_coef1", betas * torch.sqrt(alpha_cumprod_prev) / (1.0 - alpha_cumprod))
543
+ self.register_buffer("posterior_mean_coef2", (1.0 - alpha_cumprod_prev) * torch.sqrt(alphas) / (1.0 - alpha_cumprod))
544
+
545
+ # Parameters for computing x_0 from x_t and noise (used in DDPM prediction and DDIM sampling)
546
+ self.register_buffer("sqrt_recip_alphas_cumprod", torch.sqrt(1.0 / alpha_cumprod))
547
+ self.register_buffer("sqrt_recipminus_alphas_cumprod", torch.sqrt(1.0 / alpha_cumprod - 1))
548
+
549
+ self.loss_fn = Losses[loss_type]()
550
+
551
+ def q_posterior(self, x_start, x, t):
552
+ """Compute the mean, variance, and log variance of the posterior q(x_{t-1} | x_t, x_0)."""
553
+ posterior_mean = (
554
+ extract(self.posterior_mean_coef1, t, x.shape) * x_start
555
+ + extract(self.posterior_mean_coef2, t, x.shape) * x
556
+ )
557
+ posterior_variance = extract(self.posterior_variance, t, x.shape)
558
+ posterior_log_variance = extract(self.posterior_log_variance_clipped, t, x.shape)
559
+ return posterior_mean, posterior_variance, posterior_log_variance
560
+
561
+ def predict_start_from_noise(self, x, t, pred_noise):
562
+ """Compute x_0 from x_t and predicted noise epsilon_theta(x_t, t).
563
+ Used by both DDPM and DDIM.
564
+ """
565
+ return (
566
+ extract(self.sqrt_recip_alphas_cumprod, t, x.shape) * x
567
+ - extract(self.sqrt_recipminus_alphas_cumprod, t, x.shape) * pred_noise
568
+ )
569
+
570
+ def p_mean_variance(self, x, t, attr, prototype):
571
+ """Compute the mean and variance of the reverse process p_theta(x_{t-1} | x_t)."""
572
+ pred_noise = self.model(x, t, attr, prototype)
573
+ x_recon = self.predict_start_from_noise(x, t, pred_noise) # Predict x0
574
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_recon, x, t)
575
+ return model_mean, posterior_log_variance
576
+
577
+ def p_sample(self, x, t, attr, prototype, start_end_info):
578
+ """Sample x_{t-1} from the model p_theta(x_{t-1} | x_t) (DDPM step)."""
579
+ b = x.shape[0]
580
+ model_mean, model_log_variance = self.p_mean_variance(x, t, attr, prototype)
581
+ noise = torch.randn_like(x)
582
+
583
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) # No noise when t=0
584
+ x = model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
585
+
586
+ # Fix the first and last point for trajectory interpolation
587
+ x[:, :, 0] = start_end_info[:, :, 0]
588
+ x[:, :, -1] = start_end_info[:, :, -1]
589
+ return x
590
+
591
+ def p_sample_loop(self, test_x0, attr, prototype, *args, **kwargs):
592
+ """DDPM sampling loop to generate x_0 from x_T (noise)."""
593
+ batch_size = attr.shape[0]
594
+ device = attr.device # Assuming attr is on the correct device
595
+
596
+ x = torch.randn(attr.shape, requires_grad=False, device=device) # Start with pure noise
597
+ start_end_info = test_x0.clone() # Contains the ground truth start and end points
598
+
599
+ # Fix the first and last point from the start
600
+ x[:, :, 0] = start_end_info[:, :, 0]
601
+ x[:, :, -1] = start_end_info[:, :, -1]
602
+
603
+ for i in reversed(range(0, self.T)): # Iterate from T-1 down to 0
604
+ t = torch.full((batch_size,), i, dtype=torch.long, device=device)
605
+ x = self.p_sample(x, t, attr, prototype, start_end_info)
606
+ return x
607
+
608
+ # --------------------- DDIM Sampling Methods ---------------------
609
+ def ddim_sample(self, x, t, t_prev, attr, prototype, start_end_info, eta=0.0):
610
+ """
611
+ DDIM sampling step from t to t_prev.
612
+ eta: Controls stochasticity. 0 for DDIM (deterministic), 1 for DDPM-like (stochastic).
613
+ """
614
+ # Ensure model is on the same device as x
615
+ self.model.to(x.device)
616
+
617
+ pred_noise = self.model(x, t, attr, prototype)
618
+ x_0_pred = self.predict_start_from_noise(x, t, pred_noise)
619
+
620
+ x_0_pred[:, :, 0] = start_end_info[:, :, 0]
621
+ x_0_pred[:, :, -1] = start_end_info[:, :, -1]
622
+
623
+ alpha_cumprod_t = extract(self.alpha_cumprod, t, x.shape)
624
+ alpha_cumprod_t_prev = extract(self.alpha_cumprod, t_prev, x.shape) if t_prev.all() >= 0 else torch.ones_like(alpha_cumprod_t)
625
+
626
+ sigma_t = eta * torch.sqrt((1 - alpha_cumprod_t_prev) / (1 - alpha_cumprod_t) * (1 - alpha_cumprod_t / alpha_cumprod_t_prev))
627
+
628
+ c1 = torch.sqrt(alpha_cumprod_t_prev)
629
+ c2 = torch.sqrt(1 - alpha_cumprod_t_prev - sigma_t**2)
630
+
631
+ noise_cond = torch.zeros_like(x)
632
+ if eta > 0:
633
+ noise_cond = torch.randn_like(x)
634
+ noise_cond[:, :, 0] = 0
635
+ noise_cond[:, :, -1] = 0
636
+
637
+ x_prev = c1 * x_0_pred + c2 * pred_noise + sigma_t * noise_cond
638
+
639
+ x_prev[:, :, 0] = start_end_info[:, :, 0]
640
+ x_prev[:, :, -1] = start_end_info[:, :, -1]
641
+
642
+ return x_prev
643
+
644
+ def ddim_sample_loop(self, test_x0, attr, prototype, num_steps=50, eta=0.0):
645
+ """
646
+ DDIM sampling loop. Can use fewer steps than original diffusion process.
647
+ num_steps: Number of sampling steps (can be less than self.T).
648
+ eta: Controls stochasticity (0 for deterministic, 1 for fully stochastic).
649
+ """
650
+ batch_size = attr.shape[0]
651
+ device = attr.device # Assuming attr is on the correct device
652
+
653
+ x = torch.randn(attr.shape, requires_grad=False, device=device)
654
+ start_end_info = test_x0.clone()
655
+
656
+ x[:, :, 0] = start_end_info[:, :, 0]
657
+ x[:, :, -1] = start_end_info[:, :, -1]
658
+
659
+ times = torch.linspace(self.T - 1, 0, num_steps + 1, device=device).long() # Ensure times tensor is on the same device
660
+
661
+ for i in range(num_steps):
662
+ t = times[i]
663
+ t_next = times[i + 1]
664
+ # Create full tensors for t and t_next for batch processing
665
+ t_tensor = torch.full((batch_size,), t.item(), dtype=torch.long, device=device)
666
+ t_next_tensor = torch.full((batch_size,), t_next.item(), dtype=torch.long, device=device)
667
+
668
+ x = self.ddim_sample(x, t_tensor, t_next_tensor, attr, prototype, start_end_info, eta)
669
+
670
+ return x
671
+
672
+ # --------------------- Unified Sampling Entry Point ---------------------
673
+ def sample(self, test_x0, attr, prototype, sampling_type='ddpm',
674
+ ddim_num_steps=50, ddim_eta=0.0, *args, **kwargs):
675
+ """Generate samples using either DDPM or DDIM.
676
+
677
+ Args:
678
+ test_x0 (torch.Tensor): Tensor containing ground truth data, primarily used for start/end points.
679
+ attr (torch.Tensor): Attributes for conditioning.
680
+ prototype (torch.Tensor): Prototypes for conditioning.
681
+ sampling_type (str, optional): 'ddpm' or 'ddim'. Defaults to 'ddpm'.
682
+ ddim_num_steps (int, optional): Number of steps for DDIM sampling. Defaults to 50.
683
+ ddim_eta (float, optional): Eta for DDIM sampling. Defaults to 0.0.
684
+ """
685
+ self.model.eval() # Set model to evaluation mode for sampling
686
+ with torch.no_grad():
687
+ if sampling_type == 'ddpm':
688
+ return self.p_sample_loop(test_x0, attr, prototype, *args, **kwargs)
689
+ elif sampling_type == 'ddim':
690
+ return self.ddim_sample_loop(test_x0, attr, prototype,
691
+ num_steps=ddim_num_steps, eta=ddim_eta)
692
+ else:
693
+ raise ValueError(f"Unsupported sampling_type: {sampling_type}. Choose 'ddpm' or 'ddim'.")
694
+
695
+ #----------------------------------training----------------------------------#
696
+ def q_sample(self, x_start, t, noise):
697
+ """Sample x_t from x_0 using q(x_t | x_0) = sqrt(alpha_bar_t)x_0 + sqrt(1-alpha_bar_t)noise."""
698
+ sample = (
699
+ extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
700
+ extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise
701
+ )
702
+ # Keep start and end points fixed during noising process as well (for interpolation task)
703
+ sample[:, :, 0] = x_start[:, :, 0]
704
+ sample[:, :, -1] = x_start[:, :, -1]
705
+ return sample
706
+
707
+ def p_losses(self, x_start, attr, prototype, t, weights=1.0):
708
+ """Calculate the diffusion loss (typically MSE between predicted noise and actual noise).
709
+ This is common for both DDPM and DDIM training.
710
+ """
711
+ noise = torch.randn_like(x_start)
712
+ # For interpolation, noise is not added to the fixed start/end points
713
+ noise[:, :, 0] = 0
714
+ noise[:, :, -1] = 0
715
+
716
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
717
+
718
+ x_recon = self.model(x_noisy, t, attr, prototype) # Model predicts noise or x0
719
+ assert noise.shape == x_recon.shape
720
+
721
+ if self.predict_epsilon:
722
+ # Loss on the predicted noise, excluding start/end points
723
+ loss = self.loss_fn(x_recon[:, :, 1:-1], noise[:, :, 1:-1], weights)
724
+ else:
725
+ # Loss on the predicted x0, excluding start/end points
726
+ loss = self.loss_fn(x_recon[:, :, 1:-1], x_start[:, :, 1:-1], weights)
727
+
728
+ return loss
729
+
730
+ def trainer(self, x, attr, prototype, weights=1.0):
731
+ """Performs a single training step. Common for DDPM and DDIM."""
732
+ self.model.train() # Set model to training mode
733
+ batch_size = len(x)
734
+ t = torch.randint(0, self.T, (batch_size,), device=x.device).long() # Sample random timesteps on the same device as x
735
+ return self.p_losses(x, attr, prototype, t, weights)
736
+
737
+ def forward(self, test_x0, attr, prototype, sampling_type='ddpm',
738
+ ddim_num_steps=50, ddim_eta=0.0, *args, **kwargs):
739
+ """Default forward pass calls the unified sampling method."""
740
+ return self.sample(test_x0, attr, prototype,
741
+ sampling_type=sampling_type,
742
+ ddim_num_steps=ddim_num_steps,
743
+ ddim_eta=ddim_eta,
744
+ *args, **kwargs)