Skip to main content
Version: Next

Closed-loop Optimization with Ax

Previously, we've demonstrated using Ax for ask-tell optimization, a paradigm in which we "ask" Ax for candidate configurations and "tell" Ax our observations. This can be effective in many scenerios, and it can be automated through use of flow control statements like for and while loops. However there are some situations where it would be beneficial to allow Ax to orchestrate the entire optimization: deploying trials to external systems, polling their status, and reading reading their results. This can be common in a number of real world engineering tasks, including:

  • Large scale machine learning experiments running workloads on high-performance computing clusters
  • A/B tests conducted using an external experimentation platform
  • Materials science optimizations utilizing a self-driving laboratory

Ax's Client can orchestrate automated adaptive experiments like this using its method run_trials. Users create custom classes which implement Ax's IMetric and IRunner protocols to handle data fetching and trial deployment respectively. Then, users simply configure their Client as they would normally and call run_trials; Ax will deploy trials, fetch data, generate candidates, and repeat as necessary. Ax can manage complex orchestration tasks including launching multiple trials in parallel while still respecting a user-defined concurrency limit, and gracefully handling trial failure by allowing the experiment to continue even if some trials do not complete successfully or data fetching fails.

In this tutorial we will optimize the Hartmann6 function as before, but we will configure custom Runners and Metrics to mimic an external execution system. The Runner will calculate Hartmann6 with the appropriate parameters, write the result to a file, and tell Ax the trial is ready after 5 seconds. The Metric will find the appropriate file and report the results back to Ax.

Learning Objectives

  • Learn when it can be appropriate and/or advantageous to run Ax in a closed-loop
  • Configure custom Runners and Metrics, allowing Ax to deploy trials and fetch data automatically
  • Understand tradeoffs between parallelism and optimization performance

Prerequisites

Step 1: Import Necessary Modules

First, ensure you have all the necessary imports:

import os
import time
from typing import Any, Mapping

import numpy as np
from ax.preview.api.client import Client
from ax.preview.api.configs import (
ExperimentConfig,
OrchestrationConfig,
ParameterType,
RangeParameterConfig,
)
from ax.preview.api.protocols.metric import IMetric
from ax.preview.api.protocols.runner import IRunner, TrialStatus
from ax.preview.api.types import TParameterization

Step 2: Defining our custom Runner and Metric

As stated before, we will be creating custom Runner and Metric classes to mimic an external system. Let's start by defining our Hartmann6 function as before.

# 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

Next, we will define the MockRunner. The MockRunner requires two methods: run_trial and poll_trial.

run_trial deploys a trial to the external system with the given parameters. In this case, we will simply save a file containing the result of a call to the Hartmann6 function.

poll_trial queries the external system to see if the trial has completed, failed, or if it's still running. In this mock example, we will check to see how many seconds have elapsed since the run_trial was called and only report a trial as completed once 5 seconds have elapsed.

Runner's may also optionally implement a stop_trial method to terminate a trial's execution before it has completed. This is necessary for using early stopping in closed-loop experimentation, but we will skip this for now.

class MockRunner(IRunner):
def run_trial(
self, trial_index: int, parameterization: TParameterization
) -> dict[str, Any]:
file_name = f"{int(time.time())}.txt"

x1 = parameterization["x1"]
x2 = parameterization["x2"]
x3 = parameterization["x3"]
x4 = parameterization["x4"]
x5 = parameterization["x5"]
x6 = parameterization["x6"]

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

with open(file_name, "w") as f:
f.write(f"{result}")

return {"file_name": file_name}

def poll_trial(
self, trial_index: int, trial_metadata: Mapping[str, Any]
) -> TrialStatus:
file_name = trial_metadata["file_name"]
time_elapsed = time.time() - int(file_name[:4])

if time_elapsed < 5:
return TrialStatus.RUNNING

return TrialStatus.COMPLETED

