Skip to main content
Version: Next

Ask-tell Optimization with Ax

Complex optimization problems where we wish to tune multiple parameters to improve metric performance, but the inter-parameter interactions are not fully understood, are common across various fields including machine learning, robotics, materials science, and chemistry. This category of problem is known as "black-box" optimization. The complexity of black-box optimization problems further increases if evaluations are expensive to conduct, time-consuming, or noisy.

We can use Ax to efficiently conduct an experiment in which we "ask" for candidate points to evaluate, "tell" Ax the results, and repeat. We'll uses Ax's Client, a tool for managing the state of our experiment, and we'll learn how to define an optimization problem, configure an experiment, run trials, analyze results, and persist the experiment for later use using the Client.

Because Ax is a black box optimizer, we can use it to optimize any arbitrary function. In this example we will minimize the Hartmann6 function, a complicated 6-dimensional function with multiple local minima. Hartmann6 is a challenging benchmark for optimization algorithms commonly used in the global optimization literature -- it tests the algorithm's ability to identify the true global minimum, rather than mistakenly converging on a local minimum. Looking at its analytic form we can see that it would be incredibly challenging to efficiently find the global minimum either by manual trial-and-error or traditional design of experiments like grid-search or random-search.

f(x)=i=14αiexp(j=16Aij(xjPij)2) f(\mathbf{x})=-\sum_{i=1}^4 \alpha_i \exp \left(-\sum_{j=1}^6 A_{i j}\left(x_j-P_{i j}\right)^2\right)

where

α=(1.0,1.2,3.0,3.2)T \alpha=(1.0,1.2,3.0,3.2)^T A=(103173.501.780.0510170.181433.51.7101781780.05100.114) \mathbf{A}=\left(\begin{array}{cccccc}10 & 3 & 17 & 3.50 & 1.7 & 8 \\ 0.05 & 10 & 17 & 0.1 & 8 & 14 \\ 3 & 3.5 & 1.7 & 10 & 17 & 8 \\ 17 & 8 & 0.05 & 10 & 0.1 & 14\end{array}\right) P=104(1312169655691248283588623294135830737361004999123481451352228833047665040478828873257431091381) \mathbf{P}=10^{-4}\left(\begin{array}{cccccc}1312 & 1696 & 5569 & 124 & 8283 & 5886 \\ 2329 & 4135 & 8307 & 3736 & 1004 & 9991 \\ 2348 & 1451 & 3522 & 2883 & 3047 & 6650 \\ 4047 & 8828 & 8732 & 5743 & 1091 & 381\end{array}\right)

Learning Objectives

  • Understand the basic concepts of black box optimization
  • Learn how to define an optimization problem using Ax
  • Configure and run an experiment using Ax's Client
  • Analyze the results of the optimization

Prerequisites

Step 1: Import Necessary Modules

First, ensure you have all the necessary imports:

import numpy as np
from ax.preview.api.client import Client
from ax.preview.api.configs import (
ExperimentConfig,
RangeParameterConfig,
ParameterType,
)
Out:

/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12/site-packages/pyro/ops/stats.py:514: SyntaxWarning: invalid escape sequence 'g'

"""

Step 2: Initialize the Client

Create an instance of the Client to manage the state of your experiment.

client = Client()

Step 3: Configure the Experiment

The Client instance can be configured with a series of Configs that define how the experiment will be run.

The Hartmann6 problem is usually evaluated on the hypercube xi(0,1)x_i \in (0, 1), so we will define six identical RangeParameterConfigs with these bounds and add these to an ExperimentConfig along with other metadata about the experiment.

You may specify additional features like parameter constraints to further refine the search space and parameter scaling to help navigate parameters with nonuniform effects. For more on configuring experiments, see this recipe.

# Define six float parameters x1, x2, x3, ... for the Hartmann6 function
parameters = [
RangeParameterConfig(
name=f"x{i + 1}", parameter_type=ParameterType.FLOAT, bounds=(0, 1)
)
for i in range(6)
]

# Create an experiment configuration
experiment_config = ExperimentConfig(
name="hartmann6_experiment",
parameters=parameters,
# The following arguments are optional
description="Optimization of the Hartmann6 function",
owner="developer",
)

# Apply the experiment configuration to the client
client.configure_experiment(experiment_config=experiment_config)

Step 4: Configure Optimization

Now, we must configure the objective for this optimization, which we do using Client.configure_optimization. This method expects a string objective, an expression containing either a single metric to maximize, a linear combination of metrics to maximize, or a tuple of multiple metrics to jointly maximize. These expressions are parsed using SymPy. For example:

  • "score" would direct Ax to maximize a metric named score
  • "-loss" would direct Ax to Ax to minimize a metric named loss
  • "task_0 + 0.5 * task_1" would direct Ax to maximize the sum of two task scores, downweighting task_1 by a factor of 0.5
  • "score, -flops" would direct Ax to simultaneously maximize score while minimizing flops

For more information on configuring objectives and outcome constraints, see this recipe.

metric_name = "hartmann6" # this name is used during the optimization loop in Step 5
objective = f"-{metric_name}" # minimization is specified by the negative sign

client.configure_optimization(objective=objective)

Step 5: Run Trials

Here, we will configure the ask-tell loop.

We begin by defining the Hartmann6 function as written above. Remember, this is just an example problem and any Python function can be substituted here.

# Hartmann6 function
def hartmann6(x1, x2, x3, x4, x5, x6):
alpha = np.array([1.0, 1.2, 3.0, 3.2])
A = np.array([
[10, 3, 17, 3.5, 1.7, 8],
[0.05, 10, 17, 0.1, 8, 14],
[3, 3.5, 1.7, 10, 17, 8],
[17, 8, 0.05, 10, 0.1, 14]
])
P = 10**-4 * np.array([
[1312, 1696, 5569, 124, 8283, 5886],
[2329, 4135, 8307, 3736, 1004, 9991],
[2348, 1451, 3522, 2883, 3047, 6650],
[4047, 8828, 8732, 5743, 1091, 381]
])

outer = 0.0
for i in range(4):
inner = 0.0
for j, x in enumerate([x1, x2, x3, x4, x5, x6]):
inner += A[i, j] * (x - P[i, j])**2
outer += alpha[i] * np.exp(-inner)
return -outer

hartmann6(0.1, 0.45, 0.8, 0.25, 0.552, 1.0)
Out:

-0.4878737485613134

Optimization Loop

We will iteratively call client.get_next_trials to "ask" Ax for a parameterization to evaluate, then call hartmann6 using those parameters, and finally "tell" Ax the result using client.complete_trial.

This loop will run multiple trials to optimize the function.

# Number of trials to run
num_trials = 30

# Run trials
for _ in range(num_trials):
trials = client.get_next_trials(
maximum_trials=1
) # We will request just one trial at a time in this example
for trial_index, parameters in trials.items():
x1 = parameters["x1"]
x2 = parameters["x2"]
x3 = parameters["x3"]
x4 = parameters["x4"]
x5 = parameters["x5"]
x6 = parameters["x6"]

result = hartmann6(x1, x2, x3, x4, x5, x6)

# Set raw_data as a dictionary with metric names as keys and results as values

raw_data = {metric_name: result}

# Complete the trial with the result

client.complete_trial(trial_index=trial_index, raw_data=raw_data)
print(f"Completed trial {trial_index} with {raw_data=}")
Out:

Completed trial 0 with raw_data={'hartmann6': -0.7084228359405653}

Completed trial 1 with raw_data={'hartmann6': -0.28492520668110194}

Completed trial 2 with raw_data={'hartmann6': -0.016405173203855573}

Completed trial 3 with raw_data={'hartmann6': -0.018773818007135696}

Completed trial 4 with raw_data={'hartmann6': -0.0033586921865887335}

Out:

Completed trial 5 with raw_data={'hartmann6': -0.7413820625678003}

Out:

Completed trial 6 with raw_data={'hartmann6': -0.0629142208869357}

Out:

Completed trial 7 with raw_data={'hartmann6': -0.24077108707058903}

Out:

Completed trial 8 with raw_data={'hartmann6': -0.9038902728853333}

Out:

Completed trial 9 with raw_data={'hartmann6': -0.6126215390541728}

Out:

Completed trial 10 with raw_data={'hartmann6': -0.49842732948592544}

Out:

Completed trial 11 with raw_data={'hartmann6': -0.12642938255765512}

Out:

Completed trial 12 with raw_data={'hartmann6': -0.7319561152209322}

Out:

Completed trial 13 with raw_data={'hartmann6': -1.1406240986297542}

Out:

Completed trial 14 with raw_data={'hartmann6': -1.572800653831424}

Out:

Completed trial 15 with raw_data={'hartmann6': -0.7990879782226975}

Out:

Completed trial 16 with raw_data={'hartmann6': -0.30451154522820806}

Out:

Completed trial 17 with raw_data={'hartmann6': -1.34411581828989}

Out:

Completed trial 18 with raw_data={'hartmann6': -1.6292420899505533}

Out:

Completed trial 19 with raw_data={'hartmann6': -1.520207659141182}

Out:

Completed trial 20 with raw_data={'hartmann6': -1.5140613524813769}

Out:

Completed trial 21 with raw_data={'hartmann6': -1.122160074915145}

Out:

Completed trial 22 with raw_data={'hartmann6': -2.333062376707554}

Out:

Completed trial 23 with raw_data={'hartmann6': -2.067671751359614}

Out:

Completed trial 24 with raw_data={'hartmann6': -1.3038487217359447}

Out:

Completed trial 25 with raw_data={'hartmann6': -2.9573998364083014}

Out:

Completed trial 26 with raw_data={'hartmann6': -2.0961097628810212}

Out:

Completed trial 27 with raw_data={'hartmann6': -3.0743979327748794}

Out:

Completed trial 28 with raw_data={'hartmann6': -2.8601204363265245}

Out:

Completed trial 29 with raw_data={'hartmann6': -2.876170680993452}

Step 6: Analyze Results

After running trials, you can analyze the results. Most commonly this means extracting the parameterization from the best performing trial you conducted.

Hartmann6 has a known global minimum of f(x)=3.322f(x*) = -3.322 at x=(0.201,0.150,0.477,0.273,0.312,0.657)x* = (0.201, 0.150, 0.477, 0.273, 0.312, 0.657). Ax is able to identify a point very near to this true optimum using just 30 evaluations. This is possible due to the sample-efficiency of Bayesian optimization, the optimization method we use under the hood in Ax.

best_parameters, prediction, index, name = client.get_best_parameterization()
print("Best Parameters:", best_parameters)
print("Prediction (mean, variance):", prediction)
Out:

Best Parameters: {'x1': 0.2084477856190312, 'x2': 0.0, 'x3': 0.47693551220003505, 'x4': 0.27330065021698624, 'x5': 0.31739927463154577, 'x6': 0.6593364912136953}

Prediction (mean, variance): {'hartmann6': (-3.0625932255769994, 0.0017194225487514806)}

Step 7: Compute Analyses

Ax can also produce a number of analyses to help interpret the results of the experiment via client.compute_analyses. Users can manually select which analyses to run, or can allow Ax to select which would be most relevant. In this case Ax selects the following:

  • Parrellel Coordinates Plot shows which parameterizations were evaluated and what metric values were observed -- this is useful for getting a high level overview of how thoroughly the search space was explored and which regions tend to produce which outcomes
  • Interaction Analysis Plot shows which parameters have the largest affect on the function and plots the most important parameters as 1 or 2 dimensional surfaces
  • Summary lists all trials generated along with their parameterizations, observations, and miscellaneous metadata
client.compute_analyses(display=True) # By default Ax will display the AnalysisCards produced by compute_analyses

Parallel Coordinates for hartmann6

View arm parameterizations with their respective metric values

loading...

Interaction Analysis for hartmann6

Understand an Experiment's data as one- or two-dimensional additive components with sparsity. Important components are visualized through slice or contour plots

loading...

Summary for hartmann6_experiment

High-level summary of the Trial-s in this Experiment

trial_indexarm_nametrial_statusgeneration_methodgeneration_nodehartmann6x1x2x3x4x5x6
000_0COMPLETEDSobolSobol-0.7084230.1737730.2711710.5066310.0848570.8394440.766637
111_0COMPLETEDSobolSobol-0.2849250.619470.514780.3882610.632220.2748630.362562
222_0COMPLETEDSobolSobol-0.0164050.9339870.1627110.9398760.4407810.0645490.16991
333_0COMPLETEDSobolSobol-0.0187740.3669450.9336620.0714760.7684180.500960.702846
444_0COMPLETEDSobolSobol-0.0033590.4363390.0906970.3285340.9961540.6945560.913037
555_0COMPLETEDBoTorchMBM-0.7413820.201760.1910070.4373800.726960.503929
666_0COMPLETEDBoTorchMBM-0.0629140.0220450.6327350.58325200.6516730.076503
777_0COMPLETEDBoTorchMBM-0.2407710.1527280.126170.41696200.9421110.952824
888_0COMPLETEDBoTorchMBM-0.903890.2035330.2915050.5033750.0704680.7386160.569746
999_0COMPLETEDBoTorchMBM-0.6126220.2409010.413020.679610.1755180.7137510.596461
101010_0COMPLETEDBoTorchMBM-0.4984270.198760.326150.37602900.6817570.455087
111111_0COMPLETEDBoTorchMBM-0.126429101001
121212_0COMPLETEDBoTorchMBM-0.731956000.53859300.9942630.577746
131313_0COMPLETEDBoTorchMBM-1.140620.308730.0878020.53390700.517990.603244
141414_0COMPLETEDBoTorchMBM-1.57280.2323500.54190200.2621730.626407
151515_0COMPLETEDBoTorchMBM-0.7990880.10899100.54336700.0773560.647915
161616_0COMPLETEDBoTorchMBM-0.3045120.2453600.5350750.0501930.1962830.185582
171717_0COMPLETEDBoTorchMBM-1.344120.25916400.51893300.2069760.696505
181818_0COMPLETEDBoTorchMBM-1.629240.21245800.55882500.3733920.625517
191919_0COMPLETEDBoTorchMBM-1.520210.0463200.5860300.3285510.665058
202020_0COMPLETEDBoTorchMBM-1.514060.25778100.62960800.311810.64316
212121_0COMPLETEDBoTorchMBM-1.122160.48090500.51227100.3256840.62696
222222_0COMPLETEDBoTorchMBM-2.333060.16132500.5504020.4341490.3393510.625884
232323_0COMPLETEDBoTorchMBM-2.067670.13324900.3267020.4524020.3564380.620311
242424_0COMPLETEDBoTorchMBM-1.303850.08048500.5560660.5511580.366190.582391
252525_0COMPLETEDBoTorchMBM-2.95740.2060100.5673080.3027380.3228980.646673
262626_0COMPLETEDBoTorchMBM-2.096110.15430400.7821490.2664630.3630020.643348
272727_0COMPLETEDBoTorchMBM-3.07440.20844800.4769360.2733010.3173990.659336
282828_0COMPLETEDBoTorchMBM-2.860120.27307300.4723140.2964340.3052180.738664
292929_0COMPLETEDBoTorchMBM-2.876170.22968300.4751380.2825670.2569970.607644

Cross Validation for hartmann6

Out-of-sample predictions using leave-one-out CV

loading...
Out:

[<ax.analysis.plotly.plotly_analysis.PlotlyAnalysisCard at 0x7f94ddeebaa0>,

<ax.analysis.plotly.plotly_analysis.PlotlyAnalysisCard at 0x7f94d3c2ac00>,

<ax.analysis.plotly.plotly_analysis.PlotlyAnalysisCard at 0x7f94d3ca56a0>,

<ax.analysis.analysis.AnalysisCard at 0x7f94dc1ae210>]

Conclusion

This tutorial demonstrates how to use Ax's Client for ask-tell optimization of Python functions using the Hartmann6 function as an example. You can adjust the function and parameters to suit your specific optimization problem.