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

[tune] Support tune.with_resources for class methods #28596

Merged
merged 1 commit into from
Sep 19, 2022
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
21 changes: 21 additions & 0 deletions python/ray/tune/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1494,6 +1494,27 @@ def default_resource_request(cls, config):
assert trial.last_result["_metric"] == num_gpus


@pytest.mark.parametrize("num_gpus", [1, 2])
def test_with_resources_class_method(ray_start_2_cpus_2_gpus, num_gpus):
class Worker:
def train_fn(self, config):
return len(ray.get_gpu_ids())

worker = Worker()

[trial] = tune.run(
tune.with_resources(
worker.train_fn,
resources=lambda config: PlacementGroupFactory(
[{"GPU": config["use_gpus"]}]
),
),
config={"use_gpus": num_gpus},
).trials

assert trial.last_result["_metric"] == num_gpus


class SerializabilityTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
Expand Down
26 changes: 25 additions & 1 deletion python/ray/tune/trainable/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import logging
import os
import shutil
import types
from typing import Any, Callable, Dict, Optional, Type, Union, TYPE_CHECKING

import pandas as pd
Expand Down Expand Up @@ -443,8 +444,31 @@ def train(config):
)

if not inspect.isclass(trainable):
if isinstance(trainable, types.MethodType):
# Methods cannot set arbitrary attributes, so we have to wrap them
use_checkpoint = _detect_checkpoint_function(trainable, partial=True)
if use_checkpoint:

def _trainable(config, checkpoint_dir):
return trainable(config, checkpoint_dir=checkpoint_dir)

else:

def _trainable(config):
return trainable(config)

_trainable._resources = pgf
return _trainable

# Just set an attribute. This will be resolved later in `wrap_function()`.
trainable._resources = pgf
try:
trainable._resources = pgf
except AttributeError as e:
raise RuntimeError(
"Could not use `tune.with_resources()` on the supplied trainable. "
"Wrap your trainable in a regular function before passing it "
"to Ray Tune."
) from e
else:

class ResourceTrainable(trainable):
Expand Down