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
49 changes: 49 additions & 0 deletions recml/core/training/batch_callbacks_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,55 @@ class _CustomSummary(keras_utils.EpochSummaryCallback):
custom = _CustomSummary(log_dir=self._tmpdir, steps_per_epoch=1)
self.assertEqual(batch_callbacks.without_batch_hooks([custom]), [custom])

def test_zero_sync_list_skips_pythonify_logs_for_train_throughput_callback(
self,
):
throughput_cb = keras_utils.TrainThroughputCallback(
global_batch_size=8,
padded_seq_len=1024,
valid_seq_len_key="labels/count_seq_len",
device_count=4,
)
trainer_callbacks = [
throughput_cb,
*batch_callbacks.without_batch_hooks(_train_callbacks(self._tmpdir)),
]
with self.assertNoLogs(level="INFO"):
cb_list = batch_callbacks.ZeroSyncCallbackList(
trainer_callbacks,
add_history=True,
add_progbar=True,
verbose=1,
)

epoch_logs = {"labels/count_seq_len": 512.0}
with mock.patch.object(
keras_utils.time, "time", autospec=True, side_effect=[0.0, 2.0]
):
throughput_cb.on_epoch_begin(0)
with mock.patch.object(
python_utils,
"pythonify_logs",
autospec=True,
wraps=python_utils.pythonify_logs,
) as pythonify:
cb_list.on_train_batch_end(0, logs={"loss": 1.0})
cb_list.on_train_batch_end(4, logs={"loss": 1.0})
pythonify.assert_not_called()
throughput_cb.on_epoch_end(0, logs=epoch_logs)

# 5 steps / 2.0 s / 4 devices = 0.625 steps/s/device -> 5 examples/s/device
# -> 2.56k valid tokens/s/device and 50% packing efficiency.
self.assertAlmostEqual(
throughput_cb.latest_metrics[
"throughput/k_valid_tokens_per_sec_per_device"
],
2.56,
)
self.assertAlmostEqual(
throughput_cb.latest_metrics["throughput/packing_efficiency_pct"], 50.0
)


if __name__ == "__main__":
absltest.main()
13 changes: 12 additions & 1 deletion recml/core/training/keras_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,14 +495,25 @@ def train_and_evaluate(self, task: KerasTask) -> core.Logs:

model = task.create_model(**self._maybe_get_model_kws(task, train_dataset))

callbacks = [
cbk
for cbk in self.train_callbacks
if not isinstance(cbk, keras_utils.TrainThroughputCallback)
]
if len(callbacks) != len(self.train_callbacks):
logging.warning(
"TrainThroughputCallback only applies to `train`; skipping it in"
" `train_and_evaluate`."
)

history = model.fit(
train_dataset,
validation_data=eval_dataset,
epochs=self._train_epochs + 1,
steps_per_epoch=self._steps_per_loop,
# Explicitly set to None for deterministic evaluation.
validation_steps=None,
callbacks=self.train_callbacks,
callbacks=callbacks,
initial_epoch=1,
)
model.summary(print_fn=logging.info)
Expand Down
43 changes: 41 additions & 2 deletions recml/core/training/keras_trainer_options_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,17 @@ def make_train_function(self, force=False):
return
self.train_function = lambda state, it: (next(it), state)

def fit(self, dataset, epochs, steps_per_epoch, callbacks, initial_epoch):
del epochs, initial_epoch
def fit(
self,
dataset,
epochs,
steps_per_epoch,
callbacks,
initial_epoch,
validation_data=None,
validation_steps=None,
):
del epochs, initial_epoch, validation_data, validation_steps
self.make_train_function()
fn = self.train_function
self.seen_in_fit.append((fn, callbacks))
Expand Down Expand Up @@ -339,6 +348,36 @@ def test_train_and_evaluate_warns_that_skip_batch_logs_is_not_applied(self):
trainer.train_and_evaluate(task)
self.assertIn("skip_batch_logs", logs.output[0])