It's worthwhile to instantiate your Runner and test it is behaving as expected. Let's deploy a mock trial by manually calling run_trial and ensuring it creates a file.

runner = MockRunner()

trial_metadata = runner.run_trial(
trial_index=-1,
parameterization={
"x1": 0.1,
"x2": 0.45,
"x3": 0.8,
"x4": 0.25,
"x5": 0.552,
"x6": 1.0,
},
)

os.path.exists(trial_metadata["file_name"])
Out:

True

Now, we will implement the Metric. Metrics only need to implement a fetch method, which returns a progression value (i.e. a step in a timeseries) and an observation value. Note that the observation can either be a simple float or a (mean, SEM) pair if the external system can report observed noise.

In this case, we have neither a relevant progression value nor observed noise so we will simply read the file and report (0, value).

class MockMetric(IMetric):
def fetch(
self,
trial_index: int,
trial_metadata: Mapping[str, Any],
) -> tuple[int, float | tuple[float, float]]:
file_name = trial_metadata["file_name"]

with open(file_name, 'r') as file:
value = float(file.readline())
return (0, value)

Again, let's validate the Metric created above by instantiating it and reporting the value from the file generated during testing of the Runner.

# Note: all Metrics must have a name. This will become relevant when attaching metrics to the Client
hartmann6_metric = MockMetric(name="hartmann6")

hartmann6_metric.fetch(trial_index=-1, trial_metadata=trial_metadata)
Out:

(0, -0.4878737485613134)

Step 3: Initialize the Client and Configure the Experiment

Finally, we can initialize the Client and configure the experiment as before. This will be familiar to readers of the Ask-tell optimization with Ax tutorial -- the only difference is we will attach the previously defined Runner and Metric by calling configure_runner and configure_metrics respectively.

Note that when initializing hartmann6_metric we set name=hartmann6, matching the objective we now set in configure_optimization. The configure_metrics method uses this name to ensure that data fetched by this Metric is used correctly during the experiment. Be careful to correctly set the name of the Metric to reflect its use as an objective or outcome constraint.

client = Client()
# Define six float parameters 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)
client.configure_optimization(objective="-hartmann6")
client.configure_runner(runner=runner)
client.configure_metrics(metrics=[hartmann6_metric])

Step 5: Run trials

Once the Client has been configured, we can begin running trials.

Internally, Ax uses a class named Scheduler to orchestrate the trial deployment, polling, data fetching, and candidate generation.

Scheduler state machine

The OrchestrationConfig provides users with control over various orchestration settings:

  • parallelism defines the maximum number of trials that may be run at once. If your external system supports multiple evaluations in parallel, increasing this number can significantly decrease experimentation time. However, it is important to note that as parallelism increases, optimiztion performance often decreases. This is because adaptive experimentation methods rely on previously observed data for candidate generation -- the more tirals that have been observed prior to generation of a new candidate, the more accurate Ax's model will be for generation of that candidate.
  • tolerated_trial_failure_rate sets the proportion of trials are allowed to fail before Ax raises an Exception. Depending on how expensive a single trial is to evaluate or how unreliable trials are expected to be, the experimenter may want to be notified as soon as a single trial fails or they may not care until more than half the trials are failing. Set this value as is appropriate for your context.
  • initial_seconds_between_polls sets the frequency at which the status of a trial is checked and the results are attempted to be fetched. Set this to be low for trials that are expected to complete quickly or high for trials the are expected to take a long time.
orchestration_config = OrchestrationConfig(
parallelism=3,
tolerated_trial_failure_rate=0.1,
initial_seconds_between_polls=1,
)
client.run_trials(maximum_trials=30, options=orchestration_config)
Out:

[INFO 03-14 05:06:54] Scheduler: Scheduler requires experiment to have immutable search space and optimization config. Setting property immutable_search_space_and_opt_config to True on experiment.

Out:

