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,509 @@
|
|
|
1
|
+
# Copyright 2023 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
"""Position layers."""
|
|
15
|
+
|
|
16
|
+
import math
|
|
17
|
+
from typing import Optional, Tuple
|
|
18
|
+
|
|
19
|
+
from sequence_layers.tensorflow import types
|
|
20
|
+
from sequence_layers.tensorflow import utils
|
|
21
|
+
import tensorflow.compat.v2 as tf
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
# A negative enough value such that it underflows to a hard zero in softmax.
|
|
25
|
+
_INVALID_LOGIT_VALUE = -1e9
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _get_timing_signal_1d(
|
|
29
|
+
length: tf.Tensor,
|
|
30
|
+
channels: tf.Tensor,
|
|
31
|
+
min_timescale: float = 1.0,
|
|
32
|
+
max_timescale: float = 1.0e4,
|
|
33
|
+
start_index: int = 0,
|
|
34
|
+
dtype: tf.DType = tf.float32,
|
|
35
|
+
) -> tf.Tensor:
|
|
36
|
+
"""Gets a bunch of sinusoids of different frequencies.
|
|
37
|
+
|
|
38
|
+
Copied from tensor2tensor.
|
|
39
|
+
|
|
40
|
+
Each channel of the input Tensor is incremented by a sinusoid of a different
|
|
41
|
+
frequency and phase.
|
|
42
|
+
|
|
43
|
+
This allows attention to learn to use absolute and relative positions.
|
|
44
|
+
Timing signals should be added to some precursors of both the query and the
|
|
45
|
+
memory inputs to attention.
|
|
46
|
+
|
|
47
|
+
The use of relative position is possible because sin(x+y) and cos(x+y) can be
|
|
48
|
+
expressed in terms of y, sin(x) and cos(x).
|
|
49
|
+
|
|
50
|
+
In particular, we use a geometric sequence of timescales starting with
|
|
51
|
+
min_timescale and ending with max_timescale. The number of different
|
|
52
|
+
timescales is equal to channels / 2. For each timescale, we
|
|
53
|
+
generate the two sinusoidal signals sin(timestep/timescale) and
|
|
54
|
+
cos(timestep/timescale). All of these sinusoids are concatenated in
|
|
55
|
+
the channels dimension.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
length: scalar, length of timing signal sequence.
|
|
59
|
+
channels: scalar, size of timing embeddings to create. The number of
|
|
60
|
+
different timescales is equal to channels / 2.
|
|
61
|
+
min_timescale: a float
|
|
62
|
+
max_timescale: a float
|
|
63
|
+
start_index: index of first position
|
|
64
|
+
dtype: Type of the returned timing signal.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
a Tensor of timing signals [1, length, channels]
|
|
68
|
+
"""
|
|
69
|
+
position = tf.cast(tf.range(length) + start_index, dtype)
|
|
70
|
+
num_timescales = channels // 2
|
|
71
|
+
log_timescale_increment = math.log(
|
|
72
|
+
float(max_timescale) / float(min_timescale)
|
|
73
|
+
) / tf.maximum(tf.cast(num_timescales, dtype) - 1, 1)
|
|
74
|
+
inv_timescales = min_timescale * tf.exp(
|
|
75
|
+
tf.cast(tf.range(num_timescales), dtype) * -log_timescale_increment
|
|
76
|
+
)
|
|
77
|
+
scaled_time = tf.expand_dims(position, 1) * tf.expand_dims(inv_timescales, 0)
|
|
78
|
+
# Please note that this slightly differs from the published paper.
|
|
79
|
+
# See a discussion here: https://github.com/tensorflow/tensor2tensor/pull/177
|
|
80
|
+
signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)
|
|
81
|
+
signal = tf.pad(signal, [[0, 0], [0, tf.math.mod(channels, 2)]])
|
|
82
|
+
signal = tf.reshape(signal, [1, length, channels])
|
|
83
|
+
return signal
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class AddTimingSignal(types.SequenceLayer):
|
|
87
|
+
"""Adds sinusoids at varying frequencies to the input channels dimension."""
|
|
88
|
+
|
|
89
|
+
def __init__(
|
|
90
|
+
self,
|
|
91
|
+
min_timescale: float = 1.0,
|
|
92
|
+
max_timescale: float = 1.0e4,
|
|
93
|
+
trainable_scale: bool = False,
|
|
94
|
+
name: Optional[str] = None,
|
|
95
|
+
):
|
|
96
|
+
super().__init__(name=name)
|
|
97
|
+
self._min_timescale = min_timescale
|
|
98
|
+
self._max_timescale = max_timescale
|
|
99
|
+
with self.name_scope:
|
|
100
|
+
if trainable_scale:
|
|
101
|
+
self._scale = tf.Variable(
|
|
102
|
+
1.0, dtype=utils.variable_dtype(), name='scale'
|
|
103
|
+
)
|
|
104
|
+
else:
|
|
105
|
+
self._scale = None
|
|
106
|
+
|
|
107
|
+
def _check_inputs(self, x: types.Sequence):
|
|
108
|
+
if not x.values.dtype.is_floating:
|
|
109
|
+
raise ValueError(
|
|
110
|
+
f'{type(self).__name__} requires floating point argument.'
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
def get_initial_state(
|
|
114
|
+
self, x: types.Sequence, constants: Optional[types.Constants] = None
|
|
115
|
+
) -> types.State:
|
|
116
|
+
self._check_inputs(x)
|
|
117
|
+
|
|
118
|
+
# State holds the current timestep (batched).
|
|
119
|
+
batch_size = utils.smart_dimension_size(x.values, 0)
|
|
120
|
+
return tf.zeros((batch_size, 1), dtype=tf.int32)
|
|
121
|
+
|
|
122
|
+
def get_output_shape(
|
|
123
|
+
self,
|
|
124
|
+
input_shape: tf.TensorShape,
|
|
125
|
+
constants: Optional[types.Constants] = None,
|
|
126
|
+
) -> tf.TensorShape:
|
|
127
|
+
return input_shape
|
|
128
|
+
|
|
129
|
+
@tf.Module.with_name_scope
|
|
130
|
+
def step(
|
|
131
|
+
self,
|
|
132
|
+
x: types.Sequence,
|
|
133
|
+
state: types.State,
|
|
134
|
+
training: bool,
|
|
135
|
+
constants: Optional[types.Constants] = None,
|
|
136
|
+
) -> Tuple[types.Sequence, types.State]:
|
|
137
|
+
self._check_inputs(x)
|
|
138
|
+
current_time = tf.reduce_max(state)
|
|
139
|
+
time = utils.smart_dimension_size(x.values, 1)
|
|
140
|
+
inner_shape = x.channel_shape
|
|
141
|
+
num_elements = inner_shape.num_elements()
|
|
142
|
+
timing_signal = _get_timing_signal_1d(
|
|
143
|
+
time,
|
|
144
|
+
num_elements,
|
|
145
|
+
min_timescale=self._min_timescale,
|
|
146
|
+
max_timescale=self._max_timescale,
|
|
147
|
+
start_index=current_time,
|
|
148
|
+
dtype=utils.compute_dtype(),
|
|
149
|
+
)
|
|
150
|
+
timing_signal = tf.reshape(timing_signal, [1, time] + inner_shape.as_list())
|
|
151
|
+
if self._scale is not None:
|
|
152
|
+
timing_signal *= tf.cast(self._scale, timing_signal.dtype)
|
|
153
|
+
x = x.apply_values(lambda v: v + tf.cast(timing_signal, v.dtype))
|
|
154
|
+
return x.mask_invalid(), state + time
|
|
155
|
+
|
|
156
|
+
@tf.Module.with_name_scope
|
|
157
|
+
def layer(
|
|
158
|
+
self,
|
|
159
|
+
x: types.Sequence,
|
|
160
|
+
training: bool,
|
|
161
|
+
initial_state: Optional[types.State] = None,
|
|
162
|
+
constants: Optional[types.Constants] = None,
|
|
163
|
+
) -> types.Sequence:
|
|
164
|
+
self._check_inputs(x)
|
|
165
|
+
time = utils.smart_dimension_size(x.values, 1)
|
|
166
|
+
inner_shape = x.channel_shape
|
|
167
|
+
num_elements = inner_shape.num_elements()
|
|
168
|
+
timing_signal = _get_timing_signal_1d(
|
|
169
|
+
time,
|
|
170
|
+
num_elements,
|
|
171
|
+
min_timescale=self._min_timescale,
|
|
172
|
+
max_timescale=self._max_timescale,
|
|
173
|
+
start_index=0,
|
|
174
|
+
dtype=utils.compute_dtype(),
|
|
175
|
+
)
|
|
176
|
+
timing_signal = tf.reshape(timing_signal, [1, time] + inner_shape.as_list())
|
|
177
|
+
if self._scale is not None:
|
|
178
|
+
timing_signal *= self._scale
|
|
179
|
+
x = x.apply_values(lambda v: v + tf.cast(timing_signal, v.dtype))
|
|
180
|
+
return x.mask_invalid()
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class ConcatTimingSignal(types.SequenceLayer):
|
|
184
|
+
"""Concatenates sinusoid timing signals to the input inner channels dimension.
|
|
185
|
+
|
|
186
|
+
If input channel rank > 1, then the timing signal is tiled over the outer
|
|
187
|
+
channel dimensions, e.g.:
|
|
188
|
+
- x: [b, t], t: [b, t, 4]) -> x_t: [b, t, 5]
|
|
189
|
+
- x: [b, t, 3], t: [b, t, 4]) -> x_t: [b, t, 7]
|
|
190
|
+
- x: [b, t, 3, 6], t: [b, t, 4]) -> x_t: [b, t, 3, 10]
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
def __init__(
|
|
194
|
+
self,
|
|
195
|
+
channels: int = 8,
|
|
196
|
+
min_timescale: float = 1.0,
|
|
197
|
+
max_timescale: float = 1.0e4,
|
|
198
|
+
name: Optional[str] = None,
|
|
199
|
+
):
|
|
200
|
+
super().__init__(name=name)
|
|
201
|
+
self._channels = channels
|
|
202
|
+
self._min_timescale = min_timescale
|
|
203
|
+
self._max_timescale = max_timescale
|
|
204
|
+
|
|
205
|
+
def _check_inputs(self, x: types.Sequence):
|
|
206
|
+
if not x.values.dtype.is_floating:
|
|
207
|
+
raise ValueError(
|
|
208
|
+
f'{type(self).__name__} requires floating point argument.'
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
def get_initial_state(
|
|
212
|
+
self, x: types.Sequence, constants: Optional[types.Constants] = None
|
|
213
|
+
) -> types.State:
|
|
214
|
+
self._check_inputs(x)
|
|
215
|
+
# State holds the current timestep.
|
|
216
|
+
return tf.constant(0, dtype=tf.int32)
|
|
217
|
+
|
|
218
|
+
def get_output_shape(
|
|
219
|
+
self,
|
|
220
|
+
input_shape: tf.TensorShape,
|
|
221
|
+
constants: Optional[types.Constants] = None,
|
|
222
|
+
) -> tf.TensorShape:
|
|
223
|
+
input_inner_dim = input_shape[-1] if input_shape.rank else 1
|
|
224
|
+
return input_shape[:-1] + [input_inner_dim + self._channels]
|
|
225
|
+
|
|
226
|
+
@tf.Module.with_name_scope
|
|
227
|
+
def step(
|
|
228
|
+
self,
|
|
229
|
+
x: types.Sequence,
|
|
230
|
+
state: types.State,
|
|
231
|
+
training: bool,
|
|
232
|
+
constants: Optional[types.Constants] = None,
|
|
233
|
+
) -> Tuple[types.Sequence, types.State]:
|
|
234
|
+
self._check_inputs(x)
|
|
235
|
+
current_time = state
|
|
236
|
+
batch_size, time = utils.smart_dimension_size(x.values, [0, 1])
|
|
237
|
+
timing_signal = _get_timing_signal_1d(
|
|
238
|
+
time,
|
|
239
|
+
self._channels,
|
|
240
|
+
min_timescale=self._min_timescale,
|
|
241
|
+
max_timescale=self._max_timescale,
|
|
242
|
+
start_index=current_time,
|
|
243
|
+
dtype=utils.compute_dtype(),
|
|
244
|
+
)
|
|
245
|
+
timing_signal = tf.tile(timing_signal, [batch_size, 1, 1])
|
|
246
|
+
timing_signal_sequence = types.Sequence(timing_signal, x.mask)
|
|
247
|
+
x = utils.sequence_broadcast_concat(x, timing_signal_sequence)
|
|
248
|
+
return x.mask_invalid(), current_time + time
|
|
249
|
+
|
|
250
|
+
@tf.Module.with_name_scope
|
|
251
|
+
def layer(
|
|
252
|
+
self,
|
|
253
|
+
x: types.Sequence,
|
|
254
|
+
training: bool,
|
|
255
|
+
initial_state: Optional[types.State] = None,
|
|
256
|
+
constants: Optional[types.Constants] = None,
|
|
257
|
+
) -> types.Sequence:
|
|
258
|
+
self._check_inputs(x)
|
|
259
|
+
batch_size, time = utils.smart_dimension_size(x.values, [0, 1])
|
|
260
|
+
timing_signal = _get_timing_signal_1d(
|
|
261
|
+
time,
|
|
262
|
+
self._channels,
|
|
263
|
+
min_timescale=self._min_timescale,
|
|
264
|
+
max_timescale=self._max_timescale,
|
|
265
|
+
start_index=0,
|
|
266
|
+
dtype=utils.compute_dtype(),
|
|
267
|
+
)
|
|
268
|
+
timing_signal = tf.tile(timing_signal, [batch_size, 1, 1])
|
|
269
|
+
timing_signal_sequence = types.Sequence(timing_signal, x.mask)
|
|
270
|
+
x = utils.sequence_broadcast_concat(x, timing_signal_sequence)
|
|
271
|
+
return x.mask_invalid()
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
class ConcatPositionEmbedding(types.SequenceLayer):
|
|
275
|
+
"""Concatenates a position embedding to the input inner channels dimension.
|
|
276
|
+
|
|
277
|
+
Asserts that sequences processed by the layer are always shorter
|
|
278
|
+
than timesteps to avoid a train-test mismatch.
|
|
279
|
+
|
|
280
|
+
If input channel rank > 1, then the position embedding is tiled over the outer
|
|
281
|
+
channel dimensions, e.g. (for channels = 4):
|
|
282
|
+
- x: [b, t], t: [b, t, 4]) -> x_t: [b, t, 5]
|
|
283
|
+
- x: [b, t, 3], t: [b, t, 4]) -> x_t: [b, t, 7]
|
|
284
|
+
- x: [b, t, 3, 6], t: [b, t, 4]) -> x_t: [b, t, 3, 10]
|
|
285
|
+
"""
|
|
286
|
+
|
|
287
|
+
def __init__(
|
|
288
|
+
self,
|
|
289
|
+
timesteps: int,
|
|
290
|
+
channels: int,
|
|
291
|
+
embeddings_initializer: tf.keras.initializers.Initializer | None = None,
|
|
292
|
+
name: str | None = None,
|
|
293
|
+
):
|
|
294
|
+
super().__init__(name=name)
|
|
295
|
+
self._timesteps = timesteps
|
|
296
|
+
self._channels = channels
|
|
297
|
+
with self.name_scope:
|
|
298
|
+
self._embedding = tf.keras.layers.Embedding(
|
|
299
|
+
timesteps,
|
|
300
|
+
channels,
|
|
301
|
+
embeddings_initializer=embeddings_initializer,
|
|
302
|
+
name='position_embedding',
|
|
303
|
+
)
|
|
304
|
+
self._embedding.build(tf.TensorShape([None, timesteps]))
|
|
305
|
+
|
|
306
|
+
def _check_inputs(self, x: types.Sequence):
|
|
307
|
+
if not x.values.dtype.is_floating:
|
|
308
|
+
raise ValueError(
|
|
309
|
+
f'{type(self).__name__} requires floating point argument.'
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
def get_initial_state(
|
|
313
|
+
self, x: types.Sequence, constants: Optional[types.Constants] = None
|
|
314
|
+
) -> types.State:
|
|
315
|
+
self._check_inputs(x)
|
|
316
|
+
# State holds the current timestep.
|
|
317
|
+
return tf.constant(0, dtype=tf.int32)
|
|
318
|
+
|
|
319
|
+
def get_output_shape(
|
|
320
|
+
self,
|
|
321
|
+
input_shape: tf.TensorShape,
|
|
322
|
+
constants: Optional[types.Constants] = None,
|
|
323
|
+
) -> tf.TensorShape:
|
|
324
|
+
input_inner_dim = input_shape[-1] if input_shape.rank else 1
|
|
325
|
+
return input_shape[:-1] + [input_inner_dim + self._channels]
|
|
326
|
+
|
|
327
|
+
def _concat_position_embedding(
|
|
328
|
+
self,
|
|
329
|
+
x: types.Sequence,
|
|
330
|
+
start_time: tf.Tensor,
|
|
331
|
+
) -> types.Sequence:
|
|
332
|
+
batch_size, num_timesteps = utils.smart_dimension_size(x.values, [0, 1])
|
|
333
|
+
position_embeddings = tf.cast(
|
|
334
|
+
self._embedding.embeddings[start_time : start_time + num_timesteps, :],
|
|
335
|
+
x.values.dtype,
|
|
336
|
+
)
|
|
337
|
+
num_embeddings = utils.smart_dimension_size(position_embeddings, 0)
|
|
338
|
+
position_embeddings = tf.pad(
|
|
339
|
+
position_embeddings, [[0, num_timesteps - num_embeddings], [0, 0]]
|
|
340
|
+
)
|
|
341
|
+
position_embeddings = tf.ensure_shape(
|
|
342
|
+
position_embeddings,
|
|
343
|
+
[
|
|
344
|
+
num_timesteps if isinstance(num_timesteps, int) else None,
|
|
345
|
+
self._channels,
|
|
346
|
+
],
|
|
347
|
+
)
|
|
348
|
+
position_embeddings = tf.tile(
|
|
349
|
+
position_embeddings[tf.newaxis, :, :], [batch_size, 1, 1]
|
|
350
|
+
)
|
|
351
|
+
tf.debugging.assert_less_equal(
|
|
352
|
+
x.lengths(),
|
|
353
|
+
num_embeddings,
|
|
354
|
+
message='Sequence is longer than valid position embeddings.',
|
|
355
|
+
)
|
|
356
|
+
position_embeddings = types.Sequence(position_embeddings, x.mask)
|
|
357
|
+
return utils.sequence_broadcast_concat(
|
|
358
|
+
x, position_embeddings
|
|
359
|
+
).mask_invalid()
|
|
360
|
+
|
|
361
|
+
@tf.Module.with_name_scope
|
|
362
|
+
def step(
|
|
363
|
+
self,
|
|
364
|
+
x: types.Sequence,
|
|
365
|
+
state: types.State,
|
|
366
|
+
training: bool,
|
|
367
|
+
constants: Optional[types.Constants] = None,
|
|
368
|
+
) -> Tuple[types.Sequence, types.State]:
|
|
369
|
+
self._check_inputs(x)
|
|
370
|
+
current_time = state
|
|
371
|
+
num_timesteps = utils.smart_dimension_size(x.values, 1)
|
|
372
|
+
x = self._concat_position_embedding(x, start_time=current_time)
|
|
373
|
+
return x, current_time + num_timesteps
|
|
374
|
+
|
|
375
|
+
@tf.Module.with_name_scope
|
|
376
|
+
def layer(
|
|
377
|
+
self,
|
|
378
|
+
x: types.Sequence,
|
|
379
|
+
training: bool,
|
|
380
|
+
initial_state: Optional[types.State] = None,
|
|
381
|
+
constants: Optional[types.Constants] = None,
|
|
382
|
+
) -> types.Sequence:
|
|
383
|
+
self._check_inputs(x)
|
|
384
|
+
return self._concat_position_embedding(x, start_time=0)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
class ApplyRotaryPositionalEncoding(types.PreservesShape, types.SequenceLayer):
|
|
388
|
+
"""Applies Rotary Positional Encodings (RoPE) to the sequence.
|
|
389
|
+
|
|
390
|
+
See the blogpost https://blog.eleuther.ai/rotary-embeddings/ and the paper
|
|
391
|
+
https://arxiv.org/abs/2104.09864.
|
|
392
|
+
"""
|
|
393
|
+
|
|
394
|
+
def __init__(
|
|
395
|
+
self,
|
|
396
|
+
min_timescale: float = 1.0,
|
|
397
|
+
max_timescale: float = 1.0e4,
|
|
398
|
+
axis: int = -1,
|
|
399
|
+
name: str | None = None,
|
|
400
|
+
):
|
|
401
|
+
"""Initializes the ApplyRotaryPositionalEncoding layer.
|
|
402
|
+
|
|
403
|
+
Args:
|
|
404
|
+
min_timescale: The minimum timescale for positional encoding.
|
|
405
|
+
max_timescale: The maximum timescale for positional encoding.
|
|
406
|
+
axis: The axis (dimension) to apply RoPE to (default -1).
|
|
407
|
+
name: The name of the layer (optional).
|
|
408
|
+
"""
|
|
409
|
+
super().__init__(name=name)
|
|
410
|
+
self.min_timescale = min_timescale
|
|
411
|
+
self.max_timescale = max_timescale
|
|
412
|
+
self.axis = axis
|
|
413
|
+
|
|
414
|
+
def _check_inputs(self, input_spec: tf.TensorSpec):
|
|
415
|
+
if not input_spec.dtype.is_floating:
|
|
416
|
+
raise ValueError(
|
|
417
|
+
f'{type(self).__name__} requires floating point argument.'
|
|
418
|
+
)
|
|
419
|
+
input_shape = (None, None) + input_spec.shape
|
|
420
|
+
axis = self.axis + len(input_shape) if self.axis < 0 else self.axis
|
|
421
|
+
if axis <= 1:
|
|
422
|
+
raise ValueError(
|
|
423
|
+
f'{type(self).__name__} axis ({self.axis}) must refer to a'
|
|
424
|
+
f' channels dimension ({input_spec=}).'
|
|
425
|
+
)
|
|
426
|
+
axis_size = input_shape[axis]
|
|
427
|
+
if axis_size % 2 != 0:
|
|
428
|
+
raise ValueError(
|
|
429
|
+
f'{type(self).__name__} requires input_shape[{axis}]={axis_size} to'
|
|
430
|
+
' be even.'
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
def get_initial_state(
|
|
434
|
+
self, x: types.Sequence, constants: Optional[types.Constants] = None
|
|
435
|
+
) -> types.State:
|
|
436
|
+
del constants
|
|
437
|
+
batch_size = utils.smart_dimension_size(x.values, 0)
|
|
438
|
+
self._check_inputs(x.channel_spec)
|
|
439
|
+
|
|
440
|
+
# State holds the current timestep (batched).
|
|
441
|
+
return tf.zeros((batch_size, 1), dtype=tf.int32)
|
|
442
|
+
|
|
443
|
+
def _apply_rope(self, x: tf.Tensor, positions: tf.Tensor) -> tf.Tensor:
|
|
444
|
+
axis = self.axis + x.ndim if self.axis < 0 else self.axis
|
|
445
|
+
assert axis > 1
|
|
446
|
+
channel_ndim = x.ndim - 2
|
|
447
|
+
broadcast_shape = [1] * x.ndim
|
|
448
|
+
axis_dim = x.shape[axis]
|
|
449
|
+
if axis_dim is None:
|
|
450
|
+
raise ValueError(f'Axis {axis} is unknown: {x.shape=}')
|
|
451
|
+
|
|
452
|
+
broadcast_shape[axis] = axis_dim // 2
|
|
453
|
+
assert axis_dim % 2 == 0
|
|
454
|
+
|
|
455
|
+
compute_dtype = utils.compute_dtype()
|
|
456
|
+
freq_exponents = (2.0 / axis_dim) * tf.cast(
|
|
457
|
+
tf.range(axis_dim // 2, dtype=tf.int32), compute_dtype
|
|
458
|
+
)
|
|
459
|
+
timescale = tf.reshape(
|
|
460
|
+
self.min_timescale
|
|
461
|
+
* (self.max_timescale / self.min_timescale) ** freq_exponents,
|
|
462
|
+
broadcast_shape,
|
|
463
|
+
)
|
|
464
|
+
|
|
465
|
+
positions = tf.cast(
|
|
466
|
+
tf.reshape(
|
|
467
|
+
positions,
|
|
468
|
+
utils.smart_dimension_size(positions, [0, 1]) + (1,) * channel_ndim,
|
|
469
|
+
),
|
|
470
|
+
compute_dtype,
|
|
471
|
+
)
|
|
472
|
+
radians = positions / timescale
|
|
473
|
+
sin, cos = tf.math.sin(radians), tf.math.cos(radians)
|
|
474
|
+
|
|
475
|
+
x1, x2 = tf.split(x, 2, axis=axis)
|
|
476
|
+
return tf.concat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], axis=axis)
|
|
477
|
+
|
|
478
|
+
def step(
|
|
479
|
+
self,
|
|
480
|
+
x: types.Sequence,
|
|
481
|
+
state: types.State,
|
|
482
|
+
training: bool,
|
|
483
|
+
constants: types.Constants | None = None,
|
|
484
|
+
) -> tuple[types.Sequence, types.State]:
|
|
485
|
+
del constants
|
|
486
|
+
self._check_inputs(x.channel_spec)
|
|
487
|
+
x_time = utils.smart_dimension_size(x.values, 1)
|
|
488
|
+
|
|
489
|
+
# Get positions for the batch.
|
|
490
|
+
positions = state + tf.range(x_time, dtype=tf.int32)
|
|
491
|
+
positions.shape.assert_is_compatible_with(x.values.shape[:2])
|
|
492
|
+
|
|
493
|
+
y = x.apply_values(self._apply_rope, positions).mask_invalid()
|
|
494
|
+
state = state + x_time
|
|
495
|
+
return y, state
|
|
496
|
+
|
|
497
|
+
def layer(
|
|
498
|
+
self,
|
|
499
|
+
x: types.Sequence,
|
|
500
|
+
training: bool,
|
|
501
|
+
initial_state: types.State | None = None,
|
|
502
|
+
constants: types.Constants | None = None,
|
|
503
|
+
) -> types.Sequence:
|
|
504
|
+
del constants
|
|
505
|
+
self._check_inputs(x.channel_spec)
|
|
506
|
+
x_time = utils.smart_dimension_size(x.values, 1)
|
|
507
|
+
positions = tf.range(x_time, dtype=tf.int32)[tf.newaxis, :]
|
|
508
|
+
x = x.apply_values(self._apply_rope, positions)
|
|
509
|
+
return x.mask_invalid()
|