sequence-layers 0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. sequence_layers/__init__.py +16 -0
  2. sequence_layers/internal/types.py +521 -0
  3. sequence_layers/jax/__init__.py +29 -0
  4. sequence_layers/jax/attention.py +6124 -0
  5. sequence_layers/jax/combinators.py +1907 -0
  6. sequence_layers/jax/conditioning.py +511 -0
  7. sequence_layers/jax/convolution.py +2103 -0
  8. sequence_layers/jax/dense.py +447 -0
  9. sequence_layers/jax/dsp.py +1686 -0
  10. sequence_layers/jax/examples/gemma3n_audio_encoder.py +358 -0
  11. sequence_layers/jax/export.py +313 -0
  12. sequence_layers/jax/meta.py +54 -0
  13. sequence_layers/jax/normalization.py +889 -0
  14. sequence_layers/jax/pooling.py +925 -0
  15. sequence_layers/jax/position.py +370 -0
  16. sequence_layers/jax/recurrent.py +674 -0
  17. sequence_layers/jax/sharding.py +48 -0
  18. sequence_layers/jax/signal.py +511 -0
  19. sequence_layers/jax/simple.py +2679 -0
  20. sequence_layers/jax/test_utils.py +1343 -0
  21. sequence_layers/jax/time_varying.py +673 -0
  22. sequence_layers/jax/types.py +1537 -0
  23. sequence_layers/jax/typing.py +59 -0
  24. sequence_layers/jax/utils.py +2149 -0
  25. sequence_layers/tensorflow/__init__.py +56 -0
  26. sequence_layers/tensorflow/attention.py +3426 -0
  27. sequence_layers/tensorflow/combinators.py +938 -0
  28. sequence_layers/tensorflow/conditioning.py +644 -0
  29. sequence_layers/tensorflow/convolution.py +1855 -0
  30. sequence_layers/tensorflow/dense.py +285 -0
  31. sequence_layers/tensorflow/dsp.py +740 -0
  32. sequence_layers/tensorflow/examples/bert.py +144 -0
  33. sequence_layers/tensorflow/examples/conformer.py +138 -0
  34. sequence_layers/tensorflow/examples/deep_voice.py +72 -0
  35. sequence_layers/tensorflow/examples/listen_attend_spell.py +102 -0
  36. sequence_layers/tensorflow/examples/mobilenet.py +92 -0
  37. sequence_layers/tensorflow/examples/t5.py +225 -0
  38. sequence_layers/tensorflow/examples/tacotron.py +124 -0
  39. sequence_layers/tensorflow/examples/transformer.py +159 -0
  40. sequence_layers/tensorflow/examples/very_attentive_tacotron.py +1771 -0
  41. sequence_layers/tensorflow/examples/wavernn.py +225 -0
  42. sequence_layers/tensorflow/normalization.py +1127 -0
  43. sequence_layers/tensorflow/pooling.py +462 -0
  44. sequence_layers/tensorflow/position.py +509 -0
  45. sequence_layers/tensorflow/recurrent.py +645 -0
  46. sequence_layers/tensorflow/simple.py +1207 -0
  47. sequence_layers/tensorflow/squeeze.py +178 -0
  48. sequence_layers/tensorflow/test_util.py +834 -0
  49. sequence_layers/tensorflow/time_varying.py +439 -0
  50. sequence_layers/tensorflow/types.py +961 -0
  51. sequence_layers/tensorflow/utils.py +858 -0
  52. sequence_layers-0.1.dist-info/METADATA +69 -0
  53. sequence_layers-0.1.dist-info/RECORD +55 -0
  54. sequence_layers-0.1.dist-info/WHEEL +4 -0
  55. sequence_layers-0.1.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,370 @@
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
+ """Position embeddings and timing signals."""
15
+
16
+ import dataclasses
17
+
18
+ import flax.linen as nn
19
+ import jax
20
+ import jax.numpy as jnp
21
+ import numpy as np
22
+ from sequence_layers.jax import types
23
+ from sequence_layers.jax import utils
24
+
25
+ __all__ = (
26
+ # go/keep-sorted start
27
+ 'AddTimingSignal',
28
+ 'ApplyRotaryPositionalEncoding',
29
+ # go/keep-sorted end
30
+ )
31
+
32
+
33
+ class AddTimingSignal(
34
+ types.PreservesType, types.PreservesShape, types.SequenceLayer
35
+ ):
36
+ """Adds sinusoids at varying frequencies to the input channels dimension."""
37
+
38
+ @dataclasses.dataclass(frozen=True)
39
+ class Config(types.SequenceLayerConfig):
40
+ """Config for AddTimingSignal."""
41
+
42
+ min_timescale: float = 1.0
43
+ max_timescale: float = 1.0e4
44
+ trainable_scale: bool = False
45
+ # Channel axes over which the timing signal's entries should vary.
46
+ axes: int | tuple[int, ...] | None = None
47
+ sharding: types.Sharding | None = None
48
+ param_dtype: types.DType = jnp.float32
49
+ # If true, only advances position counter for valid timesteps. If false, the
50
+ # position is determined by the physical length of the inputs.
51
+ only_advance_position_for_valid_timesteps: bool = True
52
+ name: str | None = None
53
+
54
+ def make(self) -> 'AddTimingSignal':
55
+ return AddTimingSignal(self, name=self.name)
56
+
57
+ config: Config
58
+
59
+ def setup(self) -> None:
60
+ if self.config.trainable_scale:
61
+ self.scale = self.param(
62
+ 'scale',
63
+ utils.shard_initializer(
64
+ nn.initializers.ones_init(),
65
+ self.config.sharding,
66
+ ),
67
+ [],
68
+ self.config.param_dtype,
69
+ )
70
+ else:
71
+ self.scale = None
72
+
73
+ @nn.nowrap
74
+ def _check_inputs(self, input_spec: types.ShapeDType):
75
+ if input_spec.dtype not in (
76
+ jnp.float16,
77
+ jnp.bfloat16,
78
+ jnp.float32,
79
+ jnp.float64,
80
+ ):
81
+ raise ValueError(
82
+ f'{type(self).__name__} requires floating point argument.'
83
+ )
84
+
85
+ @property
86
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
87
+ if self.config.only_advance_position_for_valid_timesteps:
88
+ return {0: (-np.inf, 0)}
89
+ else:
90
+ return {0: (0, 0)}
91
+
92
+ def get_initial_state(
93
+ self,
94
+ batch_size: int,
95
+ input_spec: types.ShapeDType,
96
+ *,
97
+ training: bool,
98
+ constants: types.Constants | None = None,
99
+ ) -> types.State:
100
+ self._check_inputs(input_spec)
101
+
102
+ # State holds the current timestep (batched).
103
+ if self.config.only_advance_position_for_valid_timesteps:
104
+ return jnp.full((batch_size, 1), -1, dtype=jnp.int32)
105
+ else:
106
+ return jnp.zeros((batch_size, 1), dtype=jnp.int32)
107
+
108
+ @types.check_step
109
+ def step(
110
+ self,
111
+ x: types.Sequence,
112
+ state: types.State,
113
+ *,
114
+ training: bool,
115
+ constants: types.Constants | None = None,
116
+ ) -> tuple[types.Sequence, types.State]:
117
+ self._check_inputs(x.channel_spec)
118
+ time = x.shape[1]
119
+ target_shape = utils.match_shape_along_axes(
120
+ x.channel_shape, axes=self.config.axes
121
+ )
122
+ # Get positions for the batch.
123
+ if self.config.only_advance_position_for_valid_timesteps:
124
+ position = state + jnp.cumsum(x.mask.astype(jnp.int32), axis=1)
125
+ state = position[:, -1:]
126
+ else:
127
+ position = state + jnp.arange(time, dtype=jnp.int32)
128
+ state = state + time
129
+
130
+ timing_signal = utils.get_timing_signal_1d_pos(
131
+ position,
132
+ np.prod(target_shape),
133
+ min_timescale=self.config.min_timescale,
134
+ max_timescale=self.config.max_timescale,
135
+ dtype=self.config.param_dtype,
136
+ )
137
+ batch_size = x.shape[0]
138
+ timing_signal = jnp.reshape(
139
+ timing_signal, [batch_size, time] + list(target_shape)
140
+ )
141
+ if self.scale is not None:
142
+ scale: jax.Array = self.scale
143
+ timing_signal *= scale
144
+ x = x.apply_values(lambda v: v + timing_signal.astype(v.dtype))
145
+ return x, state
146
+
147
+ @types.check_layer
148
+ def layer(
149
+ self,
150
+ x: types.Sequence,
151
+ *,
152
+ training: bool,
153
+ constants: types.Constants | None = None,
154
+ ) -> types.Sequence:
155
+ self._check_inputs(x.channel_spec)
156
+ target_shape = utils.match_shape_along_axes(
157
+ x.channel_shape, axes=self.config.axes
158
+ )
159
+ if self.config.only_advance_position_for_valid_timesteps:
160
+ position = jnp.maximum(
161
+ 0, jnp.cumsum(x.mask.astype(jnp.int32), axis=1) - 1
162
+ )
163
+ else:
164
+ position = jnp.arange(x.shape[1], dtype=jnp.int32)[jnp.newaxis, :]
165
+ timing_signal = utils.get_timing_signal_1d_pos(
166
+ position,
167
+ np.prod(target_shape),
168
+ min_timescale=self.config.min_timescale,
169
+ max_timescale=self.config.max_timescale,
170
+ dtype=self.config.param_dtype,
171
+ )
172
+ timing_signal = jnp.reshape(
173
+ timing_signal, position.shape[:2] + target_shape
174
+ )
175
+ if self.scale is not None:
176
+ scale: jax.Array = self.scale
177
+ timing_signal *= scale
178
+ x = x.apply_values(lambda v: v + timing_signal.astype(v.dtype))
179
+ return x
180
+
181
+
182
+ class ApplyRotaryPositionalEncoding(
183
+ types.PreservesType, types.PreservesShape, types.SequenceLayer
184
+ ):
185
+ """Applies Rotary Positional Encodings (RoPE) to the sequence.
186
+
187
+ See the blogpost https://blog.eleuther.ai/rotary-embeddings/ and the paper
188
+ https://arxiv.org/abs/2104.09864.
189
+ """
190
+
191
+ @dataclasses.dataclass(frozen=True)
192
+ class Config(types.SequenceLayerConfig):
193
+ """Config for ApplyRotaryPositionalEncoding."""
194
+
195
+ max_wavelength: float
196
+ axis: int = -1
197
+ # If true, only advances position counter for valid timesteps. If false, the
198
+ # position is determined by the physical length of the inputs.
199
+ only_advance_position_for_valid_timesteps: bool = True
200
+ # Whether RoPE should be applied with positions in at least float32. This
201
+ # option is for backwards compatibility. True is the recommended value.
202
+ positions_in_at_least_fp32: bool = True
203
+ # If specified, the [batch_size, time] jnp.int32 position used for computing
204
+ # RoPE will be read from the constants dictionary with this name. Otherwise,
205
+ # the physical position in the array is used. If specified,
206
+ # only_advance_position_for_valid_timesteps has no effect.
207
+ positions_name: str | None = None
208
+ # An optional name for the layer.
209
+ name: str | None = None
210
+
211
+ def make(self) -> 'ApplyRotaryPositionalEncoding':
212
+ return ApplyRotaryPositionalEncoding(self, name=self.name)
213
+
214
+ config: Config
215
+
216
+ def setup(self) -> None:
217
+ if (
218
+ self.config.only_advance_position_for_valid_timesteps
219
+ and self.config.positions_name
220
+ ):
221
+ raise ValueError(
222
+ 'only_advance_position_for_valid_timesteps is incompatible with'
223
+ f' {self.config.positions_name=}.'
224
+ )
225
+
226
+ @property
227
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
228
+ if self.config.only_advance_position_for_valid_timesteps:
229
+ return {0: (-np.inf, 0)}
230
+ else:
231
+ return {0: (0, 0)}
232
+
233
+ @nn.nowrap
234
+ def _check_inputs(self, input_spec: types.ShapeDType):
235
+ if input_spec.dtype not in (
236
+ jnp.float16,
237
+ jnp.bfloat16,
238
+ jnp.float32,
239
+ jnp.float64,
240
+ ):
241
+ raise ValueError(
242
+ f'{type(self).__name__} requires floating point argument.'
243
+ )
244
+ input_shape = (None, None) + input_spec.shape
245
+ axis = (
246
+ self.config.axis + len(input_shape)
247
+ if self.config.axis < 0
248
+ else self.config.axis
249
+ )
250
+ if axis <= 1:
251
+ raise ValueError(
252
+ f'{type(self).__name__} axis ({self.config.axis}) must refer to a'
253
+ f' channels dimension ({input_spec=}).'
254
+ )
255
+ axis_size = input_shape[axis]
256
+ if axis_size % 2 != 0:
257
+ raise ValueError(
258
+ f'{type(self).__name__} requires input_shape[{axis}]={axis_size} to'
259
+ ' be even.'
260
+ )
261
+
262
+ def get_initial_state(
263
+ self,
264
+ batch_size: int,
265
+ input_spec: types.ShapeDType,
266
+ *,
267
+ training: bool,
268
+ constants: types.Constants | None = None,
269
+ ) -> types.State:
270
+ self._check_inputs(input_spec)
271
+
272
+ # State holds the current timestep (batched). If step_positions_name is
273
+ # specified, the layer does not track position internally.
274
+ if self.config.positions_name:
275
+ return ()
276
+ elif self.config.only_advance_position_for_valid_timesteps:
277
+ return jnp.full((batch_size, 1), -1, dtype=jnp.int32)
278
+ else:
279
+ return jnp.zeros((batch_size, 1), dtype=jnp.int32)
280
+
281
+ @nn.nowrap
282
+ def _apply_rope(self, x: jax.Array, positions: jax.Array) -> jax.Array:
283
+ axis = (
284
+ self.config.axis + x.ndim if self.config.axis < 0 else self.config.axis
285
+ )
286
+ assert axis > 1
287
+ channel_ndim = x.ndim - 2
288
+ broadcast_shape = [1] * x.ndim
289
+ axis_dim = x.shape[axis]
290
+ broadcast_shape[axis] = axis_dim // 2
291
+ assert axis_dim % 2 == 0
292
+
293
+ freq_exponents = 2.0 * jnp.arange(axis_dim // 2) / axis_dim
294
+ timescale = self.config.max_wavelength**freq_exponents
295
+
296
+ @utils.maybe_in_at_least_fp32(
297
+ self.config.positions_in_at_least_fp32,
298
+ restore_dtypes=False,
299
+ )
300
+ def apply_position_embeddings(positions):
301
+ radians = positions.reshape(
302
+ positions.shape + (1,) * channel_ndim
303
+ ) / timescale.reshape(broadcast_shape)
304
+ sin, cos = jnp.sin(radians), jnp.cos(radians)
305
+ x1, x2 = jnp.split(x, 2, axis=axis)
306
+ return jnp.concatenate(
307
+ [x1 * cos - x2 * sin, x2 * cos + x1 * sin], axis=axis, dtype=x.dtype
308
+ )
309
+
310
+ return apply_position_embeddings(positions)
311
+
312
+ @types.check_step
313
+ def step(
314
+ self,
315
+ x: types.Sequence,
316
+ state: types.State,
317
+ *,
318
+ training: bool,
319
+ constants: types.Constants | None = None,
320
+ ) -> tuple[types.Sequence, types.State]:
321
+ self._check_inputs(x.channel_spec)
322
+ x_time = x.shape[1]
323
+
324
+ # Get positions for the batch.
325
+ if self.config.positions_name:
326
+ positions = utils.get_constant_array(
327
+ self,
328
+ constants,
329
+ self.config.positions_name,
330
+ expected_shape=(x.shape[0], x_time),
331
+ unpack_sequence=True,
332
+ allow_broadcastable=True,
333
+ )
334
+ elif self.config.only_advance_position_for_valid_timesteps:
335
+ positions = state + jnp.cumsum(x.mask.astype(jnp.int32), axis=1)
336
+ state = positions[:, -1:]
337
+ else:
338
+ positions = state + jnp.arange(x_time, dtype=jnp.int32)
339
+ state = state + x_time
340
+ utils.assert_is_compatible_with(positions.shape, [x.shape[0], x_time])
341
+
342
+ y = x.apply_values(self._apply_rope, positions)
343
+ return y, state
344
+
345
+ @types.check_layer
346
+ def layer(
347
+ self,
348
+ x: types.Sequence,
349
+ *,
350
+ training: bool,
351
+ constants: types.Constants | None = None,
352
+ ) -> types.Sequence:
353
+ self._check_inputs(x.channel_spec)
354
+ if self.config.positions_name:
355
+ positions = utils.get_constant_array(
356
+ self,
357
+ constants,
358
+ self.config.positions_name,
359
+ expected_shape=x.shape[:2],
360
+ unpack_sequence=True,
361
+ allow_broadcastable=True,
362
+ )
363
+ elif self.config.only_advance_position_for_valid_timesteps:
364
+ positions = jnp.maximum(
365
+ 0, jnp.cumsum(x.mask.astype(jnp.int32), axis=1) - 1
366
+ )
367
+ else:
368
+ positions = jnp.arange(x.shape[1], dtype=jnp.int32)[jnp.newaxis, :]
369
+ x = x.apply_values(self._apply_rope, positions)
370
+ return x