sequence-layers 0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sequence_layers/__init__.py +16 -0
- sequence_layers/internal/types.py +521 -0
- sequence_layers/jax/__init__.py +29 -0
- sequence_layers/jax/attention.py +6124 -0
- sequence_layers/jax/combinators.py +1907 -0
- sequence_layers/jax/conditioning.py +511 -0
- sequence_layers/jax/convolution.py +2103 -0
- sequence_layers/jax/dense.py +447 -0
- sequence_layers/jax/dsp.py +1686 -0
- sequence_layers/jax/examples/gemma3n_audio_encoder.py +358 -0
- sequence_layers/jax/export.py +313 -0
- sequence_layers/jax/meta.py +54 -0
- sequence_layers/jax/normalization.py +889 -0
- sequence_layers/jax/pooling.py +925 -0
- sequence_layers/jax/position.py +370 -0
- sequence_layers/jax/recurrent.py +674 -0
- sequence_layers/jax/sharding.py +48 -0
- sequence_layers/jax/signal.py +511 -0
- sequence_layers/jax/simple.py +2679 -0
- sequence_layers/jax/test_utils.py +1343 -0
- sequence_layers/jax/time_varying.py +673 -0
- sequence_layers/jax/types.py +1537 -0
- sequence_layers/jax/typing.py +59 -0
- sequence_layers/jax/utils.py +2149 -0
- sequence_layers/tensorflow/__init__.py +56 -0
- sequence_layers/tensorflow/attention.py +3426 -0
- sequence_layers/tensorflow/combinators.py +938 -0
- sequence_layers/tensorflow/conditioning.py +644 -0
- sequence_layers/tensorflow/convolution.py +1855 -0
- sequence_layers/tensorflow/dense.py +285 -0
- sequence_layers/tensorflow/dsp.py +740 -0
- sequence_layers/tensorflow/examples/bert.py +144 -0
- sequence_layers/tensorflow/examples/conformer.py +138 -0
- sequence_layers/tensorflow/examples/deep_voice.py +72 -0
- sequence_layers/tensorflow/examples/listen_attend_spell.py +102 -0
- sequence_layers/tensorflow/examples/mobilenet.py +92 -0
- sequence_layers/tensorflow/examples/t5.py +225 -0
- sequence_layers/tensorflow/examples/tacotron.py +124 -0
- sequence_layers/tensorflow/examples/transformer.py +159 -0
- sequence_layers/tensorflow/examples/very_attentive_tacotron.py +1771 -0
- sequence_layers/tensorflow/examples/wavernn.py +225 -0
- sequence_layers/tensorflow/normalization.py +1127 -0
- sequence_layers/tensorflow/pooling.py +462 -0
- sequence_layers/tensorflow/position.py +509 -0
- sequence_layers/tensorflow/recurrent.py +645 -0
- sequence_layers/tensorflow/simple.py +1207 -0
- sequence_layers/tensorflow/squeeze.py +178 -0
- sequence_layers/tensorflow/test_util.py +834 -0
- sequence_layers/tensorflow/time_varying.py +439 -0
- sequence_layers/tensorflow/types.py +961 -0
- sequence_layers/tensorflow/utils.py +858 -0
- sequence_layers-0.1.dist-info/METADATA +69 -0
- sequence_layers-0.1.dist-info/RECORD +55 -0
- sequence_layers-0.1.dist-info/WHEEL +4 -0
- sequence_layers-0.1.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,925 @@
|
|
|
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
|
+
"""Pooling layers."""
|
|
15
|
+
|
|
16
|
+
import dataclasses
|
|
17
|
+
import fractions
|
|
18
|
+
from typing import Any, Sequence as TypingSequence
|
|
19
|
+
|
|
20
|
+
import flax.linen as nn
|
|
21
|
+
import jax
|
|
22
|
+
import jax.numpy as jnp
|
|
23
|
+
import numpy as np
|
|
24
|
+
from sequence_layers.jax import convolution
|
|
25
|
+
from sequence_layers.jax import types
|
|
26
|
+
from sequence_layers.jax import typing as jt
|
|
27
|
+
from sequence_layers.jax import utils
|
|
28
|
+
|
|
29
|
+
__all__ = (
|
|
30
|
+
# go/keep-sorted start
|
|
31
|
+
'AveragePooling1D',
|
|
32
|
+
'AveragePooling2D',
|
|
33
|
+
'MaxPooling1D',
|
|
34
|
+
'MaxPooling2D',
|
|
35
|
+
'MinPooling1D',
|
|
36
|
+
'MinPooling2D',
|
|
37
|
+
# go/keep-sorted end
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _max_pool_init_value(dtype: types.DType) -> complex:
|
|
42
|
+
"""Returns a dtype-appropriate initial value for max reduction."""
|
|
43
|
+
if issubclass(dtype.type, jnp.floating):
|
|
44
|
+
return -jnp.inf
|
|
45
|
+
elif issubclass(dtype.type, jnp.integer):
|
|
46
|
+
return jnp.iinfo(dtype).min
|
|
47
|
+
elif dtype == jnp.bool_:
|
|
48
|
+
return False
|
|
49
|
+
else:
|
|
50
|
+
raise ValueError(f'Unsupported dtype: {dtype}')
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _min_pool_init_value(dtype: types.DType) -> complex:
|
|
54
|
+
"""Returns a dtype-appropriate initial value for min reduction."""
|
|
55
|
+
if issubclass(dtype.type, jnp.floating):
|
|
56
|
+
return jnp.inf
|
|
57
|
+
elif issubclass(dtype.type, jnp.integer):
|
|
58
|
+
return jnp.iinfo(dtype).max
|
|
59
|
+
elif dtype == jnp.bool_:
|
|
60
|
+
return True
|
|
61
|
+
else:
|
|
62
|
+
raise ValueError(f'Unsupported dtype: {dtype}')
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _reduce_window(
|
|
66
|
+
x: jax.Array,
|
|
67
|
+
init_value: complex,
|
|
68
|
+
computation,
|
|
69
|
+
window_dimensions: TypingSequence[int],
|
|
70
|
+
window_strides: TypingSequence[int],
|
|
71
|
+
window_dilation: TypingSequence[int],
|
|
72
|
+
padding: TypingSequence[tuple[int, int]],
|
|
73
|
+
) -> jax.Array:
|
|
74
|
+
"""Executes a reduce_window with the provided parameters."""
|
|
75
|
+
|
|
76
|
+
def pack(value: TypingSequence[Any], default: Any) -> tuple[Any, ...]:
|
|
77
|
+
return (default,) + tuple(value) + (default,) * (x.ndim - len(value) - 1)
|
|
78
|
+
|
|
79
|
+
return jax.lax.reduce_window(
|
|
80
|
+
x,
|
|
81
|
+
init_value=np.asarray(init_value, x.dtype),
|
|
82
|
+
computation=computation,
|
|
83
|
+
window_dimensions=pack(window_dimensions, 1),
|
|
84
|
+
window_strides=pack(window_strides, 1),
|
|
85
|
+
padding=pack(padding, (0, 0)),
|
|
86
|
+
base_dilation=(1,) * x.ndim,
|
|
87
|
+
window_dilation=pack(window_dilation, 1),
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class BasePooling1D(
|
|
92
|
+
types.PreservesShape, types.PreservesType, types.SequenceLayer
|
|
93
|
+
):
|
|
94
|
+
"""Shared base logic for 1D pooling layers."""
|
|
95
|
+
|
|
96
|
+
def setup(self):
|
|
97
|
+
if self.config.padding == types.PaddingMode.CAUSAL_VALID.value:
|
|
98
|
+
raise ValueError(
|
|
99
|
+
'CAUSAL_VALID is not supported for 2D pooling. Use CAUSAL instead.'
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def supports_step(self) -> bool:
|
|
104
|
+
return self.config.padding in (
|
|
105
|
+
types.PaddingMode.REVERSE_CAUSAL_VALID.value,
|
|
106
|
+
types.PaddingMode.CAUSAL.value,
|
|
107
|
+
types.PaddingMode.REVERSE_CAUSAL.value,
|
|
108
|
+
types.PaddingMode.SEMICAUSAL.value,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def block_size(self) -> int:
|
|
113
|
+
return self.config.strides
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def output_ratio(self) -> fractions.Fraction:
|
|
117
|
+
return fractions.Fraction(1, self.config.strides)
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def input_latency(self) -> int:
|
|
121
|
+
effective_pool_size = utils.convolution_effective_kernel_size(
|
|
122
|
+
self.config.pool_size, self.config.dilation_rate
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
match self.config.padding:
|
|
126
|
+
case (
|
|
127
|
+
types.PaddingMode.CAUSAL_VALID.value
|
|
128
|
+
| types.PaddingMode.CAUSAL.value
|
|
129
|
+
| types.PaddingMode.SEMICAUSAL.value
|
|
130
|
+
):
|
|
131
|
+
# Causal padding eliminates latency.
|
|
132
|
+
return 0
|
|
133
|
+
case (
|
|
134
|
+
types.PaddingMode.REVERSE_CAUSAL_VALID.value
|
|
135
|
+
| types.PaddingMode.REVERSE_CAUSAL.value
|
|
136
|
+
):
|
|
137
|
+
# Reverse causal introduces no past padding in layer-wise mode, so we
|
|
138
|
+
# need a full effective_pool_size window to compute the first output
|
|
139
|
+
# layer-wise processing would produce. Since we do not count the current
|
|
140
|
+
# input as part of the latency, the input latency is one smaller than
|
|
141
|
+
# the effective pool size.
|
|
142
|
+
return effective_pool_size - 1
|
|
143
|
+
case _:
|
|
144
|
+
# Unsupported.
|
|
145
|
+
return 0
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
|
|
149
|
+
return convolution.conv_receptive_field_per_step(
|
|
150
|
+
self.config.pool_size,
|
|
151
|
+
self.config.strides,
|
|
152
|
+
self.config.dilation_rate,
|
|
153
|
+
self.config.padding,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def _buffer_width(self) -> int:
|
|
158
|
+
effective_pool_size = utils.convolution_effective_kernel_size(
|
|
159
|
+
self.config.pool_size, self.config.dilation_rate
|
|
160
|
+
)
|
|
161
|
+
match self.config.padding:
|
|
162
|
+
case types.PaddingMode.SEMICAUSAL.value:
|
|
163
|
+
return max(effective_pool_size - self.config.strides, 0)
|
|
164
|
+
case (
|
|
165
|
+
types.PaddingMode.REVERSE_CAUSAL.value
|
|
166
|
+
| types.PaddingMode.REVERSE_CAUSAL_VALID.value
|
|
167
|
+
):
|
|
168
|
+
return (
|
|
169
|
+
(effective_pool_size - 1)
|
|
170
|
+
// self.config.strides
|
|
171
|
+
* self.config.strides
|
|
172
|
+
)
|
|
173
|
+
case _:
|
|
174
|
+
return effective_pool_size - 1
|
|
175
|
+
|
|
176
|
+
def get_initial_state(
|
|
177
|
+
self,
|
|
178
|
+
batch_size: int,
|
|
179
|
+
input_spec: types.ShapeDType,
|
|
180
|
+
*,
|
|
181
|
+
training: bool,
|
|
182
|
+
constants: types.Constants | None = None,
|
|
183
|
+
) -> types.State:
|
|
184
|
+
# Special case pool_size 1 since it is stateless.
|
|
185
|
+
if not self._buffer_width:
|
|
186
|
+
return ()
|
|
187
|
+
|
|
188
|
+
# When executing a pooling step-by-step, we need a buffer for tracking the
|
|
189
|
+
# current pooling window. This matches the padding added by `layer`.
|
|
190
|
+
return convolution.compute_conv_initial_state(
|
|
191
|
+
batch_size,
|
|
192
|
+
input_spec,
|
|
193
|
+
self._buffer_width,
|
|
194
|
+
self.config.padding,
|
|
195
|
+
self._pad_value(input_spec.dtype),
|
|
196
|
+
).unmask()
|
|
197
|
+
|
|
198
|
+
@types.check_step
|
|
199
|
+
def step(
|
|
200
|
+
self,
|
|
201
|
+
x: types.Sequence,
|
|
202
|
+
state: types.State,
|
|
203
|
+
*,
|
|
204
|
+
training: bool,
|
|
205
|
+
constants: types.Constants | None = None,
|
|
206
|
+
) -> tuple[types.Sequence, types.State]:
|
|
207
|
+
|
|
208
|
+
# Replace masked timesteps with pad value.
|
|
209
|
+
x = x.mask_invalid(self._pad_value(x.dtype))
|
|
210
|
+
|
|
211
|
+
if buffer_width := self._buffer_width:
|
|
212
|
+
# Concatenate the new frames with the previous buffer_width frames.
|
|
213
|
+
state = state.concatenate(x)
|
|
214
|
+
else:
|
|
215
|
+
state = x
|
|
216
|
+
|
|
217
|
+
# Compute the output for the current timestep.
|
|
218
|
+
values = self._layer(state.values, state.mask, padding=(0, 0))
|
|
219
|
+
mask = convolution.compute_conv_mask(
|
|
220
|
+
state.mask,
|
|
221
|
+
self.config.pool_size,
|
|
222
|
+
self.config.strides,
|
|
223
|
+
self.config.dilation_rate,
|
|
224
|
+
self.config.padding,
|
|
225
|
+
is_step=True,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
# Keep the trailing buffer_width samples for the next step.
|
|
229
|
+
if buffer_width:
|
|
230
|
+
state = state[:, -buffer_width:]
|
|
231
|
+
else:
|
|
232
|
+
state = ()
|
|
233
|
+
|
|
234
|
+
# Pooling can leave unmasked values with non-zero values.
|
|
235
|
+
return types.Sequence(values, mask), state
|
|
236
|
+
|
|
237
|
+
@types.check_layer
|
|
238
|
+
def layer(
|
|
239
|
+
self,
|
|
240
|
+
x: types.Sequence,
|
|
241
|
+
training: bool,
|
|
242
|
+
constants: types.Constants | None = None,
|
|
243
|
+
):
|
|
244
|
+
padding = utils.convolution_explicit_padding(
|
|
245
|
+
self.config.padding,
|
|
246
|
+
self.config.pool_size,
|
|
247
|
+
self.config.strides,
|
|
248
|
+
self.config.dilation_rate,
|
|
249
|
+
)
|
|
250
|
+
# Replace masked timesteps with pad value.
|
|
251
|
+
x = x.mask_invalid(self._pad_value(x.dtype))
|
|
252
|
+
values = self._layer(x.values, x.mask, padding)
|
|
253
|
+
|
|
254
|
+
mask = convolution.compute_conv_mask(
|
|
255
|
+
x.mask,
|
|
256
|
+
self.config.pool_size,
|
|
257
|
+
self.config.strides,
|
|
258
|
+
self.config.dilation_rate,
|
|
259
|
+
self.config.padding,
|
|
260
|
+
is_step=False,
|
|
261
|
+
)
|
|
262
|
+
return types.Sequence(values, mask)
|
|
263
|
+
|
|
264
|
+
@nn.nowrap
|
|
265
|
+
def _pad_value(self, input_dtype: types.DType) -> complex:
|
|
266
|
+
raise NotImplementedError()
|
|
267
|
+
|
|
268
|
+
@nn.nowrap
|
|
269
|
+
def _layer(
|
|
270
|
+
self,
|
|
271
|
+
x: jt.Float[jt.ArrayT, 'B T *D'],
|
|
272
|
+
mask: jt.Bool[jt.ArrayT, 'B T'],
|
|
273
|
+
padding: tuple[int, int],
|
|
274
|
+
) -> jt.Float[jt.ArrayT, 'B T *D']:
|
|
275
|
+
raise NotImplementedError()
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
class MinPooling1D(BasePooling1D):
|
|
279
|
+
"""A 1D min pooling layer."""
|
|
280
|
+
|
|
281
|
+
@dataclasses.dataclass(frozen=True)
|
|
282
|
+
class Config(types.SequenceLayerConfig):
|
|
283
|
+
"""Config for MinPooling1D."""
|
|
284
|
+
|
|
285
|
+
pool_size: int
|
|
286
|
+
strides: int = 1
|
|
287
|
+
dilation_rate: int = 1
|
|
288
|
+
padding: types.PaddingModeString = types.PaddingMode.VALID.value
|
|
289
|
+
name: str | None = None
|
|
290
|
+
|
|
291
|
+
def __post_init__(self):
|
|
292
|
+
object.__setattr__(self, 'padding', types.validate_padding(self.padding))
|
|
293
|
+
|
|
294
|
+
def make(self) -> 'MinPooling1D':
|
|
295
|
+
return MinPooling1D(self, name=self.name)
|
|
296
|
+
|
|
297
|
+
config: Config
|
|
298
|
+
|
|
299
|
+
@nn.nowrap
|
|
300
|
+
def _pad_value(self, input_dtype: types.DType) -> complex:
|
|
301
|
+
return _min_pool_init_value(input_dtype)
|
|
302
|
+
|
|
303
|
+
@nn.nowrap
|
|
304
|
+
def _layer(
|
|
305
|
+
self,
|
|
306
|
+
x: jt.Float[jt.ArrayT, 'B T *D'],
|
|
307
|
+
mask: jt.Bool[jt.ArrayT, 'B T'],
|
|
308
|
+
padding: tuple[int, int],
|
|
309
|
+
) -> jt.Float[jt.ArrayT, 'B T *D']:
|
|
310
|
+
return _reduce_window(
|
|
311
|
+
x,
|
|
312
|
+
init_value=self._pad_value(x.dtype),
|
|
313
|
+
computation=jax.lax.min,
|
|
314
|
+
window_dimensions=(self.config.pool_size,),
|
|
315
|
+
window_dilation=(self.config.dilation_rate,),
|
|
316
|
+
window_strides=(self.config.strides,),
|
|
317
|
+
padding=(padding,),
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
class MaxPooling1D(BasePooling1D):
|
|
322
|
+
"""A 1D max pooling layer."""
|
|
323
|
+
|
|
324
|
+
@dataclasses.dataclass(frozen=True)
|
|
325
|
+
class Config(types.SequenceLayerConfig):
|
|
326
|
+
"""Config for MaxPooling1D."""
|
|
327
|
+
|
|
328
|
+
pool_size: int
|
|
329
|
+
strides: int = 1
|
|
330
|
+
dilation_rate: int = 1
|
|
331
|
+
padding: types.PaddingModeString = types.PaddingMode.VALID.value
|
|
332
|
+
name: str | None = None
|
|
333
|
+
|
|
334
|
+
def __post_init__(self):
|
|
335
|
+
object.__setattr__(self, 'padding', types.validate_padding(self.padding))
|
|
336
|
+
|
|
337
|
+
def make(self) -> 'MaxPooling1D':
|
|
338
|
+
return MaxPooling1D(self, name=self.name)
|
|
339
|
+
|
|
340
|
+
config: Config
|
|
341
|
+
|
|
342
|
+
@nn.nowrap
|
|
343
|
+
def _pad_value(self, input_dtype: types.DType) -> complex:
|
|
344
|
+
return _max_pool_init_value(input_dtype)
|
|
345
|
+
|
|
346
|
+
@nn.nowrap
|
|
347
|
+
def _layer(
|
|
348
|
+
self,
|
|
349
|
+
x: jt.Float[jt.ArrayT, 'B T *D'],
|
|
350
|
+
mask: jt.Bool[jt.ArrayT, 'B T'],
|
|
351
|
+
padding: tuple[int, int],
|
|
352
|
+
) -> jt.Float[jt.ArrayT, 'B T *D']:
|
|
353
|
+
del mask
|
|
354
|
+
return _reduce_window(
|
|
355
|
+
x,
|
|
356
|
+
init_value=self._pad_value(x.dtype),
|
|
357
|
+
computation=jax.lax.max,
|
|
358
|
+
window_dimensions=(self.config.pool_size,),
|
|
359
|
+
window_dilation=(self.config.dilation_rate,),
|
|
360
|
+
window_strides=(self.config.strides,),
|
|
361
|
+
padding=(padding,),
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def div_no_nan_grad(x, y):
|
|
366
|
+
"""Divides x by y elment-wise, and return 0 value and grad where y is 0."""
|
|
367
|
+
# Apply jnp.where before div to avoid NaN grad, due to inf x / y, when y == 0.
|
|
368
|
+
is_zero = y == 0
|
|
369
|
+
return jnp.where(is_zero, jnp.zeros_like(x), x) / jnp.where(is_zero, 1.0, y)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
class AveragePooling1D(BasePooling1D):
|
|
373
|
+
"""A 1D average pooling layer."""
|
|
374
|
+
|
|
375
|
+
@dataclasses.dataclass(frozen=True)
|
|
376
|
+
class Config(types.SequenceLayerConfig):
|
|
377
|
+
"""Config for AveragePooling1D."""
|
|
378
|
+
|
|
379
|
+
pool_size: int
|
|
380
|
+
strides: int = 1
|
|
381
|
+
dilation_rate: int = 1
|
|
382
|
+
padding: types.PaddingModeString = types.PaddingMode.VALID.value
|
|
383
|
+
# If true, divide by the number of valid items (i.e., sum of the mask)
|
|
384
|
+
# instead of the pool size.
|
|
385
|
+
masked_average: bool = False
|
|
386
|
+
name: str | None = None
|
|
387
|
+
|
|
388
|
+
def __post_init__(self):
|
|
389
|
+
object.__setattr__(self, 'padding', types.validate_padding(self.padding))
|
|
390
|
+
|
|
391
|
+
def make(self) -> 'AveragePooling1D':
|
|
392
|
+
return AveragePooling1D(self, name=self.name)
|
|
393
|
+
|
|
394
|
+
config: Config
|
|
395
|
+
|
|
396
|
+
@nn.nowrap
|
|
397
|
+
def _pad_value(self, input_dtype: types.DType) -> complex:
|
|
398
|
+
return 0
|
|
399
|
+
|
|
400
|
+
@nn.nowrap
|
|
401
|
+
def _layer(
|
|
402
|
+
self,
|
|
403
|
+
x: jt.Float[jt.ArrayT, 'B T *D'],
|
|
404
|
+
mask: jt.Bool[jt.ArrayT, 'B T'],
|
|
405
|
+
padding: tuple[int, int],
|
|
406
|
+
) -> jt.Float[jt.ArrayT, 'B T *D']:
|
|
407
|
+
y_sum = _reduce_window(
|
|
408
|
+
x,
|
|
409
|
+
init_value=self._pad_value(x.dtype),
|
|
410
|
+
computation=jax.lax.add,
|
|
411
|
+
window_dimensions=(self.config.pool_size,),
|
|
412
|
+
window_dilation=(self.config.dilation_rate,),
|
|
413
|
+
window_strides=(self.config.strides,),
|
|
414
|
+
padding=(padding,),
|
|
415
|
+
)
|
|
416
|
+
if self.config.masked_average:
|
|
417
|
+
mask_sum = _reduce_window(
|
|
418
|
+
mask.astype(x.dtype),
|
|
419
|
+
init_value=self._pad_value(x.dtype),
|
|
420
|
+
computation=jax.lax.add,
|
|
421
|
+
window_dimensions=(self.config.pool_size,),
|
|
422
|
+
window_dilation=(self.config.dilation_rate,),
|
|
423
|
+
window_strides=(self.config.strides,),
|
|
424
|
+
padding=(padding,),
|
|
425
|
+
)
|
|
426
|
+
mask_sum = jnp.expand_dims(mask_sum, range(2, y_sum.ndim))
|
|
427
|
+
if issubclass(x.dtype.type, jnp.integer):
|
|
428
|
+
y = jnp.floor_divide(y_sum, mask_sum)
|
|
429
|
+
else:
|
|
430
|
+
y = div_no_nan_grad(y_sum, mask_sum)
|
|
431
|
+
elif issubclass(x.dtype.type, jnp.integer):
|
|
432
|
+
# Divide the summed windows by the number of elements per window to get
|
|
433
|
+
# the average. Ignore dilation since the holes in the pool operation do
|
|
434
|
+
# not contribute to the sum.
|
|
435
|
+
y = y_sum // self.config.pool_size
|
|
436
|
+
else:
|
|
437
|
+
# TODO(rryan): Should we divide first to avoid loss of precision due to
|
|
438
|
+
# reduction, or alternatively increase precision of the reduction?
|
|
439
|
+
y = y_sum / self.config.pool_size
|
|
440
|
+
return y
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
class BasePooling2D(types.PreservesType, types.SequenceLayer):
|
|
444
|
+
"""Shared base logic for 2D pooling layers."""
|
|
445
|
+
|
|
446
|
+
def setup(self):
|
|
447
|
+
# Configs are normalized in __post_init__.
|
|
448
|
+
assert (
|
|
449
|
+
isinstance(self.config.pool_size, tuple)
|
|
450
|
+
and len(self.config.pool_size) == 2
|
|
451
|
+
)
|
|
452
|
+
assert (
|
|
453
|
+
isinstance(self.config.dilation_rate, tuple)
|
|
454
|
+
and len(self.config.dilation_rate) == 2
|
|
455
|
+
)
|
|
456
|
+
if self.config.time_padding == types.PaddingMode.CAUSAL_VALID.value:
|
|
457
|
+
raise ValueError(
|
|
458
|
+
'CAUSAL_VALID is not supported for 2D pooling. Use CAUSAL instead.'
|
|
459
|
+
)
|
|
460
|
+
|
|
461
|
+
@property
|
|
462
|
+
def supports_step(self) -> bool:
|
|
463
|
+
return self.config.time_padding in (
|
|
464
|
+
types.PaddingMode.REVERSE_CAUSAL_VALID.value,
|
|
465
|
+
types.PaddingMode.CAUSAL.value,
|
|
466
|
+
types.PaddingMode.REVERSE_CAUSAL.value,
|
|
467
|
+
types.PaddingMode.SEMICAUSAL.value,
|
|
468
|
+
)
|
|
469
|
+
|
|
470
|
+
@property
|
|
471
|
+
def block_size(self) -> int:
|
|
472
|
+
return self.config.strides[0]
|
|
473
|
+
|
|
474
|
+
@property
|
|
475
|
+
def output_ratio(self) -> fractions.Fraction:
|
|
476
|
+
return fractions.Fraction(1, self.config.strides[0])
|
|
477
|
+
|
|
478
|
+
@property
|
|
479
|
+
def input_latency(self) -> int:
|
|
480
|
+
effective_pool_size = utils.convolution_effective_kernel_size(
|
|
481
|
+
self.config.pool_size[0], self.config.dilation_rate[0]
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
match self.config.time_padding:
|
|
485
|
+
case (
|
|
486
|
+
types.PaddingMode.CAUSAL_VALID.value
|
|
487
|
+
| types.PaddingMode.CAUSAL.value
|
|
488
|
+
| types.PaddingMode.SEMICAUSAL.value
|
|
489
|
+
):
|
|
490
|
+
# Causal padding eliminates latency.
|
|
491
|
+
return 0
|
|
492
|
+
case (
|
|
493
|
+
types.PaddingMode.REVERSE_CAUSAL_VALID.value
|
|
494
|
+
| types.PaddingMode.REVERSE_CAUSAL.value
|
|
495
|
+
):
|
|
496
|
+
# Reverse causal introduces no past padding in layer-wise mode, so we
|
|
497
|
+
# need a full effective_pool_size window to compute the first output
|
|
498
|
+
# layer-wise processing would produce. Since we do not count the current
|
|
499
|
+
# input as part of the latency, the input latency is one smaller than
|
|
500
|
+
# the effective pool size.
|
|
501
|
+
return effective_pool_size - 1
|
|
502
|
+
case _:
|
|
503
|
+
# Unsupported.
|
|
504
|
+
return 0
|
|
505
|
+
|
|
506
|
+
@property
|
|
507
|
+
def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
|
|
508
|
+
past = -utils.convolution_explicit_padding(
|
|
509
|
+
self.config.time_padding,
|
|
510
|
+
self.config.pool_size[0],
|
|
511
|
+
self.config.strides[0],
|
|
512
|
+
self.config.dilation_rate[0],
|
|
513
|
+
)[0]
|
|
514
|
+
effective_pool_size = utils.convolution_effective_kernel_size(
|
|
515
|
+
self.config.pool_size[0], self.config.dilation_rate[0]
|
|
516
|
+
)
|
|
517
|
+
future = past + effective_pool_size - 1
|
|
518
|
+
return {0: (past, future)}
|
|
519
|
+
|
|
520
|
+
@property
|
|
521
|
+
def _buffer_width(self) -> int:
|
|
522
|
+
effective_pool_size = utils.convolution_effective_kernel_size(
|
|
523
|
+
self.config.pool_size[0], self.config.dilation_rate[0]
|
|
524
|
+
)
|
|
525
|
+
match self.config.time_padding:
|
|
526
|
+
case types.PaddingMode.SEMICAUSAL.value:
|
|
527
|
+
return max(effective_pool_size - self.config.strides[0], 0)
|
|
528
|
+
case (
|
|
529
|
+
types.PaddingMode.REVERSE_CAUSAL.value
|
|
530
|
+
| types.PaddingMode.REVERSE_CAUSAL_VALID.value
|
|
531
|
+
):
|
|
532
|
+
return (
|
|
533
|
+
(effective_pool_size - 1)
|
|
534
|
+
// self.config.strides[0]
|
|
535
|
+
* self.config.strides[0]
|
|
536
|
+
)
|
|
537
|
+
case _:
|
|
538
|
+
return effective_pool_size - 1
|
|
539
|
+
|
|
540
|
+
def get_initial_state(
|
|
541
|
+
self,
|
|
542
|
+
batch_size: int,
|
|
543
|
+
input_spec: types.ShapeDType,
|
|
544
|
+
*,
|
|
545
|
+
training: bool,
|
|
546
|
+
constants: types.Constants | None = None,
|
|
547
|
+
) -> types.State:
|
|
548
|
+
# Special case pool_size 1 since it is stateless.
|
|
549
|
+
if not (buffer_width := self._buffer_width):
|
|
550
|
+
return ()
|
|
551
|
+
|
|
552
|
+
# When executing a pool step-by-step, we need a buffer for tracking
|
|
553
|
+
# the current pooling window.
|
|
554
|
+
# This matches the causal padding added by `layer`.
|
|
555
|
+
return convolution.compute_conv_initial_state(
|
|
556
|
+
batch_size,
|
|
557
|
+
input_spec,
|
|
558
|
+
buffer_width,
|
|
559
|
+
self.config.time_padding,
|
|
560
|
+
self._pad_value(input_spec.dtype),
|
|
561
|
+
).unmask()
|
|
562
|
+
|
|
563
|
+
@nn.nowrap
|
|
564
|
+
def get_output_shape(
|
|
565
|
+
self,
|
|
566
|
+
input_shape: types.ShapeLike,
|
|
567
|
+
*,
|
|
568
|
+
constants: types.Constants | None = None,
|
|
569
|
+
) -> types.Shape:
|
|
570
|
+
output_shape = list(input_shape)
|
|
571
|
+
spatial_output_size = utils.convolution_padding_output_size(
|
|
572
|
+
input_shape[0],
|
|
573
|
+
self.config.spatial_padding,
|
|
574
|
+
kernel_size=self.config.pool_size[1],
|
|
575
|
+
stride=self.config.strides[1],
|
|
576
|
+
dilation_rate=self.config.dilation_rate[1],
|
|
577
|
+
)
|
|
578
|
+
output_shape[0] = spatial_output_size
|
|
579
|
+
return tuple(output_shape)
|
|
580
|
+
|
|
581
|
+
@types.check_step
|
|
582
|
+
def step(
|
|
583
|
+
self,
|
|
584
|
+
x: types.Sequence,
|
|
585
|
+
state: types.State,
|
|
586
|
+
*,
|
|
587
|
+
training: bool,
|
|
588
|
+
constants: types.Constants | None = None,
|
|
589
|
+
) -> tuple[types.Sequence, types.State]:
|
|
590
|
+
# In step mode, padding is handled by the state that is concatenated below.
|
|
591
|
+
time_padding = (0, 0)
|
|
592
|
+
spatial_padding = utils.convolution_explicit_padding(
|
|
593
|
+
self.config.spatial_padding,
|
|
594
|
+
self.config.pool_size[1],
|
|
595
|
+
self.config.strides[1],
|
|
596
|
+
self.config.dilation_rate[1],
|
|
597
|
+
)
|
|
598
|
+
|
|
599
|
+
# Replace masked timesteps with pad value.
|
|
600
|
+
x = x.mask_invalid(self._pad_value(x.dtype))
|
|
601
|
+
|
|
602
|
+
if buffer_width := self._buffer_width:
|
|
603
|
+
# Concatenate the new frames with the previous buffer_width frames.
|
|
604
|
+
state = state.concatenate(x)
|
|
605
|
+
else:
|
|
606
|
+
state = x
|
|
607
|
+
|
|
608
|
+
# Compute the output for the current timestep.
|
|
609
|
+
values = self._layer(
|
|
610
|
+
state.values, state.mask, padding=(time_padding, spatial_padding)
|
|
611
|
+
)
|
|
612
|
+
mask = convolution.compute_conv_mask(
|
|
613
|
+
state.mask,
|
|
614
|
+
self.config.pool_size[0],
|
|
615
|
+
self.config.strides[0],
|
|
616
|
+
self.config.dilation_rate[0],
|
|
617
|
+
self.config.time_padding,
|
|
618
|
+
is_step=True,
|
|
619
|
+
)
|
|
620
|
+
|
|
621
|
+
# Keep the trailing buffer_width samples for the next step.
|
|
622
|
+
if buffer_width:
|
|
623
|
+
state = state[:, -buffer_width:]
|
|
624
|
+
else:
|
|
625
|
+
state = ()
|
|
626
|
+
|
|
627
|
+
# Pooling can leave unmasked values with non-zero values.
|
|
628
|
+
return types.Sequence(values, mask), state
|
|
629
|
+
|
|
630
|
+
@types.check_layer
|
|
631
|
+
def layer(
|
|
632
|
+
self,
|
|
633
|
+
x: types.Sequence,
|
|
634
|
+
training: bool,
|
|
635
|
+
constants: types.Constants | None = None,
|
|
636
|
+
):
|
|
637
|
+
time_padding = utils.convolution_explicit_padding(
|
|
638
|
+
self.config.time_padding,
|
|
639
|
+
self.config.pool_size[0],
|
|
640
|
+
self.config.strides[0],
|
|
641
|
+
self.config.dilation_rate[0],
|
|
642
|
+
)
|
|
643
|
+
spatial_padding = utils.convolution_explicit_padding(
|
|
644
|
+
self.config.spatial_padding,
|
|
645
|
+
self.config.pool_size[1],
|
|
646
|
+
self.config.strides[1],
|
|
647
|
+
self.config.dilation_rate[1],
|
|
648
|
+
)
|
|
649
|
+
x = x.mask_invalid(mask_value=self._pad_value(x.dtype))
|
|
650
|
+
values = self._layer(
|
|
651
|
+
x.values, x.mask, padding=(time_padding, spatial_padding)
|
|
652
|
+
)
|
|
653
|
+
|
|
654
|
+
mask = convolution.compute_conv_mask(
|
|
655
|
+
x.mask,
|
|
656
|
+
self.config.pool_size[0],
|
|
657
|
+
self.config.strides[0],
|
|
658
|
+
self.config.dilation_rate[0],
|
|
659
|
+
self.config.time_padding,
|
|
660
|
+
is_step=False,
|
|
661
|
+
)
|
|
662
|
+
return types.Sequence(values, mask)
|
|
663
|
+
|
|
664
|
+
@nn.nowrap
|
|
665
|
+
def _layer(
|
|
666
|
+
self,
|
|
667
|
+
x: jt.Float[jt.ArrayT, 'B T H *D'],
|
|
668
|
+
mask: jt.Bool[jt.ArrayT, 'B T'],
|
|
669
|
+
padding: tuple[tuple[int, int], tuple[int, int]],
|
|
670
|
+
) -> jt.Float[jt.ArrayT, 'B T H *D']:
|
|
671
|
+
raise NotImplementedError()
|
|
672
|
+
|
|
673
|
+
@nn.nowrap
|
|
674
|
+
def _pad_value(self, input_dtype: types.DType) -> complex:
|
|
675
|
+
raise NotImplementedError()
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
class MinPooling2D(BasePooling2D):
|
|
679
|
+
"""A 2D min pooling layer."""
|
|
680
|
+
|
|
681
|
+
@dataclasses.dataclass(frozen=True)
|
|
682
|
+
class Config(types.SequenceLayerConfig):
|
|
683
|
+
"""Config for MinPooling2D."""
|
|
684
|
+
|
|
685
|
+
pool_size: int | TypingSequence[int]
|
|
686
|
+
strides: int | TypingSequence[int] = 1
|
|
687
|
+
dilation_rate: int | TypingSequence[int] = 1
|
|
688
|
+
# A padding mode string determining how to pad the time dimension of the
|
|
689
|
+
# pool. MinPooling2D is only streamable if time_padding is 'causal_valid'
|
|
690
|
+
# 'reverse_causal_valid', 'causal', or 'reverse_causal'.
|
|
691
|
+
time_padding: types.PaddingModeString = types.PaddingMode.VALID.value
|
|
692
|
+
# A padding mode string or explicit padding values determining how to pad
|
|
693
|
+
# the spatial pooling dimension.
|
|
694
|
+
spatial_padding: types.PaddingModeString | tuple[int, int] = (
|
|
695
|
+
types.PaddingMode.SAME.value
|
|
696
|
+
)
|
|
697
|
+
name: str | None = None
|
|
698
|
+
|
|
699
|
+
def __post_init__(self):
|
|
700
|
+
object.__setattr__(
|
|
701
|
+
self, 'time_padding', types.validate_padding(self.time_padding)
|
|
702
|
+
)
|
|
703
|
+
if isinstance(self.spatial_padding, str):
|
|
704
|
+
object.__setattr__(
|
|
705
|
+
self,
|
|
706
|
+
'spatial_padding',
|
|
707
|
+
types.validate_padding(self.spatial_padding),
|
|
708
|
+
)
|
|
709
|
+
else:
|
|
710
|
+
object.__setattr__(
|
|
711
|
+
self,
|
|
712
|
+
'spatial_padding',
|
|
713
|
+
types.validate_explicit_padding(self.spatial_padding),
|
|
714
|
+
)
|
|
715
|
+
object.__setattr__(
|
|
716
|
+
self, 'pool_size', utils.normalize_2tuple(self.pool_size)
|
|
717
|
+
)
|
|
718
|
+
object.__setattr__(self, 'strides', utils.normalize_2tuple(self.strides))
|
|
719
|
+
object.__setattr__(
|
|
720
|
+
self, 'dilation_rate', utils.normalize_2tuple(self.dilation_rate)
|
|
721
|
+
)
|
|
722
|
+
|
|
723
|
+
def make(self) -> 'MinPooling2D':
|
|
724
|
+
return MinPooling2D(self, name=self.name)
|
|
725
|
+
|
|
726
|
+
config: Config
|
|
727
|
+
|
|
728
|
+
@nn.nowrap
|
|
729
|
+
def _pad_value(self, input_dtype: types.DType) -> complex:
|
|
730
|
+
return _min_pool_init_value(input_dtype)
|
|
731
|
+
|
|
732
|
+
@nn.nowrap
|
|
733
|
+
def _layer(
|
|
734
|
+
self,
|
|
735
|
+
x: jt.Float[jt.ArrayT, 'B T H *D'],
|
|
736
|
+
mask: jt.Bool[jt.ArrayT, 'B T'],
|
|
737
|
+
padding: tuple[tuple[int, int], tuple[int, int]],
|
|
738
|
+
) -> jt.Float[jt.ArrayT, 'B T H *D']:
|
|
739
|
+
del mask
|
|
740
|
+
return _reduce_window(
|
|
741
|
+
x,
|
|
742
|
+
init_value=self._pad_value(x.dtype),
|
|
743
|
+
computation=jax.lax.min,
|
|
744
|
+
window_dimensions=self.config.pool_size,
|
|
745
|
+
window_dilation=self.config.dilation_rate,
|
|
746
|
+
window_strides=self.config.strides,
|
|
747
|
+
padding=padding,
|
|
748
|
+
)
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
class MaxPooling2D(BasePooling2D):
|
|
752
|
+
"""A 2D max pooling layer."""
|
|
753
|
+
|
|
754
|
+
@dataclasses.dataclass(frozen=True)
|
|
755
|
+
class Config(types.SequenceLayerConfig):
|
|
756
|
+
"""Config for MaxPooling2D."""
|
|
757
|
+
|
|
758
|
+
pool_size: int | TypingSequence[int]
|
|
759
|
+
strides: int | TypingSequence[int] = 1
|
|
760
|
+
dilation_rate: int | TypingSequence[int] = 1
|
|
761
|
+
# A padding mode string determining how to pad the time dimension of the
|
|
762
|
+
# pool. MaxPooling2D is only streamable if time_padding is 'causal_valid'
|
|
763
|
+
# 'reverse_causal_valid', 'causal', 'reverse_causal', or 'semicausal'.
|
|
764
|
+
time_padding: types.PaddingModeString = types.PaddingMode.VALID.value
|
|
765
|
+
# A padding mode string or explicit padding values determining how to pad
|
|
766
|
+
# the spatial pooling dimension.
|
|
767
|
+
spatial_padding: types.PaddingModeString | tuple[int, int] = (
|
|
768
|
+
types.PaddingMode.SAME.value
|
|
769
|
+
)
|
|
770
|
+
name: str | None = None
|
|
771
|
+
|
|
772
|
+
def __post_init__(self):
|
|
773
|
+
object.__setattr__(
|
|
774
|
+
self, 'time_padding', types.validate_padding(self.time_padding)
|
|
775
|
+
)
|
|
776
|
+
if isinstance(self.spatial_padding, str):
|
|
777
|
+
object.__setattr__(
|
|
778
|
+
self,
|
|
779
|
+
'spatial_padding',
|
|
780
|
+
types.validate_padding(self.spatial_padding),
|
|
781
|
+
)
|
|
782
|
+
else:
|
|
783
|
+
object.__setattr__(
|
|
784
|
+
self,
|
|
785
|
+
'spatial_padding',
|
|
786
|
+
types.validate_explicit_padding(self.spatial_padding),
|
|
787
|
+
)
|
|
788
|
+
object.__setattr__(
|
|
789
|
+
self, 'pool_size', utils.normalize_2tuple(self.pool_size)
|
|
790
|
+
)
|
|
791
|
+
object.__setattr__(self, 'strides', utils.normalize_2tuple(self.strides))
|
|
792
|
+
object.__setattr__(
|
|
793
|
+
self, 'dilation_rate', utils.normalize_2tuple(self.dilation_rate)
|
|
794
|
+
)
|
|
795
|
+
|
|
796
|
+
def make(self) -> 'MaxPooling2D':
|
|
797
|
+
return MaxPooling2D(self, name=self.name)
|
|
798
|
+
|
|
799
|
+
config: Config
|
|
800
|
+
|
|
801
|
+
@nn.nowrap
|
|
802
|
+
def _pad_value(self, input_dtype: types.DType) -> complex:
|
|
803
|
+
return _max_pool_init_value(input_dtype)
|
|
804
|
+
|
|
805
|
+
@nn.nowrap
|
|
806
|
+
def _layer(
|
|
807
|
+
self,
|
|
808
|
+
x: jt.Float[jt.ArrayT, 'B T H *D'],
|
|
809
|
+
mask: jt.Bool[jt.ArrayT, 'B T'],
|
|
810
|
+
padding: tuple[tuple[int, int], tuple[int, int]],
|
|
811
|
+
) -> jt.Float[jt.ArrayT, 'B T H *D']:
|
|
812
|
+
del mask
|
|
813
|
+
return _reduce_window(
|
|
814
|
+
x,
|
|
815
|
+
init_value=self._pad_value(x.dtype),
|
|
816
|
+
computation=jax.lax.max,
|
|
817
|
+
window_dimensions=self.config.pool_size,
|
|
818
|
+
window_dilation=self.config.dilation_rate,
|
|
819
|
+
window_strides=self.config.strides,
|
|
820
|
+
padding=padding,
|
|
821
|
+
)
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
class AveragePooling2D(BasePooling2D):
|
|
825
|
+
"""A 2D average pooling layer."""
|
|
826
|
+
|
|
827
|
+
@dataclasses.dataclass(frozen=True)
|
|
828
|
+
class Config(types.SequenceLayerConfig):
|
|
829
|
+
"""Config for AveragePooling2D."""
|
|
830
|
+
|
|
831
|
+
pool_size: int | TypingSequence[int]
|
|
832
|
+
strides: int | TypingSequence[int] = 1
|
|
833
|
+
dilation_rate: int | TypingSequence[int] = 1
|
|
834
|
+
# A padding mode string determining how to pad the time dimension of the
|
|
835
|
+
# pool. AveragePooling2D is only streamable if time_padding is
|
|
836
|
+
# 'causal_valid' 'reverse_causal_valid', 'causal', 'reverse_causal', or
|
|
837
|
+
# 'semicausal'.
|
|
838
|
+
time_padding: types.PaddingModeString = types.PaddingMode.VALID.value
|
|
839
|
+
# A padding mode string or explicit padding values determining how to pad
|
|
840
|
+
# the spatial pooling dimension.
|
|
841
|
+
spatial_padding: types.PaddingModeString | tuple[int, int] = (
|
|
842
|
+
types.PaddingMode.SAME.value
|
|
843
|
+
)
|
|
844
|
+
# If true, divide by the number of valid items (i.e., sum of the expanded
|
|
845
|
+
# mask), instead of the overall pool size.
|
|
846
|
+
masked_average: bool = False
|
|
847
|
+
name: str | None = None
|
|
848
|
+
|
|
849
|
+
def __post_init__(self):
|
|
850
|
+
object.__setattr__(
|
|
851
|
+
self, 'time_padding', types.validate_padding(self.time_padding)
|
|
852
|
+
)
|
|
853
|
+
if isinstance(self.spatial_padding, str):
|
|
854
|
+
object.__setattr__(
|
|
855
|
+
self,
|
|
856
|
+
'spatial_padding',
|
|
857
|
+
types.validate_padding(self.spatial_padding),
|
|
858
|
+
)
|
|
859
|
+
else:
|
|
860
|
+
object.__setattr__(
|
|
861
|
+
self,
|
|
862
|
+
'spatial_padding',
|
|
863
|
+
types.validate_explicit_padding(self.spatial_padding),
|
|
864
|
+
)
|
|
865
|
+
object.__setattr__(
|
|
866
|
+
self, 'pool_size', utils.normalize_2tuple(self.pool_size)
|
|
867
|
+
)
|
|
868
|
+
object.__setattr__(self, 'strides', utils.normalize_2tuple(self.strides))
|
|
869
|
+
object.__setattr__(
|
|
870
|
+
self, 'dilation_rate', utils.normalize_2tuple(self.dilation_rate)
|
|
871
|
+
)
|
|
872
|
+
|
|
873
|
+
def make(self) -> 'AveragePooling2D':
|
|
874
|
+
return AveragePooling2D(self, name=self.name)
|
|
875
|
+
|
|
876
|
+
config: Config
|
|
877
|
+
|
|
878
|
+
@nn.nowrap
|
|
879
|
+
def _pad_value(self, input_dtype: types.DType) -> complex:
|
|
880
|
+
return 0
|
|
881
|
+
|
|
882
|
+
@nn.nowrap
|
|
883
|
+
def _layer(
|
|
884
|
+
self,
|
|
885
|
+
x: jt.Float[jt.ArrayT, 'B T H *D'],
|
|
886
|
+
mask: jt.Bool[jt.ArrayT, 'B T'],
|
|
887
|
+
padding: tuple[tuple[int, int], tuple[int, int]],
|
|
888
|
+
) -> jt.Float[jt.ArrayT, 'B T H *D']:
|
|
889
|
+
y_sum = _reduce_window(
|
|
890
|
+
x,
|
|
891
|
+
init_value=self._pad_value(x.dtype),
|
|
892
|
+
computation=jax.lax.add,
|
|
893
|
+
window_dimensions=self.config.pool_size,
|
|
894
|
+
window_dilation=self.config.dilation_rate,
|
|
895
|
+
window_strides=self.config.strides,
|
|
896
|
+
padding=padding,
|
|
897
|
+
)
|
|
898
|
+
|
|
899
|
+
if self.config.masked_average:
|
|
900
|
+
time_dim_val = lambda v: v if isinstance(v, int) else v[0]
|
|
901
|
+
mask_sum = _reduce_window(
|
|
902
|
+
mask.astype(x.dtype),
|
|
903
|
+
init_value=self._pad_value(x.dtype),
|
|
904
|
+
computation=jax.lax.add,
|
|
905
|
+
window_dimensions=(time_dim_val(self.config.pool_size),),
|
|
906
|
+
window_dilation=(time_dim_val(self.config.dilation_rate),),
|
|
907
|
+
window_strides=(time_dim_val(self.config.strides),),
|
|
908
|
+
padding=padding[:1],
|
|
909
|
+
)
|
|
910
|
+
mask_sum = jnp.expand_dims(mask_sum, range(2, y_sum.ndim))
|
|
911
|
+
mask_sum *= np.prod(self.config.pool_size[1:])
|
|
912
|
+
if issubclass(x.dtype.type, jnp.integer):
|
|
913
|
+
y = jnp.floor_divide(y_sum, mask_sum)
|
|
914
|
+
else:
|
|
915
|
+
y = div_no_nan_grad(y_sum, mask_sum)
|
|
916
|
+
elif issubclass(x.dtype.type, jnp.integer):
|
|
917
|
+
# Divide the summed windows by the number of elements per window to get
|
|
918
|
+
# the average. Ignore dilation since the holes in the pool operation do
|
|
919
|
+
# not contribute to the sum.
|
|
920
|
+
y = y_sum // np.prod(self.config.pool_size)
|
|
921
|
+
else:
|
|
922
|
+
# TODO(rryan): Should we divide first to avoid loss of precision due to
|
|
923
|
+
# reduction, or alternatively increase precision of the reduction?
|
|
924
|
+
y = y_sum / np.prod(self.config.pool_size)
|
|
925
|
+
return y
|