Skip to content

[Train][Data] Fix double step count with TF MultiWorkerMirroredStrategy and pre-sharded dataset - #66189

Closed
lorenzozanee wants to merge 1 commit into
ray-project:masterfrom
lorenzozanee:restore/pr-65762
Closed

lorenzozanee wants to merge 1 commit into
ray-project:masterfrom
lorenzozanee:restore/pr-65762

Conversation

@lorenzozanee

Copy link
Copy Markdown

Description

When using TensorflowTrainer with MultiWorkerMirroredStrategy and 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

Supercedes #65762(原PR分支已删,按原提交重建)

@lorenzozanee
lorenzozanee requested review from a team as code owners September 15, 2026 22:45

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces the write_orc method to Dataset to support writing datasets to ORC files, and updates to_tf to return a prefetched dataset with disabled auto-sharding to prevent double-sharding issues when using TensorFlow's MultiWorkerMirroredStrategy. Feedback on these changes includes a recommendation to replace a lambda assignment with a local function definition in write_orc to comply with PEP 8 (E731), as well as minor suggestions to correct a typo and remove redundant phrasing in the write_orc docstrings.

Comment on lines +5759 to +5760
if arrow_orc_args_fn is None:
arrow_orc_args_fn = lambda: {} # noqa: E731

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

According to PEP 8 (E731), do not assign a lambda expression to an identifier. Use a local function definition (def) instead to improve readability and traceback support.

Suggested change
if arrow_orc_args_fn is None:
arrow_orc_args_fn = lambda: {} # noqa: E731
if arrow_orc_args_fn is None:
def arrow_orc_args_fn():
return {}
References
  1. PEP 8: Do not assign a lambda expression, use a def. (link)

"""Writes the :class:`~ray.data.Dataset` to ORC files.

The number of files is determined by the number of blocks in the dataset.
To control the number of number of blocks, call

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

There is a minor typo in the docstring: "number of number of blocks". It should be "number of blocks".

Suggested change
To control the number of number of blocks, call
To control the number of blocks, call

Comment on lines +5718 to +5719
try_create_dir: If ``True``, attempts to create all directories in the
destination path if ``True``. Does nothing if all directories already

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The description for try_create_dir is redundant ("if True ... if True"). Let's simplify it for clarity.

Suggested change
try_create_dir: If ``True``, attempts to create all directories in the
destination path if ``True``. Does nothing if all directories already
try_create_dir: If ``True``, attempts to create all directories in the
destination path. Does nothing if all directories already

@ray-gardener ray-gardener Bot added train Ray Train Related Issue data Ray Data-related issues community-contribution Contributed by the community labels Sep 16, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Sep 30, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

Please feel free to reopen or open a new pull request if you'd still like this to be addressed.

Again, you can always ask for help on our discussion forum or Ray's public slack channel.

Thanks again for your contribution!

@github-actions github-actions Bot closed this Oct 15, 2026
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 11, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community data Ray Data-related issues stale The issue is stale. It will be closed within 7 days unless there are further conversation train Ray Train Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Train] Step Count Discrepancy in Ray Train + TensorFlow with MultiWorkerMirroredStrategy

1 participant