forked from magenta/ddsp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.py
1690 lines (1364 loc) · 62.2 KB
/
core.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 2022 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 functions for differentiable digital signal processing (DDSP)."""
import collections
import copy
from typing import Any, Dict, Optional, Sequence, Text, TypeVar
import gin
import numpy as np
from scipy import fftpack
import tensorflow.compat.v2 as tf
Number = TypeVar('Number', int, float, np.ndarray, tf.Tensor)
DB_RANGE = 80.0
# Utility Functions ------------------------------------------------------------
def tf_float32(x):
"""Ensure array/tensor is a float32 tf.Tensor."""
if isinstance(x, tf.Tensor):
return tf.cast(x, dtype=tf.float32) # This is a no-op if x is float32.
else:
return tf.convert_to_tensor(x, tf.float32)
def make_iterable(x):
"""Wrap in a list if not iterable, return empty list if None."""
if x is None:
return []
elif isinstance(x, (np.ndarray, tf.Tensor)):
# Wrap in list so you don't iterate over the batch.
return [x]
else:
return x if isinstance(x, collections.Iterable) else [x]
def to_dict(x, keys):
"""Converts list to a dictionary with supplied keys."""
if isinstance(x, dict):
# No-op for dict.
return x
else:
# Wrap individual tensors in a list so we don't iterate over batch..
x = make_iterable(x)
if len(keys) != len(x):
raise ValueError(f'Keys: {keys} must be the same length as {x}')
# Use keys to create an output dictionary.
return dict(zip(keys, x))
def copy_if_tf_function(x):
"""Copy if wrapped by tf.function.
Prevents side-effects if x is the input to the tf.function and it is later
altered. If eager, avoids unnecessary copies.
Args:
x: Any inputs.
Returns:
A shallow copy of x if inside a tf.function.
"""
return copy.copy(x) if not tf.executing_eagerly() else x
def nested_keys(nested_dict: Dict[Text, Any],
delimiter: Text = '/',
prefix: Text = '') -> Sequence[Text]:
"""Returns a flattend list of nested key strings of a nested dict.
Args:
nested_dict: Nested dictionary.
delimiter: String that splits the nested keys.
prefix: Top-level key used for recursion, usually leave blank.
Returns:
List of nested key strings.
"""
keys = []
for k, v in nested_dict.items():
key = k if not prefix else f'{prefix}{delimiter}{k}'
if not isinstance(v, dict):
keys.append(key)
else:
dict_keys = nested_keys(v, prefix=key)
keys += dict_keys
return keys
def nested_lookup(nested_key: Text,
nested_dict: Dict[Text, Any],
delimiter: Text = '/') -> tf.Tensor:
"""Returns the value of a nested dict according to a parsed input string.
Args:
nested_key: String of the form "key/key/key...".
nested_dict: Nested dictionary.
delimiter: String that splits the nested keys.
Returns:
value: Value of the key from the nested dictionary.
"""
# Parse the input string.
keys = nested_key.split(delimiter)
# Return the nested value.
value = nested_dict
for key in keys:
try:
value = value[key]
except KeyError:
raise KeyError(f'Key \'{key}\' as a part of nested key \'{nested_key}\' '
'not found during nested dictionary lookup, out of '
f'available keys: {nested_keys(nested_dict)}')
return value
def leaf_key(nested_key: Text,
delimiter: Text = '/') -> tf.Tensor:
"""Returns the leaf node key name.
Args:
nested_key: String of the form "key/key/key...".
delimiter: String that splits the nested keys.
Returns:
value: Final leaf node key name.
"""
# Parse the input string.
keys = nested_key.split(delimiter)
return keys[-1]
def map_shape(x: Dict[Text, tf.Tensor]) -> Dict[Text, Sequence[int]]:
"""Recursively infer tensor shapes for a dictionary of tensors."""
return tf.nest.map_structure(lambda t: list(tf.shape(t).numpy()), x)
def pad_axis(x, padding=(0, 0), axis=0, **pad_kwargs):
"""Pads only one axis of a tensor.
Args:
x: Input tensor.
padding: Tuple of number of samples to pad (before, after).
axis: Which axis to pad.
**pad_kwargs: Other kwargs to pass to tf.pad.
Returns:
A tensor padded with padding along axis.
"""
n_end_dims = len(x.shape) - axis - 1
n_end_dims *= n_end_dims > 0
paddings = [[0, 0]] * axis + [list(padding)] + [[0, 0]] * n_end_dims
return tf.pad(x, paddings, **pad_kwargs)
def diff(x, axis=-1):
"""Take the finite difference of a tensor along an axis.
Args:
x: Input tensor of any dimension.
axis: Axis on which to take the finite difference.
Returns:
d: Tensor with size less than x by 1 along the difference dimension.
Raises:
ValueError: Axis out of range for tensor.
"""
shape = x.shape.as_list()
ndim = len(shape)
if axis >= ndim:
raise ValueError('Invalid axis index: %d for tensor with only %d axes.' %
(axis, ndim))
begin_back = [0 for _ in range(ndim)]
begin_front = [0 for _ in range(ndim)]
begin_front[axis] = 1
shape[axis] -= 1
slice_front = tf.slice(x, begin_front, shape)
slice_back = tf.slice(x, begin_back, shape)
d = slice_front - slice_back
return d
# Math -------------------------------------------------------------------------
def nan_to_num(x, value=0.0):
"""Replace NaNs with value."""
return tf.where(tf.math.is_nan(x), value * tf.ones_like(x), x)
def safe_divide(numerator, denominator, eps=1e-7):
"""Avoid dividing by zero by adding a small epsilon."""
safe_denominator = tf.where(denominator == 0.0, eps, denominator)
return numerator / safe_denominator
def safe_log(x, eps=1e-5):
"""Avoid taking the log of a non-positive number."""
safe_x = tf.where(x <= 0.0, eps, x)
return tf.math.log(safe_x)
def logb(x, base=2.0, eps=1e-5):
"""Logarithm with base as an argument."""
return safe_divide(safe_log(x, eps), safe_log(base, eps), eps)
def log10(x, eps=1e-5):
"""Logarithm with base 10."""
return logb(x, base=10, eps=eps)
def log_scale(x, min_x, max_x):
"""Scales a -1 to 1 value logarithmically between min and max."""
x = tf_float32(x)
x = (x + 1.0) / 2.0 # Scale [-1, 1] to [0, 1]
return tf.exp((1.0 - x) * tf.math.log(min_x) + x * tf.math.log(max_x))
def soft_limit(x, x_min=0.0, x_max=1.0):
"""Softly limits inputs to the range [x_min, x_max]."""
return tf.nn.softplus(x) + x_min - tf.nn.softplus(x - (x_max - x_min))
def gradient_reversal(x):
"""Identity operation that reverses the gradient."""
return tf.stop_gradient(2.0 * x) - x
# Unit Conversions -------------------------------------------------------------
def amplitude_to_db(amplitude, ref_db=0.0, range_db=DB_RANGE, use_tf=True):
"""Converts amplitude in linear scale to power in decibels."""
power = amplitude**2.0
return power_to_db(power, ref_db=ref_db, range_db=range_db, use_tf=use_tf)
def power_to_db(power, ref_db=0.0, range_db=DB_RANGE, use_tf=True):
"""Converts power from linear scale to decibels."""
# Choose library.
maximum = tf.maximum if use_tf else np.maximum
log_base10 = log10 if use_tf else np.log10
# Convert to decibels.
pmin = 10**-(range_db / 10.0)
power = maximum(pmin, power)
db = 10.0 * log_base10(power)
# Set dynamic range.
db -= ref_db
db = maximum(db, -range_db)
return db
def db_to_amplitude(db):
"""Converts power in decibels to amplitude in linear scale."""
return db_to_power(db / 2.0)
def db_to_power(db):
"""Converts power from decibels to linear scale."""
return 10.0**(db / 10.0)
def midi_to_hz(notes: Number, midi_zero_silence: bool = False) -> Number:
"""TF-compatible midi_to_hz function.
Args:
notes: Tensor containing encoded pitch in MIDI scale.
midi_zero_silence: Whether to output 0 hz for midi 0, which would be
convenient when midi 0 represents silence. By defualt (False), midi 0.0
corresponds to 8.18 Hz.
Returns:
hz: Frequency of MIDI in hz, same shape as input.
"""
notes = tf_float32(notes)
hz = 440.0 * (2.0 ** ((notes - 69.0) / 12.0))
# Map MIDI 0 as 0 hz when MIDI 0 is silence.
if midi_zero_silence:
hz = tf.where(tf.equal(notes, 0.0), 0.0, hz)
return hz
def hz_to_midi(frequencies: Number) -> Number:
"""TF-compatible hz_to_midi function."""
frequencies = tf_float32(frequencies)
notes = 12.0 * (logb(frequencies, 2.0) - logb(440.0, 2.0)) + 69.0
# Map 0 Hz to MIDI 0 (Replace -inf MIDI with 0.)
notes = tf.where(tf.less_equal(frequencies, 0.0), 0.0, notes)
return notes
def unit_to_midi(unit: Number,
midi_min: Number = 20.0,
midi_max: Number = 90.0,
clip: bool = False) -> Number:
"""Map the unit interval [0, 1] to MIDI notes."""
unit = tf.clip_by_value(unit, 0.0, 1.0) if clip else unit
return midi_min + (midi_max - midi_min) * unit
def midi_to_unit(midi: Number,
midi_min: Number = 20.0,
midi_max: Number = 90.0,
clip: bool = False) -> Number:
"""Map MIDI notes to the unit interval [0, 1]."""
unit = (midi - midi_min) / (midi_max - midi_min)
return tf.clip_by_value(unit, 0.0, 1.0) if clip else unit
def unit_to_hz(unit: Number,
hz_min: Number,
hz_max: Number,
clip: bool = False) -> Number:
"""Map unit interval [0, 1] to [hz_min, hz_max], scaling logarithmically."""
midi = unit_to_midi(unit,
midi_min=hz_to_midi(hz_min),
midi_max=hz_to_midi(hz_max),
clip=clip)
return midi_to_hz(midi)
def hz_to_unit(hz: Number,
hz_min: Number,
hz_max: Number,
clip: bool = False) -> Number:
"""Map [hz_min, hz_max] to unit interval [0, 1], scaling logarithmically."""
midi = hz_to_midi(hz)
return midi_to_unit(midi,
midi_min=hz_to_midi(hz_min),
midi_max=hz_to_midi(hz_max),
clip=clip)
def hz_to_bark(hz):
"""From Tranmuller (1990, https://asa.scitation.org/doi/10.1121/1.399849)."""
return 26.81 / (1.0 + (1960.0 / hz)) - 0.53
def bark_to_hz(bark):
"""From Tranmuller (1990, https://asa.scitation.org/doi/10.1121/1.399849)."""
return 1960.0 / (26.81 / (bark + 0.53) - 1.0)
def hz_to_mel(hz):
"""From Young et al. "The HTK book", Chapter 5.4."""
return 2595.0 * logb(1.0 + hz / 700.0, 10.0)
def mel_to_hz(mel):
"""From Young et al. "The HTK book", Chapter 5.4."""
return 700.0 * (10.0**(mel / 2595.0) - 1.0)
def hz_to_erb(hz):
"""Equivalent Rectangular Bandwidths (ERB) from Moore & Glasberg (1996).
https://research.tue.nl/en/publications/a-revision-of-zwickers-loudness-model
https://ccrma.stanford.edu/~jos/bbt/Equivalent_Rectangular_Bandwidth.html
Args:
hz: Inputs frequencies in hertz.
Returns:
Critical bandwidths (in hertz) for each input frequency.
"""
return 0.108 * hz + 24.7
# Scaling functions ------------------------------------------------------------
@gin.register
def exp_sigmoid(x, exponent=10.0, max_value=2.0, threshold=1e-7):
"""Exponentiated Sigmoid pointwise nonlinearity.
Bounds input to [threshold, max_value] with slope given by exponent.
Args:
x: Input tensor.
exponent: In nonlinear regime (away from x=0), the output varies by this
factor for every change of x by 1.0.
max_value: Limiting value at x=inf.
threshold: Limiting value at x=-inf. Stablizes training when outputs are
pushed to 0.
Returns:
A tensor with pointwise nonlinearity applied.
"""
x = tf_float32(x)
return max_value * tf.nn.sigmoid(x)**tf.math.log(exponent) + threshold
@gin.register
def sym_exp_sigmoid(x, width=8.0):
"""Symmetrical version of exp_sigmoid centered at (0, 1e-7)."""
x = tf_float32(x)
return exp_sigmoid(width * (tf.abs(x)/2.0 - 1.0))
def _add_depth_axis(freqs: tf.Tensor, depth: int = 1) -> tf.Tensor:
"""Turns [batch, time, sinusoids*depth] to [batch, time, sinusoids, depth]."""
freqs = freqs[..., tf.newaxis]
# Unpack sinusoids dimension.
n_batch, n_time, n_combined, _ = freqs.shape
n_sinusoids = int(n_combined) // depth
return tf.reshape(freqs, [n_batch, n_time, n_sinusoids, depth])
@gin.register
def frequencies_softmax(freqs: tf.Tensor,
depth: int = 1,
hz_min: float = 20.0,
hz_max: float = 8000.0) -> tf.Tensor:
"""Softmax to logarithmically scale network outputs to frequencies.
Args:
freqs: Neural network outputs, [batch, time, n_sinusoids * depth] or
[batch, time, n_sinusoids, depth].
depth: If freqs is 3-D, the number of softmax components per a sinusoid to
unroll from the last dimension.
hz_min: Lowest frequency to consider.
hz_max: Highest frequency to consider.
Returns:
A tensor of frequencies in hertz [batch, time, n_sinusoids].
"""
if len(freqs.shape) == 3:
# Add depth: [B, T, N*D] -> [B, T, N, D]
freqs = _add_depth_axis(freqs, depth)
else:
depth = int(freqs.shape[-1])
# Probs: [B, T, N, D].
f_probs = tf.nn.softmax(freqs, axis=-1)
# [1, 1, 1, D]
unit_bins = tf.linspace(0.0, 1.0, depth)
unit_bins = unit_bins[tf.newaxis, tf.newaxis, tf.newaxis, :]
# [B, T, N]
f_unit = tf.reduce_sum(unit_bins * f_probs, axis=-1, keepdims=False)
return unit_to_hz(f_unit, hz_min=hz_min, hz_max=hz_max)
@gin.register
def frequencies_sigmoid(freqs: tf.Tensor,
depth: int = 1,
hz_min: float = 0.0,
hz_max: float = 8000.0) -> tf.Tensor:
"""Sum of sigmoids to logarithmically scale network outputs to frequencies.
Args:
freqs: Neural network outputs, [batch, time, n_sinusoids * depth] or
[batch, time, n_sinusoids, depth].
depth: If freqs is 3-D, the number of sigmoid components per a sinusoid to
unroll from the last dimension.
hz_min: Lowest frequency to consider.
hz_max: Highest frequency to consider.
Returns:
A tensor of frequencies in hertz [batch, time, n_sinusoids].
"""
if len(freqs.shape) == 3:
# Add depth: [B, T, N*D] -> [B, T, N, D]
freqs = _add_depth_axis(freqs, depth)
else:
depth = int(freqs.shape[-1])
# Probs: [B, T, N, D]
f_probs = tf.nn.sigmoid(freqs)
# [B, T N]
# Partition frequency space in factors of 2, limit to range [hz_max, hz_min].
hz_scales = []
hz_min_copy = hz_min
remainder = hz_max - hz_min
scale_factor = remainder**(1.0 / depth)
for i in range(depth):
if i == (depth - 1):
# Last depth element goes between minimum and remainder.
hz_max = remainder
hz_min = hz_min_copy
else:
# Reduce max by a constant factor for each depth element.
hz_max = remainder * (1.0 - 1.0 / scale_factor)
hz_min = 0
remainder -= hz_max
hz_scales.append(unit_to_hz(f_probs[..., i],
hz_min=hz_min,
hz_max=hz_max))
return tf.reduce_sum(tf.stack(hz_scales, axis=-1), axis=-1)
@gin.register
def frequencies_critical_bands(freqs,
depth=1,
depth_scale=10.0,
bandwidth_scale=1.0,
hz_min=20.0,
hz_max=8000.0,
scale='bark'):
"""Center frequencies scaled on mel or bark scale, with ranges given by erb.
Args:
freqs: Neural network outputs, [batch, time, n_sinusoids * depth] or
[batch, time, n_sinusoids, depth].
depth: If freqs is 3-D, the number of sigmoid components per a sinusoid to
unroll from the last dimension.
depth_scale: The degree by which to reduce the influence of each subsequent
dimension of depth.
bandwidth_scale: Multiplier (to ERB) for the range of each sinusoid.
hz_min: Lowest frequency to consider.
hz_max: Highest frequency to consider.
scale: Critical frequency scaling, must be either 'mel' or 'bark'.
Returns:
A tensor of frequencies in hertz [batch, time, n_sinusoids].
"""
if len(freqs.shape) == 3:
# Add depth: [B, T, N*D] -> [B, T, N, D]
freqs = _add_depth_axis(freqs, depth)
else:
depth = int(freqs.shape[-1])
# Figure out the number of sinusoids.
n_sinusoids = freqs.shape[-2]
# Initilaize the critical frequencies and bandwidths.
if scale == 'bark':
# Bark.
bark_min = hz_to_bark(hz_min)
bark_max = hz_to_bark(hz_max)
linear_bark = np.linspace(bark_min, bark_max, n_sinusoids)
f_center = bark_to_hz(linear_bark)
else:
# Mel.
mel_min = hz_to_mel(hz_min)
mel_max = hz_to_mel(hz_max)
linear_mel = np.linspace(mel_min, mel_max, n_sinusoids)
f_center = mel_to_hz(linear_mel)
# Bandwiths given by equivalent rectangular bandwidth (ERB).
bw = hz_to_erb(f_center)
# Probs: [B, T, N, D]
modifier = tf.nn.tanh(freqs)
depth_modifier = depth_scale ** -tf.range(depth, dtype=tf.float32)
# print(depth, depth_modifier, modifier)
modifier = tf.reduce_sum(
modifier * depth_modifier[tf.newaxis, tf.newaxis, tf.newaxis, :], axis=-1)
f_modifier = bandwidth_scale * bw[tf.newaxis, tf.newaxis, :] * modifier
return soft_limit(f_center + f_modifier, hz_min, hz_max)
# Resampling -------------------------------------------------------------------
def resample(inputs: tf.Tensor,
n_timesteps: int,
method: Text = 'linear',
add_endpoint: bool = True) -> tf.Tensor:
"""Interpolates a tensor from n_frames to n_timesteps.
Args:
inputs: Framewise 1-D, 2-D, 3-D, or 4-D Tensor. Shape [n_frames],
[batch_size, n_frames], [batch_size, n_frames, channels], or
[batch_size, n_frames, n_freq, channels].
n_timesteps: Time resolution of the output signal.
method: Type of resampling, must be in ['nearest', 'linear', 'cubic',
'window']. Linear and cubic ar typical bilinear, bicubic interpolation.
'window' uses overlapping windows (only for upsampling) which is smoother
for amplitude envelopes with large frame sizes.
add_endpoint: Hold the last timestep for an additional step as the endpoint.
Then, n_timesteps is divided evenly into n_frames segments. If false, use
the last timestep as the endpoint, producing (n_frames - 1) segments with
each having a length of n_timesteps / (n_frames - 1).
Returns:
Interpolated 1-D, 2-D, 3-D, or 4-D Tensor. Shape [n_timesteps],
[batch_size, n_timesteps], [batch_size, n_timesteps, channels], or
[batch_size, n_timesteps, n_freqs, channels].
Raises:
ValueError: If method is 'window' and input is 4-D.
ValueError: If method is not one of 'nearest', 'linear', 'cubic', or
'window'.
"""
inputs = tf_float32(inputs)
is_1d = len(inputs.shape) == 1
is_2d = len(inputs.shape) == 2
is_4d = len(inputs.shape) == 4
# Ensure inputs are at least 3d.
if is_1d:
inputs = inputs[tf.newaxis, :, tf.newaxis]
elif is_2d:
inputs = inputs[:, :, tf.newaxis]
def _image_resize(method):
"""Closure around tf.image.resize."""
# Image resize needs 4-D input. Add/remove extra axis if not 4-D.
outputs = inputs[:, :, tf.newaxis, :] if not is_4d else inputs
outputs = tf.compat.v1.image.resize(outputs,
[n_timesteps, outputs.shape[2]],
method=method,
align_corners=not add_endpoint)
return outputs[:, :, 0, :] if not is_4d else outputs
# Perform resampling.
if method == 'nearest':
outputs = _image_resize(tf.compat.v1.image.ResizeMethod.NEAREST_NEIGHBOR)
elif method == 'linear':
outputs = _image_resize(tf.compat.v1.image.ResizeMethod.BILINEAR)
elif method == 'cubic':
outputs = _image_resize(tf.compat.v1.image.ResizeMethod.BICUBIC)
elif method == 'window':
outputs = upsample_with_windows(inputs, n_timesteps, add_endpoint)
else:
raise ValueError('Method ({}) is invalid. Must be one of {}.'.format(
method, "['nearest', 'linear', 'cubic', 'window']"))
# Return outputs to the same dimensionality of the inputs.
if is_1d:
outputs = outputs[0, :, 0]
elif is_2d:
outputs = outputs[:, :, 0]
return outputs
def upsample_with_windows(inputs: tf.Tensor,
n_timesteps: int,
add_endpoint: bool = True) -> tf.Tensor:
"""Upsample a series of frames using using overlapping hann windows.
Good for amplitude envelopes.
Args:
inputs: Framewise 3-D tensor. Shape [batch_size, n_frames, n_channels].
n_timesteps: The time resolution of the output signal.
add_endpoint: Hold the last timestep for an additional step as the endpoint.
Then, n_timesteps is divided evenly into n_frames segments. If false, use
the last timestep as the endpoint, producing (n_frames - 1) segments with
each having a length of n_timesteps / (n_frames - 1).
Returns:
Upsampled 3-D tensor. Shape [batch_size, n_timesteps, n_channels].
Raises:
ValueError: If input does not have 3 dimensions.
ValueError: If attempting to use function for downsampling.
ValueError: If n_timesteps is not divisible by n_frames (if add_endpoint is
true) or n_frames - 1 (if add_endpoint is false).
"""
inputs = tf_float32(inputs)
if len(inputs.shape) != 3:
raise ValueError('Upsample_with_windows() only supports 3 dimensions, '
'not {}.'.format(inputs.shape))
# Mimic behavior of tf.image.resize.
# For forward (not endpointed), hold value for last interval.
if add_endpoint:
inputs = tf.concat([inputs, inputs[:, -1:, :]], axis=1)
n_frames = int(inputs.shape[1])
n_intervals = (n_frames - 1)
if n_frames >= n_timesteps:
raise ValueError('Upsample with windows cannot be used for downsampling'
'More input frames ({}) than output timesteps ({})'.format(
n_frames, n_timesteps))
if n_timesteps % n_intervals != 0.0:
minus_one = '' if add_endpoint else ' - 1'
raise ValueError(
'For upsampling, the target the number of timesteps must be divisible '
'by the number of input frames{}. (timesteps:{}, frames:{}, '
'add_endpoint={}).'.format(minus_one, n_timesteps, n_frames,
add_endpoint))
# Constant overlap-add, half overlapping windows.
hop_size = n_timesteps // n_intervals
window_length = 2 * hop_size
window = tf.signal.hann_window(window_length) # [window]
# Transpose for overlap_and_add.
x = tf.transpose(inputs, perm=[0, 2, 1]) # [batch_size, n_channels, n_frames]
# Broadcast multiply.
# Add dimension for windows [batch_size, n_channels, n_frames, window].
x = x[:, :, :, tf.newaxis]
window = window[tf.newaxis, tf.newaxis, tf.newaxis, :]
x_windowed = (x * window)
x = tf.signal.overlap_and_add(x_windowed, hop_size)
# Transpose back.
x = tf.transpose(x, perm=[0, 2, 1]) # [batch_size, n_timesteps, n_channels]
# Trim the rise and fall of the first and last window.
return x[:, hop_size:-hop_size, :]
def center_crop(audio, frame_size):
"""Remove padding introduced from centering frames.
Inverse of center_pad().
Args:
audio: Input, shape [batch, time, ...].
frame_size: Size of each frame.
Returns:
audio_cropped: Shape [batch, time - (frame_size // 2) * 2, ...].
"""
pad_amount = int(frame_size // 2) # Symmetric even padding like librosa.
return audio[:, pad_amount:-pad_amount]
# Synth conversions ------------------------------------------------------------
def sinusoidal_to_harmonic(sin_amps,
sin_freqs,
f0_hz,
harmonic_width=0.1,
n_harmonics=100,
sample_rate=16000,
normalize=False):
"""Extract harmonic components from sinusoids given a fundamental frequency.
Args:
sin_amps: Sinusoidal amplitudes (linear), shape [batch, time, n_sinusoids].
sin_freqs: Sinusoidal frequencies in Hz, shape [batch, time, n_sinusoids].
f0_hz: Fundamental frequency in Hz, shape [batch, time, 1].
harmonic_width: Standard deviation of gaussian weighting based on relative
frequency difference between a harmonic and a sinusoid.
n_harmonics: Number of output harmonics to consider.
sample_rate: Hertz, rate of the signal.
normalize: If true, per timestep, each harmonic has a max of 1.0 weight to
assign between the sinusoids. max(harm_amp) = max(sin_amp).
Returns:
harm_amp: Harmonic amplitude (linear), shape [batch, time, 1].
harm_dist: Harmonic distribution, shape [batch, time, n_harmonics].
"""
# [b, t, n_harm]
harm_freqs = get_harmonic_frequencies(f0_hz, n_harmonics)
# [b, t, n_harm, n_sin]
freqs_diff = sin_freqs[:, :, tf.newaxis, :] - harm_freqs[..., tf.newaxis]
freqs_ratio = tf.abs(safe_divide(freqs_diff, f0_hz[..., tf.newaxis]))
weights = tf.math.exp(-(freqs_ratio / harmonic_width)**2.0)
if normalize:
# Sum of sinusoidal weights for a given harmonic. [b, t, n_harm, 1]
weights_sum = tf.reduce_sum(weights, axis=-1, keepdims=True)
weights_norm = safe_divide(weights, weights_sum)
weights = tf.where(weights_sum > 1.0, weights_norm, weights)
# [b, t, n_harm, n_sin] -> [b, t, n_harm]
harm_amps = tf.reduce_sum(weights * sin_amps[:, :, tf.newaxis, :], axis=-1)
# Filter harmonics above nyquist.
harm_amps = remove_above_nyquist(harm_freqs, harm_amps, sample_rate)
# Get harmonic distribution.
harm_amp = tf.reduce_sum(harm_amps, axis=-1, keepdims=True)
harm_dist = safe_divide(harm_amps, harm_amp)
return harm_amp, harm_dist
def harmonic_to_sinusoidal(harm_amp, harm_dist, f0_hz, sample_rate=16000):
"""Converts controls for a harmonic synth to those for a sinusoidal synth."""
n_harmonics = int(harm_dist.shape[-1])
freqs = get_harmonic_frequencies(f0_hz, n_harmonics)
# Double check to remove anything above Nyquist.
harm_dist = remove_above_nyquist(freqs, harm_dist, sample_rate)
# Renormalize after removing above nyquist.
harm_dist_sum = tf.reduce_sum(harm_dist, axis=-1, keepdims=True)
harm_dist = safe_divide(harm_dist, harm_dist_sum)
amps = harm_amp * harm_dist
return amps, freqs
# Harmonic Synthesizer ---------------------------------------------------------
# TODO(jesseengel): Remove reliance on global injection for angular cumsum.
@gin.configurable
def angular_cumsum(angular_frequency, chunk_size=1000):
"""Get phase by cumulative sumation of angular frequency.
Custom cumsum splits first axis into chunks to avoid accumulation error.
Just taking tf.sin(tf.cumsum(angular_frequency)) leads to accumulation of
phase errors that are audible for long segments or at high sample rates. Also,
in reduced precision settings, cumsum can overflow the threshold.
During generation, if syntheiszed examples are longer than ~100k samples,
consider using angular_sum to avoid noticible phase errors. This version is
currently activated by global gin injection. Set the gin parameter
`oscillator_bank.use_angular_cumsum=True` to activate.
Given that we are going to take the sin of the accumulated phase anyways, we
don't care about the phase modulo 2 pi. This code chops the incoming frequency
into chunks, applies cumsum to each chunk, takes mod 2pi, and then stitches
them back together by adding the cumulative values of the final step of each
chunk to the next chunk.
Seems to be ~30% faster on CPU, but at least 40% slower on TPU.
Args:
angular_frequency: Radians per a sample. Shape [batch, time, ...].
If there is no batch dimension, one will be temporarily added.
chunk_size: Number of samples per a chunk. to avoid overflow at low
precision [chunk_size <= (accumulation_threshold / pi)].
Returns:
The accumulated phase in range [0, 2*pi], shape [batch, time, ...].
"""
# Get tensor shapes.
n_batch = angular_frequency.shape[0]
n_time = angular_frequency.shape[1]
n_dims = len(angular_frequency.shape)
n_ch_dims = n_dims - 2
# Pad if needed.
remainder = n_time % chunk_size
if remainder:
pad_amount = chunk_size - remainder
angular_frequency = pad_axis(angular_frequency, [0, pad_amount], axis=1)
# Split input into chunks.
length = angular_frequency.shape[1]
n_chunks = int(length / chunk_size)
chunks = tf.reshape(angular_frequency,
[n_batch, n_chunks, chunk_size] + [-1] * n_ch_dims)
phase = tf.cumsum(chunks, axis=2)
# Add offsets.
# Offset of the next row is the last entry of the previous row.
offsets = phase[:, :, -1:, ...] % (2.0 * np.pi)
offsets = pad_axis(offsets, [1, 0], axis=1)
offsets = offsets[:, :-1, ...]
# Offset is cumulative among the rows.
offsets = tf.cumsum(offsets, axis=1) % (2.0 * np.pi)
phase = phase + offsets
# Put back in original shape.
phase = phase % (2.0 * np.pi)
phase = tf.reshape(phase, [n_batch, length] + [-1] * n_ch_dims)
# Remove padding if added it.
if remainder:
phase = phase[:, :n_time]
return phase
def remove_above_nyquist(frequency_envelopes: tf.Tensor,
amplitude_envelopes: tf.Tensor,
sample_rate: int = 16000) -> tf.Tensor:
"""Set amplitudes for oscillators above nyquist to 0.
Args:
frequency_envelopes: Sample-wise oscillator frequencies (Hz). Shape
[batch_size, n_samples, n_sinusoids].
amplitude_envelopes: Sample-wise oscillator amplitude. Shape [batch_size,
n_samples, n_sinusoids].
sample_rate: Sample rate in samples per a second.
Returns:
amplitude_envelopes: Sample-wise filtered oscillator amplitude.
Shape [batch_size, n_samples, n_sinusoids].
"""
frequency_envelopes = tf_float32(frequency_envelopes)
amplitude_envelopes = tf_float32(amplitude_envelopes)
amplitude_envelopes = tf.where(
tf.greater_equal(frequency_envelopes, sample_rate / 2.0),
tf.zeros_like(amplitude_envelopes), amplitude_envelopes)
return amplitude_envelopes
def normalize_harmonics(harmonic_distribution, f0_hz=None, sample_rate=None):
"""Normalize the harmonic distribution, optionally removing above nyquist."""
# Bandlimit the harmonic distribution.
if sample_rate is not None and f0_hz is not None:
n_harmonics = int(harmonic_distribution.shape[-1])
harmonic_frequencies = get_harmonic_frequencies(f0_hz, n_harmonics)
harmonic_distribution = remove_above_nyquist(
harmonic_frequencies, harmonic_distribution, sample_rate)
# Normalize
harmonic_distribution = safe_divide(
harmonic_distribution,
tf.reduce_sum(harmonic_distribution, axis=-1, keepdims=True))
return harmonic_distribution
# TODO(jesseengel): Remove reliance on global injection for angular cumsum.
@gin.configurable
def oscillator_bank(frequency_envelopes: tf.Tensor,
amplitude_envelopes: tf.Tensor,
sample_rate: int = 16000,
sum_sinusoids: bool = True,
use_angular_cumsum: bool = False) -> tf.Tensor:
"""Generates audio from sample-wise frequencies for a bank of oscillators.
Args:
frequency_envelopes: Sample-wise oscillator frequencies (Hz). Shape
[batch_size, n_samples, n_sinusoids].
amplitude_envelopes: Sample-wise oscillator amplitude. Shape [batch_size,
n_samples, n_sinusoids].
sample_rate: Sample rate in samples per a second.
sum_sinusoids: Add up audio from all the sinusoids.
use_angular_cumsum: If synthesized examples are longer than ~100k audio
samples, consider use_angular_cumsum to avoid accumulating noticible phase
errors due to the limited precision of tf.cumsum. Unlike the rest of the
library, this property can be set with global dependency injection with
gin. Set the gin parameter `oscillator_bank.use_angular_cumsum=True`
to activate. Avoids accumulation of errors for generation, but don't use
usually for training because it is slower on accelerators.
Returns:
wav: Sample-wise audio. Shape [batch_size, n_samples, n_sinusoids] if
sum_sinusoids=False, else shape is [batch_size, n_samples].
"""
frequency_envelopes = tf_float32(frequency_envelopes)
amplitude_envelopes = tf_float32(amplitude_envelopes)
# Don't exceed Nyquist.
amplitude_envelopes = remove_above_nyquist(frequency_envelopes,
amplitude_envelopes,
sample_rate)
# Angular frequency, Hz -> radians per sample.
omegas = frequency_envelopes * (2.0 * np.pi) # rad / sec
omegas = omegas / float(sample_rate) # rad / sample
# Accumulate phase and synthesize.
if use_angular_cumsum:
# Avoids accumulation errors.
phases = angular_cumsum(omegas)
else:
phases = tf.cumsum(omegas, axis=1)
# Convert to waveforms.
wavs = tf.sin(phases)
audio = amplitude_envelopes * wavs # [mb, n_samples, n_sinusoids]
if sum_sinusoids:
audio = tf.reduce_sum(audio, axis=-1) # [mb, n_samples]
return audio
# TODO(jesseengel): Remove reliance on global injection for angular cumsum.
@gin.configurable
def harmonic_oscillator_bank(
frequency: tf.Tensor,
amplitude_envelopes: tf.Tensor,
initial_phase: Optional[tf.Tensor] = None,
sample_rate: int = 16000,
use_angular_cumsum: bool = True) -> tf.Tensor:
"""Special oscillator bank for harmonic frequencies and streaming synthesis.
Args:
frequency: Sample-wise oscillator frequencies (Hz). Shape
[batch_size, n_samples, 1].
amplitude_envelopes: Sample-wise oscillator amplitude. Shape [batch_size,
n_samples, n_sinusoids].
initial_phase: Starting phase. Shape [batch_size, 1, 1].
sample_rate: Sample rate in samples per a second.
use_angular_cumsum: If synthesized examples are longer than ~100k audio
samples, consider use_angular_cumsum to avoid accumulating noticible phase
errors due to the limited precision of tf.cumsum. Unlike the rest of the
library, this property can be set with global dependency injection with
gin. Set the gin parameter `oscillator_bank.use_angular_cumsum=True`
to activate. Avoids accumulation of errors for generation, but don't use
usually for training because it is slower on accelerators.
Returns:
wav: Sample-wise audio. Shape [batch_size, n_samples, n_sinusoids] if
sum_sinusoids=False, else shape is [batch_size, n_samples].
"""
frequency = tf_float32(frequency)
amplitude_envelopes = tf_float32(amplitude_envelopes)
# Angular frequency, Hz -> radians per sample.
omega = frequency * (2.0 * np.pi) # rad / sec
omega = omega / float(sample_rate) # rad / sample