-
Notifications
You must be signed in to change notification settings - Fork 331
/
nn.py
1464 lines (1178 loc) · 48.3 KB
/
nn.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
# Copyright 2023 The DDSP Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Library of neural network functions."""
import inspect
from ddsp import core
from ddsp import losses
import gin
import tensorflow as tf
import tensorflow_probability as tfp
tfk = tf.keras
tfkl = tfk.layers
# False positive lint error on tf.split().
# pylint: disable=redundant-keyword-arg
def gin_register_keras_layers():
"""Registers all keras layers and Sequential to be referenceable in gin."""
# Register sequential model.
gin.external_configurable(tf.keras.Sequential, 'tf.keras.Sequential')
# Register all the layers.
for k, v in inspect.getmembers(tf.keras.layers):
# Duck typing for tf.keras.layers.Layer since keras uses metaclasses.
if hasattr(v, 'variables'):
gin.external_configurable(v, f'tf.keras.layers.{k}')
gin_register_keras_layers()
class DictLayer(tfkl.Layer):
"""Wrap a Keras Layer to take dictionary inputs and outputs.
Note that all return values will be converted to a dictionary, even if
the `call()` returns a tuple. For instance, a function like so:
```
class MyLayer(DictLayer):
# --- (init ignored)
def call(self, a, b, c) --> ['x', 'y', 'z']:
# Do something cool
return a, b, c # Note: returned as tuple in call().
```
Will return the following:
>>> my_layer = MyLayer()
>>> my_layer(1, 2, 3)
{'x': 1, 'y': 2, 'z': 3} # Note: returned values is dict when called.
"""
def __init__(self, input_keys=None, output_keys=None, **kwargs):
"""Constructor, define input and output keys.
Args:
input_keys: A list of keys to read out of a dictionary passed to call().
If no input_keys are provided to the constructor, they are inferred from
the argument names in call(). Input_keys are ignored if call() recieves
tensors as arguments instead of a dict.
output_keys: A list of keys to name the outputs returned from call(), and
construct an outputs dictionary. If call() returns a dictionary, these
keys are ignored. If no output_keys are provided to the constructor,
they are inferred from return annotation of call() (a list of strings).
**kwargs: Other keras layer kwargs such as name.
"""
super().__init__(**kwargs)
if not input_keys:
input_keys = self.get_argument_names('call')
self.default_input_keys = list(self.get_default_argument_names('call'))
self.default_input_values = list(self.get_default_argument_values('call'))
else:
# Manually specifying input keys overwrites default arguments.
self.default_input_keys = []
self.default_input_values = []
output_keys = output_keys or self.get_return_annotations('call')
self.input_keys = list(input_keys)
self.output_keys = list(output_keys)
@property
def all_input_keys(self):
"""Full list of inputs and outputs."""
return self.input_keys + self.default_input_keys
@property
def n_inputs(self):
"""Dynamically computed in case input_keys is changed in subclass init."""
return len(self.all_input_keys)
def __call__(self, *inputs, **kwargs):
"""Wrap the layer's __call__() with dictionary inputs and outputs.
IMPORTANT: If no input_keys are provided to the constructor, they are
inferred from the argument names in call(). If no output_keys are provided
to the constructor, they are inferred from return annotation of call()
(a list of strings).
Example:
========
```
def call(self, f0_hz, loudness, power=None) -> ['amps', 'frequencies']:
...
return amps, frequencies
```
Will infer `self.input_keys = ['f0_hz', 'loudness']` and
`self.output_keys = ['amps', 'frequencies']`. If input_keys, or output_keys
are provided to the constructor they will override these inferred values.
It will also infer `self.default_input_keys = ['power']`, which it will try
to look up the inputs, but use the default values and not throw an error if
the key is not in the input dictionary.
Example Usage:
==============
The the example above works with both tensor inputs `layer(f0_hz, loudness)`
or `layer(f0_hz, loudness, power)` or a dictionary of tensors
`layer({'f0_hz':..., 'loudness':...})`, or
`layer({'f0_hz':..., 'loudness':..., 'power':...})` and in both cases will
return a dictionary of tensors `{'amps':..., 'frequencies':...}`.
Args:
*inputs: Arguments passed on to call(). If any arguments are dicts, they
will be merged and self.input_keys will be read out of them and passed
to call() while other args will be ignored.
**kwargs: Keyword arguments passed on to call().
Returns:
outputs: A dictionary of layer outputs from call(). If the layer call()
returns a dictionary it will be returned directly, otherwise the output
tensors will be wrapped in a dictionary {output_key: output_tensor}.
"""
# Construct a list of input tensors equal in length and order to the `call`
# input signature.
# -- Start first with any tensor arguments.
# -- Then lookup tensors from input dictionaries.
# -- Use default values if not found.
# Start by merging all dictionaries of tensors from the input.
input_dict = {}
for v in inputs:
if isinstance(v, dict):
input_dict.update(v)
# And then strip all dictionaries from the input.
inputs = [v for v in inputs if not isinstance(v, dict)]
# Add any tensors from kwargs.
for key in self.all_input_keys:
if key in kwargs:
input_dict[key] = kwargs[key]
# And strip from kwargs.
kwargs = {k: v for k, v in kwargs.items() if k not in self.all_input_keys}
# Look up further inputs from the dictionaries.
for key in self.input_keys:
try:
# If key is present use the input_dict value.
inputs.append(core.nested_lookup(key, input_dict))
except KeyError:
# Skip if not present.
pass
# Add default arguments.
for key, value in zip(self.default_input_keys, self.default_input_values):
try:
# If key is present, use the input_dict value.
inputs.append(core.nested_lookup(key, input_dict))
except KeyError:
# Otherwise use the default value if not supplied as non-dict input.
if len(inputs) < self.n_inputs:
inputs.append(value)
# Run input tensors through the model.
if len(inputs) != self.n_inputs:
raise TypeError(f'{len(inputs)} input tensors extracted from inputs'
'(including default args) but the layer expects '
f'{self.n_inputs} tensors.\n'
f'Input keys: {self.input_keys}\n'
f'Default keys: {self.default_input_keys}\n'
f'Default values: {self.default_input_values}\n'
f'Input dictionaries: {input_dict}\n'
f'Input Tensors (Args, Dicts, and Defaults): {inputs}\n')
outputs = super().__call__(*inputs, **kwargs)
# Return dict if call() returns it.
if isinstance(outputs, dict):
return outputs
# Otherwise make a dict from output_keys.
else:
outputs = core.make_iterable(outputs)
if len(self.output_keys) != len(outputs):
raise ValueError(f'Output keys ({self.output_keys}) must have the same'
f'length as outputs ({outputs})')
return dict(zip(self.output_keys, outputs))
def get_argument_names(self, method):
"""Get list of strings for names of required arguments to method."""
spec = inspect.getfullargspec(getattr(self, method))
if spec.defaults:
n_defaults = len(spec.defaults)
return spec.args[1:-n_defaults]
else:
return spec.args[1:]
def get_default_argument_names(self, method):
"""Get list of strings for names of default arguments to method."""
spec = inspect.getfullargspec(getattr(self, method))
if spec.defaults:
n_defaults = len(spec.defaults)
return spec.args[-n_defaults:]
else:
return []
def get_default_argument_values(self, method):
"""Get list of strings for names of default arguments to method."""
spec = inspect.getfullargspec(getattr(self, method))
if spec.defaults:
return spec.defaults
else:
return []
def get_return_annotations(self, method):
"""Get list of strings of return annotations of method."""
spec = inspect.getfullargspec(getattr(self, method))
return core.make_iterable(spec.annotations['return'])
class OutputSplitsLayer(DictLayer):
"""A DictLayer that splits an output tensor into a dictionary of tensors."""
def __init__(self,
input_keys=None,
output_splits=(('amps', 1), ('harmonic_distribution', 40)),
**kwargs):
"""Layer constructor.
A common architecture is to have a homogenous network with a final dense
layer for each output type, for instance, for each parameter of a
synthesizer. This base layer wraps this process by just requiring that
`compute_output()` return a single tensor, which is then run through a dense
layer and split into a dict according to `output_splits`.
Args:
input_keys: A list of keys to read out of a dictionary passed to call().
If no input_keys are provided to the constructor, they are inferred from
the argument names in compute_outputs().
output_splits: A list of tuples (output_key, n_channels). Output keys are
extracted from the list and the output tensor from compute_output(), is
split into a dictionary of tensors, each with its matching n_channels.
**kwargs: Other tf.keras.layer kwargs, such as name.
"""
self.output_splits = output_splits
self.n_out = sum([v[1] for v in output_splits])
self.dense_out = tfkl.Dense(self.n_out)
input_keys = input_keys or self.get_argument_names('compute_output')
output_keys = [v[0] for v in output_splits]
super().__init__(input_keys=input_keys, output_keys=output_keys, **kwargs)
def call(self, *inputs, **unused_kwargs):
"""Run compute_output(), dense output layer, then split to a dictionary."""
output = self.compute_output(*inputs)
return split_to_dict(self.dense_out(output), self.output_splits)
def compute_output(self, *inputs):
"""Takes tensors as input, runs network, and outputs a single tensor.
Args:
*inputs: A variable number of tensor inputs. Automatically infers
self.input_keys from the name of each argmument in the function
signature.
Returns:
A single tensor (usually [batch, time, channels]). The tensor can have any
number of channels, because the base layer will run through a final dense
layer to compress to appropriate number of channels for output_splits.
"""
raise NotImplementedError
# ------------------------ Shapes ----------------------------------------------
def ensure_4d(x):
"""Add extra dimensions to make sure tensor has height and width."""
if len(x.shape) == 2:
return x[:, tf.newaxis, tf.newaxis, :]
elif len(x.shape) == 3:
return x[:, :, tf.newaxis, :]
else:
return x
def inv_ensure_4d(x, n_dims):
"""Remove excess dims, inverse of ensure_4d() function."""
if n_dims == 2:
return x[:, 0, 0, :]
if n_dims == 3:
return x[:, :, 0, :]
else:
return x
# ------------------ Utilities -------------------------------------------------
@gin.register
def split_to_dict(tensor, tensor_splits):
"""Split a tensor into a dictionary of multiple tensors."""
labels = [v[0] for v in tensor_splits]
sizes = [v[1] for v in tensor_splits]
tensors = tf.split(tensor, sizes, axis=-1)
return dict(zip(labels, tensors))
def get_nonlinearity(nonlinearity):
"""Get nonlinearity function by name."""
try:
return tf.keras.activations.get(nonlinearity)
except ValueError:
pass
return getattr(tf.nn, nonlinearity)
# ------------------ Straight-through Estimators -------------------------------
def straight_through_softmax(logits):
"""Straight-through estimator of a one-hot categorical distribution."""
probs = tf.nn.softmax(logits)
one_hot = tfp.distributions.OneHotCategorical(probs=probs)
sample = tf.cast(one_hot.sample(), tf.float32)
p_sample = probs * sample
sample = tf.stop_gradient(sample - p_sample) + p_sample
return sample, probs
def straight_through_choice(logits, values):
"""Straight-throgh estimator of choosing a value using a boolean mask."""
choice, _ = straight_through_softmax(logits)
return tf.reduce_sum(choice * values, axis=-1, keepdims=True)
def straight_through_int_quantization(x):
"""Rounds tensor to nearest integer using a straight through estimator.
Args:
x (tf.Tensor): Input Tensor that will get quantized. Values will be rounded
to the nearest integer and are not assumed to be scaled (i.e., values in
[-1.0, 1.0] will only produce -1, 0, or 1).
Returns:
A quantized version of the input Tensor `x`, with gradients as if no
quantization happened.
"""
return x + tf.stop_gradient(tf.math.round(x) - x)
# Masking ----------------------------------------------------------------------
def get_note_mask(q_pitch, max_regions=100, note_on_only=True):
"""Get a binary mask for each note from a monophonic instrument.
Each transition of the q_pitch value creates a new region. Returns the mask of
each region.
Args:
q_pitch: A quantized value, such as pitch or velocity. Shape
[batch, n_timesteps] or [batch, n_timesteps, 1].
max_regions: Maximum number of note regions to consider in the sequence.
Also, the channel dimension of the output mask. Each value transition
defines a new region, e.g. each note-on and note-off count as a separate
region.
note_on_only: Return a mask that is true only for regions where the pitch
is greater than 0.
Returns:
A binary mask of each region [batch, n_timesteps, max_regions].
"""
# Only batch and time dimensions.
if len(q_pitch.shape) == 3:
q_pitch = q_pitch[:, :, 0]
# Get onset and offset points.
edges = tf.abs(core.diff(q_pitch, axis=1)) > 0
# Count endpoints as starts/ends of regions.
edges = edges[:, :-1, ...]
edges = tf.pad(edges,
[[0, 0], [1, 0]], mode='constant', constant_values=True)
edges = tf.pad(edges,
[[0, 0], [0, 1]], mode='constant', constant_values=False)
edges = tf.cast(edges, tf.int32)
# Count up onset and offsets for each timestep.
# Assumes each onset has a corresponding offset.
# The -1 ensures that the 0th index is the first note.
edge_idx = tf.cumsum(edges, axis=1) - 1
# Create masks of shape [batch, n_timesteps, max_regions].
note_mask = edge_idx[..., None] == tf.range(max_regions)[None, None, :]
note_mask = tf.cast(note_mask, tf.float32)
if note_on_only:
# [batch, notes]
note_pitches = get_note_moments(q_pitch, note_mask, return_std=False)
# [batch, time, notes]
note_on = tf.cast(note_pitches > 0.0, tf.float32)[:, None, :]
# [batch, time, notes]
note_mask *= note_on
return note_mask
def get_note_mask_from_onset(q_pitch, onset, max_regions=100,
note_on_only=True):
"""Get a binary mask for each note from a monophonic instrument.
Each onset creates a new region. Returns the mask of each region.
Args:
q_pitch: A quantized value, such as pitch or velocity. Shape
[batch, n_timesteps] or [batch, n_timesteps, 1].
onset: Binary onset in shape [batch, n_timesteps] or
[batch, n_timesteps, 1]. 1 represents onset.
max_regions: Maximum number of note regions to consider in the sequence.
Also, the channel dimension of the output mask. Each value transition
defines a new region, e.g. each note-on and note-off count as a separate
region.
note_on_only: Return a mask that is true only for regions where the pitch
is greater than 0.
Returns:
A binary mask of each region [batch, n_timesteps, max_regions].
"""
# Only batch and time dimensions.
if len(q_pitch.shape) == 3:
q_pitch = q_pitch[:, :, 0]
if len(onset.shape) == 3:
onset = onset[:, :, 0]
edges = onset
# Count endpoints as starts/ends of regions.
edges = edges[:, 1:, ...]
edges = tf.pad(edges,
[[0, 0], [1, 0]], mode='constant', constant_values=True)
edges = tf.cast(edges, tf.int32)
# Count up onset and offsets for each timestep.
# Assumes each onset has a corresponding offset.
# The -1 ensures that the 0th index is the first note.
edge_idx = tf.cumsum(edges, axis=1) - 1
# Create masks of shape [batch, n_timesteps, max_regions].
note_mask = edge_idx[..., None] == tf.range(max_regions)[None, None, :]
note_mask = tf.cast(note_mask, tf.float32)
if note_on_only:
# [batch, time, notes]
note_on = tf.cast(q_pitch > 0.0, tf.float32)[:, :, None]
# [batch, time, notes]
note_mask *= note_on
return note_mask
def get_note_lengths(note_mask):
"""Count the lengths of each note [batch, time, notes] -> [batch, notes]."""
return tf.reduce_sum(note_mask, axis=1)
def get_note_moments(x, note_mask, return_std=True):
"""Return the moments of value xm, pooled over the length of the note.
Args:
x: Value to be pooled, [batch, time, dims] or [batch, time].
note_mask: Binary mask of notes [batch, time, notes].
return_std: Also return the standard deviation for each note.
Returns:
Values pooled over each note region, [batch, notes, dims] or [batch, notes].
Returns only mean if return_std=False, else mean and std.
"""
is_2d = len(x.shape) == 2
if is_2d:
x = x[:, :, tf.newaxis]
note_mask_d = note_mask[..., tf.newaxis] # [b, t, n, 1]
note_lengths = tf.reduce_sum(note_mask_d, axis=1) # [b, n, 1]
# Mean.
x_masked = x[:, :, tf.newaxis, :] * note_mask_d # [b, t, n, d]
x_mean = core.safe_divide(
tf.reduce_sum(x_masked, axis=1), note_lengths) # [b, n, d]
# Standard Deviation.
numerator = (x[:, :, tf.newaxis, :] -
x_mean[:, tf.newaxis, :, :]) * note_mask_d
numerator = tf.reduce_sum(numerator ** 2.0, axis=1) # [b, n, d]
x_std = core.safe_divide(numerator, note_lengths) ** 0.5
x_mean = x_mean[:, :, 0] if is_2d else x_mean
x_std = x_std[:, :, 0] if is_2d else x_std
if return_std:
return x_mean, x_std
else:
return x_mean
def pool_over_notes(x, note_mask, return_std=True):
"""Return the time-distributed average value of x pooled over the note.
Args:
x: Value to be pooled, [batch, time, dims].
note_mask: Binary mask of notes [batch, time, notes].
return_std: Also return the standard deviation for each note.
Returns:
Values pooled over each note region, [batch, time, dims].
Returns only mean if return_std=False, else mean and std.
"""
x_notes, x_notes_std = get_note_moments(x, note_mask,
return_std=True) # [b, n, d]
x_time_notes_mean = (x_notes[:, tf.newaxis, ...] *
note_mask[..., tf.newaxis]) # [b, t, n, d]
pooled_mean = tf.reduce_sum(x_time_notes_mean, axis=2) # [b, t, d]
if return_std:
x_time_notes_std = (x_notes_std[:, tf.newaxis, ...] *
note_mask[..., tf.newaxis]) # [b, t, n, d]
pooled_std = tf.reduce_sum(x_time_notes_std, axis=2) # [b, t, d]
return pooled_mean, pooled_std
else:
return pooled_mean
def get_short_note_loss_mask(note_mask, note_lengths,
note_pitches, min_length=40):
"""Creates a 1-D binary mask for notes shorter than min_length."""
short_notes = tf.logical_and(note_lengths < min_length, note_pitches > 0.0)
short_notes = tf.cast(short_notes, tf.float32)
short_note_mask = note_mask * short_notes[:, None, :]
loss_mask = tf.reduce_sum(short_note_mask, axis=-1)
return loss_mask
# ------------------ Normalization ---------------------------------------------
def normalize_op(x, norm_type='layer', eps=1e-5):
"""Apply either Group, Instance, or Layer normalization, or None."""
if norm_type is not None:
# mb, h, w, ch
x_shape = tf.shape(x)
n_groups = {'instance': x_shape[-1], 'layer': 1, 'group': 32}[norm_type]
x = tf.reshape(
x, tf.concat([x_shape[:-1], [n_groups, x_shape[-1] // n_groups]],
axis=0))
mean, var = tf.nn.moments(x, [1, 2, 4], keepdims=True)
x = (x - mean) / tf.sqrt(var + eps)
x = tf.reshape(x, x_shape)
return x
@gin.register
class Normalize(tfkl.Layer):
"""Normalization layer with learnable parameters."""
def __init__(self, norm_type='layer'):
super().__init__()
self.norm_type = norm_type
def build(self, x_shape):
self.scale = self.add_weight(
name='scale',
shape=[1, 1, 1, int(x_shape[-1])],
dtype=tf.float32,
initializer=tf.ones_initializer)
self.shift = self.add_weight(
name='shift',
shape=[1, 1, 1, int(x_shape[-1])],
dtype=tf.float32,
initializer=tf.zeros_initializer)
def call(self, x):
n_dims = len(x.shape)
x = ensure_4d(x)
x = normalize_op(x, self.norm_type)
x = (x * self.scale) + self.shift
return inv_ensure_4d(x, n_dims)
def get_norm(norm_type, conditional, shift_only):
"""Helper function to get conditional norm if needed."""
if conditional:
return ConditionalNorm(norm_type=norm_type, shift_only=shift_only)
else:
return Normalize(norm_type)
# ------------------ Resampling ------------------------------------------------
def polyphase_resample(x, stride=2, resample_type='down', trim_or_pad='pad'):
"""Resample by 'space_to_depth' conversion of time and channels.
For example,
Downsampling: [batch, time, ch] --> [batch, time/stride, ch*stride]
Upsampling: [batch, time, ch] --> [batch, time*stride, ch/stride]
Named 'polyphase' resample because it performs a transformation similar to a
polyphase filter (each "phase" gets its own channel, filter in parallel).
Args:
x: Input tensor, shape [batch, time, ch].
stride: Amount to resample by.
resample_type: 'up' or 'down'.
trim_or_pad: 'trim' or 'pad'. What to do if time or channels cannot be
evenly divided by stride.
Returns:
A resampled tensor.
"""
is_4d = len(x.shape) == 4
if is_4d:
x = x[:, :, 0, :]
n_time = x.shape[1]
n_ch = x.shape[2]
if resample_type == 'down':
# Pad or trim.
if trim_or_pad == 'pad':
pad = (stride - n_time % stride) % stride
x = tf.pad(x, [[0, 0], [0, pad], [0, 0]]) if pad > 0 else x
else:
trim = n_time % stride
x = x[:, :-trim, :] if trim > 0 else x
# Reshape.
n_time = x.shape[1]
x_reshape = tf.reshape(x, [-1, n_time // stride, n_ch * stride])
elif resample_type == 'up':
# Pad or trim.
if trim_or_pad == 'pad':
pad = (stride - n_ch % stride) % stride
x = tf.pad(x, [[0, 0], [0, 0], [0, pad]]) if pad > 0 else x
else:
trim = n_ch % stride
if trim > 0:
x = x[:, :, :-trim]
# Reshape.
n_ch = x.shape[2]
x_reshape = tf.reshape(x, [-1, n_time * stride, n_ch // stride])
else:
raise ValueError('`resample_type` must be either "up" or "down"')
if is_4d:
x_reshape = x_reshape[:, :, None, :]
return x_reshape
@gin.register
class PolyphaseResample(tfkl.Layer):
"""Resample by interleaving time and channels."""
def __init__(self,
stride=2,
resample_type='down',
trim_or_pad='pad',
**kwargs):
super().__init__(**kwargs)
self.stride = stride
self.resample_type = resample_type
self.trim_or_pad = trim_or_pad
def call(self, x):
return polyphase_resample(
x, self.stride, self.resample_type, self.trim_or_pad)
# ------------------ ResNet ----------------------------------------------------
@gin.register
class NormReluConv(tf.keras.Sequential):
"""Norm -> ReLU -> Conv layer."""
def __init__(self, ch, k, s, norm_type, **kwargs):
"""Downsample frequency by stride."""
layers = [
Normalize(norm_type),
tfkl.Activation(tf.nn.relu),
tfkl.Conv2D(ch, (k, k), (1, s), padding='same'),
]
super().__init__(layers, **kwargs)
@gin.register
class ResidualLayer(tfkl.Layer):
"""A single layer for ResNet, with a bottleneck."""
def __init__(self, ch, stride, shortcut, norm_type,
conditional, shift_only, **kwargs):
"""Downsample frequency by stride, upsample channels by 4."""
super().__init__(**kwargs)
ch_out = 4 * ch
self.shortcut = shortcut
self.conditional = conditional
# Layers.
self.norm_input = get_norm(norm_type, conditional, shift_only)
if self.shortcut:
self.conv_proj = tfkl.Conv2D(
ch_out, (1, 1), (1, stride), padding='same', name='conv_proj')
layers = [
tfkl.Conv2D(ch, (1, 1), (1, 1), padding='same'),
NormReluConv(ch, 3, stride, norm_type),
NormReluConv(ch_out, 1, 1, norm_type),
]
self.bottleneck = tf.keras.Sequential(layers, name='bottleneck')
def call(self, inputs):
if self.conditional:
x, z = inputs
r = x
x = ensure_4d(x)
z = ensure_4d(z)
x = tf.nn.relu(self.norm_input((x, z)))
else:
x = inputs
r = x
x = ensure_4d(x)
x = tf.nn.relu(self.norm_input(x))
# The projection shortcut should come after the first norm and ReLU
# since it performs a 1x1 convolution.
r = self.conv_proj(x) if self.shortcut else r
x = self.bottleneck(x)
return x + r
@gin.register
class ResidualStack(tfkl.Layer):
"""LayerNorm -> ReLU -> Conv layer."""
def __init__(self,
filters,
block_sizes,
strides,
norm_type,
conditional=False,
shift_only=False,
nonlinearity='relu',
**kwargs):
"""ResNet layers."""
super().__init__(**kwargs)
self.conditional = conditional
layers = []
for (ch, n_layers, stride) in zip(filters, block_sizes, strides):
# Only the first block per residual_stack uses shortcut and strides.
layers.append(ResidualLayer(ch, stride, True, norm_type,
conditional, shift_only))
# Add the additional (n_layers - 1) layers to the stack.
for _ in range(1, n_layers):
layers.append(ResidualLayer(ch, 1, False, norm_type,
conditional, shift_only))
layers.append(Normalize(norm_type))
layers.append(tfkl.Activation(get_nonlinearity(nonlinearity)))
self.layers = layers
def __call__(self, inputs):
if self.conditional:
x, z = inputs
else:
x = inputs
for layer in self.layers:
is_cond = self.conditional and isinstance(layer, ResidualLayer)
l_in = [x, z] if is_cond else x
x = layer(l_in)
return x
@gin.register
class ResNet(tfkl.Layer):
"""Residual network."""
def __init__(self, size='large', norm_type='layer',
conditional=False, shift_only=False, **kwargs):
super().__init__(**kwargs)
self.conditional = conditional
size_dict = {
'small': (32, [2, 3, 4]),
'medium': (32, [3, 4, 6]),
'large': (64, [3, 4, 6]),
}
ch, blocks = size_dict[size]
self.layers = [
tfkl.Conv2D(64, (7, 7), (1, 2), padding='same'),
tfkl.MaxPool2D(pool_size=(1, 3), strides=(1, 2), padding='same'),
ResidualStack([ch, 2 * ch, 4 * ch], blocks, [1, 2, 2], norm_type,
conditional, shift_only),
ResidualStack([8 * ch], [3], [2], norm_type,
conditional, shift_only)
]
def __call__(self, inputs):
if self.conditional:
x, z = inputs
else:
x = inputs
for layer in self.layers:
is_cond = self.conditional and isinstance(layer, ResidualStack)
l_in = [x, z] if is_cond else x
x = layer(l_in)
return x
# ---------------- Stacks ------------------------------------------------------
@gin.register
class Fc(tf.keras.Sequential):
"""Makes a Dense -> LayerNorm -> Leaky ReLU layer."""
def __init__(self, ch=128, nonlinearity='leaky_relu', **kwargs):
layers = [
tfkl.Dense(ch),
tfkl.LayerNormalization(),
tfkl.Activation(get_nonlinearity(nonlinearity)),
]
super().__init__(layers, **kwargs)
@gin.register
class FcStack(tf.keras.Sequential):
"""Stack Dense -> LayerNorm -> Leaky ReLU layers."""
def __init__(self, ch=256, layers=2, nonlinearity='leaky_relu', **kwargs):
layers = [Fc(ch, nonlinearity) for i in range(layers)]
super().__init__(layers, **kwargs)
@gin.register
class Rnn(tfkl.Layer):
"""Single RNN layer."""
def __init__(self, dims, rnn_type, return_sequences=True, bidir=False,
**kwargs):
super().__init__(**kwargs)
rnn_class = {'lstm': tfkl.LSTM,
'gru': tfkl.GRU}[rnn_type]
self.rnn = rnn_class(dims, return_sequences=return_sequences)
if bidir:
self.rnn = tfkl.Bidirectional(self.rnn)
def call(self, x):
return self.rnn(x)
@gin.register
class StatelessRnn(tfkl.Layer):
"""Stateless unidirectional RNN for streaming models."""
def __init__(self, dims, rnn_type, **kwargs):
super().__init__(**kwargs)
rnn_class = {'lstm': tfkl.LSTM,
'gru': tfkl.GRU}[rnn_type]
self.rnn = rnn_class(dims, return_sequences=True, return_state=True)
def call(self, x, state):
"""Make a call with explicit carrying of state.
Args:
x: Input, shape [batch, T, dims_in].
state: Last output, shape [batch, dims].
Returns:
y: Output, shape [batch, T, dims].
new_state: Carried state, shape [batch, dims]
"""
y, new_state = self.rnn(x, initial_state=state)
return y, new_state
@gin.register
class RnnFc(tfk.Sequential):
"""RNN layer -> fully connected -> LayerNorm -> Activation fn."""
def __init__(self, rnn_feat, out_feat,
rnn_type='lstm', nonlinearity='sigmoid',
bidir=False, n_rnn=1, **kwargs):
layers = [Rnn(rnn_feat, rnn_type, bidir) for _ in range(n_rnn)]
layers.append(Fc(out_feat, nonlinearity=nonlinearity))
super().__init__(layers, **kwargs)
@gin.register
class RnnSandwich(tf.keras.Sequential):
"""RNN Sandwiched by two FC Stacks."""
def __init__(self,
fc_stack_ch=256,
fc_stack_layers=2,
rnn_ch=512,
rnn_type='gru',
**kwargs):
layers = [
FcStack(fc_stack_ch, fc_stack_layers),
Rnn(rnn_ch, rnn_type),
FcStack(fc_stack_ch, fc_stack_layers),
]
super().__init__(layers, **kwargs)
# ------------------ Utility Layers --------------------------------------------
@gin.register
class Identity(tfkl.Layer):
"""Utility identity layer."""
def call(self, x):
return x
gin.register(tfkl.Dense, module=__name__)
class SpectralNormalization(tf.keras.layers.Wrapper):
"""Performs spectral normalization on weights.
Copied from soon to be deprecated TF addons that broke training.
https://github.com/tensorflow/addons/issues/2807
This wrapper controls the Lipschitz constant of the layer by
constraining its spectral norm, which can stabilize the training of GANs.
See [Spectral Normalization for Generative Adversarial
Networks](https://arxiv.org/abs/1802.05957).
Wrap `tf.keras.layers.Conv2D`:
>>> x = np.random.rand(1, 10, 10, 1)
>>> conv2d = SpectralNormalization(tf.keras.layers.Conv2D(2, 2))
>>> y = conv2d(x)
>>> y.shape
TensorShape([1, 9, 9, 2])
Wrap `tf.keras.layers.Dense`:
>>> x = np.random.rand(1, 10, 10, 1)
>>> dense = SpectralNormalization(tf.keras.layers.Dense(10))
>>> y = dense(x)
>>> y.shape
TensorShape([1, 10, 10, 10])
Args:
layer: A `tf.keras.layers.Layer` instance that has either `kernel` or
`embeddings` attribute.
power_iterations: `int`, the number of iterations during normalization.
Raises:
AssertionError: If not initialized with a `Layer` instance.
ValueError: If initialized with negative `power_iterations`.
AttributeError: If `layer` does not has `kernel` or `embeddings`
attribute.
"""
def __init__(self,
layer: tf.keras.layers,
power_iterations: int = 1,
**kwargs):
super().__init__(layer, **kwargs)
if power_iterations <= 0:
raise ValueError('`power_iterations` should be greater than zero, got '
'`power_iterations={}`'.format(power_iterations))
self.power_iterations = power_iterations
self._initialized = False
def build(self, input_shape):
"""Build `Layer`."""