-
Notifications
You must be signed in to change notification settings - Fork 5
/
methods.py
1836 lines (1525 loc) · 76.3 KB
/
methods.py
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Methods
"""
import random
import numpy as np
import tensorflow as tf
import tensorflow_addons as tfa
from absl import flags
from scipy.spatial.distance import euclidean
# from tqdm import tqdm
import models
import load_datasets
# from pool import run_job_pool
from pickle_data import load_pickle
from class_balance import class_balance
FLAGS = flags.FLAGS
flags.DEFINE_float("lr", 0.0001, "Learning rate for training")
flags.DEFINE_float("lr_domain_mult", 1.0, "Learning rate multiplier for training domain classifier")
flags.DEFINE_boolean("ensemble_same_data", False, "Train each model on the same batch of data, or if false use a different random batch for each model")
flags.DEFINE_float("similarity_weight", 10.0, "Weight for contrastive loss")
flags.DEFINE_integer("max_anchors", 0, "For cross-source self-supervision (v2), how many anchors to use; 0 = all of them")
flags.DEFINE_integer("max_positives", 10, "For cross-source self-supervision (v2), how many positives can be used for each anchor; 0 = all of them")
flags.DEFINE_integer("max_negatives", 40, "For cross-source self-supervision (v2), how many negatives can be used for each positive (actually relative to anchor, so probably make this bigger than max_positives); 0 = all of them")
flags.DEFINE_integer("contrastive_units", 128, "For cross-source self-supervision (v2), how many contrastive units to use")
flags.DEFINE_float("temperature", 0.1, "For cross-source self-supervision (v2), temperature parameter (tau)")
flags.DEFINE_float("ws_noise", 0, "When using weak supervision, how much to noise the target label proportions (simulates not completely accurate self-reporting)")
methods = {}
def register_method(name):
""" Add method to the list of methods, e.g. add @register_method("name")
before a class definition """
assert name not in methods, "duplicate method named " + name
def decorator(cls):
methods[name] = cls
return cls
return decorator
def get_method(name, *args, **kwargs):
""" Based on the given name, call the correct method """
assert name in methods.keys(), \
"Unknown method name " + name
return methods[name](*args, **kwargs)
def list_methods():
""" Returns list of all the available methods """
return list(methods.keys())
class MethodBase:
def __init__(self, source_datasets, target_dataset, model_name,
*args, ensemble_size=1, trainable=True, moving_average=False,
shared_modalities=None, share_most_weights=False,
dataset_name=None, **kwargs):
self.source_datasets = source_datasets
self.target_dataset = target_dataset
self.moving_average = moving_average
self.ensemble_size = ensemble_size
assert ensemble_size > 0, "ensemble_size should be >= 1"
self.share_most_weights = share_most_weights # for HeterogeneousBase
self.dataset_name = dataset_name
# Support multiple targets when we add that functionality
self.num_source_domains = len(source_datasets)
self.num_domains = len(source_datasets)
if target_dataset is not None:
if isinstance(target_dataset, list):
self.num_domains += len(target_dataset)
elif isinstance(target_dataset, load_datasets.Dataset):
self.num_domains += 1
else:
raise NotImplementedError("target_dataset should be either one "
"load_datasets.Dataset() or a list of them, "
"but is "+str(target_dataset))
if shared_modalities is not None:
self.shared_modalities = [int(x) for x in shared_modalities.split(",")]
else:
# Use first modality, assuming there's only one
# Note: this of course also requires that there is a target domain.
source_num_modalities, target_num_modalities = self.get_num_modalities()
assert source_num_modalities == 1, \
"if multiple modalities, set shared_modalities"
assert target_num_modalities == 1, \
"if multiple modalities, set shared_modalities"
self.shared_modalities = [0]
# How to calculate the number of domain outputs
self.domain_outputs = self.calculate_domain_outputs()
# We need to know the num_classes for creating the model
# We'll just pick the first source since we have to have at least one
# source and we've already verified they're all the same in load_da()
self.num_classes = source_datasets[0].num_classes
# Needed for CoDATS label
self.train_batch = source_datasets[0].train_batch
# What we want in the checkpoint
self.checkpoint_variables = {}
# Initialize components -- support ensemble, training all simultaneously
# I think will be faster / more efficient overall time-wise
self.create_iterators()
self.opt = [self.create_optimizers() for _ in range(ensemble_size)]
self.model = [self.create_model(model_name) for _ in range(ensemble_size)]
self.create_losses()
# Checkpoint/save the model and optimizers
for i, model in enumerate(self.model):
self.checkpoint_variables["model_" + str(i)] = model
for i, opt_dict in enumerate(self.opt):
for name, opt in opt_dict.items():
self.checkpoint_variables["opt_" + name + "_" + str(i)] = opt
# Names of the losses returned in compute_losses
self.loss_names = ["total"]
# Should this method be trained (if not, then in main.py the config
# is written and then it exits)
self.trainable = trainable
def get_num_modalities(self):
""" Get the number of source/target modalities """
source_num_modalities = self.source_datasets[0].num_modalities
for other_source in range(1, len(self.source_datasets)):
assert self.source_datasets[other_source].num_modalities \
== source_num_modalities, \
"sources with different num_modalities not supported yet"
if self.target_dataset is not None:
target_num_modalities = self.target_dataset.num_modalities
else:
target_num_modalities = None
return source_num_modalities, target_num_modalities
def calc_num_components(self):
"""
We need a feature extractor for each modality. Take the max of the
source or target number of modalities. Note: if for example the source
has 2 and the target has 1, the lowest index source FE will be used
for the target modality ("left to right" of sorts). Change the
ordering with {source,target}_modality_subset if desired.
We can't use len(self.shared_modalities) here since we need a FE even
for the non-shared modalities.
"""
source_num_modalities, target_num_modalities = self.get_num_modalities()
if target_num_modalities is not None:
num_feature_extractors = max(source_num_modalities,
target_num_modalities)
else:
num_feature_extractors = source_num_modalities
# However, for the domain classifiers, we need one per shared modality.
num_domain_classifiers = len(self.shared_modalities)
print("Creating", num_feature_extractors, "feature extractors")
print("Creating", num_domain_classifiers, "domain classifiers")
return num_feature_extractors, num_domain_classifiers
def calculate_domain_outputs(self):
""" Calculate the number of outputs for the domain classifier. By
default it's the number of domains. However, for example, in domain
generalization we ignore the target, so it'll actually be the number of
source domains only, in which case override this function. """
return self.num_domains
def create_iterators(self):
""" Get the source/target train/eval datasets """
self.source_domain_ids = [x.domain_id for x in self.source_datasets]
self.source_train_iterators = [iter(x.train) for x in self.source_datasets]
self.source_train_eval_datasets = [x.train_evaluation for x in self.source_datasets]
self.source_test_eval_datasets = [x.test_evaluation for x in self.source_datasets]
if self.target_dataset is not None:
self.target_domain_id = self.target_dataset.domain_id
self.target_train_iterator = iter(self.target_dataset.train)
self.target_train_eval_dataset = self.target_dataset.train_evaluation
self.target_test_eval_dataset = self.target_dataset.test_evaluation
else:
self.target_domain_id = None
self.target_train_iterator = None
self.target_train_eval_dataset = None
self.target_test_eval_dataset = None
def create_optimizer(self, *args, **kwargs):
""" Create a single optimizer """
opt = tf.keras.optimizers.Adam(*args, **kwargs)
if self.moving_average:
opt = tfa.optimizers.MovingAverage(opt)
return opt
def create_optimizers(self):
return {"opt": self.create_optimizer(learning_rate=FLAGS.lr)}
def create_model(self, model_name):
return models.BasicModel(self.num_classes, self.domain_outputs,
model_name=model_name)
def create_losses(self):
self.task_loss = make_loss()
@tf.function
def get_next_train_data(self):
""" Get next batch of training data """
# Note we will use this same exact data in Metrics() as we use in
# train_step()
data_sources = [next(x) for x in self.source_train_iterators]
data_target = next(self.target_train_iterator) \
if self.target_train_iterator is not None else None
return self.get_next_batch_both(data_sources, data_target)
def domain_label(self, index, is_target):
""" Default domain labeling. Indexes should be in [0,+inf) and integers.
0 = target
1 = source #0
2 = source #1
3 = source #2
...
"""
if is_target:
return 0
else:
return index+1
@tf.function
def get_next_batch_both(self, data_sources, data_target):
""" Compile for training. Don't for evaluation (called directly,
not this _both function). """
data_sources = self.get_next_batch_multiple(data_sources, is_target=False)
data_target = self.get_next_batch_single(data_target, is_target=True)
return data_sources, data_target
def get_next_batch_multiple(self, data, is_target):
"""
Get next set of training data. data should be a list of data (probably
something like [next(x) for x in iterators]).
Returns: (
[x_a1, x_a2, x_a3, ...],
[y_a1, y_a2, y_a3, ...],
[domain_a1, domain_a2, domain_a3, ...]
)
"""
if data is None:
return None
assert not is_target or len(data) == 1, \
"only support one target at present"
xs = []
ys = []
ds = []
example_ids = []
for i, (x, y, example_id) in enumerate(data):
xs.append(x)
ys.append(y)
ds.append(tf.ones_like(y)*self.domain_label(index=i,
is_target=is_target))
example_ids.append(example_id)
return (xs, ys, ds, example_ids)
def get_next_batch_single(self, data, is_target, index=0):
"""
Get next set of training data. data should be a single batch (probably
something like next(iterator)). When processing target data, index
must be 0 since we only support one target at the moment. However,
during evaluation we evaluate each source's data individually so if
is_target is False, then index can be whichever source domain was
passed.
Returns: (x, y, domain)
"""
if data is None:
return None
assert not is_target or index == 0, \
"only support one target at present"
x, y, example_id = data
d = tf.ones_like(y)*self.domain_label(index=index, is_target=is_target)
data_target = (x, y, d, example_id)
return data_target
# Allow easily overriding each part of the train_step() function, without
# having to override train_step() in its entirety
@tf.function
def prepare_data(self, data_sources, data_target, which_model):
""" Prepare the data for the model, e.g. by concatenating all sources
together. Note: do not put code in here that changes the domain labels
since you presumably want that during evaluation too. Put that in
domain_label()
Input xs shape: [num_domains, num_modalities, per-modality x shape...]
Output xs shape: [num_modalities, per-modality x shape...]
Note: compile by adding @tf.function decorator if the contents of this
(overrided) function is compilable
"""
# By default (e.g. for no adaptation or domain generalization), ignore
# the target data
xs_a, y_a, domain_a, example_ids = data_sources
# Concatenate all source domains' data
#
# xs is a list of domains, which is a tuple of modalities, which is
# tensors, e.g. if one modality but two sources:
# [(s1 tensor,), (s2 tensor,)]
# We want to concatenate the tensors from all domains separately for
# each modality.
source_num_modalities, target_num_modalities = self.get_num_modalities()
xs = [
tf.concat([x_a[i] for x_a in xs_a], axis=0)
for i in range(source_num_modalities)
]
task_y_true = tf.concat(y_a, axis=0)
domain_y_true = tf.concat(domain_a, axis=0)
auxiliary_data = None
return xs, task_y_true, domain_y_true, auxiliary_data
def prepare_data_eval(self, data, is_target):
""" Prepare the data for the model, e.g. by concatenating all sources
together. This is like prepare_data() but use during evaluation.
Input xs shape: [num_domains, num_modalities, per-modality x shape...]
Output xs shape: [num_modalities, per-modality x shape...]
"""
xs, y, domain, example_ids = data
for x in xs:
assert isinstance(x, list), \
"Must pass xs=[[...],[...],...] even if only one domain for tf.function consistency"
assert isinstance(y, list), \
"Must pass y=[...] even if only one domain for tf.function consistency"
assert isinstance(domain, list), \
"Must pass domain=[...] even if only one domain for tf.function consistency"
# Concatenate all the data (e.g. if multiple source domains)
source_num_modalities, target_num_modalities = self.get_num_modalities()
num_modalities = target_num_modalities if is_target else source_num_modalities
xs = [
tf.concat([x[i] for x in xs], axis=0)
for i in range(num_modalities)
]
y = tf.concat(y, axis=0)
domain = tf.concat(domain, axis=0)
auxiliary_data = None
return xs, y, domain, auxiliary_data
def post_data_eval(self, task_y_true, task_y_pred, domain_y_true,
domain_y_pred):
""" Optionally do something with the data after feeding through the
model. Since the model outputs logits, here we actually take the softmax
so that during evaluation we have probability distributions. """
task_y_pred = tf.nn.softmax(task_y_pred)
domain_y_pred = [tf.nn.softmax(d) for d in domain_y_pred]
return task_y_true, task_y_pred, domain_y_true, domain_y_pred
def call_model(self, xs, which_model, is_target=None, **kwargs):
return self.model[which_model](xs, **kwargs)
def compute_losses(self, xs, task_y_true, domain_y_true, task_y_pred,
domain_y_pred, fe_output, contrastive_output, auxiliary_data,
which_model, training):
# Maybe: regularization = sum(model.losses) and add to loss
return self.task_loss(task_y_true, task_y_pred)
def compute_gradients(self, tape, loss, which_model):
return tape.gradient(loss,
self.model[which_model].trainable_variables_task_fe)
def apply_gradients(self, grad, which_model):
self.opt[which_model]["opt"].apply_gradients(zip(grad,
self.model[which_model].trainable_variables_task_fe))
def train_step(self):
"""
Get batch of data, prepare data, run through model, compute losses,
apply the gradients
Override the individual parts with prepare_data(), call_model(),
compute_losses(), compute_gradients(), and apply_gradients()
We return the batch of data so we can use the exact same training batch
for the "train" evaluation metrics.
"""
# TensorFlow errors constructing the graph (with tf.function, which
# makes training faster) if we don't know the data size. Thus, first
# load batches, then pass to compiled train step.
all_data_sources = []
all_data_target = []
for i in range(self.ensemble_size):
data_sources, data_target = self.get_next_train_data()
all_data_sources.append(data_sources)
all_data_target.append(data_target)
# If desired, use the same batch for each of the models.
if FLAGS.ensemble_same_data:
break
for i in range(self.ensemble_size):
# Get random batch for this model in the ensemble (either same for
# all or different for each)
if FLAGS.ensemble_same_data:
data_sources = all_data_sources[0]
data_target = all_data_target[0]
else:
data_sources = all_data_sources[i]
data_target = all_data_target[i]
# Prepare
xs, task_y_true, domain_y_true, auxiliary_data = self.prepare_data(
data_sources, data_target, which_model=i
)
# We compile the entire model call, loss computation, and gradient
# update/apply
self._update_model(
xs, task_y_true, domain_y_true, auxiliary_data, which_model=i
)
# We return the first one since we don't really care about the "train"
# evaluation metrics that much.
return all_data_sources[0], all_data_target[0]
@tf.function
def _update_model(self, xs, task_y_true, domain_y_true, auxiliary_data,
which_model):
# Run batch through the model and compute loss
with tf.GradientTape(persistent=True) as tape:
task_y_pred, domain_y_pred, fe_output, contrastive_output = \
self.call_model(xs, which_model=which_model, training=True)
losses = self.compute_losses(xs, task_y_true, domain_y_true,
task_y_pred, domain_y_pred, fe_output, contrastive_output,
auxiliary_data, which_model=which_model, training=True)
# Update model
gradients = self.compute_gradients(tape, losses, which_model=which_model)
del tape
self.apply_gradients(gradients, which_model=which_model)
def eval_step(self, data, is_target, is_single_domain):
""" Evaluate a batch of source or target data, called in metrics.py.
This preprocesses the data to have x, y, domain always be lists so
we can use the same compiled tf.function code in eval_step_list() for
both sources and target domains. """
xs, y, domain, example_ids = data
# If it's a single domain,to make later code consistent, embed in a
# single-item list.
if is_single_domain:
xs = [xs]
# Convert any tuples to lists
xs_list = []
for x in xs:
if isinstance(x, tuple):
# convert the tuple from load_datasets.py (avoiding a TF error)
# back to a list
x = list(x)
xs_list.append(x)
xs = xs_list
if not isinstance(y, list):
y = [y]
if not isinstance(domain, list):
domain = [domain]
if not isinstance(example_ids, list):
example_ids = [example_ids]
return self.eval_step_list((xs, y, domain, example_ids), is_target)
def add_multiple_losses(self, losses, average=False):
"""
losses = [
[total_loss1, task_loss1, ...],
[total_loss2, task_loss2, ...],
...
]
returns [total_loss, task_loss, ...] either the sum or average
"""
losses_added = None
for loss_list in losses:
# If no losses yet, then just set to this
if losses_added is None:
losses_added = loss_list
# Otherwise, add to the previous loss values
else:
assert len(losses_added) == len(loss_list), \
"subsequent losses have different length than the first"
for i, loss in enumerate(loss_list):
losses_added[i] += loss
assert losses_added is not None, \
"must return losses from at least one domain"
if average:
averaged_losses = []
for loss in losses_added:
averaged_losses.append(loss / len(losses))
return averaged_losses
else:
return losses_added
#@tf.function # faster not to compile
def eval_step_list(self, data, is_target):
""" Override preparation in prepare_data_eval() """
(
xs,
orig_task_y_true,
orig_domain_y_true,
auxiliary_data,
) = self.prepare_data_eval(data, is_target)
task_y_true_list = []
task_y_pred_list = []
domain_y_true_list = []
domain_y_pred_list = []
losses_list = []
for i in range(self.ensemble_size):
# Run through model
#
# We don't need to handle both_domains_simultaneously here because
# during evaluation we already pass the source(s) data through
# first and the target data through separately second.
task_y_pred, domain_y_pred, fe_output, contrastive_output = \
self.call_model(xs, which_model=i, is_target=is_target,
training=False)
# Calculate losses
losses = self.compute_losses(xs, orig_task_y_true,
orig_domain_y_true, task_y_pred, domain_y_pred, fe_output,
contrastive_output, auxiliary_data, which_model=i,
training=False)
if not isinstance(losses, list):
losses = [losses]
losses_list.append(losses)
# Post-process data (e.g. compute softmax from logits)
task_y_true, task_y_pred, domain_y_true, domain_y_pred = \
self.post_data_eval(orig_task_y_true, task_y_pred,
orig_domain_y_true, domain_y_pred)
task_y_true_list.append(task_y_true)
task_y_pred_list.append(task_y_pred)
domain_y_true_list.append(domain_y_true)
domain_y_pred_list += domain_y_pred # list from multiple modalities
# Combine information from each model in the ensemble -- averaging.
#
# Note: this is how the ensemble predictions are made with InceptionTime
# having an ensemble of 5 models -- they average the softmax outputs
# over the ensemble (and we now have softmax after the post_data_eval()
# call). See their code:
# https://github.com/hfawaz/InceptionTime/blob/master/classifiers/nne.py
task_y_true_avg = tf.math.reduce_mean(task_y_true_list, axis=0)
task_y_pred_avg = tf.math.reduce_mean(task_y_pred_list, axis=0)
domain_y_true_avg = tf.math.reduce_mean(domain_y_true_list, axis=0)
domain_y_pred_avg = tf.math.reduce_mean(domain_y_pred_list, axis=0)
losses_avg = self.add_multiple_losses(losses_list, average=True)
return task_y_true_avg, task_y_pred_avg, domain_y_true_avg, \
domain_y_pred_avg, losses_avg
# The base method class performs no adaptation. Use this by passing the "target"
# as the source and not specifying a target domain. Then, set shared_modalities
# to be "0" to train just on modality 0, or "0,1" for both, or "1" for just
# modality 1, etc.
@register_method("none")
class MethodNone(MethodBase):
def create_model(self, model_name):
# We need to create the right number of FE's and DC's otherwise the
# closed method will error, though the open/partial will work (assuming
# there's only 2 modalities, since then we only have 1 shared)
num_feature_extractors, num_domain_classifiers \
= self.calc_num_components()
return models.BasicModel(self.num_classes, self.domain_outputs,
model_name=model_name,
num_feature_extractors=num_feature_extractors,
num_domain_classifiers=num_domain_classifiers,
shared_modalities=self.shared_modalities,
share_most_weights=self.share_most_weights)
def _keep_shared(self, xs):
""" Keep only the domains set in --shared_modalities and the order """
return [xs[modality] for modality in self.shared_modalities]
@tf.function
def prepare_data(self, data_sources, data_target, which_model):
xs, task_y_true, domain_y_true, auxiliary_data = super().prepare_data(
data_sources, data_target, which_model
)
return self._keep_shared(xs), task_y_true, domain_y_true, auxiliary_data
def prepare_data_eval(self, data, is_target):
xs, y, domain, auxiliary_data = super().prepare_data_eval(data, is_target)
return self._keep_shared(xs), y, domain, auxiliary_data
@register_method("codats")
class MethodDann(MethodBase):
"""
DANN / CoDATS (with modal architecture and MS-DA, then CoDATS)
Only supports one modality. We create only one feature extractor in
create_model() and drop the other modalities in prepare_data() and
prepare_data_eval(), only including the one modality specified
in --shared_modalities=...
"""
def __init__(self, source_datasets, target_dataset,
global_step, total_steps, *args, **kwargs):
self.global_step = global_step # should be TF variable
self.total_steps = total_steps
super().__init__(source_datasets, target_dataset, *args, **kwargs)
self.loss_names += ["task", "domain"]
def create_model(self, model_name):
# By default we create only one FE, so make sure we only have one
# shared modality. We drop the non-shared modalities in prepare_data()
# and prepare_data_eval().
assert len(self.shared_modalities) == 1, \
"DANN only supports one shared modality between domains"
return models.DannModel(self.num_classes, self.domain_outputs,
self.global_step, self.total_steps, model_name=model_name)
def create_optimizers(self):
opt = super().create_optimizers()
# We need an additional optimizer for DANN
opt["d_opt"] = self.create_optimizer(
learning_rate=FLAGS.lr*FLAGS.lr_domain_mult)
return opt
def create_losses(self):
# Note: at the moment these are the same, but if we go back to
# single-source, then the domain classifier may be sigmoid not softmax
super().create_losses()
self.domain_loss = make_loss()
@tf.function
def prepare_data(self, data_sources, data_target, which_model):
assert data_target is not None, "cannot run DANN without target"
xs_a, y_a, domain_a, example_ids_a = data_sources
xs_b, y_b, domain_b, example_ids_b = data_target
# Concatenate all source domains' data
#
# xs is a list of domains, which is a tuple of modalities, which is
# tensors, e.g. if one modality but two sources:
# [(s1 tensor,), (s2 tensor,)]
# We want to concatenate the tensors from all domains separately for
# each modality.
source_num_modalities, target_num_modalities = self.get_num_modalities()
xs_a = [
tf.concat([x_a[i] for x_a in xs_a], axis=0)
for i in range(source_num_modalities)
]
y_a = tf.concat(y_a, axis=0)
domain_a = tf.concat(domain_a, axis=0)
# Concatenate for adaptation - concatenate source labels with all-zero
# labels for target since we can't use the target labels during
# unsupervised domain adaptation
#
# We concatenate the shared modalities, dropping the non-shared
# modalities. DANN by itself doesn't know how to handle changes in the
# number of modalities between domains.
xs = [
tf.concat((xs_a[modality], xs_b[modality]), axis=0)
for modality in self.shared_modalities
]
task_y_true = tf.concat((y_a, tf.zeros_like(y_b)), axis=0)
domain_y_true = tf.concat((domain_a, domain_b), axis=0)
auxiliary_data = None
return xs, task_y_true, domain_y_true, auxiliary_data
def prepare_data_eval(self, data, is_target):
""" Prepare the data for the model, e.g. by concatenating all sources
together. This is like prepare_data() but use during evaluation. """
xs, y, domain, auxiliary_data = super().prepare_data_eval(data, is_target)
xs = [
xs[modality] for modality in self.shared_modalities
]
return xs, y, domain, auxiliary_data
def compute_losses(self, xs, task_y_true, domain_y_true, task_y_pred,
domain_y_pred, fe_output, contrastive_output, auxiliary_data,
which_model, training):
nontarget = tf.where(tf.not_equal(domain_y_true, 0))
task_y_true = tf.gather(task_y_true, nontarget, axis=0)
task_y_pred = tf.gather(task_y_pred, nontarget, axis=0)
task_loss = self.task_loss(task_y_true, task_y_pred)
d_loss = sum([
self.domain_loss(domain_y_true, d)
for d in domain_y_pred
])/len(domain_y_pred)
total_loss = task_loss + d_loss
return [total_loss, task_loss, d_loss]
def compute_gradients(self, tape, losses, which_model):
total_loss, task_loss, d_loss = losses
grad = tape.gradient(total_loss,
self.model[which_model].trainable_variables_task_fe_domain)
d_grad = tape.gradient(d_loss,
self.model[which_model].trainable_variables_domain)
return [grad, d_grad]
def apply_gradients(self, gradients, which_model):
grad, d_grad = gradients
self.opt[which_model]["opt"].apply_gradients(zip(grad,
self.model[which_model].trainable_variables_task_fe_domain))
# Update discriminator again
self.opt[which_model]["d_opt"].apply_gradients(zip(d_grad,
self.model[which_model].trainable_variables_domain))
class MethodDawsBase(MethodDann):
""" Domain adaptation with weak supervision (in this case, target-domain
label proportions)"""
def __init__(self, *args, noise_amount=None, **kwargs):
super().__init__(*args, **kwargs)
if noise_amount is None:
noise_amount = FLAGS.ws_noise
self.loss_names += ["weak"]
self.compute_p_y(noise_amount)
def compute_p_y(self, noise_amount=None):
""" Compute P(y) (i.e. class balance) of the training target dataset
Note: we simulate the self-report label proportions from looking at
the target training labels (not validation or test sets). However, after
this function call, we don't use the labels themselves (outside of
computing evaluation accuracy), just the computed proportions for the
training.
"""
# Compute proportion of each class
# Note: we use the "eval" train dataset since it doesn't repeat infinitely
# and we use "train" not test since we don't want to peak at the
# validation data we use for model selection.
self.p_y = class_balance(self.target_train_eval_dataset, self.num_classes)
print("Correct proportions:", self.p_y)
before = self.p_y * 1.0
total_noise = 0
# Add noise
if noise_amount is not None and noise_amount != 0:
# Make sure it's float
noise_amount = float(noise_amount)
while noise_amount > 0:
# Randomly pick a class
label = random.randint(0, len(self.p_y)-1)
# Randomly pick some amount of our noise budget. Always positive
# since otherwise we could do this loop forever.
noise = random.uniform(0.000001, noise_amount)
# We skip negatives since afterwards we normalize, so adding
# to other classes results in a negative.
#
# Randomly pick whether to add/subtract this from the class
# proportions (otherwise it's always additive noise)
# positive = random.choice([True, False])
# if not positive:
# noise *= -1
# Update the class proportions
new_value = self.p_y[label] + noise
# Noise was too much, so break before we add it and go over.
# if noise_amount - noise < 0:
# break
# Skip and try again if we end up with a negative or zero
# proportion. Also, make sure we don't add too much noise.
if new_value > 0:
print("{} {} {} label {}".format(
"Adding" if noise > 0 else "Subtracting",
noise,
"to" if noise > 0 else "from",
label,
))
self.p_y[label] = new_value
# Subtract the amount we used from the noise budget
noise_amount -= noise
# Debugging
total_noise += noise
print("Noised proportions:", self.p_y)
print("Sum difference:", sum([abs(self.p_y[i]-before[i]) for i in range(len(self.p_y))]))
print("Total noise:", total_noise)
# Re-normalize so the sum still is 1
self.p_y = self.p_y / sum(self.p_y)
print("Normalized noised proportions:", self.p_y)
print("Sum difference norm:", sum([abs(self.p_y[i]-before[i]) for i in range(len(self.p_y))]))
def compute_losses(self, xs, task_y_true, domain_y_true, task_y_pred,
domain_y_pred, fe_output, contrastive_output, auxiliary_data,
which_model, training):
# DANN losses
nontarget = tf.where(tf.not_equal(domain_y_true, 0))
task_y_true_nontarget = tf.gather(task_y_true, nontarget, axis=0)
task_y_pred_nontarget = tf.gather(task_y_pred, nontarget, axis=0)
task_loss = self.task_loss(task_y_true_nontarget, task_y_pred_nontarget)
d_loss = sum([
self.domain_loss(domain_y_true, d)
for d in domain_y_pred
])/len(domain_y_pred)
# DA-WS regularizer
#
# Get predicted target-domain labels. We ignore label proportions for
# the source domains since we train to predict the correct labels there.
# We don't know the target-domain labels, so instead we try using this
# additional P(y) label proportion information. Thus, we use it and the
# adversarial domain-invariant FE objectives as sort of auxiliary
# losses.
target = tf.where(tf.equal(domain_y_true, 0))
task_y_pred_target = tf.gather(task_y_pred, target, axis=0)
# Idea:
# argmax, one-hot, reduce_sum(..., axis=1), /= batch_size, KL with p_y
# However, argmax yields essentially useless gradients (as far as I
# understand it, e.g. we use cross entropy loss for classification not
# the actual 0-1 loss or loss on the argmax of the softmax outputs)
#
# Thus, a soft version. Idea: softmax each, reduce sum vertically,
# /= batch_size, then KL
# This is different than per-example-in-batch KLD because we average
# over the softmax outputs across the batch before KLD. So, the
# difference is whether averaging before or after KLD.
#
# Note: this depends on a large enough batch size. If you can't set it
# >=64 or so (like what we use in SS-DA for the target data, i.e. half
# the 128 batch size), then accumulate this gradient over multiple steps
# and then apply.
#
# cast batch_size to float otherwise:
# "x and y must have the same dtype, got tf.float32 != tf.int32"
batch_size = tf.cast(tf.shape(task_y_pred_target)[0], dtype=tf.float32)
p_y_batch = tf.reduce_sum(tf.nn.softmax(task_y_pred_target), axis=0) / batch_size
daws_loss = tf.keras.losses.KLD(self.p_y, p_y_batch)
# Sum up individual losses for the total
#
# Note: daws_loss doesn't have the DANN learning rate schedule because
# it goes with the task_loss. We want to learn predictions for the task
# classifier that both correctly predicts labels on the source data and
# on the target data aligns with the correct label proportions.
# Separately, we want the FE representation to also be domain invariant,
# which we apply the learning rate schedule to, I think, to help the
# adversarial part converge properly (recall GAN training instability
# stuff).
total_loss = task_loss + d_loss + daws_loss
return [total_loss, task_loss, d_loss, daws_loss]
def compute_gradients(self, tape, losses, which_model):
# We only use daws_loss for plotting -- for computing gradients it's
# included in the total loss
return super().compute_gradients(tape, losses[:-1], which_model)
@register_method("codats_ws")
class MethodCodatsWS(MethodDawsBase):
pass
#
# Contrastive Adversarial Learning for Multi-Source Time Series Domain Adaptation
#
class MethodCaldaBase:
""" CALDA - instantiations chosen via arguments
For Domain Adaptation, also inherit from MethodDann.
For Domain Generalization, also inherit from MethodDannDG.
"""
def __init__(self, *args, num_contrastive_units=None,
pseudo_label_target=False, hard=False,
in_domain=False, any_domain=False,
domain_generalization=False, weight_adversary=1, **kwargs):
self.weight_adversary = weight_adversary
self.weight_similarity = FLAGS.similarity_weight
self.pseudo_label_target = pseudo_label_target
self.hard = hard
self.in_domain = in_domain
self.any_domain = any_domain
self.domain_generalization = domain_generalization
if num_contrastive_units is None:
self.num_contrastive_units = FLAGS.contrastive_units
else:
self.num_contrastive_units = num_contrastive_units
super().__init__(*args, **kwargs)
self.loss_names += ["similarity"]
def create_losses(self):
super().create_losses()
# Used in non-compiled version
self.cl_crossentropy_loss = make_loss()
# Used in hard pos/neg
self.task_no_reduction_loss = make_loss(
reduction=tf.keras.losses.Reduction.NONE)
def create_model(self, model_name):
# Not multi-modal at the moment
assert len(self.shared_modalities) == 1, \
"only supports one shared modality between domains"
return models.DannModel(self.num_classes, self.domain_outputs,
self.global_step, self.total_steps,
num_contrastive_units=self.num_contrastive_units,
model_name=model_name)
def _cartesian_product(self, a, b):
"""
Assumes a and b are 1D
https://stackoverflow.com/a/47133461
"""
tile_a = tf.tile(tf.expand_dims(a, 1), [1, tf.shape(b)[0]])
tile_a = tf.expand_dims(tile_a, 2)
tile_b = tf.tile(tf.expand_dims(b, 0), [tf.shape(a)[0], 1])
tile_b = tf.expand_dims(tile_b, 2)
cartesian_product = tf.concat([tile_a, tile_b], axis=2)
return cartesian_product
def _contrastive_get_examples(self, task_y_true, domain_y_true,
z_output, task_y_pred):
"""
Get y, d, z, and pred used in contrastive learning
Take the true domain and class labels and model outputs and get the
source-only or if pseudo labeling the source + pseudo-labeled target
"""
# For domain generalization, d=0 is the first source domain not the
# target domain since in domain generalization we don't have target
# domain data. Thus, just use everything, but do range here so we don't
# have to rewrite the rest of the code.
if self.domain_generalization:
nontarget = tf.expand_dims(tf.range(0, tf.shape(domain_y_true)[0]), axis=-1)
else:
# Anchors = the full batch, excluding the target data
nontarget = tf.where(tf.not_equal(domain_y_true, 0))
y = tf.gather(task_y_true, nontarget, axis=0)
d = tf.gather(domain_y_true, nontarget, axis=0)
z = tf.gather(z_output, nontarget, axis=0)
pred = tf.gather(task_y_pred, nontarget, axis=0)
# If we include the target domain, since we don't know the true labels,
# we instead take the current task classifier predictions for the target
# data as the true labels, i.e. pseudo labeling the target data. Then
# concatenate with the non-target y/d/z we generated above.
if self.pseudo_label_target: