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, ObjectiveProperties
from ax.utils.measurement.synthetic_functions import hartmann6
from ax.utils.notebook.plotting import init_notebook_plotting, render
init_notebook_plotting()
[INFO 12-26 05:08:09] ax.utils.notebook.plotting: Injecting Plotly library into cell. Do not overwrite or delete cell.
[INFO 12-26 05:08:09] ax.utils.notebook.plotting: Please see (https://ax.dev/tutorials/visualizations.html#Fix-for-plots-that-are-not-rendering) if visualizations are not rendering.
Create a client object to interface with Ax APIs. By default this runs locally without storage.
ax_client = AxClient()
[INFO 12-26 05:08:09] 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 (objectives and outcome constraints). Note that:
parameters
, and objectives
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],
},
],
objectives={"hartmann6": ObjectiveProperties(minimize=True)},
parameter_constraints=["x1 + x2 <= 2.0"], # Optional.
outcome_constraints=["l2norm <= 1.25"], # Optional.
)
[INFO 12-26 05:08:09] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x2. If that is not the expected value type, you can explicitly specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict.
[INFO 12-26 05:08:09] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x3. If that is not the expected value type, you can explicitly specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict.
[INFO 12-26 05:08:09] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x4. If that is not the expected value type, you can explicitly specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict.
[INFO 12-26 05:08:09] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x5. If that is not the expected value type, you can explicitly specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict.
[INFO 12-26 05:08:09] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x6. If that is not the expected value type, you can explicitly specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict.
[INFO 12-26 05:08:09] 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 12-26 05:08:09] ax.modelbridge.dispatch_utils: Using Models.BOTORCH_MODULAR since there is at least one ordered parameter and there are no unordered categorical parameters.
[INFO 12-26 05:08:09] ax.modelbridge.dispatch_utils: Calculating the number of remaining initialization trials based on num_initialization_trials=None max_initialization_trials=None num_tunable_parameters=6 num_trials=None use_batch_trials=False
[INFO 12-26 05:08:09] ax.modelbridge.dispatch_utils: calculated num_initialization_trials=12
[INFO 12-26 05:08:09] ax.modelbridge.dispatch_utils: num_completed_initialization_trials=0 num_remaining_initialization_trials=12
[INFO 12-26 05:08:09] ax.modelbridge.dispatch_utils: `verbose`, `disable_progbar`, and `jit_compile` are not yet supported when using `choose_generation_strategy` with ModularBoTorchModel, dropping these arguments.
[INFO 12-26 05:08:09] ax.modelbridge.dispatch_utils: Using Bayesian Optimization generation strategy: GenerationStrategy(name='Sobol+BoTorch', steps=[Sobol for 12 trials, BoTorch 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 objectives
set on experiment creation or the metric names mentioned in outcome_constraints
.
import numpy as np
def evaluate(parameterization):
x = np.array([parameterization.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):
parameterization, 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(parameterization))
/tmp/tmp.2WLYdnTLMd/Ax-main/ax/modelbridge/cross_validation.py:439: UserWarning: Encountered exception in computing model fit quality: RandomModelBridge does not support prediction. [INFO 12-26 05:08:10] ax.service.ax_client: Generated new trial 0 with parameters {'x1': 0.037741, 'x2': 0.481861, 'x3': 0.910446, 'x4': 0.418893, 'x5': 0.374044, 'x6': 0.657108} using model Sobol.
[INFO 12-26 05:08:10] ax.service.ax_client: Completed trial 0 with data: {'hartmann6': (-0.961849, 0.0), 'l2norm': (1.34525, 0.0)}.
/tmp/tmp.2WLYdnTLMd/Ax-main/ax/modelbridge/cross_validation.py:439: UserWarning: Encountered exception in computing model fit quality: RandomModelBridge does not support prediction. [INFO 12-26 05:08:10] ax.service.ax_client: Generated new trial 1 with parameters {'x1': 0.880874, 'x2': 0.565623, 'x3': 0.14098, 'x4': 0.534254, 'x5': 0.922321, 'x6': 0.207174} using model Sobol.
[INFO 12-26 05:08:10] ax.service.ax_client: Completed trial 1 with data: {'hartmann6': (-0.018297, 0.0), 'l2norm': (1.514849, 0.0)}.
/tmp/tmp.2WLYdnTLMd/Ax-main/ax/modelbridge/cross_validation.py:439: UserWarning: Encountered exception in computing model fit quality: RandomModelBridge does not support prediction. [INFO 12-26 05:08:10] ax.service.ax_client: Generated new trial 2 with parameters {'x1': 0.702081, 'x2': 0.089069, 'x3': 0.670913, 'x4': 0.000517, 'x5': 0.503819, 'x6': 0.262258} using model Sobol.
[INFO 12-26 05:08:10] ax.service.ax_client: Completed trial 2 with data: {'hartmann6': (-0.089761, 0.0), 'l2norm': (1.128534, 0.0)}.
/tmp/tmp.2WLYdnTLMd/Ax-main/ax/modelbridge/cross_validation.py:439: UserWarning: Encountered exception in computing model fit quality: RandomModelBridge does not support prediction. [INFO 12-26 05:08:10] ax.service.ax_client: Generated new trial 3 with parameters {'x1': 0.3577, 'x2': 0.989668, 'x3': 0.401447, 'x4': 0.89004, 'x5': 0.1998, 'x6': 0.867463} using model Sobol.
[INFO 12-26 05:08:10] ax.service.ax_client: Completed trial 3 with data: {'hartmann6': (-0.00614, 0.0), 'l2norm': (1.689122, 0.0)}.
/tmp/tmp.2WLYdnTLMd/Ax-main/ax/modelbridge/cross_validation.py:439: UserWarning: Encountered exception in computing model fit quality: RandomModelBridge does not support prediction. [INFO 12-26 05:08:10] ax.service.ax_client: Generated new trial 4 with parameters {'x1': 0.455437, 'x2': 0.193778, 'x3': 0.086407, 'x4': 0.819336, 'x5': 0.060422, 'x6': 0.593407} using model Sobol.
[INFO 12-26 05:08:10] ax.service.ax_client: Completed trial 4 with data: {'hartmann6': (-0.048097, 0.0), 'l2norm': (1.131164, 0.0)}.
/tmp/tmp.2WLYdnTLMd/Ax-main/ax/modelbridge/cross_validation.py:439: UserWarning: Encountered exception in computing model fit quality: RandomModelBridge does not support prediction. [INFO 12-26 05:08:10] ax.service.ax_client: Generated new trial 5 with parameters {'x1': 0.612287, 'x2': 0.851755, 'x3': 0.855882, 'x4': 0.196404, 'x5': 0.736993, 'x6': 0.042361} using model Sobol.
[INFO 12-26 05:08:10] ax.service.ax_client: Completed trial 5 with data: {'hartmann6': (-0.352546, 0.0), 'l2norm': (1.554491, 0.0)}.
/tmp/tmp.2WLYdnTLMd/Ax-main/ax/modelbridge/cross_validation.py:439: UserWarning: Encountered exception in computing model fit quality: RandomModelBridge does not support prediction. [INFO 12-26 05:08:10] ax.service.ax_client: Generated new trial 6 with parameters {'x1': 0.806728, 'x2': 0.359574, 'x3': 0.331249, 'x4': 0.729046, 'x5': 0.813674, 'x6': 0.488069} using model Sobol.
[INFO 12-26 05:08:10] ax.service.ax_client: Completed trial 6 with data: {'hartmann6': (-0.002909, 0.0), 'l2norm': (1.523684, 0.0)}.
/tmp/tmp.2WLYdnTLMd/Ax-main/ax/modelbridge/cross_validation.py:439: UserWarning: Encountered exception in computing model fit quality: RandomModelBridge does not support prediction. [INFO 12-26 05:08:10] ax.service.ax_client: Generated new trial 7 with parameters {'x1': 0.151064, 'x2': 0.717208, 'x3': 0.600724, 'x4': 0.349041, 'x5': 0.388927, 'x6': 0.881886} using model Sobol.
[INFO 12-26 05:08:10] ax.service.ax_client: Completed trial 7 with data: {'hartmann6': (-0.670944, 0.0), 'l2norm': (1.396028, 0.0)}.
/tmp/tmp.2WLYdnTLMd/Ax-main/ax/modelbridge/cross_validation.py:439: UserWarning: Encountered exception in computing model fit quality: RandomModelBridge does not support prediction. [INFO 12-26 05:08:10] ax.service.ax_client: Generated new trial 8 with parameters {'x1': 0.230146, 'x2': 0.045946, 'x3': 0.255996, 'x4': 0.174472, 'x5': 0.994607, 'x6': 0.790049} using model Sobol.
[INFO 12-26 05:08:10] ax.service.ax_client: Completed trial 8 with data: {'hartmann6': (-0.117558, 0.0), 'l2norm': (1.328335, 0.0)}.
/tmp/tmp.2WLYdnTLMd/Ax-main/ax/modelbridge/cross_validation.py:439: UserWarning: Encountered exception in computing model fit quality: RandomModelBridge does not support prediction. [INFO 12-26 05:08:10] ax.service.ax_client: Generated new trial 9 with parameters {'x1': 0.823295, 'x2': 0.876294, 'x3': 0.549031, 'x4': 0.80985, 'x5': 0.301801, 'x6': 0.341583} using model Sobol.
[INFO 12-26 05:08:10] ax.service.ax_client: Completed trial 9 with data: {'hartmann6': (-0.029997, 0.0), 'l2norm': (1.615784, 0.0)}.
/tmp/tmp.2WLYdnTLMd/Ax-main/ax/modelbridge/cross_validation.py:439: UserWarning: Encountered exception in computing model fit quality: RandomModelBridge does not support prediction. [INFO 12-26 05:08:10] ax.service.ax_client: Generated new trial 10 with parameters {'x1': 0.503786, 'x2': 0.39974, 'x3': 0.013107, 'x4': 0.280142, 'x5': 0.131435, 'x6': 0.130307} using model Sobol.
[INFO 12-26 05:08:10] ax.service.ax_client: Completed trial 10 with data: {'hartmann6': (-0.247295, 0.0), 'l2norm': (0.725602, 0.0)}.
/tmp/tmp.2WLYdnTLMd/Ax-main/ax/modelbridge/cross_validation.py:439: UserWarning: Encountered exception in computing model fit quality: RandomModelBridge does not support prediction.
[INFO 12-26 05:08:10] ax.service.ax_client: Generated new trial 11 with parameters {'x1': 0.40945, 'x2': 0.553753, 'x3': 0.806142, 'x4': 0.641832, 'x5': 0.572173, 'x6': 0.736002} using model Sobol.
[INFO 12-26 05:08:10] ax.service.ax_client: Completed trial 11 with data: {'hartmann6': (-0.170254, 0.0), 'l2norm': (1.550866, 0.0)}.
[INFO 12-26 05:08:21] ax.service.ax_client: Generated new trial 12 with parameters {'x1': 0.034772, 'x2': 0.374251, 'x3': 0.817777, 'x4': 0.277055, 'x5': 0.200323, 'x6': 0.648895} using model BoTorch.
[INFO 12-26 05:08:21] ax.service.ax_client: Completed trial 12 with data: {'hartmann6': (-1.561547, 0.0), 'l2norm': (1.161028, 0.0)}.
[INFO 12-26 05:08:26] ax.service.ax_client: Generated new trial 13 with parameters {'x1': 0.0, 'x2': 0.227001, 'x3': 0.88754, 'x4': 0.121594, 'x5': 0.120415, 'x6': 0.578276} using model BoTorch.
[INFO 12-26 05:08:27] ax.service.ax_client: Completed trial 13 with data: {'hartmann6': (-0.73042, 0.0), 'l2norm': (1.096788, 0.0)}.
[INFO 12-26 05:08:36] ax.service.ax_client: Generated new trial 14 with parameters {'x1': 0.0, 'x2': 0.358965, 'x3': 0.829028, 'x4': 0.291631, 'x5': 0.0, 'x6': 0.924989} using model BoTorch.
[INFO 12-26 05:08:36] ax.service.ax_client: Completed trial 14 with data: {'hartmann6': (-1.189065, 0.0), 'l2norm': (1.325442, 0.0)}.
[INFO 12-26 05:08:42] ax.service.ax_client: Generated new trial 15 with parameters {'x1': 0.0, 'x2': 0.40499, 'x3': 0.845951, 'x4': 0.289891, 'x5': 0.190529, 'x6': 0.339525} using model BoTorch.
[INFO 12-26 05:08:42] ax.service.ax_client: Completed trial 15 with data: {'hartmann6': (-0.501948, 0.0), 'l2norm': (1.056061, 0.0)}.
[INFO 12-26 05:08:50] ax.service.ax_client: Generated new trial 16 with parameters {'x1': 0.058312, 'x2': 0.369943, 'x3': 0.77304, 'x4': 0.288491, 'x5': 0.090006, 'x6': 0.7153} using model BoTorch.
[INFO 12-26 05:08:50] ax.service.ax_client: Completed trial 16 with data: {'hartmann6': (-1.218844, 0.0), 'l2norm': (1.157942, 0.0)}.
[INFO 12-26 05:08:58] ax.service.ax_client: Generated new trial 17 with parameters {'x1': 0.024775, 'x2': 0.421758, 'x3': 0.827895, 'x4': 0.317321, 'x5': 0.256635, 'x6': 0.712358} using model BoTorch.
[INFO 12-26 05:08:58] ax.service.ax_client: Completed trial 17 with data: {'hartmann6': (-1.670399, 0.0), 'l2norm': (1.240125, 0.0)}.
[INFO 12-26 05:09:05] ax.service.ax_client: Generated new trial 18 with parameters {'x1': 0.0, 'x2': 0.271436, 'x3': 0.747409, 'x4': 0.278618, 'x5': 0.221421, 'x6': 0.790169} using model BoTorch.
[INFO 12-26 05:09:05] ax.service.ax_client: Completed trial 18 with data: {'hartmann6': (-1.996301, 0.0), 'l2norm': (1.176147, 0.0)}.
[INFO 12-26 05:09:15] ax.service.ax_client: Generated new trial 19 with parameters {'x1': 0.0, 'x2': 0.174143, 'x3': 0.763787, 'x4': 0.267479, 'x5': 0.233061, 'x6': 0.884862} using model BoTorch.
[INFO 12-26 05:09:15] ax.service.ax_client: Completed trial 19 with data: {'hartmann6': (-1.718064, 0.0), 'l2norm': (1.233912, 0.0)}.
[INFO 12-26 05:09:24] ax.service.ax_client: Generated new trial 20 with parameters {'x1': 0.0, 'x2': 0.327017, 'x3': 0.640198, 'x4': 0.257589, 'x5': 0.26625, 'x6': 0.904456} using model BoTorch.
[INFO 12-26 05:09:24] ax.service.ax_client: Completed trial 20 with data: {'hartmann6': (-1.772644, 0.0), 'l2norm': (1.213291, 0.0)}.
[INFO 12-26 05:09:31] ax.service.ax_client: Generated new trial 21 with parameters {'x1': 0.0, 'x2': 0.259078, 'x3': 0.260408, 'x4': 0.333647, 'x5': 0.247572, 'x6': 0.758756} using model BoTorch.
[INFO 12-26 05:09:31] ax.service.ax_client: Completed trial 21 with data: {'hartmann6': (-2.127851, 0.0), 'l2norm': (0.939817, 0.0)}.
[INFO 12-26 05:09:40] ax.service.ax_client: Generated new trial 22 with parameters {'x1': 0.531186, 'x2': 0.253412, 'x3': 0.0, 'x4': 0.340307, 'x5': 0.249272, 'x6': 0.766538} using model BoTorch.
[INFO 12-26 05:09:40] ax.service.ax_client: Completed trial 22 with data: {'hartmann6': (-1.524414, 0.0), 'l2norm': (1.054468, 0.0)}.
[INFO 12-26 05:09:49] ax.service.ax_client: Generated new trial 23 with parameters {'x1': 0.0, 'x2': 0.27401, 'x3': 0.0, 'x4': 0.387171, 'x5': 0.208671, 'x6': 0.823231} using model BoTorch.
[INFO 12-26 05:09:49] ax.service.ax_client: Completed trial 23 with data: {'hartmann6': (-1.233752, 0.0), 'l2norm': (0.972747, 0.0)}.
[INFO 12-26 05:09:55] ax.service.ax_client: Generated new trial 24 with parameters {'x1': 0.063466, 'x2': 0.22976, 'x3': 0.449888, 'x4': 0.269024, 'x5': 0.268162, 'x6': 0.714398} using model BoTorch.
[INFO 12-26 05:09:55] ax.service.ax_client: Completed trial 24 with data: {'hartmann6': (-2.855453, 0.0), 'l2norm': (0.955963, 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 12-26 05:09:56] 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(s) | Trial Index | Trial Status | Arm Parameterizations | |
---|---|---|---|---|---|
0 | [GenerationStep_0] | [Sobol] | 0 | COMPLETED | {'0_0': {'x1': 0.04, 'x2': 0.48, 'x3': 0.91, '... |
1 | [GenerationStep_0] | [Sobol] | 1 | COMPLETED | {'1_0': {'x1': 0.88, 'x2': 0.57, 'x3': 0.14, '... |
2 | [GenerationStep_0] | [Sobol] | 2 | COMPLETED | {'2_0': {'x1': 0.7, 'x2': 0.09, 'x3': 0.67, 'x... |
3 | [GenerationStep_0] | [Sobol] | 3 | COMPLETED | {'3_0': {'x1': 0.36, 'x2': 0.99, 'x3': 0.4, 'x... |
4 | [GenerationStep_0] | [Sobol] | 4 | COMPLETED | {'4_0': {'x1': 0.46, 'x2': 0.19, 'x3': 0.09, '... |
5 | [GenerationStep_0] | [Sobol] | 5 | COMPLETED | {'5_0': {'x1': 0.61, 'x2': 0.85, 'x3': 0.86, '... |
6 | [GenerationStep_0] | [Sobol] | 6 | COMPLETED | {'6_0': {'x1': 0.81, 'x2': 0.36, 'x3': 0.33, '... |
7 | [GenerationStep_0] | [Sobol] | 7 | COMPLETED | {'7_0': {'x1': 0.15, 'x2': 0.72, 'x3': 0.6, 'x... |
8 | [GenerationStep_0] | [Sobol] | 8 | COMPLETED | {'8_0': {'x1': 0.23, 'x2': 0.05, 'x3': 0.26, '... |
9 | [GenerationStep_0] | [Sobol] | 9 | COMPLETED | {'9_0': {'x1': 0.82, 'x2': 0.88, 'x3': 0.55, '... |
10 | [GenerationStep_0] | [Sobol] | 10 | COMPLETED | {'10_0': {'x1': 0.5, 'x2': 0.4, 'x3': 0.01, 'x... |
11 | [GenerationStep_0] | [Sobol] | 11 | COMPLETED | {'11_0': {'x1': 0.41, 'x2': 0.55, 'x3': 0.81, ... |
12 | [GenerationStep_1] | [BoTorch] | 12 | COMPLETED | {'12_0': {'x1': 0.03, 'x2': 0.37, 'x3': 0.82, ... |
13 | [GenerationStep_1] | [BoTorch] | 13 | COMPLETED | {'13_0': {'x1': 0.0, 'x2': 0.23, 'x3': 0.89, '... |
14 | [GenerationStep_1] | [BoTorch] | 14 | COMPLETED | {'14_0': {'x1': 0.0, 'x2': 0.36, 'x3': 0.83, '... |
15 | [GenerationStep_1] | [BoTorch] | 15 | COMPLETED | {'15_0': {'x1': 0.0, 'x2': 0.4, 'x3': 0.85, 'x... |
16 | [GenerationStep_1] | [BoTorch] | 16 | COMPLETED | {'16_0': {'x1': 0.06, 'x2': 0.37, 'x3': 0.77, ... |
17 | [GenerationStep_1] | [BoTorch] | 17 | COMPLETED | {'17_0': {'x1': 0.02, 'x2': 0.42, 'x3': 0.83, ... |
18 | [GenerationStep_1] | [BoTorch] | 18 | COMPLETED | {'18_0': {'x1': 0.0, 'x2': 0.27, 'x3': 0.75, '... |
19 | [GenerationStep_1] | [BoTorch] | 19 | COMPLETED | {'19_0': {'x1': 0.0, 'x2': 0.17, 'x3': 0.76, '... |
20 | [GenerationStep_1] | [BoTorch] | 20 | COMPLETED | {'20_0': {'x1': 0.0, 'x2': 0.33, 'x3': 0.64, '... |
21 | [GenerationStep_1] | [BoTorch] | 21 | COMPLETED | {'21_0': {'x1': 0.0, 'x2': 0.26, 'x3': 0.26, '... |
22 | [GenerationStep_1] | [BoTorch] | 22 | COMPLETED | {'22_0': {'x1': 0.53, 'x2': 0.25, 'x3': 0.0, '... |
23 | [GenerationStep_1] | [BoTorch] | 23 | COMPLETED | {'23_0': {'x1': 0.0, 'x2': 0.27, 'x3': 0.0, 'x... |
24 | [GenerationStep_1] | [BoTorch] | 24 | COMPLETED | {'24_0': {'x1': 0.06, 'x2': 0.23, 'x3': 0.45, ... |
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.0634663891563144, 'x2': 0.22976015678783954, 'x3': 0.44988790888667335, 'x4': 0.26902439319476557, 'x5': 0.268161950068116, 'x6': 0.7143975157470651}
means, covariances = values
means
{'hartmann6': -2.855444220143215, 'l2norm': 0.95597641795138}
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 12-26 05:09:57] 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 12-26 05:09:58] 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 12-26 05:09:59] 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 12-26 05:09: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.
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 12-26 05:10:00] 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 12-26 05:10:07] ax.service.ax_client: Generated new trial 25 with parameters {'x1': 0.208038, 'x2': 0.10997, 'x3': 0.470392, 'x4': 0.185277, 'x5': 0.299478, 'x6': 0.668185} using model BoTorch.
[INFO 12-26 05:10:07] 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 12-26 05:10:07] ax.core.experiment: Attached custom parameterizations [{'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)
.
Nonlinear parameter constraints and/or constraints on non-Range parameters: Ax parameter constraints can currently only support linear inequalities (discussion). Users may be able to simulate this functionality, however, by substituting the following evaluate
function for that defined in section 3 above.
def evaluate(parameterization):
x = np.array([parameterization.get(f"x{i+1}") for i in range(6)])
# First calculate the nonlinear quantity to be constrained.
l2norm = np.sqrt((x**2).sum())
# Then define a constraint consistent with an outcome constraint on this experiment.
if l2norm > 1.25:
return {"l2norm": (l2norm, 0.0)}
return {"hartmann6": (hartmann6(x), 0.0), "l2norm": (l2norm, 0.0)}
For this to work, the constraint quantity (l2norm
in this case) should have a corresponding outcome constraint on the experiment. See the outcome_constraint arg to ax_client.create_experiment in section 2 above for how to specify outcome constraints.
This setup accomplishes the following:
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 12-26 05:10:08] 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 12-26 05:10:08] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x. If that is not the expected value type, you can explicitly specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict.
[INFO 12-26 05:10:08] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter y. If that is not the expected value type, you can explicitly specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict.
[INFO 12-26 05:10:08] 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 12-26 05:10:08] ax.modelbridge.dispatch_utils: Using Models.BOTORCH_MODULAR since there is at least one ordered parameter and there are no unordered categorical parameters.
[INFO 12-26 05:10:08] ax.modelbridge.dispatch_utils: Calculating the number of remaining initialization trials based on num_initialization_trials=None max_initialization_trials=None num_tunable_parameters=2 num_trials=None use_batch_trials=False
[INFO 12-26 05:10:08] ax.modelbridge.dispatch_utils: calculated num_initialization_trials=5
[INFO 12-26 05:10:08] ax.modelbridge.dispatch_utils: num_completed_initialization_trials=0 num_remaining_initialization_trials=5
[INFO 12-26 05:10:08] ax.modelbridge.dispatch_utils: `verbose`, `disable_progbar`, and `jit_compile` are not yet supported when using `choose_generation_strategy` with ModularBoTorchModel, dropping these arguments.
[INFO 12-26 05:10:08] ax.modelbridge.dispatch_utils: Using Bayesian Optimization generation strategy: GenerationStrategy(name='Sobol+BoTorch', steps=[Sobol for 5 trials, BoTorch 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: 2 minutes, 6.64 seconds.