def test_train_and_evaluate_skips_train_throughput_callback_with_warning(
self,
):
throughput_cb = keras_utils.TrainThroughputCallback(
global_batch_size=8,
padded_seq_len=1024,
valid_seq_len_key="labels/count_seq_len",
device_count=1,
)
other_cb = keras.callbacks.Callback()
trainer = _trainer(
self._tmpdir,
train_callbacks=[throughput_cb, other_cb],
)
model = _DummyModel()
task = _task(model, [])
task.create_dataset = lambda training: tf.data.Dataset.from_tensor_slices(
np.zeros((10, 1), dtype=np.float32)
)

with self.assertLogs(level="WARNING") as logs:
trainer.train_and_evaluate(task)

self.assertTrue(
any("TrainThroughputCallback" in msg for msg in logs.output)
)
_, callbacks_in_fit = model.seen_in_fit[0]
self.assertNotIn(throughput_cb, callbacks_in_fit)
self.assertIn(other_cb, callbacks_in_fit)

def test_skip_batch_logs_uses_the_zero_sync_list(self):
trainer = _trainer(self._tmpdir, skip_batch_logs=True)
model = _DummyModel()
Expand Down
64 changes: 42 additions & 22 deletions recml/core/utils/keras_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2130,12 +2130,14 @@ class _TokenThroughputCallback(MetricsCallback):
In unpacked runs each row holds one example (`examples_per_row = 1`), so
`examples_per_step == global_batch_size` and `valid_row_seq_len ==
valid_seq_len`. In batch-packed runs, `global_batch_size` is the number of
packed sequence rows per step while `valid_seq_len_key` is still normalized
per example (user); pass `examples_per_row` (or `examples_per_step_key` when
the packed example count varies per step) so `examples_per_sec_per_device`,
`k_valid_tokens_per_sec_per_device`, and `packing_efficiency_pct` reflect the
packed examples while `k_tokens_per_sec_per_device` reflects the emitted
padded rows.
packed sequence rows per step; pass `examples_per_row` (or
`examples_per_step_key` when the packed example count varies per step) so
`examples_per_sec_per_device` reflects the packed examples while
`k_tokens_per_sec_per_device` reflects the emitted padded rows. When the
number of examples packed per row varies across steps, pass a per-row valid
token metric with `valid_seq_len_per_row=True` so `valid_row_seq_len` is read
directly instead of multiplying a per-example mean by `examples_per_step`
(which suffers ratio-of-means inflation when row counts vary).

`k_valid / k_tokens == packing_efficiency_pct / 100` by construction. So the
token and packing metrics have only two degrees of freedom, and the fact that
Expand All @@ -2150,15 +2152,20 @@ class _TokenThroughputCallback(MetricsCallback):
startup or upon recovery after a preemption) therefore includes JIT
compilation time and reads lower than steady-state windows.

The callback never reads `logs` in its batch hooks and sets `async_safe`.
Thus Keras can keep dispatching batch callbacks asynchronously. Without
`async_safe`, one callback with a batch hook makes Keras convert all the
step logs to Python floats on the main thread on every step, which blocks
The callback never reads `logs` in its batch hooks and sets `async_safe` and
`requires_batch_logs = False`. Thus standard Keras `CallbackList` can keep
dispatching batch callbacks asynchronously, and
`KerasTrainer(skip_batch_logs=True)` continues to skip per-step host
conversions of `logs` (running batch hooks synchronously with `logs=None`).
Without `async_safe`, one callback with a batch hook makes Keras convert all
the step logs to Python floats on the main thread on every step, which blocks
the accelerator.

Subclasses select the Keras hooks that open and close the window.
"""

requires_batch_logs: bool = False

def __init__(
self,
*,
Expand All @@ -2168,6 +2175,7 @@ def __init__(
device_count: int | None = None,
examples_per_row: int = 1,
examples_per_step_key: str | None = None,
valid_seq_len_per_row: bool = False,
):
"""Initializes the callback.

