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,2103 @@
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
+ """Convolution layers."""
15
+
16
+ import abc
17
+ import dataclasses
18
+ import fractions
19
+ import math
20
+ import typing
21
+ from typing import Callable, Sequence as TypingSequence
22
+
23
+ import flax.linen as nn
24
+ import jax
25
+ import jax.numpy as jnp
26
+ import numpy as np
27
+ from sequence_layers.jax import meta
28
+ from sequence_layers.jax import types
29
+ from sequence_layers.jax import typing as jt
30
+ from sequence_layers.jax import utils
31
+
32
+
33
+ __all__ = (
34
+ # go/keep-sorted start
35
+ 'Conv1D',
36
+ 'Conv1DTranspose',
37
+ 'Conv2D',
38
+ 'Conv2DTranspose',
39
+ 'Conv3D',
40
+ 'DepthwiseConv1D',
41
+ # go/keep-sorted end
42
+ )
43
+
44
+
45
+ def _compute_conv_mask_logical(
46
+ mask: types.MaskT,
47
+ kernel_size: int,
48
+ stride: int,
49
+ dilation_rate: int,
50
+ use_logical_or: bool,
51
+ ) -> types.MaskT:
52
+ """Computes the mask resulting from applying a "logical AND" masking rule.
53
+
54
+ Args:
55
+ mask: The input mask.
56
+ kernel_size: The kernel size in the time dimension.
57
+ stride: The stride in the time dimension.
58
+ dilation_rate: The dilation rate in the time dimension.
59
+ use_logical_or: When False (default), an AND mask is computed. When True, an
60
+ OR mask is used instead.
61
+
62
+ Returns:
63
+ The mask resulting from applying a VALID-like "logical AND" rule. If any
64
+ input timestep in the receptive field of the convolution is invalid, then
65
+ the output is considered invalid.
66
+ """
67
+ # TODO(b/273591446): Workaround for VMEM OOMs when applying convolutions or
68
+ # framing to long mask sequences. Remove when fixed.
69
+ # Discussion: https://chat.google.com/room/AAAAfoV82X8/o2AWMjKjdwY
70
+ if dilation_rate == 1 and kernel_size % stride == 0:
71
+ num_frames = mask.shape[1] // stride
72
+ mask = mask[:, : num_frames * stride]
73
+ mask = jnp.reshape(mask, [mask.shape[0], num_frames, stride])
74
+
75
+ if use_logical_or:
76
+ mask = jnp.max(mask, axis=-1)
77
+ else:
78
+ mask = jnp.min(mask, axis=-1)
79
+
80
+ kernel_size = kernel_size // stride
81
+ stride = 1
82
+
83
+ if use_logical_or:
84
+ # Compute an OR operation over windows so any window overlapping with at
85
+ # least some valid samples is considered valid.
86
+ computation_fn = jax.lax.max
87
+ init_value = False
88
+ else:
89
+ # Compute an AND operation over windows so any window with invalid samples
90
+ # is considered invalid.
91
+ computation_fn = jax.lax.min
92
+ init_value = True
93
+
94
+ mask = jax.lax.reduce_window(
95
+ mask,
96
+ init_value=init_value,
97
+ computation=computation_fn,
98
+ window_dimensions=(1, kernel_size),
99
+ base_dilation=(1, 1),
100
+ window_dilation=(1, dilation_rate),
101
+ window_strides=(1, stride),
102
+ padding='VALID',
103
+ )
104
+ return mask
105
+
106
+
107
+ def compute_conv_mask(
108
+ mask: types.MaskT,
109
+ kernel_size: int,
110
+ stride: int,
111
+ dilation_rate: int,
112
+ padding: tuple[int, int] | types.PaddingModeString,
113
+ is_step: bool,
114
+ ) -> types.MaskT:
115
+ """Computes the output mask for a convolution-like operation.
116
+
117
+ The formula for the output time dimension for a [b, t] mask is:
118
+
119
+ effective_kernel_size = (kernel_size - 1) * dilation_rate + 1
120
+ output_frames = ceil((t - effective_kernel_size + 1) / stride)
121
+
122
+ If padding is 'causal_valid' or 'reverse_causal_valid', we assume that the
123
+ mask has padding of `effective_kernel_size - 1` applied which ensures that the
124
+ above formula is at least zero, because `t >= effective_kernel_size - 1`.
125
+
126
+ Args:
127
+ mask: The input [b, t] mask.
128
+ kernel_size: The kernel size in the time dimension.
129
+ stride: The stride in the time dimension.
130
+ dilation_rate: The dilation rate in the time dimension.
131
+ padding: The padding mode or a tuple of explicit padding amounts.
132
+ is_step: If true, we assume effective_kernel_size - 1 timesteps of padding
133
+ have been prepended to the mask.
134
+
135
+ Returns:
136
+ The output mask. [b, ceil((t - effective_kernel_size + 1) / stride)]
137
+ """
138
+ assert kernel_size >= 1
139
+ assert stride >= 1
140
+ assert dilation_rate >= 1
141
+
142
+ explicit_padding = not isinstance(padding, str)
143
+ if explicit_padding:
144
+ if dilation_rate != 1:
145
+ raise ValueError('Dilation and explicit padding is not supported.')
146
+ else:
147
+ padding = types.validate_padding(padding)
148
+
149
+ # If we are stepping, the caller has prepended buffer_size frames of padding
150
+ # to the mask.
151
+ #
152
+ # TODO(rryan): How does stride offset factor into this?
153
+ #
154
+ # To simulate the convolution this mask is associated with, we perform a valid
155
+ # convolution on the mask with a kernel that selects the correct starting
156
+ # timestep.
157
+ if is_step:
158
+ if explicit_padding or padding in (
159
+ types.PaddingMode.SAME.value,
160
+ types.PaddingMode.CAUSAL.value,
161
+ types.PaddingMode.REVERSE_CAUSAL.value,
162
+ types.PaddingMode.SEMICAUSAL.value,
163
+ ):
164
+ effective_kernel_size = utils.convolution_effective_kernel_size(
165
+ kernel_size, dilation_rate
166
+ )
167
+ past_pad, future_pad = utils.convolution_explicit_padding(
168
+ padding,
169
+ kernel_size,
170
+ stride=stride,
171
+ dilation_rate=dilation_rate,
172
+ )
173
+ if past_pad + future_pad != effective_kernel_size - 1:
174
+ raise ValueError(f'Padding {padding=} must sum to {kernel_size - 1}.')
175
+
176
+ # TODO(rryan): Replace with a (presumably more efficient) strided slice.
177
+ # It's tricky to get the details right with stride and dilation.
178
+ kernel = jnp.array([0] * past_pad + [1] + [0] * future_pad, jnp.float32)
179
+ return jnp.squeeze(
180
+ jax.lax.conv_general_dilated(
181
+ mask[:, :, jnp.newaxis].astype(jnp.float32),
182
+ kernel[:, jnp.newaxis, jnp.newaxis],
183
+ window_strides=[stride],
184
+ padding='VALID',
185
+ rhs_dilation=[1],
186
+ dimension_numbers=('NHC', 'HIO', 'NHC'),
187
+ ),
188
+ axis=2,
189
+ ).astype(jnp.bool_)
190
+ else:
191
+ assert padding in (
192
+ types.PaddingMode.VALID.value,
193
+ types.PaddingMode.CAUSAL_VALID.value,
194
+ types.PaddingMode.REVERSE_CAUSAL_VALID.value,
195
+ ), padding
196
+ return _compute_conv_mask_logical(
197
+ mask, kernel_size, stride, dilation_rate, use_logical_or=False
198
+ )
199
+
200
+ # All logic below concerns layer-wise mask calculation.
201
+ assert not is_step
202
+
203
+ if explicit_padding or padding in (
204
+ types.PaddingMode.SAME.value,
205
+ types.PaddingMode.CAUSAL.value,
206
+ types.PaddingMode.REVERSE_CAUSAL.value,
207
+ types.PaddingMode.SEMICAUSAL.value,
208
+ ):
209
+ if stride > 1:
210
+ mask = mask[:, ::stride]
211
+ return mask
212
+
213
+ assert padding in (
214
+ types.PaddingMode.VALID.value,
215
+ types.PaddingMode.CAUSAL_VALID.value,
216
+ types.PaddingMode.REVERSE_CAUSAL_VALID.value,
217
+ types.PaddingMode.SEMICAUSAL_FULL.value,
218
+ ), padding
219
+
220
+ past_pad, future_pad = utils.convolution_explicit_padding(
221
+ padding, kernel_size, stride, dilation_rate
222
+ )
223
+ # TODO(rryan): Fold this padding into the below reduce_window. Not sure if
224
+ # this would introduce a bug in the workaround for b/273591446 below.
225
+ mask = jnp.pad(
226
+ mask,
227
+ [(0, 0), (past_pad, future_pad)],
228
+ mode='constant',
229
+ constant_values=padding == types.PaddingMode.CAUSAL_VALID.value,
230
+ )
231
+
232
+ return _compute_conv_mask_logical(
233
+ mask,
234
+ kernel_size,
235
+ stride,
236
+ dilation_rate,
237
+ use_logical_or=(padding == types.PaddingMode.SEMICAUSAL_FULL.value),
238
+ )
239
+
240
+
241
+ def compute_conv_initial_state(
242
+ batch_size: int,
243
+ input_spec: types.ShapeDType,
244
+ buffer_width: int,
245
+ padding: types.PaddingModeString,
246
+ pad_value: complex | None = None,
247
+ ) -> types.MaskedSequence:
248
+ """Returns the initial state for a convolution layer."""
249
+ match padding:
250
+ case (
251
+ types.PaddingMode.CAUSAL_VALID.value
252
+ | types.PaddingMode.REVERSE_CAUSAL_VALID.value
253
+ | types.PaddingMode.SEMICAUSAL_FULL.value
254
+ ):
255
+ mask = jnp.ones((batch_size, buffer_width), dtype=types.MASK_DTYPE)
256
+ case (
257
+ types.PaddingMode.CAUSAL.value
258
+ | types.PaddingMode.REVERSE_CAUSAL.value
259
+ | types.PaddingMode.SEMICAUSAL.value
260
+ ):
261
+ mask = jnp.zeros((batch_size, buffer_width), dtype=types.MASK_DTYPE)
262
+ case _:
263
+ raise ValueError(
264
+ f'Stepwise processing is not supported with padding: {padding}'
265
+ )
266
+ values = jnp.full(
267
+ (batch_size, buffer_width) + input_spec.shape,
268
+ pad_value if pad_value is not None else 0.0,
269
+ dtype=input_spec.dtype,
270
+ )
271
+
272
+ return types.MaskedSequence(values, mask)
273
+
274
+
275
+ def _compute_conv_transpose_output_length(
276
+ time: int,
277
+ kernel_size: int,
278
+ stride: int,
279
+ dilation_rate: int,
280
+ padding: types.PaddingModeString,
281
+ ):
282
+ """Returns the output time for a transpose convolution, matching Keras."""
283
+ # Based on google3/third_party/py/tf_keras/utils/conv_utils.py.
284
+ padding = types.validate_padding(padding)
285
+
286
+ effective_kernel_size = utils.convolution_effective_kernel_size(
287
+ kernel_size, dilation_rate
288
+ )
289
+
290
+ match padding: # pytype: disable=incomplete-match
291
+ case (
292
+ types.PaddingMode.SAME.value
293
+ | types.PaddingMode.CAUSAL.value
294
+ | types.PaddingMode.SEMICAUSAL_FULL.value
295
+ ):
296
+ output_time = time * stride
297
+ case types.PaddingMode.VALID.value:
298
+ output_time = time * stride + max(effective_kernel_size - stride, 0)
299
+ case _:
300
+ raise ValueError(f'Unsupported padding mode: {padding}')
301
+
302
+ return output_time
303
+
304
+
305
+ def transpose_conv_explicit_padding(
306
+ kernel_size: int,
307
+ stride: int,
308
+ dilation_rate: int,
309
+ padding: types.PaddingModeString,
310
+ ) -> tuple[int, int]:
311
+ """Returns the explicit padding for the desired transpose convolution mode."""
312
+ effective_kernel_size = utils.convolution_effective_kernel_size(
313
+ kernel_size, dilation_rate
314
+ )
315
+
316
+ match padding: # pytype: disable=incomplete-match
317
+ case types.PaddingMode.VALID.value:
318
+ pad_amount = (
319
+ effective_kernel_size
320
+ + stride
321
+ - 2
322
+ + max(effective_kernel_size - stride, 0)
323
+ )
324
+ pad_left = effective_kernel_size - 1
325
+ pad_right = pad_amount - pad_left
326
+ case types.PaddingMode.CAUSAL.value:
327
+ pad_amount = effective_kernel_size + stride - 2
328
+ pad_left = effective_kernel_size - 1
329
+ pad_right = pad_amount - pad_left
330
+ case types.PaddingMode.SAME.value:
331
+ pad_amount = effective_kernel_size + stride - 2
332
+ if stride > effective_kernel_size - 1:
333
+ pad_left = effective_kernel_size - 1
334
+ else:
335
+ pad_left = int(np.ceil(pad_amount / 2))
336
+ pad_right = pad_amount - pad_left
337
+ case types.PaddingMode.SEMICAUSAL_FULL.value:
338
+ pad_left = effective_kernel_size - stride
339
+ pad_right = effective_kernel_size - 1
340
+ case _:
341
+ raise ValueError(f'Unsupported padding: {padding}')
342
+
343
+ return pad_left, pad_right
344
+
345
+
346
+ def transpose_conv_receptive_field_per_step(
347
+ kernel_size: int,
348
+ stride: int,
349
+ dilation_rate: int,
350
+ padding: types.PaddingModeString,
351
+ ) -> dict[int, types.ReceptiveField]:
352
+ """Returns the receptive field per step for a transpose convolution."""
353
+ explicit_padding = transpose_conv_explicit_padding(
354
+ kernel_size,
355
+ stride,
356
+ dilation_rate,
357
+ padding,
358
+ )
359
+ effective_kernel_size = utils.convolution_effective_kernel_size(
360
+ kernel_size, dilation_rate
361
+ )
362
+ # Shift in transposed conv kernel in the first step, i.e., the number of
363
+ # kernel items are unused in the first step.
364
+ shift_left = effective_kernel_size - explicit_padding[0] - 1
365
+ p = -math.ceil(float(explicit_padding[0] + 1) / stride) + 1
366
+ f = math.ceil(float(shift_left) / stride) - 1
367
+ rf_per_step = {}
368
+ for i in range(stride):
369
+ if (explicit_padding[0] + 1) % stride == 0 or (
370
+ i < ((explicit_padding[0] + 1)) % stride
371
+ ):
372
+ p_i = p
373
+ else:
374
+ p_i = p + 1
375
+ f_i = f if i < -shift_left % stride else f + 1
376
+ rf_per_step[i] = (p_i, f_i) if p_i <= f_i else None
377
+ return rf_per_step
378
+
379
+
380
+ def conv_receptive_field_per_step(
381
+ kernel_size: int,
382
+ stride: int,
383
+ dilation_rate: int,
384
+ padding: types.PaddingModeString,
385
+ ) -> dict[int, types.ReceptiveField]:
386
+ """Returns the receptive field per step for a convolution."""
387
+ effective_kernel_size = utils.convolution_effective_kernel_size(
388
+ kernel_size, dilation_rate
389
+ )
390
+ past = -utils.convolution_explicit_padding(
391
+ padding, kernel_size, stride, dilation_rate
392
+ )[0]
393
+ future = past + effective_kernel_size - 1
394
+ return {0: (past, future)}
395
+
396
+
397
+ def compute_conv_transpose_mask(
398
+ mask: jax.Array,
399
+ kernel_size: int,
400
+ stride: int,
401
+ dilation_rate: int,
402
+ padding: types.PaddingModeString,
403
+ ) -> jax.Array:
404
+ """Given an input mask, computes the output mask for a transpose convolution.
405
+
406
+ Args:
407
+ mask: The input [b, t] mask.
408
+ kernel_size: The kernel size in the time dimension.
409
+ stride: The stride in the time dimension.
410
+ dilation_rate: The dilation rate of the transpose convolution.
411
+ padding: The padding mode. One of 'valid', 'same', or 'causal'.
412
+
413
+ Returns:
414
+ The output mask. [b, t * stride + max(kernel_size - stride, 0)].
415
+ """
416
+ padding = types.validate_padding(padding)
417
+
418
+ if padding in (
419
+ types.PaddingMode.REVERSE_CAUSAL.value,
420
+ types.PaddingMode.REVERSE_CAUSAL_VALID.value,
421
+ types.PaddingMode.CAUSAL_VALID.value,
422
+ ):
423
+ raise ValueError(f'Unsupported padding mode: {padding}')
424
+
425
+ effective_kernel_size = utils.convolution_effective_kernel_size(
426
+ kernel_size, dilation_rate
427
+ )
428
+
429
+ if effective_kernel_size <= stride or padding in (
430
+ types.PaddingMode.SAME.value,
431
+ types.PaddingMode.CAUSAL.value,
432
+ ):
433
+ return jnp.repeat(mask, stride, axis=1)
434
+
435
+ # If effective_kernel_size > stride, use an actual transpose convolution to
436
+ # compute the mask.
437
+ explicit_padding = transpose_conv_explicit_padding(
438
+ kernel_size,
439
+ stride,
440
+ dilation_rate,
441
+ padding,
442
+ )
443
+
444
+ # Any non-zero values in mask have been corrupted by invalid timesteps.
445
+ if padding == types.PaddingMode.SEMICAUSAL_FULL.value:
446
+ # The mask will result in an OR mask.
447
+ test_signal = mask
448
+ test_fn = jnp.greater
449
+ else:
450
+ # The invalid mask will give an AND mask.
451
+ test_signal = jnp.logical_not(mask)
452
+ test_fn = jnp.equal
453
+
454
+ mask = jax.lax.conv_general_dilated(
455
+ test_signal.astype(jnp.float32)[:, :, jnp.newaxis],
456
+ jnp.ones((kernel_size, 1, 1)),
457
+ window_strides=(1,),
458
+ padding=(explicit_padding,),
459
+ lhs_dilation=(stride,),
460
+ rhs_dilation=(dilation_rate,),
461
+ dimension_numbers=('NHC', 'HIO', 'NHC'),
462
+ feature_group_count=1,
463
+ batch_group_count=1,
464
+ )
465
+ return jnp.squeeze(test_fn(mask, 0.0), -1)
466
+
467
+
468
+ class BaseConv(types.SequenceLayer, metaclass=abc.ABCMeta):
469
+ """Shared base logic for convolution layers."""
470
+
471
+ @property
472
+ @abc.abstractmethod
473
+ def _kernel_size(self) -> tuple[int, ...]:
474
+ pass
475
+
476
+ @property
477
+ @abc.abstractmethod
478
+ def _strides(self) -> tuple[int, ...]:
479
+ pass
480
+
481
+ @property
482
+ @abc.abstractmethod
483
+ def _dilation_rate(self) -> tuple[int, ...]:
484
+ pass
485
+
486
+ @property
487
+ @abc.abstractmethod
488
+ def _paddings(self) -> tuple[types.PaddingModeString | tuple[int, int], ...]:
489
+ pass
490
+
491
+ @property
492
+ def supports_step(self) -> bool:
493
+ return self._paddings[0] in (
494
+ types.PaddingMode.CAUSAL_VALID.value,
495
+ types.PaddingMode.REVERSE_CAUSAL_VALID.value,
496
+ types.PaddingMode.CAUSAL.value,
497
+ types.PaddingMode.REVERSE_CAUSAL.value,
498
+ types.PaddingMode.SEMICAUSAL.value,
499
+ )
500
+
501
+ @property
502
+ def block_size(self) -> int:
503
+ return self._strides[0]
504
+
505
+ @property
506
+ def output_ratio(self) -> fractions.Fraction:
507
+ return fractions.Fraction(1, self._strides[0])
508
+
509
+ @property
510
+ def input_latency(self) -> int:
511
+ effective_kernel_size = utils.convolution_effective_kernel_size(
512
+ self._kernel_size[0], self._dilation_rate[0]
513
+ )
514
+
515
+ match self._paddings[0]:
516
+ case (
517
+ types.PaddingMode.CAUSAL_VALID.value
518
+ | types.PaddingMode.CAUSAL.value
519
+ | types.PaddingMode.SEMICAUSAL.value
520
+ ):
521
+ # Causal padding eliminates latency.
522
+ return 0
523
+ case (
524
+ types.PaddingMode.REVERSE_CAUSAL_VALID.value
525
+ | types.PaddingMode.REVERSE_CAUSAL.value
526
+ | types.PaddingMode.SEMICAUSAL_FULL.value
527
+ ):
528
+ # Reverse causal introduces no past padding in layer-wise mode, so we
529
+ # need a full effective_kernel_size kernel to compute the first output
530
+ # layer-wise processing would produce. Since we do not count the current
531
+ # input as part of the latency, the input latency is one smaller than
532
+ # the effective kernel size.
533
+ # Semicausal-full will pad zeros at the end of the sequence until the
534
+ # kernel no longer overlaps with the sequence. This results in at most
535
+ # the effective kernel size minus 1 zeros padded.
536
+ return effective_kernel_size - 1
537
+ case _:
538
+ # Unsupported.
539
+ return 0
540
+
541
+ @property
542
+ def output_latency(self) -> int:
543
+ """Returns the output latency of this layer.
544
+
545
+ Output latency is defined as the number of output timesteps before the
546
+ step-wise output of the layer matches its layer-wise output.
547
+ """
548
+ match self._paddings[0]:
549
+ case types.PaddingMode.SEMICAUSAL_FULL.value:
550
+ # The semicausal-full padding has both left and right padding, which
551
+ # requires a different output_latency for correct operations.
552
+ # It only requires to wait for strides[0] - 1 samples, and the
553
+ # output_ratio is also strides[0], which means the latency is 0.
554
+ return 0
555
+ case _:
556
+ # Other cases are handled in the parent class.
557
+ return super().output_latency
558
+
559
+ @property
560
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
561
+ effective_kernel_size = utils.convolution_effective_kernel_size(
562
+ self._kernel_size[0], self._dilation_rate[0]
563
+ )
564
+ past = -utils.convolution_explicit_padding(
565
+ self._paddings[0],
566
+ self._kernel_size[0],
567
+ self._strides[0],
568
+ self._dilation_rate[0],
569
+ )[0]
570
+ future = past + effective_kernel_size - 1
571
+ return {0: (past, future)}
572
+
573
+ @property
574
+ def _buffer_width(self) -> int:
575
+ effective_kernel_size = utils.convolution_effective_kernel_size(
576
+ self._kernel_size[0], self._dilation_rate[0]
577
+ )
578
+
579
+ match self._paddings[0]:
580
+ case types.PaddingMode.SEMICAUSAL.value:
581
+ return max(effective_kernel_size - self._strides[0], 0)
582
+ case (
583
+ types.PaddingMode.REVERSE_CAUSAL.value
584
+ | types.PaddingMode.REVERSE_CAUSAL_VALID.value
585
+ ):
586
+ return (
587
+ (effective_kernel_size - 1) // self._strides[0] * self._strides[0]
588
+ )
589
+ case (
590
+ types.PaddingMode.CAUSAL.value | types.PaddingMode.CAUSAL_VALID.value
591
+ ):
592
+ return effective_kernel_size - 1
593
+ case _:
594
+ raise NotImplementedError(
595
+ f'Unsupported padding mode: {self._paddings[0]}'
596
+ )
597
+
598
+ def get_initial_state(
599
+ self,
600
+ batch_size: int,
601
+ input_spec: types.ShapeDType,
602
+ *,
603
+ training: bool,
604
+ constants: types.Constants | None = None,
605
+ ) -> types.State:
606
+ # Special case kernel_size 1 since it is stateless.
607
+ if not (buffer_width := self._buffer_width):
608
+ return ()
609
+
610
+ # Input spec should be the non-time conv dimensions plus a channels
611
+ # dimension.
612
+ if len(input_spec.shape) != len(self._kernel_size):
613
+ raise ValueError(
614
+ f'{type(self).__name__} requires a rank 2 input spec, got:'
615
+ f' {input_spec}.'
616
+ )
617
+
618
+ return compute_conv_initial_state(
619
+ batch_size,
620
+ input_spec,
621
+ buffer_width,
622
+ self._paddings[0],
623
+ )
624
+
625
+ @types.check_step
626
+ def step(
627
+ self,
628
+ x: types.Sequence,
629
+ state: types.State,
630
+ *,
631
+ training: bool,
632
+ constants: types.Constants | None = None,
633
+ ) -> tuple[types.Sequence, types.State]:
634
+ # In step mode, causal padding is handled by the state that is concatenated
635
+ # below.
636
+ explicit_paddings = ((0, 0),) + tuple(
637
+ utils.convolution_explicit_padding(
638
+ padding, kernel_size, stride, dilation_rate
639
+ )
640
+ for padding, kernel_size, stride, dilation_rate in zip(
641
+ self._paddings[1:],
642
+ self._kernel_size[1:],
643
+ self._strides[1:],
644
+ self._dilation_rate[1:],
645
+ strict=True,
646
+ )
647
+ )
648
+
649
+ effective_kernel_size = utils.convolution_effective_kernel_size(
650
+ self._kernel_size[0], self._dilation_rate[0]
651
+ )
652
+ # Mask the input if the effective kernel size is greater than 1.
653
+ if effective_kernel_size > 1:
654
+ x = x.mask_invalid()
655
+
656
+ if buffer_width := self._buffer_width:
657
+ # Concatenate the new frames with the previous buffer_width frames.
658
+ state = state.concatenate(x)
659
+ else:
660
+ state = x
661
+
662
+ # Compute the output for the current timestep.
663
+ values = self._layer(state.values, padding=explicit_paddings)
664
+ mask = compute_conv_mask(
665
+ state.mask,
666
+ self._kernel_size[0],
667
+ self._strides[0],
668
+ self._dilation_rate[0],
669
+ self._paddings[0],
670
+ is_step=True,
671
+ )
672
+
673
+ # Keep the trailing buffer_width samples for the next step.
674
+ if buffer_width:
675
+ state = state[:, -buffer_width:]
676
+ else:
677
+ state = ()
678
+
679
+ # Convolution can leave unmasked values with non-zero values.
680
+ return types.Sequence(values, mask), state
681
+
682
+ @types.check_layer
683
+ def layer(
684
+ self,
685
+ x: types.Sequence,
686
+ training: bool,
687
+ constants: types.Constants | None = None,
688
+ ):
689
+ # Mask inputs if receptive field is greater than 1.
690
+ if self._kernel_size[0] > 1:
691
+ x = x.mask_invalid()
692
+
693
+ explicit_paddings = tuple(
694
+ utils.convolution_explicit_padding(p, k, s, d)
695
+ for p, k, s, d in zip(
696
+ self._paddings,
697
+ self._kernel_size,
698
+ self._strides,
699
+ self._dilation_rate,
700
+ strict=True,
701
+ )
702
+ )
703
+ values = self._layer(x.values, padding=explicit_paddings)
704
+ mask = compute_conv_mask(
705
+ x.mask,
706
+ self._kernel_size[0],
707
+ self._strides[0],
708
+ self._dilation_rate[0],
709
+ self._paddings[0],
710
+ is_step=False,
711
+ )
712
+ # If the convolution has a receptive field of 1 and no bias then the output
713
+ # preserves the input mask state.
714
+ result_type = (
715
+ types.Sequence
716
+ if self.config.use_bias or self._kernel_size[0] > 1
717
+ else type(x)
718
+ )
719
+ return result_type(values, mask)
720
+
721
+ def _layer(
722
+ self,
723
+ x: jt.Float[jt.ArrayT, 'B T *S D'],
724
+ padding: tuple[tuple[int, int], ...],
725
+ ) -> jt.Float[jt.ArrayT, 'B T *S D']:
726
+ raise NotImplementedError()
727
+
728
+
729
+ def _weight_norm(module: nn.Module, weight: jax.Array, name: str) -> jax.Array:
730
+ """Normalizes weight along the last dim https://arxiv.org/abs/1602.07868."""
731
+ # TODO: b/330719129 - EMA(WN(w)) support similar to TF2 seanet.
732
+ # http://google3/audio/ears/minimodal/seanet/layers/wrappers.py;l=36;rcl=530722248
733
+ if module.is_initializing():
734
+ # Based on tensorflow addon, which preserves the original scale.
735
+ # http://google3/third_party/py/tensorflow_addons/layers/wrappers.py;l=181;rcl=509843210
736
+ scale = module.param(
737
+ name,
738
+ lambda unused_key: jnp.linalg.norm(
739
+ weight.reshape([-1, weight.shape[-1]]), axis=0
740
+ ),
741
+ )
742
+ else:
743
+ # Dummy initializer to avoid flax's eval_shape cost.
744
+ scale = module.param(
745
+ name, nn.initializers.zeros_init(), [weight.shape[-1]], weight.dtype
746
+ )
747
+ axis = list(range(weight.ndim - 1))
748
+ scale = jnp.expand_dims(scale, axis)
749
+ return scale * _l2_normalize(weight, axis)
750
+
751
+
752
+ def _l2_normalize(
753
+ x: jax.Array, axis: int | TypingSequence[int] | None, eps: float = 1e-12
754
+ ) -> jax.Array:
755
+ """L2-normalize a Jax tensor along certain dimension."""
756
+ return x * jax.lax.rsqrt((x * x).sum(axis=axis, keepdims=True) + eps)
757
+
758
+
759
+ class Conv1D(BaseConv):
760
+ """A 1D strided or dilated convolution layer."""
761
+
762
+ @dataclasses.dataclass(frozen=True)
763
+ class Config(types.SequenceLayerConfig):
764
+ """Config for Conv1D."""
765
+
766
+ filters: int
767
+ kernel_size: int
768
+ strides: int = 1
769
+ dilation_rate: int = 1
770
+ padding: types.PaddingModeString = types.PaddingMode.VALID.value
771
+ groups: int = 1
772
+ use_bias: bool = True
773
+ use_weight_norm: bool = False
774
+ activation: Callable[[jax.Array], jax.Array] | None = None
775
+ compute_dtype: types.DType | None = None
776
+ param_dtype: types.DType = jnp.float32
777
+ precision: nn.linear.PrecisionLike = None
778
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
779
+ kernel_sharding: types.Sharding | None = None
780
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
781
+ bias_sharding: types.Sharding | None = None
782
+ name: str | None = None
783
+
784
+ def __post_init__(self):
785
+ object.__setattr__(self, 'padding', types.validate_padding(self.padding))
786
+
787
+ def make(self) -> 'Conv1D':
788
+ return Conv1D(self, name=self.name)
789
+
790
+ config: Config
791
+
792
+ @property
793
+ def _kernel_size(self) -> tuple[int, ...]:
794
+ return (self.config.kernel_size,)
795
+
796
+ @property
797
+ def _strides(self) -> tuple[int, ...]:
798
+ return (self.config.strides,)
799
+
800
+ @property
801
+ def _dilation_rate(self) -> tuple[int, ...]:
802
+ return (self.config.dilation_rate,)
803
+
804
+ @property
805
+ def _paddings(self) -> tuple[types.PaddingModeString | tuple[int, int], ...]:
806
+ return (self.config.padding,)
807
+
808
+ @nn.nowrap
809
+ def get_output_shape(
810
+ self,
811
+ input_shape: types.ShapeLike,
812
+ *,
813
+ constants: types.Constants | None = None,
814
+ ) -> types.Shape:
815
+ if len(input_shape) != 1:
816
+ raise ValueError(
817
+ 'Conv1D requires rank 3 input got: %s'
818
+ % ([None, None] + list(input_shape))
819
+ )
820
+ return (self.config.filters,)
821
+
822
+ @nn.nowrap
823
+ def get_output_dtype(
824
+ self,
825
+ input_dtype: types.DType,
826
+ ) -> types.DType:
827
+ return utils.get_promoted_dtype(
828
+ input_dtype, self.config.param_dtype, dtype=self.config.compute_dtype
829
+ )
830
+
831
+ @nn.compact
832
+ def _layer(
833
+ self,
834
+ x: jt.Float[jt.ArrayT, 'B T D'],
835
+ padding: tuple[tuple[int, int], ...],
836
+ ) -> jt.Float[jt.ArrayT, 'B T D']:
837
+ assert len(padding) == 1, padding
838
+ in_features = jnp.shape(x)[-1]
839
+ if in_features % self.config.groups != 0:
840
+ raise ValueError(
841
+ f'Input features ({in_features}) must be divisible by groups'
842
+ f' ({self.config.groups}).'
843
+ )
844
+ kernel_shape = (
845
+ self.config.kernel_size,
846
+ in_features // self.config.groups,
847
+ self.config.filters,
848
+ )
849
+ kernel_init = utils.shard_initializer(
850
+ self.config.kernel_init,
851
+ self.config.kernel_sharding,
852
+ projectable=True,
853
+ axes_types=(meta.AxisType.FANIN, meta.AxisType.FANIN, None),
854
+ )
855
+ kernel = self.param(
856
+ 'kernel', kernel_init, kernel_shape, self.config.param_dtype
857
+ )
858
+ if self.config.use_weight_norm:
859
+ kernel = _weight_norm(self, kernel, 'scale')
860
+ # One bias weight per output channel, shared between pixels.
861
+ if self.config.use_bias:
862
+ bias_init = utils.shard_initializer(
863
+ self.config.bias_init, self.config.bias_sharding
864
+ )
865
+ bias = self.param(
866
+ 'bias',
867
+ bias_init,
868
+ (self.config.filters,),
869
+ self.config.param_dtype,
870
+ )
871
+ else:
872
+ bias = None
873
+
874
+ x, kernel, bias = nn.dtypes.promote_dtype(
875
+ x, kernel, bias, dtype=self.config.compute_dtype
876
+ )
877
+
878
+ y = jax.lax.conv_general_dilated(
879
+ x,
880
+ kernel,
881
+ window_strides=(self.config.strides,),
882
+ padding=padding,
883
+ lhs_dilation=(1,),
884
+ rhs_dilation=(self.config.dilation_rate,),
885
+ dimension_numbers=('NHC', 'HIO', 'NHC'),
886
+ feature_group_count=self.config.groups,
887
+ precision=self.config.precision,
888
+ )
889
+
890
+ if bias is not None:
891
+ y = utils.bias_add(y, bias)
892
+
893
+ if self.config.activation:
894
+ y = self.config.activation(y)
895
+
896
+ return y
897
+
898
+
899
+ class DepthwiseConv1D(BaseConv):
900
+ """A 1D depthwise strided or dilated convolution layer."""
901
+
902
+ @dataclasses.dataclass(frozen=True)
903
+ class Config(types.SequenceLayerConfig):
904
+ """Config for DepthwiseConv1D."""
905
+
906
+ kernel_size: int
907
+ strides: int = 1
908
+ depth_multiplier: int = 1
909
+ dilation_rate: int = 1
910
+ padding: types.PaddingModeString = types.PaddingMode.VALID.value
911
+ use_bias: bool = True
912
+ use_weight_norm: bool = False
913
+ activation: Callable[[jax.Array], jax.Array] | None = None
914
+ compute_dtype: types.DType | None = None
915
+ param_dtype: types.DType = jnp.float32
916
+ precision: nn.linear.PrecisionLike = None
917
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
918
+ kernel_sharding: types.Sharding | None = None
919
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
920
+ bias_sharding: types.Sharding | None = None
921
+ name: str | None = None
922
+
923
+ def __post_init__(self):
924
+ object.__setattr__(self, 'padding', types.validate_padding(self.padding))
925
+
926
+ def make(self) -> 'DepthwiseConv1D':
927
+ return DepthwiseConv1D(self, name=self.name)
928
+
929
+ config: Config
930
+
931
+ @property
932
+ def _kernel_size(self) -> tuple[int, ...]:
933
+ return (self.config.kernel_size,)
934
+
935
+ @property
936
+ def _strides(self) -> tuple[int, ...]:
937
+ return (self.config.strides,)
938
+
939
+ @property
940
+ def _dilation_rate(self) -> tuple[int, ...]:
941
+ return (self.config.dilation_rate,)
942
+
943
+ @property
944
+ def _paddings(self) -> tuple[types.PaddingModeString | tuple[int, int], ...]:
945
+ return (self.config.padding,)
946
+
947
+ @nn.nowrap
948
+ def get_output_shape(
949
+ self,
950
+ input_shape: types.ShapeLike,
951
+ *,
952
+ constants: types.Constants | None = None,
953
+ ) -> types.Shape:
954
+ if len(input_shape) != 1:
955
+ raise ValueError(
956
+ 'Conv1D requires rank 3 input got: %s'
957
+ % ([None, None] + list(input_shape))
958
+ )
959
+ return (input_shape[0] * self.config.depth_multiplier,)
960
+
961
+ @nn.nowrap
962
+ def get_output_dtype(
963
+ self,
964
+ input_dtype: types.DType,
965
+ ) -> types.DType:
966
+ return utils.get_promoted_dtype(
967
+ input_dtype, self.config.param_dtype, dtype=self.config.compute_dtype
968
+ )
969
+
970
+ @nn.compact
971
+ def _layer(
972
+ self,
973
+ x: jt.Float[jt.ArrayT, 'B T D'],
974
+ padding: tuple[tuple[int, int], ...],
975
+ ) -> jt.Float[jt.ArrayT, 'B T D']:
976
+ assert len(padding) == 1, padding
977
+ in_features = jnp.shape(x)[-1]
978
+ out_features = in_features * self.config.depth_multiplier
979
+ kernel_shape = (self.config.kernel_size, 1, out_features)
980
+ kernel_init = utils.shard_initializer(
981
+ self.config.kernel_init,
982
+ self.config.kernel_sharding,
983
+ projectable=True,
984
+ axes_types=(meta.AxisType.FANIN, meta.AxisType.FANIN, None),
985
+ )
986
+ kernel = self.param(
987
+ 'kernel', kernel_init, kernel_shape, self.config.param_dtype
988
+ )
989
+ if self.config.use_weight_norm:
990
+ kernel = _weight_norm(self, kernel, 'scale')
991
+ # One bias weight per output channel, shared between pixels.
992
+ if self.config.use_bias:
993
+ bias_init = utils.shard_initializer(
994
+ self.config.bias_init, self.config.bias_sharding
995
+ )
996
+ bias = self.param(
997
+ 'bias',
998
+ bias_init,
999
+ (out_features,),
1000
+ self.config.param_dtype,
1001
+ )
1002
+ else:
1003
+ bias = None
1004
+
1005
+ x, kernel, bias = nn.dtypes.promote_dtype(
1006
+ x, kernel, bias, dtype=self.config.compute_dtype
1007
+ )
1008
+
1009
+ y = jax.lax.conv_general_dilated(
1010
+ x,
1011
+ kernel,
1012
+ window_strides=(self.config.strides,),
1013
+ padding=padding,
1014
+ lhs_dilation=(1,),
1015
+ rhs_dilation=(self.config.dilation_rate,),
1016
+ dimension_numbers=('NHC', 'HIO', 'NHC'),
1017
+ feature_group_count=in_features,
1018
+ precision=self.config.precision,
1019
+ )
1020
+
1021
+ if bias is not None:
1022
+ y = utils.bias_add(y, bias)
1023
+
1024
+ if self.config.activation:
1025
+ y = self.config.activation(y)
1026
+
1027
+ return y
1028
+
1029
+
1030
+ class Conv2D(BaseConv):
1031
+ """A 2D strided or dilated convolution layer."""
1032
+
1033
+ @dataclasses.dataclass(frozen=True)
1034
+ class Config(types.SequenceLayerConfig):
1035
+ """Config for Conv2D."""
1036
+
1037
+ filters: int
1038
+ kernel_size: int | TypingSequence[int]
1039
+ strides: int | TypingSequence[int] = 1
1040
+ dilation_rate: int | TypingSequence[int] = 1
1041
+ # A padding mode string determining how to pad the time dimension of the
1042
+ # convolution. Conv2D is only streamable if time_padding is 'causal_valid'
1043
+ # 'reverse_causal_valid', 'causal', or 'reverse_causal'.
1044
+ time_padding: types.PaddingModeString = types.PaddingMode.VALID.value
1045
+ # A padding mode string or explicit padding values determining how to pad
1046
+ # the spatial dimension of the convolution.
1047
+ spatial_padding: types.PaddingModeString | tuple[int, int] = (
1048
+ types.PaddingMode.SAME.value
1049
+ )
1050
+ groups: int = 1
1051
+ use_bias: bool = True
1052
+ use_weight_norm: bool = False
1053
+ activation: Callable[[jax.Array], jax.Array] | None = None
1054
+ compute_dtype: types.DType | None = None
1055
+ param_dtype: types.DType = jnp.float32
1056
+ precision: nn.linear.PrecisionLike = None
1057
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
1058
+ kernel_sharding: types.Sharding | None = None
1059
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
1060
+ bias_sharding: types.Sharding | None = None
1061
+ name: str | None = None
1062
+
1063
+ def __post_init__(self):
1064
+ object.__setattr__(
1065
+ self, 'time_padding', types.validate_padding(self.time_padding)
1066
+ )
1067
+ if isinstance(self.spatial_padding, str):
1068
+ object.__setattr__(
1069
+ self,
1070
+ 'spatial_padding',
1071
+ types.validate_padding(self.spatial_padding),
1072
+ )
1073
+ else:
1074
+ object.__setattr__(
1075
+ self,
1076
+ 'spatial_padding',
1077
+ types.validate_explicit_padding(self.spatial_padding),
1078
+ )
1079
+ object.__setattr__(
1080
+ self, 'kernel_size', utils.normalize_2tuple(self.kernel_size)
1081
+ )
1082
+ object.__setattr__(self, 'strides', utils.normalize_2tuple(self.strides))
1083
+ object.__setattr__(
1084
+ self, 'dilation_rate', utils.normalize_2tuple(self.dilation_rate)
1085
+ )
1086
+
1087
+ def make(self) -> 'Conv2D':
1088
+ return Conv2D(self, name=self.name)
1089
+
1090
+ config: Config
1091
+
1092
+ @property
1093
+ def _kernel_size(self) -> tuple[int, ...]:
1094
+ # Config normalizes these for us in __post_init__.
1095
+ assert (
1096
+ isinstance(self.config.kernel_size, tuple)
1097
+ and len(self.config.kernel_size) == 2
1098
+ ), self.config.kernel_size
1099
+ return typing.cast(tuple[int, ...], self.config.kernel_size)
1100
+
1101
+ @property
1102
+ def _strides(self) -> tuple[int, ...]:
1103
+ # Config normalizes these for us in __post_init__.
1104
+ assert (
1105
+ isinstance(self.config.strides, tuple) and len(self.config.strides) == 2
1106
+ ), self.config.strides
1107
+ return typing.cast(tuple[int, ...], self.config.strides)
1108
+
1109
+ @property
1110
+ def _dilation_rate(self) -> tuple[int, ...]:
1111
+ # Config normalizes these for us in __post_init__.
1112
+ assert (
1113
+ isinstance(self.config.dilation_rate, tuple)
1114
+ and len(self.config.dilation_rate) == 2
1115
+ ), self.config.dilation_rate
1116
+ return typing.cast(tuple[int, ...], self.config.dilation_rate)
1117
+
1118
+ @property
1119
+ def _paddings(self) -> tuple[types.PaddingModeString | tuple[int, int], ...]:
1120
+ return (self.config.time_padding, self.config.spatial_padding)
1121
+
1122
+ @nn.nowrap
1123
+ def get_output_shape(
1124
+ self,
1125
+ input_shape: types.ShapeLike,
1126
+ *,
1127
+ constants: types.Constants | None = None,
1128
+ ) -> types.Shape:
1129
+ if len(input_shape) != 2:
1130
+ raise ValueError(
1131
+ 'Conv2D requires rank 4 input got:'
1132
+ f' {(None, None) + tuple(input_shape)}'
1133
+ )
1134
+ spatial_output_size = utils.convolution_padding_output_size(
1135
+ input_shape[0],
1136
+ self.config.spatial_padding,
1137
+ kernel_size=self.config.kernel_size[1],
1138
+ stride=self.config.strides[1],
1139
+ dilation_rate=self.config.dilation_rate[1],
1140
+ )
1141
+ return (
1142
+ spatial_output_size,
1143
+ self.config.filters,
1144
+ )
1145
+
1146
+ @nn.nowrap
1147
+ def get_output_dtype(
1148
+ self,
1149
+ input_dtype: types.DType,
1150
+ ) -> types.DType:
1151
+ return utils.get_promoted_dtype(
1152
+ input_dtype, self.config.param_dtype, dtype=self.config.compute_dtype
1153
+ )
1154
+
1155
+ @nn.compact
1156
+ def _layer(
1157
+ self,
1158
+ x: jt.Float[jt.ArrayT, 'B T H D'],
1159
+ padding: tuple[tuple[int, int], tuple[int, int]],
1160
+ ) -> jt.Float[jt.ArrayT, 'B T H D']:
1161
+ assert len(padding) == 2, padding
1162
+ in_features = jnp.shape(x)[-1]
1163
+ if in_features % self.config.groups != 0:
1164
+ raise ValueError(
1165
+ f'Input features ({in_features}) must be divisible by groups'
1166
+ f' ({self.config.groups}).'
1167
+ )
1168
+
1169
+ # Config normalizes these for us in __post_init__.
1170
+ assert (
1171
+ isinstance(self.config.kernel_size, tuple)
1172
+ and len(self.config.kernel_size) == 2
1173
+ )
1174
+ assert (
1175
+ isinstance(self.config.strides, tuple) and len(self.config.strides) == 2
1176
+ )
1177
+ assert (
1178
+ isinstance(self.config.dilation_rate, tuple)
1179
+ and len(self.config.dilation_rate) == 2
1180
+ )
1181
+
1182
+ kernel_shape = self.config.kernel_size + (
1183
+ in_features // self.config.groups,
1184
+ self.config.filters,
1185
+ )
1186
+ kernel_init = utils.shard_initializer(
1187
+ self.config.kernel_init,
1188
+ self.config.kernel_sharding,
1189
+ projectable=True,
1190
+ axes_types=(
1191
+ meta.AxisType.FANIN,
1192
+ meta.AxisType.FANIN,
1193
+ meta.AxisType.FANIN,
1194
+ None,
1195
+ ),
1196
+ )
1197
+ kernel = self.param(
1198
+ 'kernel', kernel_init, kernel_shape, self.config.param_dtype
1199
+ )
1200
+ if self.config.use_weight_norm:
1201
+ kernel = _weight_norm(self, kernel, 'scale')
1202
+ # One bias weight per output channel, shared between pixels.
1203
+ if self.config.use_bias:
1204
+ bias_init = utils.shard_initializer(
1205
+ self.config.bias_init, self.config.bias_sharding
1206
+ )
1207
+ bias = self.param(
1208
+ 'bias',
1209
+ bias_init,
1210
+ (self.config.filters,),
1211
+ self.config.param_dtype,
1212
+ )
1213
+ else:
1214
+ bias = None
1215
+
1216
+ x, kernel, bias = nn.dtypes.promote_dtype(
1217
+ x, kernel, bias, dtype=self.config.compute_dtype
1218
+ )
1219
+
1220
+ y = jax.lax.conv_general_dilated(
1221
+ x,
1222
+ kernel,
1223
+ window_strides=self.config.strides,
1224
+ padding=padding,
1225
+ lhs_dilation=(1, 1),
1226
+ rhs_dilation=self.config.dilation_rate,
1227
+ dimension_numbers=('NHWC', 'HWIO', 'NHWC'),
1228
+ feature_group_count=self.config.groups,
1229
+ precision=self.config.precision,
1230
+ )
1231
+
1232
+ if bias is not None:
1233
+ y = utils.bias_add(y, bias)
1234
+
1235
+ if self.config.activation:
1236
+ y = self.config.activation(y)
1237
+
1238
+ return y
1239
+
1240
+
1241
+ class Conv3D(BaseConv):
1242
+ """A 3D strided or dilated convolution layer."""
1243
+
1244
+ @dataclasses.dataclass(frozen=True)
1245
+ class Config(types.SequenceLayerConfig):
1246
+ """Config for Conv3D."""
1247
+
1248
+ filters: int
1249
+ kernel_size: int | TypingSequence[int]
1250
+ strides: int | TypingSequence[int] = 1
1251
+ dilation_rate: int | TypingSequence[int] = 1
1252
+ # A padding mode string determining how to pad the time dimension of the
1253
+ # convolution. Conv3D is only streamable if time_padding is 'causal_valid'
1254
+ # 'reverse_causal_valid', 'causal', or 'reverse_causal'.
1255
+ time_padding: types.PaddingModeString = types.PaddingMode.VALID.value
1256
+ # A padding mode string or explicit padding values determining how to pad
1257
+ # the spatial dimensions of the convolution.
1258
+ spatial_padding: tuple[
1259
+ types.PaddingModeString | tuple[int, int],
1260
+ types.PaddingModeString | tuple[int, int],
1261
+ ] = (types.PaddingMode.SAME.value, types.PaddingMode.SAME.value)
1262
+ groups: int = 1
1263
+ use_bias: bool = True
1264
+ use_weight_norm: bool = False
1265
+ activation: Callable[[jax.Array], jax.Array] | None = None
1266
+ compute_dtype: types.DType | None = None
1267
+ param_dtype: types.DType = jnp.float32
1268
+ precision: nn.linear.PrecisionLike = None
1269
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
1270
+ kernel_sharding: types.Sharding | None = None
1271
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
1272
+ bias_sharding: types.Sharding | None = None
1273
+ name: str | None = None
1274
+
1275
+ def __post_init__(self):
1276
+ object.__setattr__(
1277
+ self, 'time_padding', types.validate_padding(self.time_padding)
1278
+ )
1279
+ if len(self.spatial_padding) != 2:
1280
+ raise ValueError(
1281
+ 'Conv3D expects 2 spatial padding modes got:'
1282
+ f' {self.spatial_padding}'
1283
+ )
1284
+
1285
+ object.__setattr__(
1286
+ self,
1287
+ 'spatial_padding',
1288
+ tuple(
1289
+ types.validate_padding(s) if isinstance(s, str) else s
1290
+ for s in self.spatial_padding
1291
+ ),
1292
+ )
1293
+ object.__setattr__(
1294
+ self, 'kernel_size', utils.normalize_3tuple(self.kernel_size)
1295
+ )
1296
+ object.__setattr__(self, 'strides', utils.normalize_3tuple(self.strides))
1297
+ object.__setattr__(
1298
+ self, 'dilation_rate', utils.normalize_3tuple(self.dilation_rate)
1299
+ )
1300
+
1301
+ def make(self) -> 'Conv3D':
1302
+ return Conv3D(self, name=self.name)
1303
+
1304
+ config: Config
1305
+
1306
+ @property
1307
+ def _kernel_size(self) -> tuple[int, ...]:
1308
+ # Config normalizes these for us in __post_init__.
1309
+ assert (
1310
+ isinstance(self.config.kernel_size, tuple)
1311
+ and len(self.config.kernel_size) == 3
1312
+ ), self.config.kernel_size
1313
+ return typing.cast(tuple[int, ...], self.config.kernel_size)
1314
+
1315
+ @property
1316
+ def _strides(self) -> tuple[int, ...]:
1317
+ # Config normalizes these for us in __post_init__.
1318
+ assert (
1319
+ isinstance(self.config.strides, tuple) and len(self.config.strides) == 3
1320
+ ), self.config.strides
1321
+ return typing.cast(tuple[int, ...], self.config.strides)
1322
+
1323
+ @property
1324
+ def _dilation_rate(self) -> tuple[int, ...]:
1325
+ # Config normalizes these for us in __post_init__.
1326
+ assert (
1327
+ isinstance(self.config.dilation_rate, tuple)
1328
+ and len(self.config.dilation_rate) == 3
1329
+ ), self.config.dilation_rate
1330
+ return typing.cast(tuple[int, ...], self.config.dilation_rate)
1331
+
1332
+ @property
1333
+ def _paddings(self) -> tuple[types.PaddingModeString | tuple[int, int], ...]:
1334
+ return (self.config.time_padding,) + self.config.spatial_padding
1335
+
1336
+ @nn.nowrap
1337
+ def get_output_shape(
1338
+ self,
1339
+ input_shape: types.ShapeLike,
1340
+ *,
1341
+ constants: types.Constants | None = None,
1342
+ ) -> types.Shape:
1343
+ if len(input_shape) != 3:
1344
+ raise ValueError(
1345
+ 'Conv3D requires rank 5 input got:'
1346
+ f' {(None, None) + tuple(input_shape)}'
1347
+ )
1348
+ spatial_output_sizes = [
1349
+ utils.convolution_padding_output_size(
1350
+ input_shape[i],
1351
+ self.config.spatial_padding[i],
1352
+ kernel_size=self.config.kernel_size[1 + i],
1353
+ stride=self.config.strides[1 + i],
1354
+ dilation_rate=self.config.dilation_rate[1 + i],
1355
+ )
1356
+ for i in range(2)
1357
+ ]
1358
+
1359
+ return tuple(spatial_output_sizes) + (self.config.filters,)
1360
+
1361
+ @nn.nowrap
1362
+ def get_output_dtype(
1363
+ self,
1364
+ input_dtype: types.DType,
1365
+ ) -> types.DType:
1366
+ return utils.get_promoted_dtype(
1367
+ input_dtype, self.config.param_dtype, dtype=self.config.compute_dtype
1368
+ )
1369
+
1370
+ @nn.compact
1371
+ def _layer(
1372
+ self,
1373
+ x: jt.Float[jt.ArrayT, 'B T H W D'],
1374
+ padding: tuple[tuple[int, int], tuple[int, int], tuple[int, int]],
1375
+ ) -> jt.Float[jt.ArrayT, 'B T H W D']:
1376
+ assert len(padding) == 3, padding
1377
+ in_features = jnp.shape(x)[-1]
1378
+ if in_features % self.config.groups != 0:
1379
+ raise ValueError(
1380
+ f'Input features ({in_features}) must be divisible by groups'
1381
+ f' ({self.config.groups}).'
1382
+ )
1383
+
1384
+ # Config normalizes these for us in __post_init__.
1385
+ assert (
1386
+ isinstance(self.config.kernel_size, tuple)
1387
+ and len(self.config.kernel_size) == 3
1388
+ )
1389
+ assert (
1390
+ isinstance(self.config.strides, tuple) and len(self.config.strides) == 3
1391
+ )
1392
+ assert (
1393
+ isinstance(self.config.dilation_rate, tuple)
1394
+ and len(self.config.dilation_rate) == 3
1395
+ )
1396
+
1397
+ kernel_shape = self.config.kernel_size + (
1398
+ in_features // self.config.groups,
1399
+ self.config.filters,
1400
+ )
1401
+ kernel_init = utils.shard_initializer(
1402
+ self.config.kernel_init,
1403
+ self.config.kernel_sharding,
1404
+ projectable=True,
1405
+ axes_types=(
1406
+ meta.AxisType.FANIN,
1407
+ meta.AxisType.FANIN,
1408
+ meta.AxisType.FANIN,
1409
+ meta.AxisType.FANIN,
1410
+ None,
1411
+ ),
1412
+ )
1413
+ kernel = self.param(
1414
+ 'kernel', kernel_init, kernel_shape, self.config.param_dtype
1415
+ )
1416
+ if self.config.use_weight_norm:
1417
+ kernel = _weight_norm(self, kernel, 'scale')
1418
+ # One bias weight per output channel, shared between channels.
1419
+ if self.config.use_bias:
1420
+ bias_init = utils.shard_initializer(
1421
+ self.config.bias_init, self.config.bias_sharding
1422
+ )
1423
+ bias = self.param(
1424
+ 'bias',
1425
+ bias_init,
1426
+ (self.config.filters,),
1427
+ self.config.param_dtype,
1428
+ )
1429
+ else:
1430
+ bias = None
1431
+
1432
+ x, kernel, bias = nn.dtypes.promote_dtype(
1433
+ x, kernel, bias, dtype=self.config.compute_dtype
1434
+ )
1435
+
1436
+ y = jax.lax.conv_general_dilated(
1437
+ x,
1438
+ kernel,
1439
+ window_strides=self.config.strides,
1440
+ padding=padding,
1441
+ lhs_dilation=(1, 1, 1),
1442
+ rhs_dilation=self.config.dilation_rate,
1443
+ dimension_numbers=('NTHWC', 'THWIO', 'NTHWC'),
1444
+ feature_group_count=self.config.groups,
1445
+ precision=self.config.precision,
1446
+ )
1447
+
1448
+ if bias is not None:
1449
+ y = utils.bias_add(y, bias)
1450
+
1451
+ if self.config.activation:
1452
+ y = self.config.activation(y)
1453
+
1454
+ return y
1455
+
1456
+
1457
+ class Conv1DTranspose(types.SequenceLayer):
1458
+ """A 1D transpose convolution layer."""
1459
+
1460
+ @dataclasses.dataclass(frozen=True)
1461
+ class Config(types.SequenceLayerConfig):
1462
+ """Config for Conv1DTranspose."""
1463
+
1464
+ filters: int
1465
+ kernel_size: int
1466
+ strides: int = 1
1467
+ dilation_rate: int = 1
1468
+ # The padding mode for the time dimension. Only 'valid', 'causal', or 'same'
1469
+ # is supported. Only streamable when using 'causal'.
1470
+ padding: types.PaddingModeString = types.PaddingMode.VALID.value
1471
+ groups: int = 1
1472
+ use_bias: bool = True
1473
+ use_weight_norm: bool = False
1474
+ activation: Callable[[jax.Array], jax.Array] | None = None
1475
+ compute_dtype: types.DType | None = None
1476
+ param_dtype: types.DType = jnp.float32
1477
+ precision: str | None = None
1478
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
1479
+ kernel_sharding: types.Sharding | None = None
1480
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
1481
+ bias_sharding: types.Sharding | None = None
1482
+ name: str | None = None
1483
+
1484
+ def __post_init__(self):
1485
+ object.__setattr__(self, 'padding', types.validate_padding(self.padding))
1486
+
1487
+ if self.padding in (
1488
+ types.PaddingMode.REVERSE_CAUSAL.value,
1489
+ types.PaddingMode.REVERSE_CAUSAL_VALID.value,
1490
+ types.PaddingMode.CAUSAL_VALID.value,
1491
+ ):
1492
+ raise ValueError(f'Unsupported padding mode: {self.padding}')
1493
+
1494
+ def make(self) -> 'Conv1DTranspose':
1495
+ return Conv1DTranspose(self, name=self.name)
1496
+
1497
+ config: Config
1498
+
1499
+ @property
1500
+ def supports_step(self) -> bool:
1501
+ return self.config.padding == types.PaddingMode.CAUSAL.value
1502
+
1503
+ @property
1504
+ def output_ratio(self) -> fractions.Fraction:
1505
+ return fractions.Fraction(self.config.strides, 1)
1506
+
1507
+ @property
1508
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
1509
+ return transpose_conv_receptive_field_per_step(
1510
+ self.config.kernel_size,
1511
+ self.config.strides,
1512
+ self.config.dilation_rate,
1513
+ self.config.padding,
1514
+ )
1515
+
1516
+ @nn.nowrap
1517
+ def get_output_shape(
1518
+ self,
1519
+ input_shape: types.ShapeLike,
1520
+ *,
1521
+ constants: types.Constants | None = None,
1522
+ ) -> types.Shape:
1523
+ return (self.config.filters,)
1524
+
1525
+ @nn.nowrap
1526
+ def get_output_dtype(
1527
+ self,
1528
+ input_dtype: types.DType,
1529
+ ) -> types.DType:
1530
+ return utils.get_promoted_dtype(
1531
+ input_dtype, self.config.param_dtype, dtype=self.config.compute_dtype
1532
+ )
1533
+
1534
+ @property
1535
+ def _buffer_width(self) -> int:
1536
+ effective_kernel_size = utils.convolution_effective_kernel_size(
1537
+ self.config.kernel_size, self.config.dilation_rate
1538
+ )
1539
+ return max(0, effective_kernel_size - self.config.strides)
1540
+
1541
+ def get_initial_state(
1542
+ self,
1543
+ batch_size: int,
1544
+ input_spec: types.ChannelSpec,
1545
+ *,
1546
+ training: bool,
1547
+ constants: types.Constants | None = None,
1548
+ ) -> types.State:
1549
+ if buffer_width := self._buffer_width:
1550
+ output_spec = self.get_output_spec(input_spec, constants=constants)
1551
+ return jnp.zeros(
1552
+ (batch_size, buffer_width) + output_spec.shape,
1553
+ dtype=output_spec.dtype,
1554
+ )
1555
+ else:
1556
+ return ()
1557
+
1558
+ @nn.compact
1559
+ def _layer(
1560
+ self,
1561
+ x: jax.Array,
1562
+ explicit_padding: tuple[int, int],
1563
+ ) -> tuple[jax.Array, jax.Array | None]:
1564
+ if x.ndim != 3:
1565
+ raise ValueError(f'Expected 3 dimension input. Got: {x.shape}')
1566
+ input_channels = x.shape[2]
1567
+
1568
+ if input_channels % self.config.groups != 0:
1569
+ raise ValueError(
1570
+ f'Input features ({input_channels}) must be divisible by groups'
1571
+ f' ({self.config.groups}).'
1572
+ )
1573
+
1574
+ kernel_init = utils.shard_initializer(
1575
+ self.config.kernel_init,
1576
+ self.config.kernel_sharding,
1577
+ projectable=True,
1578
+ axes_types=(meta.AxisType.FANIN, meta.AxisType.FANIN, None),
1579
+ )
1580
+
1581
+ kernel_shape = (
1582
+ self.config.kernel_size,
1583
+ input_channels // self.config.groups,
1584
+ self.config.filters,
1585
+ )
1586
+ kernel = self.param(
1587
+ 'kernel', kernel_init, kernel_shape, self.config.param_dtype
1588
+ )
1589
+ if self.config.use_weight_norm:
1590
+ kernel = _weight_norm(self, kernel, 'scale')
1591
+
1592
+ if self.config.use_bias:
1593
+ bias_init = utils.shard_initializer(
1594
+ self.config.bias_init, self.config.bias_sharding
1595
+ )
1596
+ bias = self.param(
1597
+ 'bias',
1598
+ bias_init,
1599
+ (self.config.filters,),
1600
+ self.config.param_dtype,
1601
+ )
1602
+ else:
1603
+ bias = None
1604
+
1605
+ x, kernel, bias = nn.dtypes.promote_dtype(
1606
+ x, kernel, bias, dtype=self.config.compute_dtype
1607
+ )
1608
+
1609
+ y = jax.lax.conv_general_dilated(
1610
+ x,
1611
+ kernel,
1612
+ window_strides=(1,),
1613
+ padding=(explicit_padding,),
1614
+ lhs_dilation=(self.config.strides,),
1615
+ rhs_dilation=(self.config.dilation_rate,),
1616
+ dimension_numbers=('NHC', 'HIO', 'NHC'),
1617
+ feature_group_count=self.config.groups,
1618
+ batch_group_count=1,
1619
+ precision=self.config.precision,
1620
+ )
1621
+
1622
+ # We apply bias and activation after overlap-adding with the state buffer.
1623
+ return y, bias
1624
+
1625
+ @nn.nowrap
1626
+ @types.check_layer
1627
+ def layer(
1628
+ self,
1629
+ x: types.Sequence,
1630
+ *,
1631
+ training: bool,
1632
+ constants: types.Constants | None = None,
1633
+ ) -> types.Sequence:
1634
+ # Mask inputs if receptive field is greater than 1.
1635
+ if self.config.kernel_size > 1:
1636
+ x = x.mask_invalid()
1637
+
1638
+ # Trim the last effective_kernel_size - stride samples since we don't
1639
+ # produce these in step mode (we can only produce stride samples at a time
1640
+ # in step mode, so we can't produce the final effective_kernel_size - stride
1641
+ # samples).
1642
+
1643
+ explicit_padding = transpose_conv_explicit_padding(
1644
+ self.config.kernel_size,
1645
+ self.config.strides,
1646
+ self.config.dilation_rate,
1647
+ self.config.padding,
1648
+ )
1649
+
1650
+ values, bias = self._layer(x.values, explicit_padding)
1651
+ mask = compute_conv_transpose_mask(
1652
+ x.mask,
1653
+ self.config.kernel_size,
1654
+ self.config.strides,
1655
+ self.config.dilation_rate,
1656
+ self.config.padding,
1657
+ )
1658
+
1659
+ if bias is not None:
1660
+ values = utils.bias_add(values, bias)
1661
+
1662
+ if self.config.activation:
1663
+ values = self.config.activation(values)
1664
+
1665
+ # Transpose convolution leaves padding with nonzero values.
1666
+ y = types.Sequence(values, mask)
1667
+
1668
+ return y
1669
+
1670
+ @types.check_step
1671
+ @nn.nowrap
1672
+ def step(
1673
+ self,
1674
+ x: types.Sequence,
1675
+ state: types.State,
1676
+ *,
1677
+ training: bool,
1678
+ constants: types.Constants | None = None,
1679
+ ) -> tuple[types.Sequence, types.State]:
1680
+ # Mask inputs if receptive field is greater than 1.
1681
+ if self.config.kernel_size > 1:
1682
+ x = x.mask_invalid()
1683
+
1684
+ # Compute valid padding for step.
1685
+ explicit_padding = transpose_conv_explicit_padding(
1686
+ self.config.kernel_size,
1687
+ self.config.strides,
1688
+ self.config.dilation_rate,
1689
+ types.PaddingMode.VALID.value,
1690
+ )
1691
+
1692
+ values, bias = self._layer(x.values, explicit_padding)
1693
+ mask = compute_conv_transpose_mask(
1694
+ x.mask,
1695
+ self.config.kernel_size,
1696
+ self.config.strides,
1697
+ self.config.dilation_rate,
1698
+ self.config.padding,
1699
+ )
1700
+
1701
+ if self._buffer_width:
1702
+ time = x.shape[1]
1703
+
1704
+ # Pad the state to extend it to the length of the layer output.
1705
+ # output_time is at least kernel_size and buffer_width is at most
1706
+ # kernel_size - 1, so output_time - buffer_width is positive.
1707
+ state = jnp.pad(
1708
+ state, [[0, 0], [0, values.shape[1] - self._buffer_width], [0, 0]]
1709
+ )
1710
+
1711
+ # Overlap-add outputs from previous timesteps into values.
1712
+ values = values + state
1713
+
1714
+ # Stride samples are "ready" for output after one timestep, so the number
1715
+ # of output samples for the block is stride * time.
1716
+ output_samples = self.config.strides * time
1717
+
1718
+ # We need to store (effective_kernel_size - stride) samples for future
1719
+ # steps, since their value depends on future inputs.
1720
+ values, state = jnp.split(values, [output_samples], axis=1)
1721
+
1722
+ if bias is not None:
1723
+ values = utils.bias_add(values, bias)
1724
+
1725
+ if self.config.activation:
1726
+ values = self.config.activation(values)
1727
+
1728
+ # Transpose convolution leaves padding with nonzero values.
1729
+ return types.Sequence(values, mask), state
1730
+
1731
+
1732
+ class Conv2DTranspose(types.SequenceLayer):
1733
+ """A 2D transpose convolution layer."""
1734
+
1735
+ @dataclasses.dataclass(frozen=True)
1736
+ class Config(types.SequenceLayerConfig):
1737
+ """Configuration for Conv2DTranspose."""
1738
+
1739
+ filters: int
1740
+ kernel_size: int | TypingSequence[int]
1741
+ strides: int | TypingSequence[int] = 1
1742
+ dilation_rate: int | TypingSequence[int] = 1
1743
+ # The padding mode for the time dimension. Only 'valid', 'causal', or 'same'
1744
+ # is supported. Only streamable when using 'causal'.
1745
+ time_padding: types.PaddingModeString = types.PaddingMode.VALID.value
1746
+ # The padding mode for the spatial dimension. Only 'valid', 'causal',
1747
+ # 'same', or explicit padding is supported.
1748
+ spatial_padding: types.PaddingModeString | tuple[int, int] = (
1749
+ types.PaddingMode.SAME.value
1750
+ )
1751
+ groups: int = 1
1752
+ use_bias: bool = True
1753
+ use_weight_norm: bool = False
1754
+ activation: Callable[[jax.Array], jax.Array] | None = None
1755
+ compute_dtype: types.DType | None = None
1756
+ param_dtype: types.DType = jnp.float32
1757
+ precision: str | None = None
1758
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
1759
+ kernel_sharding: types.Sharding | None = None
1760
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
1761
+ bias_sharding: types.Sharding | None = None
1762
+ name: str | None = None
1763
+
1764
+ def __post_init__(self):
1765
+ object.__setattr__(
1766
+ self, 'time_padding', types.validate_padding(self.time_padding)
1767
+ )
1768
+
1769
+ if self.time_padding in (
1770
+ types.PaddingMode.REVERSE_CAUSAL.value,
1771
+ types.PaddingMode.REVERSE_CAUSAL_VALID.value,
1772
+ types.PaddingMode.CAUSAL_VALID.value,
1773
+ ):
1774
+ raise ValueError(f'Unsupported padding mode: {self.time_padding}')
1775
+ if isinstance(self.spatial_padding, str):
1776
+ object.__setattr__(
1777
+ self,
1778
+ 'spatial_padding',
1779
+ types.validate_padding(self.spatial_padding),
1780
+ )
1781
+ if self.spatial_padding in (
1782
+ types.PaddingMode.REVERSE_CAUSAL.value,
1783
+ types.PaddingMode.REVERSE_CAUSAL_VALID.value,
1784
+ types.PaddingMode.CAUSAL_VALID.value,
1785
+ ):
1786
+ raise ValueError(f'Unsupported padding mode: {self.spatial_padding}')
1787
+ else:
1788
+ object.__setattr__(
1789
+ self,
1790
+ 'spatial_padding',
1791
+ types.validate_explicit_padding(self.spatial_padding),
1792
+ )
1793
+ object.__setattr__(
1794
+ self, 'kernel_size', utils.normalize_2tuple(self.kernel_size)
1795
+ )
1796
+ object.__setattr__(self, 'strides', utils.normalize_2tuple(self.strides))
1797
+ object.__setattr__(
1798
+ self, 'dilation_rate', utils.normalize_2tuple(self.dilation_rate)
1799
+ )
1800
+
1801
+ def make(self) -> 'Conv2DTranspose':
1802
+ return Conv2DTranspose(self, name=self.name)
1803
+
1804
+ config: Config
1805
+
1806
+ @property
1807
+ def _kernel_size(self) -> tuple[int, ...]:
1808
+ # Config normalizes these for us in __post_init__.
1809
+ assert (
1810
+ isinstance(self.config.kernel_size, tuple)
1811
+ and len(self.config.kernel_size) == 2
1812
+ ), self.config.kernel_size
1813
+ return typing.cast(tuple[int, ...], self.config.kernel_size)
1814
+
1815
+ @property
1816
+ def _strides(self) -> tuple[int, ...]:
1817
+ # Config normalizes these for us in __post_init__.
1818
+ assert (
1819
+ isinstance(self.config.strides, tuple) and len(self.config.strides) == 2
1820
+ ), self.config.strides
1821
+ return typing.cast(tuple[int, ...], self.config.strides)
1822
+
1823
+ @property
1824
+ def _dilation_rate(self) -> tuple[int, ...]:
1825
+ # Config normalizes these for us in __post_init__.
1826
+ assert (
1827
+ isinstance(self.config.dilation_rate, tuple)
1828
+ and len(self.config.dilation_rate) == 2
1829
+ ), self.config.dilation_rate
1830
+ return typing.cast(tuple[int, ...], self.config.dilation_rate)
1831
+
1832
+ @property
1833
+ def _paddings(self) -> tuple[types.PaddingModeString | tuple[int, int], ...]:
1834
+ return (self.config.time_padding, self.config.spatial_padding)
1835
+
1836
+ @property
1837
+ def supports_step(self) -> bool:
1838
+ return self.config.time_padding == types.PaddingMode.CAUSAL.value
1839
+
1840
+ @property
1841
+ def output_ratio(self) -> fractions.Fraction:
1842
+ return fractions.Fraction(self.config.strides[0], 1)
1843
+
1844
+ @property
1845
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
1846
+ return transpose_conv_receptive_field_per_step(
1847
+ self._kernel_size[0],
1848
+ self._strides[0],
1849
+ self._dilation_rate[0],
1850
+ self._paddings[0],
1851
+ )
1852
+
1853
+ @nn.nowrap
1854
+ def get_output_shape(
1855
+ self,
1856
+ input_shape: types.ShapeLike,
1857
+ *,
1858
+ constants: types.Constants | None = None,
1859
+ ) -> types.Shape:
1860
+ if len(input_shape) != 2:
1861
+ raise ValueError(
1862
+ 'Conv2DTranspose requires rank 4 input got:'
1863
+ f' {(None, None) + tuple(input_shape)}'
1864
+ )
1865
+ spatial_output_size = _compute_conv_transpose_output_length(
1866
+ input_shape[0],
1867
+ self.config.kernel_size[1],
1868
+ self.config.strides[1],
1869
+ dilation_rate=self.config.dilation_rate[1],
1870
+ padding=self.config.spatial_padding,
1871
+ )
1872
+ return (
1873
+ spatial_output_size,
1874
+ self.config.filters,
1875
+ )
1876
+
1877
+ @nn.nowrap
1878
+ def get_output_dtype(
1879
+ self,
1880
+ input_dtype: types.DType,
1881
+ ) -> types.DType:
1882
+ return utils.get_promoted_dtype(
1883
+ input_dtype, self.config.param_dtype, dtype=self.config.compute_dtype
1884
+ )
1885
+
1886
+ @property
1887
+ def _buffer_width(self) -> int:
1888
+ effective_kernel_size = utils.convolution_effective_kernel_size(
1889
+ self.config.kernel_size[0], self.config.dilation_rate[0]
1890
+ )
1891
+ return max(0, effective_kernel_size - self.config.strides[0])
1892
+
1893
+ def get_initial_state(
1894
+ self,
1895
+ batch_size: int,
1896
+ input_spec: types.ChannelSpec,
1897
+ *,
1898
+ training: bool,
1899
+ constants: types.Constants | None = None,
1900
+ ) -> types.State:
1901
+ output_spec = self.get_output_spec(input_spec, constants=constants)
1902
+ if buffer_width := self._buffer_width:
1903
+ return jnp.zeros(
1904
+ (batch_size, buffer_width) + output_spec.shape,
1905
+ dtype=output_spec.dtype,
1906
+ )
1907
+ else:
1908
+ return ()
1909
+
1910
+ @nn.compact
1911
+ def _layer(
1912
+ self,
1913
+ x: jax.Array,
1914
+ explicit_padding: tuple[tuple[int, int], tuple[int, int]],
1915
+ ) -> tuple[jax.Array, jax.Array | None]:
1916
+ if x.ndim != 4:
1917
+ raise ValueError(f'Expected 4 dimension input. Got: {x.shape}')
1918
+ input_channels = x.shape[3]
1919
+
1920
+ if input_channels % self.config.groups != 0:
1921
+ raise ValueError(
1922
+ f'Input features ({input_channels}) must be divisible by groups'
1923
+ f' ({self.config.groups}).'
1924
+ )
1925
+
1926
+ kernel_init = utils.shard_initializer(
1927
+ self.config.kernel_init,
1928
+ self.config.kernel_sharding,
1929
+ projectable=True,
1930
+ axes_types=(
1931
+ meta.AxisType.FANIN,
1932
+ meta.AxisType.FANIN,
1933
+ meta.AxisType.FANIN,
1934
+ None,
1935
+ ),
1936
+ )
1937
+
1938
+ kernel_shape = tuple(self.config.kernel_size) + (
1939
+ input_channels // self.config.groups,
1940
+ self.config.filters,
1941
+ )
1942
+ kernel = self.param(
1943
+ 'kernel', kernel_init, kernel_shape, self.config.param_dtype
1944
+ )
1945
+ if self.config.use_weight_norm:
1946
+ kernel = _weight_norm(self, kernel, 'scale')
1947
+
1948
+ if self.config.use_bias:
1949
+ bias_init = utils.shard_initializer(
1950
+ self.config.bias_init, self.config.bias_sharding
1951
+ )
1952
+ bias = self.param(
1953
+ 'bias',
1954
+ bias_init,
1955
+ (self.config.filters,),
1956
+ self.config.param_dtype,
1957
+ )
1958
+ else:
1959
+ bias = None
1960
+
1961
+ x, kernel, bias = nn.dtypes.promote_dtype(
1962
+ x, kernel, bias, dtype=self.config.compute_dtype
1963
+ )
1964
+
1965
+ y = jax.lax.conv_general_dilated(
1966
+ x,
1967
+ kernel,
1968
+ window_strides=(1, 1),
1969
+ padding=explicit_padding,
1970
+ lhs_dilation=self.config.strides,
1971
+ rhs_dilation=self.config.dilation_rate,
1972
+ dimension_numbers=('NHWC', 'HWIO', 'NHWC'),
1973
+ feature_group_count=self.config.groups,
1974
+ batch_group_count=1,
1975
+ precision=self.config.precision,
1976
+ )
1977
+
1978
+ # We apply bias and activation after overlap-adding with the state buffer.
1979
+ return y, bias
1980
+
1981
+ @nn.nowrap
1982
+ @types.check_layer
1983
+ def layer(
1984
+ self,
1985
+ x: types.Sequence,
1986
+ *,
1987
+ training: bool,
1988
+ constants: types.Constants | None = None,
1989
+ ) -> types.Sequence:
1990
+ # Mask inputs if time receptive field is greater than 1.
1991
+ if self.config.kernel_size[0] > 1:
1992
+ x = x.mask_invalid()
1993
+
1994
+ explicit_time_padding = transpose_conv_explicit_padding(
1995
+ self.config.kernel_size[0],
1996
+ self.config.strides[0],
1997
+ self.config.dilation_rate[0],
1998
+ self.config.time_padding,
1999
+ )
2000
+
2001
+ explicit_spatial_padding = transpose_conv_explicit_padding(
2002
+ self.config.kernel_size[1],
2003
+ self.config.strides[1],
2004
+ self.config.dilation_rate[1],
2005
+ self.config.spatial_padding,
2006
+ )
2007
+
2008
+ # Trim the last effective_kernel_size - stride samples since we don't
2009
+ # produce these in step mode (we can only produce stride samples at a time
2010
+ # in step mode, so we can't produce the final effective_kernel_size - stride
2011
+ # samples).
2012
+ values, bias = self._layer(
2013
+ x.values, (explicit_time_padding, explicit_spatial_padding)
2014
+ )
2015
+ mask = compute_conv_transpose_mask(
2016
+ x.mask,
2017
+ self.config.kernel_size[0],
2018
+ self.config.strides[0],
2019
+ self.config.dilation_rate[0],
2020
+ self.config.time_padding,
2021
+ )
2022
+
2023
+ if bias is not None:
2024
+ values = utils.bias_add(values, bias)
2025
+
2026
+ if self.config.activation:
2027
+ values = self.config.activation(values)
2028
+
2029
+ # Transpose convolution leaves padding with nonzero values.
2030
+ y = types.Sequence(values, mask)
2031
+
2032
+ return y
2033
+
2034
+ @types.check_step
2035
+ @nn.nowrap
2036
+ def step(
2037
+ self,
2038
+ x: types.Sequence,
2039
+ state: types.State,
2040
+ *,
2041
+ training: bool,
2042
+ constants: types.Constants | None = None,
2043
+ ) -> tuple[types.Sequence, types.State]:
2044
+ # Mask inputs if time receptive field is greater than 1.
2045
+ if self.config.kernel_size[0] > 1:
2046
+ x = x.mask_invalid()
2047
+
2048
+ # Compute valid padding for step.
2049
+ explicit_time_padding = transpose_conv_explicit_padding(
2050
+ self.config.kernel_size[0],
2051
+ self.config.strides[0],
2052
+ self.config.dilation_rate[0],
2053
+ types.PaddingMode.VALID.value,
2054
+ )
2055
+
2056
+ explicit_spatial_padding = transpose_conv_explicit_padding(
2057
+ self.config.kernel_size[1],
2058
+ self.config.strides[1],
2059
+ self.config.dilation_rate[1],
2060
+ self.config.spatial_padding,
2061
+ )
2062
+
2063
+ values, bias = self._layer(
2064
+ x.values, (explicit_time_padding, explicit_spatial_padding)
2065
+ )
2066
+ mask = compute_conv_transpose_mask(
2067
+ x.mask,
2068
+ self.config.kernel_size[0],
2069
+ self.config.strides[0],
2070
+ self.config.dilation_rate[0],
2071
+ self.config.time_padding,
2072
+ )
2073
+
2074
+ if self._buffer_width:
2075
+ time = x.shape[1]
2076
+
2077
+ # Pad the state to extend it to the length of the layer output.
2078
+ # output_time is at least kernel_size and buffer_width is at most
2079
+ # kernel_size - 1, so output_time - buffer_width is positive.
2080
+ state = jnp.pad(
2081
+ state,
2082
+ [[0, 0], [0, values.shape[1] - self._buffer_width], [0, 0], [0, 0]],
2083
+ )
2084
+
2085
+ # Overlap-add outputs from previous timesteps into values.
2086
+ values = values + state
2087
+
2088
+ # Stride samples are "ready" for output after one timestep, so the number
2089
+ # of output samples for the block is stride * time.
2090
+ output_samples = self.config.strides[0] * time
2091
+
2092
+ # We need to store (effective_kernel_size - stride) samples for future
2093
+ # steps, since their value depends on future inputs.
2094
+ values, state = jnp.split(values, [output_samples], axis=1)
2095
+
2096
+ if bias is not None:
2097
+ values = utils.bias_add(values, bias)
2098
+
2099
+ if self.config.activation:
2100
+ values = self.config.activation(values)
2101
+
2102
+ # Transpose convolution leaves padding with nonzero values.
2103
+ return types.Sequence(values, mask), state