[INFO 03-14 05:06:54] Scheduler: Running trials [0]...

Out:

[INFO 03-14 05:06:55] Scheduler: Running trials [1]...

Out:

[INFO 03-14 05:06:55] Scheduler: Running trials [2]...

Out:

[INFO 03-14 05:06:56] Scheduler: Retrieved COMPLETED trials: 0 - 2.

Out:

[INFO 03-14 05:06:56] Scheduler: Running trials [3]...

Out:

[INFO 03-14 05:06:57] Scheduler: Running trials [4]...

Out:

[INFO 03-14 05:06:59] Scheduler: Running trials [5]...

Out:

[INFO 03-14 05:07:00] Scheduler: Retrieved COMPLETED trials: 3 - 5.

Out:

[INFO 03-14 05:07:01] Scheduler: Running trials [6]...

Out:

[INFO 03-14 05:07:03] Scheduler: Running trials [7]...

Out:

[INFO 03-14 05:07:05] Scheduler: Running trials [8]...

Out:

[INFO 03-14 05:07:05] Scheduler: Retrieved COMPLETED trials: 6 - 8.

Out:

[INFO 03-14 05:07:06] Scheduler: Running trials [9]...

Out:

[INFO 03-14 05:07:08] Scheduler: Running trials [10]...

Out:

[INFO 03-14 05:07:10] Scheduler: Running trials [11]...

Out:

[INFO 03-14 05:07:11] Scheduler: Retrieved COMPLETED trials: 9 - 11.

Out:

[INFO 03-14 05:07:12] Scheduler: Running trials [12]...

Out:

[INFO 03-14 05:07:14] Scheduler: Running trials [13]...

Out:

[INFO 03-14 05:07:16] Scheduler: Running trials [14]...

Out:

[INFO 03-14 05:07:17] Scheduler: Retrieved COMPLETED trials: 12 - 14.

Out:

[INFO 03-14 05:07:19] Scheduler: Running trials [15]...

Out:

[INFO 03-14 05:07:21] Scheduler: Running trials [16]...

Out:

[INFO 03-14 05:07:23] Scheduler: Running trials [17]...

Out:

[INFO 03-14 05:07:24] Scheduler: Retrieved COMPLETED trials: 15 - 17.

Out:

[INFO 03-14 05:07:25] Scheduler: Running trials [18]...

Out:

[INFO 03-14 05:07:28] Scheduler: Running trials [19]...

Out:

[INFO 03-14 05:07:28] Scheduler: Running trials [20]...

Out:

[INFO 03-14 05:07:29] Scheduler: Retrieved COMPLETED trials: 18 - 20.

Out:

[INFO 03-14 05:07:31] Scheduler: Running trials [21]...

Out:

[INFO 03-14 05:07:34] Scheduler: Running trials [22]...

Out:

[INFO 03-14 05:07:37] Scheduler: Running trials [23]...

Out:

[INFO 03-14 05:07:37] Scheduler: Retrieved COMPLETED trials: 21 - 23.

Out:

[INFO 03-14 05:07:39] Scheduler: Running trials [24]...

Out:

[INFO 03-14 05:07:41] Scheduler: Running trials [25]...

Out:

[INFO 03-14 05:07:43] Scheduler: Running trials [26]...

Out:

[INFO 03-14 05:07:44] Scheduler: Retrieved COMPLETED trials: 24 - 26.

Out:

[INFO 03-14 05:07:46] Scheduler: Running trials [27]...

Out:

[INFO 03-14 05:07:48] Scheduler: Running trials [28]...

Out:

[INFO 03-14 05:07:50] Scheduler: Running trials [29]...

Out:

[INFO 03-14 05:07:51] Scheduler: Retrieved COMPLETED trials: 27 - 29.

Step 6: Analyze Results

As before, Ax can compute the best parameterization observed and produce a number of analyses to help interpret the results of the experiment.

