Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions recml/core/training/keras_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ def __init__(
fold_batch_leaves: bool = False,
zero_copy_batches: bool = False,
fold_state_max_leaf_size: int = 0,
fold_step_logs: bool = False,
):
"""Initializes the instance.

Expand Down Expand Up @@ -199,6 +200,11 @@ def __init__(
pass in and out of each step, which reduces the host time per step for
models with many small variables, such as metrics. `0` disables state
folding. Not applied in `train_and_evaluate`. Defaults to 0.
fold_step_logs: With `fold_state_max_leaf_size > 0`, also stack the step
logs into one 1-D array per dtype inside the jitted train step if every
log has one element, so fewer arrays come back from each step. One-
element logs then come back as scalars. Not applied in
`train_and_evaluate`. Defaults to False.
resume_training_launcher: Launcher to resume training.
enable_xmanager_measurements: Whether to enable XManager measurements.
enable_autoxprof: Whether to enable AutoXprof.
Expand All @@ -207,7 +213,8 @@ def __init__(

Raises:
ValueError: If `device_prefetch_depth` or `fold_state_max_leaf_size` is
negative, or if `fold_batch_leaves` is set on a backend other than JAX.
negative, if `fold_batch_leaves` is set on a backend other than JAX, or
if `fold_step_logs` is set without `fold_state_max_leaf_size`.
"""
if device_prefetch_depth < 0:
raise ValueError(
Expand All @@ -223,6 +230,8 @@ def __init__(
"fold_state_max_leaf_size must be >= 0, got"
f" {fold_state_max_leaf_size}."
)
if fold_step_logs and not fold_state_max_leaf_size:
raise ValueError("fold_step_logs needs fold_state_max_leaf_size > 0.")

keras.utils.set_random_seed(rng_seed)

Expand Down Expand Up @@ -250,6 +259,7 @@ def __init__(
self._fold_batch_leaves = fold_batch_leaves
self._zero_copy_batches = zero_copy_batches
self._fold_state_max_leaf_size = fold_state_max_leaf_size
self._fold_step_logs = fold_step_logs
self._marker_path = os.path.join(
model_dir, core.TRAINING_COMPLETE_MARKER_FILE
)
Expand Down Expand Up @@ -440,6 +450,7 @@ def train(self, task: KerasTask) -> core.Logs:
if keras.backend.backend() == "jax"
else 0
),
fold_logs=self._fold_step_logs,
),
device_prefetch.model_prefetch_scope(
model, depth=self._device_prefetch_depth
Expand Down Expand Up @@ -505,8 +516,8 @@ def train_and_evaluate(self, task: KerasTask) -> core.Logs:
):
logging.warning(
"device_prefetch_depth, skip_batch_logs, fold_batch_leaves,"
" zero_copy_batches and fold_state_max_leaf_size only apply to"
" `train`; ignoring them in `train_and_evaluate`."
" zero_copy_batches, fold_state_max_leaf_size and fold_step_logs only"
" apply to `train`; ignoring them in `train_and_evaluate`."
)
train_dataset = task.create_dataset(
training=True, **self._maybe_get_dataset_kws(task)
Expand Down
60 changes: 60 additions & 0 deletions recml/core/training/keras_trainer_options_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ def test_prefetch_skips_export_on_non_chief_hosts(self):
dict(fold_batch_leaves=True),
dict(zero_copy_batches=True),
dict(fold_state_max_leaf_size=64),
dict(fold_state_max_leaf_size=64, fold_step_logs=True),
)
def test_train_and_evaluate_warns_that_option_is_not_applied(self, **options):
trainer = _trainer(self._tmpdir, **options)
Expand Down Expand Up @@ -336,6 +337,10 @@ def test_zero_copy_batches_with_fold_batch_leaves(self):
value, features[key][2 * step : 2 * step + 2]
)

def test_rejects_fold_step_logs_without_state_folding(self):
with self.assertRaisesRegex(ValueError, "fold_step_logs needs"):
_trainer(self._tmpdir, fold_step_logs=True)

def test_fold_state_max_leaf_size_folds_the_state_during_train(self):
rng = np.random.default_rng(0)
x = rng.random((8, 4)).astype(np.float32)
Expand Down Expand Up @@ -467,6 +472,7 @@ def make_dataset():
fold_batch_leaves=True,
zero_copy_batches=True,
fold_state_max_leaf_size=64,
fold_step_logs=True,
distribution=keras.distribution.DataParallel(),
).train(
types.SimpleNamespace(
Expand All @@ -486,6 +492,60 @@ def make_dataset():
opt_history.history[key], values, rtol=1e-6, err_msg=key
)

# Exercise `_FoldedLogs._read()` through `KerasTrainer.train` with
# `skip_batch_logs=False` and a per-batch callback.
want_batch_logs = []
ref_cb_dir = os.path.join(self._tmpdir, "ref_batch_logs")
os.makedirs(ref_cb_dir)
_trainer(
ref_cb_dir,
train_steps=4,
steps_per_loop=2,
train_callbacks=[
keras.callbacks.LambdaCallback(
on_train_batch_end=lambda _, logs: want_batch_logs.append(
dict(logs)
)
)
],
distribution=keras.distribution.DataParallel(),
).train(
types.SimpleNamespace(
create_dataset=lambda training: make_dataset(),
create_model=build_model,
export_model=lambda m, model_dir: None,
)
)
got_batch_logs = []
opt_cb_dir = os.path.join(self._tmpdir, "opt_batch_logs")
os.makedirs(opt_cb_dir)
_trainer(
opt_cb_dir,
train_steps=4,
steps_per_loop=2,
fold_state_max_leaf_size=64,
fold_step_logs=True,
train_callbacks=[
keras.callbacks.LambdaCallback(
on_train_batch_end=lambda _, logs: got_batch_logs.append(
dict(logs)
)
)
],
distribution=keras.distribution.DataParallel(),
).train(
types.SimpleNamespace(
create_dataset=lambda training: make_dataset(),
create_model=build_model,
export_model=lambda m, model_dir: None,
)
)
self.assertLen(got_batch_logs, 4)
for got, want in zip(got_batch_logs, want_batch_logs, strict=True):
self.assertCountEqual(got, want)
for key, value in want.items():
np.testing.assert_allclose(got[key], value, rtol=1e-6, err_msg=key)

def test_train_and_evaluate_skips_train_throughput_callback_with_warning(
self,
):
Expand Down
Loading
Loading