Skip to content

Add ability to use built-in pickle for saving AutoMLSearch #2463

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

Merged
merged 10 commits into from
Jul 7, 2021
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
1 change: 1 addition & 0 deletions docs/source/release_notes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ Release Notes
* Added support for showing a Individual Conditional Expectations plot when graphing Partial Dependence :pr:`2386`
* Exposed ``thread_count`` for Catboost estimators as ``n_jobs`` parameter :pr:`2410`
* Updated Objectives API to allow for sample weighting :pr:`2433`
* Added ability to use built-in pickle for saving AutoMLSearch :pr:`2463`
* Fixes
* Deleted unreachable line from ``IterativeAlgorithm`` :pr:`2464`
* Changes
Expand Down
28 changes: 24 additions & 4 deletions evalml/automl/automl_search.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import copy
import pickle
import sys
import time
import traceback
Expand Down Expand Up @@ -1307,31 +1308,50 @@ def best_pipeline(self):

return self._best_pipeline

def save(self, file_path, pickle_protocol=cloudpickle.DEFAULT_PROTOCOL):
def save(
self,
file_path,
pickle_type="cloudpickle",
pickle_protocol=cloudpickle.DEFAULT_PROTOCOL,
):
"""Saves AutoML object at file path

Arguments:
file_path (str): location to save file
pickle_type {"pickle", "cloudpickle"}: the pickling library to use.
pickle_protocol (int): the pickle data stream format.

Returns:
None
"""
if pickle_type == "cloudpickle":
pkl_lib = cloudpickle
elif pickle_type == "pickle":
pkl_lib = pickle
else:
raise ValueError(
f"`pickle_type` must be either 'pickle' or 'cloudpickle'. Received {pickle_type}"
)

with open(file_path, "wb") as f:
cloudpickle.dump(self, f, protocol=pickle_protocol)
pkl_lib.dump(self, f, protocol=pickle_protocol)
Copy link
Contributor

Choose a reason for hiding this comment

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

What if the user uses a cloudpickle protocol while trying to use pickle? 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Apparently cloudpickles can be opened by the regular pickling library (according to their example on their README.md and the doc string for cloudpickle.py in the attached screenshot)! I didn't know this before so that's pretty neat.

image

Copy link
Contributor

Choose a reason for hiding this comment

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

So cool 🤩


@staticmethod
def load(file_path):
def load(
file_path,
pickle_type="cloudpickle",
):
"""Loads AutoML object at file path

Arguments:
file_path (str): location to find file to load
pickle_type {"pickle", "cloudpickle"}: the pickling library to use. Currently not used since the standard pickle library can handle cloudpickles.

Returns:
AutoSearchBase object
"""
with open(file_path, "rb") as f:
return cloudpickle.load(f)
return pickle.load(f)
Copy link
Contributor

Choose a reason for hiding this comment

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

So we can save with cloudpickle and read with pickle?! Wow, I had no idea that works hehe.

I feel like we should accept an argument here for the "pickle type"? Feels weird to offer a choice of library for save but not respect that in load. Not blocking though.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Hmm yeah I agree, it does feel symmetrical to do so. I think it would be a no-op though since it looks like the doc for cloudpickle just recommends using the standard python pickler for loading.


def train_pipelines(self, pipelines):
"""Train a list of pipelines on the training data.
Expand Down
1 change: 1 addition & 0 deletions evalml/automl/pipeline_search_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def __init__(self, results, objective):
self.best_score_by_iter_fig = self._go.FigureWidget(data, layout)
self.best_score_by_iter_fig.update_layout(showlegend=False)
self.update(results, objective)
self._go = None

def update(self, results, objective):
if len(results["search_order"]) > 0 and len(results["pipeline_results"]) > 0:
Expand Down
64 changes: 40 additions & 24 deletions evalml/tests/automl_tests/test_automl.py
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,8 @@ def test_automl_allowed_component_graphs_algorithm(
assert actual.parameters == expected.parameters


def test_automl_serialization(X_y_binary, tmpdir):
@pytest.mark.parametrize("pickle_type", ["cloudpickle", "pickle", "invalid"])
def test_automl_serialization(pickle_type, X_y_binary, tmpdir):
X, y = X_y_binary
path = os.path.join(str(tmpdir), "automl.pkl")
num_max_iterations = 5
Expand All @@ -663,35 +664,50 @@ def test_automl_serialization(X_y_binary, tmpdir):
n_jobs=1,
)
automl.search()
automl.save(path)
loaded_automl = automl.load(path)

for i in range(num_max_iterations):
assert (
automl.get_pipeline(i).__class__ == loaded_automl.get_pipeline(i).__class__
)
assert (
automl.get_pipeline(i).parameters
== loaded_automl.get_pipeline(i).parameters
if automl.search_iteration_plot:
# Testing pickling of SearchIterationPlot object
automl.search_iteration_plot = automl.plot.search_iteration_plot(
interactive_plot=True
)

for id_, pipeline_results in automl.results["pipeline_results"].items():
loaded_ = loaded_automl.results["pipeline_results"][id_]
for name in pipeline_results:
# Use np to check percent_better_than_baseline because of (possible) nans
if name == "percent_better_than_baseline_all_objectives":
for objective_name, value in pipeline_results[name].items():
if pickle_type == "invalid":
with pytest.raises(
ValueError,
match="`pickle_type` must be either 'pickle' or 'cloudpickle'. Received invalid",
):
automl.save(path, pickle_type=pickle_type)
else:
automl.save(path, pickle_type=pickle_type)
loaded_automl = automl.load(path)

for i in range(num_max_iterations):
assert (
automl.get_pipeline(i).__class__
== loaded_automl.get_pipeline(i).__class__
)
assert (
automl.get_pipeline(i).parameters
== loaded_automl.get_pipeline(i).parameters
)

for id_, pipeline_results in automl.results["pipeline_results"].items():
loaded_ = loaded_automl.results["pipeline_results"][id_]
for name in pipeline_results:
# Use np to check percent_better_than_baseline because of (possible) nans
if name == "percent_better_than_baseline_all_objectives":
for objective_name, value in pipeline_results[name].items():
np.testing.assert_almost_equal(
value, loaded_[name][objective_name]
)
elif name == "percent_better_than_baseline":
np.testing.assert_almost_equal(
value, loaded_[name][objective_name]
pipeline_results[name], loaded_[name]
)
elif name == "percent_better_than_baseline":
np.testing.assert_almost_equal(
pipeline_results[name], loaded_[name]
)
else:
assert pipeline_results[name] == loaded_[name]
else:
assert pipeline_results[name] == loaded_[name]

pd.testing.assert_frame_equal(automl.rankings, loaded_automl.rankings)
pd.testing.assert_frame_equal(automl.rankings, loaded_automl.rankings)


@patch("cloudpickle.dump")
Expand Down