-
Notifications
You must be signed in to change notification settings - Fork 1
/
tf_macros.py
executable file
·2034 lines (1716 loc) · 79.6 KB
/
tf_macros.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
from itertools import chain, combinations
import tensorflow as tf
def rank(x):
assert isinstance(x, tf.Tensor)
return x.shape.ndims
def shape(x):
assert isinstance(x, tf.Tensor)
return tuple(-1 if dims.value is None else dims.value for dims in x.shape.dims)
def product(xs):
prod = 1
for x in xs:
prod *= x
return prod
def make_least_common_shape(xs, ignore_ranks=()):
assert len(xs) > 1
shapes = [shape(x) for x in xs]
common_rank = len(shapes[0])
assert all(len(s) == common_rank for s in shapes)
ref_shape = tuple(max(s[r] for s in shapes) for r in range(common_rank))
ys = list()
for x, s in zip(xs, shapes):
multiples = [ref_dims if dims == 1 and r not in ignore_ranks else 1 for r, (dims, ref_dims) in enumerate(zip(s, ref_shape))]
if not all(m == 1 for m in multiples):
x = tf.tile(input=x, multiples=multiples)
assert rank(x) == common_rank and all(d1 == d2 for r, (d1, d2) in enumerate(zip(shape(x), ref_shape)) if r not in ignore_ranks)
ys.append(x)
return ys
def make_broadcastable(xs):
assert len(xs) > 0
if len(xs) == 1 and not isinstance(xs[0], tf.Tensor):
xs = xs[0]
shapes = [shape(x) for x in xs]
ref_shape = max(shapes, key=(lambda s: len(s) - sum(dims == 1 for dims in s) / (len(s) + 1)))
ys = list()
for x, s in zip(xs, shapes):
s = list(s)
if len(s) < len(ref_shape):
last_dims = None
for r, (dims, ref_dims) in enumerate(zip(s, ref_shape)):
if r < len(s) and dims in (ref_dims, 1):
last_dims = dims
else:
assert dims != last_dims
x = tf.expand_dims(input=x, axis=r)
s.insert(r, 1)
assert rank(x) == len(ref_shape) and all(d1 == d2 or d1 == 1 for d1, d2 in zip(shape(x), ref_shape))
ys.append(x)
return ys
class Model(object):
precision = 32
current = None
@staticmethod
def dtype(dtype, include_bytes=False):
assert Model.precision % 8 == 0
assert dtype in ('float', 'int', 'bool')
if dtype == 'float':
if Model.precision == 32:
dtype = tf.float32
else:
assert False
elif dtype == 'int':
if Model.precision == 32:
dtype = tf.int32
else:
assert False
elif dtype == 'bool':
dtype = tf.bool
else:
assert False
if include_bytes:
return dtype, Model.precision // 8
else:
return dtype
def __init__(self, name=None, optimizer='adam', learning_rate=0.001, weight_decay=None, clip_gradients=None, model_directory=None, summary_directory=None):
assert name is None or isinstance(name, str)
assert optimizer in ('adam',)
assert isinstance(learning_rate, float)
assert weight_decay is None or isinstance(weight_decay, float)
assert clip_gradients is None or isinstance(clip_gradients, float)
assert model_directory is None or isinstance(model_directory, str)
assert summary_directory is None or isinstance(summary_directory, str)
self.name = name
self.optimizer = optimizer
self.learning_rate = learning_rate
self.weight_decay = weight_decay
self.clip_gradients = clip_gradients
self.model_directory = model_directory
self.summary_directory = summary_directory
self.tensors = dict()
self.variables = dict()
self.placeholders = dict()
self.num_parameters = 0
self.num_bytes = 0
self.scope = None
self.session = None
self.coordinator = None
self.defined = False
self.optimization = None
def __str__(self):
if self.name is None:
return 'Model'
else:
return self.name
def register_tensor(self, key, tensor):
assert key not in ('loss', 'dropout')
assert key not in self.tensors
self.tensors[key] = tensor
def register_variable(self, key, variable, num_parameters, num_bytes):
if key in self.variables:
assert variable == self.variables[key]
else:
self.variables[key] = variable
self.num_parameters += num_parameters
self.num_bytes += num_bytes
def register_placeholder(self, key, placeholder):
assert key not in self.placeholders
self.placeholders[key] = placeholder
def __enter__(self):
tf.reset_default_graph()
assert Model.current is None
Model.current = self
self.scope = tf.variable_scope(str(self))
self.scope.__enter__()
Input(name='training', shape=(), dtype='bool', batched=False).forward()
self.training = self.placeholders.pop('training')
Input(name='dropout', shape=(), batched=False).forward()
self.dropout = self.placeholders.pop('dropout')
return self
def __exit__(self, type, value, tb):
if type is not None:
if self.scope is not None:
self.scope.__exit__(None, None, None)
if self.coordinator is not None:
self.coordinator.request_stop()
self.coordinator.join(threads=self.queue_threads)
if self.session is not None:
self.session.close()
Model.current = None
raise
if self.defined:
self.coordinator.request_stop()
self.coordinator.join(threads=self.queue_threads)
self.save()
self.session.close()
else:
if self.weight_decay is not None and self.weight_decay > 0.0:
for name, variable in self.variables.items():
regularization = self.weight_decay * tf.nn.l2_loss(t=variable, name=(name + '-regularization'))
tf.losses.add_loss(loss=regularization, loss_collection=tf.GraphKeys.REGULARIZATION_LOSSES)
loss = tf.losses.get_total_loss()
self.tensors['loss'] = loss
if self.optimizer == 'adam':
optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)
try:
grads_and_vars = optimizer.compute_gradients(loss=loss)
if self.clip_gradients is not None:
grads_and_vars = [(tf.clip_by_value(t=grad, clip_value_min=-self.clip_gradients, clip_value_max=self.clip_gradients), var) for grad, var in grads_and_vars]
self.optimization = optimizer.apply_gradients(grads_and_vars=grads_and_vars)
except ValueError as exc:
if str(exc) == 'No variables to optimize.':
if self.optimization is None:
self.optimization = tf.no_op()
else:
raise exc
self.scope.__exit__(type, value, tb)
assert Model.current is not None
Model.current = None
def finalize(self, restore=False):
assert not self.defined
if self.weight_decay is not None and self.weight_decay > 0.0:
for name, variable in self.variables.items():
regularization = self.weight_decay * tf.nn.l2_loss(t=variable, name=(name + '-regularization'))
tf.losses.add_loss(loss=regularization, loss_collection=tf.GraphKeys.REGULARIZATION_LOSSES)
loss = tf.losses.get_total_loss()
self.tensors['loss'] = loss
if self.optimizer == 'adam':
optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)
try:
grads_and_vars = optimizer.compute_gradients(loss=loss)
if self.clip_gradients is not None:
grads_and_vars = [(tf.clip_by_value(t=grad, clip_value_min=-self.clip_gradients, clip_value_max=self.clip_gradients), var) for grad, var in grads_and_vars]
self.optimization = optimizer.apply_gradients(grads_and_vars=grads_and_vars)
except ValueError as exc:
if str(exc) == 'No variables to optimize.':
if self.optimization is None:
self.optimization = tf.no_op()
else:
raise exc
global_variables_initializer = tf.global_variables_initializer()
if self.model_directory is not None:
self.saver = tf.train.Saver()
if self.summary_directory is not None:
tf.summary.scalar(name='loss', tensor=loss)
for variable in tf.trainable_variables():
tf.summary.histogram(name=variable.name, values=variable)
self.summaries = tf.summary.merge_all()
self.scope.__exit__(None, None, None)
self.scope = None
tf.get_default_graph().finalize()
self.defined = True
self.session = tf.Session()
if restore:
assert self.model_directory
# save_path = tf.train.latest_checkpoint(checkpoint_dir=self.model_directory)
self.saver.restore(sess=self.session, save_path=(self.model_directory + 'model'))
else:
self.session.run(fetches=global_variables_initializer)
if self.summary_directory is not None:
self.summary_writer = tf.summary.FileWriter(logdir=self.summary_directory, graph=self.session.graph)
self.coordinator = tf.train.Coordinator()
self.queue_threads = tf.train.start_queue_runners(sess=self.session, coord=self.coordinator)
def save(self):
assert self.defined
if self.model_directory:
self.saver.save(sess=self.session, save_path=(self.model_directory + 'model'))
def __call__(self, query=None, data=None, optimize=False, summarize=False, dropout=None):
assert self.session
if query is None:
fetches = dict()
elif isinstance(query, str):
fetches = dict(query=self.tensors[query])
else:
fetches = {name: self.tensors[name] for name in query}
if data is None:
feed_dict = dict()
elif isinstance(data, dict):
feed_dict = {self.placeholders[name]: value for name, value in data.items() if name in self.placeholders}
else:
assert len(self.placeholders) == 1
feed_dict = {next(iter(self.placeholders.values())): data}
if optimize:
feed_dict[self.training] = True
assert 'optimization' not in fetches
fetches['optimization'] = self.optimization
else:
feed_dict[self.training] = False
if self.summary_directory is not None and summarize:
assert 'summaries' not in fetches
fetches['summaries'] = self.summaries
assert dropout is None or 0.0 <= dropout < 1.0
if dropout is None:
feed_dict[self.dropout] = 0.0
else:
feed_dict[self.dropout] = dropout
fetched = self.session.run(fetches=fetches, feed_dict=feed_dict)
if optimize:
fetched.pop('optimization')
if self.summary_directory is not None and summarize:
fetched.pop('summaries')
return fetched
class Unit(object):
num_in = None
num_out = None
index = 0
def __init__(self, name=None, template=True):
assert Model.current is not None
assert self.num_in is not None and self.num_out is not None
assert name is None or isinstance(name, str)
if name is None:
name = self.__class__.__name__ + str(self.__class__.index)
self.__class__.index += 1
self.name = name
self.initialized = False
self.outputs = dict()
if template:
self.fn_forward = tf.make_template(name_=str(self), func_=self.forward, create_scope_now_=True)
else:
self.fn_forward = self.forward
def __str__(self):
return self.name
def __repr__(self):
return str(self)
def initialize(self, *xs):
assert not self.initialized
self.initialized = True
def forward(self, *xs):
# try:
# assert any(self.num_in == num_in for num_in in self.__class__.num_in)
# except TypeError:
# assert self.num_in == self.__class__.num_in
assert len(xs) == self.num_in or self.num_in == -1, (len(xs), self.num_in)
if not self.initialized:
self.initialize(*xs)
def __call__(self, inputs=(), output_key=None):
assert output_key is None or isinstance(output_key, str)
if output_key is not None and output_key in self.outputs:
return self.outputs[output_key]
output = self.fn_forward(*inputs)
if isinstance(output, tf.Tensor):
if output_key is not None:
self.outputs[output_key] = output
Model.current.register_tensor(key=output_key, tensor=output)
elif len(output) == 1:
output = output[0]
if output_key is not None:
self.outputs[output_key] = output
Model.current.register_tensor(key=output_key, tensor=output)
else:
output = tuple(output)
if output_key is not None:
self.outputs[output_key] = output
for n, tensor in enumerate(output):
Model.current.register_tensor(key=(output_key + str(n)), tensor=tensor)
return output
def __rshift__(self, other):
assert isinstance(other, Unit)
if self.num_in == 0:
assert self.num_out == other.num_in or other.num_in == -1, (self.num_out, other.num_in)
inputs = self()
inputs = (inputs,) if isinstance(inputs, tf.Tensor) else inputs
return other(inputs=inputs)
else:
return Composed(first=self, second=other)
def __rrshift__(self, other):
if isinstance(other, tf.Tensor):
return self(inputs=(other,))
inputs = list()
composed = False
for x in other:
if isinstance(x, tf.Tensor):
inputs.append(x)
elif x.num_in == 0:
x = x()
assert isinstance(x, tf.Tensor)
inputs.append(x)
elif isinstance(x, Unit):
inputs.append(x)
composed = True
else:
assert False
# x = x()
# assert isinstance(x, tf.Tensor)
# inputs.append(x)
if composed:
return Composed(first=inputs, second=self)
else:
assert len(inputs) == self.num_in or self.num_in == -1, (len(inputs), self.num_in)
return self(inputs=inputs)
class Composed(Unit):
def __init__(self, first, second):
if isinstance(first, Unit):
assert first.num_out == second.num_in or second.num_in == -1, (first.num_out, second.num_in)
self.num_in = first.num_in
else:
assert all(isinstance(unit, tf.Tensor) or unit.num_out == 1 for unit in first)
assert len(first) == second.num_in or second.num_in == -1, (len(first), second.num_in)
self.num_in = 1
self.num_out = second.num_out
super(Composed, self).__init__(template=False)
self.first = first
self.second = second
def __str__(self):
return '({} -> {})'.format(self.first, self.second)
def initialize(self, *xs):
assert not self.initialized
self.initialized = True
def forward(self, *xs):
super(Composed, self).forward(*xs)
# assert isinstance(self.first, Unit) or len(xs) == 1
if isinstance(self.first, Unit):
assert all(isinstance(x, tf.Tensor) for x in xs)
if len(xs) == 1:
xs = xs[0]
return xs >> self.first >> self.second
else:
assert all(isinstance(x, tf.Tensor) for x in xs)
if len(xs) == 1:
xs = tuple(unit if isinstance(unit, tf.Tensor) else xs[0] >> unit for unit in self.first)
else:
xs = tuple(unit if isinstance(unit, tf.Tensor) else xs >> unit for unit in self.first)
assert all(isinstance(x, tf.Tensor) for x in xs)
return xs >> self.second
def __rshift__(self, other):
assert isinstance(other, Unit)
return Composed(first=self, second=other)
# Create a custom class with some arguments specified
def customize(unit_, **specified):
class CustomUnit(unit_):
def __init__(self, **kwargs):
assert all(arg not in kwargs for arg in specified)
kwargs.update(specified)
if kwargs.get('name') is None:
kwargs['name'] = unit_.__name__ + str(unit_.index)
unit_.index += 1
super(CustomUnit, self).__init__(**kwargs)
return CustomUnit
class Layer(Unit):
num_in = 1
num_out = 1
def __init__(self, size, name=None):
super(Layer, self).__init__(name=name)
assert self.__class__.num_in == self.__class__.num_out
assert isinstance(size, int) and size >= 0
if size == 0:
size = 1
self.squeeze = True
else:
self.squeeze = False
self.size = size
class LayerStack(Unit):
num_in = 1
num_out = 1
def initialize(self, *xs):
super(LayerStack, self).initialize(*xs)
self.layers = list()
def forward(self, *xs):
super(LayerStack, self).forward(*xs)
for layer in self.layers:
xs >>= layer
return xs
class Variable(Unit):
num_in = 0
num_out = 1
def __init__(self, name, shape=None, dtype='float', init='out', value=None):
super(Variable, self).__init__(name=name)
assert self.__class__.num_in == 0 and self.__class__.num_out == 1
assert isinstance(name, str)
if shape is not None:
shape = (shape,) if isinstance(shape, int) else tuple(shape)
assert len(shape) > 0 and all(isinstance(n, int) and n > 0 for n in shape)
assert init in ('constant', 'zeros', 'ones', 'in', 'out', 'in-out', 'stddev') or Activation.valid(init)
assert init in ('constant', 'zeros', 'ones') or dtype == 'float'
self.shape = shape
self.dtype, self.dtype_bytes = Model.dtype(dtype=dtype, include_bytes=True)
self.init = init
self.value = value
def specify_shape(self, shape):
if self.shape is None:
self.shape = shape
else:
assert self.shape == shape
def forward(self):
super(Variable, self).forward()
# TODO: own instead of tf.contrib.layers.variance_scaling_initializer, and with min(?, 0.01)
assert self.shape is not None
if self.init == 'zeros':
initializer = tf.zeros_initializer(dtype=self.dtype)
elif self.init == 'ones':
initializer = tf.ones_initializer(dtype=self.dtype)
elif self.init == 'stddev':
assert self.value is not None
initializer = tf.random_normal_initializer(mean=0.0, stddev=self.value, dtype=tf.float32)
elif self.init == 'selu':
initializer = tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_OUT', dtype=self.dtype)
elif self.init == 'out':
initializer = tf.contrib.layers.variance_scaling_initializer(factor=2.0, mode='FAN_OUT', dtype=self.dtype)
elif self.init == 'in' or self.init in ('elu', 'relu'):
assert len(self.shape) >= 2
initializer = tf.contrib.layers.variance_scaling_initializer(factor=2.0, mode='FAN_IN', dtype=self.dtype)
elif self.init == 'in-out' or Activation.valid(self.init):
assert len(self.shape) >= 2
initializer = tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG', dtype=self.dtype)
else:
assert False
variable = tf.get_variable(name=str(self), shape=self.shape, dtype=self.dtype, initializer=initializer)
num_parameters = product(self.shape)
num_bytes = num_parameters * self.dtype_bytes
Model.current.register_variable(key='{}/{}'.format(tf.get_variable_scope().name, str(self)), variable=variable, num_parameters=num_parameters, num_bytes=num_bytes)
return tf.identity(input=variable)
class Linear(Layer):
def __init__(self, size, bias=True, name=None):
super(Linear, self).__init__(size=size, name=name)
assert isinstance(bias, bool)
self.weights = None
self.bias = bias
def initialize(self, x):
super(Linear, self).initialize(x)
if rank(x) == 2:
self.weights = Variable(name='weights', shape=(shape(x)[-1], self.size), init='in-out')
elif rank(x) == 3:
self.weights = Variable(name='weights', shape=(1, shape(x)[-1], self.size), init='in-out')
elif rank(x) == 4:
self.weights = Variable(name='weights', shape=(1, 1, shape(x)[-1], self.size), init='in-out')
self.bias = Variable(name='bias', shape=self.size, init='zeros') if self.bias else None
def forward(self, x):
super(Linear, self).forward(x)
assert 2 <= rank(x) <= 4
if rank(x) == 2:
x = tf.matmul(a=x, b=self.weights())
elif rank(x) == 3:
x = tf.nn.conv1d(value=x, filters=self.weights(), stride=1, padding='SAME')
elif rank(x) == 4:
x = tf.nn.conv2d(input=x, filter=self.weights(), strides=(1, 1, 1, 1), padding='SAME')
if self.bias is not None:
x = tf.nn.bias_add(value=x, bias=self.bias())
if self.squeeze:
x = tf.squeeze(input=x, axis=-1)
return x
class Input(Unit):
num_in = 0
num_out = 1
def __init__(self, name, shape, dtype='float', batched=True, tensor=None):
super(Input, self).__init__(name=name)
assert isinstance(name, str)
shape = (shape,) if isinstance(shape, int) else tuple(shape)
assert all(isinstance(n, int) and (n > 0 or n == -1) for n in shape)
assert isinstance(batched, bool)
self.shape = tuple(None if x == -1 else x for x in shape)
self.dtype = Model.dtype(dtype=dtype)
if batched:
self.shape = (None,) + self.shape
self.tensor = tensor
def forward(self):
super(Input, self).forward()
if self.tensor is None:
placeholder = tf.placeholder(dtype=self.dtype, shape=self.shape, name=str(self))
Model.current.register_placeholder(key=str(self), placeholder=placeholder)
self.tensor = tf.identity(input=placeholder)
return self.tensor
class Output(Unit):
num_in = 1
num_out = 2
def __init__(self, name, shape, dtype='float', batched=True, tensor=None):
super(Output, self).__init__(name=name)
assert isinstance(name, str)
self.shape = shape
self.dtype = dtype
self.batched = batched
self.tensor = tensor
def initialize(self, x):
super(Output, self).initialize(x)
self.input = Input(name=str(self), shape=self.shape, dtype=self.dtype, batched=self.batched, tensor=self.tensor)
class Binary(Output):
def __init__(self, name, binary_transform=True, soft=0.0, tensor=None):
super(Binary, self).__init__(name=name, shape=(), tensor=tensor)
assert isinstance(binary_transform, bool)
assert isinstance(soft, float) and 0.0 <= soft < 0.5
self.binary_transform = binary_transform
self.soft = soft
def initialize(self, x):
super(Binary, self).initialize(x)
self.linear = Linear(size=0)
def forward(self, x):
super(Binary, self).forward(x)
correct = self.input()
if self.soft > 0.0:
noise = tf.random_uniform(shape=tf.shape(input=correct), minval=0.0, maxval=self.soft)
soft_correct = tf.abs(x=(correct - noise))
else:
soft_correct = correct
if self.binary_transform:
x >>= self.linear
x = (tf.tanh(x=x) + 1.0) / 2.0
cross_entropy = -(soft_correct * tf.log(x=tf.maximum(x=x, y=1e-8)) + (1.0 - soft_correct) * tf.log(x=tf.maximum(x=(1.0 - x), y=1e-8)))
loss = tf.reduce_mean(input_tensor=cross_entropy)
tf.losses.add_loss(loss=loss)
prediction = tf.cast(x=tf.greater(x=x, y=tf.constant(value=0.5)), dtype=Model.dtype('float'))
num_correct = tf.cast(x=tf.equal(x=prediction, y=correct), dtype=Model.dtype('float'))
accuracy = tf.reduce_mean(input_tensor=num_correct)
Model.current.register_tensor(key=(str(self) + '_accuracy'), tensor=accuracy)
return correct, prediction
class Classification(Output):
def __init__(self, name, num_classes, multi_class=False, soft=0.0, tensor=None):
super(Classification, self).__init__(name=name, shape=(), tensor=tensor)
assert isinstance(num_classes, int) and num_classes > 0
assert isinstance(multi_class, bool)
assert isinstance(soft, float) and 0.0 <= soft < 0.5
self.num_classes = num_classes
self.multi_class = multi_class
self.soft = soft
def initialize(self, x):
super(Classification, self).initialize(x)
self.linear = Linear(size=self.num_classes)
def forward(self, x):
super(Classification, self).forward(x)
correct = self.input()
if not self.multi_class and rank(correct) == 1:
correct = tf.cast(correct, tf.int32)
correct_onehot = tf.one_hot(indices=correct, depth=self.num_classes)
else:
correct_onehot = correct
if self.soft > 0.0:
noise = tf.random_uniform(shape=(1, shape(correct_onehot)[1]), minval=0.0, maxval=self.soft)
soft_correct = tf.abs(x=(correct_onehot - noise))
else:
soft_correct = correct_onehot
x >>= self.linear
if self.multi_class:
tf.losses.sigmoid_cross_entropy(multi_class_labels=soft_correct, logits=x)
else:
tf.losses.softmax_cross_entropy(onehot_labels=soft_correct, logits=x)
prediction = tf.argmax(input=x, axis=1)
prediction_onehot = tf.one_hot(indices=prediction, depth=self.num_classes)
if self.multi_class or rank(correct) == 2:
prediction = prediction_onehot
relevant = tf.reduce_sum(input_tensor=correct_onehot, axis=1)
selected = tf.reduce_sum(input_tensor=prediction_onehot, axis=1)
true_positive = tf.reduce_sum(input_tensor=tf.minimum(x=prediction_onehot, y=correct_onehot), axis=1)
precision = tf.reduce_mean(input_tensor=tf.divide(x=true_positive, y=selected), axis=0)
recall = tf.reduce_mean(input_tensor=tf.divide(x=true_positive, y=relevant), axis=0)
fscore = (2 * precision * recall) / (precision + recall)
Model.current.register_tensor(key=(str(self) + '_precision'), tensor=precision)
Model.current.register_tensor(key=(str(self) + '_recall'), tensor=recall)
Model.current.register_tensor(key=(str(self) + '_fscore'), tensor=fscore)
return correct, prediction
class Distance(Output):
def __init__(self, name, shape, tensor=None):
super(Distance, self).__init__(name=name, shape=shape, tensor=tensor)
def forward(self, x):
super(Distance, self).forward(x)
correct = self.input()
prediction = x
tf.losses.mean_squared_error(labels=correct, predictions=prediction)
return correct, prediction
class Identity(Unit):
num_in = 1
num_out = 1
def forward(self, *xs):
super(Identity, self).forward(*xs)
assert len(xs) >= 1
return xs[0] if len(xs) == 1 else xs
class Print(Unit):
num_in = -1
num_out = -1
def __init__(self, size=10, times=None, prefix=None, name=None):
super(Print, self).__init__(name=name)
assert isinstance(size, int) and size > 0
assert times is None or isinstance(times, int) and times > 0
assert prefix is None or isinstance(prefix, str)
self.size = size
self.times = times
self.prefix = prefix
def forward(self, *xs):
super(Print, self).forward(*xs)
if self.prefix is None or self.prefix[-2:] == ': ':
message = self.prefix
elif self.prefix[-1] == ':':
message = self.prefix + ' '
else:
message = self.prefix + ': '
return (tf.Print(input_=xs[0], data=xs, message=message, first_n=self.times, summarize=self.size),) + tuple(xs[1:])
class Constant(Unit):
num_in = 1
num_out = 1
def __init__(self, value, dtype, name=None):
super(Constant, self).__init__(name=name)
self.value = value
self.dtype = dtype
def forward(self, x):
super(Constant, self).forward(x)
batch_size = tf.shape(input=x)[0]
x = tf.constant(value=self.value, dtype=Model.dtype(self.dtype))
multiples = (batch_size,) + tuple(1 for _ in range(rank(x)))
return tf.tile(input=tf.expand_dims(input=x, axis=0), multiples=multiples)
class Select(Unit):
num_in = -1
num_out = 1
def __init__(self, index, name=None):
super(Select, self).__init__(name=name)
assert isinstance(index, int) and index >= 0
self.index = index
def forward(self, *xs):
super(Select, self).forward(*xs)
assert len(xs) > self.index
return xs[self.index]
class Activation(Unit):
num_in = 1
num_out = 1
@staticmethod
def valid(activation):
return activation in ('elu', 'relu', 'sigmoid', 'softmax', 'tanh')
def __init__(self, activation='relu', name=None):
super(Activation, self).__init__(name=name)
assert Activation.valid(activation)
self.activation = activation
def forward(self, x):
super(Activation, self).forward(x)
if self.activation == 'elu':
return tf.nn.elu(features=x)
elif self.activation == 'relu':
return tf.nn.relu(features=x)
elif self.activation == 'selu':
# https://arxiv.org/pdf/1706.02515.pdf
alpha = 1.6732632423543772848170429916717
scale = 1.0507009873554804934193349852946
return scale * tf.where(condition=(x >= 0.0), x=x, y=(alpha * tf.nn.elu(features=x)))
elif self.activation == 'sigmoid':
return tf.sigmoid(x=x)
elif self.activation == 'softmax':
return tf.nn.softmax(logits=x)
elif self.activation == 'tanh':
return tf.nn.tanh(x=x)
class Dropout(Unit):
num_in = 1
num_out = 1
def forward(self, x):
super(Dropout, self).forward(x)
return tf.nn.dropout(x=x, rate=Model.current.dropout)
class Normalization(Unit):
# https://arxiv.org/abs/1803.08494
num_in = 1
num_out = 1
@staticmethod
def valid(normalization):
return normalization in ('batch', 'group', 'instance', 'layer')
def __init__(self, normalization, scale=True, offset=True, variance_epsilon=1e-6, name=None):
super(Normalization, self).__init__(name=name)
assert Normalization.valid(normalization)
assert isinstance(scale, bool)
assert isinstance(offset, bool)
assert isinstance(variance_epsilon, float) and variance_epsilon > 0.0
self.normalization = normalization
self.scale = scale
self.offset = offset
self.variance_epsilon = variance_epsilon
# hyperparameter 32 for 'group'
def initialize(self, x):
super(Normalization, self).initialize(x)
if self.normalization == 'batch':
self.exp_moving_average = tf.train.ExponentialMovingAverage(decay=0.9, num_updates=None)
mean_shape = tuple(1 for _ in range(rank(x) - 1)) + (shape(x)[-1],)
if self.scale:
self.scale = Variable(name='scale', shape=mean_shape, init='zeros')
else:
self.scale = None
if self.offset:
self.offset = Variable(name='offset', shape=mean_shape, init='zeros')
else:
self.offset = None
def forward(self, x):
super(Normalization, self).forward(x)
if self.normalization == 'batch':
mean, variance = tf.nn.moments(x=x, axes=tuple(range(rank(x) - 1)), keep_dims=True)
elif self.normalization == 'group':
tensor_shape = shape(x)
x = tf.reshape(input=x, shape=(tensor_shape[:-1], tensor_shape[-1] // 32, 32)) # hyperparameter!!!
mean, variance = tf.nn.moments(x=x, axes=tuple(1, range(rank(x) - 1)), keep_dims=True)
elif self.normalization == 'instance':
mean, variance = tf.nn.moments(x=x, axes=tuple(range(1, rank(x) - 1)), keep_dims=True)
elif self.normalization == 'layer':
mean, variance = tf.nn.moments(x=x, axes=tuple(range(1, rank(x))), keep_dims=True)
if self.normalization != 'instance':
def true_fn():
exp_moving_average_op = self.exp_moving_average.apply(var_list=(mean, variance))
with tf.control_dependencies(control_inputs=(exp_moving_average_op,)):
return tf.identity(input=mean), tf.identity(input=variance)
def false_fn():
return self.exp_moving_average.average(var=mean), self.exp_moving_average.average(var=variance)
mean, variance = tf.cond(pred=Model.current.training, true_fn=true_fn, false_fn=false_fn)
if self.scale is None:
scale = None
else:
scale = 1.0 + self.scale()
if self.offset is None:
offset = None
else:
offset = self.offset()
if self.normalization == 'group':
x = tf.nn.batch_normalization(x=x, mean=mean, variance=variance, offset=None, scale=None, variance_epsilon=self.variance_epsilon)
x = tf.reshape(input=x, shape=tensor_shape)
return x * scale + offset
else:
return tf.nn.batch_normalization(x=x, mean=mean, variance=variance, offset=offset, scale=scale, variance_epsilon=self.variance_epsilon)
class FeaturewiseLinearModulation(Unit):
num_in = 2
num_out = 1
def __init__(self, scale=Linear, offset=Linear, name=None):
super(FeaturewiseLinearModulation, self).__init__(name=name)
assert issubclass(scale, Layer)
assert issubclass(offset, Layer)
self.scale = scale
self.offset = offset
def initialize(self, x, condition):
super(FeaturewiseLinearModulation, self).initialize(x, condition)
size = shape(x)[-1]
self.scale = self.scale(size=size)
self.offset = self.offset(size=size)
def forward(self, x, condition):
super(FeaturewiseLinearModulation, self).forward(x, condition)
scale = 1.0 + (condition >> self.scale)
scale = tf.expand_dims(input=tf.expand_dims(input=scale, axis=1), axis=2)
offset = condition >> self.offset
offset = tf.expand_dims(input=tf.expand_dims(input=offset, axis=1), axis=2)
return x * scale + offset
class FiLM(Unit):
num_in = 2
num_out = 1
def __init__(self, layer, scale=Linear, offset=Linear, normalization='instance', activation='relu', dropout=False, norm_act_film_before=False, name=None, **kwargs):
super(FiLM, self).__init__(name=name)
assert issubclass(layer, Layer)
assert issubclass(scale, Layer) and issubclass(offset, Layer)
assert not normalization or Normalization.valid(normalization)
assert not activation or Activation.valid(activation)
assert isinstance(dropout, bool)
assert isinstance(norm_act_film_before, bool)
self.layer = layer
self.scale = scale
self.offset = offset
self.normalization = normalization
self.activation = activation
self.dropout = dropout
self.norm_act_film_before = norm_act_film_before
self.kwargs = kwargs # kwargs ??????????
def initialize(self, x, condition):
super(FiLM, self).initialize(x, condition)
self.layer = self.layer(normalization=False, activation=None, dropout=False, **self.kwargs)
self.film = FeaturewiseLinearModulation(offset=self.offset, scale=self.scale)
self.normalization = Normalization(normalization=self.normalization, scale=False, offset=False) if self.normalization else None
self.activation = Activation(activation=self.activation) if self.activation else None
self.dropout = Dropout() if self.dropout else None
def forward(self, x, condition):
super(FiLM, self).forward(x, condition)
if self.norm_act_film_before:
if self.normalization is not None:
x >>= self.normalization
x = (x, condition) >> self.film
if self.activation is not None:
x >>= self.activation
if self.dropout is not None:
x >>= self.dropout
x >>= self.layer
if not self.norm_act_film_before:
if self.normalization is not None:
x >>= self.normalization
x = (x, condition) >> self.film
if self.activation is not None:
x >>= self.activation
if self.dropout is not None:
x >>= self.dropout
return x
class Reduction(Unit):
num_in = -1
num_out = 1
@staticmethod
def valid(reduction):
return reduction in ('cbp', 'collapse', 'concat', 'conv', 'conv2d', 'last', 'max', 'mean', 'min', 'prod', 'stack', 'sum')
def __init__(self, reduction, axis=-1, arg=-1, name=None):
super(Reduction, self).__init__(name=name)
assert Reduction.valid(reduction)
if isinstance(axis, int):
axis = (axis,)
elif len(axis) == 3 and axis[1] is Ellipsis:
assert isinstance(axis[0], int) and isinstance(axis[2], int)
axis = tuple(axis)
else:
assert len(axis) > 0 and all(isinstance(a, int) for a in axis)
axis = tuple(sorted(axis))
assert len(set(axis)) == len(axis)
assert isinstance(arg, int)
self.reduction = reduction
self.axis = axis
self.arg = arg
self.multiple_inputs = None
self.weights = None
def initialize(self, *xs):
super(Reduction, self).initialize(*xs)