sequence-layers 0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. sequence_layers/__init__.py +16 -0
  2. sequence_layers/internal/types.py +521 -0
  3. sequence_layers/jax/__init__.py +29 -0
  4. sequence_layers/jax/attention.py +6124 -0
  5. sequence_layers/jax/combinators.py +1907 -0
  6. sequence_layers/jax/conditioning.py +511 -0
  7. sequence_layers/jax/convolution.py +2103 -0
  8. sequence_layers/jax/dense.py +447 -0
  9. sequence_layers/jax/dsp.py +1686 -0
  10. sequence_layers/jax/examples/gemma3n_audio_encoder.py +358 -0
  11. sequence_layers/jax/export.py +313 -0
  12. sequence_layers/jax/meta.py +54 -0
  13. sequence_layers/jax/normalization.py +889 -0
  14. sequence_layers/jax/pooling.py +925 -0
  15. sequence_layers/jax/position.py +370 -0
  16. sequence_layers/jax/recurrent.py +674 -0
  17. sequence_layers/jax/sharding.py +48 -0
  18. sequence_layers/jax/signal.py +511 -0
  19. sequence_layers/jax/simple.py +2679 -0
  20. sequence_layers/jax/test_utils.py +1343 -0
  21. sequence_layers/jax/time_varying.py +673 -0
  22. sequence_layers/jax/types.py +1537 -0
  23. sequence_layers/jax/typing.py +59 -0
  24. sequence_layers/jax/utils.py +2149 -0
  25. sequence_layers/tensorflow/__init__.py +56 -0
  26. sequence_layers/tensorflow/attention.py +3426 -0
  27. sequence_layers/tensorflow/combinators.py +938 -0
  28. sequence_layers/tensorflow/conditioning.py +644 -0
  29. sequence_layers/tensorflow/convolution.py +1855 -0
  30. sequence_layers/tensorflow/dense.py +285 -0
  31. sequence_layers/tensorflow/dsp.py +740 -0
  32. sequence_layers/tensorflow/examples/bert.py +144 -0
  33. sequence_layers/tensorflow/examples/conformer.py +138 -0
  34. sequence_layers/tensorflow/examples/deep_voice.py +72 -0
  35. sequence_layers/tensorflow/examples/listen_attend_spell.py +102 -0
  36. sequence_layers/tensorflow/examples/mobilenet.py +92 -0
  37. sequence_layers/tensorflow/examples/t5.py +225 -0
  38. sequence_layers/tensorflow/examples/tacotron.py +124 -0
  39. sequence_layers/tensorflow/examples/transformer.py +159 -0
  40. sequence_layers/tensorflow/examples/very_attentive_tacotron.py +1771 -0
  41. sequence_layers/tensorflow/examples/wavernn.py +225 -0
  42. sequence_layers/tensorflow/normalization.py +1127 -0
  43. sequence_layers/tensorflow/pooling.py +462 -0
  44. sequence_layers/tensorflow/position.py +509 -0
  45. sequence_layers/tensorflow/recurrent.py +645 -0
  46. sequence_layers/tensorflow/simple.py +1207 -0
  47. sequence_layers/tensorflow/squeeze.py +178 -0
  48. sequence_layers/tensorflow/test_util.py +834 -0
  49. sequence_layers/tensorflow/time_varying.py +439 -0
  50. sequence_layers/tensorflow/types.py +961 -0
  51. sequence_layers/tensorflow/utils.py +858 -0
  52. sequence_layers-0.1.dist-info/METADATA +69 -0
  53. sequence_layers-0.1.dist-info/RECORD +55 -0
  54. sequence_layers-0.1.dist-info/WHEEL +4 -0
  55. sequence_layers-0.1.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,225 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """WaveRNN using SequenceLayers.
16
+
17
+ This demonstrates how to train and sample from an autoregressive,
18
+ sample-by-sample waveform predictor that is loosely based on WaveRNN. The main
19
+ differences between this model and WaveRNN are:
20
+ - Uses a single quantized logistic output distribution instead of the "double
21
+ softmax" output distribution.
22
+ - Conditions on multiple previous waveform samples to demonstrate how
23
+ SequenceLayers tracks convolution state.
24
+ - Adds truncated normal noise in training to avoid overfitting.
25
+
26
+ Based on:
27
+ - Efficient Neural Audio Synthesis
28
+ https://arxiv.org/abs/1802.08435
29
+ - PixelCNN++: Improving the PixelCNN with Discretized Logistic Mixture
30
+ Likelihood and Other Modifications
31
+ https://arxiv.org/abs/1701.05517
32
+ """
33
+
34
+ from typing import Optional
35
+
36
+ from sequence_layers import tensorflow as sl
37
+ import tensorflow.compat.v2 as tf
38
+ import tensorflow_probability as tfp
39
+
40
+ tfd = tfp.distributions
41
+ tfb = tfp.bijectors
42
+
43
+
44
+ def WaveRNNBody(
45
+ num_units: int,
46
+ num_distribution_parameters: int,
47
+ conditioning_name: str,
48
+ upsample_ratio: int,
49
+ ) -> sl.SequenceLayer:
50
+ """Builds a WaveRNN-like SequenceLayer body.
51
+
52
+ This is the "body" of the autoregressive model. In sampling, the input is the
53
+ previous output sample, while in training it is teacher forced inputs (i.e.
54
+ the ground truth audio shifted by one timestep). The body doesn't know whether
55
+ the inputs it processes are teacher forced or true samples.
56
+
57
+ See the WaveRNN class below for an example of how to teacher force and sample
58
+ from this model.
59
+
60
+ Args:
61
+ num_units: The number of units for the WaveRNN.
62
+ num_distribution_parameters: The number of distribution parameters to
63
+ predict per timestep.
64
+ conditioning_name: The name of the conditioning feature provided to the
65
+ layer.
66
+ upsample_ratio: The ratio of waveform timesteps to conditioning feature
67
+ timesteps.
68
+
69
+ Returns:
70
+ A SequenceLayer that outputs num_distribution_parameters for each timestep.
71
+ """
72
+ return sl.Serial([
73
+ # Condition on the previous 5 samples.
74
+ sl.Conv1D(filters=num_units, kernel_size=5),
75
+ # Upsample and project the conditioning to num_units and add it to the
76
+ # previous output representation.
77
+ sl.UpsampleConditioning(
78
+ conditioning_name,
79
+ projection=sl.UpsampleConditioning.Projection.LINEAR,
80
+ combination=sl.UpsampleConditioning.Combination.ADD,
81
+ upsample_ratio=upsample_ratio,
82
+ ),
83
+ # Add noise to the GRU inputs in training to avoid overfitting on
84
+ # the conditioning and previous outputs.
85
+ sl.Noise(
86
+ sl.TruncatedNormalSampler(mean=0.0, stddev=0.01), training_only=True
87
+ ),
88
+ # Recurrent transformation.
89
+ sl.RNN(tf.keras.layers.GRUCell(num_units)),
90
+ # Linear projection to the distribution parameters we are modeling.
91
+ sl.Dense(num_distribution_parameters),
92
+ ])
93
+
94
+
95
+ class WaveRNN(tf.Module):
96
+ """A simplified WaveRNN model."""
97
+
98
+ def __init__(
99
+ self, num_units: int, upsample_ratio: int, name: Optional[str] = None
100
+ ):
101
+ super().__init__(name=name)
102
+ self._upsample_ratio = upsample_ratio
103
+ # Build the SequenceLayer body that predicts distribution parameters for
104
+ # each waveform sample from conditioning features and previous timesteps.
105
+ with self.name_scope:
106
+ self._body = WaveRNNBody(
107
+ num_units,
108
+ # One location and scale parameter per timestep.
109
+ num_distribution_parameters=2,
110
+ conditioning_name='conditioning',
111
+ upsample_ratio=upsample_ratio,
112
+ )
113
+
114
+ def _get_distribution(self, logits: tf.Tensor) -> tfd.Distribution:
115
+ loc, scale_logits = tf.split(logits, 2, axis=-1)
116
+ # Ensure scale is positive.
117
+ scale = 1e-16 + tf.nn.softplus(scale_logits)
118
+ # Model the waveform with a single quantized logistic distribution.
119
+ # This is similar to the output distribution used in the PixelCNN++ paper.
120
+ distribution = tfd.Logistic(loc, scale)
121
+ # Quantize the [-1.0, 1.0] float samples into 2**14 + 1 (for symmetry) bins.
122
+ # TODO(b/157322614): Predict 2**16 + 1 bins once numerically stable to match
123
+ # the actual quantization of typical PCM audio we train WaveRNN on.
124
+ distribution = tfd.QuantizedDistribution(distribution, low=-8192, high=8192)
125
+ return tfd.TransformedDistribution(
126
+ distribution=distribution, bijector=tfb.Scale(scale=1.0 / 8192)
127
+ )
128
+
129
+ def log_prob(
130
+ self, waveform: sl.Sequence, conditioning: sl.Sequence, training: bool
131
+ ) -> sl.Sequence:
132
+ """Compute log P(waveform|conditioning) under this model.
133
+
134
+ Computes the log probability of waveform under the distribution implied by
135
+ conditioning. Maximizing this value trains the WaveRNN to predict this
136
+ waveform.
137
+
138
+ It is typical for waveform and conditioning to be a slice (e.g. 40 ms of
139
+ audio) of a larger waveform sequence, since it's typically infeasible to
140
+ train an RNN unrolled at common speech waveform sample rates.
141
+
142
+ Args:
143
+ waveform: The waveform to compute the log probability of, shaped [b, t_w,
144
+ 1] with float samples in the range [-1, 1].
145
+ conditioning: The conditioning feature sequence, [b, t_c, ...]. The
146
+ relation t_w = t_c * upsample_ratio must hold.
147
+ training: Whether we are in training mode.
148
+
149
+ Returns:
150
+ A Sequence containing per-timestep log probabilities.
151
+ """
152
+ # To teacher force an autoregressive model we pretend that it did a perfect
153
+ # job producing the ground truth on the previous step. This is normally done
154
+ # by padding the ground truth with one sample and trimming one off the end.
155
+ #
156
+ # So for the sequence:
157
+ # A B C D E F
158
+ # the inputs to the layer look like:
159
+ # 0 A B C D E
160
+ # We then optimize the likelihood of the ground truth to train it to predict
161
+ # the ground truth sequence.
162
+ #
163
+ # An easy way to do this is to compose the body with a Delay layer:
164
+ teacher_forcing = sl.Serial([sl.Delay(self._body.block_size), self._body])
165
+ logits = teacher_forcing.layer(
166
+ waveform, training=training, constants={'conditioning': conditioning}
167
+ )
168
+ distribution = self._get_distribution(logits.values)
169
+ return waveform.apply_values(distribution.log_prob).mask_invalid()
170
+
171
+ @tf.function
172
+ def sample(self, conditioning: sl.Sequence) -> sl.Sequence:
173
+ """Sample from the distribution P(waveform|conditioning).
174
+
175
+ Args:
176
+ conditioning: The conditioning sequence [b, t_c, ...].
177
+
178
+ Returns:
179
+ A sampled waveform sequence shaped [b, t_w, 1], where
180
+ t_w = t_c * upsample_ratio.
181
+ """
182
+ batch_size, conditioning_time = conditioning.values.shape.as_list()[:2]
183
+
184
+ # Since the ratio between the conditioning features and the waveform
185
+ # sequence is fixed, we know how many samples we are going to produce for
186
+ # conditioning.
187
+ time = conditioning_time * self._upsample_ratio
188
+
189
+ # A TensorArray-like object to write the samples to at each timestep.
190
+ sequence_array = sl.SequenceArray.new(tf.float32, size=time)
191
+
192
+ # When sampling from the model the input to each timestep is the output from
193
+ # the previous timestep. On the first iteration, we have no output to feed
194
+ # in, so we just feed in a zero vector. This matches the zero padding
195
+ # timestep we insert via the Delay layer in the above log_prob method.
196
+ output = sl.Sequence(
197
+ tf.zeros([batch_size, self._body.block_size, 1]),
198
+ tf.ones([batch_size, self._body.block_size]),
199
+ )
200
+
201
+ # We provide the conditioning sequence to the SequenceLayer via a
202
+ # "constants" dictionary. The key matches the name we used when creating the
203
+ # WaveRNN body.
204
+ constants = {'conditioning': conditioning}
205
+
206
+ # Get the initial state for the layer. This will be updated for each
207
+ # timestep of the sampling loop.
208
+ state = self._body.get_initial_state(output, constants=constants)
209
+
210
+ # For each timestep of the output waveform:
211
+ # - compute the new state and distribution parameters from the previous
212
+ # state and output.
213
+ # - draw a sample from the distribution.
214
+ # - write the sample to the SequenceArray.
215
+ for i in tf.range(time):
216
+ logits, state = self._body.step(
217
+ output, state, training=False, constants=constants
218
+ )
219
+ distribution = self._get_distribution(logits.values)
220
+ output = sl.Sequence(distribution.sample(), logits.mask)
221
+ sequence_array = sequence_array.write(i, output)
222
+
223
+ # Concatenate all the timesteps together into a final Sequence, and mask out
224
+ # the timesteps that were computed from padding.
225
+ return sequence_array.concat().mask_invalid()