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,1343 @@
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
+ """Test utilities."""
15
+
16
+ import dataclasses
17
+ import functools
18
+ import itertools
19
+ import logging
20
+ import random
21
+ from typing import Any, Callable, Iterable, Mapping, Sequence as TypingSequence, TypeVar
22
+
23
+ from absl.testing import absltest
24
+ from absl.testing import parameterized
25
+ import chex
26
+ import flax.linen as nn
27
+ import jax
28
+ import jax.numpy as jnp
29
+ import numpy as np
30
+ from sequence_layers.jax import types
31
+ from sequence_layers.jax import typing as jt
32
+ from sequence_layers.jax import utils
33
+
34
+
35
+ _SequenceLayerT = TypeVar('_SequenceLayerT', bound=types.SequenceLayer)
36
+ _T = TypeVar('_T')
37
+ _TestFnT = Callable[..., None]
38
+
39
+
40
+ def random_sequence(
41
+ *dims: int,
42
+ dtype=jnp.float32,
43
+ random_mask: bool = False,
44
+ random_lengths: bool | None = None,
45
+ low: int | None = 0,
46
+ high: int | None = 10,
47
+ low_length: int = 0,
48
+ high_length: int | None = None,
49
+ ) -> types.Sequence:
50
+ """Generates a random Sequence with dims dimension.
51
+
52
+ Each batch item has a randomly generated length in [0, dims[1]) which is used
53
+ to compute the mask.
54
+
55
+ Args:
56
+ *dims: The dimensions of the sequence.
57
+ dtype: The dtype of the sequence.
58
+ random_mask: Whether to generate a random, non-contiguous mask.
59
+ random_lengths: Whether to generate random lengths (i.e. a random,
60
+ contiguous mask).
61
+ low: For integer dtypes, the minimum value to generate.
62
+ high: For integer dtypes, one above the maximum value to generate.
63
+ low_length: For random_lengths, the minimum length to generate.
64
+ high_length: For random lengths, one above the maximum length to generate.
65
+
66
+ Returns:
67
+ A Sequence with the specified dimensions and type. Invalid values timesteps
68
+ are masked.
69
+ """
70
+ # If random_mask is disabled, default to random_lengths.
71
+ if random_lengths is None:
72
+ random_lengths = not random_mask
73
+ if random_mask and random_lengths:
74
+ raise ValueError('Must not specify random_mask and random_lengths.')
75
+ if len(dims) < 2:
76
+ raise ValueError(
77
+ 'random_sequence expects at least 2 dimensions, got: %s' % (dims,)
78
+ )
79
+
80
+ is_complex = dtype in (np.complex64, np.complex128)
81
+ is_integer = np.issubdtype(dtype, np.integer)
82
+
83
+ if is_complex:
84
+ np_values = np.random.normal(size=dims) + 1j * np.random.normal(size=dims)
85
+ elif is_integer:
86
+ np_values = np.random.randint(low, high, size=dims)
87
+ else:
88
+ np_values = np.random.normal(size=dims)
89
+
90
+ batch_size, time = dims[0], dims[1]
91
+ values = np_values.astype(dtype)
92
+ if random_mask:
93
+ mask = np.random.uniform(size=(batch_size, time)) > 0.5
94
+ else:
95
+ if time > 0:
96
+ if random_lengths:
97
+ if high_length is None:
98
+ high_length = time + 1
99
+ lengths = np.random.randint(
100
+ low_length, high_length, size=[batch_size]
101
+ ).astype(np.int32)
102
+ else:
103
+ lengths = np.full([batch_size], time).astype(np.int32)
104
+ else:
105
+ lengths = np.full([batch_size], 0).astype(np.int32)
106
+
107
+ mask = np.arange(time)[np.newaxis, :] < lengths[:, np.newaxis]
108
+ # We cast to jax.Array to avoid being surprised by NumPy promotion rules.
109
+ return types.Sequence(jnp.asarray(values), jnp.asarray(mask)).mask_invalid()
110
+
111
+
112
+ def cast_from_to(tree, from_dtype: types.DType, to_dtype: types.DType):
113
+ """Casts arrays with dtype from_dtype to to_dtype."""
114
+ return jax.tree.map(
115
+ lambda a: a.astype(to_dtype) if a.dtype == from_dtype else a, tree
116
+ )
117
+
118
+
119
+ def standard_dtype_configs(
120
+ param: bool | None = None,
121
+ input: bool | None = None, # pylint: disable=redefined-builtin
122
+ compute: bool | None = None,
123
+ param_dtype: str = 'param_dtype',
124
+ input_dtype: str = 'input_dtype',
125
+ compute_dtype: str = 'compute_dtype',
126
+ expected: bool = False,
127
+ expected_dtype: str = 'expected_dtype',
128
+ praxis_only: bool = False,
129
+ include_default: bool = True,
130
+ named: bool = False,
131
+ ) -> list[dict[str, types.DType | None | str]]:
132
+ """Returns a list of standard dtype configurations; restrictable via flags.
133
+
134
+ Args:
135
+ param: If any of these three are set, restrict the returned configs to only
136
+ include args set to True (deduplicating if needed).
137
+ input: (see above)
138
+ compute: (see above)
139
+ param_dtype: Key to use for parameter dtypes in the returned configs.
140
+ input_dtype: Key to use for input dtypes in the returned configs.
141
+ compute_dtype: Key to use for compute dtypes in the returned configs.
142
+ expected: Whether to include the expected dtype in the returned configs.
143
+ expected_dtype: Key to use for expected dtypes in the returned configs.
144
+ praxis_only: Whether to only include Praxis-like configs (e.g., for
145
+ conversion/equivalence).
146
+ include_default: Whether to include the default (fp32, fp32, None) dtype
147
+ config.
148
+ named: Whether to include a `testcase_name` in the returned configs.
149
+
150
+ Returns:
151
+ A list of known configs mapping each class of dtype parameter to a dtype.
152
+ Each config will be ordered (param, input, compute), for use in unlabelled
153
+ parameter tuples. If named=True, the `testcase_name` will be prepended to
154
+ the config dictionary, with an abbreviated name for the dtype combination.
155
+ """
156
+ if param is None and input is None and compute is None:
157
+ param = True
158
+ input = True
159
+ compute = True
160
+
161
+ results = []
162
+
163
+ if include_default:
164
+ results += [
165
+ # Tests W32A32 (this is the default):
166
+ {
167
+ param_dtype: jnp.float32,
168
+ input_dtype: jnp.float32,
169
+ compute_dtype: None,
170
+ },
171
+ ]
172
+
173
+ # Subset of configurations that we care about matching with Praxis.
174
+ results += [
175
+ # W16A16 (typical inference config):
176
+ {
177
+ param_dtype: jnp.bfloat16,
178
+ input_dtype: jnp.bfloat16,
179
+ compute_dtype: jnp.bfloat16,
180
+ },
181
+ ]
182
+
183
+ if not praxis_only:
184
+ results += [
185
+ # Tests W32A16 (typical training config):
186
+ {
187
+ param_dtype: jnp.float32,
188
+ input_dtype: jnp.bfloat16,
189
+ compute_dtype: jnp.bfloat16,
190
+ },
191
+ # Tests W16A32 w/ automatic promotion:
192
+ {
193
+ param_dtype: jnp.bfloat16,
194
+ input_dtype: jnp.float32,
195
+ compute_dtype: None,
196
+ },
197
+ # Tests W32A16 when inputs are float32:
198
+ {
199
+ param_dtype: jnp.float32,
200
+ input_dtype: jnp.float32,
201
+ compute_dtype: jnp.bfloat16,
202
+ },
203
+ ]
204
+
205
+ # Remove unneeded keys, deduplicate, then return:
206
+ keep = {
207
+ param_dtype: param,
208
+ input_dtype: input,
209
+ compute_dtype: compute,
210
+ }
211
+ keep_keys = tuple(k for k, v in keep.items() if v)
212
+
213
+ shorthands = {
214
+ jnp.float32: 'fp32',
215
+ jnp.bfloat16: 'bf16',
216
+ None: 'None',
217
+ }
218
+
219
+ found = set()
220
+ reduced = []
221
+ for result in results:
222
+ config_keys = tuple(k for k in result if keep[k])
223
+ assert keep_keys == config_keys, (
224
+ 'Dtype configs should be ordered params, keys, compute. Expected'
225
+ f' {keep_keys}, got {config_keys}'
226
+ )
227
+ config_vals = tuple(result[k] for k in config_keys)
228
+ if config_vals not in found:
229
+ found.add(config_vals)
230
+ # We still want to return the dictionary form:
231
+ config = {k: v for k, v in result.items() if keep[k]}
232
+ # If named=True, we want to add the testcase name first:
233
+ if named:
234
+ config |= {
235
+ 'testcase_name': '_'.join(
236
+ f'{k[0]}-{shorthands[v]}' for k, v in config.items()
237
+ )
238
+ }
239
+
240
+ # We still want to return the dictionary form:
241
+ reduced.append(config)
242
+
243
+ if expected:
244
+ for reduced_config in reduced:
245
+ args = []
246
+ if param_dtype in reduced_config:
247
+ args.append(reduced_config[param_dtype])
248
+ if input_dtype in reduced_config:
249
+ args.append(reduced_config[input_dtype])
250
+ reduced_config[expected_dtype] = utils.get_promoted_dtype(
251
+ *args,
252
+ dtype=reduced_config.get(compute_dtype),
253
+ )
254
+
255
+ return reduced
256
+
257
+
258
+ def zip_longest(
259
+ targets: Iterable[Iterable[Any]],
260
+ sources: Iterable[_T],
261
+ ) -> list[_T]:
262
+ """Applies zip_longest, specialized to @parameterized's argument format.
263
+
264
+ Args:
265
+ targets: Iterable of parameterized test arguments.
266
+ sources: Iterable of parameterized test arguments. If `targets` is a mapping
267
+ `sources` must be a mapping as well.
268
+
269
+ Returns:
270
+ A list of the zipped arguments, of the type of `targets` and with each
271
+ zipped argument internally sorted (target, source). If either input sequence
272
+ was longer, the last element of the shorter input sequence is repeated.
273
+ """
274
+
275
+ results = []
276
+ prev_source, prev_target = None, None
277
+ for source, target in itertools.zip_longest(sources, targets):
278
+ # If either runs out ahead-of-time, we repeat the final non-None element.
279
+ # (This is safest as we cannot inspect the function's defaults.)
280
+ if source is None:
281
+ source = prev_source
282
+ elif target is None:
283
+ target = prev_target
284
+
285
+ if isinstance(target, Mapping):
286
+ assert isinstance(source, Mapping)
287
+ results.append({**target, **source})
288
+ elif isinstance(sources, Iterable):
289
+ # target is a non-mapping iterable, like tuple or list.
290
+ if isinstance(source, Mapping):
291
+ # To match the target, we replace the source with its unlabeled values.
292
+ source = source.values()
293
+ results.append((*target, *source))
294
+ prev_source, prev_target = source, target
295
+ else:
296
+ raise NotImplementedError(
297
+ f'Targets of type {type(target)=} are unsupported.'
298
+ )
299
+
300
+ return results
301
+
302
+
303
+ def named_product(
304
+ first: Iterable[TypingSequence[Any] | Mapping[str, Any]],
305
+ second: Iterable[TypingSequence[Any] | Mapping[str, Any]],
306
+ ) -> Callable[[_TestFnT], _TestFnT]:
307
+ """Builds named parameters from the product of iterators of named parameters.
308
+
309
+ As in parameterized.named_parameters, if an iterator's items are sequences,
310
+ the first element is interpreted as the name. If an iterator's items are
311
+ mappings, the `testcase_name` key is used.
312
+
313
+ Args:
314
+ first: Iterable of named parameters, whose names will be the first part of
315
+ the named product's test names.
316
+ second: Iterable of named parameters, whose names will be the second part of
317
+ the named product's test names.
318
+
319
+ Returns:
320
+ A decorator that calls the test function with the cartesian product of the
321
+ given iterators, whose items are named parameters with names of the form
322
+ `{first_item_name}_{second_item_name}`. If both iterators' items are
323
+ mappings, the product's items are mappings; otherwise they are ordered
324
+ tuples.
325
+
326
+ For example, if `first` is
327
+ `[{**foo, 'testcase_name': 'foo'}, {**bar, 'testcase_name': 'bar'}]` and
328
+ `second` is `[['baz', *baz], ['qux', *qux]]`, the items will be
329
+ `('foo_baz', *foo.values(), *baz), ('foo_qux', *foo.values(), *qux), ...`
330
+
331
+ Raises:
332
+ ValueError: A testcase_name is missing; either an iterator item is empty, or
333
+ one is a mapping without a `testcase_name` key.
334
+ """
335
+
336
+ results = []
337
+
338
+ for p1, p2 in itertools.product(first, second):
339
+
340
+ for source, parameters in enumerate([p1, p2]):
341
+ if isinstance(parameters, Mapping):
342
+ if 'testcase_name' not in parameters:
343
+ raise ValueError(
344
+ f'Mapping {parameters} from iterable #{source+1} does not have'
345
+ ' key `testcase_name`.'
346
+ )
347
+ elif not parameters:
348
+ raise ValueError(
349
+ f'An sequence from iterable #{source+1} is empty; the first entry'
350
+ ' is expected to be a testcase name.'
351
+ )
352
+
353
+ # When both are mappings, we merge by key:
354
+ if isinstance(p1, Mapping) and isinstance(p2, Mapping):
355
+ testcase_name = f'{p1["testcase_name"]}_{p2["testcase_name"]}'
356
+ p1 = {k: v for k, v in p1.items() if k != 'testcase_name'}
357
+ p2 = {k: v for k, v in p2.items() if k != 'testcase_name'}
358
+ results.append({**p1, **p2, 'testcase_name': testcase_name})
359
+
360
+ # Else, we return an ordered tuple based on each parameter set's order:
361
+ else:
362
+
363
+ if isinstance(p1, Mapping):
364
+ p1_name = p1['testcase_name']
365
+ p1 = tuple(v for k, v in p1.items() if k != 'testcase_name')
366
+ else:
367
+ p1_name = p1[0]
368
+ p1 = p1[1:]
369
+
370
+ if isinstance(p2, Mapping):
371
+ p2_name = p2['testcase_name']
372
+ p2 = tuple(v for k, v in p2.items() if k != 'testcase_name')
373
+ else:
374
+ p2_name = p2[0]
375
+ p2 = p2[1:]
376
+
377
+ testcase_name = f'{p1_name}_{p2_name}'
378
+ results.append((testcase_name, *p1, *p2))
379
+
380
+ return parameterized.named_parameters(*results)
381
+
382
+
383
+ def get_grad_tols(
384
+ l: types.SequenceLayer,
385
+ x: types.Sequence,
386
+ param_dtype: types.DType | None,
387
+ compute_dtype: types.DType | None,
388
+ ) -> dict[str, float | None]:
389
+ """Estimate reasonable tolerances given the layer, inputs, and dtypes."""
390
+ del l, x
391
+ supported_param_dtypes = {jnp.float32, jnp.bfloat16, jnp.float16, None}
392
+ supported_compute_dtypes = {jnp.float32, jnp.bfloat16, jnp.float16, None}
393
+ if param_dtype not in supported_param_dtypes:
394
+ raise ValueError(f'Unsupported param_dtype: {param_dtype}')
395
+ if compute_dtype not in supported_compute_dtypes:
396
+ raise ValueError(f'Unsupported compute_dtype: {compute_dtype}')
397
+ # If no param_dtype is specified, defer to the callee's defaults.
398
+ if param_dtype is None:
399
+ return {}
400
+
401
+ if param_dtype == jnp.float32 and (
402
+ compute_dtype is None or compute_dtype == jnp.float32
403
+ ):
404
+ return {'grad_rtol': 1e-5, 'grad_atol': 1e-5}
405
+ else:
406
+ return {'grad_rtol': 1e-1, 'grad_atol': 1e-1}
407
+
408
+
409
+ def flax_init(layer: nn.Module, *args, **kwargs):
410
+ """Initialize a Flax Module with optional jax.jit wrapping it."""
411
+ method = kwargs.pop('method', '__call__')
412
+ should_jit = kwargs.pop('jit', False)
413
+
414
+ def init_layer(*args, **kwargs):
415
+ return layer.init(*args, **kwargs, method=method)
416
+
417
+ if should_jit:
418
+ init_layer = jax.jit(init_layer)
419
+ return init_layer(*args, **kwargs)
420
+
421
+
422
+ def flax_apply(layer: nn.Module, params, *args, **kwargs):
423
+ method = kwargs.pop('method', '__call__')
424
+ should_jit = kwargs.pop('jit', True)
425
+
426
+ def layer_fn(params, *args, **kwargs):
427
+ return layer.apply(params, *args, **kwargs, method=method)
428
+
429
+ if should_jit:
430
+ layer_fn = jax.jit(layer_fn)
431
+ return layer_fn(params, *args, **kwargs)
432
+
433
+
434
+ def sl_init(layer: types.SequenceLayer, *args, **kwargs):
435
+ training = kwargs.pop('training', False)
436
+ method = kwargs.pop('method', '__call__')
437
+ should_jit = kwargs.pop('jit', True)
438
+
439
+ def init_layer(*args, **kwargs):
440
+ return layer.init(*args, **kwargs, training=training, method=method)
441
+
442
+ if should_jit:
443
+ init_layer = jax.jit(init_layer)
444
+ return init_layer(*args, **kwargs)
445
+
446
+
447
+ def sl_layer(
448
+ layer: types.SequenceLayer, params, *args, **kwargs
449
+ ) -> types.MaskedSequence:
450
+ """Runs layer, masking the output with optional jax.jit wrapping."""
451
+ training = kwargs.pop('training', False)
452
+ method = kwargs.pop('method', 'layer')
453
+ should_jit = kwargs.pop('jit', True)
454
+
455
+ def layer_fn(params, *args, **kwargs):
456
+ return layer.apply(
457
+ params, *args, **kwargs, training=training, method=method
458
+ ).mask_invalid()
459
+
460
+ if should_jit:
461
+ layer_fn = jax.jit(layer_fn)
462
+ return layer_fn(params, *args, **kwargs)
463
+
464
+
465
+ def sl_layer_with_emits(
466
+ layer: types.SequenceLayer, params, *args, **kwargs
467
+ ) -> tuple[types.MaskedSequence, types.Emits]:
468
+ """Runs layer_with_emits masking the output with optional jax.jit wrapping."""
469
+ training = kwargs.pop('training', False)
470
+ method = kwargs.pop('method', 'layer_with_emits')
471
+ should_jit = kwargs.pop('jit', True)
472
+
473
+ def layer_fn(params, *args, **kwargs):
474
+ output, emits = layer.apply(
475
+ params, *args, **kwargs, training=training, method=method
476
+ )
477
+ return output.mask_invalid(), emits
478
+
479
+ if should_jit:
480
+ layer_fn = jax.jit(layer_fn)
481
+ return layer_fn(params, *args, **kwargs)
482
+
483
+
484
+ def pad_batch_axis_with_garbage(tree):
485
+ """Pads the batch dimension of all arrays in tree with garbage values."""
486
+
487
+ def pad_with_garbage(
488
+ x: types.Sequence | jax.Array,
489
+ ) -> types.Sequence | jax.Array:
490
+ paddings = [(0, 0)] * x.ndim
491
+ paddings[0] = (1, 1)
492
+
493
+ if issubclass(x.dtype.type, (jnp.floating, jnp.complexfloating)):
494
+ pad_value = jnp.nan
495
+ elif issubclass(x.dtype.type, jnp.integer):
496
+ pad_value = jnp.iinfo(x.dtype).max
497
+ else:
498
+ pad_value = 0
499
+
500
+ if isinstance(x, jax.Array):
501
+ return jnp.pad(x, paddings, constant_values=pad_value)
502
+ else:
503
+ return type(x)(
504
+ jnp.pad(x.values, paddings, constant_values=pad_value),
505
+ jnp.pad(x.mask, [(1, 1), (0, 0)], constant_values=True),
506
+ )
507
+
508
+ return jax.tree.map(
509
+ pad_with_garbage, tree, is_leaf=lambda x: isinstance(x, types.Sequence)
510
+ )
511
+
512
+
513
+ def strip_batch_axis_of_garbage(tree):
514
+ """Strips garbage values from the batch dimension of all arrays in tree."""
515
+ return jax.tree.map(
516
+ lambda a: a[1:-1], tree, is_leaf=lambda x: isinstance(x, types.Sequence)
517
+ )
518
+
519
+
520
+ @jax.jit
521
+ def _shear_2d(x: jt.Shaped[jt.ArrayT, 'r c']) -> jt.Shaped[jt.ArrayT, 'r d']:
522
+ """Shears a 2D JAX array to produce a diagonal padding effect.
523
+
524
+ Example:
525
+ x:
526
+ [[1, 2, 3],
527
+ [4, 5, 6],
528
+ [7, 8, 9]]
529
+
530
+ output:
531
+ [[0, 0, 1, 2, 3],
532
+ [0, 4, 5, 6, 0],
533
+ [7, 8, 9, 0, 0]]
534
+
535
+ Args:
536
+ x: The input 2D JAX array of shape (r, c).
537
+
538
+ Returns:
539
+ A 2D JAX array of shape (r, d), where d = c + r - 1.
540
+ """
541
+ r, c = x.shape
542
+ # [r, c].
543
+ x = x[:, ::-1]
544
+ # [r, c + r].
545
+ x = jnp.pad(x, [[0, 0], [0, r]], constant_values=0.0)
546
+ # [r * (c + r)].
547
+ x = x.reshape(-1)
548
+ # [r * (c + r - 1)].
549
+ x = x[:-r]
550
+ # [r, c + r - 1].
551
+ x = x.reshape([r, c + r - 1])
552
+ # [r, c + r - 1].
553
+ x = x[:, ::-1]
554
+ return x
555
+
556
+
557
+ def _prep_input_for_receptive_field(
558
+ l: types.SequenceLayer,
559
+ x: types.Sequence,
560
+ constants: types.Constants | None,
561
+ pad_constants: bool,
562
+ pad_constants_ratio: int,
563
+ ) -> tuple[types.Sequence, types.Constants | None]:
564
+ """Pads the input to the maximum receptive field."""
565
+ values = x.values
566
+ mask = jnp.ones_like(x.mask)
567
+ x_len = values.shape[1]
568
+ if l.receptive_field is not None:
569
+ past, future = l.receptive_field
570
+ rf_len = (
571
+ (future if future != np.inf else 0)
572
+ - (past if past != -np.inf else 0)
573
+ + 1
574
+ )
575
+ assert rf_len > 0
576
+ required_len = rf_len * 2
577
+ else:
578
+ # RF is None, so any length is fine.
579
+ required_len = x_len
580
+ if x_len < required_len:
581
+ pad_amount = required_len - x_len
582
+ pad_shape = (values.shape[0], pad_amount) + values.shape[2:]
583
+ values = jnp.concatenate(
584
+ [np.random.normal(size=pad_shape).astype(values.dtype), values],
585
+ axis=1,
586
+ )
587
+ batch_size, _ = mask.shape
588
+ mask = jnp.full([batch_size, x_len + pad_amount], True)
589
+ if constants is not None and pad_constants:
590
+ constant_pad_amount = pad_amount * pad_constants_ratio
591
+ padded_constants = {}
592
+ for k, v in constants.items():
593
+ if isinstance(v, types.Sequence):
594
+ v = v.pad_time(0, constant_pad_amount, valid=False)
595
+ # Mark all as valid to avoid blocking grads in receptive field
596
+ # calculations.
597
+ v = types.Sequence(v.values, jnp.ones_like(v.mask))
598
+ padded_constants[k] = v
599
+ constants = padded_constants
600
+ x = types.Sequence(values, mask)
601
+ return x, constants
602
+
603
+
604
+ def _gradient_receptive_field(
605
+ l: types.SequenceLayer,
606
+ layer_fn: Callable[
607
+ [types.SequenceLayer, types.Sequence, types.Constants],
608
+ types.Sequence,
609
+ ],
610
+ x: types.Sequence,
611
+ constants: types.Constants | None = None,
612
+ ) -> types.ReceptiveField:
613
+ """Computes the gradient receptive field of a layer."""
614
+
615
+ def fn(
616
+ x: jt.Float[jt.ArrayT, 'b t *'],
617
+ x_fn: Callable[[jt.Float[jt.ArrayT, 'b t *']], types.Sequence],
618
+ y_fn: Callable[[types.Sequence], jt.Float[jt.ArrayT, 'b t *']],
619
+ ):
620
+ y = y_fn(layer_fn(l, x_fn(x), constants).mask_invalid().values)
621
+ # Reduce y to sum of absolute values of individual y channel values to
622
+ # avoid large gradient matrices.
623
+ return jax.lax.reduce_sum(jnp.abs(y), axes=list(range(2, y.ndim)))
624
+
625
+ x_real_fn = lambda x_: types.Sequence(x_ + 1j * jnp.imag(x.values), x.mask)
626
+ x_imag_fn = lambda x_: types.Sequence(jnp.real(x.values) + 1j * x_, x.mask)
627
+ jac_fn_real_y = functools.partial(
628
+ fn, x_fn=lambda x_: types.Sequence(x_, x.mask), y_fn=jnp.real
629
+ )
630
+ jac_fn_imag_y = functools.partial(
631
+ fn, x_fn=lambda x_: types.Sequence(x_, x.mask), y_fn=jnp.real
632
+ )
633
+ jac_fn_real_x_real_y = functools.partial(fn, x_fn=x_real_fn, y_fn=jnp.real)
634
+ jac_fn_imag_x_real_y = functools.partial(fn, x_fn=x_imag_fn, y_fn=jnp.real)
635
+ jac_fn_real_x_imag_y = functools.partial(fn, x_fn=x_real_fn, y_fn=jnp.imag)
636
+ jac_fn_imag_x_imag_y = functools.partial(fn, x_fn=x_imag_fn, y_fn=jnp.imag)
637
+
638
+ x_dtype = x.values.dtype
639
+ y_dtype = l.get_output_dtype(x_dtype)
640
+ x_is_complex = jnp.issubdtype(x_dtype, jnp.complexfloating)
641
+ y_is_complex = jnp.issubdtype(y_dtype, jnp.complexfloating)
642
+ x_is_floating = jnp.issubdtype(x_dtype, jnp.floating)
643
+ y_is_floating = jnp.issubdtype(y_dtype, jnp.floating)
644
+
645
+ if x_is_floating and y_is_floating:
646
+ # [By, Ty, Bx, Tx, *I].
647
+ grads = jax.jacrev(jac_fn_real_y)(x.values)
648
+ grads = jnp.where(jnp.isfinite(grads), grads, 0.0)
649
+ has_grad = jnp.logical_not(jnp.equal(grads, 0))
650
+ elif x_is_floating and y_is_complex:
651
+ # [By, Ty, Bx, Tx, *I].
652
+ grads_real = jax.jacrev(jac_fn_real_y)(x.values)
653
+ grads_imag = jax.jacrev(jac_fn_imag_y)(x.values)
654
+ grads_real = jnp.where(jnp.isfinite(grads_real), grads_real, 0.0)
655
+ grads_imag = jnp.where(jnp.isfinite(grads_imag), grads_imag, 0.0)
656
+ has_grad = jnp.logical_not(
657
+ jnp.logical_and(jnp.equal(grads_real, 0), jnp.equal(grads_imag, 0))
658
+ )
659
+ elif x_is_complex and y_is_floating:
660
+ # [By, Ty, Bx, Tx, *I].
661
+ grads_real = jax.jacrev(jac_fn_real_x_real_y)(jnp.real(x.values))
662
+ grads_imag = jax.jacrev(jac_fn_imag_x_real_y)(jnp.imag(x.values))
663
+ grads_real = jnp.where(jnp.isfinite(grads_real), grads_real, 0.0)
664
+ grads_imag = jnp.where(jnp.isfinite(grads_imag), grads_imag, 0.0)
665
+ has_grad = jnp.logical_not(
666
+ jnp.logical_and(jnp.equal(grads_real, 0), jnp.equal(grads_imag, 0))
667
+ )
668
+ elif x_is_complex and y_is_complex:
669
+ # [By, Ty, Bx, Tx, *I].
670
+ grads_real_x_real_y = jax.jacrev(jac_fn_real_x_real_y)(jnp.real(x.values))
671
+ grads_imag_x_real_y = jax.jacrev(jac_fn_imag_x_real_y)(jnp.imag(x.values))
672
+ grads_real_x_imag_y = jax.jacrev(jac_fn_real_x_imag_y)(jnp.real(x.values))
673
+ grads_imag_x_imag_y = jax.jacrev(jac_fn_imag_x_imag_y)(jnp.imag(x.values))
674
+ grads_real_x_real_y = jnp.where(
675
+ jnp.isfinite(grads_real_x_real_y), grads_real_x_real_y, 0.0
676
+ )
677
+ grads_imag_x_real_y = jnp.where(
678
+ jnp.isfinite(grads_imag_x_real_y), grads_imag_x_real_y, 0.0
679
+ )
680
+ grads_real_x_imag_y = jnp.where(
681
+ jnp.isfinite(grads_real_x_imag_y), grads_real_x_imag_y, 0.0
682
+ )
683
+ grads_imag_x_imag_y = jnp.where(
684
+ jnp.isfinite(grads_imag_x_imag_y), grads_imag_x_imag_y, 0.0
685
+ )
686
+
687
+ has_grad = jnp.logical_not(
688
+ jnp.all(
689
+ jnp.stack(
690
+ [
691
+ jnp.equal(grads_real_x_real_y, 0),
692
+ jnp.equal(grads_imag_x_real_y, 0),
693
+ jnp.equal(grads_real_x_imag_y, 0),
694
+ jnp.equal(grads_imag_x_imag_y, 0),
695
+ ],
696
+ axis=-1,
697
+ ),
698
+ axis=-1,
699
+ )
700
+ )
701
+ else:
702
+ raise ValueError(f'Unsupported dtypes: {x_dtype=}, {y_dtype=}.')
703
+
704
+ # From [By, Ty, Bx, Tx, *I] choose [By, Bx, *I]
705
+ y_batch_channel_axes = (0,)
706
+ x_batch_channel_axes = (2,) + tuple(range(4, 4 + x.ndim - 2))
707
+
708
+ # Reduce over batch and channel to get input/output timesteps grad presence.
709
+ # [Ty, Tx].
710
+ has_grad = has_grad.any(axis=x_batch_channel_axes + y_batch_channel_axes)
711
+ ty, tx = has_grad.shape
712
+
713
+ # Adjust the has_grad array to account for output ratio.
714
+ # E.g., with output_ratio = 3/2, we have.
715
+ # (3 x 2) --> (3 * 2 x 2) ---> (2 x 2)
716
+ # [[1, 0] insert [[1, 0] reduce [[1, 1] => Overall receptive field: [0, 1].
717
+ # [1, 1] zeros [0, 0] [0, 1]]
718
+ # [0, 1]] [1, 1]
719
+ # [0, 0]
720
+ # [0, 1]
721
+ # [0, 0]]
722
+ if l.output_ratio.denominator != 1:
723
+ # Insert output ratio denominator - 1 zeros between every output time step.
724
+ zeros = jnp.zeros(
725
+ (ty, l.output_ratio.denominator - 1, tx), dtype=has_grad.dtype
726
+ )
727
+ has_grad = jnp.concatenate([has_grad[:, None, :], zeros], axis=1)
728
+ has_grad = has_grad.reshape(-1, tx)
729
+ if l.output_ratio.numerator != 1:
730
+ n = l.output_ratio.numerator
731
+ # Reduce every output ratio numerator steps.
732
+ if has_grad.shape[0] % n != 0:
733
+ pad_width = (
734
+ (0, n - has_grad.shape[0] % n),
735
+ (0, 0),
736
+ )
737
+ has_grad = jnp.pad(has_grad, pad_width)
738
+
739
+ has_grad = jnp.reshape(has_grad, [-1, l.output_ratio.numerator, tx]).any(
740
+ axis=1
741
+ )
742
+
743
+ # After adjustments above has_grad should be shaped as [Tx, Tx] and each row
744
+ # i indicates the receptive field for the ith time step. To compute the
745
+ # aggregate union of the receptive fields, we shear it.
746
+ # Example: (relative indices)
747
+ # -3 5
748
+ # [[1 1 0 0 0] [[0 0 0 0 1 1 0 0 0] | .... |
749
+ # [1 1 1 0 0] shear [0 0 0 1 1 1 0 0 0] reduce v v
750
+ # [0 1 1 1 0] --> [0 0 0 1 1 1 0 0 0] --> [0 0 0 1 1 1 0 0 0]
751
+ # [0 0 1 1 1] [0 0 0 1 1 1 0 0 0] | |
752
+ # [0 0 0 1 1]] [0 0 0 1 1 0 0 0 0]] v v
753
+ # receptive field:[0, 2]
754
+ # ---------------------------------------------------------------------------
755
+ has_grad_sheared = _shear_2d(has_grad)
756
+ has_grad_sheared_any = has_grad_sheared.any(axis=0)
757
+ shift = -has_grad.shape[0] + 1
758
+
759
+ # Shift the array indices to account for past time steps.
760
+ receptive_field_indices = jnp.where(has_grad_sheared_any)[0] + shift
761
+ if receptive_field_indices.shape[0] == 0:
762
+ return None
763
+ past = receptive_field_indices[0].item()
764
+ future = receptive_field_indices[-1].item()
765
+ return past, future
766
+
767
+
768
+ def _mask_and_pad_to_max_length(
769
+ a: types.Sequence, b: types.Sequence
770
+ ) -> tuple[types.Sequence, types.Sequence]:
771
+ # Only compare values in non-masked regions.
772
+ a = a.mask_invalid()
773
+ b = b.mask_invalid()
774
+ a_time = a.values.shape[1]
775
+ b_time = b.values.shape[1]
776
+ max_time = max(a_time, b_time)
777
+ a = a.pad_time(0, max_time - a_time, valid=False)
778
+ b = b.pad_time(0, max_time - b_time, valid=False)
779
+ return a, b
780
+
781
+
782
+ class SequenceLayerTest(parameterized.TestCase):
783
+ """Base class for SequenceLayer tests."""
784
+
785
+ def setUp(self):
786
+ super().setUp()
787
+ # To avoid flakes, fix random seeds.
788
+ random.seed(123456789)
789
+ np.random.seed(123456789)
790
+
791
+ def init_and_bind_layer(
792
+ self,
793
+ key: jax.Array,
794
+ layer: _SequenceLayerT,
795
+ x: types.Sequence,
796
+ randomize_weights: bool = False,
797
+ constants: types.Constants | None = None,
798
+ jit: bool = False,
799
+ ) -> _SequenceLayerT:
800
+ """Initializes and binds a SequenceLayer for testing.
801
+
802
+ Args:
803
+ key: Random key for generating weights.
804
+ layer: Layer to initialize and bind.
805
+ x: Example input sequence to use for initialization.
806
+ randomize_weights: Whether to replace all variables with random normal
807
+ generations of the same shape and dtype.
808
+ constants: Constants to provide to layer, if needed.
809
+ jit: Whether to jit the initialization function.
810
+
811
+ Returns:
812
+ The provided layer, bound with initialized weights.
813
+ """
814
+
815
+ def init_fn(x: types.Sequence, constants: types.Constants):
816
+ return layer.init(key, x, training=False, constants=constants)
817
+
818
+ if jit:
819
+ init_fn = jax.jit(init_fn)
820
+
821
+ variables = init_fn(x, constants)
822
+
823
+ if randomize_weights:
824
+
825
+ @jax.jit
826
+ def randomize_weights_fn(variables):
827
+ variables, variables_pytree = jax.tree.flatten(variables)
828
+ # TODO(rryan): Use jax.random.split here.
829
+ keys = [key] * len(variables)
830
+ variables = [
831
+ jax.random.normal(k, v.shape, v.dtype)
832
+ for k, v in zip(keys, variables)
833
+ ]
834
+ return jax.tree.unflatten(variables_pytree, variables)
835
+
836
+ variables = randomize_weights_fn(variables)
837
+
838
+ return layer.bind(variables)
839
+
840
+ def verify_masked(self, x: types.Sequence):
841
+ """Asserts all invalid timesteps in x have values masked to zero."""
842
+ # Manually mask even if x is a MaskedSequence.
843
+ expected = types.Sequence(x.values, x.mask).mask_invalid()
844
+ self.assertAllEqual(x.values, expected.values)
845
+
846
+ def verify_contract(
847
+ self,
848
+ l: types.SequenceLayer,
849
+ x: types.Sequence,
850
+ *,
851
+ training: bool,
852
+ constants: types.Constants | None = None,
853
+ stream_constants: bool = False,
854
+ rtol: float = 1e-6,
855
+ atol: float = 1e-6,
856
+ test_gradients: bool = True,
857
+ grad_rtol=None,
858
+ grad_atol=None,
859
+ padding_invariance_pad_value: float = jnp.nan,
860
+ pad_constants: bool = False,
861
+ pad_constants_ratio: int = 1,
862
+ test_2x_step: bool = True,
863
+ jit: bool = False,
864
+ test_batching: bool = True,
865
+ test_padding_invariance: bool = True,
866
+ test_receptive_field: bool = True,
867
+ test_receptive_field_relaxed: bool = False,
868
+ ) -> types.Sequence:
869
+ """Verifies that the provided layer obeys the SequenceLayer contract.
870
+
871
+ The contract has three main requirements:
872
+ 1. Layer-wise and step-wise equivalence of outputs and gradients.
873
+ 2. Step must support any multiple of block size.
874
+ 3. Padding invariance.
875
+
876
+ This function tests l for all three using the provided input x, training
877
+ mode, and constants.
878
+
879
+ To test layer-wise and step-wise equivalence, the layer is executed
880
+ layer-wise and step-wise on x and the valid regions are compared for
881
+ equivalence up to rtol/atol. If test_gradients is True, the gradient of the
882
+ input x with respect to the output y and the gradient of the layer
883
+ parameters with respect to y are measured and checked for equivalence up to
884
+ grad_rtol/grad_atol.
885
+
886
+ To test that step supports sequences whose length is any multiple of its
887
+ block size, the layer is run on step-wise on inputs of length 2 *
888
+ l.block_size and the output is compared to the step-wise output on inputs of
889
+ length l.block_size.
890
+
891
+ To test padding invariance, all invalid values in the sequence are replaced
892
+ with padding_invariance_pad_value and the sequence and constants are
893
+ extended by 4 block_sizes worth of padding. The layer-wise output is checked
894
+ for equivalence on this padded sequence.
895
+
896
+ If the provided layer is not steppable, only padding invariance is tested.
897
+
898
+ Args:
899
+ l: The layer to test.
900
+ x: The sequence to use as input.
901
+ training: Whether to verify the contract in training mode.
902
+ constants: Optional constants to provide to the layer.
903
+ stream_constants: If True, stream Sequences present in constants at the
904
+ same block size as x.
905
+ rtol: The relative tolerance to test equality with.
906
+ atol: The absolute tolerance to test equality with.
907
+ test_gradients: Whether to compute and compare the gradients for l applied
908
+ to x in step-wise and layer-wise mode.
909
+ grad_rtol: Optional relative tolerance to test layer/step gradient
910
+ equivalence to. Uses rtol if not specified.
911
+ grad_atol: Optional absolute tolerance to test layer/step gradient
912
+ equivalence to. Uses atol if not specified.
913
+ padding_invariance_pad_value: The value to use for testing padding
914
+ invariance. By default, use NaN to show that NaNs do not leak into valid
915
+ regions of the sequence.
916
+ pad_constants: Whether to pad types.Sequence instances in constants along
917
+ with padding x with padding_invariance_pad_value, when testing padding
918
+ invariance.
919
+ pad_constants_ratio: The ratio between the time dimension of x and
920
+ sequences in constants.
921
+ test_2x_step: Whether to test that the layer can be run in step-wise mode
922
+ on sequences whose length is twice the block size.
923
+ jit: If true, jits all functions associated with the model.
924
+ test_batching: Whether to increase the batch size to verify batching
925
+ works.
926
+ test_padding_invariance: Whether to test the layer for padding invariance.
927
+ test_receptive_field: Whether to test the layer for receptive field.
928
+ test_receptive_field_relaxed: Whether to test the layer for receptive
929
+ field with relaxed conditions, i.e., allowing the layer to report a
930
+ receptive field that is larger than the actual receptive field.
931
+
932
+ Returns:
933
+ The output of
934
+ l.layer(x, training=training, constants=constants).mask_invalid().
935
+ This is a convenience for tests that want to do correctness testing after
936
+ verifying the contract, without repeating the work of the layer method.
937
+ """
938
+ if l.scope is None:
939
+ raise ValueError(f'Expected {l=} to be bound to variables for testing.')
940
+
941
+ if grad_rtol is None:
942
+ grad_rtol = rtol
943
+ if grad_atol is None:
944
+ grad_atol = atol
945
+
946
+ self.verify_masked(x)
947
+
948
+ x_spec = x.channel_spec
949
+ y_spec = l.get_output_spec(x_spec, constants=constants)
950
+ output_latency = l.output_latency
951
+ input_latency = l.input_latency
952
+
953
+ def get_initial_state_fn(
954
+ l: types.SequenceLayer, batch_size: int, constants: types.Constants
955
+ ) -> types.State:
956
+ return l.get_initial_state(
957
+ batch_size, x_spec, training=training, constants=constants
958
+ )
959
+
960
+ def get_dy(y: types.Sequence) -> types.Sequence:
961
+ # Do not flow gradient through masked regions by masking dy.
962
+ dy = types.Sequence(jnp.ones_like(y.values), y.mask).mask_invalid().values
963
+ dmask = jnp.zeros_like(y.mask)
964
+ return type(y)(dy, dmask)
965
+
966
+ def layer_fn(
967
+ l: types.SequenceLayer, x: types.Sequence, constants: types.Constants
968
+ ) -> types.Sequence:
969
+ return l.layer(x, training=training, constants=constants).mask_invalid()
970
+
971
+ def layer_vjp_fn(
972
+ l: types.SequenceLayer, x: types.Sequence, constants: types.Constants
973
+ ):
974
+ y, layer_vjp_fn = nn.vjp(layer_fn, l, x, constants)
975
+ params_grad, x_grad, unused_constants_grad = layer_vjp_fn(get_dy(y))
976
+ x_grad = types.Sequence(x_grad.values, x.mask).mask_invalid()
977
+ return y, x_grad, params_grad
978
+
979
+ def step_fn(
980
+ l: types.SequenceLayer,
981
+ x: types.Sequence,
982
+ constants: types.Constants,
983
+ *,
984
+ blocks_per_step: int = 1,
985
+ ) -> tuple[types.Sequence, types.State]:
986
+ state = get_initial_state_fn(l, x.shape[0], constants)
987
+ y, new_state, _ = utils.step_by_step_static(
988
+ l,
989
+ x,
990
+ training=training,
991
+ initial_state=state,
992
+ constants=constants,
993
+ stream_constants=stream_constants,
994
+ blocks_per_step=blocks_per_step,
995
+ )
996
+ chex.assert_trees_all_equal_shapes_and_dtypes(new_state, state)
997
+ # Trim output latency. Doing so here avoids awkwardness with vjp.
998
+ y = y[:, output_latency:]
999
+ return y.mask_invalid(), new_state
1000
+
1001
+ def step_vjp_fn(
1002
+ l: types.SequenceLayer,
1003
+ x: types.Sequence,
1004
+ constants: types.Constants,
1005
+ ):
1006
+ (y, new_state), step_vjp_fn = nn.vjp(step_fn, l, x, constants)
1007
+ dy = get_dy(y)
1008
+ dstate = jax.tree_util.tree_map(jnp.zeros_like, new_state)
1009
+ params_grad, x_grad, unused_constants_grad = step_vjp_fn((dy, dstate))
1010
+ x_grad = types.Sequence(x_grad.values, x.mask).mask_invalid()
1011
+ return y, new_state, x_grad, params_grad
1012
+
1013
+ if jit:
1014
+ layer_fn = nn.jit(layer_fn)
1015
+ layer_vjp_fn = nn.jit(layer_vjp_fn)
1016
+ step_fn = nn.jit(step_fn, static_argnames=('blocks_per_step',))
1017
+ step_vjp_fn = nn.jit(step_vjp_fn)
1018
+
1019
+ if test_gradients:
1020
+ y_layer, y_layer_x_grad, y_layer_params_grad = layer_vjp_fn(
1021
+ l, x, constants
1022
+ )
1023
+ else:
1024
+ y_layer = layer_fn(l, x, constants)
1025
+ y_layer_x_grad = None
1026
+ y_layer_params_grad = None
1027
+
1028
+ chex.assert_equal(y_layer.channel_shape, y_spec.shape)
1029
+ if y_layer.dtype != y_spec.dtype:
1030
+ raise ValueError(
1031
+ f'{y_layer.dtype=} does not match the output spec {y_spec.dtype=}.'
1032
+ )
1033
+
1034
+ if not y_layer.values.size:
1035
+ raise ValueError(
1036
+ f'Layer output is empty, probably unintended: {y_layer=}.'
1037
+ )
1038
+
1039
+ # Pad with 4 blocks of invalid garbage data.
1040
+ pad_amount = 4 * l.block_size
1041
+
1042
+ def _pad(x: types.Sequence, pad_back: int) -> types.Sequence:
1043
+ """Pad pad_back steps and masks with padding_invariance_pad_value."""
1044
+ return x.pad_time(0, pad_back, valid=False).mask_invalid(
1045
+ padding_invariance_pad_value
1046
+ )
1047
+
1048
+ x_padded, constants_padded = x, constants
1049
+ if test_padding_invariance:
1050
+ x_padded = _pad(x, pad_amount)
1051
+ if pad_constants and constants_padded is not None:
1052
+ constants_padded = {
1053
+ k: (
1054
+ _pad(v, pad_amount * pad_constants_ratio)
1055
+ if isinstance(v, types.Sequence)
1056
+ else v
1057
+ )
1058
+ for k, v in constants.items()
1059
+ }
1060
+ y_layer_padded = layer_fn(l, x_padded, constants_padded)
1061
+ self.assertSequencesClose(y_layer, y_layer_padded, rtol=rtol, atol=atol)
1062
+
1063
+ x_batch = None
1064
+ constants_batch = None
1065
+ if test_batching:
1066
+ x_batch, constants_batch = pad_batch_axis_with_garbage((x, constants))
1067
+ y_layer_batch = layer_fn(l, x_batch, constants_batch)
1068
+ y_layer_batch = strip_batch_axis_of_garbage(y_layer_batch)
1069
+ self.assertSequencesClose(y_layer, y_layer_batch, rtol=rtol, atol=atol)
1070
+
1071
+ original_x = x
1072
+ if l.supports_step:
1073
+ # Extend x by the input latency so we run the layer until all outputs are
1074
+ # flushed.
1075
+ x = x.pad_time(0, input_latency, valid=False)
1076
+ if test_padding_invariance:
1077
+ x_padded = x_padded.pad_time(0, input_latency, valid=False)
1078
+
1079
+ if test_gradients:
1080
+ y_step, _, y_step_x_grad, y_step_params_grad = step_vjp_fn(
1081
+ l, x, constants
1082
+ )
1083
+ else:
1084
+ y_step, _ = step_fn(l, x, constants)
1085
+ y_step_x_grad = None
1086
+ y_step_params_grad = None
1087
+
1088
+ if test_2x_step:
1089
+ y_step_2x, _ = step_fn(l, x, constants, blocks_per_step=2)
1090
+ else:
1091
+ y_step_2x = None
1092
+
1093
+ if test_batching:
1094
+ assert x_batch is not None
1095
+ x_batch = x_batch.pad_time(0, input_latency, valid=False)
1096
+ y_step_batch, _ = step_fn(l, x_batch, constants_batch)
1097
+ y_step_batch = strip_batch_axis_of_garbage(y_step_batch)
1098
+ self.assertSequencesClose(y_step, y_step_batch, rtol=rtol, atol=atol)
1099
+
1100
+ # Property 1: Check layer-wise and step-wise equivalence.
1101
+ self.assertSequencesClose(y_layer, y_step, rtol=rtol, atol=atol)
1102
+ if test_2x_step:
1103
+ self.assertSequencesClose(y_layer, y_step_2x, rtol=rtol, atol=atol)
1104
+
1105
+ # Property 2: Padding invariance.
1106
+ if test_padding_invariance:
1107
+ y_step_padded, _ = step_fn(l, x_padded, constants_padded)
1108
+ self.assertSequencesClose(y_step, y_step_padded, rtol=rtol, atol=atol)
1109
+
1110
+ if test_gradients:
1111
+ # Property 1: Check layer-wise and step-wise equivalence of gradients.
1112
+ # Skip comparison of JAX float0 types, which are used in
1113
+ # jvp/linearization of integers / booleans. This likely means the input
1114
+ # is an integer type. go/jax-integer-autodiff
1115
+ assert y_layer_x_grad is not None
1116
+ if y_layer_x_grad.dtype != jax.dtypes.float0:
1117
+ self.assertSequencesClose(
1118
+ y_layer_x_grad, y_step_x_grad, rtol=grad_rtol, atol=grad_atol
1119
+ )
1120
+ chex.assert_trees_all_close(
1121
+ y_layer_params_grad,
1122
+ y_step_params_grad,
1123
+ rtol=grad_rtol,
1124
+ atol=grad_atol,
1125
+ )
1126
+
1127
+ if test_receptive_field:
1128
+ x_is_inexact = jnp.issubdtype(x.dtype, jnp.inexact)
1129
+ y_is_inexact = jnp.issubdtype(y_layer.dtype, jnp.inexact)
1130
+ receptive_field = l.receptive_field
1131
+ if receptive_field == (-np.inf, np.inf):
1132
+ logging.warning(
1133
+ 'Skipping receptive field test since layer has infinite receptive'
1134
+ ' field.'
1135
+ )
1136
+ elif not x_is_inexact or not y_is_inexact:
1137
+ # With integer types we cannot test with gradients. We can only verify
1138
+ # that changing values outside receptive field does not change the
1139
+ # output, which is not implemented yet.
1140
+ raise NotImplementedError(
1141
+ 'Receptive field test with non-float/complex input/output types is'
1142
+ ' not supported.'
1143
+ )
1144
+ else:
1145
+ rf_x, rf_constants = _prep_input_for_receptive_field(
1146
+ l, original_x, constants, pad_constants, pad_constants_ratio
1147
+ )
1148
+ expected_receptive_field = _gradient_receptive_field(
1149
+ l, layer_fn, rf_x, rf_constants
1150
+ )
1151
+
1152
+ if receptive_field is None:
1153
+ self.assertIsNone(expected_receptive_field)
1154
+ elif receptive_field[0] == -np.inf:
1155
+ if test_receptive_field_relaxed:
1156
+ self.assertGreaterEqual(
1157
+ receptive_field[1], expected_receptive_field[1]
1158
+ )
1159
+ else:
1160
+ self.assertEqual(receptive_field[1], expected_receptive_field[1])
1161
+ elif receptive_field[1] == np.inf:
1162
+ if test_receptive_field_relaxed:
1163
+ self.assertLessEqual(
1164
+ receptive_field[0], expected_receptive_field[0]
1165
+ )
1166
+ else:
1167
+ self.assertEqual(receptive_field[0], expected_receptive_field[0])
1168
+ else:
1169
+ if test_receptive_field_relaxed:
1170
+ self.assertLessEqual(
1171
+ receptive_field[0], expected_receptive_field[0]
1172
+ )
1173
+ self.assertGreaterEqual(
1174
+ receptive_field[1], expected_receptive_field[1]
1175
+ )
1176
+ else:
1177
+ self.assertEqual(receptive_field, expected_receptive_field)
1178
+ return y_layer
1179
+
1180
+ def assertSequencesClose( # pylint: disable=invalid-name
1181
+ self,
1182
+ a: types.Sequence,
1183
+ b: types.Sequence,
1184
+ atol: float = 1e-6,
1185
+ rtol: float = 1e-6,
1186
+ ):
1187
+ """After padding, checks sequence values are close and masks are equal."""
1188
+ a, b = _mask_and_pad_to_max_length(a, b)
1189
+ self.assertAllClose(a.values, b.values, atol=atol, rtol=rtol)
1190
+ self.assertAllEqual(a.mask, b.mask)
1191
+
1192
+ def assertSequencesNotClose( # pylint: disable=invalid-name
1193
+ self,
1194
+ a: types.Sequence,
1195
+ b: types.Sequence,
1196
+ atol: float = 1e-6,
1197
+ rtol: float = 1e-6,
1198
+ ):
1199
+ """After padding, checks sequence values aren't close, masks are equal."""
1200
+ a, b = _mask_and_pad_to_max_length(a, b)
1201
+ self.assertNotAllClose(a.values, b.values, atol=atol, rtol=rtol)
1202
+ self.assertAllEqual(a.mask, b.mask)
1203
+
1204
+ def assertSequencesEqual( # pylint: disable=invalid-name
1205
+ self,
1206
+ a: types.Sequence,
1207
+ b: types.Sequence,
1208
+ ):
1209
+ """After padding, checks sequence values are equal and masks are equal."""
1210
+ a, b = _mask_and_pad_to_max_length(a, b)
1211
+ self.assertAllEqual(a.values, b.values)
1212
+ self.assertAllEqual(a.mask, b.mask)
1213
+
1214
+ def assertSequencesNotEqual( # pylint: disable=invalid-name
1215
+ self,
1216
+ a: types.Sequence,
1217
+ b: types.Sequence,
1218
+ ):
1219
+ """After padding, checks sequence values aren't equal, masks are equal."""
1220
+ a, b = _mask_and_pad_to_max_length(a, b)
1221
+ self.assertNotAllEqual(a.values, b.values)
1222
+ self.assertAllEqual(a.mask, b.mask)
1223
+
1224
+ def assertAllEqual(self, a, b): # pylint: disable=invalid-name
1225
+ """Asserts that two arrays are equal."""
1226
+ if jnp.iscomplexobj(a) or jnp.iscomplexobj(b):
1227
+ a_real, a_imag = jnp.real(a), jnp.imag(a)
1228
+ b_real, b_imag = jnp.real(b), jnp.imag(b)
1229
+ chex.assert_trees_all_equal(a_real, b_real)
1230
+ chex.assert_trees_all_equal(a_imag, b_imag)
1231
+ else:
1232
+ chex.assert_trees_all_equal(a, b)
1233
+
1234
+ def assertAllClose(self, a, b, atol: float = 1e-6, rtol: float = 1e-6): # pylint: disable=invalid-name
1235
+ """Asserts that two arrays have close values."""
1236
+ if jnp.iscomplexobj(a) or jnp.iscomplexobj(b):
1237
+ a_real, a_imag = jnp.real(a), jnp.imag(a)
1238
+ b_real, b_imag = jnp.real(b), jnp.imag(b)
1239
+ chex.assert_trees_all_close(a_real, b_real, atol=atol, rtol=rtol)
1240
+ chex.assert_trees_all_close(a_imag, b_imag, atol=atol, rtol=rtol)
1241
+ else:
1242
+ chex.assert_trees_all_close(a, b, atol=atol, rtol=rtol)
1243
+
1244
+ def assertNotAllEqual(self, a, b): # pylint: disable=invalid-name
1245
+ """Asserts that two arrays do not have equal values."""
1246
+ try:
1247
+ chex.assert_trees_all_equal(a, b)
1248
+ except AssertionError:
1249
+ return
1250
+ raise AssertionError(
1251
+ 'The two values are equal at all elements. %s %s' % (a, b)
1252
+ )
1253
+
1254
+ def assertNotAllClose(self, a, b, atol: float = 1e-6, rtol: float = 1e-6): # pylint: disable=invalid-name
1255
+ """Asserts that two arrays do not have close values."""
1256
+ try:
1257
+ self.assertAllClose(a, b, atol=atol, rtol=rtol)
1258
+ except AssertionError:
1259
+ return
1260
+ raise AssertionError(
1261
+ 'The two values are close at all elements. %s %s' % (a, b)
1262
+ )
1263
+
1264
+
1265
+ class AssertConstantsLayer(types.PreservesType, types.StatelessPointwise):
1266
+ """Identity layer that raises ValueError if 'test' is not in constants."""
1267
+
1268
+ @dataclasses.dataclass(frozen=True)
1269
+ class Config(types.SequenceLayerConfig):
1270
+ name: str | None = None
1271
+
1272
+ def make(self) -> 'AssertConstantsLayer':
1273
+ return AssertConstantsLayer(self, name=self.name)
1274
+
1275
+ config: Config
1276
+
1277
+ def get_initial_state(
1278
+ self,
1279
+ batch_size: int,
1280
+ input_spec: types.ChannelSpec,
1281
+ *,
1282
+ training: bool,
1283
+ constants: types.Constants | None = None,
1284
+ ) -> types.State:
1285
+ if constants is None or 'test' not in constants:
1286
+ raise ValueError('constant not present')
1287
+ return super().get_initial_state(
1288
+ batch_size, input_spec, training=training, constants=constants
1289
+ )
1290
+
1291
+ def get_output_shape(
1292
+ self,
1293
+ input_shape: types.ShapeLike,
1294
+ *,
1295
+ constants: types.Constants | None = None,
1296
+ ) -> types.Shape:
1297
+ if constants is None or 'test' not in constants:
1298
+ raise ValueError('constant not present')
1299
+ return super().get_output_shape(input_shape, constants=constants)
1300
+
1301
+ def layer(
1302
+ self,
1303
+ x: types.Sequence,
1304
+ *,
1305
+ training: bool,
1306
+ constants: types.Constants | None = None,
1307
+ ) -> types.Sequence:
1308
+ del training
1309
+ if constants is None or 'test' not in constants:
1310
+ raise ValueError('constant not present')
1311
+ return x
1312
+
1313
+
1314
+ class NonSteppableLayer(types.PreservesType, types.StatelessPointwise):
1315
+ """A test layer that does not support stepping."""
1316
+
1317
+ @dataclasses.dataclass(frozen=True)
1318
+ class Config(types.SequenceLayerConfig):
1319
+ name: str | None = None
1320
+
1321
+ def make(self) -> 'NonSteppableLayer':
1322
+ return NonSteppableLayer(self, name=self.name)
1323
+
1324
+ config: Config
1325
+
1326
+ @property
1327
+ def supports_step(self):
1328
+ return False
1329
+
1330
+ def layer(
1331
+ self,
1332
+ x: types.Sequence,
1333
+ *,
1334
+ training: bool,
1335
+ constants: types.Constants | None = None,
1336
+ ) -> types.Sequence:
1337
+ del training
1338
+ del constants
1339
+ return x
1340
+
1341
+
1342
+ # Forward main for convenience.
1343
+ main = absltest.main