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,358 @@
|
|
|
1
|
+
# Copyright 2025 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
|
+
"""Gemma 3n audio encoder."""
|
|
15
|
+
|
|
16
|
+
import dataclasses
|
|
17
|
+
import enum
|
|
18
|
+
|
|
19
|
+
import jax
|
|
20
|
+
import jax.numpy as jnp
|
|
21
|
+
import sequence_layers.jax as sl
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclasses.dataclass(frozen=True)
|
|
25
|
+
class AttentionEinsumFactoryConfig:
|
|
26
|
+
qkv_einsum: sl.EinsumFactoryT | None = None
|
|
27
|
+
position_embedding: sl.EinsumFactoryT | None = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclasses.dataclass(frozen=True)
|
|
31
|
+
class ConvEinsumFactoryConfig:
|
|
32
|
+
linear: sl.EinsumFactoryT | None = None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclasses.dataclass(frozen=True)
|
|
36
|
+
class FFWEinsumFactoryConfig:
|
|
37
|
+
linear: sl.EinsumFactoryT | None = None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclasses.dataclass(frozen=True)
|
|
41
|
+
class EinsumFactoryConfig:
|
|
42
|
+
"""Configuration for einsum factory replacement."""
|
|
43
|
+
|
|
44
|
+
# Attention einsum factory config.
|
|
45
|
+
attention: AttentionEinsumFactoryConfig = AttentionEinsumFactoryConfig()
|
|
46
|
+
# Conv einsum factory config.
|
|
47
|
+
conv: ConvEinsumFactoryConfig = ConvEinsumFactoryConfig()
|
|
48
|
+
# MLP einsum factory config.
|
|
49
|
+
mlp: FFWEinsumFactoryConfig = FFWEinsumFactoryConfig()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@enum.unique
|
|
53
|
+
class QuantMode(enum.Enum):
|
|
54
|
+
"""Quantization modes."""
|
|
55
|
+
|
|
56
|
+
# No quantization will happen in the layer.
|
|
57
|
+
NONE = enum.auto()
|
|
58
|
+
# QAT will happen in the layer if an injection factory is supplied.
|
|
59
|
+
TRAIN = enum.auto()
|
|
60
|
+
# Parameters in the layer will be quantized in a namespace inside
|
|
61
|
+
# the injected layer.
|
|
62
|
+
CONVERT = enum.auto()
|
|
63
|
+
# The layer will not create a parameter and instead use the quantized
|
|
64
|
+
# parameters (and scales) created in the injected namespace.
|
|
65
|
+
SERVE = enum.auto()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def prepare_einsum_factory(
|
|
69
|
+
einsum_factory: sl.EinsumFactoryT | None,
|
|
70
|
+
) -> sl.EinsumFactoryT | None:
|
|
71
|
+
# Note, we ignore the `w_wrapper` from cl/549464508.
|
|
72
|
+
# It is unclear if it is still necessary.
|
|
73
|
+
if einsum_factory is None:
|
|
74
|
+
return None
|
|
75
|
+
quant_w_init = jnp.zeros
|
|
76
|
+
return lambda: einsum_factory(
|
|
77
|
+
rhs_quant_mode=QuantMode.TRAIN,
|
|
78
|
+
rhs_init=quant_w_init,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclasses.dataclass(frozen=True)
|
|
83
|
+
class Gemma3nAudioEncoderConfig(sl.SequenceLayerConfig):
|
|
84
|
+
"""Configuration for the Gemma 3n audio encoder.
|
|
85
|
+
|
|
86
|
+
A Conformer / USM-based audio encoder implemented with SequenceLayers.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
# input_latency is the SequenceLayer.output_latency of the layers preceding
|
|
90
|
+
# this network. It's used to insert appropriate delays in the strided
|
|
91
|
+
# convolutions so that stepwise execution matches layerwise execution.
|
|
92
|
+
input_latency: int = 0
|
|
93
|
+
# Default to regular dtype promotion rules based on inputs and parameters.
|
|
94
|
+
compute_dtype: sl.DType | None = None
|
|
95
|
+
# By default store all model weights as float32.
|
|
96
|
+
param_dtype: sl.DType = jnp.float32
|
|
97
|
+
|
|
98
|
+
# Only available to be changed for testing.
|
|
99
|
+
num_layers: int = 12
|
|
100
|
+
model_dims: int = 1536
|
|
101
|
+
ffn_residual_weight: float = 0.5
|
|
102
|
+
atten_num_heads: int = 8
|
|
103
|
+
atten_left_context: int = 13
|
|
104
|
+
name: str | None = None
|
|
105
|
+
|
|
106
|
+
# Optional quantization
|
|
107
|
+
einsum_factories: EinsumFactoryConfig = EinsumFactoryConfig()
|
|
108
|
+
|
|
109
|
+
def make(self) -> sl.SequenceLayer:
|
|
110
|
+
"""Builds the Gemma 3n audio encoder."""
|
|
111
|
+
conv_stride = 2
|
|
112
|
+
return sl.Serial.Config(
|
|
113
|
+
[
|
|
114
|
+
sl.Serial.Config(
|
|
115
|
+
[
|
|
116
|
+
sl.ExpandDims.Config(-1),
|
|
117
|
+
sl.Delay.Config(
|
|
118
|
+
-self.input_latency % conv_stride,
|
|
119
|
+
delay_layer_output=False,
|
|
120
|
+
),
|
|
121
|
+
sl.Conv2D.Config(
|
|
122
|
+
filters=128,
|
|
123
|
+
kernel_size=3,
|
|
124
|
+
strides=conv_stride,
|
|
125
|
+
time_padding='reverse_causal',
|
|
126
|
+
spatial_padding='same',
|
|
127
|
+
use_bias=False,
|
|
128
|
+
compute_dtype=self.compute_dtype,
|
|
129
|
+
param_dtype=self.param_dtype,
|
|
130
|
+
name='subsampling_0',
|
|
131
|
+
),
|
|
132
|
+
sl.GroupNormalization.Config(
|
|
133
|
+
num_groups=1,
|
|
134
|
+
epsilon=1e-3,
|
|
135
|
+
cumulative=True,
|
|
136
|
+
use_bias=False,
|
|
137
|
+
name='norm_0',
|
|
138
|
+
),
|
|
139
|
+
sl.Relu.Config(),
|
|
140
|
+
# Introduce a delay in step mode so that the accumulated
|
|
141
|
+
# latency is divisible by the stride.
|
|
142
|
+
sl.Delay.Config(1, delay_layer_output=False),
|
|
143
|
+
sl.Conv2D.Config(
|
|
144
|
+
filters=32,
|
|
145
|
+
kernel_size=3,
|
|
146
|
+
strides=conv_stride,
|
|
147
|
+
time_padding='reverse_causal',
|
|
148
|
+
spatial_padding='same',
|
|
149
|
+
use_bias=False,
|
|
150
|
+
compute_dtype=self.compute_dtype,
|
|
151
|
+
param_dtype=self.param_dtype,
|
|
152
|
+
name='subsampling_1',
|
|
153
|
+
),
|
|
154
|
+
sl.GroupNormalization.Config(
|
|
155
|
+
num_groups=1,
|
|
156
|
+
epsilon=1e-3,
|
|
157
|
+
cumulative=True,
|
|
158
|
+
use_bias=False,
|
|
159
|
+
name='norm_1',
|
|
160
|
+
),
|
|
161
|
+
sl.Relu.Config(),
|
|
162
|
+
sl.DenseShaped.Config(
|
|
163
|
+
[self.model_dims],
|
|
164
|
+
use_bias=False,
|
|
165
|
+
compute_dtype=None,
|
|
166
|
+
param_dtype=self.param_dtype,
|
|
167
|
+
name='input_proj',
|
|
168
|
+
),
|
|
169
|
+
],
|
|
170
|
+
name='feature',
|
|
171
|
+
),
|
|
172
|
+
sl.Repeat.Config(
|
|
173
|
+
sl.Serial.Config(
|
|
174
|
+
[
|
|
175
|
+
sl.Residual.Config(
|
|
176
|
+
[
|
|
177
|
+
sl.RMSNormalization.Config(
|
|
178
|
+
param_dtype=self.param_dtype,
|
|
179
|
+
name='pre_layer_norm',
|
|
180
|
+
),
|
|
181
|
+
sl.Dense.Config(
|
|
182
|
+
self.model_dims * 4,
|
|
183
|
+
use_bias=False,
|
|
184
|
+
activation=jax.nn.swish,
|
|
185
|
+
compute_dtype=self.compute_dtype,
|
|
186
|
+
param_dtype=self.param_dtype,
|
|
187
|
+
einsum_factory=prepare_einsum_factory(
|
|
188
|
+
self.einsum_factories.mlp.linear,
|
|
189
|
+
),
|
|
190
|
+
name='ffn_layer1',
|
|
191
|
+
),
|
|
192
|
+
sl.Dense.Config(
|
|
193
|
+
self.model_dims,
|
|
194
|
+
use_bias=False,
|
|
195
|
+
compute_dtype=self.compute_dtype,
|
|
196
|
+
param_dtype=self.param_dtype,
|
|
197
|
+
einsum_factory=prepare_einsum_factory(
|
|
198
|
+
self.einsum_factories.mlp.linear,
|
|
199
|
+
),
|
|
200
|
+
name='ffn_layer2',
|
|
201
|
+
),
|
|
202
|
+
sl.RMSNormalization.Config(
|
|
203
|
+
param_dtype=self.param_dtype,
|
|
204
|
+
name='post_layer_norm',
|
|
205
|
+
),
|
|
206
|
+
sl.Scale.Config(self.ffn_residual_weight),
|
|
207
|
+
],
|
|
208
|
+
name='fflayer_start',
|
|
209
|
+
),
|
|
210
|
+
# Attention with residual connection.
|
|
211
|
+
sl.Residual.Config(
|
|
212
|
+
[
|
|
213
|
+
sl.RMSNormalization.Config(
|
|
214
|
+
param_dtype=self.param_dtype,
|
|
215
|
+
name='pre_norm',
|
|
216
|
+
),
|
|
217
|
+
sl.LocalDotProductSelfAttention.Config(
|
|
218
|
+
input_projection=sl.CombinedQueryKeyValueProjection(
|
|
219
|
+
einsum_factory=prepare_einsum_factory(
|
|
220
|
+
self.einsum_factories.attention.qkv_einsum,
|
|
221
|
+
),
|
|
222
|
+
),
|
|
223
|
+
num_heads=self.atten_num_heads,
|
|
224
|
+
units_per_head=self.model_dims
|
|
225
|
+
// self.atten_num_heads,
|
|
226
|
+
use_bias=False,
|
|
227
|
+
block_size=12,
|
|
228
|
+
max_past_horizon=self.atten_left_context
|
|
229
|
+
- 1,
|
|
230
|
+
max_future_horizon=0,
|
|
231
|
+
attention_logits_soft_cap=50.0,
|
|
232
|
+
relative_position_embedding=sl.TransformerXLRelativePositionEmbedding.Config(
|
|
233
|
+
num_heads=self.atten_num_heads,
|
|
234
|
+
units_per_head=self.model_dims
|
|
235
|
+
// self.atten_num_heads,
|
|
236
|
+
max_backward=self.atten_left_context
|
|
237
|
+
- 1,
|
|
238
|
+
max_forward=0,
|
|
239
|
+
position_bias_dim=self.model_dims,
|
|
240
|
+
use_bias=False,
|
|
241
|
+
param_dtype=self.param_dtype,
|
|
242
|
+
einsum_factory=prepare_einsum_factory(
|
|
243
|
+
self.einsum_factories.attention.position_embedding,
|
|
244
|
+
),
|
|
245
|
+
),
|
|
246
|
+
per_dim_scale=True,
|
|
247
|
+
compute_dtype=self.compute_dtype,
|
|
248
|
+
param_dtype=self.param_dtype,
|
|
249
|
+
name='self_atten',
|
|
250
|
+
),
|
|
251
|
+
sl.DenseShaped.Config(
|
|
252
|
+
[self.model_dims],
|
|
253
|
+
use_bias=False,
|
|
254
|
+
compute_dtype=self.compute_dtype,
|
|
255
|
+
param_dtype=self.param_dtype,
|
|
256
|
+
name='post',
|
|
257
|
+
),
|
|
258
|
+
sl.RMSNormalization.Config(
|
|
259
|
+
param_dtype=self.param_dtype,
|
|
260
|
+
name='post_norm',
|
|
261
|
+
),
|
|
262
|
+
],
|
|
263
|
+
name='trans_atten',
|
|
264
|
+
),
|
|
265
|
+
sl.Residual.Config(
|
|
266
|
+
[
|
|
267
|
+
sl.RMSNormalization.Config(
|
|
268
|
+
param_dtype=self.param_dtype,
|
|
269
|
+
name='ln',
|
|
270
|
+
),
|
|
271
|
+
sl.Dense.Config(
|
|
272
|
+
2 * self.model_dims,
|
|
273
|
+
use_bias=False,
|
|
274
|
+
compute_dtype=self.compute_dtype,
|
|
275
|
+
param_dtype=self.param_dtype,
|
|
276
|
+
einsum_factory=prepare_einsum_factory(
|
|
277
|
+
self.einsum_factories.conv.linear,
|
|
278
|
+
),
|
|
279
|
+
name='linear_start',
|
|
280
|
+
),
|
|
281
|
+
sl.GatedLinearUnit.Config(name='glu'),
|
|
282
|
+
sl.DepthwiseConv1D.Config(
|
|
283
|
+
kernel_size=5,
|
|
284
|
+
padding='causal',
|
|
285
|
+
use_bias=False,
|
|
286
|
+
compute_dtype=self.compute_dtype,
|
|
287
|
+
param_dtype=self.param_dtype,
|
|
288
|
+
name='depthwise_conv1d',
|
|
289
|
+
),
|
|
290
|
+
sl.RMSNormalization.Config(
|
|
291
|
+
param_dtype=self.param_dtype,
|
|
292
|
+
name='conv_norm',
|
|
293
|
+
),
|
|
294
|
+
sl.Swish.Config(name='conv_activation'),
|
|
295
|
+
sl.Dense.Config(
|
|
296
|
+
self.model_dims,
|
|
297
|
+
use_bias=False,
|
|
298
|
+
compute_dtype=self.compute_dtype,
|
|
299
|
+
param_dtype=self.param_dtype,
|
|
300
|
+
einsum_factory=prepare_einsum_factory(
|
|
301
|
+
self.einsum_factories.conv.linear,
|
|
302
|
+
),
|
|
303
|
+
name='linear_end',
|
|
304
|
+
),
|
|
305
|
+
],
|
|
306
|
+
name='lconv',
|
|
307
|
+
),
|
|
308
|
+
sl.Residual.Config(
|
|
309
|
+
[
|
|
310
|
+
sl.RMSNormalization.Config(
|
|
311
|
+
param_dtype=self.param_dtype,
|
|
312
|
+
name='pre_layer_norm',
|
|
313
|
+
),
|
|
314
|
+
sl.Dense.Config(
|
|
315
|
+
self.model_dims * 4,
|
|
316
|
+
use_bias=False,
|
|
317
|
+
activation=jax.nn.swish,
|
|
318
|
+
compute_dtype=self.compute_dtype,
|
|
319
|
+
param_dtype=self.param_dtype,
|
|
320
|
+
einsum_factory=prepare_einsum_factory(
|
|
321
|
+
self.einsum_factories.mlp.linear,
|
|
322
|
+
),
|
|
323
|
+
name='ffn_layer1',
|
|
324
|
+
),
|
|
325
|
+
sl.Dense.Config(
|
|
326
|
+
self.model_dims,
|
|
327
|
+
use_bias=False,
|
|
328
|
+
compute_dtype=self.compute_dtype,
|
|
329
|
+
param_dtype=self.param_dtype,
|
|
330
|
+
einsum_factory=prepare_einsum_factory(
|
|
331
|
+
self.einsum_factories.mlp.linear,
|
|
332
|
+
),
|
|
333
|
+
name='ffn_layer2',
|
|
334
|
+
),
|
|
335
|
+
sl.RMSNormalization.Config(
|
|
336
|
+
param_dtype=self.param_dtype,
|
|
337
|
+
name='post_layer_norm',
|
|
338
|
+
),
|
|
339
|
+
sl.Scale.Config(self.ffn_residual_weight),
|
|
340
|
+
],
|
|
341
|
+
name='fflayer_end',
|
|
342
|
+
),
|
|
343
|
+
sl.RMSNormalization.Config(
|
|
344
|
+
param_dtype=self.param_dtype,
|
|
345
|
+
name='final_ln',
|
|
346
|
+
),
|
|
347
|
+
],
|
|
348
|
+
name='stacked_layers',
|
|
349
|
+
),
|
|
350
|
+
num_repeats=self.num_layers,
|
|
351
|
+
name='conformer',
|
|
352
|
+
),
|
|
353
|
+
sl.Delay.Config(2, delay_layer_output=False),
|
|
354
|
+
sl.Downsample1D.Config(rate=4, name='reducer'),
|
|
355
|
+
sl.MaskInvalid.Config(),
|
|
356
|
+
],
|
|
357
|
+
name=self.name,
|
|
358
|
+
).make()
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
# Copyright 2025 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
|
+
"""Utilities for exporting JAX models to TensorFlow and tf.lite."""
|
|
15
|
+
|
|
16
|
+
from collections.abc import Mapping
|
|
17
|
+
import dataclasses
|
|
18
|
+
from typing import Any, Callable, NamedTuple
|
|
19
|
+
|
|
20
|
+
import jax
|
|
21
|
+
import jax.numpy as jnp
|
|
22
|
+
import orbax.export
|
|
23
|
+
from sequence_layers.jax import types
|
|
24
|
+
from sequence_layers.jax import typing
|
|
25
|
+
import tensorflow as tf
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_PATH_SEP = '/'
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class TFSequence(NamedTuple):
|
|
32
|
+
values: tf.Tensor
|
|
33
|
+
mask: tf.Tensor
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class TFMaskedSequence(TFSequence):
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _to_tf_sequence(a: types.Sequence | jax.Array) -> TFSequence | jax.Array:
|
|
41
|
+
if isinstance(a, types.Sequence):
|
|
42
|
+
return TFSequence(a.values, a.mask)
|
|
43
|
+
return a
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _from_tf_sequence(a: TFSequence | jax.Array) -> types.Sequence | jax.Array:
|
|
47
|
+
if isinstance(a, TFMaskedSequence):
|
|
48
|
+
return types.MaskedSequence(a.values, a.mask)
|
|
49
|
+
elif isinstance(a, TFSequence):
|
|
50
|
+
return types.Sequence(a.values, a.mask)
|
|
51
|
+
return a
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _tree_to_tf_sequence(tree: typing.AnyPyTree) -> typing.AnyPyTree:
|
|
55
|
+
return jax.tree.map(
|
|
56
|
+
_to_tf_sequence, tree, is_leaf=lambda a: isinstance(a, types.Sequence)
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _tree_from_tf_sequence(tree: typing.AnyPyTree) -> typing.AnyPyTree:
|
|
61
|
+
return jax.tree.map(
|
|
62
|
+
_from_tf_sequence, tree, is_leaf=lambda a: isinstance(a, TFSequence)
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _to_tf_dtype(jax_dtype):
|
|
67
|
+
if jax_dtype == jnp.bfloat16:
|
|
68
|
+
return tf.bfloat16
|
|
69
|
+
elif jax_dtype == jax.dtypes.float0:
|
|
70
|
+
return tf.float32
|
|
71
|
+
else:
|
|
72
|
+
return tf.dtypes.as_dtype(jax_dtype)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _tf_spec_to_polymorphic_shape(tree: typing.AnyPyTree) -> typing.PyTree[str]:
|
|
76
|
+
"""Converts a PyTree of tensors to a string representation of their shape."""
|
|
77
|
+
return tf.nest.map_structure(
|
|
78
|
+
lambda spec: _tf_shape_to_polymorphic_shape(spec.shape), tree
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _tf_shape_to_polymorphic_shape(shape: tf.TensorShape) -> str:
|
|
83
|
+
"""Converts a TensorShape to a string representation of its shape.
|
|
84
|
+
|
|
85
|
+
Unknown dimensions are assigned a dimension letter according to their index.
|
|
86
|
+
This is useful for expressing the common constraint that batch and time
|
|
87
|
+
dimension should match.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
shape: TensorShape to convert.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
A string matching jax2tf's polymorphic shape spec:
|
|
94
|
+
https://github.com/jax-ml/jax/blob/main/jax/experimental/jax2tf/README.md#shape-polymorphic-conversion
|
|
95
|
+
"""
|
|
96
|
+
dims = []
|
|
97
|
+
for i, d in enumerate(shape.as_list()):
|
|
98
|
+
if d is None:
|
|
99
|
+
if i > 25:
|
|
100
|
+
raise NotImplementedError('too many unknown dimensions')
|
|
101
|
+
dims.append(chr(ord('a') + i))
|
|
102
|
+
else:
|
|
103
|
+
dims.append(str(d))
|
|
104
|
+
return f'({", ".join(dims)})'
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _jax_key_path_to_str(key_path) -> str:
|
|
108
|
+
"""Converts a jax tree_util.KeyPath to string."""
|
|
109
|
+
match key_path:
|
|
110
|
+
case jax.tree_util.SequenceKey():
|
|
111
|
+
return str(key_path.idx)
|
|
112
|
+
case jax.tree_util.DictKey():
|
|
113
|
+
return str(key_path.key)
|
|
114
|
+
case jax.tree_util.GetAttrKey():
|
|
115
|
+
return key_path.name
|
|
116
|
+
case jax.tree_util.FlattenedIndexKey():
|
|
117
|
+
return str(key_path.key)
|
|
118
|
+
case _:
|
|
119
|
+
return str(key_path)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _get_shape(
|
|
123
|
+
input_shape: types.ShapeLike, unknown_batch: bool, unknown_time: bool
|
|
124
|
+
) -> tuple[int | None, ...]:
|
|
125
|
+
shape = list(input_shape)
|
|
126
|
+
if unknown_batch:
|
|
127
|
+
shape[0] = None
|
|
128
|
+
if unknown_time:
|
|
129
|
+
shape[1] = None
|
|
130
|
+
return tuple(shape)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _input_keys_and_leaves(tree):
|
|
134
|
+
leaves = jax.tree.leaves_with_path(
|
|
135
|
+
tree, is_leaf=lambda a: isinstance(a, TFSequence)
|
|
136
|
+
)
|
|
137
|
+
for path, v in leaves:
|
|
138
|
+
k = _PATH_SEP.join(_jax_key_path_to_str(p) for p in path)
|
|
139
|
+
yield k, v
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _tree_to_flat_dict(tree):
|
|
143
|
+
input_dict = {}
|
|
144
|
+
for k, v in _input_keys_and_leaves(tree):
|
|
145
|
+
if isinstance(v, TFSequence):
|
|
146
|
+
input_dict[f'{k}{_PATH_SEP}values'] = v.values
|
|
147
|
+
input_dict[f'{k}{_PATH_SEP}mask'] = v.mask
|
|
148
|
+
else:
|
|
149
|
+
input_dict[k] = v
|
|
150
|
+
return input_dict
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _result_dict_to_tree(result_dict, tree):
|
|
154
|
+
"""Map keys in result_dict back to entries in tree without assuming dict flattening order was preserved."""
|
|
155
|
+
leaves, treedef = jax.tree.flatten_with_path(tree)
|
|
156
|
+
key_to_index = {}
|
|
157
|
+
|
|
158
|
+
for i, (path, v) in enumerate(leaves):
|
|
159
|
+
k = _PATH_SEP.join(_jax_key_path_to_str(p) for p in path)
|
|
160
|
+
key_to_index[k] = i
|
|
161
|
+
|
|
162
|
+
leaves = [None] * len(leaves)
|
|
163
|
+
for k, v in result_dict.items():
|
|
164
|
+
leaves[key_to_index[k]] = v
|
|
165
|
+
|
|
166
|
+
return jax.tree.unflatten(treedef, leaves)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _tree_to_input_signature(
|
|
170
|
+
tree: typing.PyTree[jax.Array],
|
|
171
|
+
unknown_batch: bool = True,
|
|
172
|
+
unknown_time: bool = False,
|
|
173
|
+
) -> typing.PyTree[tf.TensorSpec]:
|
|
174
|
+
"""Returns a PyTree of tf.TensorSpec for the provided PyTree."""
|
|
175
|
+
leaves, treedef = jax.tree.flatten_with_path(
|
|
176
|
+
tree, is_leaf=lambda a: isinstance(a, TFSequence)
|
|
177
|
+
)
|
|
178
|
+
spec_leaves = []
|
|
179
|
+
|
|
180
|
+
for path, v in leaves:
|
|
181
|
+
k = _PATH_SEP.join(_jax_key_path_to_str(p) for p in path)
|
|
182
|
+
if isinstance(v, TFSequence):
|
|
183
|
+
spec_leaves.append(
|
|
184
|
+
TFSequence(
|
|
185
|
+
tf.TensorSpec(
|
|
186
|
+
_get_shape(v.values.shape, unknown_batch, unknown_time),
|
|
187
|
+
_to_tf_dtype(v.values.dtype),
|
|
188
|
+
name=f'{k}{_PATH_SEP}values',
|
|
189
|
+
),
|
|
190
|
+
tf.TensorSpec(
|
|
191
|
+
_get_shape(v.mask.shape, unknown_batch, unknown_time),
|
|
192
|
+
_to_tf_dtype(v.mask.dtype),
|
|
193
|
+
name=f'{k}{_PATH_SEP}mask',
|
|
194
|
+
),
|
|
195
|
+
)
|
|
196
|
+
)
|
|
197
|
+
else:
|
|
198
|
+
spec_leaves.append(
|
|
199
|
+
tf.TensorSpec(
|
|
200
|
+
_get_shape(v.shape, unknown_batch, False),
|
|
201
|
+
_to_tf_dtype(v.dtype),
|
|
202
|
+
name=k,
|
|
203
|
+
)
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
return jax.tree.unflatten(treedef, spec_leaves)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
@dataclasses.dataclass(frozen=True)
|
|
210
|
+
class Signature:
|
|
211
|
+
"""A signature to export to a TensorFlow saved model."""
|
|
212
|
+
|
|
213
|
+
# The function to be exported. Must take a tree of parameters as its first
|
|
214
|
+
# argument and a set of keyword arguments matching input_kwargs.
|
|
215
|
+
fn: Callable[..., Any]
|
|
216
|
+
# A set of keyword arguments to use as the input arguments to the function.
|
|
217
|
+
# The values of the keyword arguments can be arbitrary PyTrees of arrays. The
|
|
218
|
+
# argument names for each array in the tree will represent the path of the
|
|
219
|
+
# array in the tree separated by slashes.
|
|
220
|
+
input_kwargs: Mapping[str, Any]
|
|
221
|
+
# Whether to allow an unknown batch dimension for array and sequence inputs.
|
|
222
|
+
unknown_batch: bool = False
|
|
223
|
+
# Whether to allow an unknown time dimension for sequence inputs.
|
|
224
|
+
unknown_time: bool = False
|
|
225
|
+
# An optional TensorFlow pre-processing function.
|
|
226
|
+
tf_preprocessor: Callable[..., Any] | None = None
|
|
227
|
+
# An optional TensorFlow post-processing function.
|
|
228
|
+
tf_postprocessor: Callable[..., Any] | None = None
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def export_to_tf_saved_model(
|
|
232
|
+
params: typing.PyTree[jax.Array],
|
|
233
|
+
signatures: Mapping[str, Signature],
|
|
234
|
+
export_dir: str,
|
|
235
|
+
) -> None:
|
|
236
|
+
"""Exports the provided JAX function to a TensorFlow saved model.
|
|
237
|
+
|
|
238
|
+
Args:
|
|
239
|
+
params: The parameters to the function.
|
|
240
|
+
signatures: A list of signatures to include in the exported saved model.
|
|
241
|
+
export_dir: The directory to export the saved model to.
|
|
242
|
+
"""
|
|
243
|
+
|
|
244
|
+
serving_configs = []
|
|
245
|
+
functions = {}
|
|
246
|
+
polymorphic_shapes = {}
|
|
247
|
+
|
|
248
|
+
for key, signature in signatures.items():
|
|
249
|
+
input_kwargs = _tree_to_tf_sequence(signature.input_kwargs)
|
|
250
|
+
input_signature = _tree_to_input_signature(
|
|
251
|
+
input_kwargs,
|
|
252
|
+
unknown_batch=signature.unknown_batch,
|
|
253
|
+
unknown_time=signature.unknown_time,
|
|
254
|
+
)
|
|
255
|
+
input_polymorphic_shape = _tf_spec_to_polymorphic_shape(input_signature)
|
|
256
|
+
|
|
257
|
+
def fn_wrapper(params, args, fn=signature.fn):
|
|
258
|
+
args = _tree_from_tf_sequence(args)
|
|
259
|
+
result = fn(params, **args)
|
|
260
|
+
result = _tree_to_tf_sequence(result)
|
|
261
|
+
return _tree_to_flat_dict(result)
|
|
262
|
+
|
|
263
|
+
functions[key] = fn_wrapper
|
|
264
|
+
polymorphic_shapes[key] = input_polymorphic_shape
|
|
265
|
+
|
|
266
|
+
serving_configs.append(
|
|
267
|
+
orbax.export.ServingConfig(
|
|
268
|
+
key,
|
|
269
|
+
input_signature=[input_signature],
|
|
270
|
+
tf_preprocessor=signature.tf_preprocessor,
|
|
271
|
+
tf_postprocessor=signature.tf_postprocessor,
|
|
272
|
+
method_key=key,
|
|
273
|
+
)
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
jax_module = orbax.export.JaxModule(
|
|
277
|
+
params, functions, input_polymorphic_shape=polymorphic_shapes
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
manager = orbax.export.ExportManager(jax_module, serving_configs)
|
|
281
|
+
manager.save(export_dir)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def tflite_convert(
|
|
285
|
+
saved_model_path: str,
|
|
286
|
+
allow_custom_ops: bool = False,
|
|
287
|
+
use_flex: bool = False,
|
|
288
|
+
signature_keys: list[str] | None = None,
|
|
289
|
+
tags: list[str] | None = None,
|
|
290
|
+
) -> bytes:
|
|
291
|
+
"""Converts the provided TesnorFlow saved model to a tf.lite model.
|
|
292
|
+
|
|
293
|
+
Args:
|
|
294
|
+
saved_model_path: The path to the saved model to convert.
|
|
295
|
+
allow_custom_ops: Whether to allow custom ops.
|
|
296
|
+
use_flex: Enable tf.lite flex ops. Requires linking
|
|
297
|
+
//third_party/tensorflow/lite/delegates/flex:delegate
|
|
298
|
+
signature_keys: The signature keys to convert.
|
|
299
|
+
tags: The tags to convert.
|
|
300
|
+
|
|
301
|
+
Returns:
|
|
302
|
+
The serialized tf.lite model.
|
|
303
|
+
"""
|
|
304
|
+
converter = tf.lite.TFLiteConverter.from_saved_model(
|
|
305
|
+
saved_model_path, signature_keys=signature_keys, tags=tags
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
if allow_custom_ops:
|
|
309
|
+
converter.allow_custom_ops = True
|
|
310
|
+
if use_flex:
|
|
311
|
+
converter.target_spec.supported_ops.add(tf.lite.OpsSet.SELECT_TF_OPS)
|
|
312
|
+
|
|
313
|
+
return converter.convert()
|