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,2679 @@
|
|
|
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
|
+
"""Simple (generally stateless) layers."""
|
|
15
|
+
|
|
16
|
+
import abc
|
|
17
|
+
from collections.abc import Mapping
|
|
18
|
+
import dataclasses
|
|
19
|
+
import fractions
|
|
20
|
+
import functools
|
|
21
|
+
import math
|
|
22
|
+
import typing
|
|
23
|
+
from typing import Any, Callable, Sequence as TypingSequence
|
|
24
|
+
|
|
25
|
+
from absl import logging
|
|
26
|
+
import einops
|
|
27
|
+
import flax.linen as nn
|
|
28
|
+
import jax
|
|
29
|
+
import jax.ad_checkpoint
|
|
30
|
+
import jax.numpy as jnp
|
|
31
|
+
import numpy as np
|
|
32
|
+
from sequence_layers.jax import sharding as sharding_lib
|
|
33
|
+
from sequence_layers.jax import types
|
|
34
|
+
from sequence_layers.jax import utils
|
|
35
|
+
from typing_extensions import override
|
|
36
|
+
|
|
37
|
+
# pylint: disable=logging-fstring-interpolation
|
|
38
|
+
|
|
39
|
+
__all__ = (
|
|
40
|
+
# go/keep-sorted start
|
|
41
|
+
'Abs',
|
|
42
|
+
'Add',
|
|
43
|
+
'Affine',
|
|
44
|
+
'ApplySharding',
|
|
45
|
+
'Argmax',
|
|
46
|
+
'Cast',
|
|
47
|
+
'CheckpointName',
|
|
48
|
+
'Downsample1D',
|
|
49
|
+
'Dropout',
|
|
50
|
+
'EinopsRearrange',
|
|
51
|
+
'Elu',
|
|
52
|
+
'Embedding',
|
|
53
|
+
'EmbeddingTranspose',
|
|
54
|
+
'Emit',
|
|
55
|
+
'Exp',
|
|
56
|
+
'ExpandDims',
|
|
57
|
+
'Flatten',
|
|
58
|
+
'GatedLinearUnit',
|
|
59
|
+
'GatedTanhUnit',
|
|
60
|
+
'GatedUnit',
|
|
61
|
+
'Gelu',
|
|
62
|
+
'GlobalEinopsRearrange',
|
|
63
|
+
'GlobalReshape',
|
|
64
|
+
'GradientClipping',
|
|
65
|
+
'Identity',
|
|
66
|
+
'Lambda',
|
|
67
|
+
'LeakyRelu',
|
|
68
|
+
'Log',
|
|
69
|
+
'Logging',
|
|
70
|
+
'MaskInvalid',
|
|
71
|
+
'Maximum',
|
|
72
|
+
'Minimum',
|
|
73
|
+
'Mod',
|
|
74
|
+
'MoveAxis',
|
|
75
|
+
'OneHot',
|
|
76
|
+
'OptimizationBarrier',
|
|
77
|
+
'PRelu',
|
|
78
|
+
'Power',
|
|
79
|
+
'Relu',
|
|
80
|
+
'Reshape',
|
|
81
|
+
'Scale',
|
|
82
|
+
'Sigmoid',
|
|
83
|
+
'Slice',
|
|
84
|
+
'Softmax',
|
|
85
|
+
'Softplus',
|
|
86
|
+
'Squeeze',
|
|
87
|
+
'SwapAxes',
|
|
88
|
+
'Swish',
|
|
89
|
+
'Tanh',
|
|
90
|
+
'Transpose',
|
|
91
|
+
'Upsample1D',
|
|
92
|
+
'Upsample2D',
|
|
93
|
+
# go/keep-sorted end
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _to_tuple(x: complex | list[Any]) -> complex | tuple[Any, ...]:
|
|
98
|
+
"""Replaces lists in a pytree of complex with tuples."""
|
|
99
|
+
if isinstance(x, list):
|
|
100
|
+
return tuple(_to_tuple(i) for i in x)
|
|
101
|
+
else:
|
|
102
|
+
return x
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclasses.dataclass(frozen=True)
|
|
106
|
+
class HashableArray:
|
|
107
|
+
"""Hashable multidimensional array of tuples."""
|
|
108
|
+
|
|
109
|
+
data: complex | tuple[Any, ...]
|
|
110
|
+
dtype: np.dtype
|
|
111
|
+
|
|
112
|
+
@classmethod
|
|
113
|
+
def from_array(cls, x: np.ndarray) -> 'HashableArray':
|
|
114
|
+
x = np.asarray(x)
|
|
115
|
+
return HashableArray(_to_tuple(x.tolist()), x.dtype)
|
|
116
|
+
|
|
117
|
+
def to_array(self) -> np.ndarray:
|
|
118
|
+
return np.asarray(self.data, dtype=self.dtype)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _to_array(x: complex | np.ndarray | HashableArray) -> np.ndarray:
|
|
122
|
+
if isinstance(x, HashableArray):
|
|
123
|
+
return x.to_array()
|
|
124
|
+
return np.asarray(x)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class StatelessPointwiseBroadcasting(
|
|
128
|
+
types.PreservesType, types.Stateless, metaclass=abc.ABCMeta
|
|
129
|
+
):
|
|
130
|
+
"""Abstract base class for pointwise operations with broadcasting."""
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
@abc.abstractmethod
|
|
134
|
+
def _broadcast_parameter(self) -> np.ndarray:
|
|
135
|
+
pass
|
|
136
|
+
|
|
137
|
+
@nn.nowrap
|
|
138
|
+
def _validate(
|
|
139
|
+
self, parameter: np.ndarray, input_shape: types.ShapeLike
|
|
140
|
+
) -> None:
|
|
141
|
+
if len(parameter.shape) > len(input_shape):
|
|
142
|
+
raise ValueError(
|
|
143
|
+
f'{self} parameter ({parameter}) has too many dimensions to broadcast'
|
|
144
|
+
f' with the input channel shape ({input_shape=}).'
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
@nn.nowrap
|
|
148
|
+
def get_output_shape(
|
|
149
|
+
self,
|
|
150
|
+
input_shape: types.ShapeLike,
|
|
151
|
+
*,
|
|
152
|
+
constants: types.Constants | None = None,
|
|
153
|
+
) -> types.Shape:
|
|
154
|
+
del constants
|
|
155
|
+
parameter = self._broadcast_parameter
|
|
156
|
+
self._validate(parameter, input_shape)
|
|
157
|
+
return jnp.broadcast_shapes(input_shape, parameter.shape)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class Scale(StatelessPointwiseBroadcasting):
|
|
161
|
+
"""Scales the input by a provided constant or array."""
|
|
162
|
+
|
|
163
|
+
@dataclasses.dataclass(frozen=True)
|
|
164
|
+
class Config(types.SequenceLayerConfig):
|
|
165
|
+
"""Config for Scale."""
|
|
166
|
+
|
|
167
|
+
# The value to scale the input by. May be a numpy array, but must be
|
|
168
|
+
# broadcastable to the channels dimension of the input. This value is cast
|
|
169
|
+
# to the dtype of the input, so the type of the input is preserved.
|
|
170
|
+
# PEP 484 says to use complex when you mean any numeric type.
|
|
171
|
+
scale: complex | np.ndarray | HashableArray
|
|
172
|
+
name: str | None = None
|
|
173
|
+
|
|
174
|
+
def __post_init__(self):
|
|
175
|
+
object.__setattr__(self, 'scale', HashableArray.from_array(self.scale))
|
|
176
|
+
|
|
177
|
+
def make(self) -> 'Scale':
|
|
178
|
+
return Scale(self, name=self.name)
|
|
179
|
+
|
|
180
|
+
config: Config
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def _broadcast_parameter(self) -> np.ndarray:
|
|
184
|
+
return _to_array(self.config.scale)
|
|
185
|
+
|
|
186
|
+
@types.check_layer
|
|
187
|
+
def layer(
|
|
188
|
+
self,
|
|
189
|
+
x: types.Sequence,
|
|
190
|
+
*,
|
|
191
|
+
training: bool,
|
|
192
|
+
constants: types.Constants | None = None,
|
|
193
|
+
) -> types.Sequence:
|
|
194
|
+
del training
|
|
195
|
+
parameter = self._broadcast_parameter
|
|
196
|
+
self._validate(parameter, x.channel_shape)
|
|
197
|
+
assert isinstance(self.config.scale, HashableArray)
|
|
198
|
+
return x.apply_values_masked(lambda v: v * parameter.astype(v.dtype))
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class Affine(types.PreservesType, types.Stateless):
|
|
202
|
+
"""Learnable additive bias and multiplicative scale scalars."""
|
|
203
|
+
|
|
204
|
+
@dataclasses.dataclass(frozen=True)
|
|
205
|
+
class Config(types.SequenceLayerConfig):
|
|
206
|
+
"""Config of the learnable scale and bias layer."""
|
|
207
|
+
|
|
208
|
+
use_bias: bool = True
|
|
209
|
+
use_scale: bool = True
|
|
210
|
+
shape: types.ShapeLike | None = None
|
|
211
|
+
param_dtype: types.DType = jnp.float32
|
|
212
|
+
scale_init: nn.initializers.Initializer = nn.initializers.ones_init()
|
|
213
|
+
bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
|
|
214
|
+
scale_sharding: types.Sharding | None = None
|
|
215
|
+
bias_sharding: types.Sharding | None = None
|
|
216
|
+
|
|
217
|
+
name: str | None = None
|
|
218
|
+
|
|
219
|
+
def __post_init__(self):
|
|
220
|
+
object.__setattr__(
|
|
221
|
+
self, 'shape', [] if self.shape is None else self.shape
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
def make(self) -> 'Affine':
|
|
225
|
+
return Affine(self, name=self.name)
|
|
226
|
+
|
|
227
|
+
def setup(self):
|
|
228
|
+
cfg = self.config
|
|
229
|
+
if cfg.use_scale:
|
|
230
|
+
scale_init = utils.shard_initializer(
|
|
231
|
+
self.config.scale_init, self.config.scale_sharding
|
|
232
|
+
)
|
|
233
|
+
self.scale = self.param(
|
|
234
|
+
'scale', scale_init, self.config.shape, cfg.param_dtype
|
|
235
|
+
)
|
|
236
|
+
if cfg.use_bias:
|
|
237
|
+
bias_init = utils.shard_initializer(
|
|
238
|
+
self.config.bias_init, self.config.bias_sharding
|
|
239
|
+
)
|
|
240
|
+
self.bias = self.param(
|
|
241
|
+
'bias', bias_init, self.config.shape, cfg.param_dtype
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
config: Config
|
|
245
|
+
|
|
246
|
+
@nn.nowrap
|
|
247
|
+
def get_output_shape(
|
|
248
|
+
self,
|
|
249
|
+
input_shape: types.ShapeLike,
|
|
250
|
+
*,
|
|
251
|
+
constants: types.Constants | None = None,
|
|
252
|
+
) -> types.Shape:
|
|
253
|
+
del constants
|
|
254
|
+
|
|
255
|
+
# Check that the parameters do not have batch or time dimension.
|
|
256
|
+
if len(input_shape) < len(self.config.shape):
|
|
257
|
+
raise ValueError(
|
|
258
|
+
f'The parameter has too many dimensions (input: {len(input_shape)},'
|
|
259
|
+
f' parameter: {len(self.config.shape)}'
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
# This function throws a value error if the shapes are not broadcastable.
|
|
263
|
+
return jnp.broadcast_shapes(input_shape, self.config.shape)
|
|
264
|
+
|
|
265
|
+
@types.check_layer
|
|
266
|
+
def layer(
|
|
267
|
+
self,
|
|
268
|
+
x: types.Sequence,
|
|
269
|
+
*,
|
|
270
|
+
training: bool,
|
|
271
|
+
constants: types.Constants | None = None,
|
|
272
|
+
) -> types.Sequence:
|
|
273
|
+
del training
|
|
274
|
+
# This will validate the shapes by the call to broadcast_shapes.
|
|
275
|
+
# Throws a ValueError when the shapes do not match.
|
|
276
|
+
_ = self.get_output_shape(x.shape[2:])
|
|
277
|
+
|
|
278
|
+
if self.config.use_scale:
|
|
279
|
+
x = x.apply_values(lambda v: v * self.scale.astype(v.dtype))
|
|
280
|
+
if self.config.use_bias:
|
|
281
|
+
x = x.apply_values(lambda v: v + self.bias.astype(v.dtype))
|
|
282
|
+
return x
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
class Add(StatelessPointwiseBroadcasting):
|
|
286
|
+
"""Adds the provided constant or array to the input."""
|
|
287
|
+
|
|
288
|
+
@dataclasses.dataclass(frozen=True)
|
|
289
|
+
class Config(types.SequenceLayerConfig):
|
|
290
|
+
"""Config for Add."""
|
|
291
|
+
|
|
292
|
+
# The value to add to the input. May be a numpy array, but must be
|
|
293
|
+
# broadcastable to the channels dimension of the input. This value is cast
|
|
294
|
+
# to the dtype of the input, so the type of the input is preserved.
|
|
295
|
+
# PEP 484 says to use complex when you mean any numeric type.
|
|
296
|
+
shift: complex | np.ndarray | HashableArray
|
|
297
|
+
name: str | None = None
|
|
298
|
+
|
|
299
|
+
def __post_init__(self):
|
|
300
|
+
object.__setattr__(self, 'shift', HashableArray.from_array(self.shift))
|
|
301
|
+
|
|
302
|
+
def make(self) -> 'Add':
|
|
303
|
+
return Add(self, name=self.name)
|
|
304
|
+
|
|
305
|
+
config: Config
|
|
306
|
+
|
|
307
|
+
@property
|
|
308
|
+
def _broadcast_parameter(self) -> np.ndarray:
|
|
309
|
+
return _to_array(self.config.shift)
|
|
310
|
+
|
|
311
|
+
@types.check_layer
|
|
312
|
+
def layer(
|
|
313
|
+
self,
|
|
314
|
+
x: types.Sequence,
|
|
315
|
+
*,
|
|
316
|
+
training: bool,
|
|
317
|
+
constants: types.Constants | None = None,
|
|
318
|
+
) -> types.Sequence:
|
|
319
|
+
del training
|
|
320
|
+
parameter = self._broadcast_parameter
|
|
321
|
+
self._validate(parameter, x.channel_shape)
|
|
322
|
+
assert isinstance(self.config.shift, HashableArray)
|
|
323
|
+
return x.apply_values(lambda v: v + parameter.astype(v.dtype))
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
class Maximum(StatelessPointwiseBroadcasting):
|
|
327
|
+
"""Clips the input with the provided maximum value."""
|
|
328
|
+
|
|
329
|
+
@dataclasses.dataclass(frozen=True)
|
|
330
|
+
class Config(types.SequenceLayerConfig):
|
|
331
|
+
"""Config for Maximum."""
|
|
332
|
+
|
|
333
|
+
# The value to clip the input with. May be a numpy array, but must be
|
|
334
|
+
# broadcastable to the channels dimension of the input. This value is cast
|
|
335
|
+
# to the dtype of the input, so the type of the input is preserved.
|
|
336
|
+
# PEP 484 says to use complex when you mean any numeric type.
|
|
337
|
+
maximum: complex | np.ndarray | HashableArray
|
|
338
|
+
name: str | None = None
|
|
339
|
+
|
|
340
|
+
def __post_init__(self):
|
|
341
|
+
object.__setattr__(
|
|
342
|
+
self, 'maximum', HashableArray.from_array(self.maximum)
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
def make(self) -> 'Maximum':
|
|
346
|
+
return Maximum(self, name=self.name)
|
|
347
|
+
|
|
348
|
+
config: Config
|
|
349
|
+
|
|
350
|
+
@property
|
|
351
|
+
def _broadcast_parameter(self) -> np.ndarray:
|
|
352
|
+
return _to_array(self.config.maximum)
|
|
353
|
+
|
|
354
|
+
@types.check_layer
|
|
355
|
+
def layer(
|
|
356
|
+
self,
|
|
357
|
+
x: types.Sequence,
|
|
358
|
+
*,
|
|
359
|
+
training: bool,
|
|
360
|
+
constants: types.Constants | None = None,
|
|
361
|
+
) -> types.Sequence:
|
|
362
|
+
del training
|
|
363
|
+
parameter = self._broadcast_parameter
|
|
364
|
+
self._validate(parameter, x.channel_shape)
|
|
365
|
+
assert isinstance(self.config.maximum, HashableArray)
|
|
366
|
+
return x.apply_values(lambda v: jnp.maximum(v, parameter.astype(v.dtype)))
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
class Mod(StatelessPointwiseBroadcasting):
|
|
370
|
+
"""Returns the remainder of division of the input by the provided divisor."""
|
|
371
|
+
|
|
372
|
+
@dataclasses.dataclass(frozen=True)
|
|
373
|
+
class Config(types.SequenceLayerConfig):
|
|
374
|
+
"""Config for Mod."""
|
|
375
|
+
|
|
376
|
+
# The divisor to compute the remainder with. May be a numpy array, but must
|
|
377
|
+
# be broadcastable to the channels dimension of the input. This value is
|
|
378
|
+
# cast to the dtype of the input, so the type of the input is preserved.
|
|
379
|
+
# PEP 484 says to use complex when you mean any numeric type.
|
|
380
|
+
divisor: complex | np.ndarray | HashableArray
|
|
381
|
+
name: str | None = None
|
|
382
|
+
|
|
383
|
+
def __post_init__(self):
|
|
384
|
+
object.__setattr__(
|
|
385
|
+
self, 'divisor', HashableArray.from_array(self.divisor)
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
def make(self) -> 'Mod':
|
|
389
|
+
return Mod(self, name=self.name)
|
|
390
|
+
|
|
391
|
+
config: Config
|
|
392
|
+
|
|
393
|
+
@property
|
|
394
|
+
def _broadcast_parameter(self) -> np.ndarray:
|
|
395
|
+
return _to_array(self.config.divisor)
|
|
396
|
+
|
|
397
|
+
@types.check_layer
|
|
398
|
+
def layer(
|
|
399
|
+
self,
|
|
400
|
+
x: types.Sequence,
|
|
401
|
+
*,
|
|
402
|
+
training: bool,
|
|
403
|
+
constants: types.Constants | None = None,
|
|
404
|
+
) -> types.Sequence:
|
|
405
|
+
del training
|
|
406
|
+
parameter = self._broadcast_parameter
|
|
407
|
+
self._validate(parameter, x.channel_shape)
|
|
408
|
+
assert isinstance(self.config.divisor, HashableArray)
|
|
409
|
+
return x.apply_values_masked(
|
|
410
|
+
lambda v: jnp.mod(v, parameter.astype(v.dtype))
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
class Minimum(StatelessPointwiseBroadcasting):
|
|
415
|
+
"""Clips the input with the provided minimum value."""
|
|
416
|
+
|
|
417
|
+
@dataclasses.dataclass(frozen=True, unsafe_hash=True)
|
|
418
|
+
class Config(types.SequenceLayerConfig):
|
|
419
|
+
"""Config for Minimum."""
|
|
420
|
+
|
|
421
|
+
# The value to clip the input with. May be a numpy array, but must be
|
|
422
|
+
# broadcastable to the channels dimension of the input. This value is cast
|
|
423
|
+
# to the dtype of the input, so the type of the input is preserved.
|
|
424
|
+
# PEP 484 says to use complex when you mean any numeric type.
|
|
425
|
+
minimum: complex | np.ndarray | HashableArray
|
|
426
|
+
name: str | None = None
|
|
427
|
+
|
|
428
|
+
def __post_init__(self):
|
|
429
|
+
object.__setattr__(
|
|
430
|
+
self, 'minimum', HashableArray.from_array(self.minimum)
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
def make(self) -> 'Minimum':
|
|
434
|
+
return Minimum(self, name=self.name)
|
|
435
|
+
|
|
436
|
+
config: Config
|
|
437
|
+
|
|
438
|
+
@property
|
|
439
|
+
def _broadcast_parameter(self) -> np.ndarray:
|
|
440
|
+
return _to_array(self.config.minimum)
|
|
441
|
+
|
|
442
|
+
@types.check_layer
|
|
443
|
+
def layer(
|
|
444
|
+
self,
|
|
445
|
+
x: types.Sequence,
|
|
446
|
+
*,
|
|
447
|
+
training: bool,
|
|
448
|
+
constants: types.Constants | None = None,
|
|
449
|
+
) -> types.Sequence:
|
|
450
|
+
del training
|
|
451
|
+
parameter = self._broadcast_parameter
|
|
452
|
+
self._validate(parameter, x.channel_shape)
|
|
453
|
+
assert isinstance(self.config.minimum, HashableArray)
|
|
454
|
+
return x.apply_values(lambda v: jnp.minimum(v, parameter.astype(v.dtype)))
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
class Abs(types.StatelessPointwiseFunctor):
|
|
458
|
+
"""Absolute value layer."""
|
|
459
|
+
|
|
460
|
+
@dataclasses.dataclass(frozen=True)
|
|
461
|
+
class Config(types.SequenceLayerConfig):
|
|
462
|
+
name: str | None = None
|
|
463
|
+
|
|
464
|
+
def make(self) -> 'Abs':
|
|
465
|
+
return Abs(self, name=self.name)
|
|
466
|
+
|
|
467
|
+
config: Config
|
|
468
|
+
|
|
469
|
+
@property
|
|
470
|
+
def mask_required(self):
|
|
471
|
+
return False
|
|
472
|
+
|
|
473
|
+
@nn.nowrap
|
|
474
|
+
def fn(
|
|
475
|
+
self,
|
|
476
|
+
values: types.ValuesT,
|
|
477
|
+
mask: types.MaskT,
|
|
478
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
479
|
+
return jnp.abs(values), mask
|
|
480
|
+
|
|
481
|
+
def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
|
|
482
|
+
# The absolute value of complex numbers is a real magnitude.
|
|
483
|
+
match input_dtype:
|
|
484
|
+
case jnp.complex64:
|
|
485
|
+
return jnp.float32
|
|
486
|
+
case jnp.complex128:
|
|
487
|
+
return jnp.float64
|
|
488
|
+
case _:
|
|
489
|
+
return input_dtype
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
class Cast(types.StatelessPointwiseFunctor):
|
|
493
|
+
"""Cast input values to the specified type."""
|
|
494
|
+
|
|
495
|
+
@dataclasses.dataclass(frozen=True)
|
|
496
|
+
class Config(types.SequenceLayerConfig):
|
|
497
|
+
dtype: types.DType
|
|
498
|
+
name: str | None = None
|
|
499
|
+
|
|
500
|
+
def make(self) -> 'Cast':
|
|
501
|
+
return Cast(self, name=self.name)
|
|
502
|
+
|
|
503
|
+
config: Config
|
|
504
|
+
|
|
505
|
+
@property
|
|
506
|
+
def mask_required(self):
|
|
507
|
+
return False
|
|
508
|
+
|
|
509
|
+
@nn.nowrap
|
|
510
|
+
def fn(
|
|
511
|
+
self,
|
|
512
|
+
values: types.ValuesT,
|
|
513
|
+
mask: types.MaskT,
|
|
514
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
515
|
+
return values.astype(self.config.dtype), mask
|
|
516
|
+
|
|
517
|
+
def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
|
|
518
|
+
return self.config.dtype
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
class GatedUnit(types.PreservesType, types.Stateless):
|
|
522
|
+
"""Computes a generalized Gated Unit, reducing the input channels by 2x."""
|
|
523
|
+
|
|
524
|
+
@dataclasses.dataclass(frozen=True)
|
|
525
|
+
class Config(types.SequenceLayerConfig):
|
|
526
|
+
feature_activation: Callable[[types.ValuesT], types.ValuesT] | None
|
|
527
|
+
gate_activation: Callable[[types.ValuesT], types.ValuesT] | None
|
|
528
|
+
name: str | None = None
|
|
529
|
+
|
|
530
|
+
def make(self) -> 'GatedUnit':
|
|
531
|
+
return GatedUnit(self, name=self.name)
|
|
532
|
+
|
|
533
|
+
config: Config
|
|
534
|
+
|
|
535
|
+
@types.check_layer
|
|
536
|
+
def layer(
|
|
537
|
+
self,
|
|
538
|
+
x: types.Sequence,
|
|
539
|
+
*,
|
|
540
|
+
training: bool,
|
|
541
|
+
constants: types.Constants | None = None,
|
|
542
|
+
) -> types.Sequence:
|
|
543
|
+
feature, gate = jnp.split(x.values, 2, axis=-1)
|
|
544
|
+
if self.config.feature_activation:
|
|
545
|
+
feature = self.config.feature_activation(feature)
|
|
546
|
+
if self.config.gate_activation:
|
|
547
|
+
gate = self.config.gate_activation(gate)
|
|
548
|
+
values = feature * gate
|
|
549
|
+
return types.Sequence(values, x.mask)
|
|
550
|
+
|
|
551
|
+
@nn.nowrap
|
|
552
|
+
def get_output_shape(
|
|
553
|
+
self,
|
|
554
|
+
input_shape: types.ShapeLike,
|
|
555
|
+
*,
|
|
556
|
+
constants: types.Constants | None = None,
|
|
557
|
+
) -> types.Shape:
|
|
558
|
+
channels = input_shape[-1]
|
|
559
|
+
if channels % 2 != 0:
|
|
560
|
+
raise ValueError(
|
|
561
|
+
f'Final dimension of input ({input_shape=}) to {self} must have an'
|
|
562
|
+
' even number of channels.'
|
|
563
|
+
)
|
|
564
|
+
return tuple(input_shape[:-1]) + (channels // 2,)
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
class GatedLinearUnit(GatedUnit):
|
|
568
|
+
"""Computes a Gated Linear Unit, reducing the input channels by 2x."""
|
|
569
|
+
|
|
570
|
+
@dataclasses.dataclass(frozen=True)
|
|
571
|
+
class Config(types.SequenceLayerConfig):
|
|
572
|
+
name: str | None = None
|
|
573
|
+
|
|
574
|
+
def make(self) -> 'GatedLinearUnit':
|
|
575
|
+
return GatedLinearUnit(
|
|
576
|
+
GatedUnit.Config(None, jax.nn.sigmoid, name=self.name), name=self.name
|
|
577
|
+
)
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
class GatedTanhUnit(GatedUnit):
|
|
581
|
+
"""Computes a Gated Tanh Unit, reducing the input channels by 2x."""
|
|
582
|
+
|
|
583
|
+
@dataclasses.dataclass(frozen=True)
|
|
584
|
+
class Config(types.SequenceLayerConfig):
|
|
585
|
+
name: str | None = None
|
|
586
|
+
|
|
587
|
+
def make(self) -> 'GatedTanhUnit':
|
|
588
|
+
return GatedTanhUnit(
|
|
589
|
+
GatedUnit.Config(jax.nn.tanh, jax.nn.sigmoid, name=self.name),
|
|
590
|
+
name=self.name,
|
|
591
|
+
)
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
class GradientClipping(types.PreservesType, types.StatelessPointwise):
|
|
595
|
+
"""Identity except the gradient is clipped."""
|
|
596
|
+
|
|
597
|
+
@dataclasses.dataclass(frozen=True)
|
|
598
|
+
class Config(types.SequenceLayerConfig):
|
|
599
|
+
clip_value: float
|
|
600
|
+
name: str | None = None
|
|
601
|
+
|
|
602
|
+
def make(self) -> 'GradientClipping':
|
|
603
|
+
assert self.clip_value > 0
|
|
604
|
+
return GradientClipping(self, name=self.name)
|
|
605
|
+
|
|
606
|
+
config: Config
|
|
607
|
+
|
|
608
|
+
@types.check_layer
|
|
609
|
+
def layer(
|
|
610
|
+
self,
|
|
611
|
+
x: types.Sequence,
|
|
612
|
+
*,
|
|
613
|
+
training: bool,
|
|
614
|
+
constants: types.Constants | None = None,
|
|
615
|
+
) -> types.Sequence:
|
|
616
|
+
del training
|
|
617
|
+
|
|
618
|
+
@jax.custom_gradient
|
|
619
|
+
def _clip_gradient(values):
|
|
620
|
+
def _custom_gradient(input_gradients):
|
|
621
|
+
return (
|
|
622
|
+
jnp.clip(
|
|
623
|
+
input_gradients,
|
|
624
|
+
-self.config.clip_value,
|
|
625
|
+
+self.config.clip_value,
|
|
626
|
+
),
|
|
627
|
+
)
|
|
628
|
+
|
|
629
|
+
return values, _custom_gradient
|
|
630
|
+
|
|
631
|
+
return x.apply_values_masked(_clip_gradient)
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
class Identity(types.PreservesType, types.StatelessPointwise):
|
|
635
|
+
"""Identity pass-through of the input."""
|
|
636
|
+
|
|
637
|
+
@dataclasses.dataclass(frozen=True)
|
|
638
|
+
class Config(types.SequenceLayerConfig):
|
|
639
|
+
name: str | None = None
|
|
640
|
+
|
|
641
|
+
def make(self) -> 'Identity':
|
|
642
|
+
return Identity(name=self.name)
|
|
643
|
+
|
|
644
|
+
@types.check_layer
|
|
645
|
+
def layer(
|
|
646
|
+
self,
|
|
647
|
+
x: types.Sequence,
|
|
648
|
+
*,
|
|
649
|
+
training: bool,
|
|
650
|
+
constants: types.Constants | None = None,
|
|
651
|
+
) -> types.Sequence:
|
|
652
|
+
del training
|
|
653
|
+
return x
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
class ApplySharding(types.PreservesType, types.StatelessPointwise):
|
|
657
|
+
"""Applies sharding annotations to the input sequence."""
|
|
658
|
+
|
|
659
|
+
@dataclasses.dataclass(frozen=True)
|
|
660
|
+
class Config(types.SequenceLayerConfig):
|
|
661
|
+
values_sharding: types.Sharding | None = None
|
|
662
|
+
mask_sharding: types.Sharding | None = None
|
|
663
|
+
name: str | None = None
|
|
664
|
+
|
|
665
|
+
def make(self) -> 'ApplySharding':
|
|
666
|
+
return ApplySharding(self, name=self.name)
|
|
667
|
+
|
|
668
|
+
config: Config
|
|
669
|
+
|
|
670
|
+
@types.check_layer
|
|
671
|
+
def layer(
|
|
672
|
+
self,
|
|
673
|
+
x: types.Sequence,
|
|
674
|
+
*,
|
|
675
|
+
training: bool,
|
|
676
|
+
constants: types.Constants | None = None,
|
|
677
|
+
) -> types.Sequence:
|
|
678
|
+
del training
|
|
679
|
+
|
|
680
|
+
# If only values sharding is provided, use the first two dimensions for the
|
|
681
|
+
# mask sharding.
|
|
682
|
+
values_sharding = self.config.values_sharding
|
|
683
|
+
mask_sharding = self.config.mask_sharding
|
|
684
|
+
if values_sharding and not mask_sharding:
|
|
685
|
+
mask_sharding = values_sharding[:2]
|
|
686
|
+
|
|
687
|
+
def shard_values_mask(values, mask):
|
|
688
|
+
values = sharding_lib.shard(values, values_sharding)
|
|
689
|
+
mask = sharding_lib.shard(mask, mask_sharding)
|
|
690
|
+
return values, mask
|
|
691
|
+
|
|
692
|
+
return x.apply_masked(shard_values_mask)
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
class OptimizationBarrier(types.PreservesType, types.StatelessPointwise):
|
|
696
|
+
"""Applies an optimization barrier to the input sequence."""
|
|
697
|
+
|
|
698
|
+
@dataclasses.dataclass(frozen=True)
|
|
699
|
+
class Config(types.SequenceLayerConfig):
|
|
700
|
+
apply_to_mask: bool = False
|
|
701
|
+
name: str | None = None
|
|
702
|
+
|
|
703
|
+
def make(self) -> 'OptimizationBarrier':
|
|
704
|
+
return OptimizationBarrier(self, name=self.name)
|
|
705
|
+
|
|
706
|
+
config: Config
|
|
707
|
+
|
|
708
|
+
@types.check_layer
|
|
709
|
+
def layer(
|
|
710
|
+
self,
|
|
711
|
+
x: types.Sequence,
|
|
712
|
+
*,
|
|
713
|
+
training: bool,
|
|
714
|
+
constants: types.Constants | None = None,
|
|
715
|
+
) -> types.Sequence:
|
|
716
|
+
del training
|
|
717
|
+
|
|
718
|
+
def shard_values_mask(values, mask):
|
|
719
|
+
values = jax.lax.optimization_barrier(values)
|
|
720
|
+
if self.config.apply_to_mask:
|
|
721
|
+
mask = jax.lax.optimization_barrier(mask)
|
|
722
|
+
return values, mask
|
|
723
|
+
|
|
724
|
+
return x.apply_masked(shard_values_mask)
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
class Lambda(types.Stateless):
|
|
728
|
+
"""A SequenceLayer that wraps a Python lambda function.
|
|
729
|
+
|
|
730
|
+
The wrapped lambda is assumed to be stateless. The receptive field of the
|
|
731
|
+
function in the time dimension should be 1 (i.e. no information crosses
|
|
732
|
+
timesteps). The function may change the shape and dtype of the input.
|
|
733
|
+
"""
|
|
734
|
+
|
|
735
|
+
@dataclasses.dataclass(frozen=True)
|
|
736
|
+
class Config(types.SequenceLayerConfig):
|
|
737
|
+
"""Configuration for a Lambda layer."""
|
|
738
|
+
|
|
739
|
+
# If sequence_input is True, a callable that takes an sl.Sequence and
|
|
740
|
+
# returns an sl.Sequence. If sequence_input is False, a callable that takes
|
|
741
|
+
# a jax.Array and returns a jax.Array. The function should be a pure,
|
|
742
|
+
# stateless function of the inputs and its receptive field should be 1.
|
|
743
|
+
fn: (
|
|
744
|
+
Callable[[jax.Array], jax.Array]
|
|
745
|
+
| Callable[[types.Sequence], types.Sequence]
|
|
746
|
+
)
|
|
747
|
+
# If true, the callable accepts and returns sequences.
|
|
748
|
+
sequence_input: bool = False
|
|
749
|
+
# If true, the output of fn is assumed to have potentially changed the
|
|
750
|
+
# masked status of its inputs.
|
|
751
|
+
mask_required: bool = True
|
|
752
|
+
# If get_output_shape or get_output_dtype are called, the input_spec to use
|
|
753
|
+
# for type or shape information (respectively). Prefer to use
|
|
754
|
+
# get_output_spec to avoid having to specify this.
|
|
755
|
+
expected_input_spec: types.ShapeDType | None = None
|
|
756
|
+
# An optional name for the layer.
|
|
757
|
+
name: str | None = None
|
|
758
|
+
|
|
759
|
+
def make(self) -> 'Lambda':
|
|
760
|
+
return Lambda(self, name=self.name)
|
|
761
|
+
|
|
762
|
+
config: Config
|
|
763
|
+
|
|
764
|
+
@property
|
|
765
|
+
def supports_step(self) -> bool:
|
|
766
|
+
return True
|
|
767
|
+
|
|
768
|
+
def _validate_input_spec(self, input_spec: types.ShapeDType) -> None:
|
|
769
|
+
del input_spec
|
|
770
|
+
# TODO(rryan): Re-enable when SoundStream works as expected with this
|
|
771
|
+
# (including the test).
|
|
772
|
+
# if (expected_input_spec := self.config.expected_input_spec) is not None:
|
|
773
|
+
# if (
|
|
774
|
+
# expected_input_spec.shape != input_spec.shape
|
|
775
|
+
# or expected_input_spec.dtype != input_spec.dtype
|
|
776
|
+
# ):
|
|
777
|
+
# raise ValueError(
|
|
778
|
+
# f'Input to Lambda layer ({input_spec=}) does not match expected'
|
|
779
|
+
# f' input spec {expected_input_spec=}'
|
|
780
|
+
# )
|
|
781
|
+
|
|
782
|
+
def get_output_spec(
|
|
783
|
+
self,
|
|
784
|
+
input_spec: types.ChannelSpec,
|
|
785
|
+
*,
|
|
786
|
+
constants: types.Constants | None = None,
|
|
787
|
+
) -> types.ChannelSpec:
|
|
788
|
+
self._validate_input_spec(input_spec)
|
|
789
|
+
if self.config.sequence_input:
|
|
790
|
+
input_spec = types.Sequence(
|
|
791
|
+
types.ShapeDType(
|
|
792
|
+
(1, 1) + tuple(input_spec.shape),
|
|
793
|
+
input_spec.dtype,
|
|
794
|
+
),
|
|
795
|
+
types.ShapeDType((1, 1), jnp.bool_),
|
|
796
|
+
)
|
|
797
|
+
else:
|
|
798
|
+
input_spec = types.ShapeDType(
|
|
799
|
+
(1, 1) + tuple(input_spec.shape),
|
|
800
|
+
input_spec.dtype,
|
|
801
|
+
)
|
|
802
|
+
output_spec = jax.eval_shape(self.config.fn, input_spec)
|
|
803
|
+
return jax.ShapeDtypeStruct(output_spec.shape[2:], output_spec.dtype)
|
|
804
|
+
|
|
805
|
+
@nn.nowrap
|
|
806
|
+
def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
|
|
807
|
+
# We don't know the input shape.
|
|
808
|
+
if self.config.expected_input_spec is None:
|
|
809
|
+
raise ValueError(
|
|
810
|
+
f'get_output_dtype requires expected_input_spec. {self.config=}'
|
|
811
|
+
)
|
|
812
|
+
return self.get_output_spec(
|
|
813
|
+
jax.ShapeDtypeStruct(
|
|
814
|
+
tuple(self.config.expected_input_spec.shape), input_dtype
|
|
815
|
+
)
|
|
816
|
+
).dtype
|
|
817
|
+
|
|
818
|
+
@nn.nowrap
|
|
819
|
+
def get_output_shape(
|
|
820
|
+
self,
|
|
821
|
+
input_shape: types.ShapeLike,
|
|
822
|
+
*,
|
|
823
|
+
constants: types.Constants | None = None,
|
|
824
|
+
) -> types.Shape:
|
|
825
|
+
# We don't know the input dtype.
|
|
826
|
+
if self.config.expected_input_spec is None:
|
|
827
|
+
raise ValueError(
|
|
828
|
+
f'get_output_shape requires expected_input_spec. {self.config=}'
|
|
829
|
+
)
|
|
830
|
+
return self.get_output_spec(
|
|
831
|
+
jax.ShapeDtypeStruct(
|
|
832
|
+
tuple(input_shape), self.config.expected_input_spec.dtype
|
|
833
|
+
)
|
|
834
|
+
).shape
|
|
835
|
+
|
|
836
|
+
@types.check_layer
|
|
837
|
+
def layer(
|
|
838
|
+
self,
|
|
839
|
+
x: types.Sequence,
|
|
840
|
+
*,
|
|
841
|
+
training: bool,
|
|
842
|
+
constants: types.Constants | None = None,
|
|
843
|
+
) -> types.Sequence:
|
|
844
|
+
self._validate_input_spec(x.channel_spec)
|
|
845
|
+
if self.config.sequence_input:
|
|
846
|
+
fn = typing.cast(
|
|
847
|
+
Callable[[types.Sequence], types.Sequence], self.config.fn
|
|
848
|
+
)
|
|
849
|
+
y = fn(x)
|
|
850
|
+
if y.shape[:2] != x.shape[:2]:
|
|
851
|
+
raise ValueError(
|
|
852
|
+
f'sl.Lambda function ({self.config.fn=}) should not change the'
|
|
853
|
+
f' batch or time shape of the input. fn({x.shape=}) -> {y.shape}'
|
|
854
|
+
)
|
|
855
|
+
else:
|
|
856
|
+
# TODO(b/325346885): Use apply_values/apply_values_masked when the pytype
|
|
857
|
+
# bug is resolved.
|
|
858
|
+
values = self.config.fn(x.values)
|
|
859
|
+
if values.shape[:2] != x.shape[:2]:
|
|
860
|
+
raise ValueError(
|
|
861
|
+
f'sl.Lambda function ({self.config.fn=}) should not change the'
|
|
862
|
+
f' batch or time shape of the input. fn({x.shape=}) ->'
|
|
863
|
+
f' {values.shape=}'
|
|
864
|
+
)
|
|
865
|
+
if self.config.mask_required:
|
|
866
|
+
y = types.Sequence(values, x.mask)
|
|
867
|
+
else:
|
|
868
|
+
y = type(x)(values, x.mask)
|
|
869
|
+
|
|
870
|
+
return y
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
class CheckpointName(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
874
|
+
"""Applies a checkpoint name to the sequence values."""
|
|
875
|
+
|
|
876
|
+
@dataclasses.dataclass(frozen=True)
|
|
877
|
+
class Config(types.SequenceLayerConfig):
|
|
878
|
+
checkpoint_name: str
|
|
879
|
+
name: str | None = None
|
|
880
|
+
|
|
881
|
+
def make(self) -> 'CheckpointName':
|
|
882
|
+
return CheckpointName(self, name=self.name)
|
|
883
|
+
|
|
884
|
+
config: Config
|
|
885
|
+
|
|
886
|
+
@property
|
|
887
|
+
def mask_required(self):
|
|
888
|
+
return False
|
|
889
|
+
|
|
890
|
+
@nn.nowrap
|
|
891
|
+
def fn(
|
|
892
|
+
self,
|
|
893
|
+
values: types.ValuesT,
|
|
894
|
+
mask: types.MaskT,
|
|
895
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
896
|
+
values = jax.ad_checkpoint.checkpoint_name(
|
|
897
|
+
values, self.config.checkpoint_name
|
|
898
|
+
)
|
|
899
|
+
return values, mask
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
class Tanh(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
903
|
+
"""A tanh layer."""
|
|
904
|
+
|
|
905
|
+
@dataclasses.dataclass(frozen=True)
|
|
906
|
+
class Config(types.SequenceLayerConfig):
|
|
907
|
+
name: str | None = None
|
|
908
|
+
|
|
909
|
+
def make(self) -> 'Tanh':
|
|
910
|
+
return Tanh(self, name=self.name)
|
|
911
|
+
|
|
912
|
+
config: Config
|
|
913
|
+
|
|
914
|
+
@property
|
|
915
|
+
def mask_required(self):
|
|
916
|
+
return False
|
|
917
|
+
|
|
918
|
+
@nn.nowrap
|
|
919
|
+
def fn(
|
|
920
|
+
self,
|
|
921
|
+
values: types.ValuesT,
|
|
922
|
+
mask: types.MaskT,
|
|
923
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
924
|
+
return jax.nn.tanh(values), mask
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
class Relu(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
928
|
+
"""A Relu layer."""
|
|
929
|
+
|
|
930
|
+
@dataclasses.dataclass(frozen=True)
|
|
931
|
+
class Config(types.SequenceLayerConfig):
|
|
932
|
+
name: str | None = None
|
|
933
|
+
|
|
934
|
+
def make(self) -> 'Relu':
|
|
935
|
+
return Relu(name=self.name)
|
|
936
|
+
|
|
937
|
+
@property
|
|
938
|
+
def mask_required(self):
|
|
939
|
+
return False
|
|
940
|
+
|
|
941
|
+
@nn.nowrap
|
|
942
|
+
def fn(
|
|
943
|
+
self,
|
|
944
|
+
values: types.ValuesT,
|
|
945
|
+
mask: types.MaskT,
|
|
946
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
947
|
+
return jax.nn.relu(values), mask
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
class LeakyRelu(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
951
|
+
"""A Leaky Relu layer."""
|
|
952
|
+
|
|
953
|
+
@dataclasses.dataclass(frozen=True)
|
|
954
|
+
class Config(types.SequenceLayerConfig):
|
|
955
|
+
negative_slope: complex = 0.01
|
|
956
|
+
name: str | None = None
|
|
957
|
+
|
|
958
|
+
def make(self) -> 'LeakyRelu':
|
|
959
|
+
return LeakyRelu(self, name=self.name)
|
|
960
|
+
|
|
961
|
+
config: Config
|
|
962
|
+
|
|
963
|
+
@property
|
|
964
|
+
def mask_required(self):
|
|
965
|
+
return False
|
|
966
|
+
|
|
967
|
+
@nn.nowrap
|
|
968
|
+
def fn(
|
|
969
|
+
self,
|
|
970
|
+
values: types.ValuesT,
|
|
971
|
+
mask: types.MaskT,
|
|
972
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
973
|
+
return jax.nn.leaky_relu(values, self.config.negative_slope), mask
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
class PRelu(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
977
|
+
"""Parametric Relu, i.e., a Leaky Relu where the negative slope is learnable."""
|
|
978
|
+
|
|
979
|
+
@dataclasses.dataclass(frozen=True)
|
|
980
|
+
class Config(types.SequenceLayerConfig):
|
|
981
|
+
negative_slope_init: float = 0.01
|
|
982
|
+
param_dtype: types.DType = jnp.float32
|
|
983
|
+
name: str | None = None
|
|
984
|
+
|
|
985
|
+
def make(self) -> 'PRelu':
|
|
986
|
+
return PRelu(self, name=self.name)
|
|
987
|
+
|
|
988
|
+
config: Config
|
|
989
|
+
|
|
990
|
+
def setup(self):
|
|
991
|
+
self.negative_slope = self.param(
|
|
992
|
+
'negative_slope',
|
|
993
|
+
lambda k: jnp.array(
|
|
994
|
+
self.config.negative_slope_init, self.config.param_dtype
|
|
995
|
+
),
|
|
996
|
+
)
|
|
997
|
+
|
|
998
|
+
@property
|
|
999
|
+
def mask_required(self) -> bool:
|
|
1000
|
+
return False
|
|
1001
|
+
|
|
1002
|
+
@nn.nowrap
|
|
1003
|
+
def fn(
|
|
1004
|
+
self,
|
|
1005
|
+
values: types.ValuesT,
|
|
1006
|
+
mask: types.MaskT,
|
|
1007
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
1008
|
+
|
|
1009
|
+
return (
|
|
1010
|
+
jnp.where(
|
|
1011
|
+
values >= 0,
|
|
1012
|
+
values,
|
|
1013
|
+
self.negative_slope.astype(values.dtype) * values,
|
|
1014
|
+
),
|
|
1015
|
+
mask,
|
|
1016
|
+
)
|
|
1017
|
+
|
|
1018
|
+
|
|
1019
|
+
class Elu(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
1020
|
+
"""An elu activation layer."""
|
|
1021
|
+
|
|
1022
|
+
@dataclasses.dataclass(frozen=True)
|
|
1023
|
+
class Config(types.SequenceLayerConfig):
|
|
1024
|
+
alpha: complex = 1.0
|
|
1025
|
+
name: str | None = None
|
|
1026
|
+
|
|
1027
|
+
def make(self) -> 'Elu':
|
|
1028
|
+
return Elu(self, name=self.name)
|
|
1029
|
+
|
|
1030
|
+
config: Config
|
|
1031
|
+
|
|
1032
|
+
@nn.nowrap
|
|
1033
|
+
def fn(
|
|
1034
|
+
self,
|
|
1035
|
+
values: types.ValuesT,
|
|
1036
|
+
mask: types.MaskT,
|
|
1037
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
1038
|
+
return jax.nn.elu(values, self.config.alpha), mask
|
|
1039
|
+
|
|
1040
|
+
|
|
1041
|
+
class Exp(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
1042
|
+
"""An exp layer."""
|
|
1043
|
+
|
|
1044
|
+
@dataclasses.dataclass(frozen=True)
|
|
1045
|
+
class Config(types.SequenceLayerConfig):
|
|
1046
|
+
name: str | None = None
|
|
1047
|
+
|
|
1048
|
+
def make(self) -> 'Exp':
|
|
1049
|
+
return Exp(self, name=self.name)
|
|
1050
|
+
|
|
1051
|
+
config: Config
|
|
1052
|
+
|
|
1053
|
+
@nn.nowrap
|
|
1054
|
+
def fn(
|
|
1055
|
+
self,
|
|
1056
|
+
values: types.ValuesT,
|
|
1057
|
+
mask: types.MaskT,
|
|
1058
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
1059
|
+
return jnp.exp(values), mask
|
|
1060
|
+
|
|
1061
|
+
|
|
1062
|
+
class Log(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
1063
|
+
"""A log layer."""
|
|
1064
|
+
|
|
1065
|
+
@dataclasses.dataclass(frozen=True)
|
|
1066
|
+
class Config(types.SequenceLayerConfig):
|
|
1067
|
+
name: str | None = None
|
|
1068
|
+
|
|
1069
|
+
def make(self) -> 'Log':
|
|
1070
|
+
return Log(self, name=self.name)
|
|
1071
|
+
|
|
1072
|
+
config: Config
|
|
1073
|
+
|
|
1074
|
+
@nn.nowrap
|
|
1075
|
+
def fn(
|
|
1076
|
+
self,
|
|
1077
|
+
values: types.ValuesT,
|
|
1078
|
+
mask: types.MaskT,
|
|
1079
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
1080
|
+
return jnp.log(values), mask
|
|
1081
|
+
|
|
1082
|
+
|
|
1083
|
+
class Power(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
1084
|
+
"""Raises the input to the specified power."""
|
|
1085
|
+
|
|
1086
|
+
@dataclasses.dataclass(frozen=True)
|
|
1087
|
+
class Config(types.SequenceLayerConfig):
|
|
1088
|
+
power: float = 1.0
|
|
1089
|
+
name: str | None = None
|
|
1090
|
+
|
|
1091
|
+
def make(self) -> 'Power':
|
|
1092
|
+
return Power(self, name=self.name)
|
|
1093
|
+
|
|
1094
|
+
config: Config
|
|
1095
|
+
|
|
1096
|
+
@property
|
|
1097
|
+
def mask_required(self):
|
|
1098
|
+
return False
|
|
1099
|
+
|
|
1100
|
+
@nn.nowrap
|
|
1101
|
+
def fn(
|
|
1102
|
+
self,
|
|
1103
|
+
values: types.ValuesT,
|
|
1104
|
+
mask: types.MaskT,
|
|
1105
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
1106
|
+
return jnp.power(values, self.config.power), mask
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
class Sigmoid(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
1110
|
+
"""A sigmoid layer."""
|
|
1111
|
+
|
|
1112
|
+
@dataclasses.dataclass(frozen=True)
|
|
1113
|
+
class Config(types.SequenceLayerConfig):
|
|
1114
|
+
name: str | None = None
|
|
1115
|
+
|
|
1116
|
+
def make(self) -> 'Sigmoid':
|
|
1117
|
+
return Sigmoid(self, name=self.name)
|
|
1118
|
+
|
|
1119
|
+
config: Config
|
|
1120
|
+
|
|
1121
|
+
@nn.nowrap
|
|
1122
|
+
def fn(
|
|
1123
|
+
self,
|
|
1124
|
+
values: types.ValuesT,
|
|
1125
|
+
mask: types.MaskT,
|
|
1126
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
1127
|
+
return jax.nn.sigmoid(values), mask
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
class Softplus(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
1131
|
+
"""A softplus layer."""
|
|
1132
|
+
|
|
1133
|
+
@dataclasses.dataclass(frozen=True)
|
|
1134
|
+
class Config(types.SequenceLayerConfig):
|
|
1135
|
+
name: str | None = None
|
|
1136
|
+
|
|
1137
|
+
def make(self) -> 'Softplus':
|
|
1138
|
+
return Softplus(self, name=self.name)
|
|
1139
|
+
|
|
1140
|
+
config: Config
|
|
1141
|
+
|
|
1142
|
+
@nn.nowrap
|
|
1143
|
+
def fn(
|
|
1144
|
+
self,
|
|
1145
|
+
values: types.ValuesT,
|
|
1146
|
+
mask: types.MaskT,
|
|
1147
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
1148
|
+
return jax.nn.softplus(values), mask
|
|
1149
|
+
|
|
1150
|
+
|
|
1151
|
+
class Softmax(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
1152
|
+
"""A softmax layer."""
|
|
1153
|
+
|
|
1154
|
+
@dataclasses.dataclass(frozen=True)
|
|
1155
|
+
class Config(types.SequenceLayerConfig):
|
|
1156
|
+
axis: int = -1
|
|
1157
|
+
name: str | None = None
|
|
1158
|
+
|
|
1159
|
+
def make(self) -> 'Softmax':
|
|
1160
|
+
return Softmax(self, name=self.name)
|
|
1161
|
+
|
|
1162
|
+
config: Config
|
|
1163
|
+
|
|
1164
|
+
@nn.nowrap
|
|
1165
|
+
def fn(
|
|
1166
|
+
self,
|
|
1167
|
+
values: types.ValuesT,
|
|
1168
|
+
mask: types.MaskT,
|
|
1169
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
1170
|
+
axis = self.config.axis
|
|
1171
|
+
if (axis if axis >= 0 else values.ndim + axis) < 2:
|
|
1172
|
+
raise ValueError(
|
|
1173
|
+
'The softmax cannot be applied on the batch or time dimension (got'
|
|
1174
|
+
f' {axis=} for shape={values.shape})'
|
|
1175
|
+
)
|
|
1176
|
+
return jax.nn.softmax(values, axis=axis), mask
|
|
1177
|
+
|
|
1178
|
+
|
|
1179
|
+
class Swish(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
1180
|
+
"""A Swish layer."""
|
|
1181
|
+
|
|
1182
|
+
@dataclasses.dataclass(frozen=True)
|
|
1183
|
+
class Config(types.SequenceLayerConfig):
|
|
1184
|
+
name: str | None = None
|
|
1185
|
+
|
|
1186
|
+
def make(self) -> 'Swish':
|
|
1187
|
+
return Swish(name=self.name)
|
|
1188
|
+
|
|
1189
|
+
@property
|
|
1190
|
+
def mask_required(self):
|
|
1191
|
+
return False
|
|
1192
|
+
|
|
1193
|
+
@nn.nowrap
|
|
1194
|
+
def fn(
|
|
1195
|
+
self,
|
|
1196
|
+
values: types.ValuesT,
|
|
1197
|
+
mask: types.MaskT,
|
|
1198
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
1199
|
+
return jax.nn.swish(values), mask
|
|
1200
|
+
|
|
1201
|
+
|
|
1202
|
+
class Gelu(types.PreservesType, types.StatelessPointwiseFunctor):
|
|
1203
|
+
"""A Gaussian Error Linear Unit (GELU) layer."""
|
|
1204
|
+
|
|
1205
|
+
@dataclasses.dataclass(frozen=True)
|
|
1206
|
+
class Config(types.SequenceLayerConfig):
|
|
1207
|
+
approximate: bool = True
|
|
1208
|
+
name: str | None = None
|
|
1209
|
+
|
|
1210
|
+
def make(self) -> 'Gelu':
|
|
1211
|
+
return Gelu(self, name=self.name)
|
|
1212
|
+
|
|
1213
|
+
config: Config
|
|
1214
|
+
|
|
1215
|
+
@property
|
|
1216
|
+
def mask_required(self):
|
|
1217
|
+
return False
|
|
1218
|
+
|
|
1219
|
+
@nn.nowrap
|
|
1220
|
+
def fn(
|
|
1221
|
+
self,
|
|
1222
|
+
values: types.ValuesT,
|
|
1223
|
+
mask: types.MaskT,
|
|
1224
|
+
) -> tuple[types.ValuesT, types.MaskT]:
|
|
1225
|
+
return jax.nn.gelu(values, approximate=self.config.approximate), mask
|
|
1226
|
+
|
|
1227
|
+
|
|
1228
|
+
class Slice(types.PreservesType, types.Stateless):
|
|
1229
|
+
"""Slices the channels dimensions of input tensors."""
|
|
1230
|
+
|
|
1231
|
+
@dataclasses.dataclass(frozen=True)
|
|
1232
|
+
class Config(types.SequenceLayerConfig):
|
|
1233
|
+
"""Config for Slice."""
|
|
1234
|
+
|
|
1235
|
+
# A slice to apply to each channel dimension of the input sequence. Follows
|
|
1236
|
+
# numpy strided-slice semantics:
|
|
1237
|
+
# - tuple[int | None, int | None, int | None]: An explicit
|
|
1238
|
+
# slice(start, stop, step) for the dimension.
|
|
1239
|
+
# - int: An index to slice.
|
|
1240
|
+
# - None: Insert a dimension at this position.
|
|
1241
|
+
# The number of non-None entries in slices must match the number of channel
|
|
1242
|
+
# dimensions.
|
|
1243
|
+
slices: TypingSequence[
|
|
1244
|
+
tuple[int | None, int | None, int | None] | int | None
|
|
1245
|
+
]
|
|
1246
|
+
name: str | None = None
|
|
1247
|
+
|
|
1248
|
+
def __post_init__(self):
|
|
1249
|
+
# Use hashable types for sequences.
|
|
1250
|
+
object.__setattr__(self, 'slices', tuple(self.slices))
|
|
1251
|
+
|
|
1252
|
+
def as_slices(self) -> tuple[slice | int | None]:
|
|
1253
|
+
return tuple(
|
|
1254
|
+
slice(*s) if isinstance(s, tuple) else s for s in self.slices
|
|
1255
|
+
)
|
|
1256
|
+
|
|
1257
|
+
def make(self) -> 'Slice':
|
|
1258
|
+
return Slice(self, name=self.name)
|
|
1259
|
+
|
|
1260
|
+
config: Config
|
|
1261
|
+
|
|
1262
|
+
def _validate_slice_for_input_shape(self, input_shape: types.ShapeLike):
|
|
1263
|
+
# None (jnp.newaxis) dimensions are expansions.
|
|
1264
|
+
non_none_dimensions = sum(1 for s in self.config.slices if s is not None)
|
|
1265
|
+
if non_none_dimensions != len(input_shape):
|
|
1266
|
+
raise ValueError(
|
|
1267
|
+
'Slice has wrong size for input: input_shape=%s slices=%s'
|
|
1268
|
+
% (input_shape, self.config.slices)
|
|
1269
|
+
)
|
|
1270
|
+
|
|
1271
|
+
def get_output_shape(
|
|
1272
|
+
self,
|
|
1273
|
+
input_shape: types.ShapeLike,
|
|
1274
|
+
*,
|
|
1275
|
+
constants: types.Constants | None = None,
|
|
1276
|
+
) -> types.Shape:
|
|
1277
|
+
self._validate_slice_for_input_shape(input_shape)
|
|
1278
|
+
output_dims = []
|
|
1279
|
+
input_index = 0
|
|
1280
|
+
|
|
1281
|
+
# Compute the output shape:
|
|
1282
|
+
# - int: Remove the current input dimension.
|
|
1283
|
+
# - slice: Compute the output dimension size using slice.indices.
|
|
1284
|
+
# - None (tf.newaxis): Add a dimension.
|
|
1285
|
+
for slice_i in self.config.slices:
|
|
1286
|
+
if isinstance(slice_i, tuple):
|
|
1287
|
+
slice_i = slice(*slice_i)
|
|
1288
|
+
# Use slice.indices(dim_size) to figure out the new length of the
|
|
1289
|
+
# dimension.
|
|
1290
|
+
output_dims.append(
|
|
1291
|
+
len(range(*slice_i.indices(input_shape[input_index])))
|
|
1292
|
+
)
|
|
1293
|
+
input_index += 1
|
|
1294
|
+
elif isinstance(slice_i, int):
|
|
1295
|
+
# Skip this input dimension.
|
|
1296
|
+
input_index += 1
|
|
1297
|
+
elif slice_i is None:
|
|
1298
|
+
# Add a dimension.
|
|
1299
|
+
output_dims.append(1)
|
|
1300
|
+
else:
|
|
1301
|
+
raise NotImplementedError(
|
|
1302
|
+
f'Unsupported slice type: {type(slice_i)}, {slice_i}'
|
|
1303
|
+
)
|
|
1304
|
+
return tuple(output_dims)
|
|
1305
|
+
|
|
1306
|
+
@types.check_layer
|
|
1307
|
+
def layer(
|
|
1308
|
+
self,
|
|
1309
|
+
x: types.Sequence,
|
|
1310
|
+
*,
|
|
1311
|
+
training: bool,
|
|
1312
|
+
constants: types.Constants | None = None,
|
|
1313
|
+
) -> types.Sequence:
|
|
1314
|
+
# Slice the batch and time dimensions with [:, :].
|
|
1315
|
+
full_slice = (
|
|
1316
|
+
slice(None, None, None),
|
|
1317
|
+
slice(None, None, None),
|
|
1318
|
+
) + self.config.as_slices()
|
|
1319
|
+
self._validate_slice_for_input_shape(x.channel_shape)
|
|
1320
|
+
# Masking status is unchanged by the slice.
|
|
1321
|
+
return x.apply_values_masked(lambda v: v.__getitem__(full_slice))
|
|
1322
|
+
|
|
1323
|
+
|
|
1324
|
+
class Flatten(types.PreservesType, types.Stateless):
|
|
1325
|
+
"""Flattens the channel dimensions of the input sequence.
|
|
1326
|
+
|
|
1327
|
+
An input sequence with shape [batch_size, time, ...] is reshaped to
|
|
1328
|
+
[batch_size, time, prod(...)]. The mask is unchanged.
|
|
1329
|
+
"""
|
|
1330
|
+
|
|
1331
|
+
@dataclasses.dataclass(frozen=True)
|
|
1332
|
+
class Config(types.SequenceLayerConfig):
|
|
1333
|
+
name: str | None = None
|
|
1334
|
+
|
|
1335
|
+
def make(self) -> 'Flatten':
|
|
1336
|
+
return Flatten(name=self.name)
|
|
1337
|
+
|
|
1338
|
+
@nn.nowrap
|
|
1339
|
+
def get_output_shape(
|
|
1340
|
+
self,
|
|
1341
|
+
input_shape: types.ShapeLike,
|
|
1342
|
+
*,
|
|
1343
|
+
constants: types.Constants | None = None,
|
|
1344
|
+
) -> types.Shape:
|
|
1345
|
+
del constants
|
|
1346
|
+
return (np.prod(input_shape),)
|
|
1347
|
+
|
|
1348
|
+
@types.check_layer
|
|
1349
|
+
def layer(
|
|
1350
|
+
self,
|
|
1351
|
+
x: types.Sequence,
|
|
1352
|
+
*,
|
|
1353
|
+
training: bool,
|
|
1354
|
+
constants: types.Constants | None = None,
|
|
1355
|
+
) -> types.Sequence:
|
|
1356
|
+
del training
|
|
1357
|
+
batch_size, time = x.values.shape[:2]
|
|
1358
|
+
num_elements = np.prod(x.channel_shape)
|
|
1359
|
+
return x.apply_values_masked(jnp.reshape, [batch_size, time, num_elements])
|
|
1360
|
+
|
|
1361
|
+
|
|
1362
|
+
class OneHot(types.Stateless):
|
|
1363
|
+
"""Computes one-hot vector of the input."""
|
|
1364
|
+
|
|
1365
|
+
@dataclasses.dataclass(frozen=True)
|
|
1366
|
+
class Config(types.SequenceLayerConfig):
|
|
1367
|
+
depth: int
|
|
1368
|
+
compute_dtype: types.DType = jnp.float32
|
|
1369
|
+
name: str | None = None
|
|
1370
|
+
|
|
1371
|
+
def make(self) -> 'OneHot':
|
|
1372
|
+
return OneHot(self, name=self.name)
|
|
1373
|
+
|
|
1374
|
+
config: Config
|
|
1375
|
+
|
|
1376
|
+
@nn.nowrap
|
|
1377
|
+
def _validate(self, dtype: types.DType):
|
|
1378
|
+
if not jnp.issubdtype(dtype, jnp.integer):
|
|
1379
|
+
raise ValueError(
|
|
1380
|
+
'Input to OneHot must be an integer or unsigned integer. Got:'
|
|
1381
|
+
f' {dtype}'
|
|
1382
|
+
)
|
|
1383
|
+
|
|
1384
|
+
@nn.nowrap
|
|
1385
|
+
def get_output_shape(
|
|
1386
|
+
self,
|
|
1387
|
+
input_shape: types.ShapeLike,
|
|
1388
|
+
*,
|
|
1389
|
+
constants: types.Constants | None = None,
|
|
1390
|
+
) -> types.Shape:
|
|
1391
|
+
return tuple(input_shape) + (self.config.depth,)
|
|
1392
|
+
|
|
1393
|
+
@nn.nowrap
|
|
1394
|
+
def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
|
|
1395
|
+
self._validate(input_dtype)
|
|
1396
|
+
return self.config.compute_dtype
|
|
1397
|
+
|
|
1398
|
+
@types.check_layer
|
|
1399
|
+
def layer(
|
|
1400
|
+
self,
|
|
1401
|
+
x: types.Sequence,
|
|
1402
|
+
*,
|
|
1403
|
+
training: bool,
|
|
1404
|
+
constants: types.Constants | None = None,
|
|
1405
|
+
) -> types.Sequence:
|
|
1406
|
+
del training
|
|
1407
|
+
self._validate(x.dtype)
|
|
1408
|
+
# "0" is mapped to "[1] + [0] * (depth - 1)", so mask status is not
|
|
1409
|
+
# preserved.
|
|
1410
|
+
return x.apply_values(
|
|
1411
|
+
lambda v: jax.nn.one_hot(
|
|
1412
|
+
v, self.config.depth, dtype=self.config.compute_dtype
|
|
1413
|
+
)
|
|
1414
|
+
)
|
|
1415
|
+
|
|
1416
|
+
|
|
1417
|
+
class Embedding(types.Stateless):
|
|
1418
|
+
"""Computes embeddings of integer input codes."""
|
|
1419
|
+
|
|
1420
|
+
@dataclasses.dataclass(frozen=True)
|
|
1421
|
+
class Config(types.SequenceLayerConfig):
|
|
1422
|
+
"""Config for Embedding."""
|
|
1423
|
+
|
|
1424
|
+
# Dimensionality of the embedded values.
|
|
1425
|
+
dimension: int
|
|
1426
|
+
# The number of embeddings in the embedding table. Inputs are expected to be
|
|
1427
|
+
# in the range [0, num_embeddings).
|
|
1428
|
+
num_embeddings: int
|
|
1429
|
+
# The dtype of the embeddings output by the layer.
|
|
1430
|
+
compute_dtype: types.DType | None = None
|
|
1431
|
+
# The dtype to use for layer parameters.
|
|
1432
|
+
param_dtype: types.DType = jnp.float32
|
|
1433
|
+
# By default, initialize embeddings to have a norm of 1.
|
|
1434
|
+
embedding_init: nn.initializers.Initializer = nn.linear.default_embed_init
|
|
1435
|
+
# Optional sharding for the embedding table.
|
|
1436
|
+
embedding_sharding: types.Sharding | None = None
|
|
1437
|
+
# Optional name for the layer.
|
|
1438
|
+
name: str | None = None
|
|
1439
|
+
|
|
1440
|
+
def make(self) -> 'Embedding':
|
|
1441
|
+
return Embedding(self, name=self.name)
|
|
1442
|
+
|
|
1443
|
+
config: Config
|
|
1444
|
+
|
|
1445
|
+
def setup(self):
|
|
1446
|
+
self.embedding = self.param(
|
|
1447
|
+
'embedding',
|
|
1448
|
+
utils.shard_initializer(
|
|
1449
|
+
self.config.embedding_init, self.config.embedding_sharding
|
|
1450
|
+
),
|
|
1451
|
+
(self.config.num_embeddings, self.config.dimension),
|
|
1452
|
+
self.config.param_dtype,
|
|
1453
|
+
)
|
|
1454
|
+
|
|
1455
|
+
@nn.nowrap
|
|
1456
|
+
def _validate(self, dtype: types.DType):
|
|
1457
|
+
if not jnp.issubdtype(dtype, jnp.integer):
|
|
1458
|
+
raise ValueError(
|
|
1459
|
+
'Input to Embedding must be an integer or unsigned integer, got:'
|
|
1460
|
+
f' {dtype}'
|
|
1461
|
+
)
|
|
1462
|
+
|
|
1463
|
+
@nn.nowrap
|
|
1464
|
+
def get_output_shape(
|
|
1465
|
+
self,
|
|
1466
|
+
input_shape: types.ShapeLike,
|
|
1467
|
+
*,
|
|
1468
|
+
constants: types.Constants | None = None,
|
|
1469
|
+
) -> types.Shape:
|
|
1470
|
+
return tuple(input_shape) + (self.config.dimension,)
|
|
1471
|
+
|
|
1472
|
+
@nn.nowrap
|
|
1473
|
+
def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
|
|
1474
|
+
self._validate(input_dtype)
|
|
1475
|
+
if self.config.compute_dtype is None:
|
|
1476
|
+
return self.config.param_dtype
|
|
1477
|
+
return self.config.compute_dtype
|
|
1478
|
+
|
|
1479
|
+
@types.check_layer
|
|
1480
|
+
def layer(
|
|
1481
|
+
self,
|
|
1482
|
+
x: types.Sequence,
|
|
1483
|
+
*,
|
|
1484
|
+
training: bool,
|
|
1485
|
+
constants: types.Constants | None = None,
|
|
1486
|
+
) -> types.Sequence:
|
|
1487
|
+
self._validate(x.dtype)
|
|
1488
|
+
embedding = self.embedding
|
|
1489
|
+
(embedding,) = nn.dtypes.promote_dtype(
|
|
1490
|
+
embedding, dtype=self.config.compute_dtype, inexact=False
|
|
1491
|
+
)
|
|
1492
|
+
return x.apply_values(lambda v: jnp.take(embedding, v, axis=0))
|
|
1493
|
+
|
|
1494
|
+
def attend(
|
|
1495
|
+
self,
|
|
1496
|
+
x: types.Sequence,
|
|
1497
|
+
embedding_dtype: types.DType | None = None,
|
|
1498
|
+
compute_dtype: types.DType | None = None,
|
|
1499
|
+
) -> types.Sequence:
|
|
1500
|
+
"""Attend over the embedding using a query array.
|
|
1501
|
+
|
|
1502
|
+
Args:
|
|
1503
|
+
x: Sequence whose last dimension's size is equal to ``dimension`` of the
|
|
1504
|
+
embedding.
|
|
1505
|
+
embedding_dtype: Optionally override the Embedding parameters' dtype. Used
|
|
1506
|
+
by containers like EmbeddingTranspose that call attend(), to achieve
|
|
1507
|
+
behavior consistent with their dtype settings.
|
|
1508
|
+
compute_dtype: Optionally overrides Embedding.dtype for computation.
|
|
1509
|
+
Useful for e.g. computing logits with a upcast dtype.
|
|
1510
|
+
|
|
1511
|
+
Returns:
|
|
1512
|
+
A Sequence with final dim ``num_embeddings`` corresponding to the batched
|
|
1513
|
+
inner-product of the array of query vectors against each embedding.
|
|
1514
|
+
Commonly used for weight-sharing between embeddings and logit transform
|
|
1515
|
+
in NLP models.
|
|
1516
|
+
|
|
1517
|
+
Raises:
|
|
1518
|
+
ValueError: Input query does not have a channel dimension (i.e., 0-dim).
|
|
1519
|
+
"""
|
|
1520
|
+
if not x.channel_shape:
|
|
1521
|
+
raise ValueError('Input query must have a channel dimension.')
|
|
1522
|
+
values = x.values
|
|
1523
|
+
embedding = (
|
|
1524
|
+
self.embedding.astype(embedding_dtype)
|
|
1525
|
+
if embedding_dtype
|
|
1526
|
+
else self.embedding
|
|
1527
|
+
)
|
|
1528
|
+
values, embedding = nn.dtypes.promote_dtype(
|
|
1529
|
+
values, embedding, dtype=(compute_dtype or self.config.compute_dtype)
|
|
1530
|
+
)
|
|
1531
|
+
return type(x)(jnp.dot(values, embedding.T), x.mask)
|
|
1532
|
+
|
|
1533
|
+
|
|
1534
|
+
class EmbeddingTranspose(types.Stateless):
|
|
1535
|
+
"""Wraps a bound Embedding layer to be attended upon (e.g. pre-softmax)."""
|
|
1536
|
+
|
|
1537
|
+
@dataclasses.dataclass(frozen=True)
|
|
1538
|
+
class Config(types.SequenceLayerConfig):
|
|
1539
|
+
"""Config for EmbeddingTranspose."""
|
|
1540
|
+
|
|
1541
|
+
# Embedding layer to allow weight sharing. If not weight sharing, prefer to
|
|
1542
|
+
# use Embedding directly instead of wrapping it with EmbeddingTranspose.
|
|
1543
|
+
embedding: Embedding
|
|
1544
|
+
|
|
1545
|
+
# Whether to use a bias, with shape imputed from `output_shape`.
|
|
1546
|
+
use_bias: bool = True
|
|
1547
|
+
# Initializer for the bias.
|
|
1548
|
+
bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
|
|
1549
|
+
# Optional sharding for the bias.
|
|
1550
|
+
bias_sharding: types.Sharding = None
|
|
1551
|
+
|
|
1552
|
+
# The dtype for layer compute; if set, overrides embedding's dtype.
|
|
1553
|
+
compute_dtype: types.DType | None = None
|
|
1554
|
+
# The dtype for layer parameters; if set, overrides embedding's param_dtype.
|
|
1555
|
+
param_dtype: types.DType | None = None
|
|
1556
|
+
# Optional name for the layer.
|
|
1557
|
+
name: str | None = None
|
|
1558
|
+
|
|
1559
|
+
@override
|
|
1560
|
+
def make(self) -> 'EmbeddingTranspose':
|
|
1561
|
+
return EmbeddingTranspose(self, name=self.name)
|
|
1562
|
+
|
|
1563
|
+
config: Config
|
|
1564
|
+
|
|
1565
|
+
@override
|
|
1566
|
+
def setup(self):
|
|
1567
|
+
# Bind the Embedding as a submodule. If it is not already parented, this
|
|
1568
|
+
# also ensures that Embedding is initialized alongside this layer.
|
|
1569
|
+
self.embedding = self.config.embedding
|
|
1570
|
+
|
|
1571
|
+
@override
|
|
1572
|
+
@nn.nowrap
|
|
1573
|
+
def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
|
|
1574
|
+
return utils.get_promoted_dtype(
|
|
1575
|
+
input_dtype,
|
|
1576
|
+
self.config.param_dtype or self.embedding.config.param_dtype,
|
|
1577
|
+
dtype=self.config.compute_dtype or self.embedding.config.compute_dtype,
|
|
1578
|
+
)
|
|
1579
|
+
|
|
1580
|
+
@override
|
|
1581
|
+
@nn.nowrap
|
|
1582
|
+
def get_output_shape(
|
|
1583
|
+
self,
|
|
1584
|
+
input_shape: types.ShapeLike,
|
|
1585
|
+
*,
|
|
1586
|
+
constants: types.Constants | None = None,
|
|
1587
|
+
) -> types.Shape:
|
|
1588
|
+
if (
|
|
1589
|
+
not input_shape
|
|
1590
|
+
or input_shape[-1] != self.config.embedding.config.dimension
|
|
1591
|
+
):
|
|
1592
|
+
raise ValueError(
|
|
1593
|
+
"Input query's final channel dimension must be equal to the embedding"
|
|
1594
|
+
' dimension.'
|
|
1595
|
+
)
|
|
1596
|
+
return (*input_shape[:-1], self.config.embedding.config.num_embeddings)
|
|
1597
|
+
|
|
1598
|
+
@override
|
|
1599
|
+
@types.check_layer
|
|
1600
|
+
@nn.compact
|
|
1601
|
+
def layer(
|
|
1602
|
+
self,
|
|
1603
|
+
x: types.Sequence,
|
|
1604
|
+
training: bool,
|
|
1605
|
+
constants: types.Constants | None = None,
|
|
1606
|
+
) -> types.Sequence:
|
|
1607
|
+
del training, constants
|
|
1608
|
+
|
|
1609
|
+
if self.config.use_bias:
|
|
1610
|
+
bias_init = utils.shard_initializer(
|
|
1611
|
+
self.config.bias_init, self.config.bias_sharding
|
|
1612
|
+
)
|
|
1613
|
+
bias = self.param(
|
|
1614
|
+
'bias',
|
|
1615
|
+
bias_init,
|
|
1616
|
+
(self.embedding.config.num_embeddings,),
|
|
1617
|
+
self.config.param_dtype or self.embedding.config.param_dtype,
|
|
1618
|
+
)
|
|
1619
|
+
else:
|
|
1620
|
+
bias = None
|
|
1621
|
+
|
|
1622
|
+
ret = self.embedding.attend(
|
|
1623
|
+
x,
|
|
1624
|
+
compute_dtype=self.config.compute_dtype,
|
|
1625
|
+
embedding_dtype=self.config.param_dtype,
|
|
1626
|
+
)
|
|
1627
|
+
if bias is not None:
|
|
1628
|
+
ret = ret.apply_values(lambda x: utils.bias_add(x, bias.astype(x.dtype)))
|
|
1629
|
+
|
|
1630
|
+
return ret
|
|
1631
|
+
|
|
1632
|
+
|
|
1633
|
+
class ExpandDims(types.PreservesType, types.Stateless):
|
|
1634
|
+
"""Applies jnp.expand_dims to the channels dimension of the input."""
|
|
1635
|
+
|
|
1636
|
+
@dataclasses.dataclass(frozen=True)
|
|
1637
|
+
class Config(types.SequenceLayerConfig):
|
|
1638
|
+
"""Configuration for ExpandDims."""
|
|
1639
|
+
|
|
1640
|
+
# The axis or axes in the channel shape to expand dims on.
|
|
1641
|
+
# For example, axis (0, -2) maps [b, t, c, d] to [b, t, 1, c, 1, d].
|
|
1642
|
+
axis: int | TypingSequence[int]
|
|
1643
|
+
# An optional name for the layer.
|
|
1644
|
+
name: str | None = None
|
|
1645
|
+
|
|
1646
|
+
def __post_init__(self):
|
|
1647
|
+
# Use hashable types for sequences.
|
|
1648
|
+
if not isinstance(self.axis, int):
|
|
1649
|
+
object.__setattr__(self, 'axis', tuple(self.axis))
|
|
1650
|
+
|
|
1651
|
+
def make(self) -> 'ExpandDims':
|
|
1652
|
+
return ExpandDims(self, name=self.name)
|
|
1653
|
+
|
|
1654
|
+
config: Config
|
|
1655
|
+
|
|
1656
|
+
@nn.nowrap
|
|
1657
|
+
def _normalize_and_validate_axes(
|
|
1658
|
+
self, input_shape: types.ShapeLike
|
|
1659
|
+
) -> list[int]:
|
|
1660
|
+
rank = len(input_shape)
|
|
1661
|
+
axis = self.config.axis
|
|
1662
|
+
if isinstance(axis, int):
|
|
1663
|
+
axis = [axis]
|
|
1664
|
+
|
|
1665
|
+
# Negative axes refer to one past their normal index.
|
|
1666
|
+
dims = [a + rank + 1 if a < 0 else a for a in axis]
|
|
1667
|
+
dims = sorted(set(dims))
|
|
1668
|
+
for dim in dims:
|
|
1669
|
+
if dim < 0 or dim > rank:
|
|
1670
|
+
raise ValueError(
|
|
1671
|
+
'ExpandDims axes must all refer to channels dimensions. Got:'
|
|
1672
|
+
f' {self.config.axis}.'
|
|
1673
|
+
)
|
|
1674
|
+
return dims
|
|
1675
|
+
|
|
1676
|
+
@nn.nowrap
|
|
1677
|
+
def get_output_shape(
|
|
1678
|
+
self,
|
|
1679
|
+
input_shape: types.ShapeLike,
|
|
1680
|
+
*,
|
|
1681
|
+
constants: types.Constants | None = None,
|
|
1682
|
+
) -> types.Shape:
|
|
1683
|
+
del constants
|
|
1684
|
+
dims = self._normalize_and_validate_axes(input_shape)
|
|
1685
|
+
output_shape = list(input_shape)
|
|
1686
|
+
for a in dims:
|
|
1687
|
+
output_shape.insert(a, 1)
|
|
1688
|
+
return tuple(output_shape)
|
|
1689
|
+
|
|
1690
|
+
@types.check_layer
|
|
1691
|
+
def layer(
|
|
1692
|
+
self,
|
|
1693
|
+
x: types.Sequence,
|
|
1694
|
+
*,
|
|
1695
|
+
training: bool,
|
|
1696
|
+
constants: types.Constants | None = None,
|
|
1697
|
+
) -> types.Sequence:
|
|
1698
|
+
del training
|
|
1699
|
+
dims = [2 + d for d in self._normalize_and_validate_axes(x.channel_shape)]
|
|
1700
|
+
return x.apply_values_masked(jnp.expand_dims, dims)
|
|
1701
|
+
|
|
1702
|
+
|
|
1703
|
+
class Reshape(types.PreservesType, types.Stateless):
|
|
1704
|
+
"""Reshapes the channels dimension of the input."""
|
|
1705
|
+
|
|
1706
|
+
@dataclasses.dataclass(frozen=True)
|
|
1707
|
+
class Config(types.SequenceLayerConfig):
|
|
1708
|
+
"""Configuration for Reshape."""
|
|
1709
|
+
|
|
1710
|
+
# The new shape of the channels dimension. Can't contain -1, and must have
|
|
1711
|
+
# the same number of elements as the input channels shape.
|
|
1712
|
+
output_shape: TypingSequence[int]
|
|
1713
|
+
# An optional name for the layer.
|
|
1714
|
+
name: str | None = None
|
|
1715
|
+
|
|
1716
|
+
def __post_init__(self):
|
|
1717
|
+
# Use hashable types for sequences.
|
|
1718
|
+
object.__setattr__(self, 'output_shape', tuple(self.output_shape))
|
|
1719
|
+
|
|
1720
|
+
def make(self) -> 'Reshape':
|
|
1721
|
+
return Reshape(self, name=self.name)
|
|
1722
|
+
|
|
1723
|
+
config: Config
|
|
1724
|
+
|
|
1725
|
+
def _validate_output_shape(self, input_shape: types.ShapeLike) -> None:
|
|
1726
|
+
input_elements = np.prod(input_shape)
|
|
1727
|
+
output_elements = np.prod(self.config.output_shape)
|
|
1728
|
+
if input_elements != output_elements:
|
|
1729
|
+
raise ValueError(
|
|
1730
|
+
f'Reshape output_shape={self.config.output_shape} must have the same'
|
|
1731
|
+
f' number of elements as {input_shape=}.'
|
|
1732
|
+
)
|
|
1733
|
+
|
|
1734
|
+
@nn.nowrap
|
|
1735
|
+
def get_output_shape(
|
|
1736
|
+
self,
|
|
1737
|
+
input_shape: types.ShapeLike,
|
|
1738
|
+
*,
|
|
1739
|
+
constants: types.Constants | None = None,
|
|
1740
|
+
) -> types.Shape:
|
|
1741
|
+
del constants
|
|
1742
|
+
self._validate_output_shape(input_shape)
|
|
1743
|
+
return tuple(self.config.output_shape)
|
|
1744
|
+
|
|
1745
|
+
@types.check_layer
|
|
1746
|
+
def layer(
|
|
1747
|
+
self,
|
|
1748
|
+
x: types.Sequence,
|
|
1749
|
+
*,
|
|
1750
|
+
training: bool,
|
|
1751
|
+
constants: types.Constants | None = None,
|
|
1752
|
+
) -> types.Sequence:
|
|
1753
|
+
self._validate_output_shape(x.channel_shape)
|
|
1754
|
+
return x.apply_values_masked(
|
|
1755
|
+
lambda v: jnp.reshape(v, v.shape[:2] + self.config.output_shape)
|
|
1756
|
+
)
|
|
1757
|
+
|
|
1758
|
+
|
|
1759
|
+
class GlobalReshape(types.PreservesType, types.Stateless):
|
|
1760
|
+
"""Reshapes the time and channel dimensions of the input sequence globally.
|
|
1761
|
+
|
|
1762
|
+
This layer reshapes inputs of shape [batch_size, time_in, *channel_shape_in]
|
|
1763
|
+
to outputs of shape `[batch_size, *output_shape]`. The total number of
|
|
1764
|
+
elements across the time and channel dimensions must remain constant.
|
|
1765
|
+
|
|
1766
|
+
Examples:
|
|
1767
|
+
* shape = [4, 3, 6], tensor shape [8, 6, 2, 6], output shape is [8, 4, 3, 6]
|
|
1768
|
+
* shape = [12, 6], tensor shape [8, 6, 2, 6], output shape is [8, 12, 6]
|
|
1769
|
+
* shape = [4, 18], tensor shape [8, 6, 2, 6], output shape is [8, 4, 18]
|
|
1770
|
+
|
|
1771
|
+
Important notes:
|
|
1772
|
+
* A timestep in the output is valid (mask=True) only if *all* values that were
|
|
1773
|
+
reshaped into that timestep came from a valid timestep in the input.
|
|
1774
|
+
* Because this operation depends on the full time dimension of the input,
|
|
1775
|
+
it is neither padding invariant nor streamable (`supports_step` is False).
|
|
1776
|
+
"""
|
|
1777
|
+
|
|
1778
|
+
@dataclasses.dataclass(frozen=True)
|
|
1779
|
+
class Config(types.SequenceLayerConfig):
|
|
1780
|
+
"""Configuration for GlobalReshape."""
|
|
1781
|
+
|
|
1782
|
+
# The desired [new_time, *new_channels] shape *after* the batch dimension.
|
|
1783
|
+
# Can't contain -1, and the product of elements in output_shape must equal
|
|
1784
|
+
# the product of the input time and channel dimensions.
|
|
1785
|
+
output_shape: TypingSequence[int]
|
|
1786
|
+
# An optional name for the layer.
|
|
1787
|
+
name: str | None = None
|
|
1788
|
+
|
|
1789
|
+
def __post_init__(self):
|
|
1790
|
+
# Use hashable types for sequences.
|
|
1791
|
+
object.__setattr__(self, 'output_shape', tuple(self.output_shape))
|
|
1792
|
+
|
|
1793
|
+
def make(self) -> 'GlobalReshape':
|
|
1794
|
+
return GlobalReshape(self, name=self.name)
|
|
1795
|
+
|
|
1796
|
+
config: Config
|
|
1797
|
+
|
|
1798
|
+
def _validate_reshape(self, input_shape: types.ShapeLike) -> None:
|
|
1799
|
+
input_elements = np.prod(input_shape)
|
|
1800
|
+
output_elements = np.prod(self.config.output_shape)
|
|
1801
|
+
if input_elements != output_elements:
|
|
1802
|
+
raise ValueError(
|
|
1803
|
+
f'{self.config.output_shape=} must have the same number of '
|
|
1804
|
+
f'elements as {input_shape=}.'
|
|
1805
|
+
)
|
|
1806
|
+
|
|
1807
|
+
@nn.nowrap
|
|
1808
|
+
def get_output_shape(
|
|
1809
|
+
self,
|
|
1810
|
+
input_shape: types.ShapeLike,
|
|
1811
|
+
*,
|
|
1812
|
+
constants: types.Constants | None = None,
|
|
1813
|
+
) -> types.Shape:
|
|
1814
|
+
del constants
|
|
1815
|
+
return tuple(self.config.output_shape[1:])
|
|
1816
|
+
|
|
1817
|
+
@property
|
|
1818
|
+
def supports_step(self) -> bool:
|
|
1819
|
+
return False
|
|
1820
|
+
|
|
1821
|
+
@property
|
|
1822
|
+
def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
|
|
1823
|
+
return {0: (-np.inf, np.inf)}
|
|
1824
|
+
|
|
1825
|
+
@types.check_layer
|
|
1826
|
+
def layer(
|
|
1827
|
+
self,
|
|
1828
|
+
x: types.Sequence,
|
|
1829
|
+
*,
|
|
1830
|
+
training: bool,
|
|
1831
|
+
constants: types.Constants | None = None,
|
|
1832
|
+
) -> types.Sequence:
|
|
1833
|
+
|
|
1834
|
+
self._validate_reshape(x.shape[1:])
|
|
1835
|
+
|
|
1836
|
+
# Perform reshape across time and channels.
|
|
1837
|
+
out_shape = (x.shape[0],) + tuple(self.config.output_shape)
|
|
1838
|
+
out = jnp.reshape(x.values, out_shape)
|
|
1839
|
+
# Since output_time can be {=, >, <} input_time, we may be splitting or
|
|
1840
|
+
# joining input timesteps into the reshaped output. This means we need to
|
|
1841
|
+
# carefully calculate the output mask:
|
|
1842
|
+
# 1. Broadcast the mask to the full input shape, and then reshape it to the
|
|
1843
|
+
# output shape.
|
|
1844
|
+
mask = jnp.reshape(x.mask, x.shape[:2] + (1,) * len(x.channel_shape))
|
|
1845
|
+
mask = jnp.broadcast_to(mask, x.shape)
|
|
1846
|
+
# 2. Reshape the mask to the output shape, and then call jnp.all to ensure
|
|
1847
|
+
# that any timestep with *any* invalid input is invalid in the output).
|
|
1848
|
+
mask = jnp.reshape(mask, out_shape)
|
|
1849
|
+
mask = jnp.all(mask, axis=range(2, mask.ndim))
|
|
1850
|
+
return types.Sequence(out, mask=mask)
|
|
1851
|
+
|
|
1852
|
+
|
|
1853
|
+
class Transpose(types.PreservesType, types.Stateless):
|
|
1854
|
+
"""Transposes (i.e., permutes) the channels dimension of the input."""
|
|
1855
|
+
|
|
1856
|
+
@dataclasses.dataclass(frozen=True)
|
|
1857
|
+
class Config(types.SequenceLayerConfig):
|
|
1858
|
+
"""Configuration for Transpose.
|
|
1859
|
+
|
|
1860
|
+
The usage is the same as that of jax.numpy.transpose.
|
|
1861
|
+
|
|
1862
|
+
Attributes:
|
|
1863
|
+
axes: This parameters allows to specify the desired order of the axis. It
|
|
1864
|
+
must be a permutation of range(2, ndim), where ndim is the number of
|
|
1865
|
+
dimensions of the input array. The first axis that can be permuted is 2
|
|
1866
|
+
because the batch and time dimensions are excluded. When axes is not
|
|
1867
|
+
specified (i.e., is None), then the order of the channel axes are
|
|
1868
|
+
reversed. E.g., an input with shape (batch, time, ch1, ch2, ch3) will
|
|
1869
|
+
results in an output of shape (batch, time, ch3, ch2, ch1).
|
|
1870
|
+
"""
|
|
1871
|
+
|
|
1872
|
+
# The axis can only be between 2 and ndim - 1.
|
|
1873
|
+
# We do not allow to permute batch and time.
|
|
1874
|
+
axes: TypingSequence[int] | None = None
|
|
1875
|
+
# An optional name for the layer.
|
|
1876
|
+
name: str | None = None
|
|
1877
|
+
|
|
1878
|
+
def __post_init__(self):
|
|
1879
|
+
# Use hashable types for sequences.
|
|
1880
|
+
if self.axes is not None:
|
|
1881
|
+
object.__setattr__(self, 'axes', tuple(self.axes))
|
|
1882
|
+
|
|
1883
|
+
def make(self) -> 'Transpose':
|
|
1884
|
+
|
|
1885
|
+
if self.axes is not None and (0 in self.axes or 1 in self.axes):
|
|
1886
|
+
raise ValueError("Can't transpose batch or time dimension.")
|
|
1887
|
+
|
|
1888
|
+
return Transpose(self, name=self.name)
|
|
1889
|
+
|
|
1890
|
+
config: Config
|
|
1891
|
+
|
|
1892
|
+
def _validate_axes(self, input_shape: types.ShapeLike) -> tuple[int, ...]:
|
|
1893
|
+
axes = self.config.axes
|
|
1894
|
+
input_axes = tuple(range(2, 2 + len(input_shape)))
|
|
1895
|
+
|
|
1896
|
+
if axes is None:
|
|
1897
|
+
return input_axes[::-1]
|
|
1898
|
+
|
|
1899
|
+
sorted_axes = tuple(sorted(axes))
|
|
1900
|
+
if sorted_axes != input_axes:
|
|
1901
|
+
raise ValueError(
|
|
1902
|
+
f'The provided axes {sorted_axes} does not match those'
|
|
1903
|
+
f' of the input {input_axes}.'
|
|
1904
|
+
)
|
|
1905
|
+
|
|
1906
|
+
return tuple(axes)
|
|
1907
|
+
|
|
1908
|
+
@nn.nowrap
|
|
1909
|
+
def get_output_shape(
|
|
1910
|
+
self,
|
|
1911
|
+
input_shape: types.ShapeLike,
|
|
1912
|
+
*,
|
|
1913
|
+
constants: types.Constants | None = None,
|
|
1914
|
+
) -> types.Shape:
|
|
1915
|
+
del constants
|
|
1916
|
+
axes = self._validate_axes(input_shape)
|
|
1917
|
+
return tuple(input_shape[a - 2] for a in axes)
|
|
1918
|
+
|
|
1919
|
+
@types.check_layer
|
|
1920
|
+
def layer(
|
|
1921
|
+
self,
|
|
1922
|
+
x: types.Sequence,
|
|
1923
|
+
*,
|
|
1924
|
+
training: bool,
|
|
1925
|
+
constants: types.Constants | None = None,
|
|
1926
|
+
) -> types.Sequence:
|
|
1927
|
+
axes = self._validate_axes(x.channel_shape)
|
|
1928
|
+
return x.apply_values_masked(lambda v: jnp.transpose(v, (0, 1) + axes))
|
|
1929
|
+
|
|
1930
|
+
|
|
1931
|
+
class SwapAxes(Transpose):
|
|
1932
|
+
"""Swap two channel axes."""
|
|
1933
|
+
|
|
1934
|
+
@dataclasses.dataclass(frozen=True)
|
|
1935
|
+
class Config(types.SequenceLayerConfig):
|
|
1936
|
+
axis1: int
|
|
1937
|
+
axis2: int
|
|
1938
|
+
name: str | None = None
|
|
1939
|
+
|
|
1940
|
+
def make(self) -> 'SwapAxes':
|
|
1941
|
+
|
|
1942
|
+
axes = [self.axis1, self.axis2]
|
|
1943
|
+
if 0 in axes or 1 in axes:
|
|
1944
|
+
raise ValueError("Can't swap batch or time dimension.")
|
|
1945
|
+
|
|
1946
|
+
return SwapAxes(
|
|
1947
|
+
Transpose.Config(axes=axes, name=self.name), name=self.name
|
|
1948
|
+
)
|
|
1949
|
+
|
|
1950
|
+
@override
|
|
1951
|
+
def _validate_axes(self, input_shape: types.ShapeLike) -> tuple[int, ...]:
|
|
1952
|
+
ndim = 2 + len(input_shape) # ndim including batch and time.
|
|
1953
|
+
axes = [a if a >= 0 else ndim + a for a in self.config.axes]
|
|
1954
|
+
if 0 in axes or 1 in axes:
|
|
1955
|
+
raise ValueError("Can't move batch or time dimension.")
|
|
1956
|
+
axis1, axis2 = axes
|
|
1957
|
+
if axis1 < 1 or axis1 >= ndim or axis2 < 1 or axis2 >= ndim:
|
|
1958
|
+
raise ValueError(
|
|
1959
|
+
f'Out of bound axis (got {axis1=} {axis2=} for {ndim=}).'
|
|
1960
|
+
)
|
|
1961
|
+
axes = list(range(2 + len(input_shape)))
|
|
1962
|
+
axes[axis1], axes[axis2] = axes[axis2], axes[axis1]
|
|
1963
|
+
return tuple(axes[2:])
|
|
1964
|
+
|
|
1965
|
+
|
|
1966
|
+
class MoveAxis(Transpose):
|
|
1967
|
+
"""Moves one or several channel axes to new locations."""
|
|
1968
|
+
|
|
1969
|
+
@dataclasses.dataclass(frozen=True)
|
|
1970
|
+
class Config(types.SequenceLayerConfig):
|
|
1971
|
+
"""Config of MoveAxis layer."""
|
|
1972
|
+
|
|
1973
|
+
source: int | TypingSequence[int]
|
|
1974
|
+
destination: int | TypingSequence[int]
|
|
1975
|
+
name: str | None = None
|
|
1976
|
+
|
|
1977
|
+
def __post_init__(self):
|
|
1978
|
+
to_tuple = lambda x: (x,) if isinstance(x, int) else x
|
|
1979
|
+
object.__setattr__(self, 'source', to_tuple(self.source))
|
|
1980
|
+
object.__setattr__(self, 'destination', to_tuple(self.destination))
|
|
1981
|
+
|
|
1982
|
+
def make(self) -> 'MoveAxis':
|
|
1983
|
+
|
|
1984
|
+
if (
|
|
1985
|
+
0 in self.source
|
|
1986
|
+
or 1 in self.source
|
|
1987
|
+
or 0 in self.destination
|
|
1988
|
+
or 1 in self.destination
|
|
1989
|
+
):
|
|
1990
|
+
raise ValueError("Can't move batch or time dimension.")
|
|
1991
|
+
|
|
1992
|
+
if len(self.source) != len(self.destination):
|
|
1993
|
+
raise ValueError(
|
|
1994
|
+
f'Inconsistent number of elements: {len(self.source)} vs'
|
|
1995
|
+
f' {len(self.destination)}'
|
|
1996
|
+
)
|
|
1997
|
+
|
|
1998
|
+
return MoveAxis(self, name=self.name)
|
|
1999
|
+
|
|
2000
|
+
config: Config
|
|
2001
|
+
|
|
2002
|
+
@override
|
|
2003
|
+
def _validate_axes(self, input_shape: types.ShapeLike) -> tuple[int, ...]:
|
|
2004
|
+
ndim = 2 + len(input_shape) # ndim including batch and time.
|
|
2005
|
+
|
|
2006
|
+
canonicalize_axes = lambda axes: [a if a >= 0 else ndim + a for a in axes]
|
|
2007
|
+
source = canonicalize_axes(self.config.source)
|
|
2008
|
+
destination = canonicalize_axes(self.config.destination)
|
|
2009
|
+
|
|
2010
|
+
if 0 in source or 1 in source or 0 in destination or 1 in destination:
|
|
2011
|
+
raise ValueError("Can't move batch or time dimension.")
|
|
2012
|
+
|
|
2013
|
+
perm = [i for i in range(ndim) if i not in source]
|
|
2014
|
+
for dest, src in sorted(zip(destination, source, strict=True)):
|
|
2015
|
+
perm.insert(dest, src)
|
|
2016
|
+
|
|
2017
|
+
return tuple(perm[2:])
|
|
2018
|
+
|
|
2019
|
+
|
|
2020
|
+
class Emit(types.PreservesType, types.PreservesShape, types.StatelessEmitting):
|
|
2021
|
+
"""An identity layer that emits its input."""
|
|
2022
|
+
|
|
2023
|
+
@dataclasses.dataclass(frozen=True)
|
|
2024
|
+
class Config(types.SequenceLayerConfig):
|
|
2025
|
+
name: str | None = None
|
|
2026
|
+
|
|
2027
|
+
def make(self) -> 'Emit':
|
|
2028
|
+
return Emit(self, name=self.name)
|
|
2029
|
+
|
|
2030
|
+
config: Config
|
|
2031
|
+
|
|
2032
|
+
@types.check_layer_with_emits
|
|
2033
|
+
def layer_with_emits(
|
|
2034
|
+
self,
|
|
2035
|
+
x: types.Sequence,
|
|
2036
|
+
*,
|
|
2037
|
+
training: bool,
|
|
2038
|
+
constants: types.Constants | None = None,
|
|
2039
|
+
) -> tuple[types.Sequence, types.Sequence]:
|
|
2040
|
+
return x, x
|
|
2041
|
+
|
|
2042
|
+
|
|
2043
|
+
class Dropout(types.PreservesType, types.StatelessPointwise):
|
|
2044
|
+
"""Computes dropout using Flax RNGs."""
|
|
2045
|
+
|
|
2046
|
+
@dataclasses.dataclass(frozen=True)
|
|
2047
|
+
class Config(types.SequenceLayerConfig):
|
|
2048
|
+
rate: float = 0.0
|
|
2049
|
+
broadcast_dims: TypingSequence[int] = ()
|
|
2050
|
+
rng_collection: str = 'dropout'
|
|
2051
|
+
name: str | None = None
|
|
2052
|
+
|
|
2053
|
+
def make(self) -> 'Dropout':
|
|
2054
|
+
return Dropout(self, name=self.name)
|
|
2055
|
+
|
|
2056
|
+
config: Config
|
|
2057
|
+
|
|
2058
|
+
@types.check_step
|
|
2059
|
+
def step(
|
|
2060
|
+
self,
|
|
2061
|
+
x: types.Sequence,
|
|
2062
|
+
state: types.State,
|
|
2063
|
+
*,
|
|
2064
|
+
training: bool,
|
|
2065
|
+
constants: types.Constants | None = None,
|
|
2066
|
+
) -> tuple[types.Sequence, types.State]:
|
|
2067
|
+
if training:
|
|
2068
|
+
# TODO(rryan): Layer/step-wise equivalence is not yet possible. Requires
|
|
2069
|
+
# deterministic dropout.
|
|
2070
|
+
raise ValueError('Step-wise training is not supported for Dropout yet.')
|
|
2071
|
+
return self.layer(x, training=training, constants=constants), state
|
|
2072
|
+
|
|
2073
|
+
def apply_dropout(self, x: jax.Array, training: bool) -> jax.Array:
|
|
2074
|
+
"""Applies dropout to array x."""
|
|
2075
|
+
if (self.config.rate == 0.0) or not training:
|
|
2076
|
+
return x
|
|
2077
|
+
|
|
2078
|
+
# Prevent gradient NaNs in 1.0 edge-case.
|
|
2079
|
+
if self.config.rate == 1.0:
|
|
2080
|
+
return jnp.zeros_like(x)
|
|
2081
|
+
|
|
2082
|
+
keep_prob = 1.0 - self.config.rate
|
|
2083
|
+
rng = self.make_rng(self.config.rng_collection)
|
|
2084
|
+
broadcast_shape = list(x.shape)
|
|
2085
|
+
for dim in self.config.broadcast_dims:
|
|
2086
|
+
broadcast_shape[dim] = 1
|
|
2087
|
+
|
|
2088
|
+
input_is_floating = utils.is_floating(x.dtype)
|
|
2089
|
+
|
|
2090
|
+
# If the input is not floating point, we use jnp.where to apply the dropout
|
|
2091
|
+
# mask. Otherwise, we use multiplication by 1 or 0 to apply dropout. In
|
|
2092
|
+
# practice, multiplication leads to faster compiled code because it is
|
|
2093
|
+
# easier to fuse with other operations.
|
|
2094
|
+
use_select = not input_is_floating
|
|
2095
|
+
|
|
2096
|
+
if input_is_floating:
|
|
2097
|
+
mask_dtype = x.dtype
|
|
2098
|
+
else:
|
|
2099
|
+
mask_dtype = jnp.float32
|
|
2100
|
+
|
|
2101
|
+
dropout_mask = jax.random.uniform(
|
|
2102
|
+
rng, shape=broadcast_shape, dtype=mask_dtype
|
|
2103
|
+
)
|
|
2104
|
+
|
|
2105
|
+
if use_select:
|
|
2106
|
+
dropout_mask = dropout_mask < keep_prob
|
|
2107
|
+
# Only scale the input if floating. This is a hack to support integer /
|
|
2108
|
+
# boolean dropout.
|
|
2109
|
+
if input_is_floating:
|
|
2110
|
+
x /= keep_prob
|
|
2111
|
+
else:
|
|
2112
|
+
# If not using select, scale the dropout mask.
|
|
2113
|
+
dropout_mask = jnp.floor(keep_prob + dropout_mask) / keep_prob
|
|
2114
|
+
|
|
2115
|
+
dropout_mask = jnp.broadcast_to(dropout_mask, x.shape)
|
|
2116
|
+
|
|
2117
|
+
if use_select:
|
|
2118
|
+
x = jax.lax.select(dropout_mask, x, jnp.zeros_like(x))
|
|
2119
|
+
else:
|
|
2120
|
+
x *= dropout_mask
|
|
2121
|
+
return x
|
|
2122
|
+
|
|
2123
|
+
@nn.compact
|
|
2124
|
+
@types.check_layer
|
|
2125
|
+
def layer(
|
|
2126
|
+
self,
|
|
2127
|
+
x: types.Sequence,
|
|
2128
|
+
*,
|
|
2129
|
+
training: bool,
|
|
2130
|
+
constants: types.Constants | None = None,
|
|
2131
|
+
) -> types.Sequence:
|
|
2132
|
+
# No mask status change since dropout only zeros values.
|
|
2133
|
+
return x.apply_values_masked(self.apply_dropout, training=training)
|
|
2134
|
+
|
|
2135
|
+
|
|
2136
|
+
class Downsample1D(types.PreservesType, types.PreservesShape, types.Stateless):
|
|
2137
|
+
"""A 1D downsampling layer."""
|
|
2138
|
+
|
|
2139
|
+
@dataclasses.dataclass(frozen=True)
|
|
2140
|
+
class Config(types.SequenceLayerConfig):
|
|
2141
|
+
"""Configuration for Downsample1D."""
|
|
2142
|
+
|
|
2143
|
+
rate: int
|
|
2144
|
+
name: str | None = None
|
|
2145
|
+
|
|
2146
|
+
def make(self) -> 'Downsample1D':
|
|
2147
|
+
return Downsample1D(self, name=self.name)
|
|
2148
|
+
|
|
2149
|
+
config: Config
|
|
2150
|
+
|
|
2151
|
+
@property
|
|
2152
|
+
def block_size(self) -> int:
|
|
2153
|
+
return self.config.rate
|
|
2154
|
+
|
|
2155
|
+
@property
|
|
2156
|
+
def output_ratio(self) -> fractions.Fraction:
|
|
2157
|
+
return fractions.Fraction(1, self.config.rate)
|
|
2158
|
+
|
|
2159
|
+
@property
|
|
2160
|
+
def input_latency(self) -> int:
|
|
2161
|
+
return self.config.rate - 1
|
|
2162
|
+
|
|
2163
|
+
@types.check_layer
|
|
2164
|
+
def layer(
|
|
2165
|
+
self,
|
|
2166
|
+
x: types.Sequence,
|
|
2167
|
+
*,
|
|
2168
|
+
training: bool,
|
|
2169
|
+
constants: types.Constants | None = None,
|
|
2170
|
+
) -> types.Sequence:
|
|
2171
|
+
# Downsampling does not change the masked state, so use the type of x to
|
|
2172
|
+
# repack the downsampled values and mask.
|
|
2173
|
+
return type(x)(
|
|
2174
|
+
x.values[:, :: self.config.rate], x.mask[:, :: self.config.rate]
|
|
2175
|
+
)
|
|
2176
|
+
|
|
2177
|
+
|
|
2178
|
+
class Upsample1D(types.PreservesType, types.PreservesShape, types.Stateless):
|
|
2179
|
+
"""A 1D upsampling layer."""
|
|
2180
|
+
|
|
2181
|
+
@dataclasses.dataclass(frozen=True)
|
|
2182
|
+
class Config(types.SequenceLayerConfig):
|
|
2183
|
+
"""Configuration for Upsample1D."""
|
|
2184
|
+
|
|
2185
|
+
rate: int
|
|
2186
|
+
name: str | None = None
|
|
2187
|
+
|
|
2188
|
+
def make(self) -> 'Upsample1D':
|
|
2189
|
+
return Upsample1D(self, name=self.name)
|
|
2190
|
+
|
|
2191
|
+
config: Config
|
|
2192
|
+
|
|
2193
|
+
@property
|
|
2194
|
+
def output_ratio(self) -> fractions.Fraction:
|
|
2195
|
+
return fractions.Fraction(self.config.rate)
|
|
2196
|
+
|
|
2197
|
+
@property
|
|
2198
|
+
def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
|
|
2199
|
+
return {s: (0, 0) for s in range(self.config.rate)}
|
|
2200
|
+
|
|
2201
|
+
@types.check_layer
|
|
2202
|
+
def layer(
|
|
2203
|
+
self,
|
|
2204
|
+
x: types.Sequence,
|
|
2205
|
+
*,
|
|
2206
|
+
training: bool,
|
|
2207
|
+
constants: types.Constants | None = None,
|
|
2208
|
+
) -> types.Sequence:
|
|
2209
|
+
# Upsampling does not change the masked state, so use the type of x to
|
|
2210
|
+
# repack the upsampled values and mask.
|
|
2211
|
+
return type(x)(
|
|
2212
|
+
jnp.repeat(x.values, self.config.rate, axis=1),
|
|
2213
|
+
jnp.repeat(x.mask, self.config.rate, axis=1),
|
|
2214
|
+
)
|
|
2215
|
+
|
|
2216
|
+
|
|
2217
|
+
class Upsample2D(types.PreservesType, types.Stateless):
|
|
2218
|
+
"""A 2D upsampling layer."""
|
|
2219
|
+
|
|
2220
|
+
@dataclasses.dataclass(frozen=True)
|
|
2221
|
+
class Config(types.SequenceLayerConfig):
|
|
2222
|
+
"""Configuration for Upsample2D."""
|
|
2223
|
+
|
|
2224
|
+
rate: int | TypingSequence[int]
|
|
2225
|
+
name: str | None = None
|
|
2226
|
+
|
|
2227
|
+
def __post_init__(self):
|
|
2228
|
+
object.__setattr__(self, 'rate', utils.normalize_2tuple(self.rate))
|
|
2229
|
+
|
|
2230
|
+
def make(self) -> 'Upsample2D':
|
|
2231
|
+
return Upsample2D(self, name=self.name)
|
|
2232
|
+
|
|
2233
|
+
config: Config
|
|
2234
|
+
|
|
2235
|
+
@property
|
|
2236
|
+
def output_ratio(self) -> fractions.Fraction:
|
|
2237
|
+
return fractions.Fraction(self.config.rate[0])
|
|
2238
|
+
|
|
2239
|
+
@property
|
|
2240
|
+
def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
|
|
2241
|
+
return {s: (0, 0) for s in range(self.config.rate[0])}
|
|
2242
|
+
|
|
2243
|
+
@nn.nowrap
|
|
2244
|
+
def get_output_shape(
|
|
2245
|
+
self,
|
|
2246
|
+
input_shape: types.ShapeLike,
|
|
2247
|
+
*,
|
|
2248
|
+
constants: types.Constants | None = None,
|
|
2249
|
+
) -> types.Shape:
|
|
2250
|
+
if len(input_shape) != 2:
|
|
2251
|
+
raise ValueError(
|
|
2252
|
+
'Upsample2D requires rank 4 input got:'
|
|
2253
|
+
f' {(None, None) + tuple(input_shape)}'
|
|
2254
|
+
)
|
|
2255
|
+
|
|
2256
|
+
return (
|
|
2257
|
+
input_shape[0] * self.config.rate[1],
|
|
2258
|
+
input_shape[1],
|
|
2259
|
+
)
|
|
2260
|
+
|
|
2261
|
+
@types.check_layer
|
|
2262
|
+
def layer(
|
|
2263
|
+
self,
|
|
2264
|
+
x: types.Sequence,
|
|
2265
|
+
*,
|
|
2266
|
+
training: bool,
|
|
2267
|
+
constants: types.Constants | None = None,
|
|
2268
|
+
) -> types.Sequence:
|
|
2269
|
+
values = jnp.repeat(x.values, self.config.rate[0], axis=1)
|
|
2270
|
+
values = jnp.repeat(values, self.config.rate[1], axis=2)
|
|
2271
|
+
mask = jnp.repeat(x.mask, self.config.rate[0], axis=1)
|
|
2272
|
+
|
|
2273
|
+
# Upsampling does not change the masked state, so use the type of x to
|
|
2274
|
+
# repack the upsampled values and mask.
|
|
2275
|
+
return type(x)(values, mask)
|
|
2276
|
+
|
|
2277
|
+
|
|
2278
|
+
class MaskInvalid(types.PreservesType, types.StatelessPointwise):
|
|
2279
|
+
"""Masks the input sequence."""
|
|
2280
|
+
|
|
2281
|
+
@dataclasses.dataclass(frozen=True)
|
|
2282
|
+
class Config(types.SequenceLayerConfig):
|
|
2283
|
+
name: str | None = None
|
|
2284
|
+
|
|
2285
|
+
def make(self) -> 'MaskInvalid':
|
|
2286
|
+
return MaskInvalid(self, name=self.name)
|
|
2287
|
+
|
|
2288
|
+
config: Config
|
|
2289
|
+
|
|
2290
|
+
@types.check_layer
|
|
2291
|
+
def layer(
|
|
2292
|
+
self,
|
|
2293
|
+
x: types.Sequence,
|
|
2294
|
+
*,
|
|
2295
|
+
training: bool,
|
|
2296
|
+
constants: types.Constants | None = None,
|
|
2297
|
+
) -> types.Sequence:
|
|
2298
|
+
del training
|
|
2299
|
+
return x.mask_invalid()
|
|
2300
|
+
|
|
2301
|
+
|
|
2302
|
+
class Logging(types.PreservesType, types.StatelessPointwise):
|
|
2303
|
+
"""Layer that logs input arguments to get_initial_state, step, and layer."""
|
|
2304
|
+
|
|
2305
|
+
@dataclasses.dataclass(frozen=True)
|
|
2306
|
+
class Config(types.SequenceLayerConfig):
|
|
2307
|
+
"""Configuration for the Logging layer."""
|
|
2308
|
+
|
|
2309
|
+
prefix: str = ''
|
|
2310
|
+
dump_tensors: bool = False
|
|
2311
|
+
_: dataclasses.KW_ONLY
|
|
2312
|
+
layer_format_str: str = (
|
|
2313
|
+
'{prefix} layer():\n'
|
|
2314
|
+
'\tx={x}\n\ttraining={training}\n\tconstants={constants}'
|
|
2315
|
+
)
|
|
2316
|
+
get_initial_state_format_str: str = (
|
|
2317
|
+
'{prefix} get_initial_state():\n'
|
|
2318
|
+
'\tbatch_size={batch_size}\n\tinput_spec={input_spec}\n\t'
|
|
2319
|
+
'training={training}\n\tconstants={constants}'
|
|
2320
|
+
)
|
|
2321
|
+
step_format_str: str = (
|
|
2322
|
+
'{prefix} step():\n'
|
|
2323
|
+
'\tx={x}\n\tstate={state}\n'
|
|
2324
|
+
'\ttraining={training}\n\tconstants={constants}'
|
|
2325
|
+
)
|
|
2326
|
+
|
|
2327
|
+
def make(self) -> 'Logging':
|
|
2328
|
+
return Logging(self)
|
|
2329
|
+
|
|
2330
|
+
config: Config
|
|
2331
|
+
|
|
2332
|
+
@nn.nowrap
|
|
2333
|
+
def _register_callback(self, format_str: str, **kwargs) -> None:
|
|
2334
|
+
if self.config.dump_tensors:
|
|
2335
|
+
# Non-JAX types are not accepted by jax.debug.callback, so we separate
|
|
2336
|
+
# them out.
|
|
2337
|
+
nonjax_kwargs = {'prefix': self.config.prefix}
|
|
2338
|
+
for k, v in list(kwargs.items()):
|
|
2339
|
+
try:
|
|
2340
|
+
jax.interpreters.xla.canonicalize_dtype(v)
|
|
2341
|
+
except: # pylint: disable=bare-except
|
|
2342
|
+
nonjax_kwargs[k] = v
|
|
2343
|
+
del kwargs[k]
|
|
2344
|
+
# We then set up a callback for the remaining tensor values:
|
|
2345
|
+
jax.debug.callback(
|
|
2346
|
+
lambda *cb_args, **cb_kwargs: logging.info(
|
|
2347
|
+
format_str.format(*cb_args, **nonjax_kwargs, **cb_kwargs)
|
|
2348
|
+
),
|
|
2349
|
+
**kwargs,
|
|
2350
|
+
)
|
|
2351
|
+
else:
|
|
2352
|
+
|
|
2353
|
+
def arrays_to_specs(leaf: Any) -> types.ShapeDType | str:
|
|
2354
|
+
if isinstance(leaf, jax.Array) or isinstance(leaf, np.ndarray):
|
|
2355
|
+
return types.ShapeDType(leaf.shape, leaf.dtype)
|
|
2356
|
+
# `types.Sequence`s repr() as their specs; we can return them directly.
|
|
2357
|
+
return leaf
|
|
2358
|
+
|
|
2359
|
+
kwargs = jax.tree.map(arrays_to_specs, kwargs)
|
|
2360
|
+
logging.info(format_str.format(prefix=self.config.prefix, **kwargs))
|
|
2361
|
+
|
|
2362
|
+
@types.check_layer
|
|
2363
|
+
def layer(
|
|
2364
|
+
self,
|
|
2365
|
+
x: types.Sequence,
|
|
2366
|
+
*,
|
|
2367
|
+
training: bool,
|
|
2368
|
+
constants: types.Constants | None = None,
|
|
2369
|
+
) -> types.Sequence:
|
|
2370
|
+
self._register_callback(
|
|
2371
|
+
self.config.layer_format_str,
|
|
2372
|
+
x=x,
|
|
2373
|
+
training=training,
|
|
2374
|
+
constants=constants,
|
|
2375
|
+
)
|
|
2376
|
+
return x
|
|
2377
|
+
|
|
2378
|
+
def get_initial_state(
|
|
2379
|
+
self,
|
|
2380
|
+
batch_size: int,
|
|
2381
|
+
input_spec: types.ChannelSpec,
|
|
2382
|
+
*,
|
|
2383
|
+
training: bool,
|
|
2384
|
+
constants: types.Constants | None = None,
|
|
2385
|
+
) -> types.State:
|
|
2386
|
+
self._register_callback(
|
|
2387
|
+
self.config.get_initial_state_format_str,
|
|
2388
|
+
batch_size=batch_size,
|
|
2389
|
+
input_spec=input_spec,
|
|
2390
|
+
training=training,
|
|
2391
|
+
constants=constants,
|
|
2392
|
+
)
|
|
2393
|
+
return super().get_initial_state(
|
|
2394
|
+
batch_size, input_spec, training=training, constants=constants
|
|
2395
|
+
)
|
|
2396
|
+
|
|
2397
|
+
@types.check_step
|
|
2398
|
+
def step(
|
|
2399
|
+
self,
|
|
2400
|
+
x: types.Sequence,
|
|
2401
|
+
state: types.State,
|
|
2402
|
+
*,
|
|
2403
|
+
training: bool,
|
|
2404
|
+
constants: types.Constants | None = None,
|
|
2405
|
+
) -> tuple[types.Sequence, types.State]:
|
|
2406
|
+
self._register_callback(
|
|
2407
|
+
self.config.step_format_str,
|
|
2408
|
+
x=x,
|
|
2409
|
+
state=state,
|
|
2410
|
+
training=training,
|
|
2411
|
+
constants=constants,
|
|
2412
|
+
)
|
|
2413
|
+
return x, state
|
|
2414
|
+
|
|
2415
|
+
|
|
2416
|
+
class Argmax(types.Stateless):
|
|
2417
|
+
"""An Argmax layer."""
|
|
2418
|
+
|
|
2419
|
+
@dataclasses.dataclass(frozen=True)
|
|
2420
|
+
class Config(types.SequenceLayerConfig):
|
|
2421
|
+
name: str | None = None
|
|
2422
|
+
|
|
2423
|
+
def make(self) -> 'Argmax':
|
|
2424
|
+
return Argmax(self, name=self.name)
|
|
2425
|
+
|
|
2426
|
+
config: Config
|
|
2427
|
+
|
|
2428
|
+
@types.check_layer
|
|
2429
|
+
def layer(
|
|
2430
|
+
self,
|
|
2431
|
+
x: types.Sequence,
|
|
2432
|
+
*,
|
|
2433
|
+
training: bool,
|
|
2434
|
+
constants: types.Constants | None = None,
|
|
2435
|
+
) -> types.Sequence:
|
|
2436
|
+
return x.apply_values(jnp.argmax, axis=-1)
|
|
2437
|
+
|
|
2438
|
+
@nn.nowrap
|
|
2439
|
+
def get_output_shape(
|
|
2440
|
+
self,
|
|
2441
|
+
input_shape: types.ShapeLike,
|
|
2442
|
+
*,
|
|
2443
|
+
constants: types.Constants | None = None,
|
|
2444
|
+
) -> types.Shape:
|
|
2445
|
+
return tuple(input_shape[:-1])
|
|
2446
|
+
|
|
2447
|
+
def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
|
|
2448
|
+
return jnp.int32
|
|
2449
|
+
|
|
2450
|
+
|
|
2451
|
+
class EinopsRearrange(types.PreservesType, types.Stateless):
|
|
2452
|
+
"""A wrapper for einops.rearrange applied to the channel dimensions."""
|
|
2453
|
+
|
|
2454
|
+
@dataclasses.dataclass(frozen=True)
|
|
2455
|
+
class Config(types.SequenceLayerConfig):
|
|
2456
|
+
"""Config of EinopsRearrange."""
|
|
2457
|
+
|
|
2458
|
+
# Rearrangement pattern excluding the batch and time dimensions.
|
|
2459
|
+
pattern: str
|
|
2460
|
+
# A dictionary of additional length specifications for dimensions.
|
|
2461
|
+
axes_lengths: Mapping[str, int] | None = None
|
|
2462
|
+
# Optional name of this layer.
|
|
2463
|
+
name: str | None = None
|
|
2464
|
+
|
|
2465
|
+
def __post_init__(self):
|
|
2466
|
+
if '->' not in self.pattern:
|
|
2467
|
+
raise ValueError(
|
|
2468
|
+
f'The input pattern is not valid (got {self.pattern}).'
|
|
2469
|
+
)
|
|
2470
|
+
|
|
2471
|
+
# Find all unique labels.
|
|
2472
|
+
labels = set(self.pattern.replace('(', ' ').replace(')', ' ').split(' '))
|
|
2473
|
+
if 'batch' in labels or 'time' in labels:
|
|
2474
|
+
raise ValueError(
|
|
2475
|
+
f'`batch` and `time` are reserved axes labels (got {self.pattern}).'
|
|
2476
|
+
)
|
|
2477
|
+
|
|
2478
|
+
def make(self) -> 'EinopsRearrange':
|
|
2479
|
+
return EinopsRearrange(self, name=self.name)
|
|
2480
|
+
|
|
2481
|
+
config: Config
|
|
2482
|
+
|
|
2483
|
+
@property
|
|
2484
|
+
def supports_step(self) -> bool:
|
|
2485
|
+
return True
|
|
2486
|
+
|
|
2487
|
+
def _get_rearrange_fn(self) -> Callable[[jax.Array], jax.Array]:
|
|
2488
|
+
before, after = self.config.pattern.split('->')
|
|
2489
|
+
pattern = f'batch time {before} -> batch time {after}'
|
|
2490
|
+
axes_lengths = self.config.axes_lengths if self.config.axes_lengths else {}
|
|
2491
|
+
return functools.partial(einops.rearrange, pattern=pattern, **axes_lengths)
|
|
2492
|
+
|
|
2493
|
+
@types.check_layer
|
|
2494
|
+
def layer(
|
|
2495
|
+
self,
|
|
2496
|
+
x: types.Sequence,
|
|
2497
|
+
*,
|
|
2498
|
+
training: bool,
|
|
2499
|
+
constants: types.Constants | None = None,
|
|
2500
|
+
) -> types.Sequence:
|
|
2501
|
+
del training, constants
|
|
2502
|
+
rearrange_fn = self._get_rearrange_fn()
|
|
2503
|
+
return x.apply_values(rearrange_fn)
|
|
2504
|
+
|
|
2505
|
+
@nn.nowrap
|
|
2506
|
+
def get_output_shape(
|
|
2507
|
+
self,
|
|
2508
|
+
input_shape: types.ShapeLike,
|
|
2509
|
+
*,
|
|
2510
|
+
constants: types.Constants | None = None,
|
|
2511
|
+
) -> types.Shape:
|
|
2512
|
+
del constants
|
|
2513
|
+
rearrange_fn = self._get_rearrange_fn()
|
|
2514
|
+
output = jax.eval_shape(rearrange_fn, jnp.zeros((1, 1) + input_shape))
|
|
2515
|
+
return tuple(output.shape[2:])
|
|
2516
|
+
|
|
2517
|
+
|
|
2518
|
+
class GlobalEinopsRearrange(types.PreservesType, types.Stateless):
|
|
2519
|
+
"""A wrapper for einops.rearrange applied to the time and channel dimensions."""
|
|
2520
|
+
|
|
2521
|
+
@dataclasses.dataclass(frozen=True)
|
|
2522
|
+
class Config(types.SequenceLayerConfig):
|
|
2523
|
+
"""Config of GlobalEinopsRearrange."""
|
|
2524
|
+
|
|
2525
|
+
# Rearrangement pattern excluding the batch dimension.
|
|
2526
|
+
pattern: str
|
|
2527
|
+
# A dictionary of additional length specifications for dimensions.
|
|
2528
|
+
axes_lengths: Mapping[str, int] | None = None
|
|
2529
|
+
# When ceil mode is False, the last frame is invalid if it contains any
|
|
2530
|
+
# invalid steps. If ceil mode is True, then Then the last frame is valid if
|
|
2531
|
+
# it contains at least one valid value.
|
|
2532
|
+
ceil_mode: bool = False
|
|
2533
|
+
# Optional name of this layer.
|
|
2534
|
+
name: str | None = None
|
|
2535
|
+
|
|
2536
|
+
def __post_init__(self):
|
|
2537
|
+
if '->' not in self.pattern:
|
|
2538
|
+
raise ValueError(
|
|
2539
|
+
f'The input pattern is not valid (got {self.pattern}).'
|
|
2540
|
+
)
|
|
2541
|
+
|
|
2542
|
+
# Find all unique labels.
|
|
2543
|
+
labels = set(self.pattern.replace('(', ' ').replace(')', ' ').split(' '))
|
|
2544
|
+
if 'batch' in labels:
|
|
2545
|
+
raise ValueError(
|
|
2546
|
+
f'`batch` is a reserved axes labels (got {self.pattern}).'
|
|
2547
|
+
)
|
|
2548
|
+
|
|
2549
|
+
def make(self) -> 'GlobalEinopsRearrange':
|
|
2550
|
+
return GlobalEinopsRearrange(self, name=self.name)
|
|
2551
|
+
|
|
2552
|
+
config: Config
|
|
2553
|
+
|
|
2554
|
+
@property
|
|
2555
|
+
def supports_step(self) -> bool:
|
|
2556
|
+
return False
|
|
2557
|
+
|
|
2558
|
+
@property
|
|
2559
|
+
def receptive_field(self) -> tuple[int | None, int | None]:
|
|
2560
|
+
return (-np.inf, np.inf)
|
|
2561
|
+
|
|
2562
|
+
def _get_rearrange_fn(self) -> Callable[[jax.Array], jax.Array]:
|
|
2563
|
+
before, after = self.config.pattern.split('->')
|
|
2564
|
+
pattern = f'batch {before} -> batch {after}'
|
|
2565
|
+
axes_lengths = self.config.axes_lengths if self.config.axes_lengths else {}
|
|
2566
|
+
return functools.partial(einops.rearrange, pattern=pattern, **axes_lengths)
|
|
2567
|
+
|
|
2568
|
+
@types.check_layer
|
|
2569
|
+
def layer(
|
|
2570
|
+
self,
|
|
2571
|
+
x: types.Sequence,
|
|
2572
|
+
*,
|
|
2573
|
+
training: bool,
|
|
2574
|
+
constants: types.Constants | None = None,
|
|
2575
|
+
) -> types.Sequence:
|
|
2576
|
+
del training, constants
|
|
2577
|
+
rearrange_fn = self._get_rearrange_fn()
|
|
2578
|
+
|
|
2579
|
+
values = rearrange_fn(x.mask_invalid().values)
|
|
2580
|
+
|
|
2581
|
+
# 1. Broadcast the mask to the full input shape, and then reshape it to the
|
|
2582
|
+
# output shape.
|
|
2583
|
+
mask = jnp.reshape(x.mask, x.shape[:2] + (1,) * len(x.channel_shape))
|
|
2584
|
+
mask = jnp.broadcast_to(mask, x.shape)
|
|
2585
|
+
# 2. EinopsRearrange the mask to the output shape, and then call jnp.all (in
|
|
2586
|
+
# ceil_mode==False) to ensure that any timestep with *any* invalid input is
|
|
2587
|
+
# invalid in the output).
|
|
2588
|
+
mask = rearrange_fn(mask)
|
|
2589
|
+
|
|
2590
|
+
if self.config.ceil_mode:
|
|
2591
|
+
mask = jnp.any(mask, axis=range(2, mask.ndim))
|
|
2592
|
+
else:
|
|
2593
|
+
mask = jnp.all(mask, axis=range(2, mask.ndim))
|
|
2594
|
+
|
|
2595
|
+
return types.Sequence(values, mask)
|
|
2596
|
+
|
|
2597
|
+
@nn.nowrap
|
|
2598
|
+
def get_output_shape(
|
|
2599
|
+
self,
|
|
2600
|
+
input_shape: types.ShapeLike,
|
|
2601
|
+
*,
|
|
2602
|
+
constants: types.Constants | None = None,
|
|
2603
|
+
) -> types.Shape:
|
|
2604
|
+
del constants
|
|
2605
|
+
rearrange_fn = self._get_rearrange_fn()
|
|
2606
|
+
if self.config.axes_lengths is not None:
|
|
2607
|
+
time_dim = math.prod(self.config.axes_lengths.values())
|
|
2608
|
+
else:
|
|
2609
|
+
time_dim = 1
|
|
2610
|
+
output = jax.eval_shape(
|
|
2611
|
+
rearrange_fn, jnp.zeros((1, time_dim) + input_shape)
|
|
2612
|
+
)
|
|
2613
|
+
return tuple(output.shape[2:])
|
|
2614
|
+
|
|
2615
|
+
|
|
2616
|
+
class Squeeze(types.PreservesType, types.Stateless):
|
|
2617
|
+
"""This layer squeezes all the depth dimensions of the input.
|
|
2618
|
+
|
|
2619
|
+
I.e. [batch_size, time, *depth_dims -> [batch_size, time] (where all the
|
|
2620
|
+
`depth_dims` need to be 1).
|
|
2621
|
+
"""
|
|
2622
|
+
|
|
2623
|
+
@dataclasses.dataclass(frozen=True)
|
|
2624
|
+
class Config(types.SequenceLayerConfig):
|
|
2625
|
+
"""Config of Squeeze."""
|
|
2626
|
+
|
|
2627
|
+
axis: int | TypingSequence[int] | None = None
|
|
2628
|
+
|
|
2629
|
+
name: str | None = None
|
|
2630
|
+
|
|
2631
|
+
def make(self) -> 'Squeeze':
|
|
2632
|
+
|
|
2633
|
+
axis = self.axis
|
|
2634
|
+
if isinstance(axis, int):
|
|
2635
|
+
if axis in (0, 1):
|
|
2636
|
+
raise ValueError('Batch and time (axis=0 or 1) cannot be squeezed.')
|
|
2637
|
+
elif axis is not None and (0 in axis or 1 in axis):
|
|
2638
|
+
raise ValueError('Batch and time (axis=0 or 1) cannot be squeezed.')
|
|
2639
|
+
|
|
2640
|
+
return Squeeze(self, name=self.name)
|
|
2641
|
+
|
|
2642
|
+
config: Config
|
|
2643
|
+
|
|
2644
|
+
def _validate_axis(self, input_shape: types.ShapeLike) -> tuple[int, ...]:
|
|
2645
|
+
axis = self.config.axis
|
|
2646
|
+
|
|
2647
|
+
if isinstance(axis, int):
|
|
2648
|
+
return (axis,)
|
|
2649
|
+
|
|
2650
|
+
if axis is None:
|
|
2651
|
+
return tuple(a + 2 for a, n in enumerate(input_shape) if n == 1)
|
|
2652
|
+
|
|
2653
|
+
return tuple(axis)
|
|
2654
|
+
|
|
2655
|
+
@nn.nowrap
|
|
2656
|
+
def get_output_shape(
|
|
2657
|
+
self,
|
|
2658
|
+
input_shape: types.ShapeLike,
|
|
2659
|
+
*,
|
|
2660
|
+
constants: types.Constants | None = None,
|
|
2661
|
+
) -> types.Shape:
|
|
2662
|
+
del constants
|
|
2663
|
+
axis = self._validate_axis(input_shape)
|
|
2664
|
+
return jax.eval_shape(
|
|
2665
|
+
lambda v: jnp.squeeze(v, axis=axis),
|
|
2666
|
+
types.ShapeDType((0, 1) + tuple(input_shape), jnp.float32),
|
|
2667
|
+
).shape[2:]
|
|
2668
|
+
|
|
2669
|
+
@types.check_layer
|
|
2670
|
+
def layer(
|
|
2671
|
+
self,
|
|
2672
|
+
x: types.Sequence,
|
|
2673
|
+
*,
|
|
2674
|
+
training: bool,
|
|
2675
|
+
constants: types.Constants | None = None,
|
|
2676
|
+
) -> types.Sequence:
|
|
2677
|
+
del training
|
|
2678
|
+
axis = self._validate_axis(x.channel_shape)
|
|
2679
|
+
return x.apply_values_masked(jnp.squeeze, axis)
|