/
fixtures.py
238 lines (197 loc) · 6.88 KB
/
fixtures.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
"""Fixtures for ScalarStop tests"""
import os
import unittest
from typing import Any, Mapping, Optional, Union
import tensorflow as tf
import scalarstop as sp
requires_external_database = unittest.skipUnless(
os.environ.get("TRAIN_STORE_CONNECTION_STRING", False),
"External database connection string was not supplied.",
)
requires_sqlite_json = unittest.skipIf(
not sp.train_store._sqlite_json_enabled(),
"The SQLite3 JSON1 extension is not enabled in this Python installation.",
)
class MyDataBlob(sp.DataBlob):
"""An example DataBlob for training."""
@sp.dataclass
class Hyperparams(sp.HyperparamsType):
"""Hyperparams."""
rows: int
cols: int
def _tfdata(self):
"""Generate example data."""
x = tf.random.uniform(
shape=(self.hyperparams.rows, self.hyperparams.cols), dtype=tf.float32
)
y = tf.random.uniform(shape=(self.hyperparams.rows,), dtype=tf.float32)
return tf.data.Dataset.zip(
(
tf.data.Dataset.from_tensor_slices(x),
tf.data.Dataset.from_tensor_slices(y),
)
)
def set_training(self):
return self._tfdata()
def set_validation(self):
return self._tfdata()
def set_test(self):
return self._tfdata()
class MyDataBlobRepeating(MyDataBlob):
"""An infinitely-repeating example DataBlob."""
def _tfdata(self):
return super()._tfdata().repeat()
class MyDataBlob2(MyDataBlob):
"""Another DataBlob to test different group names."""
@sp.dataclass
class Hyperparams(sp.HyperparamsType):
"""Hyperparams."""
rows: int
cols: int
def _tfdata(self):
"""Generate example data."""
x = tf.random.uniform(
shape=(self.hyperparams.rows, self.hyperparams.cols), dtype=tf.float32
)
y = tf.random.uniform(shape=(self.hyperparams.rows,), dtype=tf.float32)
return tf.data.Dataset.zip(
(
tf.data.Dataset.from_tensor_slices(x),
tf.data.Dataset.from_tensor_slices(y),
)
)
def set_training(self):
return self._tfdata()
def set_validation(self):
return self._tfdata()
def set_test(self):
return self._tfdata()
class MyShardableDataBlob(MyDataBlob):
"""
A :py:class:`~scalarstop.datablob.DataBlob` instance that
handles sharding internally.
"""
def __init__(
self,
*,
hyperparams: Optional[Union[Mapping[str, Any], sp.HyperparamsType]] = None,
num_shards: Optional[int] = None,
shard_index: Optional[int] = None,
**kwargs, # pylint: disable=unused-argument
):
super().__init__(hyperparams=hyperparams, **kwargs)
self._num_shards = num_shards
self._shard_index = shard_index
def _tfdata(self):
if self._num_shards is not None and self._shard_index is not None:
return (
super()
._tfdata()
.shard(num_shards=self._num_shards, index=self._shard_index)
)
return super()._tfdata()
class MyModelTemplate(sp.ModelTemplate):
"""Example model template."""
@sp.dataclass
class Hyperparams(sp.HyperparamsType):
"""Hyperparams."""
layer_1_units: int
optimizer: str = "adam"
loss: str = "binary_crossentropy"
def new_model(self):
"""Set a model."""
model = tf.keras.Sequential(
layers=[
tf.keras.layers.Dense(
units=self.hyperparams.layer_1_units,
kernel_initializer="zeros",
bias_initializer="zeros",
),
tf.keras.layers.Dense(
units=1,
activation="sigmoid",
kernel_initializer="zeros",
bias_initializer="zeros",
),
]
)
model.compile(
optimizer=self.hyperparams.optimizer,
loss=self.hyperparams.loss,
metrics=[
tf.keras.metrics.BinaryAccuracy(name="binary_accuracy"),
tf.keras.metrics.Precision(name="precision"),
tf.keras.metrics.Recall(name="recall"),
],
)
return model
class MyModelTemplate2(MyModelTemplate):
"""Another ModelTemplate to test different group names."""
@sp.dataclass
class Hyperparams(sp.HyperparamsType):
"""Hyperparams."""
layer_1_units: int
optimizer: str = "adam"
loss: str = "binary_crossentropy"
def new_model(self):
"""Set a model."""
model = tf.keras.Sequential(
layers=[
tf.keras.layers.Dense(
units=self.hyperparams.layer_1_units,
kernel_initializer="zeros",
bias_initializer="zeros",
),
tf.keras.layers.Dense(
units=1,
activation="sigmoid",
kernel_initializer="zeros",
bias_initializer="zeros",
),
]
)
model.compile(
optimizer=self.hyperparams.optimizer,
loss=self.hyperparams.loss,
metrics=[
tf.keras.metrics.BinaryAccuracy(name="binary_accuracy"),
tf.keras.metrics.Precision(name="precision"),
tf.keras.metrics.Recall(name="recall"),
],
)
return model
class MyShardableDistributedDataBlob(sp.DistributedDataBlob):
"""
An example of a custom :py:class:`~scalarstop.datablob.DistributedDataBlob`
subclass, wrapping :py:class:`MyShardableDataBlob`.
"""
def __init__(
self,
*,
hyperparams: Optional[Union[Mapping[str, Any], sp.HyperparamsType]] = None,
cache: bool = False,
repeat: Union[bool, int, None] = True,
per_replica_batch_size: Optional[int] = None,
tf_distribute_strategy: Optional[tf.distribute.get_strategy] = None,
):
name = MyShardableDataBlob.calculate_name(hyperparams=hyperparams)
group_name = MyShardableDataBlob.__name__
hyperparams_class = MyShardableDataBlob.Hyperparams
super().__init__(
name=name,
group_name=group_name,
hyperparams=hyperparams,
hyperparams_class=hyperparams_class,
cache=cache,
repeat=repeat,
per_replica_batch_size=per_replica_batch_size,
tf_distribute_strategy=tf_distribute_strategy,
)
def new_sharded_datablob(
self, ctx: tf.distribute.InputContext # pylint: disable=unused-argument
) -> sp.DataBlob:
return MyShardableDataBlob(
hyperparams=self._hyperparams,
num_shards=ctx.num_input_pipelines,
shard_index=ctx.input_pipeline_id,
)