It is also worth noting that the experiment can be resumed at any time using Ax's storage functionality. When configured to use a SQL databse, the Client saves a snapshot of itself at various points throughout the call to run_trials, making it incredibly easy to continue optimization after an unexpected failure. You can learn more about storage in Ax here.

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

Best Parameters: {'x1': 0.4320685968130141, 'x2': 1.0, 'x3': 0.0, 'x4': 0.4733910884430662, 'x5': 0.8982612189634599, 'x6': 0.0}

Prediction (mean, variance): {'hartmann6': (-2.315409450975517, 0.002494148248227793)}

client.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.6236440.3630310.9452950.3401830.6679940.6033350.362126
111_0COMPLETEDSobolSobol-0.0411140.652670.1135050.9925590.2254290.0063120.771671
222_0COMPLETEDSobolSobol-0.0411140.8348330.5901510.0917890.7673720.3842730.63648
333_0COMPLETEDSobolSobol-0.2163960.1808680.4839540.7439180.3389680.9754370.233522
444_0COMPLETEDSobolSobol-0.1238340.0478930.6569320.7665660.424410.8316110.444829
555_0COMPLETEDBoTorchMBM-0.6643240.26252710.1245670.8597070.5104530.174615
666_0COMPLETEDBoTorchMBM-1.255970.370259100.8395730.7652580
777_0COMPLETEDBoTorchMBM-0.3634330.3217710.2127050.8939270.1271750.29284
888_0COMPLETEDBoTorchMBM-0.0010470.287625100.9923480.7227550.689541
999_0COMPLETEDBoTorchMBM-1.928150.443413100.7311310.9265240
101010_0COMPLETEDBoTorchMBM-0.4233650.42515810.34762710.8801670
111111_0COMPLETEDBoTorchMBM-2.106110.415318100.4293010.7248230
121212_0COMPLETEDBoTorchMBM-1.351670.593764100.54892410
131313_0COMPLETEDBoTorchMBM-0.1527520100.54239810
141414_0COMPLETEDBoTorchMBM-0.0060131100.55246410
151515_0COMPLETEDBoTorchMBM-2.347490.447036100.51805810
161616_0COMPLETEDBoTorchMBM-2.016180.4458230.70070400.51941910
171717_0COMPLETEDBoTorchMBM-0.0003590.07944600.236764100
181818_0COMPLETEDBoTorchMBM-1.554310.465478100.46416410.187063
191919_0COMPLETEDBoTorchMBM-3.6e-050.473244100.509270.3496360
202020_0COMPLETEDBoTorchMBM-3.6e-05111011
212121_0COMPLETEDBoTorchMBM-2.285350.391745100.4738180.9121460
222222_0COMPLETEDBoTorchMBM-2.265930.432069100.4733910.8982610
232323_0COMPLETEDBoTorchMBM-2.277570.40118710.2569140.4616420.9084510
242424_0COMPLETEDBoTorchMBM-0.1627980.403391100.0480440.7515970
252525_0COMPLETEDBoTorchMBM-0.5259920.233813100.2386570.5377350
262626_0COMPLETEDBoTorchMBM-0.0845270.3105341000.5943620
272727_0COMPLETEDBoTorchMBM-2.53340.403422100.554210.8913760
282828_0COMPLETEDBoTorchMBM-0.0179650.07507511100.892241
292929_0COMPLETEDBoTorchMBM-0.0209620.4791211101

Cross Validation for hartmann6

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

loading...
Out:

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

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

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

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

Conclusion

This tutorial demonstrates how to use Ax's Client for closed-loop optimization using the Hartmann6 function as an example. This style of optimization is useful in scenarios where trials are evaluated on some external system or when experimenters wish to take advantage of parallel evaluation, trial failure handling, or simply to manage long-running optimization tasks without human intervention. You can define your own Runner and Metric classes to communicate with whatever external systems you wish to interface with, and control optimization using the OrchestrationConfig.