Skip to content

Commit

Permalink
[tune] Raise an error if Tuner.restore() is called on an instance (r…
Browse files Browse the repository at this point in the history
…ay-project#39676)

`Tuner.restore()` is used to construct a `Tuner` object from an existing experiment. However, calling `tuner = Tuner(...); tuner.restore()` is a common misuse of the API and does not throw an error.

This PR updates the `Tuner` class to only allow `restore()` to be called on the class, not on an instance of the class.

Signed-off-by: Kai Fricke <kai@anyscale.com>
  • Loading branch information
krfricke authored Sep 15, 2023
1 parent ba730ce commit 71f0ae7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
15 changes: 15 additions & 0 deletions python/ray/tune/tests/test_tuner.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,21 @@ def to_dict(self) -> dict:
tune.run(trainable, config=CustomConfig())


def test_tuner_restore_classmethod():
tuner = Tuner("PPO")

# Calling `tuner.restore()` on an instance should raise an AttributeError
with pytest.raises(AttributeError):
tuner.restore("/", "PPO")

# Calling `Tuner.restore()` on the class should work. This will throw a
# FileNotFoundError because no checkpoint exists at that location. Since
# this happens in the downstream restoration code, this means that the
# classmethod check successfully passed.
with pytest.raises(FileNotFoundError):
tuner = Tuner.restore("/invalid", "PPO")


if __name__ == "__main__":
import sys

Expand Down
9 changes: 9 additions & 0 deletions python/ray/tune/tuner.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,3 +432,12 @@ def get_results(self) -> ResultGrid:
string_queue,
)
return ray.get(get_results_future)

def __getattribute__(self, item):
if item == "restore":
raise AttributeError(
"`Tuner.restore()` is a classmethod and cannot be called on an "
"instance. Use `tuner = Tuner.restore(...)` to instantiate the "
"Tuner instead."
)
return super().__getattribute__(item)

0 comments on commit 71f0ae7

Please sign in to comment.