-
Notifications
You must be signed in to change notification settings - Fork 82
/
test_keras_mirrored.py
500 lines (430 loc) · 18 KB
/
test_keras_mirrored.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# Future
from __future__ import absolute_import, division, print_function, unicode_literals
# Standard Library
import os
import time
# Third Party
import pytest
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
from tensorflow.python.client import device_lib
from tests.core.utils import verify_files
from tests.tensorflow2.utils import is_greater_than_tf_2_2, is_tf_2_3, is_tf_2_6, is_tf_version_gte
from tests.tensorflow.utils import create_trial_fast_refresh
from tests.utils import verify_shapes
from packaging import version
if version.parse(tf.__version__) >= version.parse("2.11.0") or "rc" in tf.__version__:
from tensorflow.keras.optimizers.legacy import Adam
else:
from tensorflow.keras.optimizers import Adam
# First Party
import smdebug.tensorflow as smd
from smdebug.core.access_layer import has_training_ended
from smdebug.core.collection import CollectionKeys
from smdebug.core.modes import ModeKeys
from smdebug.core.reduction_config import ALLOWED_NORMS, ALLOWED_REDUCTIONS
from smdebug.exceptions import TensorUnavailable, TensorUnavailableForStep
from smdebug.tensorflow import ReductionConfig, SaveConfig
from smdebug.tensorflow.keras import KerasHook
tfds.disable_progress_bar()
def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return len([x.name for x in local_device_protos if x.device_type == "GPU"])
def train_model(
trial_dir,
save_all=False,
hook=None,
include_collections=None,
reduction_config=None,
save_config=None,
eager=True,
strategy=None,
steps=None,
add_callbacks=None,
include_workers="all",
):
tf.keras.backend.clear_session()
if not eager:
tf.compat.v1.disable_eager_execution()
datasets, info = tfds.load(name="mnist", with_info=True, as_supervised=True)
mnist_train, mnist_test = datasets["train"], datasets["test"]
if strategy is None:
strategy = tf.distribute.MirroredStrategy()
# You can also do info.splits.total_num_examples to get the total
# number of examples in the dataset.
BUFFER_SIZE = 10000
BATCH_SIZE_PER_REPLICA = 64
BATCH_SIZE = BATCH_SIZE_PER_REPLICA * strategy.num_replicas_in_sync
def scale(image, label):
image = tf.cast(image, tf.float32)
image /= 255
return image, label
train_dataset = mnist_train.map(scale).cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
eval_dataset = mnist_test.map(scale).batch(BATCH_SIZE)
if hook is None:
if save_config is None:
save_config = SaveConfig(save_interval=3)
hook = KerasHook(
out_dir=trial_dir,
save_config=save_config,
reduction_config=reduction_config,
include_collections=include_collections,
save_all=save_all,
include_workers=include_workers,
)
if not save_all and include_collections is not None:
for cname in hook.include_collections:
if cname not in include_collections:
hook.get_collection(cname).save_config = SaveConfig(end_step=0)
opt = Adam()
opt = hook.wrap_optimizer(opt)
with strategy.scope():
relu_layer = tf.keras.layers.Dense(64, activation="relu")
model = tf.keras.Sequential(
[
tf.keras.layers.Conv2D(32, 3, activation="relu", input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
relu_layer,
tf.keras.layers.Dense(10, activation="softmax"),
]
)
model.compile(loss="sparse_categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
hooks = []
if add_callbacks:
if "tensorboard" in add_callbacks:
hooks.append(
# write_grads = True causes crash saying handle must be created in scope
# erorr like this https://stackoverflow.com/questions/56836895/custom-training-loop-using-tensorflow-gpu-1-14-and-tf-distribute-mirroredstrateg
# this crash is even if callback is off
tf.keras.callbacks.TensorBoard(
log_dir="/tmp/logs", histogram_freq=4, write_images=True
)
)
hooks.append(hook)
scalars_to_be_saved = dict()
ts = time.time()
scalars_to_be_saved["scalar/foobar"] = (ts, steps)
hook.save_scalar("foobar", 1, sm_metric=True, timestamp=ts)
if steps is None:
steps = ["train"]
for step in steps:
if step == "train":
model.fit(train_dataset, epochs=1, steps_per_epoch=10, callbacks=hooks, verbose=0)
elif step == "eval":
model.evaluate(eval_dataset, steps=10, callbacks=hooks, verbose=0)
elif step == "predict":
model.predict(train_dataset, steps=4, callbacks=hooks, verbose=0)
smd.get_hook().close()
return strategy, scalars_to_be_saved
def exhaustive_check(trial_dir, include_workers="one", eager=True):
include_collections = [
CollectionKeys.WEIGHTS,
CollectionKeys.BIASES,
CollectionKeys.GRADIENTS,
CollectionKeys.LOSSES,
CollectionKeys.OUTPUTS,
CollectionKeys.METRICS,
CollectionKeys.OPTIMIZER_VARIABLES,
]
strategy, _ = train_model(
trial_dir,
include_collections=include_collections,
steps=["train", "eval", "predict", "train"],
include_workers=include_workers,
eager=eager,
)
tr = create_trial_fast_refresh(trial_dir)
print(tr.tensor_names())
if include_workers == "all":
assert len(tr.workers()) == strategy.num_replicas_in_sync
if eager:
if is_tf_2_6():
assert len(tr.tensor_names()) == 15
elif is_greater_than_tf_2_2():
assert len(tr.tensor_names()) == (6 + 1 + 2 + 5 + 1 + 6 + 2)
# 6 weights, 1 loss, 2 metrics, 5 optimizer variables, 6 gradients, 2 outputs for Tf 2.2, 1 scalar
else:
assert len(tr.tensor_names()) == (
6 + 1 + 2 + 5 + 1
if (is_greater_than_tf_2_2() or is_tf_2_3())
else 6 + 1 + 3 + 5 + 1
)
# 6 weights, 1 loss, 2 metrics, 5 optimizer variables for Tf 2.3, 1 scalar
# 6 weights, 1 loss, 3 metrics, 5 optimizer variables for Tf 2.1, 1 scalar
else:
assert len(tr.tensor_names()) == (6 + 6 + 1 + 3 + strategy.num_replicas_in_sync * 3 + 5)
else:
assert len(tr.workers()) == 1
if eager:
assert len(tr.tensor_names()) == (6 + 3 + 1)
else:
assert len(tr.tensor_names()) == (6 + 6 + 1 + 3 + 1 * 3 + 5)
# 6 weights, 6 gradients, 1 loss, 3 metrics, 24 outputs (8 for each mode), 5 optimizer variables
assert len(tr.modes()) == 3
assert len(tr.steps()) == 14
assert len(tr.steps(ModeKeys.TRAIN)) == 8 # 0, 3, 6, 9, 12, 15, 18, 19(end of epoch)
assert len(tr.steps(ModeKeys.EVAL)) == 4
assert len(tr.steps(ModeKeys.PREDICT)) == 2 # ran 4 steps above
assert len(tr.tensor_names(collection=CollectionKeys.BIASES)) == 3
wtnames = tr.tensor_names(collection=CollectionKeys.WEIGHTS)
assert len(wtnames) == 3
for wtname in wtnames:
assert len(tr.tensor(wtname).steps()) == 13, wtname
assert len(tr.tensor(wtname).steps(ModeKeys.TRAIN)) == 7
for s in tr.tensor(wtname).steps(ModeKeys.TRAIN):
assert tr.tensor(wtname).value(s, mode=ModeKeys.TRAIN) is not None
for worker in tr.workers():
assert tr.tensor(wtname).value(s, mode=ModeKeys.TRAIN, worker=worker) is not None
assert len(tr.tensor(wtname).steps(ModeKeys.EVAL)) == 4
for s in tr.tensor(wtname).steps(ModeKeys.EVAL):
assert tr.tensor(wtname).value(s, mode=ModeKeys.EVAL) is not None
for worker in tr.workers():
assert tr.tensor(wtname).value(s, mode=ModeKeys.EVAL, worker=worker) is not None
assert len(tr.tensor(wtname).steps(ModeKeys.PREDICT)) == 2
if not eager:
gradnames = tr.tensor_names(collection=CollectionKeys.GRADIENTS)
assert len(gradnames) == 6
for gradname in gradnames:
assert len(tr.tensor(gradname).steps(ModeKeys.TRAIN)) == 7
for s in tr.tensor(gradname).steps(ModeKeys.TRAIN):
assert tr.tensor(gradname).value(s, mode=ModeKeys.TRAIN) is not None
assert len(tr.tensor(gradname).steps(ModeKeys.EVAL)) == 0
assert len(tr.tensor(gradname).steps(ModeKeys.PREDICT)) == 0
optvarnames = tr.tensor_names(collection=CollectionKeys.OPTIMIZER_VARIABLES)
assert len(optvarnames) == 5
for optvarname in optvarnames:
assert len(tr.tensor(optvarname).steps(ModeKeys.TRAIN)) == 7
for s in tr.tensor(optvarname).steps(ModeKeys.TRAIN):
assert tr.tensor(optvarname).value(s, mode=ModeKeys.TRAIN) is not None
assert len(tr.tensor(optvarname).steps(ModeKeys.EVAL)) == 0
assert len(tr.tensor(optvarname).steps(ModeKeys.PREDICT)) == 0
assert len(tr.tensor_names(collection=CollectionKeys.LOSSES)) == 1
loss_name = tr.tensor_names(collection=CollectionKeys.LOSSES)[0]
# loss is not in predict mode (so less 2)
# add one for end of epoch
assert len(tr.tensor(loss_name).steps(ModeKeys.TRAIN)) == 8
assert len(tr.tensor(loss_name).steps(ModeKeys.EVAL)) == 4
assert len(tr.tensor(loss_name).steps(ModeKeys.PREDICT)) == 0
assert len(tr.tensor(loss_name).steps()) == 12
metricnames = tr.tensor_names(collection=CollectionKeys.METRICS)
assert len(metricnames) == (2 if (is_greater_than_tf_2_2() or is_tf_2_3()) else 3)
@pytest.mark.skipif(is_tf_version_gte("2.7"), reason="flaky for TF 2.7 (segfault)")
@pytest.mark.slow
def test_tf_keras(out_dir, tf_eager_mode, include_workers="all"):
exhaustive_check(out_dir, include_workers=include_workers, eager=tf_eager_mode)
@pytest.mark.skipif(is_tf_version_gte("2.7"), reason="flaky for TF 2.7 (segfault)")
@pytest.mark.slow
@pytest.mark.parametrize("workers", ["one", "all"])
def test_save_all(out_dir, tf_eager_mode, workers):
save_config = SaveConfig(save_steps=[5])
strategy, saved_scalars = train_model(
out_dir,
include_collections=None,
save_all=True,
save_config=save_config,
steps=["train"],
eager=tf_eager_mode,
include_workers=workers,
)
tr = create_trial_fast_refresh(out_dir)
print(tr.tensor_names())
if tf_eager_mode:
if is_tf_2_6():
assert len(tr.tensor_names()) == 15
elif is_greater_than_tf_2_2():
assert len(tr.tensor_names()) == (
6 + 2 + 1 + 5 + 1 + 1 + 2 + 8 + 8 if is_greater_than_tf_2_2() else 6 + 3 + 1 + 5 + 1
)
# weights, metrics, losses, optimizer variables, scalar, inputs, outputs, gradients, layers
else:
assert len(tr.tensor_names()) == (
6 + 2 + 1 + 5 + 1 if is_tf_2_3() else 6 + 3 + 1 + 5 + 1
)
else:
assert (
len(tr.tensor_names())
== 6
+ 6
+ 5
+ 3
+ 1
+ 3 * strategy.num_replicas_in_sync
+ 2 * strategy.num_replicas_in_sync
)
# weights, grads, optimizer_variables, metrics, losses, outputs
assert len(tr.steps()) == 3
for tname in tr.tensor_names():
assert len(tr.tensor(tname).workers(0)) == (
1 if workers == "one" else strategy.num_replicas_in_sync
)
verify_files(out_dir, save_config, saved_scalars)
@pytest.mark.skipif(is_tf_version_gte("2.7"), reason="flaky for TF 2.7 (segfault)")
@pytest.mark.slow
def test_shapes(out_dir, tf_eager_mode):
strategy, _ = train_model(
out_dir,
save_all=True,
save_config=SaveConfig(save_steps=[0]),
reduction_config=ReductionConfig(save_shape=True),
steps=["train"],
eager=tf_eager_mode,
)
multiworker = strategy.num_replicas_in_sync > 1
verify_shapes(out_dir, 0, multiworker=multiworker)
@pytest.mark.skipif(is_tf_version_gte("2.7"), reason="flaky for TF 2.7 (segfault)")
@pytest.mark.slow
def test_base_reductions(out_dir, tf_eager_mode):
train_model(
out_dir,
include_collections=[
CollectionKeys.WEIGHTS,
CollectionKeys.BIASES,
CollectionKeys.METRICS,
CollectionKeys.LOSSES,
],
reduction_config=ReductionConfig(norms=ALLOWED_NORMS, reductions=ALLOWED_REDUCTIONS),
steps=["train"],
eager=tf_eager_mode,
)
tr = create_trial_fast_refresh(out_dir)
weight_name = tr.tensor_names(collection=CollectionKeys.WEIGHTS)[0]
try:
tr.tensor(weight_name).value(0)
assert False
except TensorUnavailableForStep:
assert tr.tensor(weight_name).reduction_values(0)
loss_name = tr.tensor_names(collection=CollectionKeys.LOSSES)[0]
assert tr.tensor(loss_name).value(0) is not None
metric_name = tr.tensor_names(collection=CollectionKeys.METRICS)[0]
assert tr.tensor(metric_name).value(0) is not None
@pytest.mark.skipif(is_tf_version_gte("2.7"), reason="flaky for TF 2.7 (segfault)")
@pytest.mark.slow
def test_collection_reductions(out_dir, tf_eager_mode):
tf.keras.backend.clear_session()
hook = KerasHook(
out_dir=out_dir,
save_config=SaveConfig(save_interval=3),
include_collections=[
CollectionKeys.WEIGHTS,
CollectionKeys.BIASES,
CollectionKeys.GRADIENTS,
],
)
hook.get_collection(CollectionKeys.WEIGHTS).reduction_config = ReductionConfig(norms=["l1"])
train_model(out_dir, hook=hook, steps=["train"], eager=tf_eager_mode)
tr = create_trial_fast_refresh(out_dir)
weight_name = tr.tensor_names(collection=CollectionKeys.WEIGHTS)[0]
try:
tr.tensor(weight_name).value(0)
assert False
except TensorUnavailableForStep:
try:
assert tr.tensor(weight_name).reduction_value(0, "l1") is not None
except ValueError:
# some tensors reduction can't be computed
pass
except TensorUnavailable:
# sometimes we might not have tensor saved if it was only being
# saved as reduction and the reduction computation failed
pass
@pytest.mark.skipif(is_tf_version_gte("2.7"), reason="flaky for TF 2.7 (segfault)")
@pytest.mark.slow
def test_training_end(out_dir, tf_eager_mode):
train_model(
out_dir, include_collections=[CollectionKeys.OUTPUTS], steps=["train"], eager=tf_eager_mode
)
assert has_training_ended(out_dir) is True
@pytest.mark.skipif(is_tf_version_gte("2.7"), reason="flaky for TF 2.7 (segfault)")
@pytest.mark.slow
@pytest.mark.parametrize("workers", ["one", "all"])
def test_include_regex(out_dir, tf_eager_mode, workers):
hook = KerasHook(
out_dir=out_dir,
save_config=SaveConfig(save_interval=9),
include_collections=["custom_coll"],
include_workers=workers,
)
hook.get_collection("custom_coll").include("dense")
strategy, _ = train_model(out_dir, hook=hook, steps=["train"], eager=tf_eager_mode)
tr = create_trial_fast_refresh(out_dir)
tnames = tr.tensor_names(collection="custom_coll")
if tf_eager_mode:
if is_tf_2_6():
num_tensors = 4
elif is_greater_than_tf_2_2():
num_tensors = 12
else:
num_tensors = 4
assert len(tnames) == num_tensors
else:
assert len(tnames) == 4 + 3 * strategy.num_replicas_in_sync
for tname in tnames:
assert tr.tensor(tname).value(0) is not None
assert len(tr.tensor(tname).workers(0)) == (
1 if workers == "one" else strategy.num_replicas_in_sync
)
@pytest.mark.skip # Skipping this test for 0.8.1 because it is flaky
@pytest.mark.parametrize("workers", ["one", "all"])
def test_include_regex_opt_var(out_dir, tf_eager_mode, workers):
include_collections = ["custom_optimizer_variables"]
save_config = SaveConfig(save_interval=3)
hook = KerasHook(
out_dir=out_dir,
save_config=save_config,
include_collections=include_collections,
include_workers=workers,
)
hook.get_collection("custom_optimizer_variables").include("Adam")
strategy, _ = train_model(out_dir, hook=hook, steps=["train"], eager=tf_eager_mode)
tr = create_trial_fast_refresh(out_dir)
tnames = tr.tensor_names(collection="custom_optimizer_variables")
if tf_eager_mode:
assert len(tnames) == 5
else:
assert len(tnames) == 4 + 3 * strategy.num_replicas_in_sync
for tname in tnames:
assert tr.tensor(tname).value(0) is not None
assert len(tr.tensor(tname).workers(0)) == (
1 if workers == "one" else strategy.num_replicas_in_sync
)
@pytest.mark.skip_if_non_eager
@pytest.mark.slow
@pytest.mark.skipif(is_tf_version_gte("2.7"), reason="flaky for TF 2.7 (segfault)")
def test_clash_with_tb_callback(out_dir):
train_model(
out_dir,
save_config=SaveConfig(save_interval=9),
include_collections=[
CollectionKeys.WEIGHTS,
CollectionKeys.BIASES,
CollectionKeys.GRADIENTS,
CollectionKeys.LOSSES,
CollectionKeys.METRICS,
],
steps=["train"],
add_callbacks=["tensorboard"],
)
tr = create_trial_fast_refresh(out_dir)
if is_tf_2_6():
assert len(tr.tensor_names()) == 10
elif is_greater_than_tf_2_2():
assert len(tr.tensor_names()) == 16
else:
assert len(tr.tensor_names()) == (10 if is_tf_2_3() else 11)
@pytest.mark.skip
def test_one_device(out_dir, tf_eager_mode):
strategy, _ = train_model(
out_dir,
include_collections=[
CollectionKeys.WEIGHTS,
CollectionKeys.BIASES,
CollectionKeys.OUTPUTS,
CollectionKeys.GRADIENTS,
],
save_config=SaveConfig(save_interval=9),
strategy=tf.distribute.OneDeviceStrategy(device="/cpu:0"),
steps=["train"],
eager=tf_eager_mode,
)
assert os.path.isdir(os.path.join(out_dir, "events")) is False