Expand All @@ -2176,7 +2184,8 @@ def __init__(
(equals examples per step when `examples_per_row == 1`).
padded_seq_len: Padded sequence length of one row.
valid_seq_len_key: Key of the model metric that holds the mean number of
non-padding tokens per example. A per-batch sum gives wrong values. If
non-padding tokens per example (or per sequence row when
`valid_seq_len_per_row=True`). A per-batch sum gives wrong values. If
the result is out of range, the token metrics are skipped and an error
is logged.
device_count: Global accelerator count. If None, it is read from
Expand All @@ -2188,6 +2197,10 @@ def __init__(
examples_per_step_key: Optional key in `logs` holding the mean number of
examples processed per step over the window (for dynamic batch packing
that drops or carries over examples).
valid_seq_len_per_row: Whether `valid_seq_len_key` already measures the
mean valid tokens per sequence row instead of per example. Set to True
for dynamic batch packing where the number of examples per row varies
across steps.
"""
super().__init__()
self.async_safe = True
Expand All @@ -2205,6 +2218,7 @@ def __init__(
"examples_per_row", examples_per_row
)
self._examples_per_step_key = examples_per_step_key
self._valid_seq_len_per_row = valid_seq_len_per_row
self._window_start = 0.0
self._steps = 0
self._warned_missing_key = False
Expand Down Expand Up @@ -2264,20 +2278,25 @@ def _close_window(self, logs: dict[str, Any] | None) -> None:
examples_per_step = float(
self._global_batch_size * self._examples_per_row
)
valid_row_seq_len = (
valid_seq_len * examples_per_step / self._global_batch_size
)
if self._valid_seq_len_per_row:
valid_row_seq_len = valid_seq_len
else:
valid_row_seq_len = (
valid_seq_len * examples_per_step / self._global_batch_size
)
packing_efficiency_pct = valid_row_seq_len / self._padded_seq_len * 100.0
if not 0.0 <= packing_efficiency_pct <= 100.0:
# Do not stop a long training job because of a logging metric, and do
# not write values that are wrong by a factor of the batch size.
unit = "per-row" if self._valid_seq_len_per_row else "per-example"
logging.error(
"%s: packing_efficiency_pct=%.1f is not in [0, 100]. %s is probably"
" a per-batch sum, not a per-example mean. Throughput metrics are"
" a per-batch sum, not a %s mean. Throughput metrics are"
" skipped.",
type(self).__name__,
packing_efficiency_pct,
self._valid_seq_len_key,
unit,
)
return
# This metric has no time term, so record it even without a step rate.
Expand Down Expand Up @@ -2305,7 +2324,7 @@ def _close_window(self, logs: dict[str, Any] | None) -> None:
self._record(
logs,
"throughput/k_valid_tokens_per_sec_per_device",
examples_per_sec_per_device * valid_seq_len / 1000.0,
rows_per_sec_per_device * valid_row_seq_len / 1000.0,
)
self._record(
logs,
Expand All @@ -2319,14 +2338,15 @@ class TrainThroughputCallback(_TokenThroughputCallback):

The window starts in `on_epoch_begin` and ends in `on_epoch_end`, i.e. it
covers `steps_per_loop` steps. In-fit validation (`model.fit(
validation_data=...)` or `KerasTrainer.train_and_evaluate`) is not supported
and raises a `ValueError`: production runs train and evaluate in separate
jobs, and the JAX `fit` loop does not wait for pending train steps before
validation starts, so the window could not exclude validation time.
validation_data=...)`) is not supported and raises a `ValueError`: production
runs train and evaluate in separate jobs, and the JAX `fit` loop does not
wait for pending train steps before validation starts, so the window could
not exclude validation time. `KerasTrainer.train_and_evaluate` skips this
callback with a warning.

See `_TokenThroughputCallback.__init__` for constructor arguments
(`global_batch_size`, `padded_seq_len`, `valid_seq_len_key`, `device_count`,
`examples_per_row`, `examples_per_step_key`).
`examples_per_row`, `examples_per_step_key`, `valid_seq_len_per_row`).
"""

def on_epoch_begin(
Expand Down Expand Up @@ -2362,7 +2382,7 @@ class EvalThroughputCallback(_TokenThroughputCallback):

See `_TokenThroughputCallback.__init__` for constructor arguments
(`global_batch_size`, `padded_seq_len`, `valid_seq_len_key`, `device_count`,
`examples_per_row`, `examples_per_step_key`).
`examples_per_row`, `examples_per_step_key`, `valid_seq_len_per_row`).
"""

def on_test_begin(self, logs: dict[str, Any] | None = None) -> None:
Expand Down
59 changes: 58 additions & 1 deletion recml/core/utils/keras_utils_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2711,17 +2711,20 @@ def _throughput_callback(
*,
global_batch_size: int = _GLOBAL_BATCH_SIZE,
padded_seq_len: int = _PADDED_SEQ_LEN,
valid_seq_len_key: str = _SEQ_LEN_KEY,
device_count: int | None = _DEVICE_COUNT,
examples_per_row: int = 1,
examples_per_step_key: str | None = None,
valid_seq_len_per_row: bool = False,
):
return callback_cls(
global_batch_size=global_batch_size,
padded_seq_len=padded_seq_len,
valid_seq_len_key=_SEQ_LEN_KEY,
valid_seq_len_key=valid_seq_len_key,
device_count=device_count,
examples_per_row=examples_per_row,
examples_per_step_key=examples_per_step_key,
valid_seq_len_per_row=valid_seq_len_per_row,
)


Expand Down Expand Up @@ -2855,6 +2858,60 @@ def test_is_async_safe(self):

self.assertTrue(callback.async_safe)

def test_does_not_require_batch_logs(self):
# Otherwise `ZeroSyncCallbackList` (`skip_batch_logs=True`) converts the
# step logs to Python floats on every step during training.
callback = _throughput_callback(keras_utils.TrainThroughputCallback)

self.assertFalse(callback.requires_batch_logs)

def test_valid_seq_len_per_row_with_dynamic_examples_per_step(self):
# 8 packed rows/step of length 24 across 4 devices, 10 steps in 5s =
# 4 rows/sec/device. Dynamic packing placed 28 examples/step (14 examples/
# sec/device) while filling 100% of each row (24 valid tokens/row).
logs = {
"packing/row_seq_len": 24.0,
"packing/users_placed": 28.0,
}
callback = _throughput_callback(
keras_utils.TrainThroughputCallback,
global_batch_size=8,
padded_seq_len=24,
valid_seq_len_key="packing/row_seq_len",
device_count=4,
examples_per_row=4,
examples_per_step_key="packing/users_placed",
valid_seq_len_per_row=True,
)

_run_train_epoch(callback, logs)

self.assertAlmostEqual(logs["throughput/examples_per_sec_per_device"], 14.0)
self.assertAlmostEqual(
logs["throughput/k_valid_tokens_per_sec_per_device"], 0.096
)
self.assertAlmostEqual(
logs["throughput/k_tokens_per_sec_per_device"], 0.096
)
self.assertAlmostEqual(logs["throughput/packing_efficiency_pct"], 100.0)

def test_valid_seq_len_per_row_skips_out_of_range_values(self):
logs = {"packing/row_seq_len": 48.0}
callback = _throughput_callback(
keras_utils.TrainThroughputCallback,
global_batch_size=8,
padded_seq_len=24,
valid_seq_len_key="packing/row_seq_len",
device_count=4,
valid_seq_len_per_row=True,
)

with self.assertLogs(level="ERROR") as log:
_run_train_epoch(callback, logs)

self.assertIn("per-row mean", log.output[0])
self.assertEmpty(callback.latest_metrics)

def test_step_count_comes_from_keras_end_step(self):
# One batch end with end step 99 means that 100 steps completed. This is
# what happens when `steps_per_execution` is more than one.
Expand Down
Loading