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,938 @@
1
+ # Copyright 2023 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Combinator layers."""
15
+
16
+ import collections
17
+ import enum
18
+ import fractions
19
+ from typing import Callable, Generator, List, Optional, Sequence, Tuple
20
+
21
+ from absl import logging
22
+ import numpy as np
23
+ from sequence_layers.tensorflow import dense
24
+ from sequence_layers.tensorflow import simple
25
+ from sequence_layers.tensorflow import types
26
+ from sequence_layers.tensorflow import utils
27
+ import tensorflow.compat.v2 as tf
28
+
29
+ # Either a SequenceLayer, a list of SequenceLayers, or a callable that returns
30
+ # a SequenceLayer or a list of SequenceLayers.
31
+ SequenceLayerOrList = types.SequenceLayer | Sequence[types.SequenceLayer]
32
+ SequenceLayerListOrCallable = (
33
+ SequenceLayerOrList | Callable[[], SequenceLayerOrList]
34
+ )
35
+
36
+
37
+ def _maybe_wrap_layers(
38
+ module: tf.Module, layers: SequenceLayerListOrCallable
39
+ ) -> types.SequenceLayer:
40
+ if callable(layers):
41
+ with module.name_scope:
42
+ layers = layers()
43
+
44
+ if isinstance(layers, types.SequenceLayer):
45
+ return layers
46
+ else:
47
+ return _SerialWithoutNameScopes(layers)
48
+
49
+
50
+ def _insert_with_unique_key(
51
+ emits: collections.OrderedDict[str, types.Emits], key: str, value
52
+ ) -> str:
53
+ """Inserts value into emits with a unique name prefixed by key."""
54
+ if key not in emits:
55
+ emits[key] = value
56
+ return key
57
+ i = 1
58
+ while True:
59
+ unique_key = f'{key}_{i}'
60
+ if unique_key not in emits:
61
+ emits[unique_key] = value
62
+ return unique_key
63
+ i += 1
64
+
65
+
66
+ class _SerialWithoutNameScopes(types.Emitting):
67
+ """Applies a sequence of layers in series.
68
+
69
+ Private implementation of Serial which doesn't introduce new name_scopes.
70
+ This is only intended to be used as an implementation detail within other
71
+ SequenceLayers.
72
+ """
73
+
74
+ @classmethod
75
+ def _default_name(cls):
76
+ # TF1 does not allow _serial_without_name_scopes.
77
+ return 'serial_without_name_scopes'
78
+
79
+ def __init__(
80
+ self,
81
+ layers: Sequence[types.SequenceLayer]
82
+ | Callable[[], Sequence[types.SequenceLayer]],
83
+ debug=False,
84
+ name: Optional[str] = None,
85
+ ):
86
+ super().__init__(name=name)
87
+ if callable(layers):
88
+ # This is _SerialWithoutNameScopes, but the only way a callable gets
89
+ # passed here is if we are a Serial, so call the callable in our name
90
+ # scope.
91
+ with self.name_scope:
92
+ layers = layers()
93
+ self._layers = layers[:] # Copy the list.
94
+ self._debug = debug
95
+
96
+ @property
97
+ def supports_step(self) -> bool:
98
+ return all(layer.supports_step for layer in self._layers)
99
+
100
+ @property
101
+ def block_size(self) -> int:
102
+ block_size = fractions.Fraction(1)
103
+ output_ratio = fractions.Fraction(1)
104
+
105
+ for layer in self._layers:
106
+ layer_output_ratio = layer.output_ratio
107
+ layer_block_size = layer.block_size
108
+ block_size = (
109
+ np.lcm(block_size * output_ratio, layer_block_size) / output_ratio
110
+ )
111
+ output_ratio *= layer_output_ratio
112
+
113
+ assert block_size.denominator == 1
114
+ return block_size.numerator
115
+
116
+ @property
117
+ def output_ratio(self) -> fractions.Fraction:
118
+ output_ratio = fractions.Fraction(1)
119
+ for layer in self._layers:
120
+ output_ratio *= layer.output_ratio
121
+ return output_ratio
122
+
123
+ def get_initial_state(
124
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
125
+ ) -> types.State:
126
+ states = []
127
+ for layer_i, layer in enumerate(self._layers):
128
+ # get_initial_state can create variables (it shouldn't, but it does).
129
+ with tf.name_scope('layer%d' % layer_i):
130
+ state = layer.get_initial_state(x, constants)
131
+ states.append(state)
132
+ output_shape = layer.get_output_shape_for_sequence(x, constants)
133
+ output_dtype = layer.get_output_dtype(x.dtype)
134
+ batch_size = utils.smart_dimension_size(x.values, 0)
135
+ x = types.Sequence(
136
+ tf.zeros(
137
+ [batch_size, 0] + output_shape.as_list(), dtype=output_dtype
138
+ ),
139
+ tf.ones([batch_size, 0], dtype=x.mask.dtype),
140
+ )
141
+ return states
142
+
143
+ def get_output_shape(
144
+ self,
145
+ input_shape: tf.TensorShape,
146
+ constants: Optional[types.Constants] = None,
147
+ ) -> tf.TensorShape:
148
+ output_shape = input_shape
149
+ for layer in self._layers:
150
+ output_shape = layer.get_output_shape(output_shape, constants)
151
+ return output_shape
152
+
153
+ def get_emit_specs(
154
+ self,
155
+ input_spec: tf.TensorSpec,
156
+ constants: Optional[types.Constants] = None,
157
+ ) -> types.EmitSpecs:
158
+ output_spec = input_spec
159
+ emit_specs = collections.OrderedDict()
160
+ for layer in self._layers:
161
+ layer_emit_specs = layer.get_emit_specs(output_spec, constants)
162
+ _insert_with_unique_key(emit_specs, layer.name, layer_emit_specs)
163
+ output_spec = layer.get_output_spec(output_spec, constants)
164
+ return emit_specs
165
+
166
+ def get_output_dtype(self, input_dtype: tf.DType) -> tf.DType:
167
+ output_dtype = input_dtype
168
+ for layer in self._layers:
169
+ output_dtype = layer.get_output_dtype(output_dtype)
170
+ return output_dtype
171
+
172
+ def step_with_emits(
173
+ self,
174
+ x: types.Sequence,
175
+ state: types.State,
176
+ training: bool,
177
+ constants: Optional[types.Constants] = None,
178
+ ) -> Tuple[types.Sequence, types.State, types.Emits]:
179
+ layer_states = []
180
+ emits = collections.OrderedDict()
181
+ assert len(self._layers) == len(state)
182
+ for layer_i, (layer, layer_state) in enumerate(zip(self._layers, state)):
183
+ with tf.name_scope('layer%d' % layer_i):
184
+ if self._debug:
185
+ logging.debug('step layer_i=%d x=%s', layer_i, x)
186
+ old_x, old_layer_state = x, layer_state
187
+ x, layer_state, layer_emits = layer.step_with_emits(
188
+ x, layer_state, training=training, constants=constants
189
+ )
190
+ if not x.channel_shape.is_fully_defined():
191
+ raise ValueError(
192
+ '%s caused input=%s state=%s to become undefined: %s'
193
+ % (layer, old_x, old_layer_state, x)
194
+ )
195
+ if self._debug:
196
+ logging.debug('step layer_i=%d -> x=%s', layer_i, x)
197
+ layer_states.append(layer_state)
198
+ _insert_with_unique_key(emits, layer.name, layer_emits)
199
+ return x, layer_states, emits
200
+
201
+ def layer_with_emits(
202
+ self,
203
+ x: types.Sequence,
204
+ training: bool,
205
+ initial_state: Optional[types.State] = None,
206
+ constants: Optional[types.Constants] = None,
207
+ ) -> Tuple[types.Sequence, types.Emits]:
208
+ if initial_state is None:
209
+ initial_state = [None] * len(self._layers)
210
+
211
+ emits = collections.OrderedDict()
212
+ assert len(self._layers) == len(initial_state)
213
+ for layer_i, (layer, layer_initial_state) in enumerate(
214
+ zip(self._layers, initial_state)
215
+ ):
216
+ with tf.name_scope('layer%d' % layer_i):
217
+ if self._debug:
218
+ logging.debug('layer layer_i=%d x=%s', layer_i, x)
219
+ x_old = x
220
+ x, layer_emits = layer.layer_with_emits(
221
+ x,
222
+ initial_state=layer_initial_state,
223
+ training=training,
224
+ constants=constants,
225
+ )
226
+ if not x.channel_shape.is_fully_defined():
227
+ raise ValueError(
228
+ '%s caused input=%s to become undefined: %s' % (layer, x_old, x)
229
+ )
230
+ if self._debug:
231
+ logging.debug('layer layer_i=%d -> x=%s', layer_i, x)
232
+ _insert_with_unique_key(emits, layer.name, layer_emits)
233
+ return x, emits
234
+
235
+ def _yield_emits(
236
+ self, emits: types.Emits
237
+ ) -> Generator[tuple[types.SequenceLayer, types.Emits], None, None]:
238
+ yield from super()._yield_emits(emits)
239
+ key_map = collections.OrderedDict()
240
+ for layer in self._layers:
241
+ # Figure out the key we inserted the emit with.
242
+ key = _insert_with_unique_key(key_map, layer.name, None)
243
+ yield from layer._yield_emits(emits[key]) # pylint: disable=protected-access
244
+
245
+
246
+ class Serial(_SerialWithoutNameScopes):
247
+ """Applies a sequence of layers in series.
248
+
249
+ The emit structure for a Serial layer is an OrderedDict of the emits for each
250
+ of the layers in the Serial whose keys are the layer names and the order is
251
+ the order of layers in the Serial. When a duplicate name exists, a "_X" suffix
252
+ is appended to the layer's name to form the key, where X is an increasing
253
+ integer starting with 1.
254
+ """
255
+
256
+ @classmethod
257
+ def _default_name(cls):
258
+ # Override _SerialWithoutNameScopes._default_name
259
+ return 'serial'
260
+
261
+ @tf.Module.with_name_scope
262
+ def step_with_emits(
263
+ self,
264
+ x: types.Sequence,
265
+ state: types.State,
266
+ training: bool,
267
+ constants: Optional[types.Constants] = None,
268
+ ) -> Tuple[types.Sequence, types.State, types.Emits]:
269
+ return super().step_with_emits(x, state, training, constants)
270
+
271
+ @tf.Module.with_name_scope
272
+ def layer_with_emits(
273
+ self,
274
+ x: types.Sequence,
275
+ training: bool,
276
+ initial_state: Optional[types.State] = None,
277
+ constants: Optional[types.Constants] = None,
278
+ ) -> Tuple[types.Sequence, types.Emits]:
279
+ return super().layer_with_emits(x, training, initial_state, constants)
280
+
281
+
282
+ class Parallel(types.Emitting):
283
+ """Applies a sequence of layers in parallel.
284
+
285
+ Outputs are broadcasted and stacked to produce a [num_layers, ...] output
286
+ shape.
287
+ """
288
+
289
+ @enum.unique
290
+ class Combination(enum.Enum):
291
+ """The type of combination to perform."""
292
+
293
+ # Stack output of each parallel layer.
294
+ STACK = 1
295
+ # Broadcast-add the output of each parallel layer.
296
+ ADD = 2
297
+ # Broadcast-mean the output of each parallel layer.
298
+ MEAN = 3
299
+
300
+ def __init__(
301
+ self,
302
+ layers: Sequence[SequenceLayerListOrCallable],
303
+ debug=False,
304
+ combination: Combination = Combination.STACK,
305
+ name: Optional[str] = None,
306
+ ):
307
+ super().__init__(name=name)
308
+ self._layers = []
309
+ for layer in layers:
310
+ self._layers.append(_maybe_wrap_layers(self, layer))
311
+ self._debug = debug
312
+ self._combination = combination
313
+
314
+ output_ratios = [l.output_ratio for l in self._layers]
315
+ if output_ratios:
316
+ for layer, output_ratio in zip(self._layers, output_ratios):
317
+ if output_ratio != output_ratios[0]:
318
+ raise ValueError(
319
+ 'Output ratios must be equal for all layers: '
320
+ f'{output_ratios[0]} != {output_ratio} for {layer}'
321
+ )
322
+ self._output_ratio = output_ratios[0]
323
+ else:
324
+ self._output_ratio = fractions.Fraction(1)
325
+
326
+ @property
327
+ def supports_step(self) -> bool:
328
+ return all(layer.supports_step for layer in self._layers)
329
+
330
+ @property
331
+ def block_size(self) -> int:
332
+ block_size = 1
333
+ for layer in self._layers:
334
+ block_size = np.lcm(block_size, layer.block_size)
335
+ return int(block_size)
336
+
337
+ @property
338
+ def output_ratio(self) -> fractions.Fraction:
339
+ return self._output_ratio
340
+
341
+ @tf.Module.with_name_scope
342
+ def get_initial_state(
343
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
344
+ ) -> types.State:
345
+ states = []
346
+ for layer_i, layer in enumerate(self._layers):
347
+ # get_initial_state can create variables (it shouldn't, but it does).
348
+ with tf.name_scope('layer%d' % layer_i):
349
+ states.append(layer.get_initial_state(x, constants))
350
+ return states
351
+
352
+ def get_output_shape(
353
+ self,
354
+ input_shape: tf.TensorShape,
355
+ constants: Optional[types.Constants] = None,
356
+ ) -> tf.TensorShape:
357
+ if not self._layers:
358
+ return input_shape
359
+
360
+ output_shape = self._layers[0].get_output_shape(input_shape, constants)
361
+ for layer in self._layers[1:]:
362
+ layer_output_shape = layer.get_output_shape(input_shape, constants)
363
+ try:
364
+ output_shape = tf.broadcast_static_shape(
365
+ output_shape, layer_output_shape
366
+ )
367
+ except ValueError as e:
368
+ raise ValueError(
369
+ 'Layer output shapes are not broadcastable: '
370
+ f'{layer_output_shape} != {output_shape}.'
371
+ ) from e
372
+
373
+ if self._combination == Parallel.Combination.STACK:
374
+ return tf.TensorShape([len(self._layers)]).concatenate(output_shape)
375
+ else:
376
+ return output_shape
377
+
378
+ def get_emit_specs(
379
+ self,
380
+ input_spec: tf.TensorSpec,
381
+ constants: Optional[types.Constants] = None,
382
+ ) -> types.EmitSpecs:
383
+ emit_specs = collections.OrderedDict()
384
+ for layer in self._layers:
385
+ layer_emit_specs = layer.get_emit_specs(input_spec, constants)
386
+ _insert_with_unique_key(emit_specs, layer.name, layer_emit_specs)
387
+ return emit_specs
388
+
389
+ def get_output_dtype(self, input_dtype: tf.DType) -> tf.DType:
390
+ output_dtypes = [l.get_output_dtype(input_dtype) for l in self._layers]
391
+ output_dtype = output_dtypes[0] if output_dtypes else input_dtype
392
+ for output_dtype, layer in zip(output_dtypes, self._layers):
393
+ if output_dtype != output_dtypes[0]:
394
+ raise ValueError(f'Incompatible dtypes: {output_dtype} for {layer}.')
395
+ return output_dtype
396
+
397
+ def _combine_outputs(self, ys: List[types.Sequence]) -> types.Sequence:
398
+ assert ys
399
+ channel_shape = ys[0].channel_shape
400
+ mask = ys[0].mask
401
+ for y in ys[1:]:
402
+ channel_shape = tf.broadcast_static_shape(channel_shape, y.channel_shape)
403
+ mask = utils.combine_mask(mask, y.mask)
404
+
405
+ values = []
406
+ for y in ys:
407
+ batch, time = utils.smart_dimension_size(y.values, [0, 1])
408
+ values.append(
409
+ tf.broadcast_to(
410
+ types.expand_to_rank(y.values, 2 + len(channel_shape)),
411
+ [batch, time] + channel_shape.as_list(),
412
+ )
413
+ )
414
+ if self._combination == Parallel.Combination.STACK:
415
+ values = tf.stack(values, axis=2, name='values')
416
+ elif self._combination == Parallel.Combination.ADD:
417
+ values = tf.add_n(values, name='values')
418
+ else:
419
+ assert self._combination == Parallel.Combination.MEAN
420
+ values = tf.identity(tf.add_n(values) / len(values), name='values')
421
+
422
+ mask = tf.identity(mask, name='mask')
423
+ return types.Sequence(values, mask)
424
+
425
+ @tf.Module.with_name_scope
426
+ def step_with_emits(
427
+ self,
428
+ x: types.Sequence,
429
+ state: types.State,
430
+ training: bool,
431
+ constants: Optional[types.Constants] = None,
432
+ ) -> Tuple[types.Sequence, types.State, types.Emits]:
433
+ layer_states = []
434
+ emits = collections.OrderedDict()
435
+ assert len(self._layers) == len(state)
436
+
437
+ if not self._layers:
438
+ return x, state, emits
439
+
440
+ ys = []
441
+ for layer_i, (layer, layer_state) in enumerate(zip(self._layers, state)):
442
+ with tf.name_scope('layer%d' % layer_i):
443
+ if self._debug:
444
+ logging.debug('step layer_i=%d x=%s', layer_i, x)
445
+ old_layer_state = layer_state
446
+ y_i, layer_state, layer_emits = layer.step_with_emits(
447
+ x, layer_state, training=training, constants=constants
448
+ )
449
+ ys.append(y_i)
450
+ if not y_i.channel_shape.is_fully_defined():
451
+ raise ValueError(
452
+ '%s caused input=%s state=%s to become undefined: %s'
453
+ % (layer, x, old_layer_state, y_i)
454
+ )
455
+ if self._debug:
456
+ logging.debug('step layer_i=%d -> y_i=%s', layer_i, y_i)
457
+ layer_states.append(layer_state)
458
+ _insert_with_unique_key(emits, layer.name, layer_emits)
459
+ y = self._combine_outputs(ys).mask_invalid()
460
+ return y, layer_states, emits
461
+
462
+ @tf.Module.with_name_scope
463
+ def layer_with_emits(
464
+ self,
465
+ x: types.Sequence,
466
+ training: bool,
467
+ initial_state: Optional[types.State] = None,
468
+ constants: Optional[types.Constants] = None,
469
+ ) -> Tuple[types.Sequence, types.Emits]:
470
+ if initial_state is None:
471
+ initial_state = [None] * len(self._layers)
472
+
473
+ emits = collections.OrderedDict()
474
+ assert len(self._layers) == len(initial_state)
475
+
476
+ if not self._layers:
477
+ return x, emits
478
+ ys = []
479
+ for layer_i, (layer, layer_initial_state) in enumerate(
480
+ zip(self._layers, initial_state)
481
+ ):
482
+ with tf.name_scope('layer%d' % layer_i):
483
+ if self._debug:
484
+ logging.debug('layer layer_i=%d x=%s', layer_i, x)
485
+ x_old = x
486
+ y_i, layer_emits = layer.layer_with_emits(
487
+ x,
488
+ initial_state=layer_initial_state,
489
+ training=training,
490
+ constants=constants,
491
+ )
492
+ ys.append(y_i)
493
+ if not y_i.channel_shape.is_fully_defined():
494
+ raise ValueError(
495
+ '%s caused input=%s to become undefined: %s' % (layer, x_old, y_i)
496
+ )
497
+ if self._debug:
498
+ logging.debug('layer layer_i=%d -> y_i=%s', layer_i, y_i)
499
+ _insert_with_unique_key(emits, layer.name, layer_emits)
500
+ y = self._combine_outputs(ys).mask_invalid()
501
+ return y, emits
502
+
503
+ def _yield_emits(
504
+ self, emits: types.Emits
505
+ ) -> Generator[tuple[types.SequenceLayer, types.Emits], None, None]:
506
+ yield from super()._yield_emits(emits)
507
+ key_map = collections.OrderedDict()
508
+ for layer in self._layers:
509
+ # Figure out the key we inserted the emit with.
510
+ key = _insert_with_unique_key(key_map, layer.name, None)
511
+ yield from layer._yield_emits(emits[key]) # pylint: disable=protected-access
512
+
513
+
514
+ class Residual(types.Emitting):
515
+ """A residual wrapper around l that computes `y = l(x) + shortcut(x)`.
516
+
517
+ If shortcut is not provided, it defaults to an identity or a linear projection
518
+ to match the output shape of l(x).
519
+ """
520
+
521
+ def __init__(
522
+ self,
523
+ layer: SequenceLayerListOrCallable,
524
+ shortcut_layer: Optional[SequenceLayerListOrCallable] = None,
525
+ name: Optional[str] = None,
526
+ ):
527
+ super().__init__(name=name)
528
+ self._layer = _maybe_wrap_layers(self, layer)
529
+ # If shortcut_layer is not None, we build a projection layer that depends
530
+ # on input size, so we have to lazily build.
531
+ if shortcut_layer is None:
532
+ self._shortcut_layer = shortcut_layer
533
+ else:
534
+ self._shortcut_layer = _maybe_wrap_layers(self, shortcut_layer)
535
+
536
+ if (
537
+ self._shortcut_layer
538
+ and self._shortcut_layer.output_ratio != self._layer.output_ratio
539
+ ):
540
+ raise ValueError(
541
+ 'layer and shortcut_layer must have the same output '
542
+ f'ratio {self._layer.output_ratio} != '
543
+ f'{self._shortcut_layer.output_ratio}.'
544
+ )
545
+ elif self._shortcut_layer is None and self._layer.output_ratio != 1:
546
+ raise ValueError(
547
+ 'Residual requires output_ratio 1, got: %s, output_ratio=%s'
548
+ % (self._layer, self._layer.output_ratio)
549
+ )
550
+
551
+ @property
552
+ def supports_step(self) -> bool:
553
+ supports_step = self._layer.supports_step
554
+ if self._shortcut_layer:
555
+ supports_step = supports_step and self._shortcut_layer.supports_step
556
+ return supports_step # pytype: disable=bad-return-type # bind-properties
557
+
558
+ @property
559
+ def block_size(self) -> int:
560
+ if self._shortcut_layer:
561
+ return int(
562
+ np.lcm(self._layer.block_size, self._shortcut_layer.block_size)
563
+ )
564
+ return self._layer.block_size
565
+
566
+ @property
567
+ def output_ratio(self) -> fractions.Fraction:
568
+ return self._layer.output_ratio
569
+
570
+ def build(self, x, constants: Optional[types.Constants] = None):
571
+ if self._shortcut_layer is None:
572
+ input_shape = x.channel_shape
573
+ output_shape = self._layer.get_output_shape(input_shape, constants)
574
+ if input_shape != output_shape:
575
+ # Linear projection to make shapes match.
576
+ self._shortcut_layer = dense.DenseShaped(
577
+ output_shape, name='residual_projection'
578
+ )
579
+ else:
580
+ self._shortcut_layer = simple.Identity()
581
+
582
+ layer_dtype = self._layer.get_output_dtype(x.dtype)
583
+ shortcut_dtype = self._shortcut_layer.get_output_dtype(x.dtype)
584
+ if shortcut_dtype != layer_dtype:
585
+ raise ValueError(
586
+ 'Residual connection must have same dtypes: '
587
+ f'layer: {layer_dtype} shortcut: {shortcut_dtype}'
588
+ )
589
+
590
+ @tf.Module.with_name_scope
591
+ def step_with_emits(
592
+ self,
593
+ x,
594
+ state,
595
+ training=False,
596
+ constants: Optional[types.Constants] = None,
597
+ ) -> Tuple[types.Sequence, types.State, types.Emits]:
598
+ self.build(x, constants)
599
+ layer_state, shortcut_state = state
600
+ y, layer_state, emits = self._layer.step_with_emits(
601
+ x, layer_state, training=training, constants=constants
602
+ )
603
+ emits = collections.OrderedDict([[self._layer.name, emits]])
604
+ y_shortcut, shortcut_state = self._shortcut_layer.step(
605
+ x, shortcut_state, training=training, constants=constants
606
+ )
607
+
608
+ y_mask = utils.combine_mask(y_shortcut.mask, y.mask)
609
+ y = y.apply(lambda v, m: (v + y_shortcut.values, y_mask))
610
+ state = (layer_state, shortcut_state)
611
+ return y.mask_invalid(), state, emits
612
+
613
+ @tf.Module.with_name_scope
614
+ def layer_with_emits(
615
+ self,
616
+ x: types.Sequence,
617
+ training: bool,
618
+ initial_state: Optional[types.State] = None,
619
+ constants: Optional[types.Constants] = None,
620
+ ) -> Tuple[types.Sequence, types.Emits]:
621
+ self.build(x, constants)
622
+ if initial_state is None:
623
+ initial_shortcut_state = None
624
+ else:
625
+ initial_state, initial_shortcut_state = initial_state
626
+ y, emits = self._layer.layer_with_emits(
627
+ x, initial_state=initial_state, training=training, constants=constants
628
+ )
629
+ emits = collections.OrderedDict([[self._layer.name, emits]])
630
+ y_shortcut = self._shortcut_layer.layer(
631
+ x,
632
+ initial_state=initial_shortcut_state,
633
+ training=training,
634
+ constants=constants,
635
+ )
636
+ y_mask = utils.combine_mask(y_shortcut.mask, y.mask)
637
+ y = y.apply(lambda v, m: (v + y_shortcut.values, y_mask))
638
+ return y.mask_invalid(), emits
639
+
640
+ @tf.Module.with_name_scope
641
+ def get_initial_state(
642
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
643
+ ) -> types.State:
644
+ self.build(x, constants)
645
+ state = self._layer.get_initial_state(x, constants)
646
+ shortcut_state = self._shortcut_layer.get_initial_state(x, constants)
647
+ return state, shortcut_state
648
+
649
+ def get_output_shape(
650
+ self,
651
+ input_shape: tf.TensorShape,
652
+ constants: Optional[types.Constants] = None,
653
+ ) -> tf.TensorShape:
654
+ return self._layer.get_output_shape(input_shape, constants)
655
+
656
+ def get_emit_specs(
657
+ self,
658
+ input_spec: tf.TensorSpec,
659
+ constants: Optional[types.Constants] = None,
660
+ ) -> types.EmitSpecs:
661
+ return collections.OrderedDict(
662
+ [[self._layer.name, self._layer.get_emit_specs(input_spec, constants)]]
663
+ )
664
+
665
+ def _yield_emits(
666
+ self, emits: types.Emits
667
+ ) -> Generator[tuple[types.SequenceLayer, types.Emits], None, None]:
668
+ yield from super()._yield_emits(emits)
669
+ yield from self._layer._yield_emits(emits[self._layer.name]) # pylint: disable=protected-access
670
+
671
+
672
+ class Skip(Parallel):
673
+ """A skip wrapper around l that computes `y = concat([x, l(x)])`."""
674
+
675
+ def __init__(
676
+ self,
677
+ layer: SequenceLayerListOrCallable,
678
+ name: Optional[str] = None,
679
+ ):
680
+ super().__init__([simple.Identity(), layer], name=name)
681
+
682
+ def _combine_outputs(self, ys: List[types.Sequence]) -> types.Sequence:
683
+ assert len(ys) == 2
684
+ if ys[0].values.dtype != ys[1].values.dtype:
685
+ raise ValueError(
686
+ 'Skip connection must have same dtypes: '
687
+ f'input_dtype:{ys[0].values.dtype} output_dtype:{ys[1].values.dtype}'
688
+ )
689
+
690
+ # Assumption: x is masked and y is masked, so no masking necessary.
691
+ # TODO(rryan): Assumes x and y mask are identical. Merge masks? If changed,
692
+ # we need to re-mask after merging.
693
+ return ys[0].apply_values(lambda v: tf.concat([v, ys[1].values], axis=2))
694
+
695
+ def get_output_shape(
696
+ self,
697
+ input_shape: tf.TensorShape,
698
+ constants: Optional[types.Constants] = None,
699
+ ) -> tf.TensorShape:
700
+ """Output size is input-dependent."""
701
+ assert len(self._layers) == 2
702
+ output_shape = self._layers[1].get_output_shape(input_shape, constants)
703
+ if input_shape.rank != output_shape.rank:
704
+ raise ValueError(
705
+ 'Skip connection inner shapes must have same '
706
+ 'rank: input_shape=%s output_shape=%s' % (input_shape, output_shape)
707
+ )
708
+ if input_shape[1:] != output_shape[1:]:
709
+ raise ValueError(
710
+ 'Skip connection requires input and output shape to '
711
+ 'match after the first dimension: input_shape=%s output_shape=%s'
712
+ % (input_shape, output_shape)
713
+ )
714
+ return tf.TensorShape(
715
+ [input_shape.dims[0].value + output_shape.dims[0].value]
716
+ ).concatenate(output_shape[1:])
717
+
718
+
719
+ class Blockwise(types.Emitting):
720
+ """Runs the specified layer block_size steps at a time."""
721
+
722
+ def __init__(
723
+ self,
724
+ layer: SequenceLayerListOrCallable,
725
+ block_size: int,
726
+ name=None,
727
+ ):
728
+ super().__init__(name=name)
729
+ self._layer = _maybe_wrap_layers(self, layer)
730
+ if not block_size:
731
+ raise ValueError(f'{self} block_size must be positive, got: {block_size}')
732
+ self._block_size = block_size
733
+
734
+ @property
735
+ def supports_step(self) -> bool:
736
+ return self._layer.supports_step # pytype: disable=bad-return-type # bind-properties
737
+
738
+ @property
739
+ def block_size(self) -> int:
740
+ return self._block_size
741
+
742
+ @property
743
+ def output_ratio(self) -> fractions.Fraction:
744
+ return self._layer.output_ratio
745
+
746
+ def get_output_shape(
747
+ self,
748
+ input_shape: tf.TensorShape,
749
+ constants: Optional[types.Constants] = None,
750
+ ) -> tf.TensorShape:
751
+ return self._layer.get_output_shape(input_shape, constants)
752
+
753
+ def get_output_dtype(self, input_dtype: tf.DType) -> tf.DType:
754
+ return self._layer.get_output_dtype(input_dtype)
755
+
756
+ def get_initial_state(
757
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
758
+ ) -> types.State:
759
+ return self._layer.get_initial_state(x, constants)
760
+
761
+ def get_emit_specs(
762
+ self,
763
+ input_spec: tf.TensorSpec,
764
+ constants: Optional[types.Constants] = None,
765
+ ) -> types.EmitSpecs:
766
+ return self._layer.get_emit_specs(input_spec, constants)
767
+
768
+ def step_with_emits(
769
+ self,
770
+ x: types.Sequence,
771
+ state: types.State,
772
+ training: bool,
773
+ constants: Optional[types.Constants] = None,
774
+ ) -> Tuple[types.Sequence, types.State, types.Emits]:
775
+ return self._layer.step_with_emits(x, state, training, constants)
776
+
777
+ def layer_with_emits(
778
+ self,
779
+ x: types.Sequence,
780
+ training: bool,
781
+ initial_state: Optional[types.State] = None,
782
+ constants: Optional[types.Constants] = None,
783
+ ) -> Tuple[types.Sequence, types.Emits]:
784
+ y, _, emits = utils.step_by_step_dynamic(
785
+ self,
786
+ x,
787
+ training=training,
788
+ initial_state=initial_state,
789
+ constants=constants,
790
+ )
791
+ return y, emits
792
+
793
+ def _yield_emits(
794
+ self, emits: types.Emits
795
+ ) -> Generator[tuple[types.SequenceLayer, types.Emits], None, None]:
796
+ yield from super()._yield_emits(emits)
797
+ yield from self._layer._yield_emits(emits) # pylint: disable=protected-access
798
+
799
+
800
+ class Bidirectional(types.Emitting):
801
+ """Performs bidirectional processing on a sequence.
802
+
803
+ TODO(rryan): Support more methods of merging the two directions beyond
804
+ depthwise concat.
805
+ """
806
+
807
+ def __init__(
808
+ self,
809
+ forward: SequenceLayerListOrCallable,
810
+ backward: SequenceLayerListOrCallable,
811
+ name: Optional[str] = None,
812
+ ):
813
+ super().__init__(name=name)
814
+ self._forward = _maybe_wrap_layers(self, forward)
815
+ self._backward = _maybe_wrap_layers(self, backward)
816
+
817
+ if self._forward.output_ratio != self._backward.output_ratio:
818
+ raise ValueError(
819
+ f'{self}: output ratios for the forward '
820
+ 'and backward direction must be equal. '
821
+ f'forward={self._forward.output_ratio} '
822
+ f'backward={self._backward.output_ratio}.'
823
+ )
824
+
825
+ @property
826
+ def supports_step(self) -> bool:
827
+ return False
828
+
829
+ @property
830
+ def block_size(self) -> int:
831
+ # Bidirectional is not steppable, so block size does not matter.
832
+ return 0
833
+
834
+ @property
835
+ def output_ratio(self) -> fractions.Fraction:
836
+ return self._forward.output_ratio
837
+
838
+ def get_output_shape(
839
+ self, input_shape: tf.TensorShape, constants: types.Constants = None
840
+ ) -> tf.TensorShape:
841
+ forward_output_shape = self._forward.get_output_shape(
842
+ input_shape, constants
843
+ )
844
+ backward_output_shape = self._backward.get_output_shape(
845
+ input_shape, constants
846
+ )
847
+
848
+ if not forward_output_shape[:-1].is_compatible_with(
849
+ backward_output_shape[:-1]
850
+ ):
851
+ raise ValueError(
852
+ f'{self}: Forward and backward output shapes are not '
853
+ f'compatible. forward={forward_output_shape} '
854
+ f'backward={backward_output_shape}'
855
+ )
856
+
857
+ output_shape = forward_output_shape[:-1].merge_with(
858
+ backward_output_shape[:-1]
859
+ )
860
+ final_dim = (
861
+ forward_output_shape.dims[-1].value
862
+ + backward_output_shape.dims[-1].value
863
+ )
864
+ return output_shape.concatenate(tf.TensorShape([final_dim]))
865
+
866
+ def get_output_dtype(self, input_dtype: tf.DType) -> tf.DType:
867
+ forward_dtype = self._forward.get_output_dtype(input_dtype)
868
+ backward_dtype = self._backward.get_output_dtype(input_dtype)
869
+ if forward_dtype != backward_dtype:
870
+ raise ValueError(
871
+ f'{self}: forward and backward dtypes are different. '
872
+ f'forward={forward_dtype} backward={backward_dtype}'
873
+ )
874
+ return forward_dtype
875
+
876
+ def get_initial_state(
877
+ self, x: types.Sequence, constants: types.Constants = None
878
+ ) -> types.State:
879
+ forward_state = self._forward.get_initial_state(x, constants)
880
+ backward_state = self._backward.get_initial_state(x, constants)
881
+ return (forward_state, backward_state)
882
+
883
+ def get_emit_specs(
884
+ self, input_spec: tf.TensorSpec, constants: types.Constants = None
885
+ ) -> types.EmitSpecs:
886
+ forward_emit_spec = self._forward.get_emit_specs(input_spec, constants)
887
+ backward_emit_spec = self._backward.get_emit_specs(input_spec, constants)
888
+ return (forward_emit_spec, backward_emit_spec)
889
+
890
+ def step_with_emits(
891
+ self,
892
+ x: types.Sequence,
893
+ state: types.State,
894
+ training: bool,
895
+ constants: types.Constants = None,
896
+ ) -> Tuple[types.Sequence, types.State, types.Emits]:
897
+ raise ValueError('Bidirectional does not support step-wise processing.')
898
+
899
+ @tf.Module.with_name_scope
900
+ def layer_with_emits(
901
+ self,
902
+ x: types.Sequence,
903
+ training: bool,
904
+ initial_state: types.State = None,
905
+ constants: types.Constants = None,
906
+ ) -> Tuple[types.Sequence, types.Emits]:
907
+ if initial_state is None:
908
+ initial_state = (None, None)
909
+ forward_state, backward_state = initial_state
910
+
911
+ y_forward, forward_emits = self._forward.layer_with_emits(
912
+ x, training=training, initial_state=forward_state, constants=constants
913
+ )
914
+
915
+ x_reverse = x.reverse_time()
916
+ y_backward, backward_emits = self._backward.layer_with_emits(
917
+ x_reverse,
918
+ training=training,
919
+ initial_state=backward_state,
920
+ constants=constants,
921
+ )
922
+ y_backward = y_backward.reverse_time()
923
+
924
+ def concat(values, mask):
925
+ values = tf.concat([values, y_backward.values], axis=-1)
926
+ mask = utils.combine_mask(mask, y_backward.mask)
927
+ return values, mask
928
+
929
+ y = y_forward.apply(concat).mask_invalid()
930
+ return y, (forward_emits, backward_emits)
931
+
932
+ def _yield_emits(
933
+ self, emits: types.Emits
934
+ ) -> Generator[tuple[types.SequenceLayer, types.Emits], None, None]:
935
+ forward_emits, backward_emits = emits
936
+ yield from super()._yield_emits(emits)
937
+ yield from self._forward._yield_emits(forward_emits) # pylint: disable=protected-access
938
+ yield from self._backward._yield_emits(backward_emits) # pylint: disable=protected-access