-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_denoise.py
More file actions
410 lines (321 loc) · 14.1 KB
/
Copy pathtrain_denoise.py
File metadata and controls
410 lines (321 loc) · 14.1 KB
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# MIT License
# Copyright (c) 2024 Ysobel Sims
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ==============================================================================
# The main training functions for the ZeroDiffusion method
from models.denoise import DenoiseNet
from models.ddpm import DDPM
from models.classifier import Compatibility
from dataloader.diffusion import DiffusionDataset
import torch
import os
def _build_loader_kwargs(device, shuffle=True):
use_cuda = isinstance(device, str) and device.startswith("cuda") and torch.cuda.is_available()
workers = min(8, os.cpu_count() or 1)
kwargs = {
"shuffle": shuffle,
"num_workers": workers,
"pin_memory": use_cuda,
}
if workers > 0:
kwargs["persistent_workers"] = True
kwargs["prefetch_factor"] = 4
return kwargs
def _label_indices_from_aux(labels, aux_bank):
# Match each label vector in a batch to its row index in the auxiliary bank.
matches = torch.isclose(
labels.unsqueeze(1), aux_bank.unsqueeze(0), atol=1e-6, rtol=1e-6
).all(dim=-1)
if not torch.all(matches.any(dim=1)):
raise RuntimeError("At least one label vector was not found in auxiliary bank.")
return matches.float().argmax(dim=1)
def train_diffusion(config, fixed_config):
diffusion = DenoiseNet(
fixed_config["feature_dim"],
config["diffusion_hidden_dim"],
fixed_config["auxiliary_dim"],
).to(fixed_config["device"])
diffusion_optimiser = torch.optim.Adam(
diffusion.parameters(), lr=config["diffusion_lr"], weight_decay=1e-4
)
loader_kwargs = _build_loader_kwargs(fixed_config["device"], shuffle=True)
# Set up dataset loaders
val_loader = torch.utils.data.DataLoader(
fixed_config["val_set"], batch_size=config["diffusion_batch_size"], **loader_kwargs
)
train_loader = torch.utils.data.DataLoader(
fixed_config["train_set"],
batch_size=config["diffusion_batch_size"],
**loader_kwargs,
)
# Main training loop
for epoch in range(config["diffusion_epoch"]):
diffusion.train()
# Batch loop
train_loss = 0.0
for _, features, auxiliary in train_loader:
features = features.to(fixed_config["device"], non_blocking=True)
auxiliary = auxiliary.to(fixed_config["device"], non_blocking=True)
diffusion_optimiser.zero_grad(set_to_none=True)
# Forward pass
generated = diffusion(
diffusion.distort(features, epoch / config["diffusion_epoch"]),
auxiliary,
)
loss = torch.nn.functional.mse_loss(generated, features)
loss.backward()
# Gradient clipping
torch.nn.utils.clip_grad_norm_(diffusion.parameters(), max_norm=1.0)
diffusion_optimiser.step()
train_loss += loss.item()
train_loss /= len(train_loader)
# Evaluation loop
diffusion.eval()
loss = 0.0
with torch.no_grad():
for _, features, auxiliary in val_loader:
features = features.to(fixed_config["device"], non_blocking=True)
auxiliary = auxiliary.to(fixed_config["device"], non_blocking=True)
generated = diffusion(
diffusion.distort(features, epoch / config["diffusion_epoch"]),
auxiliary,
)
loss += torch.nn.functional.mse_loss(generated, features).item()
loss /= len(val_loader)
if epoch % 100 == 0:
print(
f"Epoch {epoch+1} \t Loss: {train_loss:.6f} \tVal Loss: {loss:.6f}"
)
return diffusion
def train_ddpm(config, fixed_config):
"""Train a DDPM diffusion model"""
ddpm = DDPM(
input_dim=fixed_config["feature_dim"],
aux_dim=fixed_config["auxiliary_dim"],
hidden_dim=config["diffusion_hidden_dim"],
n_layers=config.get("ddpm_n_layers", 4),
n_timesteps=config.get("ddpm_n_timesteps", 1000),
dropout=config.get("ddpm_dropout", 0.3),
use_layernorm=config.get("ddpm_use_layernorm", True),
).to(fixed_config["device"])
ddpm_optimiser = torch.optim.Adam(
ddpm.parameters(), lr=config["diffusion_lr"], weight_decay=1e-4
)
loader_kwargs = _build_loader_kwargs(fixed_config["device"], shuffle=True)
# Set up dataset loaders
val_loader = torch.utils.data.DataLoader(
fixed_config["val_set"], batch_size=config["diffusion_batch_size"], **loader_kwargs
)
train_loader = torch.utils.data.DataLoader(
fixed_config["train_set"],
batch_size=config["diffusion_batch_size"],
**loader_kwargs,
)
# Main training loop
for epoch in range(config["diffusion_epoch"]):
ddpm.train()
# Batch loop
train_loss = 0.0
for _, features, auxiliary in train_loader:
features = features.to(fixed_config["device"], non_blocking=True).float()
auxiliary = auxiliary.to(fixed_config["device"], non_blocking=True).float()
ddpm_optimiser.zero_grad(set_to_none=True)
# Sample random timesteps
batch_size = features.shape[0]
t = torch.randint(0, config.get("ddpm_n_timesteps", 1000), (batch_size,),
device=fixed_config["device"])
# Forward diffusion: add noise
x_t, noise = ddpm.q_sample(features, t)
# Predict noise
noise_pred = ddpm(x_t, t, auxiliary)
# Loss: MSE between predicted and actual noise
loss = torch.nn.functional.mse_loss(noise_pred, noise)
loss.backward()
# Gradient clipping
torch.nn.utils.clip_grad_norm_(ddpm.parameters(), max_norm=1.0)
ddpm_optimiser.step()
train_loss += loss.item()
train_loss /= len(train_loader)
# Evaluation loop
ddpm.eval()
val_loss = 0.0
with torch.no_grad():
for _, features, auxiliary in val_loader:
features = features.to(fixed_config["device"], non_blocking=True).float()
auxiliary = auxiliary.to(fixed_config["device"], non_blocking=True).float()
# Sample random timesteps
batch_size = features.shape[0]
t = torch.randint(0, config.get("ddpm_n_timesteps", 1000), (batch_size,),
device=fixed_config["device"])
# Forward diffusion
x_t, noise = ddpm.q_sample(features, t)
# Predict noise
noise_pred = ddpm(x_t, t, auxiliary)
# Loss
val_loss += torch.nn.functional.mse_loss(noise_pred, noise).item()
val_loss /= len(val_loader)
if epoch % 100 == 0:
print(
f"DDPM Epoch {epoch+1} \t Loss: {train_loss:.6f} \tVal Loss: {val_loss:.6f}"
)
return ddpm
def train(config, fixed_config, method="dae"):
"""
Train diffusion model and classifier for zero-shot learning.
Args:
config: Training configuration dict
fixed_config: Fixed configuration dict
method: "dae" for DenoiseNet or "ddpm" for DDPM model
"""
if torch.cuda.is_available() and isinstance(fixed_config["device"], str) and fixed_config["device"].startswith("cuda"):
torch.backends.cudnn.benchmark = True
# Train the diffusion model
if method == "dae":
print(f"Training DenoiseNet diffusion model...")
diffusion = train_diffusion(config, fixed_config)
elif method == "ddpm":
print(f"Training DDPM diffusion model...")
diffusion = train_ddpm(config, fixed_config)
else:
raise ValueError(f"Unknown method: {method}. Choose 'dae' or 'ddpm'")
diffusion.eval()
classifier = Compatibility(
fixed_config["feature_dim"],
fixed_config["auxiliary_dim"],
).to(fixed_config["device"])
criterion = torch.nn.CrossEntropyLoss()
optimiser = torch.optim.Adam(
classifier.parameters(),
lr=config["classifier_learning_rate"],
weight_decay=1e-5,
)
# Get the average norm of the training set
norm = torch.tensor(
[
features.norm() if features.dim() == 1 else torch.norm(features, dim=1).mean()
for _, features, _ in fixed_config["train_set"]
]
).mean().to(fixed_config["device"])
# Generate the dataset for the unseen classes
gen_set = DiffusionDataset(
diffusion,
fixed_config["feature_dim"],
fixed_config["val_auxiliary"],
config["classifier_dataset_size"],
norm,
generation_batch_size=config.get("generation_batch_size", 128),
)
all_aux = (
torch.cat(
[
fixed_config["val_auxiliary"],
fixed_config["train_auxiliary"],
],
dim=0,
)
.float()
.to(fixed_config["device"])
)
classifier_loader_kwargs = _build_loader_kwargs(fixed_config["device"], shuffle=True)
train_gen_loader = torch.utils.data.DataLoader(
gen_set,
batch_size=config["classifier_batch_size"],
**classifier_loader_kwargs,
)
train_real_loader = torch.utils.data.DataLoader(
fixed_config["train_set"],
batch_size=config["classifier_batch_size"],
**classifier_loader_kwargs,
)
val_loader = torch.utils.data.DataLoader(
fixed_config["val_set"],
batch_size=config["classifier_batch_size"],
**classifier_loader_kwargs,
)
# Keep track of val accuracy for when returning
val_acc = 0.0
# Main training loop
for epoch in range(config["classifier_epoch"]):
# Batch loop
train_loss = 0.0
train_count = 0.0
train_acc = 0.0
classifier.train()
for data, labels in train_gen_loader:
data = data.to(fixed_config["device"], non_blocking=True)
labels = labels.to(fixed_config["device"], non_blocking=True)
optimiser.zero_grad(set_to_none=True)
predicted = classifier(data, all_aux).squeeze(1)
labels_ = _label_indices_from_aux(labels, all_aux).long()
loss = criterion(predicted, labels_)
loss.backward()
optimiser.step()
train_loss += loss.item()
# Get the predicted labels
_, predicted_labels = torch.max(predicted, dim=1)
# Calculate the number of correct predictions
correct_predictions = (predicted_labels == labels_).sum().item()
# Calculate the accuracy
accuracy = correct_predictions / labels_.size(0)
# Add the accuracy to the total accuracy
train_acc += accuracy
train_count += 1
for _, data, labels in train_real_loader:
data = data.to(fixed_config["device"], non_blocking=True)
labels = labels.to(fixed_config["device"], non_blocking=True)
optimiser.zero_grad(set_to_none=True)
predicted = classifier(data, all_aux).squeeze(1)
labels_ = _label_indices_from_aux(labels, all_aux).long()
loss = criterion(predicted, labels_)
loss.backward()
optimiser.step()
train_loss += loss.item()
# Get the predicted labels
_, predicted_labels = torch.max(predicted, dim=1)
# Calculate the number of correct predictions
correct_predictions = (predicted_labels == labels_).sum().item()
# Calculate the accuracy
accuracy = correct_predictions / labels_.size(0)
# Add the accuracy to the total accuracy
train_acc += accuracy
train_count += 1
train_acc /= train_count
# Evaluation loop
val_count = 0.0
val_loss = 0.0
val_acc = 0.0
val_aux = fixed_config["val_auxiliary"].float().to(fixed_config["device"])
classifier.eval()
with torch.no_grad():
for index, data, labels in val_loader:
data = data.to(fixed_config["device"], non_blocking=True)
labels = labels.to(fixed_config["device"], non_blocking=True)
labels_ = _label_indices_from_aux(labels, val_aux).long()
predicted = classifier(data, val_aux)
loss = criterion(predicted, labels_)
val_loss += loss.item()
# Get the predicted labels
_, predicted_labels = torch.max(predicted, dim=1)
# Calculate the number of correct predictions
correct_predictions = (predicted_labels == labels_).sum().item()
val_acc += correct_predictions
val_count += labels_.size(0)
val_acc /= val_count
print(
f"Epoch {epoch+1} \t Train Loss: {(train_loss / (len(train_gen_loader) + len(train_real_loader))):.6f} \t Train acc: {train_acc:.6f} \t Val Loss: {(val_loss / len(val_loader)):.6f} \t Val acc {val_acc:.6f}"
)
return {"mean_accuracy": val_acc}