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,889 @@
|
|
|
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
|
+
"""Normalization layers."""
|
|
15
|
+
|
|
16
|
+
import dataclasses
|
|
17
|
+
from typing import Callable
|
|
18
|
+
|
|
19
|
+
import flax.linen as nn
|
|
20
|
+
import jax
|
|
21
|
+
import jax.numpy as jnp
|
|
22
|
+
import numpy as np
|
|
23
|
+
from sequence_layers.jax import meta
|
|
24
|
+
from sequence_layers.jax import types
|
|
25
|
+
from sequence_layers.jax import typing as jt
|
|
26
|
+
from sequence_layers.jax import utils
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
__all__ = (
|
|
30
|
+
# go/keep-sorted start
|
|
31
|
+
'BatchNormalization',
|
|
32
|
+
'GroupNormalization',
|
|
33
|
+
'LayerNormalization',
|
|
34
|
+
'RMSNormalization',
|
|
35
|
+
# go/keep-sorted end
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _guard_against_excess_precision(x: jax.Array) -> jax.Array:
|
|
40
|
+
"""Guards against "excess precision" introduced by XLA fusions."""
|
|
41
|
+
finfo = jnp.finfo(x.dtype) # jnp important!
|
|
42
|
+
return jax.lax.reduce_precision(x, finfo.nexp, finfo.nmant)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _validate_and_normalize_axes(
|
|
46
|
+
axes: int | list[int] | tuple[int, ...],
|
|
47
|
+
input_shape: types.Shape,
|
|
48
|
+
) -> tuple[int, ...]:
|
|
49
|
+
"""Normalizes user-provided axes and checks batch/time are not specified."""
|
|
50
|
+
# If axis is left unspecified, normalize all dimensions.
|
|
51
|
+
if isinstance(axes, int):
|
|
52
|
+
axes = (axes,)
|
|
53
|
+
else:
|
|
54
|
+
normalized_axes = set()
|
|
55
|
+
for axis in axes:
|
|
56
|
+
if axis < 0:
|
|
57
|
+
axis += len(input_shape)
|
|
58
|
+
if axis < 0 or axis > len(input_shape) - 1:
|
|
59
|
+
raise ValueError(
|
|
60
|
+
f'Axis out of range {axis=} for {axes=} with {input_shape=}.'
|
|
61
|
+
)
|
|
62
|
+
normalized_axes.add(axis)
|
|
63
|
+
axes = tuple(sorted(normalized_axes))
|
|
64
|
+
for axis in axes:
|
|
65
|
+
if axis in (0, 1):
|
|
66
|
+
raise ValueError(
|
|
67
|
+
'Normalizing over the batch or time dimension is '
|
|
68
|
+
f'not allowed. Got: {axes}'
|
|
69
|
+
)
|
|
70
|
+
return axes
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _zero_gradient_helper(
|
|
74
|
+
forward_fn: Callable[..., tuple[jt.AnyPyTree, jt.AnyPyTree]],
|
|
75
|
+
*args: jt.AnyPyTree,
|
|
76
|
+
) -> jt.AnyPyTree:
|
|
77
|
+
"""Wrap forward_fn's gradient with safety checks that zero gradient.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
forward_fn: The function to be wrapped with a custom gradient. The function
|
|
81
|
+
returns a two-tuple of PyTrees (output, should_zero_gradient), where
|
|
82
|
+
should_zero_gradient is a PyTree matching the structure of the *args
|
|
83
|
+
array, indicating whether the pointwise gradient flowing to that argument
|
|
84
|
+
should be zeroed.
|
|
85
|
+
*args: The arguments to pass to forward_fn.
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
Returns the first tuple element in the two-tuple return value of
|
|
89
|
+
forward_fn(*args).
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
@jax.custom_gradient
|
|
93
|
+
def forward_fn_custom_gradient(*args):
|
|
94
|
+
values, vjp_fn, should_zero_gradients = jax.vjp(
|
|
95
|
+
forward_fn, *args, has_aux=True
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
def custom_gradient(input_gradients: jt.AnyPyTree) -> jt.AnyPyTree:
|
|
99
|
+
grads = vjp_fn(input_gradients)
|
|
100
|
+
|
|
101
|
+
def maybe_zero_gradient(
|
|
102
|
+
grad: jax.Array | types.Sequence, should_zero_gradient: jax.Array
|
|
103
|
+
):
|
|
104
|
+
jnp.broadcast_shapes(grad.shape, should_zero_gradient.shape)
|
|
105
|
+
if should_zero_gradient.ndim != grad.ndim:
|
|
106
|
+
raise ValueError(
|
|
107
|
+
f'Expected {should_zero_gradient.shape=} to be the same size is'
|
|
108
|
+
f' {grad.shape=}.'
|
|
109
|
+
)
|
|
110
|
+
if isinstance(grad, types.Sequence):
|
|
111
|
+
grad = grad.apply_values_masked(
|
|
112
|
+
lambda g: jnp.where(should_zero_gradient, jnp.zeros_like(g), g)
|
|
113
|
+
)
|
|
114
|
+
else:
|
|
115
|
+
grad = jnp.where(should_zero_gradient, jnp.zeros_like(grad), grad)
|
|
116
|
+
return grad
|
|
117
|
+
|
|
118
|
+
return jax.tree.map(
|
|
119
|
+
maybe_zero_gradient,
|
|
120
|
+
grads,
|
|
121
|
+
should_zero_gradients,
|
|
122
|
+
is_leaf=lambda x: isinstance(x, types.Sequence),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
return values, custom_gradient
|
|
126
|
+
|
|
127
|
+
return forward_fn_custom_gradient(*args)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class LayerNormalization(types.PreservesType, types.StatelessPointwise):
|
|
131
|
+
"""Applies layer normalization to input sequences."""
|
|
132
|
+
|
|
133
|
+
@dataclasses.dataclass(frozen=True)
|
|
134
|
+
class Config(types.SequenceLayerConfig):
|
|
135
|
+
"""Config for LayerNormalization."""
|
|
136
|
+
|
|
137
|
+
axis: int | types.ShapeLike = -1
|
|
138
|
+
epsilon: float = 1e-6
|
|
139
|
+
use_bias: bool = True
|
|
140
|
+
use_scale: bool = True
|
|
141
|
+
bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
|
|
142
|
+
scale_init: nn.initializers.Initializer = nn.initializers.ones_init()
|
|
143
|
+
sharding: types.Sharding | None = None
|
|
144
|
+
reductions_in_at_least_fp32: bool = True
|
|
145
|
+
param_dtype: types.DType = jnp.float32
|
|
146
|
+
# If true, guards against "excess precision" introduced by XLA fusions in
|
|
147
|
+
# the backward pass. Equivalent to --noxla_allow_excess_precision but only
|
|
148
|
+
# for the input to this layer.
|
|
149
|
+
guard_against_excess_precision: bool = False
|
|
150
|
+
name: str | None = None
|
|
151
|
+
|
|
152
|
+
def __post_init__(self):
|
|
153
|
+
# Use hashable types for sequences.
|
|
154
|
+
if not isinstance(self.axis, int):
|
|
155
|
+
object.__setattr__(self, 'axis', tuple(self.axis))
|
|
156
|
+
|
|
157
|
+
def make(self) -> 'LayerNormalization':
|
|
158
|
+
return LayerNormalization(self, name=self.name)
|
|
159
|
+
|
|
160
|
+
config: Config
|
|
161
|
+
|
|
162
|
+
@nn.compact
|
|
163
|
+
@types.check_layer
|
|
164
|
+
def layer(
|
|
165
|
+
self,
|
|
166
|
+
x: types.Sequence,
|
|
167
|
+
*,
|
|
168
|
+
training: bool,
|
|
169
|
+
constants: types.Constants | None = None,
|
|
170
|
+
) -> types.Sequence:
|
|
171
|
+
reduction_axes = _validate_and_normalize_axes(self.config.axis, x.shape)
|
|
172
|
+
|
|
173
|
+
if self.config.guard_against_excess_precision:
|
|
174
|
+
x = x.apply_values_masked(_guard_against_excess_precision)
|
|
175
|
+
|
|
176
|
+
feature_shape = [1] * x.ndim
|
|
177
|
+
reduced_feature_shape = []
|
|
178
|
+
for ax in reduction_axes:
|
|
179
|
+
feature_shape[ax] = x.shape[ax]
|
|
180
|
+
reduced_feature_shape.append(x.shape[ax])
|
|
181
|
+
|
|
182
|
+
@utils.maybe_in_at_least_fp32(self.config.reductions_in_at_least_fp32)
|
|
183
|
+
def reductions(values: jax.Array) -> jax.Array:
|
|
184
|
+
|
|
185
|
+
def forward_fn(values: jax.Array) -> tuple[jt.AnyPyTree, jt.AnyPyTree]:
|
|
186
|
+
# Since layer normalization does not operate over batch and time, we can
|
|
187
|
+
# skip masking the moment calculation.
|
|
188
|
+
mean = jnp.mean(values, axis=reduction_axes, keepdims=True)
|
|
189
|
+
variance = jnp.mean(
|
|
190
|
+
jnp.square(values - mean), axis=reduction_axes, keepdims=True
|
|
191
|
+
)
|
|
192
|
+
# TODO(rryan): Evaluate the flax approach of applying scale before
|
|
193
|
+
# broadcasting.
|
|
194
|
+
normed = (values - mean) * jax.lax.rsqrt(variance + self.config.epsilon)
|
|
195
|
+
|
|
196
|
+
# Guard against blowup from all-zero inputs.
|
|
197
|
+
should_zero_gradient = variance == 0
|
|
198
|
+
|
|
199
|
+
return normed, (should_zero_gradient,)
|
|
200
|
+
|
|
201
|
+
return _zero_gradient_helper(forward_fn, values)
|
|
202
|
+
|
|
203
|
+
y = reductions(x.values)
|
|
204
|
+
|
|
205
|
+
# Apply scale and bias.
|
|
206
|
+
if self.config.use_scale:
|
|
207
|
+
scale_init = utils.shard_initializer(
|
|
208
|
+
self.config.scale_init,
|
|
209
|
+
self.config.sharding,
|
|
210
|
+
labels=[meta.IS_NORMALIZER],
|
|
211
|
+
)
|
|
212
|
+
scale = self.param(
|
|
213
|
+
'scale',
|
|
214
|
+
scale_init,
|
|
215
|
+
reduced_feature_shape,
|
|
216
|
+
self.config.param_dtype,
|
|
217
|
+
).astype(y.dtype)
|
|
218
|
+
y *= jnp.reshape(scale, feature_shape)
|
|
219
|
+
|
|
220
|
+
if self.config.use_bias:
|
|
221
|
+
bias_init = utils.shard_initializer(
|
|
222
|
+
self.config.bias_init, self.config.sharding
|
|
223
|
+
)
|
|
224
|
+
y += jnp.reshape(
|
|
225
|
+
self.param(
|
|
226
|
+
'bias',
|
|
227
|
+
bias_init,
|
|
228
|
+
reduced_feature_shape,
|
|
229
|
+
self.config.param_dtype,
|
|
230
|
+
).astype(y.dtype),
|
|
231
|
+
feature_shape,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
# Normalization leaves padded regions unmasked.
|
|
235
|
+
return types.Sequence(y, x.mask)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
class RMSNormalization(types.PreservesType, types.StatelessPointwise):
|
|
239
|
+
"""A simplified version of LayerNormalization used in T5.
|
|
240
|
+
|
|
241
|
+
No mean statistics or offset terms are included.
|
|
242
|
+
|
|
243
|
+
Implementation follows:
|
|
244
|
+
google3/third_party/tensorflow_models/official/nlp/modeling/models/t5.py
|
|
245
|
+
|
|
246
|
+
As in flax.linen.RMSNorm, reductions are performed in at least float32 unless
|
|
247
|
+
reductions_in_at_least_fp32=False. This is a difference with respect to many
|
|
248
|
+
common RMSNorm implementations (e.g. Praxis). If interoperability is required,
|
|
249
|
+
consider turning this off.
|
|
250
|
+
"""
|
|
251
|
+
|
|
252
|
+
@dataclasses.dataclass(frozen=True)
|
|
253
|
+
class Config(types.SequenceLayerConfig):
|
|
254
|
+
"""Config for RMSNormalization."""
|
|
255
|
+
|
|
256
|
+
axis: int | types.ShapeLike = -1
|
|
257
|
+
epsilon: float = 1e-6
|
|
258
|
+
use_scale: bool = True
|
|
259
|
+
scale_init: nn.initializers.Initializer = nn.initializers.ones_init()
|
|
260
|
+
sharding: types.Sharding | None = None
|
|
261
|
+
reductions_in_at_least_fp32: bool = True
|
|
262
|
+
param_dtype: types.DType = jnp.float32
|
|
263
|
+
# If true, guards against "excess precision" introduced by XLA fusions in
|
|
264
|
+
# the backward pass. Equivalent to --noxla_allow_excess_precision but only
|
|
265
|
+
# for the input to this layer.
|
|
266
|
+
guard_against_excess_precision: bool = False
|
|
267
|
+
name: str | None = None
|
|
268
|
+
|
|
269
|
+
def __post_init__(self):
|
|
270
|
+
# Use hashable types for sequences.
|
|
271
|
+
if not isinstance(self.axis, int):
|
|
272
|
+
object.__setattr__(self, 'axis', tuple(self.axis))
|
|
273
|
+
|
|
274
|
+
def make(self) -> 'RMSNormalization':
|
|
275
|
+
return RMSNormalization(self, name=self.name)
|
|
276
|
+
|
|
277
|
+
config: Config
|
|
278
|
+
|
|
279
|
+
@nn.compact
|
|
280
|
+
@types.check_layer
|
|
281
|
+
def layer(
|
|
282
|
+
self,
|
|
283
|
+
x: types.Sequence,
|
|
284
|
+
*,
|
|
285
|
+
training: bool,
|
|
286
|
+
constants: types.Constants | None = None,
|
|
287
|
+
) -> types.Sequence:
|
|
288
|
+
reduction_axes = _validate_and_normalize_axes(
|
|
289
|
+
self.config.axis, x.values.shape
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
feature_shape = [1] * x.values.ndim
|
|
293
|
+
reduced_feature_shape = []
|
|
294
|
+
for ax in reduction_axes:
|
|
295
|
+
feature_shape[ax] = x.values.shape[ax]
|
|
296
|
+
reduced_feature_shape.append(x.values.shape[ax])
|
|
297
|
+
|
|
298
|
+
if self.config.guard_against_excess_precision:
|
|
299
|
+
x = x.apply_values_masked(_guard_against_excess_precision)
|
|
300
|
+
|
|
301
|
+
@utils.maybe_in_at_least_fp32(self.config.reductions_in_at_least_fp32)
|
|
302
|
+
def reductions(values: jax.Array) -> jax.Array:
|
|
303
|
+
|
|
304
|
+
def forward_fn(values: jax.Array) -> tuple[jt.AnyPyTree, jt.AnyPyTree]:
|
|
305
|
+
# Since RMS normalization does not operate over batch and time, we can
|
|
306
|
+
# skip masking the moment calculation.
|
|
307
|
+
mean_square = jnp.mean(
|
|
308
|
+
jnp.square(values), axis=reduction_axes, keepdims=True
|
|
309
|
+
)
|
|
310
|
+
# TODO(rryan): Evaluate the flax approach of applying scale before
|
|
311
|
+
# broadcasting.
|
|
312
|
+
normed = values * jax.lax.rsqrt(mean_square + self.config.epsilon)
|
|
313
|
+
|
|
314
|
+
# Guard against blowup from all-zero inputs.
|
|
315
|
+
should_zero_gradient = mean_square == 0
|
|
316
|
+
|
|
317
|
+
return normed, (should_zero_gradient,)
|
|
318
|
+
|
|
319
|
+
return _zero_gradient_helper(forward_fn, values)
|
|
320
|
+
|
|
321
|
+
y = reductions(x.values)
|
|
322
|
+
|
|
323
|
+
# Apply scale and bias.
|
|
324
|
+
if self.config.use_scale:
|
|
325
|
+
scale_init = utils.shard_initializer(
|
|
326
|
+
self.config.scale_init,
|
|
327
|
+
self.config.sharding,
|
|
328
|
+
labels=[meta.IS_NORMALIZER],
|
|
329
|
+
)
|
|
330
|
+
y *= jnp.reshape(
|
|
331
|
+
self.param(
|
|
332
|
+
'scale',
|
|
333
|
+
scale_init,
|
|
334
|
+
reduced_feature_shape,
|
|
335
|
+
self.config.param_dtype,
|
|
336
|
+
).astype(y.dtype),
|
|
337
|
+
feature_shape,
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
# Normalization leaves padded regions unmasked.
|
|
341
|
+
return types.Sequence(y, x.mask)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
class BatchNormalization(types.PreservesType, types.StatelessPointwise):
|
|
345
|
+
"""Applies batch normalization to the channels dimensions of input sequences.
|
|
346
|
+
|
|
347
|
+
In training mode this layer computes statistics from valid sequence timesteps
|
|
348
|
+
and uses a cross-replica sum when running under pmap.
|
|
349
|
+
|
|
350
|
+
Step-wise training is not supported, since it cannot be made identical to
|
|
351
|
+
layer-wise training (it's not causal, since it relies on statistics of future
|
|
352
|
+
timesteps). When not training, the calculation performed by this layer is
|
|
353
|
+
causal, since it only relies on statistics learned in training.
|
|
354
|
+
"""
|
|
355
|
+
|
|
356
|
+
@dataclasses.dataclass(frozen=True)
|
|
357
|
+
class Config(types.SequenceLayerConfig):
|
|
358
|
+
"""Batch normalization config."""
|
|
359
|
+
|
|
360
|
+
axis: int = -1
|
|
361
|
+
momentum: float = 0.99
|
|
362
|
+
epsilon: float = 0.001
|
|
363
|
+
use_bias: bool = True
|
|
364
|
+
use_scale: bool = True
|
|
365
|
+
bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
|
|
366
|
+
scale_init: nn.initializers.Initializer = nn.initializers.ones_init()
|
|
367
|
+
sharding: types.Sharding | None = None
|
|
368
|
+
use_fast_variance: bool = True
|
|
369
|
+
param_dtype: types.DType = jnp.float32
|
|
370
|
+
# If true, guards against "excess precision" introduced by XLA fusions in
|
|
371
|
+
# the backward pass. Equivalent to --noxla_allow_excess_precision but only
|
|
372
|
+
# for the input to this layer.
|
|
373
|
+
guard_against_excess_precision: bool = False
|
|
374
|
+
name: str | None = None
|
|
375
|
+
|
|
376
|
+
def make(self) -> 'BatchNormalization':
|
|
377
|
+
return BatchNormalization(self, name=self.name)
|
|
378
|
+
|
|
379
|
+
config: Config
|
|
380
|
+
|
|
381
|
+
@types.check_step
|
|
382
|
+
def step(
|
|
383
|
+
self,
|
|
384
|
+
x: types.Sequence,
|
|
385
|
+
state: types.State,
|
|
386
|
+
*,
|
|
387
|
+
training: bool,
|
|
388
|
+
constants: types.Constants | None = None,
|
|
389
|
+
) -> tuple[types.Sequence, types.State]:
|
|
390
|
+
# There are too many caveats that prevent this from being correct. Just
|
|
391
|
+
# disallow it.
|
|
392
|
+
if training:
|
|
393
|
+
raise ValueError(
|
|
394
|
+
'Step-wise training is not supported for BatchNormalization.'
|
|
395
|
+
)
|
|
396
|
+
return self.layer(x, training=training, constants=constants), state
|
|
397
|
+
|
|
398
|
+
@nn.compact
|
|
399
|
+
@types.check_layer
|
|
400
|
+
def layer(
|
|
401
|
+
self,
|
|
402
|
+
x: types.Sequence,
|
|
403
|
+
*,
|
|
404
|
+
training: bool,
|
|
405
|
+
constants: types.Constants | None = None,
|
|
406
|
+
) -> types.Sequence:
|
|
407
|
+
(axis,) = _validate_and_normalize_axes([self.config.axis], x.shape)
|
|
408
|
+
|
|
409
|
+
scale_init = utils.shard_initializer(
|
|
410
|
+
self.config.scale_init,
|
|
411
|
+
self.config.sharding,
|
|
412
|
+
labels=[meta.IS_NORMALIZER],
|
|
413
|
+
)
|
|
414
|
+
bias_init = utils.shard_initializer(
|
|
415
|
+
self.config.bias_init, self.config.sharding
|
|
416
|
+
)
|
|
417
|
+
|
|
418
|
+
if self.config.guard_against_excess_precision:
|
|
419
|
+
x = x.apply_values_masked(_guard_against_excess_precision)
|
|
420
|
+
|
|
421
|
+
bn = nn.BatchNorm(
|
|
422
|
+
use_running_average=None,
|
|
423
|
+
axis=axis,
|
|
424
|
+
momentum=self.config.momentum,
|
|
425
|
+
epsilon=self.config.epsilon,
|
|
426
|
+
dtype=x.dtype,
|
|
427
|
+
param_dtype=self.config.param_dtype,
|
|
428
|
+
use_bias=self.config.use_bias,
|
|
429
|
+
use_scale=self.config.use_scale,
|
|
430
|
+
bias_init=bias_init,
|
|
431
|
+
scale_init=scale_init,
|
|
432
|
+
use_fast_variance=self.config.use_fast_variance,
|
|
433
|
+
name=self.config.name,
|
|
434
|
+
)
|
|
435
|
+
y = bn(x.values, use_running_average=not training, mask=x.expanded_mask())
|
|
436
|
+
# Normalization leaves padded regions unmasked.
|
|
437
|
+
return types.Sequence(y, x.mask)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _cumulative_masked_moments_streaming(
|
|
441
|
+
inputs: types.Sequence,
|
|
442
|
+
reduction_axes: list[int],
|
|
443
|
+
cumulative_axis: int,
|
|
444
|
+
accum_sum_v: jax.Array,
|
|
445
|
+
accum_count_v: jax.Array,
|
|
446
|
+
accum_sum_vv: jax.Array,
|
|
447
|
+
) -> tuple[jax.Array, jax.Array, jax.Array, jax.Array, jax.Array]:
|
|
448
|
+
"""Compute the moments of inputs/input_lengths over reduction_axes.
|
|
449
|
+
|
|
450
|
+
This implementation follows Babelfish's in:
|
|
451
|
+
google3/third_party/py/lingvo/core/bn_layers.py
|
|
452
|
+
|
|
453
|
+
Args:
|
|
454
|
+
inputs: A [batch_size, time, ...] sequence.
|
|
455
|
+
reduction_axes: The axes to reduce over for computing the moments.
|
|
456
|
+
cumulative_axis: If non-None, accumulates moments along this axis. Must not
|
|
457
|
+
be an axis in reduction_axes.
|
|
458
|
+
accum_sum_v: Streaming accumulator for sum_v.
|
|
459
|
+
accum_count_v: Streaming accumulator for count_v.
|
|
460
|
+
accum_sum_vv: Streaming accumulator for sum_vv.
|
|
461
|
+
|
|
462
|
+
Returns:
|
|
463
|
+
means: The means of inputs along the axes indicated in
|
|
464
|
+
reduction_axes. For example, if the input is [a, b, c, d] and
|
|
465
|
+
reduction_axes is [0, 1, 3], means's shape is [1, 1, c, 1].
|
|
466
|
+
variances: The variance of inputs along the axes indicated in
|
|
467
|
+
reduction_axes. For example, if the input is [a, b, c, d] and
|
|
468
|
+
reduction_axes is [0, 1, 3], variance's shape is [1, 1, c, 1].
|
|
469
|
+
accum_sum_v: Streaming accumulator for sum_v.
|
|
470
|
+
accum_count_v: Streaming accumulator for count_v.
|
|
471
|
+
accum_sum_vv: Streaming accumulator for sum_vv.
|
|
472
|
+
"""
|
|
473
|
+
# Mask input if it isn't already.
|
|
474
|
+
inputs = inputs.mask_invalid()
|
|
475
|
+
mask = inputs.expanded_mask()
|
|
476
|
+
assert accum_sum_v.shape[cumulative_axis] == 1
|
|
477
|
+
assert accum_count_v.shape[cumulative_axis] == 1
|
|
478
|
+
assert accum_sum_vv.shape[cumulative_axis] == 1
|
|
479
|
+
sum_v = jnp.sum(inputs.values, reduction_axes, keepdims=True)
|
|
480
|
+
count_v = jnp.sum(mask, reduction_axes, keepdims=True)
|
|
481
|
+
|
|
482
|
+
# Multiply counts by non-batch/time reduction dimensions. This is more
|
|
483
|
+
# efficient than broadcast the count_v sum above to the shape of inputs.
|
|
484
|
+
non_batch_time_axes = [a for a in reduction_axes if a not in (0, 1)]
|
|
485
|
+
if non_batch_time_axes:
|
|
486
|
+
counts_multiplier = np.prod(
|
|
487
|
+
[inputs.shape[ax] for ax in non_batch_time_axes]
|
|
488
|
+
)
|
|
489
|
+
count_v *= jnp.array(counts_multiplier, dtype=count_v.dtype)
|
|
490
|
+
|
|
491
|
+
# Broadcast add the accumulators to the cumsum of the input timesteps.
|
|
492
|
+
sum_v = accum_sum_v + jnp.cumsum(sum_v, axis=cumulative_axis)
|
|
493
|
+
count_v = accum_count_v + jnp.cumsum(count_v, axis=cumulative_axis)
|
|
494
|
+
|
|
495
|
+
# Keep the total sum/count up to the end of this chunk as the accumulator
|
|
496
|
+
# state.
|
|
497
|
+
accum_sum_v = jax.lax.slice_in_dim(
|
|
498
|
+
sum_v, -1, limit_index=None, axis=cumulative_axis
|
|
499
|
+
)
|
|
500
|
+
accum_count_v = jax.lax.slice_in_dim(
|
|
501
|
+
count_v, -1, limit_index=None, axis=cumulative_axis
|
|
502
|
+
)
|
|
503
|
+
|
|
504
|
+
count_v = jnp.maximum(count_v, 1.0)
|
|
505
|
+
mean = sum_v / count_v
|
|
506
|
+
sum_vv = jnp.sum(
|
|
507
|
+
jnp.where(mask, jnp.square(inputs.values - mean), 0),
|
|
508
|
+
reduction_axes,
|
|
509
|
+
keepdims=True,
|
|
510
|
+
)
|
|
511
|
+
# Broadcast add the accumulators to the cumsum of the input timesteps.
|
|
512
|
+
sum_vv = accum_sum_vv + jnp.cumsum(sum_vv, axis=cumulative_axis)
|
|
513
|
+
|
|
514
|
+
# Keep the total sum/count up to the end of this chunk as the accumulator
|
|
515
|
+
# state.
|
|
516
|
+
accum_sum_vv = jax.lax.slice_in_dim(
|
|
517
|
+
sum_vv, -1, limit_index=None, axis=cumulative_axis
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
variance = sum_vv / count_v
|
|
521
|
+
return mean, variance, accum_sum_v, accum_count_v, accum_sum_vv
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _masked_moments(
|
|
525
|
+
inputs: types.Sequence,
|
|
526
|
+
reduction_axes: list[int],
|
|
527
|
+
cumulative_axis: int | None = None,
|
|
528
|
+
) -> tuple[jax.Array, jax.Array]:
|
|
529
|
+
"""Compute the moments of inputs/input_lengths over reduction_axes.
|
|
530
|
+
|
|
531
|
+
This implementation follows Babelfish's in:
|
|
532
|
+
google3/third_party/py/lingvo/core/bn_layers.py
|
|
533
|
+
|
|
534
|
+
Args:
|
|
535
|
+
inputs: A [batch_size, time, ...] sequence.
|
|
536
|
+
reduction_axes: The axes to reduce over for computing the moments.
|
|
537
|
+
cumulative_axis: If non-None, accumulates moments along this axis. Must not
|
|
538
|
+
be an axis in reduction_axes.
|
|
539
|
+
|
|
540
|
+
Returns:
|
|
541
|
+
means: The means of inputs along the axes indicated in
|
|
542
|
+
reduction_axes. For example, if the input is [a, b, c, d] and
|
|
543
|
+
reduction_axes is [0, 1, 3], means's shape is [1, 1, c, 1].
|
|
544
|
+
variances: The variance of inputs along the axes indicated in
|
|
545
|
+
reduction_axes. For example, if the input is [a, b, c, d] and
|
|
546
|
+
reduction_axes is [0, 1, 3], variance's shape is [1, 1, c, 1].
|
|
547
|
+
"""
|
|
548
|
+
# Mask input if it isn't already.
|
|
549
|
+
inputs = inputs.mask_invalid()
|
|
550
|
+
mask = inputs.expanded_mask()
|
|
551
|
+
if cumulative_axis is not None:
|
|
552
|
+
assert cumulative_axis not in reduction_axes
|
|
553
|
+
|
|
554
|
+
sum_v = jnp.sum(inputs.values, reduction_axes, keepdims=True)
|
|
555
|
+
count_v = jnp.sum(mask, reduction_axes, keepdims=True)
|
|
556
|
+
|
|
557
|
+
# Multiply counts by non-batch/time reduction dimensions. This is more
|
|
558
|
+
# efficient than broadcast the count_v sum above to the shape of inputs.
|
|
559
|
+
non_batch_time_axes = [a for a in reduction_axes if a not in (0, 1)]
|
|
560
|
+
if non_batch_time_axes:
|
|
561
|
+
counts_multiplier = np.prod(
|
|
562
|
+
[inputs.shape[ax] for ax in non_batch_time_axes]
|
|
563
|
+
)
|
|
564
|
+
count_v *= jnp.array(counts_multiplier, dtype=count_v.dtype)
|
|
565
|
+
|
|
566
|
+
if cumulative_axis is not None:
|
|
567
|
+
sum_v = jnp.cumsum(sum_v, axis=cumulative_axis)
|
|
568
|
+
count_v = jnp.cumsum(count_v, axis=cumulative_axis)
|
|
569
|
+
|
|
570
|
+
count_v = jnp.maximum(count_v, 1.0)
|
|
571
|
+
mean = sum_v / count_v
|
|
572
|
+
sum_vv = jnp.sum(
|
|
573
|
+
jnp.where(mask, jnp.square(inputs.values - mean), 0),
|
|
574
|
+
reduction_axes,
|
|
575
|
+
keepdims=True,
|
|
576
|
+
)
|
|
577
|
+
if cumulative_axis is not None:
|
|
578
|
+
sum_vv = jnp.cumsum(sum_vv, axis=cumulative_axis)
|
|
579
|
+
|
|
580
|
+
variance = sum_vv / count_v
|
|
581
|
+
return mean, variance
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
class GroupNormalization(types.PreservesType, types.StatelessPointwise):
|
|
585
|
+
"""Applies group normalization to input sequences.
|
|
586
|
+
|
|
587
|
+
https://arxiv.org/abs/1803.08494
|
|
588
|
+
"""
|
|
589
|
+
|
|
590
|
+
@dataclasses.dataclass(frozen=True)
|
|
591
|
+
class Config(types.SequenceLayerConfig):
|
|
592
|
+
"""Config for GroupNormalization."""
|
|
593
|
+
|
|
594
|
+
num_groups: int
|
|
595
|
+
axis: int = -1
|
|
596
|
+
epsilon: float = 1e-6
|
|
597
|
+
cumulative: bool = False
|
|
598
|
+
use_bias: bool = True
|
|
599
|
+
use_scale: bool = True
|
|
600
|
+
bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
|
|
601
|
+
scale_init: nn.initializers.Initializer = nn.initializers.ones_init()
|
|
602
|
+
sharding: types.Sharding | None = None
|
|
603
|
+
param_dtype: types.DType = jnp.float32
|
|
604
|
+
# If true, guards against "excess precision" introduced by XLA fusions in
|
|
605
|
+
# the backward pass. Equivalent to --noxla_allow_excess_precision but only
|
|
606
|
+
# for the input to this layer.
|
|
607
|
+
guard_against_excess_precision: bool = False
|
|
608
|
+
name: str | None = None
|
|
609
|
+
|
|
610
|
+
def make(self) -> 'GroupNormalization':
|
|
611
|
+
if self.num_groups <= 0:
|
|
612
|
+
raise ValueError(f'{self.num_groups=} must be positive.')
|
|
613
|
+
return GroupNormalization(self, name=self.name)
|
|
614
|
+
|
|
615
|
+
config: Config
|
|
616
|
+
|
|
617
|
+
@property
|
|
618
|
+
def supports_step(self) -> bool:
|
|
619
|
+
return self.config.cumulative
|
|
620
|
+
|
|
621
|
+
@property
|
|
622
|
+
def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
|
|
623
|
+
return {0: (-np.inf, 0 if self.config.cumulative else np.inf)}
|
|
624
|
+
|
|
625
|
+
def get_initial_state(
|
|
626
|
+
self,
|
|
627
|
+
batch_size: int,
|
|
628
|
+
input_spec: types.ShapeDType,
|
|
629
|
+
*,
|
|
630
|
+
training: bool,
|
|
631
|
+
constants: types.Constants | None = None,
|
|
632
|
+
) -> types.State:
|
|
633
|
+
if not self.supports_step:
|
|
634
|
+
raise ValueError(
|
|
635
|
+
'Step-wise processing requires cumulative mode for'
|
|
636
|
+
' GroupNormalization.'
|
|
637
|
+
)
|
|
638
|
+
assert self.config.cumulative
|
|
639
|
+
(axis,) = _validate_and_normalize_axes(
|
|
640
|
+
[self.config.axis], (None, None) + input_spec.shape
|
|
641
|
+
)
|
|
642
|
+
|
|
643
|
+
input_shape = (batch_size, 1) + input_spec.shape
|
|
644
|
+
axis_size = input_shape[axis]
|
|
645
|
+
if axis_size % self.config.num_groups != 0:
|
|
646
|
+
raise ValueError(
|
|
647
|
+
f'Input shape ({input_shape}) axis={axis} must be'
|
|
648
|
+
f' divisible by {self.config.num_groups}'
|
|
649
|
+
)
|
|
650
|
+
|
|
651
|
+
group_size = axis_size // self.config.num_groups
|
|
652
|
+
|
|
653
|
+
outer_indices, _, inner_indices = np.split(
|
|
654
|
+
input_shape, indices_or_sections=[axis, axis + 1]
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
expanded_shape = (
|
|
658
|
+
outer_indices.tolist()
|
|
659
|
+
+ [self.config.num_groups, group_size]
|
|
660
|
+
+ inner_indices.tolist()
|
|
661
|
+
)
|
|
662
|
+
|
|
663
|
+
dtype = jnp.promote_types(input_spec.dtype, jnp.float32)
|
|
664
|
+
moments_shape = [
|
|
665
|
+
expanded_shape[ax] if ax in (0, 1, axis) else 1
|
|
666
|
+
for ax in range(len(expanded_shape))
|
|
667
|
+
]
|
|
668
|
+
|
|
669
|
+
sum_v = jnp.zeros(moments_shape, dtype)
|
|
670
|
+
count_v = jnp.zeros(moments_shape, dtype)
|
|
671
|
+
sum_vv = jnp.zeros(moments_shape, dtype)
|
|
672
|
+
|
|
673
|
+
return sum_v, count_v, sum_vv
|
|
674
|
+
|
|
675
|
+
@nn.nowrap
|
|
676
|
+
def _group(self, values: jax.Array, normalized_axis: int) -> jax.Array:
|
|
677
|
+
axis_size = values.shape[normalized_axis]
|
|
678
|
+
if axis_size % self.config.num_groups != 0:
|
|
679
|
+
raise ValueError(
|
|
680
|
+
f'Input shape ({values.shape}) axis={normalized_axis} must be'
|
|
681
|
+
f' divisible by {self.config.num_groups}'
|
|
682
|
+
)
|
|
683
|
+
|
|
684
|
+
group_size = axis_size // self.config.num_groups
|
|
685
|
+
|
|
686
|
+
outer_indices, _, inner_indices = np.split(
|
|
687
|
+
values.shape, indices_or_sections=[normalized_axis, normalized_axis + 1]
|
|
688
|
+
)
|
|
689
|
+
|
|
690
|
+
expanded_shape = (
|
|
691
|
+
outer_indices.tolist()
|
|
692
|
+
+ [self.config.num_groups, group_size]
|
|
693
|
+
+ inner_indices.tolist()
|
|
694
|
+
)
|
|
695
|
+
return jnp.reshape(values, expanded_shape)
|
|
696
|
+
|
|
697
|
+
@nn.compact
|
|
698
|
+
def _scale_and_shift(
|
|
699
|
+
self,
|
|
700
|
+
values: jax.Array,
|
|
701
|
+
reduced_feature_shape: list[int],
|
|
702
|
+
feature_shape: list[int],
|
|
703
|
+
) -> jax.Array:
|
|
704
|
+
# Apply scale and bias.
|
|
705
|
+
if self.config.use_scale:
|
|
706
|
+
scale_init = utils.shard_initializer(
|
|
707
|
+
self.config.scale_init,
|
|
708
|
+
self.config.sharding,
|
|
709
|
+
labels=[meta.IS_NORMALIZER],
|
|
710
|
+
)
|
|
711
|
+
values *= jnp.reshape(
|
|
712
|
+
self.param(
|
|
713
|
+
'scale',
|
|
714
|
+
scale_init,
|
|
715
|
+
reduced_feature_shape,
|
|
716
|
+
self.config.param_dtype,
|
|
717
|
+
),
|
|
718
|
+
feature_shape,
|
|
719
|
+
)
|
|
720
|
+
|
|
721
|
+
if self.config.use_bias:
|
|
722
|
+
bias_init = utils.shard_initializer(
|
|
723
|
+
self.config.bias_init, self.config.sharding
|
|
724
|
+
)
|
|
725
|
+
values += jnp.reshape(
|
|
726
|
+
self.param(
|
|
727
|
+
'bias',
|
|
728
|
+
bias_init,
|
|
729
|
+
reduced_feature_shape,
|
|
730
|
+
self.config.param_dtype,
|
|
731
|
+
),
|
|
732
|
+
feature_shape,
|
|
733
|
+
)
|
|
734
|
+
|
|
735
|
+
return values
|
|
736
|
+
|
|
737
|
+
@types.check_step
|
|
738
|
+
def step(
|
|
739
|
+
self,
|
|
740
|
+
x: types.Sequence,
|
|
741
|
+
state: types.State,
|
|
742
|
+
*,
|
|
743
|
+
training: bool,
|
|
744
|
+
constants: types.Constants | None = None,
|
|
745
|
+
) -> tuple[types.Sequence, types.State]:
|
|
746
|
+
if not self.supports_step:
|
|
747
|
+
raise ValueError(
|
|
748
|
+
'Step-wise processing requires cumulative mode for'
|
|
749
|
+
' GroupNormalization.'
|
|
750
|
+
)
|
|
751
|
+
assert self.config.cumulative
|
|
752
|
+
|
|
753
|
+
(axis,) = _validate_and_normalize_axes([self.config.axis], x.shape)
|
|
754
|
+
|
|
755
|
+
axis_size = x.shape[axis]
|
|
756
|
+
feature_shape = [1] * x.ndim
|
|
757
|
+
feature_shape[axis] = axis_size
|
|
758
|
+
reduced_feature_shape = [axis_size]
|
|
759
|
+
|
|
760
|
+
if self.config.guard_against_excess_precision:
|
|
761
|
+
x = x.apply_values_masked(_guard_against_excess_precision)
|
|
762
|
+
|
|
763
|
+
# GroupNorm's gradients are particularly sensitive, so we do most
|
|
764
|
+
# operations (inc. scale and shift in higher precision).
|
|
765
|
+
@utils.run_in_at_least_fp32
|
|
766
|
+
def reductions(x: types.Sequence) -> jax.Array:
|
|
767
|
+
nonlocal state
|
|
768
|
+
|
|
769
|
+
state_sum_v, state_count_v, state_sum_vv = state
|
|
770
|
+
# Grouping leaves the mask status of the input unchanged, since
|
|
771
|
+
# axis > 1.
|
|
772
|
+
grouped_x = x.apply_values_masked(self._group, axis)
|
|
773
|
+
expanded_rank = x.values.ndim + 1
|
|
774
|
+
|
|
775
|
+
# Reduce over all dimension but batch, time, and num_groups.
|
|
776
|
+
reduction_axes = [
|
|
777
|
+
ax for ax in range(expanded_rank) if ax not in (0, 1, axis)
|
|
778
|
+
]
|
|
779
|
+
|
|
780
|
+
def forward_fn(
|
|
781
|
+
grouped_x: types.Sequence,
|
|
782
|
+
state_sum_v: jax.Array,
|
|
783
|
+
state_count_v: jax.Array,
|
|
784
|
+
state_sum_vv: jax.Array,
|
|
785
|
+
) -> tuple[jt.AnyPyTree, jt.AnyPyTree]:
|
|
786
|
+
group_mean, group_variance, state_sum_v, state_count_v, state_sum_vv = (
|
|
787
|
+
_cumulative_masked_moments_streaming(
|
|
788
|
+
grouped_x,
|
|
789
|
+
reduction_axes,
|
|
790
|
+
cumulative_axis=1,
|
|
791
|
+
accum_sum_v=state_sum_v,
|
|
792
|
+
accum_count_v=state_count_v,
|
|
793
|
+
accum_sum_vv=state_sum_vv,
|
|
794
|
+
)
|
|
795
|
+
)
|
|
796
|
+
|
|
797
|
+
group_stddev_inv = jax.lax.rsqrt(group_variance + self.config.epsilon)
|
|
798
|
+
grouped_values = (grouped_x.values - group_mean) * group_stddev_inv
|
|
799
|
+
should_zero_gradient = (
|
|
800
|
+
group_variance == 0.0,
|
|
801
|
+
jnp.zeros(state_sum_v.shape, jnp.bool_),
|
|
802
|
+
jnp.zeros(state_count_v.shape, jnp.bool_),
|
|
803
|
+
jnp.zeros(state_sum_vv.shape, jnp.bool_),
|
|
804
|
+
)
|
|
805
|
+
return (
|
|
806
|
+
(grouped_values, state_sum_v, state_count_v, state_sum_vv),
|
|
807
|
+
should_zero_gradient,
|
|
808
|
+
)
|
|
809
|
+
|
|
810
|
+
grouped_values, state_sum_v, state_count_v, state_sum_vv = ( # pylint: disable=unbalanced-tuple-unpacking
|
|
811
|
+
_zero_gradient_helper(
|
|
812
|
+
forward_fn, grouped_x, state_sum_v, state_count_v, state_sum_vv
|
|
813
|
+
)
|
|
814
|
+
)
|
|
815
|
+
|
|
816
|
+
state = (state_sum_v, state_count_v, state_sum_vv)
|
|
817
|
+
# Combine num_groups and group_size.
|
|
818
|
+
values = jnp.reshape(grouped_values, x.values.shape)
|
|
819
|
+
return self._scale_and_shift(values, reduced_feature_shape, feature_shape)
|
|
820
|
+
|
|
821
|
+
# Normalization leaves padded regions unmasked.
|
|
822
|
+
return types.Sequence(reductions(x), x.mask), state
|
|
823
|
+
|
|
824
|
+
@types.check_layer
|
|
825
|
+
def layer(
|
|
826
|
+
self,
|
|
827
|
+
x: types.Sequence,
|
|
828
|
+
*,
|
|
829
|
+
training: bool,
|
|
830
|
+
constants: types.Constants | None = None,
|
|
831
|
+
) -> types.Sequence:
|
|
832
|
+
# Only one axis in [2, ndim) is supported.
|
|
833
|
+
(axis,) = _validate_and_normalize_axes([self.config.axis], x.shape)
|
|
834
|
+
|
|
835
|
+
axis_size = x.shape[axis]
|
|
836
|
+
feature_shape = [1] * x.ndim
|
|
837
|
+
feature_shape[axis] = axis_size
|
|
838
|
+
reduced_feature_shape = [axis_size]
|
|
839
|
+
|
|
840
|
+
if self.config.guard_against_excess_precision:
|
|
841
|
+
x = x.apply_values_masked(_guard_against_excess_precision)
|
|
842
|
+
|
|
843
|
+
# GroupNorm's gradients are particularly sensitive, so we do most
|
|
844
|
+
# operations (inc. scale and shift in higher precision).
|
|
845
|
+
@utils.run_in_at_least_fp32
|
|
846
|
+
def reductions(x: types.Sequence) -> jax.Array:
|
|
847
|
+
# Grouping leaves the mask status of the input unchanged, since
|
|
848
|
+
# axis > 1.
|
|
849
|
+
grouped_x = x.apply_values_masked(self._group, axis)
|
|
850
|
+
expanded_rank = x.values.ndim + 1
|
|
851
|
+
|
|
852
|
+
if self.config.cumulative:
|
|
853
|
+
# Reduce over all dimension but batch, time, and num_groups.
|
|
854
|
+
reduction_axes = [
|
|
855
|
+
ax for ax in range(expanded_rank) if ax not in (0, 1, axis)
|
|
856
|
+
]
|
|
857
|
+
else:
|
|
858
|
+
# Reduce over all dimension but batch and num_groups.
|
|
859
|
+
reduction_axes = [
|
|
860
|
+
ax for ax in range(expanded_rank) if ax not in (0, axis)
|
|
861
|
+
]
|
|
862
|
+
|
|
863
|
+
def forward_fn(
|
|
864
|
+
grouped_x: types.Sequence,
|
|
865
|
+
) -> tuple[jt.AnyPyTree, jt.AnyPyTree]:
|
|
866
|
+
group_mean, group_variance = _masked_moments(
|
|
867
|
+
# Grouping leaves the mask status of the input unchanged, since axis
|
|
868
|
+
# > 1.
|
|
869
|
+
grouped_x,
|
|
870
|
+
reduction_axes,
|
|
871
|
+
cumulative_axis=1 if self.config.cumulative else None,
|
|
872
|
+
)
|
|
873
|
+
|
|
874
|
+
group_stddev_inv = jax.lax.rsqrt(group_variance + self.config.epsilon)
|
|
875
|
+
grouped_values = (grouped_x.values - group_mean) * group_stddev_inv
|
|
876
|
+
|
|
877
|
+
# Guard against blowup from all-zero inputs.
|
|
878
|
+
should_zero_gradient = group_variance == 0.0
|
|
879
|
+
|
|
880
|
+
return grouped_values, (should_zero_gradient,)
|
|
881
|
+
|
|
882
|
+
grouped_values = _zero_gradient_helper(forward_fn, grouped_x)
|
|
883
|
+
|
|
884
|
+
# Combine num_groups and group_size.
|
|
885
|
+
values = jnp.reshape(grouped_values, x.values.shape)
|
|
886
|
+
return self._scale_and_shift(values, reduced_feature_shape, feature_shape)
|
|
887
|
+
|
|
888
|
+
# Normalization leaves padded regions unmasked.
|
|
889
|
+
return types.Sequence(reductions(x), x.mask)
|