Repository navigation
[Train][Data] Fix double step count with TF MultiWorkerMirroredStrategy and pre-sharded dataset - #65762
[Train][Data] Fix double step count with TF MultiWorkerMirroredStrategy and pre-sharded dataset#65762lorenzozanee wants to merge 2 commits into
Conversation
…gy and pre-sharded dataset When using TensorflowTrainer with MultiWorkerMirroredStrategy and a pre-sharded Ray Dataset via train.get_dataset_shard, the per-epoch step count was double the expected value (66 vs 33 for 2000 rows, 2 workers, batch 31). The Ray shard already partitions the data, but the TF dataset was not consistently marked as pre-sharded, allowing the distribution strategy to re-partition and double-count. Make DataIterator.to_tf consistent with prepare_dataset_shard by disabling auto-sharding and prefetching, and clarify the sharding contract in DataConfig. Fixes #61838 Signed-off-by: lorenzozanee <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request updates TensorFlow dataset handling for pre-sharded Ray datasets to prevent auto-sharding issues under MultiWorkerMirroredStrategy, adding explanatory comments and appending .prefetch(tf.data.AUTOTUNE) in iterator.py. Feedback highlights that adding .prefetch(tf.data.AUTOTUNE) here causes redundant double prefetching when combined with prepare_dataset_shard, leading to unnecessary memory overhead and background threads.
| # already receives a disjoint shard (n_rows / n_workers). If TF were to | ||
| # re-shard the dataset, the effective step count would double | ||
| # (e.g., 33 -> 66 for 2000 rows, 2 workers, batch 31). See #61838. | ||
| return dataset.with_options(options).prefetch(tf.data.AUTOTUNE) |
There was a problem hiding this comment.
Calling prepare_dataset_shard on the output of to_tf() is explicitly recommended in the docstring of prepare_dataset_shard. However, since to_tf() now automatically appends .prefetch(tf.data.AUTOTUNE) and prepare_dataset_shard also appends .prefetch(tf.data.AUTOTUNE), using them together as recommended will result in redundant double prefetching.
This double prefetching can lead to unnecessary memory overhead and extra background threads. Consider removing .prefetch(tf.data.AUTOTUNE) from to_tf() and letting prepare_dataset_shard handle the prefetching for Ray Train users, or update the documentation to clarify that prepare_dataset_shard is redundant when using to_tf().
| return dataset.with_options(options).prefetch(tf.data.AUTOTUNE) | |
| return dataset.with_options(options) |
…gy and pre-sharded dataset When using TensorflowTrainer with MultiWorkerMirroredStrategy and a pre-sharded Ray Dataset via train.get_dataset_shard, the per-epoch step count was double the expected value (66 vs 33 for 2000 rows, 2 workers, batch 31). The Ray shard already partitions the data, but the TF dataset was not consistently marked as pre-sharded, allowing the distribution strategy to re-partition and double-count. Make DataIterator.to_tf consistent with prepare_dataset_shard by disabling auto-sharding and prefetching, and clarify the sharding contract in DataConfig. Fixes #61838 Signed-off-by: lorenzozanee <[email protected]>
Jokasa7
left a comment
There was a problem hiding this comment.
The TensorFlow symptom is narrow, but the equal=True change is made in Ray Train's shared DataConfig. That is the default configuration of DataParallelTrainer, including non-TensorFlow subclasses and direct/custom trainer use.
On this exact head, Dataset.streaming_split documents that equal=True guarantees equal row counts by dropping data when necessary, and OutputSplitter.all_inputs_done() explicitly drains the truncated remainder after allocating remainder // world_size rows per output. A five-row dataset split across two ordinary Torch or custom workers therefore changes from consuming all five rows to silently consuming four. No TensorFlow strategy or to_tf() call is involved in those paths, so this is a cross-backend data-loss regression introduced by a TensorFlow-specific fix. The existing automated review only discusses duplicate prefetching.
Please scope equalized splitting to the TensorFlow path that requires synchronized step counts (or use a TensorFlow-specific data configuration), keep the shared default lossless, and add a non-TensorFlow regression asserting that all input rows remain observable.
| # dataset and double the step count (see #61838). | ||
| for i, split in enumerate( | ||
| ds.streaming_split( | ||
| world_size, equal=True, locality_hints=locality_hints |
There was a problem hiding this comment.
[P1] This changes the shared DataConfig used by every DataParallelTrainer, not only TensorflowTrainer. Dataset.streaming_split(equal=True) explicitly drops rows that cannot be divided evenly, and OutputSplitter drains that truncated remainder. For example, five rows with two Torch or custom workers now silently train on four rows, whereas the previous equal=False path preserved all five. Please keep the common split lossless and scope equalization to the TensorFlow/MultiWorker path that needs identical step counts (or use a TensorFlow-specific data config), with a non-TensorFlow regression that sums the rows observed across workers.
…es (#68006) ## Description With `tf.distribute.MultiWorkerMirroredStrategy`, the batch size of the dataset passed to `model.fit()` is the global batch size, and TensorFlow splits each batch evenly across the workers. Several Ray Train TensorFlow examples passed the per-worker batch size to `Dataset.to_tf()` or `iter_tf_batches()` instead. With 2 workers, every step then processes half the configured batch per worker, so Keras reports twice as many steps per epoch as expected (#61838). Ray's data split isn't actually the reason; each worker's shard has the expected number of batches. The Train guide's Step 2 already says to set the dataset's batch size to the per-worker batch size times the number of workers, and `tensorflow_mnist_example.py` already does so. These didn't: - `doc/source/train/doc_code/tf_starter.py`, the code shown on the TensorFlow guide page - `python/ray/train/examples/tf/tensorflow_regression_example.py` - `python/ray/train/examples/tf/tensorflow_autoencoder_example.py` Each now computes `global_batch_size = per_worker_batch_size * train.get_context().get_world_size()` and passes it to the dataset. In `doc/source/train/distributed-tensorflow-keras.md`, the Step 2 diff uses the same variable names as the example, and the inline sample, which hard-coded `batch_size=64`, uses the global batch size too. A new test, `test_tensorflow_dataset_batch_size_is_global` in `python/ray/train/tests/test_tensorflow_trainer.py`, runs a `TensorflowTrainer` with 1 and 2 workers and checks that Keras runs `rows_per_worker // per_worker_batch_size` steps in an epoch when the dataset uses the global batch size. Measured effect (200 rows for `tf_starter.py`, 2 workers, per-worker batch size 32; regression example with `--smoke-test`): | Example | Keras steps per epoch before | after | |---|---|---| | `tf_starter.py` | 8 | 4 (= ⌈100 ÷ 32⌉) | | `tensorflow_regression_example.py` | 400 | 200 | ## Related issues Fixes #61838 ## Additional information **Requested on the issue:** `pseudo-rnd-thoughts` asked for a doc PR with a test to confirm this works as expected. **Not a duplicate:** no open PR references #61838 or changes these files. The two earlier attempts, #65762 and #66189 (both closed as stale), changed Ray Train's data configuration. This PR changes only the examples, the guide, and adds a test, because the step count comes from how TensorFlow treats the batch size, not from how Ray splits the data. **Tests** (Ray 2.59.0, macOS, Python 3.12, TensorFlow 2.21 with `tf-keras`, `TF_USE_LEGACY_KERAS=1`): ``` python -m pytest test_tensorflow_trainer.py -k batch_size_is_global 2 passed # num_workers = 1 and 2 ``` As a negative control, passing the per-worker batch size instead (the old examples' behavior) fails the 2-worker case with `assert 20 == (160 // 16)`: twice the expected steps. The 1-worker case passes either way. I ran the examples before and after the change to get the table above. The test file and the regression example skip themselves on Python 3.12, because TensorFlow isn't installed there in CI. I ran copies with that guard removed, so CI is the first run of the actual files. I didn't run `tensorflow_autoencoder_example.py`, which downloads image data and has no CI test target; I checked that it compiles and passes the linters. The inline sample in the guide is a `{testcode}` block that only defines `train_func`, so the new `get_world_size()` call doesn't execute during the docs doctest. `pre-commit run --files` on all five changed files passes. AI assistance (Claude Code) was used for this change. --------- Signed-off-by: miggle711 <[email protected]>
Description
When using
TensorflowTrainerwithMultiWorkerMirroredStrategyand a pre-sharded Ray Dataset, the per-epoch step count was double the expected value. This change ensures the TF dataset is consistently marked as pre-sharded to prevent re-partitioning by the distribution strategy.Related issues
Fixes #61838
Additional information
N/A