Skip to content

[Train] Allow DataParallelTrainer's train_fn to return data - #62021

Merged
matthewdeng merged 32 commits into
ray-project:masterfrom
pseudo-rnd-thoughts:train-973
Apr 28, 2026
Merged

matthewdeng merged 32 commits into
ray-project:masterfrom
pseudo-rnd-thoughts:train-973

Conversation

@pseudo-rnd-thoughts

@pseudo-rnd-thoughts pseudo-rnd-thoughts commented Mar 24, 2026 •

Copy link
Copy Markdown
Member

Description

Ray Train's Trainer has no mechanism for train functions to return data directly — the only way to extract results is via ray.train.report with metrics or checkpoints. This is unnecessarily limiting for any distributed function that needs to return output to the caller (e.g. validation, inference, feature extraction).

This PR adds a return_value attribute to Result, populated from worker 0's return value, mirroring how ray.train.report metrics only capture worker 0's data.

Example use case: distributed validation

A common pattern is running a DataParallelTrainer purely for distributed validation (https://docs.ray.io/en/latest/train/user-guides/asynchronous-validation.html#write-a-distributed-validation-function). Previously, returning a score required a dummy checkpoint report:

# OLD — hacky workaround
ray.train.report(
    metrics={"score": mean_valid_loss.compute().item()},
    checkpoint=ray.train.Checkpoint(
        ray.train.get_context()
        .get_storage()
        .build_checkpoint_path_from_name("placeholder")
    ),
    checkpoint_upload_mode=ray.train.CheckpointUploadMode.NO_UPLOAD,
)

Now the train function can simply return its result:

# New
return {"score": mean_valid_loss.compute().item()}

And the caller accesses it via:

results = trainer.fit()     
return results.return_value  # instead of results.metrics

Changes:

  • Add return_value: Optional[Any] to Result and expand its docstring to cover all attributes
  • Add return_value field to WorkerStatus; populate it from the training thread runner on completion
  • TrainController captures rank-0's return_value and passes it through to Result. Torch tensors aren't supported values.
  • Both local-mode controllers (LocalController, LocalTorchController) capture the train function's return value
  • Update train_loop_per_worker type hints from Callable[[], None] to Callable[[], Any] across all trainers (DataParallel, Torch, JAX, TensorFlow, LightGBM, XGBoost)
  • Three new tests: old report-based approach, new return-based approach, multi-worker isolation (asserts only rank-0's value is captured)
  • Docs: new return_value section in results.rst; asynchronous_validation example updated to the return-based style

Unsupported features

  • The return_value isn't recorded like the checkpoint state so on resumption it isn't recorded (though this should be very rare issue) and Result.from_path("...").return_value is None

@pseudo-rnd-thoughts pseudo-rnd-thoughts added the train Ray Train Related Issue label Mar 24, 2026
@pseudo-rnd-thoughts
pseudo-rnd-thoughts marked this pull request as ready for review March 24, 2026 11:51
@pseudo-rnd-thoughts
pseudo-rnd-thoughts requested a review from a team as a code owner March 24, 2026 11:51

@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 successfully implements the feature allowing DataParallelTrainer's train_fn to return data directly, which is then accessible via result.return_values. This provides a cleaner and more direct way to retrieve metrics from validation functions, moving away from the previous 'hacky' solution involving dummy checkpoints and ray.train.report. The changes are well-implemented across the codebase, including updates to Result and WorkerStatus dataclasses, and the logic in the controller and worker to capture and propagate these return values. The documentation and example code have been updated accordingly, and new tests have been added to validate the new functionality. Overall, this is a valuable improvement for user experience and code clarity.

@TimothySeah TimothySeah 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.

LGTM, thanks!

Mark Towers and others added 2 commits March 25, 2026 09:55
@pseudo-rnd-thoughts pseudo-rnd-thoughts added docs An issue or change related to documentation go add ONLY when ready to merge, run all tests labels Mar 25, 2026
Comment thread python/ray/train/v2/api/result.py Resolved
…nd update `train_loop_per_worker` output from `None` to `Any`

Signed-off-by: Mark Towers <[email protected]>
Mark Towers and others added 4 commits March 27, 2026 15:10
Mark Towers and others added 3 commits April 14, 2026 13:53
# Conflicts:
#	doc/source/train/doc_code/asynchronous_validation.py
#	doc/source/train/user-guides/asynchronous-validation.rst
#	python/ray/train/v2/_internal/execution/controller/controller.py
#	python/ray/train/v2/_internal/execution/worker_group/poll.py
Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
Comment thread python/ray/train/v2/api/result.py Outdated
checkpoint: The latest checkpoint saved by the training function
via :func:`ray.train.report`.
return_value: The value returned by the training function on the
rank-0 worker.

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.

  1. Can you add documentation to the results.rst user guide? Also call out what types of data are supported.
  2. Can you update the description of the PR to be more generalized? Specifically, explain the general use case first for distributed training, and then describe validation as use case.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks for the review,

  1. added documentation to results.rst. For the types of data support, should this be the same as ray.train.report(metrics)'s supported values?
  2. Updated

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@matthewdeng I've added an error for torch tensors and documentation

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.

I think it should be slightly different since these values do not need to be in a dictionary and are not written to disk.

Maybe something like:

The value returned by the user-defined training function on the
rank 0 worker, or ``None`` if no value was returned or if training did not
complete successfully. The return value must be serializable.

Mark Towers added 2 commits April 21, 2026 13:40
Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
Mark Towers added 2 commits April 21, 2026 17:49
Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 902d5b1. Configure here.

Signed-off-by: Mark Towers <[email protected]>
@matthewdeng
matthewdeng merged commit 6f37e6d into ray-project:master Apr 28, 2026
3 checks passed
Lucas61000 pushed a commit to Lucas61000/ray that referenced this pull request May 15, 2026
…project#62021)

## Description
Ray Train's Trainer has no mechanism for train functions to return data
directly — the only way to extract results is via ray.train.report with
metrics or checkpoints. This is unnecessarily limiting for any
distributed function that needs to return output to the caller (e.g.
validation, inference, feature extraction).

This PR adds a return_value attribute to Result, populated from worker
0's return value, mirroring how ray.train.report metrics only capture
worker 0's data.

### Example use case: distributed validation 

A common pattern is running a DataParallelTrainer purely for distributed
validation
(https://docs.ray.io/en/latest/train/user-guides/asynchronous-validation.html#write-a-distributed-validation-function).
Previously, returning a score required a dummy checkpoint report:
```python
# OLD — hacky workaround
ray.train.report(
    metrics={"score": mean_valid_loss.compute().item()},
    checkpoint=ray.train.Checkpoint(
        ray.train.get_context()
        .get_storage()
        .build_checkpoint_path_from_name("placeholder")
    ),
    checkpoint_upload_mode=ray.train.CheckpointUploadMode.NO_UPLOAD,
)
```

Now the train function can simply return its result:
```python
# New
return {"score": mean_valid_loss.compute().item()}
```
And the caller accesses it via:
```python
results = trainer.fit()     
return results.return_value  # instead of results.metrics
```

Changes:
- Add `return_value: Optional[Any]` to `Result` and expand its docstring
to cover all attributes
- Add `return_value` field to `WorkerStatus`; populate it from the
training thread runner on completion
- `TrainController` captures rank-0's `return_value` and passes it
through to `Result`. Torch tensors aren't supported values.
- Both local-mode controllers (`LocalController`,
`LocalTorchController`) capture the train function's return value
- Update `train_loop_per_worker` type hints from `Callable[[], None]` to
`Callable[[], Any]` across all trainers (DataParallel, Torch, JAX,
TensorFlow, LightGBM, XGBoost)
- Three new tests: old report-based approach, new return-based approach,
multi-worker isolation (asserts only rank-0's value is captured)
- Docs: new `return_value` section in results.rst;
asynchronous_validation example updated to the return-based style

Unsupported features
- The `return_value` isn't recorded like the checkpoint state so on
resumption it isn't recorded (though this should be very rare issue) and
`Result.from_path("...").return_value is None`

---------

Signed-off-by: Mark Towers <[email protected]>
Co-authored-by: Mark Towers <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs An issue or change related to documentation go add ONLY when ready to merge, run all tests train Ray Train Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants