Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Train] Add support for metrics aggregation #22099

Merged
merged 23 commits into from
Mar 8, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
10 changes: 9 additions & 1 deletion python/ray/train/examples/train_linear_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,20 @@ def train_func(config):
return results


def average_validation_loss(intermediate_results):
worker_results = [worker_result["loss"] for worker_result in intermediate_results]
return np.mean(worker_results)


def train_linear(num_workers=2, use_gpu=False, epochs=3):
trainer = Trainer(backend="torch", num_workers=num_workers, use_gpu=use_gpu)
config = {"lr": 1e-2, "hidden_size": 1, "batch_size": 4, "epochs": epochs}
trainer.start()
results = trainer.run(
train_func, config, callbacks=[JsonLoggerCallback(), TBXLoggerCallback()]
train_func,
config,
callbacks=[JsonLoggerCallback(), TBXLoggerCallback()],
aggregate_funcs=[average_validation_loss],
)
trainer.shutdown()

Expand Down
17 changes: 16 additions & 1 deletion python/ray/train/trainer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import datetime
import collections
import inspect
import logging
import os
Expand Down Expand Up @@ -269,6 +270,7 @@ def run(
dataset: Optional[Union[RayDataset, Dict[str, RayDataset]]] = None,
checkpoint: Optional[Union[Dict, str, Path]] = None,
checkpoint_strategy: Optional[CheckpointStrategy] = None,
aggregate_funcs: Optional[Union[Dict, List]] = None,
) -> List[T]:
"""Runs a training function in a distributed manner.

Expand Down Expand Up @@ -298,6 +300,9 @@ def run(
``None`` then no checkpoint will be loaded.
checkpoint_strategy (Optional[CheckpointStrategy]): The
configurations for saving checkpoints.
aggregate_funcs (Optional[Union[Dict, List]]): The methods
used to aggregate intermediate results returned
by `train.report()` on each worker.

Returns:
A list of results from the training function. Each value in the
Expand Down Expand Up @@ -330,12 +335,22 @@ def run(
checkpoint_strategy=checkpoint_strategy,
run_dir=self.latest_run_dir,
)
aggregated_results = collections.defaultdict(list)
if aggregate_funcs is None or len(aggregate_funcs) == 0:
aggregate_funcs = {}
elif isinstance(aggregate_funcs, list):
aggregate_funcs = {e.__name__: e for e in aggregate_funcs}

for intermediate_result in iterator:
for aggregate_name, func in aggregate_funcs.items():
aggregated_results[aggregate_name].append(func(intermediate_result))
jwyyy marked this conversation as resolved.
Show resolved Hide resolved
for callback in callbacks:
callback.process_results(intermediate_result)

assert iterator.is_finished()
return iterator.get_final_results()
final_results = iterator.get_final_results()
final_results.append(aggregated_results)
jwyyy marked this conversation as resolved.
Show resolved Hide resolved
return final_results
finally:
for callback in callbacks:
callback.finish_training(error=finished_with_errors)
Expand Down