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.
- sequence_layers/__init__.py +16 -0
- sequence_layers/internal/types.py +521 -0
- sequence_layers/jax/__init__.py +29 -0
- sequence_layers/jax/attention.py +6124 -0
- sequence_layers/jax/combinators.py +1907 -0
- sequence_layers/jax/conditioning.py +511 -0
- sequence_layers/jax/convolution.py +2103 -0
- sequence_layers/jax/dense.py +447 -0
- sequence_layers/jax/dsp.py +1686 -0
- sequence_layers/jax/examples/gemma3n_audio_encoder.py +358 -0
- sequence_layers/jax/export.py +313 -0
- sequence_layers/jax/meta.py +54 -0
- sequence_layers/jax/normalization.py +889 -0
- sequence_layers/jax/pooling.py +925 -0
- sequence_layers/jax/position.py +370 -0
- sequence_layers/jax/recurrent.py +674 -0
- sequence_layers/jax/sharding.py +48 -0
- sequence_layers/jax/signal.py +511 -0
- sequence_layers/jax/simple.py +2679 -0
- sequence_layers/jax/test_utils.py +1343 -0
- sequence_layers/jax/time_varying.py +673 -0
- sequence_layers/jax/types.py +1537 -0
- sequence_layers/jax/typing.py +59 -0
- sequence_layers/jax/utils.py +2149 -0
- sequence_layers/tensorflow/__init__.py +56 -0
- sequence_layers/tensorflow/attention.py +3426 -0
- sequence_layers/tensorflow/combinators.py +938 -0
- sequence_layers/tensorflow/conditioning.py +644 -0
- sequence_layers/tensorflow/convolution.py +1855 -0
- sequence_layers/tensorflow/dense.py +285 -0
- sequence_layers/tensorflow/dsp.py +740 -0
- sequence_layers/tensorflow/examples/bert.py +144 -0
- sequence_layers/tensorflow/examples/conformer.py +138 -0
- sequence_layers/tensorflow/examples/deep_voice.py +72 -0
- sequence_layers/tensorflow/examples/listen_attend_spell.py +102 -0
- sequence_layers/tensorflow/examples/mobilenet.py +92 -0
- sequence_layers/tensorflow/examples/t5.py +225 -0
- sequence_layers/tensorflow/examples/tacotron.py +124 -0
- sequence_layers/tensorflow/examples/transformer.py +159 -0
- sequence_layers/tensorflow/examples/very_attentive_tacotron.py +1771 -0
- sequence_layers/tensorflow/examples/wavernn.py +225 -0
- sequence_layers/tensorflow/normalization.py +1127 -0
- sequence_layers/tensorflow/pooling.py +462 -0
- sequence_layers/tensorflow/position.py +509 -0
- sequence_layers/tensorflow/recurrent.py +645 -0
- sequence_layers/tensorflow/simple.py +1207 -0
- sequence_layers/tensorflow/squeeze.py +178 -0
- sequence_layers/tensorflow/test_util.py +834 -0
- sequence_layers/tensorflow/time_varying.py +439 -0
- sequence_layers/tensorflow/types.py +961 -0
- sequence_layers/tensorflow/utils.py +858 -0
- sequence_layers-0.1.dist-info/METADATA +69 -0
- sequence_layers-0.1.dist-info/RECORD +55 -0
- sequence_layers-0.1.dist-info/WHEEL +4 -0
- sequence_layers-0.1.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,1127 @@
|
|
|
1
|
+
# Copyright 2023 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
|
+
"""Normalization layers."""
|
|
15
|
+
|
|
16
|
+
from typing import List, Optional, Sequence, Tuple, Union
|
|
17
|
+
|
|
18
|
+
from sequence_layers.tensorflow import types
|
|
19
|
+
import tensorflow.compat.v1 as tf1
|
|
20
|
+
import tensorflow.compat.v2 as tf
|
|
21
|
+
|
|
22
|
+
# TODO(dthkao): Since this is only needed for tf1 tpu context checking,
|
|
23
|
+
# consider removing TF1 support?
|
|
24
|
+
from tensorflow.python.tpu.tpu_function import get_tpu_context
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _is_tf1_tpu():
|
|
28
|
+
"""Returns True if we are in an XLA context."""
|
|
29
|
+
if tf.__internal__.tf2.enabled():
|
|
30
|
+
return False
|
|
31
|
+
return get_tpu_context().number_of_shards is not None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _validate_and_normalize_axes(
|
|
35
|
+
axes: Union[int, List[int]], input_shape: tf.TensorShape
|
|
36
|
+
) -> List[int]:
|
|
37
|
+
"""Normalizes user-provided axes and checks batch/time are not specified."""
|
|
38
|
+
if isinstance(axes, int):
|
|
39
|
+
axes = [axes]
|
|
40
|
+
else:
|
|
41
|
+
axes = list(axes)
|
|
42
|
+
for axis in axes:
|
|
43
|
+
if axis < 0:
|
|
44
|
+
axis += input_shape.rank
|
|
45
|
+
if axis in (0, 1):
|
|
46
|
+
raise ValueError(
|
|
47
|
+
'Normalizing over the batch or time dimension is '
|
|
48
|
+
f'not allowed. Got: {axes}'
|
|
49
|
+
)
|
|
50
|
+
return axes
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class LayerNormalization(types.PreservesShape, types.Stateless):
|
|
54
|
+
"""Applies layer normalization to input sequences."""
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
axis=-1,
|
|
59
|
+
epsilon=0.001,
|
|
60
|
+
center=True,
|
|
61
|
+
scale=True,
|
|
62
|
+
beta_initializer='zeros',
|
|
63
|
+
gamma_initializer='ones',
|
|
64
|
+
beta_regularizer=None,
|
|
65
|
+
gamma_regularizer=None,
|
|
66
|
+
beta_constraint=None,
|
|
67
|
+
gamma_constraint=None,
|
|
68
|
+
trainable=True,
|
|
69
|
+
name=None,
|
|
70
|
+
):
|
|
71
|
+
super().__init__(name=name)
|
|
72
|
+
self._layer = None
|
|
73
|
+
self._layer_kwargs = {
|
|
74
|
+
'axis': axis,
|
|
75
|
+
'epsilon': epsilon,
|
|
76
|
+
'center': center,
|
|
77
|
+
'scale': scale,
|
|
78
|
+
'beta_initializer': beta_initializer,
|
|
79
|
+
'gamma_initializer': gamma_initializer,
|
|
80
|
+
'beta_regularizer': beta_regularizer,
|
|
81
|
+
'gamma_regularizer': gamma_regularizer,
|
|
82
|
+
'beta_constraint': beta_constraint,
|
|
83
|
+
'gamma_constraint': gamma_constraint,
|
|
84
|
+
'trainable': trainable,
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
def build(self, input_shape: tf.TensorShape):
|
|
88
|
+
if self._layer is None:
|
|
89
|
+
self._layer_kwargs['axis'] = _validate_and_normalize_axes(
|
|
90
|
+
self._layer_kwargs['axis'], input_shape
|
|
91
|
+
)
|
|
92
|
+
with self.name_scope as name_scope:
|
|
93
|
+
self._layer = tf.keras.layers.LayerNormalization(
|
|
94
|
+
**self._layer_kwargs, name=name_scope
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
@tf.Module.with_name_scope
|
|
98
|
+
def layer(
|
|
99
|
+
self,
|
|
100
|
+
x: types.Sequence,
|
|
101
|
+
training: bool,
|
|
102
|
+
initial_state: types.State = None,
|
|
103
|
+
constants: types.Constants = None,
|
|
104
|
+
) -> types.Sequence:
|
|
105
|
+
self.build(x.values.shape)
|
|
106
|
+
# TODO(rryan): Investigate precision of Keras LayerNormalization. It
|
|
107
|
+
# requires dropping layer/step equivalence tests to to 1e-5 tolerance.
|
|
108
|
+
values = self._layer(x.values, training=training)
|
|
109
|
+
return types.Sequence(values, x.mask).mask_invalid()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class RMSNormalization(types.PreservesShape, types.Stateless):
|
|
113
|
+
"""A simplified version of LayerNormalization used in T5.
|
|
114
|
+
|
|
115
|
+
No mean statistics or offset terms are included.
|
|
116
|
+
|
|
117
|
+
Implementation follows:
|
|
118
|
+
https://github.com/tensorflow/models/blob/master/official/nlp/modeling/models/t5.py
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
def __init__(
|
|
122
|
+
self,
|
|
123
|
+
axis: Union[int, tuple[int, ...]] = -1,
|
|
124
|
+
epsilon: float = 0.001,
|
|
125
|
+
scale: bool = True,
|
|
126
|
+
gamma_initializer: tf.keras.initializers.Initializer = 'ones',
|
|
127
|
+
trainable: bool = True,
|
|
128
|
+
name: Optional[str] = None,
|
|
129
|
+
):
|
|
130
|
+
super().__init__(name=name)
|
|
131
|
+
self._epsilon = epsilon
|
|
132
|
+
self._axis = axis
|
|
133
|
+
self._gamma_initializer = tf.keras.initializers.get(gamma_initializer)
|
|
134
|
+
self._trainable = trainable
|
|
135
|
+
self._built = False
|
|
136
|
+
self._should_scale = scale
|
|
137
|
+
|
|
138
|
+
def build(self, input_shape: tf.TensorShape):
|
|
139
|
+
if self._built:
|
|
140
|
+
return
|
|
141
|
+
with self.name_scope:
|
|
142
|
+
self._axis = _validate_and_normalize_axes(self._axis, input_shape)
|
|
143
|
+
param_shape = [input_shape[dim] for dim in self._axis]
|
|
144
|
+
|
|
145
|
+
if self._should_scale:
|
|
146
|
+
self.scale = tf.Variable(
|
|
147
|
+
lambda: self._gamma_initializer(param_shape),
|
|
148
|
+
trainable=self._trainable,
|
|
149
|
+
name='gamma',
|
|
150
|
+
)
|
|
151
|
+
self._built = True
|
|
152
|
+
|
|
153
|
+
@tf.Module.with_name_scope
|
|
154
|
+
def layer(
|
|
155
|
+
self,
|
|
156
|
+
x: types.Sequence,
|
|
157
|
+
training: bool,
|
|
158
|
+
initial_state: Optional[types.State] = None,
|
|
159
|
+
constants: Optional[types.Constants] = None,
|
|
160
|
+
) -> types.Sequence:
|
|
161
|
+
x_dtype = x.values.dtype
|
|
162
|
+
if not x_dtype.is_floating:
|
|
163
|
+
raise ValueError(f'{self} requires floating point inputs.')
|
|
164
|
+
self.build(x.values.shape)
|
|
165
|
+
|
|
166
|
+
# Compute variance in fp32.
|
|
167
|
+
variance_dtype = tf.float32 if x_dtype.size < tf.float32.size else x_dtype
|
|
168
|
+
values = tf.cast(x.values, variance_dtype)
|
|
169
|
+
variance = tf.math.reduce_mean(
|
|
170
|
+
tf.math.square(values), axis=self._axis, keepdims=True
|
|
171
|
+
)
|
|
172
|
+
values = values * tf.math.rsqrt(variance + self._epsilon)
|
|
173
|
+
values = tf.cast(values, x_dtype)
|
|
174
|
+
|
|
175
|
+
if self._should_scale:
|
|
176
|
+
scale = self.scale
|
|
177
|
+
# If simple broadcasting doesn't work, reshape
|
|
178
|
+
if self._axis != [values.shape.rank - 1]:
|
|
179
|
+
# Broadcasting only necessary for norm when the axis is not just
|
|
180
|
+
# the last dimension
|
|
181
|
+
broadcast_shape = [1] * values.shape.rank
|
|
182
|
+
for dim in self._axis:
|
|
183
|
+
broadcast_shape[dim] = values.shape.dims[dim].value
|
|
184
|
+
scale = tf.reshape(scale, broadcast_shape)
|
|
185
|
+
|
|
186
|
+
values = values * tf.cast(scale, values.dtype)
|
|
187
|
+
|
|
188
|
+
return types.Sequence(values, x.mask).mask_invalid()
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class _SequenceBatchNormalization(tf.keras.layers.Layer):
|
|
192
|
+
"""Like Keras BatchNormalization but sequence and multi-replica aware.
|
|
193
|
+
|
|
194
|
+
Only valid timesteps of input sequences are considered for computing moments,
|
|
195
|
+
and they are computed across replicas with DistributionStrategy
|
|
196
|
+
ReplicaContext.all_reduce, or in TF1 mode on TPU with
|
|
197
|
+
tf.tpu.cross_replica_sum.
|
|
198
|
+
"""
|
|
199
|
+
|
|
200
|
+
def __init__(
|
|
201
|
+
self,
|
|
202
|
+
axis=-1,
|
|
203
|
+
momentum=0.99,
|
|
204
|
+
epsilon=1e-3,
|
|
205
|
+
center=True,
|
|
206
|
+
scale=True,
|
|
207
|
+
beta_initializer=tf.zeros_initializer(),
|
|
208
|
+
gamma_initializer=tf.ones_initializer(),
|
|
209
|
+
moving_mean_initializer=tf.zeros_initializer(),
|
|
210
|
+
moving_variance_initializer=tf.ones_initializer(),
|
|
211
|
+
beta_regularizer=None,
|
|
212
|
+
gamma_regularizer=None,
|
|
213
|
+
beta_constraint=None,
|
|
214
|
+
gamma_constraint=None,
|
|
215
|
+
trainable=True,
|
|
216
|
+
name=None,
|
|
217
|
+
use_cross_replica_sum=True,
|
|
218
|
+
mask_output=True,
|
|
219
|
+
**kwargs,
|
|
220
|
+
):
|
|
221
|
+
super().__init__(name=name, **kwargs)
|
|
222
|
+
if isinstance(axis, (list, tuple)):
|
|
223
|
+
self.axis = axis[:]
|
|
224
|
+
elif isinstance(axis, int):
|
|
225
|
+
self.axis = axis
|
|
226
|
+
else:
|
|
227
|
+
raise TypeError('axis must be int or tuple/list, got: %s' % axis)
|
|
228
|
+
self.momentum = momentum
|
|
229
|
+
self.epsilon = epsilon
|
|
230
|
+
self.center = center
|
|
231
|
+
self.scale = scale
|
|
232
|
+
self.beta_initializer = tf.keras.initializers.get(beta_initializer)
|
|
233
|
+
self.gamma_initializer = tf.keras.initializers.get(gamma_initializer)
|
|
234
|
+
self.moving_mean_initializer = tf.keras.initializers.get(
|
|
235
|
+
moving_mean_initializer
|
|
236
|
+
)
|
|
237
|
+
self.moving_variance_initializer = tf.keras.initializers.get(
|
|
238
|
+
moving_variance_initializer
|
|
239
|
+
)
|
|
240
|
+
self.beta_regularizer = tf.keras.regularizers.get(beta_regularizer)
|
|
241
|
+
self.gamma_regularizer = tf.keras.regularizers.get(gamma_regularizer)
|
|
242
|
+
self.beta_constraint = tf.keras.constraints.get(beta_constraint)
|
|
243
|
+
self.gamma_constraint = tf.keras.constraints.get(gamma_constraint)
|
|
244
|
+
self.supports_masking = True
|
|
245
|
+
self._trainable = trainable
|
|
246
|
+
self._use_cross_replica_sum = use_cross_replica_sum
|
|
247
|
+
self._mask_output = mask_output
|
|
248
|
+
|
|
249
|
+
@property
|
|
250
|
+
def trainable(self):
|
|
251
|
+
return self._trainable
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def _param_dtype(self):
|
|
255
|
+
# Raise parameters of fp16 batch norm to fp32
|
|
256
|
+
if self.dtype == tf.float16 or self.dtype == tf.bfloat16:
|
|
257
|
+
return tf.float32
|
|
258
|
+
else:
|
|
259
|
+
return self.dtype or tf.float32
|
|
260
|
+
|
|
261
|
+
def _support_zero_size_input(self):
|
|
262
|
+
return tf.distribute.has_strategy() and getattr(
|
|
263
|
+
tf.distribute.get_strategy().extended,
|
|
264
|
+
'enable_partial_batch_handling',
|
|
265
|
+
False,
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
def build(self, input_and_mask_shape):
|
|
269
|
+
input_shape, _ = input_and_mask_shape
|
|
270
|
+
input_shape = tf.TensorShape(input_shape)
|
|
271
|
+
if not input_shape.ndims:
|
|
272
|
+
raise ValueError('Input has undefined rank:', input_shape)
|
|
273
|
+
ndims = len(input_shape)
|
|
274
|
+
|
|
275
|
+
# Convert axis to list and resolve negatives
|
|
276
|
+
if isinstance(self.axis, int):
|
|
277
|
+
self.axis = [self.axis]
|
|
278
|
+
|
|
279
|
+
for idx, x in enumerate(self.axis):
|
|
280
|
+
if x < 0:
|
|
281
|
+
self.axis[idx] = ndims + x
|
|
282
|
+
|
|
283
|
+
# Validate axes
|
|
284
|
+
for x in self.axis:
|
|
285
|
+
if x < 0 or x >= ndims:
|
|
286
|
+
raise ValueError('Invalid axis: %d' % x)
|
|
287
|
+
if len(self.axis) != len(set(self.axis)):
|
|
288
|
+
raise ValueError('Duplicate axis: %s' % self.axis)
|
|
289
|
+
if 0 in self.axis or 1 in self.axis:
|
|
290
|
+
raise ValueError(
|
|
291
|
+
'This implementation assumes axis 0 is batch and 1 is '
|
|
292
|
+
'time. Computing BatchNormalization on either of these '
|
|
293
|
+
'dimensions is not supported. Got axis=%s'
|
|
294
|
+
% self.axis
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
axis_to_dim = {x: input_shape.dims[x].value for x in self.axis}
|
|
298
|
+
for x in axis_to_dim:
|
|
299
|
+
if axis_to_dim[x] is None:
|
|
300
|
+
raise ValueError(
|
|
301
|
+
'Input has undefined `axis` dimension. Received input '
|
|
302
|
+
'with shape %s. Axis value: %s' % (tuple(input_shape), self.axis)
|
|
303
|
+
)
|
|
304
|
+
self.input_spec = (
|
|
305
|
+
tf.keras.layers.InputSpec(ndim=ndims, axes=axis_to_dim),
|
|
306
|
+
tf.keras.layers.InputSpec(shape=[None, None], dtype=types.MASK_DTYPE),
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
if len(axis_to_dim) == 1:
|
|
310
|
+
# Single axis batch norm (most common/default use-case)
|
|
311
|
+
param_shape = (list(axis_to_dim.values())[0],)
|
|
312
|
+
else:
|
|
313
|
+
# Parameter shape is the original shape but with 1 in all non-axis dims
|
|
314
|
+
param_shape = [
|
|
315
|
+
axis_to_dim[i] if i in axis_to_dim else 1 for i in range(ndims)
|
|
316
|
+
]
|
|
317
|
+
|
|
318
|
+
if self.scale:
|
|
319
|
+
self.gamma = self.add_weight(
|
|
320
|
+
name='gamma',
|
|
321
|
+
shape=param_shape,
|
|
322
|
+
dtype=self._param_dtype,
|
|
323
|
+
initializer=self.gamma_initializer,
|
|
324
|
+
regularizer=self.gamma_regularizer,
|
|
325
|
+
constraint=self.gamma_constraint,
|
|
326
|
+
trainable=self.trainable,
|
|
327
|
+
experimental_autocast=False,
|
|
328
|
+
)
|
|
329
|
+
else:
|
|
330
|
+
self.gamma = None
|
|
331
|
+
|
|
332
|
+
if self.center:
|
|
333
|
+
self.beta = self.add_weight(
|
|
334
|
+
name='beta',
|
|
335
|
+
shape=param_shape,
|
|
336
|
+
dtype=self._param_dtype,
|
|
337
|
+
initializer=self.beta_initializer,
|
|
338
|
+
regularizer=self.beta_regularizer,
|
|
339
|
+
constraint=self.beta_constraint,
|
|
340
|
+
trainable=self.trainable,
|
|
341
|
+
experimental_autocast=False,
|
|
342
|
+
)
|
|
343
|
+
else:
|
|
344
|
+
self.beta = None
|
|
345
|
+
|
|
346
|
+
# Disable variable partitioning when creating the moving mean and variance
|
|
347
|
+
if hasattr(self, '_scope') and self._scope:
|
|
348
|
+
partitioner = self._scope.partitioner
|
|
349
|
+
self._scope.set_partitioner(None)
|
|
350
|
+
else:
|
|
351
|
+
partitioner = None
|
|
352
|
+
try:
|
|
353
|
+
self.moving_mean = self.add_weight(
|
|
354
|
+
name='moving_mean',
|
|
355
|
+
shape=param_shape,
|
|
356
|
+
dtype=self._param_dtype,
|
|
357
|
+
initializer=self.moving_mean_initializer,
|
|
358
|
+
synchronization=tf.VariableSynchronization.ON_READ,
|
|
359
|
+
trainable=False,
|
|
360
|
+
aggregation=tf.VariableAggregation.MEAN,
|
|
361
|
+
experimental_autocast=False,
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
self.moving_variance = self.add_weight(
|
|
365
|
+
name='moving_variance',
|
|
366
|
+
shape=param_shape,
|
|
367
|
+
dtype=self._param_dtype,
|
|
368
|
+
initializer=self.moving_variance_initializer,
|
|
369
|
+
synchronization=tf.VariableSynchronization.ON_READ,
|
|
370
|
+
trainable=False,
|
|
371
|
+
aggregation=tf.VariableAggregation.MEAN,
|
|
372
|
+
experimental_autocast=False,
|
|
373
|
+
)
|
|
374
|
+
finally:
|
|
375
|
+
if partitioner:
|
|
376
|
+
self._scope.set_partitioner(partitioner)
|
|
377
|
+
self.built = True
|
|
378
|
+
|
|
379
|
+
def _assign_moving_average(self, variable, value, momentum, inputs_size):
|
|
380
|
+
with tf.name_scope('AssignMovingAvg') as scope:
|
|
381
|
+
with tf1.colocate_with(variable):
|
|
382
|
+
decay = tf.convert_to_tensor(1.0 - momentum, name='decay')
|
|
383
|
+
if decay.dtype != variable.dtype.base_dtype:
|
|
384
|
+
decay = tf.cast(decay, variable.dtype.base_dtype)
|
|
385
|
+
update_delta = (variable - tf.cast(value, variable.dtype)) * decay
|
|
386
|
+
if inputs_size is not None:
|
|
387
|
+
update_delta = tf.where(inputs_size > 0, update_delta, 0)
|
|
388
|
+
return tf1.assign_sub(variable, update_delta, name=scope)
|
|
389
|
+
|
|
390
|
+
def _assign_new_value(self, variable, value):
|
|
391
|
+
with tf.name_scope('AssignNewValue') as scope:
|
|
392
|
+
with tf1.colocate_with(variable):
|
|
393
|
+
return tf.assign(variable, value, name=scope)
|
|
394
|
+
|
|
395
|
+
def _maybe_cross_replica_sum(self, values):
|
|
396
|
+
# Don't sum across replicas if disabled by the caller.
|
|
397
|
+
if not self._use_cross_replica_sum:
|
|
398
|
+
return values
|
|
399
|
+
|
|
400
|
+
# In TF1 mode on a TPU, use tf1.tpu.cross_replica_sum.
|
|
401
|
+
if _is_tf1_tpu():
|
|
402
|
+
return tf1.tpu.cross_replica_sum(values)
|
|
403
|
+
|
|
404
|
+
# If we're in a DistributionStrategy replica context, use all_reduce.
|
|
405
|
+
replica_context = tf.distribute.get_replica_context()
|
|
406
|
+
if replica_context is not None:
|
|
407
|
+
return replica_context.all_reduce(tf.distribute.ReduceOp.SUM, values)
|
|
408
|
+
|
|
409
|
+
# Otherwise leave values unchanged.
|
|
410
|
+
return values
|
|
411
|
+
|
|
412
|
+
def _moments(self, inputs, mask, reduction_axes, keep_dims):
|
|
413
|
+
"""Compute the moments of inputs/input_lengths over reduction_axes.
|
|
414
|
+
|
|
415
|
+
This implementation follows the version in:
|
|
416
|
+
https://github.com/tensorflow/lingvo/blob/master/lingvo/core/bn_layers.py
|
|
417
|
+
|
|
418
|
+
Args:
|
|
419
|
+
inputs: A [batch_size, time, ...] tensor of sequences.
|
|
420
|
+
mask: A [batch_size, time, 1...] mask tensor containing 1.0 for valid
|
|
421
|
+
timesteps.
|
|
422
|
+
reduction_axes: The axes to reduce over for computing the moments.
|
|
423
|
+
keep_dims: If true, preserve reduction_axes in the output moments.
|
|
424
|
+
|
|
425
|
+
Returns:
|
|
426
|
+
means: The means of inputs along the axes indicated in
|
|
427
|
+
reduction_axes. For example, if the input is [a, b, c, d] and
|
|
428
|
+
reduction_axes is [0, 1, 3], means's shape is [c] if keep_dims is
|
|
429
|
+
False, and [1, 1, c, 1] if keep_dims is True.
|
|
430
|
+
variances: The variance of inputs along the axes indicated in
|
|
431
|
+
reduction_axes. For example, if the input is [a, b, c, d] and
|
|
432
|
+
reduction_axes is [0, 1, 3], variance's shape is [c] if keep_dims is
|
|
433
|
+
False, and [1, 1, c, 1] if keep_dims is True.
|
|
434
|
+
"""
|
|
435
|
+
# This method assumes we are reducing over the batch and time dimension of
|
|
436
|
+
# the sequence.
|
|
437
|
+
assert 0 in reduction_axes and 1 in reduction_axes
|
|
438
|
+
|
|
439
|
+
# TODO(rryan): We should be able to assume inputs are masked.
|
|
440
|
+
sum_v = tf.reduce_sum(inputs * mask, reduction_axes, keepdims=True)
|
|
441
|
+
count_v = tf.reduce_sum(mask, reduction_axes, keepdims=True)
|
|
442
|
+
|
|
443
|
+
# Multiply counts by non-batch/time reduction dimensions.
|
|
444
|
+
if len(reduction_axes) > 2:
|
|
445
|
+
counts_multiplier = tf.gather(
|
|
446
|
+
tf.shape(inputs), [a for a in reduction_axes if a not in (0, 1)]
|
|
447
|
+
)
|
|
448
|
+
count_v *= tf.cast(tf.reduce_prod(counts_multiplier), count_v.dtype)
|
|
449
|
+
|
|
450
|
+
# Aggregate sums and counts across replicas if enabled.
|
|
451
|
+
sum_v = self._maybe_cross_replica_sum(sum_v)
|
|
452
|
+
count_v = self._maybe_cross_replica_sum(count_v)
|
|
453
|
+
|
|
454
|
+
count_v = tf.maximum(count_v, 1.0)
|
|
455
|
+
mean = sum_v / count_v
|
|
456
|
+
sum_vv = tf.reduce_sum(
|
|
457
|
+
tf.square(inputs - mean) * mask, reduction_axes, keepdims=keep_dims
|
|
458
|
+
)
|
|
459
|
+
|
|
460
|
+
# Aggregate summed squares across replicas if enabled.
|
|
461
|
+
sum_vv = self._maybe_cross_replica_sum(sum_vv)
|
|
462
|
+
|
|
463
|
+
if not keep_dims:
|
|
464
|
+
count_v = tf.squeeze(count_v, reduction_axes)
|
|
465
|
+
mean = tf.squeeze(mean, reduction_axes)
|
|
466
|
+
|
|
467
|
+
variance = sum_vv / count_v
|
|
468
|
+
# TODO(b/129279393): Support zero batch input in non DistributionStrategy
|
|
469
|
+
# code as well.
|
|
470
|
+
if self._support_zero_size_input():
|
|
471
|
+
input_batch_size = tf.size(inputs)
|
|
472
|
+
mean = tf.where(input_batch_size > 0, mean, 0)
|
|
473
|
+
variance = tf.where(input_batch_size > 0, variance, 0)
|
|
474
|
+
return mean, variance
|
|
475
|
+
|
|
476
|
+
def _get_training_value(self, training=None):
|
|
477
|
+
if training is None:
|
|
478
|
+
training = tf.keras.backend.learning_phase()
|
|
479
|
+
return training
|
|
480
|
+
|
|
481
|
+
def call(self, inputs_and_mask, training=None):
|
|
482
|
+
inputs, mask = inputs_and_mask
|
|
483
|
+
expanded_mask = types.Sequence(inputs, mask).expanded_mask()
|
|
484
|
+
training = self._get_training_value(training)
|
|
485
|
+
|
|
486
|
+
inputs_dtype = inputs.dtype.base_dtype
|
|
487
|
+
if inputs_dtype in (tf.float16, tf.bfloat16):
|
|
488
|
+
# Do all math in float32 if given 16-bit inputs for numeric stability.
|
|
489
|
+
# In particular, it's very easy for variance to overflow in float16 and
|
|
490
|
+
# for safety we also choose to cast bfloat16 to float32.
|
|
491
|
+
inputs = tf.cast(inputs, tf.float32)
|
|
492
|
+
|
|
493
|
+
# Compute the axes along which to reduce the mean / variance
|
|
494
|
+
input_shape = inputs.shape
|
|
495
|
+
ndims = len(input_shape)
|
|
496
|
+
reduction_axes = [i for i in range(ndims) if i not in self.axis]
|
|
497
|
+
|
|
498
|
+
# Broadcasting only necessary for single-axis batch norm where the axis is
|
|
499
|
+
# not the last dimension
|
|
500
|
+
broadcast_shape = [1] * ndims
|
|
501
|
+
broadcast_shape[self.axis[0]] = input_shape.dims[self.axis[0]].value
|
|
502
|
+
|
|
503
|
+
def _broadcast(v):
|
|
504
|
+
if (
|
|
505
|
+
v is not None
|
|
506
|
+
and len(v.shape) != ndims
|
|
507
|
+
and reduction_axes != list(range(ndims - 1))
|
|
508
|
+
):
|
|
509
|
+
return tf.reshape(v, broadcast_shape)
|
|
510
|
+
return v
|
|
511
|
+
|
|
512
|
+
scale, offset = _broadcast(self.gamma), _broadcast(self.beta)
|
|
513
|
+
|
|
514
|
+
# Determine a boolean value for `training`: could be True, False, or None.
|
|
515
|
+
training_value = tf.get_static_value(training)
|
|
516
|
+
if training_value == False: # pylint: disable=singleton-comparison,g-explicit-bool-comparison
|
|
517
|
+
mean, variance = self.moving_mean, self.moving_variance
|
|
518
|
+
else:
|
|
519
|
+
# Some of the computations here are not necessary when training==False
|
|
520
|
+
# but not a constant. However, this makes the code simpler.
|
|
521
|
+
keep_dims = len(self.axis) > 1
|
|
522
|
+
mean, variance = self._moments(
|
|
523
|
+
tf.cast(inputs, self._param_dtype),
|
|
524
|
+
expanded_mask,
|
|
525
|
+
reduction_axes,
|
|
526
|
+
keep_dims=keep_dims,
|
|
527
|
+
)
|
|
528
|
+
|
|
529
|
+
moving_mean = self.moving_mean
|
|
530
|
+
moving_variance = self.moving_variance
|
|
531
|
+
|
|
532
|
+
mean = tf.__internal__.smart_cond.smart_cond(
|
|
533
|
+
training, lambda: mean, lambda: tf.convert_to_tensor(moving_mean)
|
|
534
|
+
)
|
|
535
|
+
variance = tf.__internal__.smart_cond.smart_cond(
|
|
536
|
+
training,
|
|
537
|
+
lambda: variance,
|
|
538
|
+
lambda: tf.convert_to_tensor(moving_variance),
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
new_mean, new_variance = mean, variance
|
|
542
|
+
|
|
543
|
+
if self._support_zero_size_input():
|
|
544
|
+
# Keras assumes that batch dimension is the first dimension for Batch
|
|
545
|
+
# Normalization.
|
|
546
|
+
input_batch_size = tf.shape(inputs)[0]
|
|
547
|
+
else:
|
|
548
|
+
input_batch_size = None
|
|
549
|
+
|
|
550
|
+
def _do_update(var, value):
|
|
551
|
+
"""Compute the updates for mean and variance."""
|
|
552
|
+
return self._assign_moving_average(
|
|
553
|
+
var, value, self.momentum, input_batch_size
|
|
554
|
+
)
|
|
555
|
+
|
|
556
|
+
mean_update_op = [None]
|
|
557
|
+
def mean_update():
|
|
558
|
+
true_branch = lambda: _do_update(self.moving_mean, new_mean)
|
|
559
|
+
false_branch = lambda: self.moving_mean
|
|
560
|
+
mean_update = mean_update_op[0] = tf.__internal__.smart_cond.smart_cond(
|
|
561
|
+
training, true_branch, false_branch
|
|
562
|
+
)
|
|
563
|
+
return mean_update
|
|
564
|
+
|
|
565
|
+
variance_update_op = [None]
|
|
566
|
+
def variance_update():
|
|
567
|
+
"""Update the moving variance."""
|
|
568
|
+
true_branch = lambda: _do_update(self.moving_variance, new_variance)
|
|
569
|
+
false_branch = lambda: self.moving_variance
|
|
570
|
+
variance_update = variance_update_op[0] = (
|
|
571
|
+
tf.__internal__.smart_cond.smart_cond(
|
|
572
|
+
training, true_branch, false_branch
|
|
573
|
+
)
|
|
574
|
+
)
|
|
575
|
+
return variance_update
|
|
576
|
+
|
|
577
|
+
# Keras stopped populating tf1.GraphKeys.UPDATE_OPS at some point.
|
|
578
|
+
# TODO(b/287668425): Remove when we delete TF1 support.
|
|
579
|
+
self.add_update(mean_update)
|
|
580
|
+
self.add_update(variance_update)
|
|
581
|
+
if not tf1.executing_eagerly_outside_functions():
|
|
582
|
+
tf1.add_to_collection(tf1.GraphKeys.UPDATE_OPS, mean_update_op[0])
|
|
583
|
+
tf1.add_to_collection(tf1.GraphKeys.UPDATE_OPS, variance_update_op[0])
|
|
584
|
+
|
|
585
|
+
mean = tf.cast(mean, inputs.dtype)
|
|
586
|
+
variance = tf.cast(variance, inputs.dtype)
|
|
587
|
+
if offset is not None:
|
|
588
|
+
offset = tf.cast(offset, inputs.dtype)
|
|
589
|
+
if scale is not None:
|
|
590
|
+
scale = tf.cast(scale, inputs.dtype)
|
|
591
|
+
outputs = tf.nn.batch_normalization(
|
|
592
|
+
inputs,
|
|
593
|
+
_broadcast(mean),
|
|
594
|
+
_broadcast(variance),
|
|
595
|
+
offset,
|
|
596
|
+
scale,
|
|
597
|
+
self.epsilon,
|
|
598
|
+
)
|
|
599
|
+
if inputs_dtype in (tf.float16, tf.bfloat16):
|
|
600
|
+
outputs = tf.cast(outputs, inputs_dtype)
|
|
601
|
+
|
|
602
|
+
# If some components of the shape got lost due to adjustments, fix that.
|
|
603
|
+
outputs.set_shape(input_shape)
|
|
604
|
+
|
|
605
|
+
if self._mask_output:
|
|
606
|
+
outputs *= expanded_mask
|
|
607
|
+
|
|
608
|
+
return outputs
|
|
609
|
+
|
|
610
|
+
def compute_output_shape(self, input_shape):
|
|
611
|
+
return input_shape
|
|
612
|
+
|
|
613
|
+
def get_config(self):
|
|
614
|
+
config = {
|
|
615
|
+
'axis': self.axis,
|
|
616
|
+
'momentum': self.momentum,
|
|
617
|
+
'epsilon': self.epsilon,
|
|
618
|
+
'center': self.center,
|
|
619
|
+
'scale': self.scale,
|
|
620
|
+
'beta_initializer': tf.keras.initializers.serialize(
|
|
621
|
+
self.beta_initializer
|
|
622
|
+
),
|
|
623
|
+
'gamma_initializer': tf.keras.initializers.serialize(
|
|
624
|
+
self.gamma_initializer
|
|
625
|
+
),
|
|
626
|
+
'moving_mean_initializer': tf.keras.initializers.serialize(
|
|
627
|
+
self.moving_mean_initializer
|
|
628
|
+
),
|
|
629
|
+
'moving_variance_initializer': tf.keras.initializers.serialize(
|
|
630
|
+
self.moving_variance_initializer
|
|
631
|
+
),
|
|
632
|
+
'beta_regularizer': tf.keras.regularizers.serialize(
|
|
633
|
+
self.beta_regularizer
|
|
634
|
+
),
|
|
635
|
+
'gamma_regularizer': tf.keras.regularizers.serialize(
|
|
636
|
+
self.gamma_regularizer
|
|
637
|
+
),
|
|
638
|
+
'beta_constraint': tf.keras.constraints.serialize(self.beta_constraint),
|
|
639
|
+
'gamma_constraint': tf.keras.constraints.serialize(
|
|
640
|
+
self.gamma_constraint
|
|
641
|
+
),
|
|
642
|
+
'use_cross_replica_sum': self._use_cross_replica_sum,
|
|
643
|
+
'mask_output': self._mask_output,
|
|
644
|
+
}
|
|
645
|
+
base_config = super().get_config()
|
|
646
|
+
return dict(list(base_config.items()) + list(config.items()))
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
class BatchNormalization(types.PreservesShape, types.Stateless):
|
|
650
|
+
"""Applies batch normalization to the channels dimensions of input sequences.
|
|
651
|
+
|
|
652
|
+
In training mode this layer computes statistics from valid sequence timesteps
|
|
653
|
+
and uses a cross-replica sum for aggregating moments across replicas if
|
|
654
|
+
tf.distribute.get_replica_context() is non-None. Neither of these are the
|
|
655
|
+
case for tf.keras.layers.BatchNormalization, so it is not a drop-in
|
|
656
|
+
replacement.
|
|
657
|
+
|
|
658
|
+
Step-wise training is not supported, since it cannot be made identical to
|
|
659
|
+
layer-wise training (it's anti-causal, since it relies on statistics of future
|
|
660
|
+
timesteps). When not training, the calculation performed by this layer is
|
|
661
|
+
causal, since it only relies on statistics learned in training.
|
|
662
|
+
"""
|
|
663
|
+
|
|
664
|
+
def __init__(
|
|
665
|
+
self,
|
|
666
|
+
axis=-1,
|
|
667
|
+
momentum=0.99,
|
|
668
|
+
epsilon=0.001,
|
|
669
|
+
center=True,
|
|
670
|
+
scale=True,
|
|
671
|
+
beta_initializer='zeros',
|
|
672
|
+
gamma_initializer='ones',
|
|
673
|
+
moving_mean_initializer='zeros',
|
|
674
|
+
moving_variance_initializer='ones',
|
|
675
|
+
beta_regularizer=None,
|
|
676
|
+
gamma_regularizer=None,
|
|
677
|
+
beta_constraint=None,
|
|
678
|
+
gamma_constraint=None,
|
|
679
|
+
trainable=True,
|
|
680
|
+
name=None,
|
|
681
|
+
):
|
|
682
|
+
super().__init__(name=name)
|
|
683
|
+
self._layer = None
|
|
684
|
+
self._layer_kwargs = {
|
|
685
|
+
'axis': axis,
|
|
686
|
+
'momentum': momentum,
|
|
687
|
+
'epsilon': epsilon,
|
|
688
|
+
'center': center,
|
|
689
|
+
'scale': scale,
|
|
690
|
+
'beta_initializer': beta_initializer,
|
|
691
|
+
'gamma_initializer': gamma_initializer,
|
|
692
|
+
'moving_mean_initializer': moving_mean_initializer,
|
|
693
|
+
'moving_variance_initializer': moving_variance_initializer,
|
|
694
|
+
'beta_regularizer': beta_regularizer,
|
|
695
|
+
'gamma_regularizer': gamma_regularizer,
|
|
696
|
+
'beta_constraint': beta_constraint,
|
|
697
|
+
'gamma_constraint': gamma_constraint,
|
|
698
|
+
'trainable': trainable,
|
|
699
|
+
'use_cross_replica_sum': True,
|
|
700
|
+
'mask_output': True,
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
def build(self, input_shape: tf.TensorShape):
|
|
704
|
+
if self._layer is None:
|
|
705
|
+
self._layer_kwargs['axis'] = _validate_and_normalize_axes(
|
|
706
|
+
self._layer_kwargs['axis'], input_shape
|
|
707
|
+
)
|
|
708
|
+
with self.name_scope as name_scope:
|
|
709
|
+
self._layer = _SequenceBatchNormalization(
|
|
710
|
+
**self._layer_kwargs, name=name_scope
|
|
711
|
+
)
|
|
712
|
+
|
|
713
|
+
@tf.Module.with_name_scope
|
|
714
|
+
def step(
|
|
715
|
+
self,
|
|
716
|
+
x: types.Sequence,
|
|
717
|
+
state: types.State,
|
|
718
|
+
training: bool,
|
|
719
|
+
constants: types.Constants = None,
|
|
720
|
+
) -> Tuple[types.Sequence, types.State]:
|
|
721
|
+
# There are too many caveats that prevent this from being correct. Just
|
|
722
|
+
# disallow it.
|
|
723
|
+
if training:
|
|
724
|
+
raise ValueError(
|
|
725
|
+
'Step-wise training is not supported for BatchNormalization.'
|
|
726
|
+
)
|
|
727
|
+
return self.layer(x, training, initial_state=state), state
|
|
728
|
+
|
|
729
|
+
@tf.Module.with_name_scope
|
|
730
|
+
def layer(
|
|
731
|
+
self,
|
|
732
|
+
x: types.Sequence,
|
|
733
|
+
training: bool,
|
|
734
|
+
initial_state: types.State = None,
|
|
735
|
+
constants: types.Constants = None,
|
|
736
|
+
) -> types.Sequence:
|
|
737
|
+
self.build(x.values.shape)
|
|
738
|
+
# _SequenceBatchNormalization masks the output.
|
|
739
|
+
values = self._layer((x.values, x.mask), training=training)
|
|
740
|
+
return types.Sequence(values, x.mask)
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
class _SequenceInstanceNormalization(tf.keras.layers.Layer):
|
|
744
|
+
r"""A sequence-aware instance normalization layer.
|
|
745
|
+
|
|
746
|
+
Ulyanov, Veldadi and Lemitsky: https://arxiv.org/abs/1607.08022
|
|
747
|
+
|
|
748
|
+
Normalizes and scales each channel across all but the batch and axis
|
|
749
|
+
dimensions, accounting for padding of the sequence dimension.
|
|
750
|
+
|
|
751
|
+
For an input x_{ntsc}, axis={c} with lengths l_t instance normalization
|
|
752
|
+
computes:
|
|
753
|
+
|
|
754
|
+
y_{ntsc} = (x_{ntsc} - \mu_{nc}) / sqrt(\sigma_{nc}^2 + eps)
|
|
755
|
+
|
|
756
|
+
Where:
|
|
757
|
+
T = \sum_t l_t
|
|
758
|
+
\mu_{nc} = (\sum_{ts} x_{ntsc}) / (T * S)
|
|
759
|
+
\sigma_{nc}^2 = (\sum_{ts} (x_{ntsc} - \mu_{nc})^2) / (T * S)
|
|
760
|
+
|
|
761
|
+
In other words, the normalization mu and sigma are specific to each batch
|
|
762
|
+
element and channel c. To contrast with batch normalization, the normalization
|
|
763
|
+
mu and sigma would be computed across batch items in training (and at test
|
|
764
|
+
time, a moving average would be used). Since this layer is sequence-aware,
|
|
765
|
+
only valid timesteps in x contribute to \mu_{nc} and \sigma_{nc}.
|
|
766
|
+
"""
|
|
767
|
+
|
|
768
|
+
def __init__(
|
|
769
|
+
self,
|
|
770
|
+
axis: Union[int, Sequence[int]] = -1,
|
|
771
|
+
epsilon: float = 0.001,
|
|
772
|
+
center: bool = True,
|
|
773
|
+
scale: bool = True,
|
|
774
|
+
beta_initializer='zeros',
|
|
775
|
+
gamma_initializer='ones',
|
|
776
|
+
beta_regularizer=None,
|
|
777
|
+
gamma_regularizer=None,
|
|
778
|
+
beta_constraint=None,
|
|
779
|
+
gamma_constraint=None,
|
|
780
|
+
trainable: bool = True,
|
|
781
|
+
mask_output: bool = True,
|
|
782
|
+
name: Optional[str] = None,
|
|
783
|
+
):
|
|
784
|
+
super().__init__(name=name)
|
|
785
|
+
if isinstance(axis, (list, tuple)):
|
|
786
|
+
self.axis = axis[:]
|
|
787
|
+
elif isinstance(axis, int):
|
|
788
|
+
self.axis = axis
|
|
789
|
+
else:
|
|
790
|
+
raise TypeError('axis must be int or tuple/list, got: %s' % axis)
|
|
791
|
+
self.epsilon = epsilon
|
|
792
|
+
self.center = center
|
|
793
|
+
self.scale = scale
|
|
794
|
+
self.beta_initializer = tf.keras.initializers.get(beta_initializer)
|
|
795
|
+
self.gamma_initializer = tf.keras.initializers.get(gamma_initializer)
|
|
796
|
+
self.beta_regularizer = tf.keras.regularizers.get(beta_regularizer)
|
|
797
|
+
self.gamma_regularizer = tf.keras.regularizers.get(gamma_regularizer)
|
|
798
|
+
self.beta_constraint = tf.keras.constraints.get(beta_constraint)
|
|
799
|
+
self.gamma_constraint = tf.keras.constraints.get(gamma_constraint)
|
|
800
|
+
self.supports_masking = True
|
|
801
|
+
self._trainable = trainable
|
|
802
|
+
self._mask_output = mask_output
|
|
803
|
+
|
|
804
|
+
@property
|
|
805
|
+
def trainable(self):
|
|
806
|
+
return self._trainable
|
|
807
|
+
|
|
808
|
+
@property
|
|
809
|
+
def _param_dtype(self):
|
|
810
|
+
# Raise parameters of fp16 batch norm to fp32
|
|
811
|
+
if self.dtype == tf.float16 or self.dtype == tf.bfloat16:
|
|
812
|
+
return tf.float32
|
|
813
|
+
else:
|
|
814
|
+
return self.dtype or tf.float32
|
|
815
|
+
|
|
816
|
+
def _moments(self, inputs, mask, reduction_axes):
|
|
817
|
+
# This method assumes we are reducing over the time dimension of the
|
|
818
|
+
# sequence.
|
|
819
|
+
assert 0 not in reduction_axes
|
|
820
|
+
assert 1 in reduction_axes
|
|
821
|
+
|
|
822
|
+
# TODO(rryan): We should be able to assume inputs are masked.
|
|
823
|
+
sum_v = tf.reduce_sum(inputs * mask, reduction_axes, keepdims=True)
|
|
824
|
+
count_v = tf.reduce_sum(mask, reduction_axes, keepdims=True)
|
|
825
|
+
|
|
826
|
+
# Multiply counts by non-batch/time reduction dimensions.
|
|
827
|
+
if len(reduction_axes) > 1:
|
|
828
|
+
counts_multiplier = tf.gather(
|
|
829
|
+
tf.shape(inputs), [a for a in reduction_axes if a != 1]
|
|
830
|
+
)
|
|
831
|
+
count_v *= tf.cast(tf.reduce_prod(counts_multiplier), count_v.dtype)
|
|
832
|
+
|
|
833
|
+
count_v = tf.maximum(count_v, 1.0)
|
|
834
|
+
mean = sum_v / count_v
|
|
835
|
+
sum_vv = tf.reduce_sum(
|
|
836
|
+
tf.square(inputs - mean) * mask, reduction_axes, keepdims=True
|
|
837
|
+
)
|
|
838
|
+
variance = sum_vv / count_v
|
|
839
|
+
return mean, variance
|
|
840
|
+
|
|
841
|
+
def build(self, input_and_mask_shape):
|
|
842
|
+
input_shape, _ = input_and_mask_shape
|
|
843
|
+
input_shape = tf.TensorShape(input_shape)
|
|
844
|
+
|
|
845
|
+
if not input_shape.ndims:
|
|
846
|
+
raise ValueError('Input has undefined rank:', input_shape)
|
|
847
|
+
ndims = len(input_shape)
|
|
848
|
+
|
|
849
|
+
# Convert axis to list and resolve negatives
|
|
850
|
+
if isinstance(self.axis, int):
|
|
851
|
+
self.axis = [self.axis]
|
|
852
|
+
|
|
853
|
+
for idx, x in enumerate(self.axis):
|
|
854
|
+
if x < 0:
|
|
855
|
+
self.axis[idx] = ndims + x
|
|
856
|
+
|
|
857
|
+
# Validate axes
|
|
858
|
+
for x in self.axis:
|
|
859
|
+
if x < 0 or x >= ndims:
|
|
860
|
+
raise ValueError('Invalid axis: %d' % x)
|
|
861
|
+
if len(self.axis) != len(set(self.axis)):
|
|
862
|
+
raise ValueError('Duplicate axis: %s' % self.axis)
|
|
863
|
+
if 0 in self.axis or 1 in self.axis:
|
|
864
|
+
raise ValueError(
|
|
865
|
+
'This implementation assumes axis 0 is batch and 1 is '
|
|
866
|
+
'time. Computing InstanceNormalization on either of '
|
|
867
|
+
'these dimensions is not supported. Got axis=%s'
|
|
868
|
+
% self.axis
|
|
869
|
+
)
|
|
870
|
+
|
|
871
|
+
axis_to_dim = {x: input_shape.dims[x].value for x in self.axis}
|
|
872
|
+
for x in axis_to_dim:
|
|
873
|
+
if axis_to_dim[x] is None:
|
|
874
|
+
raise ValueError(
|
|
875
|
+
'Input has undefined `axis` dimension. Received input '
|
|
876
|
+
'with shape %s. Axis value: %s' % (tuple(input_shape), self.axis)
|
|
877
|
+
)
|
|
878
|
+
self.input_spec = (
|
|
879
|
+
tf.keras.layers.InputSpec(ndim=ndims, axes=axis_to_dim),
|
|
880
|
+
tf.keras.layers.InputSpec(shape=[None, None], dtype=types.MASK_DTYPE),
|
|
881
|
+
)
|
|
882
|
+
|
|
883
|
+
if len(axis_to_dim) == 1:
|
|
884
|
+
# Single axis instance norm (most common/default use-case)
|
|
885
|
+
param_shape = (list(axis_to_dim.values())[0],)
|
|
886
|
+
else:
|
|
887
|
+
# Parameter shape is the original shape but with 1 in all non-axis dims
|
|
888
|
+
param_shape = [
|
|
889
|
+
axis_to_dim[i] if i in axis_to_dim else 1 for i in range(ndims)
|
|
890
|
+
]
|
|
891
|
+
|
|
892
|
+
if self.scale:
|
|
893
|
+
self.gamma = self.add_weight(
|
|
894
|
+
name='gamma',
|
|
895
|
+
shape=param_shape,
|
|
896
|
+
dtype=self._param_dtype,
|
|
897
|
+
initializer=self.gamma_initializer,
|
|
898
|
+
regularizer=self.gamma_regularizer,
|
|
899
|
+
constraint=self.gamma_constraint,
|
|
900
|
+
trainable=self.trainable,
|
|
901
|
+
experimental_autocast=False,
|
|
902
|
+
)
|
|
903
|
+
else:
|
|
904
|
+
self.gamma = None
|
|
905
|
+
|
|
906
|
+
if self.center:
|
|
907
|
+
self.beta = self.add_weight(
|
|
908
|
+
name='beta',
|
|
909
|
+
shape=param_shape,
|
|
910
|
+
dtype=self._param_dtype,
|
|
911
|
+
initializer=self.beta_initializer,
|
|
912
|
+
regularizer=self.beta_regularizer,
|
|
913
|
+
constraint=self.beta_constraint,
|
|
914
|
+
trainable=self.trainable,
|
|
915
|
+
experimental_autocast=False,
|
|
916
|
+
)
|
|
917
|
+
else:
|
|
918
|
+
self.beta = None
|
|
919
|
+
self.built = True
|
|
920
|
+
|
|
921
|
+
def call(self, inputs_and_mask):
|
|
922
|
+
inputs, mask = inputs_and_mask
|
|
923
|
+
expanded_mask = types.Sequence(inputs, mask).expanded_mask()
|
|
924
|
+
|
|
925
|
+
inputs_dtype = inputs.dtype.base_dtype
|
|
926
|
+
if inputs_dtype in (tf.float16, tf.bfloat16):
|
|
927
|
+
# Do all math in float32 if given 16-bit inputs for numeric stability.
|
|
928
|
+
# In particular, it's very easy for variance to overflow in float16 and
|
|
929
|
+
# for safety we also choose to cast bfloat16 to float32.
|
|
930
|
+
inputs = tf.cast(inputs, tf.float32)
|
|
931
|
+
|
|
932
|
+
# Compute the axes along which to reduce the mean / variance
|
|
933
|
+
input_shape = inputs.shape
|
|
934
|
+
ndims = len(input_shape)
|
|
935
|
+
# Don't reduce over batch or axis dimensions.
|
|
936
|
+
reduction_axes = [i for i in range(1, ndims) if i not in self.axis]
|
|
937
|
+
|
|
938
|
+
# Broadcasting only necessary for single-axis instance norm where the axis
|
|
939
|
+
# is not the last dimension
|
|
940
|
+
broadcast_shape = [1] * ndims
|
|
941
|
+
broadcast_shape[self.axis[0]] = input_shape.dims[self.axis[0]].value
|
|
942
|
+
|
|
943
|
+
def _broadcast(v):
|
|
944
|
+
if (
|
|
945
|
+
v is not None
|
|
946
|
+
and len(v.shape) != ndims
|
|
947
|
+
and reduction_axes != list(range(ndims - 1))
|
|
948
|
+
):
|
|
949
|
+
return tf.reshape(v, broadcast_shape)
|
|
950
|
+
return v
|
|
951
|
+
|
|
952
|
+
scale, offset = _broadcast(self.gamma), _broadcast(self.beta)
|
|
953
|
+
|
|
954
|
+
mean, variance = self._moments(
|
|
955
|
+
tf.cast(inputs, self._param_dtype), expanded_mask, reduction_axes
|
|
956
|
+
)
|
|
957
|
+
|
|
958
|
+
mean = tf.cast(mean, inputs.dtype)
|
|
959
|
+
variance = tf.cast(variance, inputs.dtype)
|
|
960
|
+
if offset is not None:
|
|
961
|
+
offset = tf.cast(offset, inputs.dtype)
|
|
962
|
+
if scale is not None:
|
|
963
|
+
scale = tf.cast(scale, inputs.dtype)
|
|
964
|
+
outputs = tf.nn.batch_normalization(
|
|
965
|
+
inputs,
|
|
966
|
+
_broadcast(mean),
|
|
967
|
+
_broadcast(variance),
|
|
968
|
+
offset,
|
|
969
|
+
scale,
|
|
970
|
+
self.epsilon,
|
|
971
|
+
)
|
|
972
|
+
if inputs_dtype in (tf.float16, tf.bfloat16):
|
|
973
|
+
outputs = tf.cast(outputs, inputs_dtype)
|
|
974
|
+
|
|
975
|
+
# If some components of the shape got lost due to adjustments, fix that.
|
|
976
|
+
outputs.set_shape(input_shape)
|
|
977
|
+
|
|
978
|
+
if self._mask_output:
|
|
979
|
+
outputs *= expanded_mask
|
|
980
|
+
|
|
981
|
+
return outputs
|
|
982
|
+
|
|
983
|
+
def compute_output_shape(self, input_shape):
|
|
984
|
+
return input_shape
|
|
985
|
+
|
|
986
|
+
def get_config(self):
|
|
987
|
+
config = {
|
|
988
|
+
'axis': self.axis,
|
|
989
|
+
'epsilon': self.epsilon,
|
|
990
|
+
'center': self.center,
|
|
991
|
+
'scale': self.scale,
|
|
992
|
+
'beta_initializer': tf.keras.initializers.serialize(
|
|
993
|
+
self.beta_initializer
|
|
994
|
+
),
|
|
995
|
+
'gamma_initializer': tf.keras.initializers.serialize(
|
|
996
|
+
self.gamma_initializer
|
|
997
|
+
),
|
|
998
|
+
'beta_regularizer': tf.keras.regularizers.serialize(
|
|
999
|
+
self.beta_regularizer
|
|
1000
|
+
),
|
|
1001
|
+
'gamma_regularizer': tf.keras.regularizers.serialize(
|
|
1002
|
+
self.gamma_regularizer
|
|
1003
|
+
),
|
|
1004
|
+
'beta_constraint': tf.keras.constraints.serialize(self.beta_constraint),
|
|
1005
|
+
'gamma_constraint': tf.keras.constraints.serialize(
|
|
1006
|
+
self.gamma_constraint
|
|
1007
|
+
),
|
|
1008
|
+
'mask_output': self._mask_output,
|
|
1009
|
+
}
|
|
1010
|
+
base_config = super().get_config()
|
|
1011
|
+
return dict(list(base_config.items()) + list(config.items()))
|
|
1012
|
+
|
|
1013
|
+
|
|
1014
|
+
class InstanceNormalization(types.PreservesShape, types.Stateless):
|
|
1015
|
+
r"""Applies instance normalization to the specified dimensions of inputs.
|
|
1016
|
+
|
|
1017
|
+
Ulyanov, Veldadi and Lemitsky: https://arxiv.org/abs/1607.08022
|
|
1018
|
+
|
|
1019
|
+
Normalizes and scales each channel across all but the batch and axis
|
|
1020
|
+
dimensions, accounting for padding of the sequence dimension.
|
|
1021
|
+
|
|
1022
|
+
For an input x_{ntsc}, axis={c} with lengths l_t instance normalization
|
|
1023
|
+
computes:
|
|
1024
|
+
|
|
1025
|
+
y_{ntsc} = (x_{ntsc} - \mu_{nc}) / sqrt(\sigma_{nc}^2 + eps)
|
|
1026
|
+
|
|
1027
|
+
Where:
|
|
1028
|
+
T = \sum_t l_t
|
|
1029
|
+
\mu_{nc} = (\sum_{ts} x_{ntsc}) / (T * S)
|
|
1030
|
+
\sigma_{nc}^2 = (\sum_{ts} (x_{ntsc} - \mu_{nc})^2) / (T * S)
|
|
1031
|
+
|
|
1032
|
+
In other words, the normalization mu and sigma are specific to each batch
|
|
1033
|
+
element and channel c. To contrast with batch normalization, the normalization
|
|
1034
|
+
mu and sigma would be computed across batch items in training (and at test
|
|
1035
|
+
time, a moving average would be used). Since this layer is sequence-aware,
|
|
1036
|
+
only valid timesteps in x contribute to \mu_{nc} and \sigma_{nc}.
|
|
1037
|
+
"""
|
|
1038
|
+
|
|
1039
|
+
def __init__(
|
|
1040
|
+
self,
|
|
1041
|
+
axis: Union[int, Sequence[int]] = -1,
|
|
1042
|
+
epsilon: float = 0.001,
|
|
1043
|
+
center: bool = True,
|
|
1044
|
+
scale: bool = True,
|
|
1045
|
+
beta_initializer='zeros',
|
|
1046
|
+
gamma_initializer='ones',
|
|
1047
|
+
beta_regularizer=None,
|
|
1048
|
+
gamma_regularizer=None,
|
|
1049
|
+
beta_constraint=None,
|
|
1050
|
+
gamma_constraint=None,
|
|
1051
|
+
trainable: bool = True,
|
|
1052
|
+
name: Optional[str] = None,
|
|
1053
|
+
):
|
|
1054
|
+
super().__init__(name=name)
|
|
1055
|
+
self._layer = None
|
|
1056
|
+
self._layer_kwargs = {
|
|
1057
|
+
'axis': axis,
|
|
1058
|
+
'epsilon': epsilon,
|
|
1059
|
+
'center': center,
|
|
1060
|
+
'scale': scale,
|
|
1061
|
+
'beta_initializer': beta_initializer,
|
|
1062
|
+
'gamma_initializer': gamma_initializer,
|
|
1063
|
+
'beta_regularizer': beta_regularizer,
|
|
1064
|
+
'gamma_regularizer': gamma_regularizer,
|
|
1065
|
+
'beta_constraint': beta_constraint,
|
|
1066
|
+
'gamma_constraint': gamma_constraint,
|
|
1067
|
+
'trainable': trainable,
|
|
1068
|
+
'mask_output': True,
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
def build(self, input_shape: tf.TensorShape):
|
|
1072
|
+
if self._layer is None:
|
|
1073
|
+
self._layer_kwargs['axis'] = _validate_and_normalize_axes(
|
|
1074
|
+
self._layer_kwargs['axis'], input_shape
|
|
1075
|
+
)
|
|
1076
|
+
with self.name_scope as name_scope:
|
|
1077
|
+
self._layer = _SequenceInstanceNormalization(
|
|
1078
|
+
**self._layer_kwargs, name=name_scope
|
|
1079
|
+
)
|
|
1080
|
+
|
|
1081
|
+
@property
|
|
1082
|
+
def supports_step(self) -> bool:
|
|
1083
|
+
return False
|
|
1084
|
+
|
|
1085
|
+
@tf.Module.with_name_scope
|
|
1086
|
+
def step(
|
|
1087
|
+
self,
|
|
1088
|
+
x: types.Sequence,
|
|
1089
|
+
state: types.State,
|
|
1090
|
+
training: bool,
|
|
1091
|
+
constants: types.Constants = None,
|
|
1092
|
+
) -> Tuple[types.Sequence, types.State]:
|
|
1093
|
+
raise ValueError(
|
|
1094
|
+
'Step-wise processing is not supported for InstanceNormalization.'
|
|
1095
|
+
)
|
|
1096
|
+
|
|
1097
|
+
@tf.Module.with_name_scope
|
|
1098
|
+
def layer(
|
|
1099
|
+
self,
|
|
1100
|
+
x: types.Sequence,
|
|
1101
|
+
training: bool,
|
|
1102
|
+
initial_state: types.State = None,
|
|
1103
|
+
constants: types.Constants = None,
|
|
1104
|
+
) -> types.Sequence:
|
|
1105
|
+
self.build(x.values.shape)
|
|
1106
|
+
# _SequenceInstanceNormalization masks the output.
|
|
1107
|
+
values = self._layer((x.values, x.mask), training=training)
|
|
1108
|
+
return types.Sequence(values, x.mask)
|
|
1109
|
+
|
|
1110
|
+
|
|
1111
|
+
class L2Normalize(types.PreservesShape, types.Stateless):
|
|
1112
|
+
"""L2 Normalize."""
|
|
1113
|
+
|
|
1114
|
+
def __init__(self, axis: Union[int, List[int]], name: Optional[str] = None):
|
|
1115
|
+
super().__init__(name=name)
|
|
1116
|
+
self._axis = axis
|
|
1117
|
+
|
|
1118
|
+
@tf.Module.with_name_scope
|
|
1119
|
+
def layer(
|
|
1120
|
+
self,
|
|
1121
|
+
x: types.Sequence,
|
|
1122
|
+
training: bool,
|
|
1123
|
+
initial_state: Optional[types.State] = None,
|
|
1124
|
+
constants: Optional[types.Constants] = None,
|
|
1125
|
+
) -> types.Sequence:
|
|
1126
|
+
_validate_and_normalize_axes(self._axis, x.values.shape)
|
|
1127
|
+
return x.apply_values(lambda v: tf.nn.l2_normalize(v, axis=self._axis))
|