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:
from ax.service.ax_client import AxClient
from ax.utils.measurement.synthetic_functions import hartmann6
from ax.utils.notebook.plotting import render, init_notebook_plotting
init_notebook_plotting()
[INFO 11-10 20:25:59] ax.utils.notebook.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()
[INFO 11-10 20:25:59] ax.service.ax_client: Starting optimization with verbose logging. To disable logging, set the `verbose_logging` argument to `False`. Note that float values in the logs are rounded to 6 decimal points.
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 11-10 20:25:59] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x2. If that is not the expected value type, you can explicity specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict. [INFO 11-10 20:25:59] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x3. If that is not the expected value type, you can explicity specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict. [INFO 11-10 20:25:59] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x4. If that is not the expected value type, you can explicity specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict. [INFO 11-10 20:25:59] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x5. If that is not the expected value type, you can explicity specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict. [INFO 11-10 20:25:59] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x6. If that is not the expected value type, you can explicity specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict. [INFO 11-10 20:25:59] ax.service.utils.instantiation: Created search space: SearchSpace(parameters=[RangeParameter(name='x1', parameter_type=FLOAT, range=[0.0, 1.0]), RangeParameter(name='x2', parameter_type=FLOAT, range=[0.0, 1.0]), RangeParameter(name='x3', parameter_type=FLOAT, range=[0.0, 1.0]), RangeParameter(name='x4', parameter_type=FLOAT, range=[0.0, 1.0]), RangeParameter(name='x5', parameter_type=FLOAT, range=[0.0, 1.0]), RangeParameter(name='x6', parameter_type=FLOAT, range=[0.0, 1.0])], parameter_constraints=[ParameterConstraint(1.0*x1 + 1.0*x2 <= 2.0)]). [INFO 11-10 20:25:59] ax.modelbridge.dispatch_utils: Using Bayesian optimization since there are more ordered parameters than there are categories for the unordered categorical parameters. [INFO 11-10 20:25:59] ax.modelbridge.dispatch_utils: Using Bayesian Optimization generation strategy: GenerationStrategy(name='Sobol+GPEI', steps=[Sobol for 12 trials, GPEI for subsequent trials]). Iterations after 12 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
.
import numpy as np
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)}
Result of the evaluation should generally be a mapping of the format: {metric_name -> (mean, SEM)}
. If there is only one metric in the experiment – the objective – then evaluation function can return a single tuple of mean and SEM, in which case Ax will assume that evaluation corresponds to the objective. It can also return only the mean as a float, in which case Ax will treat SEM as unknown and use a model that can infer it.
For more details on evaluation function, refer to the "Trial Evaluation" section in the Ax docs at ax.dev
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(25):
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))
/home/runner/work/Ax/Ax/ax/core/observation.py:274: FutureWarning: In a future version of pandas, a length 1 tuple will be returned when iterating over a groupby with a grouper equal to a list of length 1. Don't supply a list with a single grouper to avoid this warning. [INFO 11-10 20:26:00] ax.service.ax_client: Generated new trial 0 with parameters {'x1': 0.172321, 'x2': 0.517218, 'x3': 0.344523, 'x4': 0.885683, 'x5': 0.140317, 'x6': 0.718026}. [INFO 11-10 20:26:00] ax.service.ax_client: Completed trial 0 with data: {'hartmann6': (-0.046833, 0.0), 'l2norm': (1.317418, 0.0)}. [INFO 11-10 20:26:00] ax.service.ax_client: Generated new trial 1 with parameters {'x1': 0.146472, 'x2': 0.038841, 'x3': 0.088612, 'x4': 0.162793, 'x5': 0.587168, 'x6': 0.875173}. [INFO 11-10 20:26:00] ax.service.ax_client: Completed trial 1 with data: {'hartmann6': (-0.396739, 0.0), 'l2norm': (1.080745, 0.0)}. [INFO 11-10 20:26:00] ax.service.ax_client: Generated new trial 2 with parameters {'x1': 0.809404, 'x2': 0.326209, 'x3': 0.626972, 'x4': 0.082043, 'x5': 0.075042, 'x6': 0.975072}. [INFO 11-10 20:26:00] ax.service.ax_client: Completed trial 2 with data: {'hartmann6': (-0.637356, 0.0), 'l2norm': (1.455256, 0.0)}. [INFO 11-10 20:26:00] ax.service.ax_client: Generated new trial 3 with parameters {'x1': 0.797891, 'x2': 0.250534, 'x3': 0.600155, 'x4': 0.60133, 'x5': 0.228134, 'x6': 0.951364}. [INFO 11-10 20:26:00] ax.service.ax_client: Completed trial 3 with data: {'hartmann6': (-0.48787, 0.0), 'l2norm': (1.54218, 0.0)}. [INFO 11-10 20:26:00] ax.service.ax_client: Generated new trial 4 with parameters {'x1': 0.563197, 'x2': 0.492574, 'x3': 0.968255, 'x4': 0.8177, 'x5': 0.955405, 'x6': 0.813688}. [INFO 11-10 20:26:00] ax.service.ax_client: Completed trial 4 with data: {'hartmann6': (-0.001946, 0.0), 'l2norm': (1.93413, 0.0)}. [INFO 11-10 20:26:00] ax.service.ax_client: Generated new trial 5 with parameters {'x1': 0.421558, 'x2': 0.814971, 'x3': 0.03074, 'x4': 0.127464, 'x5': 0.794167, 'x6': 0.873966}. [INFO 11-10 20:26:00] ax.service.ax_client: Completed trial 5 with data: {'hartmann6': (-0.004945, 0.0), 'l2norm': (1.5012, 0.0)}. [INFO 11-10 20:26:00] ax.service.ax_client: Generated new trial 6 with parameters {'x1': 0.699434, 'x2': 0.047338, 'x3': 0.882242, 'x4': 0.915542, 'x5': 0.973457, 'x6': 0.066844}. [INFO 11-10 20:26:00] ax.service.ax_client: Completed trial 6 with data: {'hartmann6': (-0.000826, 0.0), 'l2norm': (1.749315, 0.0)}. [INFO 11-10 20:26:00] ax.service.ax_client: Generated new trial 7 with parameters {'x1': 0.271127, 'x2': 0.745455, 'x3': 0.913109, 'x4': 0.351518, 'x5': 0.719434, 'x6': 0.180559}. [INFO 11-10 20:26:00] ax.service.ax_client: Completed trial 7 with data: {'hartmann6': (-0.906873, 0.0), 'l2norm': (1.461757, 0.0)}. [INFO 11-10 20:26:00] ax.service.ax_client: Generated new trial 8 with parameters {'x1': 0.218215, 'x2': 0.574428, 'x3': 0.536205, 'x4': 0.252885, 'x5': 0.982586, 'x6': 0.60361}. [INFO 11-10 20:26:00] ax.service.ax_client: Completed trial 8 with data: {'hartmann6': (-0.444431, 0.0), 'l2norm': (1.434877, 0.0)}. [INFO 11-10 20:26:00] ax.service.ax_client: Generated new trial 9 with parameters {'x1': 0.591028, 'x2': 0.222858, 'x3': 0.834184, 'x4': 0.461383, 'x5': 0.65922, 'x6': 0.726995}. [INFO 11-10 20:26:00] ax.service.ax_client: Completed trial 9 with data: {'hartmann6': (-0.15202, 0.0), 'l2norm': (1.50692, 0.0)}. [INFO 11-10 20:26:00] ax.service.ax_client: Generated new trial 10 with parameters {'x1': 0.056185, 'x2': 0.153245, 'x3': 0.349294, 'x4': 0.243428, 'x5': 0.940295, 'x6': 0.918951}. [INFO 11-10 20:26:00] ax.service.ax_client: Completed trial 10 with data: {'hartmann6': (-0.155673, 0.0), 'l2norm': (1.391593, 0.0)}. [INFO 11-10 20:26:00] ax.service.ax_client: Generated new trial 11 with parameters {'x1': 0.902924, 'x2': 0.647648, 'x3': 0.180444, 'x4': 0.34063, 'x5': 0.584432, 'x6': 0.567231}. [INFO 11-10 20:26:00] ax.service.ax_client: Completed trial 11 with data: {'hartmann6': (-0.074036, 0.0), 'l2norm': (1.430601, 0.0)}. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.'), OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.'), OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.'), OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:328: RuntimeWarning: Optimization failed on the second try, after generating a new set of initial conditions. [INFO 11-10 20:26:15] ax.service.ax_client: Generated new trial 12 with parameters {'x1': 0.245593, 'x2': 0.0, 'x3': 0.078957, 'x4': 0.090501, 'x5': 0.390547, 'x6': 0.770684}. [INFO 11-10 20:26:15] ax.service.ax_client: Completed trial 12 with data: {'hartmann6': (-1.347773, 0.0), 'l2norm': (0.906213, 0.0)}. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.'), OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. [INFO 11-10 20:26:27] ax.service.ax_client: Generated new trial 13 with parameters {'x1': 0.278499, 'x2': 0.0, 'x3': 0.082759, 'x4': 0.058813, 'x5': 0.326477, 'x6': 0.74841}. [INFO 11-10 20:26:27] ax.service.ax_client: Completed trial 13 with data: {'hartmann6': (-1.365714, 0.0), 'l2norm': (0.868663, 0.0)}. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. [INFO 11-10 20:26:37] ax.service.ax_client: Generated new trial 14 with parameters {'x1': 0.2416, 'x2': 0.0, 'x3': 0.021506, 'x4': 0.108558, 'x5': 0.352812, 'x6': 0.679172}. [INFO 11-10 20:26:37] ax.service.ax_client: Completed trial 14 with data: {'hartmann6': (-1.611604, 0.0), 'l2norm': (0.810166, 0.0)}. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. [INFO 11-10 20:26:48] ax.service.ax_client: Generated new trial 15 with parameters {'x1': 0.189616, 'x2': 0.0, 'x3': 0.005524, 'x4': 0.084756, 'x5': 0.356595, 'x6': 0.598097}. [INFO 11-10 20:26:48] ax.service.ax_client: Completed trial 15 with data: {'hartmann6': (-1.378585, 0.0), 'l2norm': (0.72667, 0.0)}. [INFO 11-10 20:26:54] ax.service.ax_client: Generated new trial 16 with parameters {'x1': 0.280064, 'x2': 0.0, 'x3': 0.0, 'x4': 0.196006, 'x5': 0.347918, 'x6': 0.679666}. [INFO 11-10 20:26:54] ax.service.ax_client: Completed trial 16 with data: {'hartmann6': (-1.994334, 0.0), 'l2norm': (0.836568, 0.0)}. [INFO 11-10 20:26:59] ax.service.ax_client: Generated new trial 17 with parameters {'x1': 0.324287, 'x2': 0.0, 'x3': 0.0, 'x4': 0.246527, 'x5': 0.309038, 'x6': 0.66616}. [INFO 11-10 20:26:59] ax.service.ax_client: Completed trial 17 with data: {'hartmann6': (-2.166236, 0.0), 'l2norm': (0.839768, 0.0)}. [INFO 11-10 20:27:04] ax.service.ax_client: Generated new trial 18 with parameters {'x1': 0.407115, 'x2': 0.0, 'x3': 0.0, 'x4': 0.273261, 'x5': 0.333879, 'x6': 0.627779}. [INFO 11-10 20:27:04] ax.service.ax_client: Completed trial 18 with data: {'hartmann6': (-2.009171, 0.0), 'l2norm': (0.86371, 0.0)}. [INFO 11-10 20:27:09] ax.service.ax_client: Generated new trial 19 with parameters {'x1': 0.296689, 'x2': 0.0, 'x3': 0.0, 'x4': 0.297054, 'x5': 0.270394, 'x6': 0.713101}. [INFO 11-10 20:27:09] ax.service.ax_client: Completed trial 19 with data: {'hartmann6': (-2.146693, 0.0), 'l2norm': (0.870569, 0.0)}. [INFO 11-10 20:27:15] ax.service.ax_client: Generated new trial 20 with parameters {'x1': 0.312275, 'x2': 0.056833, 'x3': 0.0, 'x4': 0.264895, 'x5': 0.273077, 'x6': 0.656239}. [INFO 11-10 20:27:15] ax.service.ax_client: Completed trial 20 with data: {'hartmann6': (-2.270711, 0.0), 'l2norm': (0.822274, 0.0)}. [INFO 11-10 20:27:20] ax.service.ax_client: Generated new trial 21 with parameters {'x1': 0.345813, 'x2': 0.102402, 'x3': 0.0, 'x4': 0.24465, 'x5': 0.247353, 'x6': 0.707538}. [INFO 11-10 20:27:20] ax.service.ax_client: Completed trial 21 with data: {'hartmann6': (-2.128842, 0.0), 'l2norm': (0.867018, 0.0)}. [INFO 11-10 20:27:24] ax.service.ax_client: Generated new trial 22 with parameters {'x1': 0.290884, 'x2': 0.057239, 'x3': 0.0, 'x4': 0.285079, 'x5': 0.247642, 'x6': 0.579308}. [INFO 11-10 20:27:24] ax.service.ax_client: Completed trial 22 with data: {'hartmann6': (-2.091576, 0.0), 'l2norm': (0.752386, 0.0)}. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:328: RuntimeWarning: Optimization failed on the second try, after generating a new set of initial conditions. [INFO 11-10 20:27:36] ax.service.ax_client: Generated new trial 23 with parameters {'x1': 0.291377, 'x2': 0.073973, 'x3': 0.0, 'x4': 0.290157, 'x5': 0.304633, 'x6': 0.669787}. [INFO 11-10 20:27:36] ax.service.ax_client: Completed trial 23 with data: {'hartmann6': (-2.365431, 0.0), 'l2norm': (0.846155, 0.0)}. [INFO 11-10 20:27:42] ax.service.ax_client: Generated new trial 24 with parameters {'x1': 0.295062, 'x2': 0.09856, 'x3': 0.061148, 'x4': 0.304024, 'x5': 0.311007, 'x6': 0.670674}. [INFO 11-10 20:27:42] ax.service.ax_client: Completed trial 24 with data: {'hartmann6': (-2.546605, 0.0), 'l2norm': (0.859927, 0.0)}.
By default, Ax restricts number of trials that can run in parallel for some optimization stages, in order to improve the optimization performance and reduce the number of trials that the optimization will require. To check the maximum parallelism for each optimization stage:
ax_client.get_max_parallelism()
[(12, 12), (-1, 3)]
The output of this function is a list of tuples of form (number of trials, max parallelism), so the example above means "the max parallelism is 12 for the first 12 trials and 3 for all subsequent trials." This is because the first 12 trials are produced quasi-randomly and can all be evaluated at once, and subsequent trials are produced via Bayesian optimization, which converges on optimal point in fewer trials when parallelism is limited. MaxParallelismReachedException
indicates that the parallelism limit has been reached –– refer to the 'Service API Exceptions Meaning and Handling' section at the end of the tutorial for handling.
ax_client.generation_strategy.trials_as_df
[INFO 11-10 20:27:42] ax.modelbridge.generation_strategy: Note that parameter values in dataframe are rounded to 2 decimal points; the values in the dataframe are thus not the exact ones suggested by Ax in trials.
Generation Step | Generation Model | Trial Index | Trial Status | Arm Parameterizations | |
---|---|---|---|---|---|
0 | 0 | Sobol | 0 | COMPLETED | {'0_0': {'x1': 0.17, 'x2': 0.52, 'x3': 0.34, '... |
1 | 0 | Sobol | 1 | COMPLETED | {'1_0': {'x1': 0.15, 'x2': 0.04, 'x3': 0.09, '... |
2 | 0 | Sobol | 2 | COMPLETED | {'2_0': {'x1': 0.81, 'x2': 0.33, 'x3': 0.63, '... |
3 | 0 | Sobol | 3 | COMPLETED | {'3_0': {'x1': 0.8, 'x2': 0.25, 'x3': 0.6, 'x4... |
4 | 0 | Sobol | 4 | COMPLETED | {'4_0': {'x1': 0.56, 'x2': 0.49, 'x3': 0.97, '... |
5 | 0 | Sobol | 5 | COMPLETED | {'5_0': {'x1': 0.42, 'x2': 0.81, 'x3': 0.03, '... |
6 | 0 | Sobol | 6 | COMPLETED | {'6_0': {'x1': 0.7, 'x2': 0.05, 'x3': 0.88, 'x... |
7 | 0 | Sobol | 7 | COMPLETED | {'7_0': {'x1': 0.27, 'x2': 0.75, 'x3': 0.91, '... |
8 | 0 | Sobol | 8 | COMPLETED | {'8_0': {'x1': 0.22, 'x2': 0.57, 'x3': 0.54, '... |
9 | 0 | Sobol | 9 | COMPLETED | {'9_0': {'x1': 0.59, 'x2': 0.22, 'x3': 0.83, '... |
10 | 0 | Sobol | 10 | COMPLETED | {'10_0': {'x1': 0.06, 'x2': 0.15, 'x3': 0.35, ... |
11 | 0 | Sobol | 11 | COMPLETED | {'11_0': {'x1': 0.9, 'x2': 0.65, 'x3': 0.18, '... |
12 | 1 | GPEI | 12 | COMPLETED | {'12_0': {'x1': 0.25, 'x2': 0.0, 'x3': 0.08, '... |
13 | 1 | GPEI | 13 | COMPLETED | {'13_0': {'x1': 0.28, 'x2': 0.0, 'x3': 0.08, '... |
14 | 1 | GPEI | 14 | COMPLETED | {'14_0': {'x1': 0.24, 'x2': 0.0, 'x3': 0.02, '... |
15 | 1 | GPEI | 15 | COMPLETED | {'15_0': {'x1': 0.19, 'x2': 0.0, 'x3': 0.01, '... |
16 | 1 | GPEI | 16 | COMPLETED | {'16_0': {'x1': 0.28, 'x2': 0.0, 'x3': 0.0, 'x... |
17 | 1 | GPEI | 17 | COMPLETED | {'17_0': {'x1': 0.32, 'x2': 0.0, 'x3': 0.0, 'x... |
18 | 1 | GPEI | 18 | COMPLETED | {'18_0': {'x1': 0.41, 'x2': 0.0, 'x3': 0.0, 'x... |
19 | 1 | GPEI | 19 | COMPLETED | {'19_0': {'x1': 0.3, 'x2': 0.0, 'x3': 0.0, 'x4... |
20 | 1 | GPEI | 20 | COMPLETED | {'20_0': {'x1': 0.31, 'x2': 0.06, 'x3': 0.0, '... |
21 | 1 | GPEI | 21 | COMPLETED | {'21_0': {'x1': 0.35, 'x2': 0.1, 'x3': 0.0, 'x... |
22 | 1 | GPEI | 22 | COMPLETED | {'22_0': {'x1': 0.29, 'x2': 0.06, 'x3': 0.0, '... |
23 | 1 | GPEI | 23 | COMPLETED | {'23_0': {'x1': 0.29, 'x2': 0.07, 'x3': 0.0, '... |
24 | 1 | GPEI | 24 | COMPLETED | {'24_0': {'x1': 0.3, 'x2': 0.1, 'x3': 0.06, 'x... |
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.29506216793846574, 'x2': 0.09855985754364237, 'x3': 0.06114817023649496, 'x4': 0.30402435742169126, 'x5': 0.3110071373642808, 'x6': 0.670673573760974}
means, covariances = values
means
{'l2norm': 0.8599296327559474, 'hartmann6': -2.5465908225719267}
For comparison, Hartmann6 minimum:
hartmann6.fmin
-3.32237
Here we arbitrarily select "x1" and "x2" as the two parameters to plot for both metrics, "hartmann6" and "l2norm".
render(ax_client.get_contour_plot())
[INFO 11-10 20:27:43] ax.service.ax_client: Retrieving contour plot with parameter 'x1' on X-axis and 'x2' on Y-axis, for metric 'hartmann6'. Remaining parameters are affixed to the middle of their range.
We can also retrieve a contour plot for the other metric, "l2norm" –– say, we are interested in seeing the response surface for parameters "x3" and "x4" for this one.
render(ax_client.get_contour_plot(param_x="x3", param_y="x4", metric_name="l2norm"))
[INFO 11-10 20:27:43] ax.service.ax_client: Retrieving contour plot with parameter 'x3' on X-axis and 'x4' on Y-axis, for metric 'l2norm'. Remaining parameters are affixed to the middle of their range.
Here we plot the optimization trace, showing the progression of finding the point with the optimal objective:
render(ax_client.get_optimization_trace(objective_optimum=hartmann6.fmin)) # Objective_optimum is optional.
We can serialize the state of optimization to JSON and save it to a .json
file or save it to the SQL backend. For the former:
ax_client.save_to_json_file() # For custom filepath, pass `filepath` argument.
[INFO 11-10 20:27:44] ax.service.ax_client: Saved JSON-serialized state of optimization to `ax_client_snapshot.json`.
restored_ax_client = AxClient.load_from_json_file() # For custom filepath, pass `filepath` argument.
[INFO 11-10 20:27:44] ax.service.ax_client: Starting optimization with verbose logging. To disable logging, set the `verbose_logging` argument to `False`. Note that float values in the logs are rounded to 6 decimal points.
To store state of optimization to an SQL backend, first follow setup instructions on Ax website.
Having set up the SQL backend, pass DBSettings
to AxClient
on instantiation (note that SQLAlchemy
dependency will have to be installed – for installation, refer to optional dependencies on Ax website):
from ax.storage.sqa_store.structs import DBSettings
# URL is of the form "dialect+driver://username:password@host:port/database".
db_settings = DBSettings(url="sqlite:///foo.db")
# Instead of URL, can provide a `creator function`; can specify custom encoders/decoders if necessary.
new_ax = AxClient(db_settings=db_settings)
[INFO 11-10 20:27:44] ax.service.ax_client: Starting optimization with verbose logging. To disable logging, set the `verbose_logging` argument to `False`. Note that float values in the logs are rounded to 6 decimal points.
When valid DBSettings
are passed into AxClient
, a unique experiment name is a required argument (name
) to ax_client.create_experiment
. The state of the optimization is auto-saved any time it changes (i.e. a new trial is added or completed, etc).
To reload an optimization state later, instantiate AxClient
with the same DBSettings
and use ax_client.load_experiment_from_database(experiment_name="my_experiment")
.
Evaluation failure: should any optimization iterations fail during evaluation, log_trial_failure
will ensure that the same trial is not proposed again.
_, trial_index = ax_client.get_next_trial()
ax_client.log_trial_failure(trial_index=trial_index)
[INFO 11-10 20:27:49] ax.service.ax_client: Generated new trial 25 with parameters {'x1': 0.290142, 'x2': 0.121615, 'x3': 0.113241, 'x4': 0.315426, 'x5': 0.313627, 'x6': 0.659443}. [INFO 11-10 20:27:49] ax.service.ax_client: Registered failure of trial 25.
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})
[INFO 11-10 20:27:49] ax.service.ax_client: Attached custom parameterization {'x1': 0.9, 'x2': 0.9, 'x3': 0.9, 'x4': 0.9, 'x5': 0.9, 'x6': 0.9} as trial 26.
({'x1': 0.9, 'x2': 0.9, 'x3': 0.9, 'x4': 0.9, 'x5': 0.9, 'x6': 0.9}, 26)
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 needs to dispatch 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)
.
DataRequiredError
: Ax generation strategy needs to be updated with more data to proceed to the next optimization model. When the optimization moves from initialization stage to the Bayesian optimization stage, the underlying BayesOpt model needs sufficient data to train. For optimal results and optimization efficiency (finding the optimal point in the least number of trials), we recommend sequential optimization (generating a few trials, then waiting for them to be completed with evaluation data). Therefore, the correct way to handle this exception is to wait until more trial evaluations complete and log their data via ax_client.complete_trial(...)
.
However, if there is strong need to generate more trials before more data is available, instantiate AxClient
as AxClient(enforce_sequential_optimization=False)
. With this setting, as many trials will be generated from the initialization stage as requested, and the optimization will move to the BayesOpt stage whenever enough trials are completed.
MaxParallelismReachedException
: generation strategy restricts the number of trials that can be ran simultaneously (to encourage sequential optimization), and the parallelism limit has been reached. The correct way to handle this exception is the same as DataRequiredError
– to wait until more trial evluations complete and log their data via ax_client.complete_trial(...)
.
In some cases higher parallelism is important, so enforce_sequential_optimization=False
kwarg to AxClient allows to suppress limiting of parallelism. It's also possible to override the default parallelism setting for all stages of the optimization by passing choose_generation_strategy_kwargs
to ax_client.create_experiment
:
ax_client = AxClient()
ax_client.create_experiment(
parameters=[
{"name": "x", "type": "range", "bounds": [-5.0, 10.0]},
{"name": "y", "type": "range", "bounds": [0.0, 15.0]},
],
# Sets max parallelism to 10 for all steps of the generation strategy.
choose_generation_strategy_kwargs={"max_parallelism_override": 10},
)
[INFO 11-10 20:27:49] ax.service.ax_client: Starting optimization with verbose logging. To disable logging, set the `verbose_logging` argument to `False`. Note that float values in the logs are rounded to 6 decimal points. [INFO 11-10 20:27:49] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x. If that is not the expected value type, you can explicity specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict. [INFO 11-10 20:27:49] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter y. If that is not the expected value type, you can explicity specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict. [INFO 11-10 20:27:49] ax.service.utils.instantiation: Created search space: SearchSpace(parameters=[RangeParameter(name='x', parameter_type=FLOAT, range=[-5.0, 10.0]), RangeParameter(name='y', parameter_type=FLOAT, range=[0.0, 15.0])], parameter_constraints=[]). [INFO 11-10 20:27:49] ax.modelbridge.dispatch_utils: Using Bayesian optimization since there are more ordered parameters than there are categories for the unordered categorical parameters. [INFO 11-10 20:27:49] ax.modelbridge.dispatch_utils: Using Bayesian Optimization generation strategy: GenerationStrategy(name='Sobol+GPEI', steps=[Sobol for 5 trials, GPEI for subsequent trials]). Iterations after 5 will take longer to generate due to model-fitting.
ax_client.get_max_parallelism() # Max parallelism is now 10 for all stages of the optimization.
[(5, 10), (-1, 10)]
Total runtime of script: 1 minutes, 55.04 seconds.