-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathinit_training.py
More file actions
484 lines (374 loc) · 18.4 KB
/
init_training.py
File metadata and controls
484 lines (374 loc) · 18.4 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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
import os
import torch
import numpy as np
import pickle
import dynaphos
from dynaphos.cortex_models import get_visual_field_coordinates_probabilistically
from dynaphos.simulator import GaussianSimulator as PhospheneSimulator
from dynaphos.utils import get_data_kwargs
import model
import local_datasets
from torch.utils.data import DataLoader
from utils import resize, normalize, undo_standardize, dilation3x3, CustomSummaryTracker
from torch.utils.tensorboard import SummaryWriter
class LossTerm():
"""Loss term that can be used for the compound loss"""
def __init__(self, name=None, func=torch.nn.functional.mse_loss, arg_names=None, weight=1.):
self.name = name
self.func = func # the loss function
self.arg_names = arg_names # the names of the inputs to the loss function
self.weight = weight # the relative weight of the loss term
class CompoundLoss():
"""Helper class for combining multiple loss terms. Initialize with list of
LossTerm instances. Returns dict with loss terms and total loss"""
def __init__(self, loss_terms):
self.loss_terms = loss_terms
def __call__(self, loss_targets):
"""Calculate all loss terms and the weighted sum"""
self.out = dict()
self.out['total'] = 0
for lt in self.loss_terms:
func_args = [loss_targets[name] for name in lt.arg_names] # Find the loss targets by their name
self.out[lt.name] = lt.func(*func_args) # calculate result and add to output dict
self.out['total'] += self.out[lt.name] * lt.weight # add the weighted loss term to the total
return self.out
def items(self):
"""return dict with loss tensors as dict with Python scalars"""
return {k: v.item() for k, v in self.out.items()}
class RunningLoss():
"""Helper class to track the running loss over multiple batches."""
def __init__(self):
self.dict = dict()
self.reset()
def reset(self):
self._counter = 0
for key in self.dict.keys():
self.dict[key] = 0.
def update(self, new_entries):
"""Add the current loss values to the running loss"""
self._counter += 1
for key, value in new_entries.items():
if key in self.dict:
self.dict[key] += value
else:
self.dict[key] = value
def get(self):
"""Get the average loss values (total loss dived by the processed batch count)"""
out = {key: (value / self._counter) for key, value in self.dict.items()}
return out
class L1FeatureLoss(object):
def __init__(self):
self.feature_extractor = model.VGGFeatureExtractor(device=device)
self.loss_fn = torch.nn.functional.l1_loss
def __call__(self, y_pred, y_true, ):
true_features = self.feature_extractor(y_true)
pred_features = self.feature_extractor(y_pred)
err = [self.loss_fn(pred, true) for pred, true in zip(pred_features, true_features)]
return torch.mean(torch.stack(err))
def get_dataset(cfg):
if cfg['dataset'] == 'ADE20K':
trainset, valset = local_datasets.get_ade20k_dataset(cfg)
elif cfg['dataset'] == 'BouncingMNIST':
trainset, valset = local_datasets.get_bouncing_mnist_dataset(cfg)
elif cfg['dataset'] == 'Characters':
trainset, valset = local_datasets.get_character_dataset(cfg)
trainloader = DataLoader(trainset, batch_size=cfg['batch_size'],shuffle=True, drop_last=True)
valloader = DataLoader(valset,batch_size=cfg['batch_size'],shuffle=False, drop_last=True)
example_batch = next(iter(valloader))
cfg['circular_mask'] = trainset._mask.to(cfg['device'])
dataset = {'trainset': trainset,
'valset': valset,
'trainloader': trainloader,
'valloader': valloader,
'example_batch': example_batch}
return dataset
def get_models(cfg):
if cfg['model_architecture'] == 'end-to-end-autoencoder':
encoder, decoder = model.get_e2e_autoencoder(cfg)
optimizer = torch.optim.Adam([*encoder.parameters(), *decoder.parameters()], lr=cfg['learning_rate'])
elif cfg['model_architecture'] == 'zhao-autoencoder':
encoder, decoder = model.get_Zhao_autoencoder(cfg)
optimizer = torch.optim.Adam([*encoder.parameters(), *decoder.parameters()], lr=cfg['learning_rate'])
else:
raise NotImplementedError
simulator = get_simulator(cfg)
models = {'encoder' : encoder,
'decoder' : decoder,
'optimizer': optimizer,
'simulator': simulator,}
# added section for exp3 with interaction layer
if 'interaction' in cfg.keys():
with open(cfg['electrode_coords'], 'rb') as handle:
electrode_coords = pickle.load(handle)
models['interaction'] = model.get_interaction_model(electrode_coords, simulator.data_kwargs, cfg['interaction'])
return models
def get_simulator(cfg):
# initialise simulator
params = dynaphos.utils.load_params(cfg['base_config'])
params['run'].update(cfg)
params['thresholding'].update(cfg)
device = get_data_kwargs(params)['device']
with open(cfg['phosphene_map'], 'rb') as handle:
coordinates_visual_field = pickle.load(handle, )
simulator = PhospheneSimulator(params, coordinates_visual_field)
cfg['SPVsize'] = simulator.phosphene_maps.shape[-2:]
return simulator
def get_logging(cfg):
out = dict()
out['training_loss'] = RunningLoss()
out['validation_loss'] = RunningLoss()
out['tensorboard_writer'] = SummaryWriter(os.path.join(cfg['save_path'], 'tensorboard/'))
out['training_summary'] = CustomSummaryTracker()
out['validation_summary'] = CustomSummaryTracker()
out['example_output'] = CustomSummaryTracker()
return out
####### ADJUST OR ADD TRAINING PIPELINE BELOW
def get_training_pipeline(cfg):
if cfg['pipeline'] == 'unconstrained-image-autoencoder':
forward, lossfunc = get_pipeline_unconstrained_image_autoencoder(cfg)
elif cfg['pipeline'] == 'constrained-image-autoencoder':
forward, lossfunc = get_pipeline_constrained_image_autoencoder(cfg)
elif cfg['pipeline'] == 'supervised-boundary-reconstruction':
forward, lossfunc = get_pipeline_supervised_boundary_reconstruction(cfg)
elif cfg['pipeline'] == 'unconstrained-video-reconstruction':
forward, lossfunc = get_pipeline_unconstrained_video_reconstruction(cfg)
elif cfg['pipeline'] == 'image-autoencoder-interaction-model':
forward, lossfunc = get_pipeline_interaction_model(cfg)
elif cfg['pipeline'] == 'image-autoencoder-coactivation-loss':
forward, lossfunc = get_pipeline_coactivation_loss(cfg)
else:
print(cfg['pipeline'] + 'not supported yet')
raise NotImplementedError
return {'forward': forward, 'compound_loss_func': lossfunc}
def get_pipeline_unconstrained_image_autoencoder(cfg):
def forward(batch, models, cfg, to_cpu=False):
"""Forward pass of the model."""
# unpack
encoder = models['encoder']
decoder = models['decoder']
simulator = models['simulator']
# Data manipulation
image, _ = batch
unstandardized_image = undo_standardize(image) # image values scaled back to range 0-1
# Forward pass
simulator.reset()
stimulation = encoder(image)
phosphenes = simulator(stimulation).unsqueeze(1)
reconstruction = decoder(phosphenes)
# Output dictionary
out = {'input': unstandardized_image * cfg['circular_mask'],
'stimulation': stimulation,
'phosphenes': phosphenes,
'reconstruction': reconstruction * cfg['circular_mask'],
'input_resized': resize(unstandardized_image * cfg['circular_mask'], cfg['SPVsize'])}
if to_cpu:
# Return a cpu-copy of the model output
out = {k: v.detach().cpu().clone() for k, v in out.items()}
return out
recon_loss = LossTerm(name='reconstruction_loss',
func=torch.nn.MSELoss(),
arg_names=('reconstruction', 'input'),
weight=1 - cfg['regularization_weight'])
regul_loss = LossTerm(name='regularization_loss',
func=torch.nn.MSELoss(),
arg_names=('phosphenes', 'input_resized'),
weight=cfg['regularization_weight'])
loss_func = CompoundLoss([recon_loss, regul_loss])
return forward, loss_func
def get_pipeline_constrained_image_autoencoder(cfg):
def forward(batch, models, cfg, to_cpu=False):
"""Forward pass of the model."""
# unpack
encoder = models['encoder']
decoder = models['decoder']
simulator = models['simulator']
# Data manipulation
image, _ = batch
unstandardized_image = undo_standardize(image) # image values scaled back to range 0-1
# Forward pass
simulator.reset()
stimulation = encoder(image)
phosphenes = simulator(stimulation).unsqueeze(1)
reconstruction = decoder(phosphenes)
# Output dictionary
out = {'input': unstandardized_image * cfg['circular_mask'],
'stimulation': stimulation,
'phosphenes': phosphenes,
'reconstruction': reconstruction * cfg['circular_mask'],
'input_resized': resize(unstandardized_image * cfg['circular_mask'], cfg['SPVsize'])}
# Sample phosphenes and target at the centers of the phosphenes
out.update({'phosphene_centers': simulator.sample_centers(phosphenes),
'input_centers': simulator.sample_centers(out['input_resized']) })
if to_cpu:
# Return a cpu-copy of the model output
out = {k: v.detach().cpu().clone() for k, v in out.items()}
return out
recon_loss = LossTerm(name='reconstruction_loss',
func=torch.nn.MSELoss(),
arg_names=('reconstruction', 'input'),
weight=1 - cfg['regularization_weight'])
regul_loss = LossTerm(name='regularization_loss',
func=torch.nn.MSELoss(),
arg_names=('phosphene_centers', 'input_centers'),
weight=cfg['regularization_weight'])
loss_func = CompoundLoss([recon_loss, regul_loss])
return forward, loss_func
def get_pipeline_supervised_boundary_reconstruction(cfg):
def forward(batch, models, cfg, to_cpu=False):
"""Forward pass of the model."""
# unpack
encoder = models['encoder']
decoder = models['decoder']
simulator = models['simulator']
# Data manipulation
image, label = batch
label = dilation3x3(label)
# Forward pass
simulator.reset()
stimulation = encoder(image)
phosphenes = simulator(stimulation).unsqueeze(1)
reconstruction = decoder(phosphenes) * cfg['circular_mask']
# Output dictionary
out = {'input': image,
'stimulation': stimulation,
'phosphenes': phosphenes,
'reconstruction': reconstruction * cfg['circular_mask'],
'target': label * cfg['circular_mask'],
'target_resized': resize(label * cfg['circular_mask'], cfg['SPVsize'],),}
# Sample phosphenes and target at the centers of the phosphenes
out.update({'phosphene_centers': simulator.sample_centers(phosphenes) ,
'target_centers': simulator.sample_centers(out['target_resized']) })
if to_cpu:
# Return a cpu-copy of the model output
out = {k: v.detach().cpu().clone() for k, v in out.items()}
return out
recon_loss = LossTerm(name='reconstruction_loss',
func=torch.nn.MSELoss(),
arg_names=('reconstruction', 'target'),
weight=1 - cfg['regularization_weight'])
regul_loss = LossTerm(name='regularization_loss',
func=torch.nn.MSELoss(),
arg_names=('phosphene_centers', 'target_centers'),
weight=cfg['regularization_weight'])
loss_func = CompoundLoss([recon_loss, regul_loss])
return forward, loss_func
def get_pipeline_unconstrained_video_reconstruction(cfg):
def forward(batch, models, cfg, to_cpu=False):
# Unpack
frames = batch
encoder = models['encoder']
decoder = models['decoder']
simulator = models['simulator']
# Forward
simulator.reset()
stimulation_sequence = encoder(frames).permute(1, 0, 2) # permute: (Batch,Time,Num_phos) -> (Time,Batch,Num_phos)
phosphenes = []
for stim in stimulation_sequence:
phosphenes.append(simulator(stim)) # simulator expects (Batch, Num_phosphenes)
phosphenes = torch.stack(phosphenes, dim=1).unsqueeze(dim=1) # Shape: (Batch, Channels=1, Time, Height, Width)
reconstruction = decoder(phosphenes)
out = {'stimulation': stimulation_sequence,
'phosphenes': phosphenes,
'reconstruction': reconstruction * cfg['circular_mask'],
'input': frames * cfg['circular_mask'],
'input_resized': resize(frames * cfg['circular_mask'],
(cfg['sequence_length'],*cfg['SPVsize']),interpolation='trilinear'),}
if to_cpu:
# Return a cpu-copy of the model output
out = {k: v.detach().cpu().clone() for k, v in out.items()}
return out
recon_loss = LossTerm(name='reconstruction_loss',
func=torch.nn.MSELoss(),
arg_names=('reconstruction', 'input'),
weight=1-cfg['regularization_weight'])
regul_loss = LossTerm(name='regularization_loss',
func=torch.nn.MSELoss(),
arg_names=('phosphenes', 'input_resized'),
weight=cfg['regularization_weight'])
loss_func = CompoundLoss([recon_loss, regul_loss])
return forward, loss_func
def get_pipeline_interaction_model(cfg):
def forward(batch, models, cfg, to_cpu=False):
"""Forward pass of the model."""
# unpack
encoder = models['encoder']
interaction_model = models['interaction']
decoder = models['decoder']
simulator = models['simulator']
# Data manipulation
image, _ = batch
# Forward pass
simulator.reset()
stimulation = encoder(image)
interaction = interaction_model(stimulation).clip(min=0)
phosphenes = simulator(interaction).unsqueeze(1)
reconstruction = decoder(phosphenes)
# Output dictionary
out = {'input': image * cfg['circular_mask'],
'stimulation': stimulation,
'interaction': interaction,
'phosphenes': phosphenes,
'reconstruction': reconstruction * cfg['circular_mask'],
'input_resized': resize(image * cfg['circular_mask'], cfg['SPVsize'])}
# Target phosphene brightness is sampled pixels at centers of the phosphenes
target_pixels = simulator.sample_centers(out['input_resized']).squeeze()
out.update({'phosphene_brightness': simulator.get_state()['brightness'].squeeze(),
'target_brightness': cfg['target_brightness_scale']*target_pixels})
if to_cpu:
# Return a cpu-copy of the model output
out = {k: v.detach().cpu().clone() for k, v in out.items()}
return out
recon_loss = LossTerm(name='reconstruction_loss',
func=torch.nn.MSELoss(),
arg_names=('reconstruction', 'input'),
weight=1 - cfg['regularization_weight'])
regul_loss = LossTerm(name='regularization_loss',
func=torch.nn.MSELoss(),
arg_names=('phosphene_brightness', 'target_brightness'),
weight=cfg['regularization_weight'])
loss_func = CompoundLoss([recon_loss, regul_loss])
return forward, loss_func
def get_pipeline_coactivation_loss(cfg):
def forward(batch, models, cfg, to_cpu=False):
"""Forward pass of the model."""
# unpack
encoder = models['encoder']
decoder = models['decoder']
simulator = models['simulator']
# Data manipulation
image, _ = batch
# Forward pass
simulator.reset()
stimulation = encoder(image)
phosphenes = simulator(stimulation).unsqueeze(1)
reconstruction = decoder(phosphenes)
coactivation = models['interaction'](stimulation) # current leaking to neighbouring electrodes
# Output dictionary
out = {'input': image * cfg['circular_mask'],
'stimulation': stimulation,
'phosphenes': phosphenes,
'reconstruction': reconstruction * cfg['circular_mask'],
'input_resized': resize(image * cfg['circular_mask'], cfg['SPVsize'])}
# Target phosphene brightness is sampled pixels at centers of the phosphenes
target_pixels = simulator.sample_centers(out['input_resized']).squeeze()
out.update({'phosphene_brightness': simulator.get_state()['brightness'].squeeze(),
'target_brightness': cfg['target_brightness_scale']*target_pixels,
'coactivation': coactivation})
if to_cpu:
# Return a cpu-copy of the model output
out = {k: v.detach().cpu().clone() for k, v in out.items()}
return out
recon_loss = LossTerm(name='reconstruction_loss',
func=torch.nn.MSELoss(),
arg_names=('reconstruction', 'input'),
weight=1 - cfg['regularization_weight'])
regul_loss = LossTerm(name='regularization_loss',
func=torch.nn.MSELoss(),
arg_names=('phosphene_brightness', 'target_brightness'),
weight=cfg['regularization_weight'])
coact_loss = LossTerm(name='coactivation_loss',
func= lambda x1, x2: torch.mean(x1*x2), # mean of product
arg_names=('stimulation','coactivation'),
weight=cfg['coact_loss_scale'])
loss_func = CompoundLoss([recon_loss, regul_loss, coact_loss])
return forward, loss_func