The Ax Service API is designed to allow the user to control scheduling of trials and data computation while having an easy to use interface with Ax.
The user iteratively:
import numpy as np
from ax.plot.contour import plot_contour
from ax.plot.trace import optimization_trace_single_method
from ax.service.ax_client import AxClient
from ax.metrics.branin import branin
from ax.utils.measurement.synthetic_functions import hartmann6
from ax.utils.notebook.plotting import render, init_notebook_plotting
init_notebook_plotting()
[INFO 04-30 17:13:15] ipy_plotting: Injecting Plotly library into cell. Do not overwrite or delete cell.
Create a client object to interface with Ax APIs. By default this runs locally without storage.
ax_client = AxClient()
An experiment consists of a search space (parameters and parameter constraints) and optimization configuration (objective name, minimization setting, and outcome constraints). Note that:
name
, parameters
, and objective_name
arguments are required.parameters
have the following required keys: "name" - parameter name, "type" - parameter type ("range", "choice" or "fixed"), "bounds" for range parameters, "values" for choice parameters, and "value" for fixed parameters.parameters
can optionally include "value_type" ("int", "float", "bool" or "str"), "log_scale" flag for range parameters, and "is_ordered" flag for choice parameters.parameter_constraints
should be a list of strings of form "p1 >= p2" or "p1 + p2 <= some_bound".outcome_constraints
should be a list of strings of form "constrained_metric <= some_bound".ax_client.create_experiment(
name="hartmann_test_experiment",
parameters=[
{
"name": "x1",
"type": "range",
"bounds": [0.0, 1.0],
"value_type": "float", # Optional, defaults to inference from type of "bounds".
"log_scale": False, # Optional, defaults to False.
},
{
"name": "x2",
"type": "range",
"bounds": [0.0, 1.0],
},
{
"name": "x3",
"type": "range",
"bounds": [0.0, 1.0],
},
{
"name": "x4",
"type": "range",
"bounds": [0.0, 1.0],
},
{
"name": "x5",
"type": "range",
"bounds": [0.0, 1.0],
},
{
"name": "x6",
"type": "range",
"bounds": [0.0, 1.0],
},
],
objective_name="hartmann6",
minimize=True, # Optional, defaults to False.
parameter_constraints=["x1 + x2 <= 2.0"], # Optional.
outcome_constraints=["l2norm <= 1.25"], # Optional.
)
[INFO 04-30 17:13:15] ax.service.utils.dispatch: Using Bayesian Optimization generation strategy. Iterations after 6 will take longer to generate due to model-fitting.
When using Ax a service, evaluation of parameterizations suggested by Ax is done either locally or, more commonly, using an external scheduler. Below is a dummy evaluation function that outputs data for two metrics "hartmann6" and "l2norm". Note that all returned metrics correspond to either the objective_name
set on experiment creation or the metric names mentioned in outcome_constraints
.
def evaluate(parameters):
x = np.array([parameters.get(f"x{i+1}") for i in range(6)])
# In our case, standard error is 0, since we are computing a synthetic function.
return {"hartmann6": (hartmann6(x), 0.0), "l2norm": (np.sqrt((x ** 2).sum()), 0.0)}
With the experiment set up, we can start the optimization loop.
At each step, the user queries the client for a new trial then submits the evaluation of that trial back to the client.
Note that Ax auto-selects an appropriate optimization algorithm based on the search space. For more advance use cases that require a specific optimization algorithm, pass a generation_strategy
argument into the AxClient
constructor. Note that when Bayesian Optimization is used, generating new trials may take a few minutes.
for i in range(30):
print(f"Running trial {i+1}/30...")
parameters, trial_index = ax_client.get_next_trial()
# Local evaluation here can be replaced with deployment to external system.
ax_client.complete_trial(trial_index=trial_index, raw_data=evaluate(parameters))
Running trial 1/20... Running trial 2/20... Running trial 3/20... Running trial 4/20... Running trial 5/20... Running trial 6/20... Running trial 7/20... Running trial 8/20... Running trial 9/20... Running trial 10/20... Running trial 11/20... Running trial 12/20... Running trial 13/20... Running trial 14/20... Running trial 15/20... Running trial 16/20... Running trial 17/20... Running trial 18/20... Running trial 19/20... Running trial 20/20... Running trial 21/20... Running trial 22/20... Running trial 23/20... Running trial 24/20... Running trial 25/20... Running trial 26/20... Running trial 27/20... Running trial 28/20... Running trial 29/20... Running trial 30/20...
Once it's complete, we can access the best parameters found, as well as the corresponding metric values.
best_parameters, values = ax_client.get_best_parameters()
best_parameters
{'x1': 0.39701823676595277, 'x2': 0.8948757193572878, 'x3': 0.2584762420738021, 'x4': 0.5789701416180112, 'x5': 0.3660583998299098, 'x6': 0.03838514696083803}
means, covariances = values
means
{'l2norm': 1.2230752760166403, 'hartmann6': -3.1190980253607856}
For comparison, Hartmann6 minimum:
hartmann6.fmin
-3.32237
Here we arbitrarily select "x1" and "x2" as the two parameters to plot for "hartmann6". The remainder of the parameters will be fixed at the middle of their range, 0.5.
render(
plot_contour(
model=ax_client.generation_strategy.model, param_x='x1', param_y='x2', metric_name='hartmann6'
)
)
We can also plot the optimization trace, showing the progression of finding the point with the optimal objective:
# `plot_single_method` expects a 2-d array of means, because it expects to average means from multiple
# optimization runs, so we wrap out best objectives array in another array.
best_objectives = np.array([[trial.objective_mean for trial in ax_client.experiment.trials.values()]])
best_objective_plot = optimization_trace_single_method(
y=np.minimum.accumulate(best_objectives, axis=1),
optimum=hartmann6.fmin,
title="Model performance vs. # of iterations",
ylabel="Hartmann6",
)
render(best_objective_plot)
Evaluation failure: should any optimization iterations fail during evaluation, log_trial_failure
will ensure that the same trial is not proposed again.
ax_client.log_trial_failure(trial_index=trial_index)
Adding custom trials: should there be need to evaluate a specific parameterization, attach_trial
will add it to the experiment.
ax_client.attach_trial(
parameters={"x1": 0.9, "x2": 0.9, "x3": 0.9, "x4": 0.9, "x5": 0.9, "x6": 0.9}
)
({'x1': 0.9, 'x2': 0.9, 'x3': 0.9, 'x4': 0.9, 'x5': 0.9, 'x6': 0.9}, 31)
Need to run many trials in parallel: for optimal results and optimization efficiency, we strongly recommend sequential optimization (generating a few trials, then waiting for them to be completed with evaluation data). However, if your use case strictly requires dispatch of many trials in parallel before they are updated with data and you are running into the "All trials for current model have been generated, but not enough data has been observed to fit next model" error, instantiate AxClient
as AxClient(enforce_sequential_optimization=False
.